var myfunctions = {
	textresize : function(){
		var $cookie_name = "textsize";
		var originalFontSize = $("#container").css("font-size");


		$("#text_sizer .reset").bind("click",function(){
			$("#container").css("font-size", originalFontSize);
			$.cookie($cookie_name, originalFontSize);
			$('#text_sizer').trigger('reset');
		});

		$("#text_sizer .smaller").bind("click",function(){
			var currentFontSize = $("#container").css("font-size");
			var currentFontSizeNum = parseFloat(currentFontSize, 10);
			var newFontSize = currentFontSizeNum - (currentFontSizeNum*.2);
			if (newFontSize > 12) {
				$("#container").css("font-size", newFontSize);
				$.cookie($cookie_name, newFontSize);
				$('#text_sizer').trigger('resized');
			}
			return false;
		});

		$("#text_sizer .bigger").bind("click",function(){
			var currentFontSize = $("#container").css("font-size");
			var currentFontSizeNum = parseFloat(currentFontSize, 10);
			var newFontSize = currentFontSizeNum*1.2;
			if (newFontSize > 12 && newFontSize <25) {
				$("#container").css("font-size", newFontSize);
				$.cookie($cookie_name, newFontSize);
				$('#text_sizer').trigger('resized');
			}
			return false;
		});

		$('#text_sizer').bind('resized', function(){
			$('#text_sizer_msg:hidden').slideDown('fast');
		})
		.bind('reset', function(){
			$('#text_sizer_msg:visible').slideUp('fast');
		});
	}
}

$(document).ready(function(){

	// FONT SIZER
	myfunctions.textresize();

	// NAVIGATION
	$('#nav div.has_sub').hoverIntent(
		// mouse over
		function(){
			// find the corresponding submenu and animate it open
			$('.sub_menu', $(this)).slideDown('fast', function(){ $(this).addClass('bottom_round_10') });
		},
		// mouse out
		function(){
			// find the corresponding submenu and animate it closed
			$('.sub_menu', $(this)).fadeOut('fast', function(){ $(this).removeClass('bottom_round_10') });
		}
	);


	// HDR FUNCTIONS
	$('#hdr_functions > a').hoverIntent(
		// mouse over
		function(){
			$('#hdr_functions div').hide();
			$('#hdr_functions a').removeClass('current');
			$(this).addClass('current');
			$('#'+$(this).attr('id')+'_frm').slideDown().mouseleave(function(){
				$(this).slideUp();
				$('#hdr_functions a').removeClass('current');
			});
		},
		// mouse out
		function(){

		}
	);

	/* 	HOMEPAGE SLIDESHOW 	*/
	$('#homepage_slideshow').innerfade({
		//containerHeight:'300px',
		speed:'slow',
		timeout:8000
	});

	// ACCORDIANS
	if($('#accordian').length){
		// loop through all the h2's which will act as a trigger
		$('h2',$('#accordian')).addClass('accordian_heading').addClass('closed').each(function(){
			// add the icon
			$(this).prepend('<span class="icon"></span>');

			var content = [];
			//loop through all the siblings of this heading
			var sibs = $(this).nextAll();
			for(i=0; i<sibs.length; i++){
				//console.log(sibs[i]);
				//if its one of the headings stop
				//otherwise add it to the content variable
				if($(sibs[i]).attr('class').match("accordian_heading"))
					break;
				else if($(sibs[i]).find('a[name="end"]').length)
					break;
				else
					content.push(sibs[i]);
			}
			//wrap all of the content into a div
			$(content).wrapAll('<div class="accordian_content"></div>');

		// open/close
		}).click(function(){
			// if the current div is closed
			if($(this).attr('class').match("closed")){
				// close whatever is open
				$('#accordian h2.open').removeClass('open').addClass('closed').next('div').slideUp();
				// open this
				$(this).removeClass('closed').addClass('open').next('div').slideDown();

			// clicked on an open one
			} else {
				$(this).removeClass('open').addClass('closed').next('div').slideUp();
			}

		});
	}


	// FAQ
	if($('#faq').length){
		// handle all of them at once
		$('#expander_all').data('open',false).click(function(){
			$expander = $(this);
			// if everything is open, close it
			if($(this).data('open')===true){
				$('dl.faq dd').slideUp('fast', function(){
					$expander.data('open',false).text('View All');
					$('h2 .expand_category').data('open',false).text('expand category');
				});
			// everything is closed, open it
			} else {
				$('dl.faq dd').slideDown('fast', function(){
					$expander.data('open',true).text('Hide All');
					$('h2 .expand_category').data('open',true).text('collapse category');
				});
			}
		});
		// whole categories
		$('h2 .expand_category').data('open',false).click(function(){
			$expander = $(this);

			// category is open, close it
			if($(this).data('open')===true){
				$(this).parent().next().find('dd').slideUp('fast', function(){
					$expander.data('open',false).text('expand category');
				});
			// category is closed, open it
			} else {
				$(this).parent().next().find('dd').slideDown('fast', function(){
					$expander.data('open',true).text('collapse category');
				});
			}
		});
		// single questions
		$('dl.faq dt').click(function(){
			$(this).next('dd').slideToggle('fast');
		});
	}


	// PRESS RELEASES
	// ARCHIVE LIST
	$('#press_release_archives li.year').click(function(){
		$(this).children('ul').toggle();
	}).find('li.month').click(function(){
		$(this).children('ul').toggle();
		return false;
	}).find('a').bind('click',function(e){
		e.stopPropagation();
	});



	// MEDIA ITEMS
	if($('#media_player_holder').length){
		var flashvars = {};
		var params = {};
			params.allowscriptaccess = "sameDomain";
			params.bgcolor = "#254f75";
		var attributes = {};
			attributes.id = "media_player";
		swfobject.embedSWF("media_player.swf", "media_player_holder", "200", "80", "9.0.0", false, flashvars, params, attributes);
	}

	$('#media .audio .play').live('click', function(e){
		e.stopPropagation();
		var song = $('p.data', $(this)).text();
		song = eval('(' + song + ')');
		var media_player = $("#media_player")[0];
		media_player.loadSong(song);
		return false;
	});

	$('#media .video .play').live('click', function(e){
		e.stopPropagation();
		// hide the media player so it doesn't go over the overlay
		$('#media_player').css('visibility','hidden');
		// get the video data
		var video = eval('('+$('p.data',$(this)).text()+')');
		// do a dialog for the video embed
		makeDialog('<h3><img src="layout_imgs/ajax-loader.gif" alt="loading" /> Loading Video</h3><p>please wait</p>', video.title);
		// ajax in the data
		$('#made_dialog').load('get_embed/'+video.item_id, function(rsp){
			if(rsp!="false"){
				$(this).html('<div class="center">'+rsp+'</div>');
			} else {
				$(this).html('<p>Sorry, but we could not find that video at this time. Please try again later.</p>');
			}
			// animate the containers to show everything
			$(this).parent().css('width','auto').animate( {
				top: $(this).parent().offset().top - (screen.height/4) + 20,
				left: '50%',
				marginLeft: -($(this).width() / 2)
			}, 'fast');
		});

		// pause the song if it's playing
		var media_player = $("#media_player")[0];
		if(!media_player.isPaused()){
			media_player.pauseSong();
			$('#made_dialog').bind('dialogclose', function(event, ui) {
				media_player.playSong();
				$('#media_player').css('visibility','visible');
			});
		} else {
			$('#made_dialog').bind('dialogclose',function(event, ui){ $('#media_player').css('visibility','visible'); });
		}
	});

	// ajax the media listing so we don't kill someone's audio
	$('#media ul.page_menu a').not('.subscribe').live('click', function(){
		var src = $(this).attr('href');

		$('#media_holder').html('<h3><img src="layout_imgs/ajax-loader.gif" alt="loading" /> Loading, please wait</h3>').load(src+' #media_holder');

		$('#media ul.page_menu')
			.find('.current').removeClass('current').end()
			.find('a[href="'+src+'"]').addClass('current');

		return false;
	});

	// media comments
	// show/hide comments
	// toggle the comments
	$('#media a.view_comments').live('click', function(){
		$link = $(this);
		// slide the comments into place with a callback
		$(this).parent('p').next('div').slideToggle('fast',function(){
			// toggle view/leave with hide
			text = $link.text();
			if(text.indexOf("View/Leave")>=0){
				text = text.replace("View/Leave","Hide");
			} else {
				text = text.replace("Hide","View/Leave");
			}
			$link.text(text);
		});
		return false;
	});
	$('#media .comment_form').live('submit', function(){
		$('input[type="submit"]',this).attr('disabled','disabled');
		var $comments = $(this).prev('.comments');
		var $form = $(this);

		var form_data = $(this).serialize();
		$.ajax({
			url: 'ajax_comments.php',
			data: form_data,
			type: "POST",
			beforeSend: function(){
				makeDialog('<h3><img src="layout_imgs/ajax-loader.gif" alt="loading" /> Saving Comment, please wait</h3>','Saving Comment',{});
			},
			success: function(rsp){
				// successfully returned, but the string starts with false
				if(rsp.substr(0,5)=="false"){
					$('#made_dialog').dialog('close');
					makeDialog(rsp.substr(6),'Comment Error');
				} else {
					$comments.find('p.empty').remove();
					$comments.append(rsp);

					// now update the comment link
					var count = $('input[name="count"]',$form).val();
					var text = $comments.parents('.comment_holder').find('a.view_comments').text();
					//console.log(text);
					if(text.indexOf("(")>=0){
						text = text.replace(/\(\d+\)/, "("+count+")")
					} else {
						text += ' ('+count+')';
					}
					$comments.parents('.comment_holder').find('a.view_comments').text(text);

					count = count*1 + 1;
					$('input[name="count"]',$form).val(count);

					$('#made_dialog').dialog('close');
				}
				// clear the form
				$('input[name="name"]',$form).val('');
				$('textarea[name="comment"]',$form).val('');
			},
			error: function(){
				$('#made_dialog').dialog('close');
				makeDialog('<p><strong>Sorry</strong> but your comment could not be saved at this time. Please try again later.</p>','Comment Error');
				// clear the form
				$('input[name="name"]',$form).val('');
				$('textarea[name="comment"]',$form).val('');
			}
		});

		$('input[type="submit"]',this).removeAttr('disabled');
		return false;
	});


	// DIALOG LINKS (staff)
	$('a.dialog').click(function(){
		// do a dialog for the video embed
		makeDialog('<h3><img src="layout_imgs/ajax-loader.gif" alt="loading" /> Loading '+$(this).attr('title')+'</h3><p>please wait</p>', $(this).attr('title'));
		var element_rel = $(this).attr('name');
		// ajax in the data
		$('#made_dialog').load($(this).attr('href')+(element_rel ? ' '+element_rel : ''), function(rsp){
			// animate the containers to show everything
			$(this).parent().css('width','705px').animate( {
				top: $(this).parent().offset().top - (screen.height/4) + 20,
				left: '50%',
				marginLeft: -($(this).width() / 2)
			}, 'fast');
		});

		return false;
	});



	// QUICKBASE LOGIN FORM
	$('#quickbase_login').click(function(){
    		// do a dialog
			makeDialog('<h3><img src="layout_imgs/ajax-loader.gif" alt="loading" /> Loading Online Login Form</h3><p>please wait</p>', 'Online Login Form');
			var element_rel = $(this).attr('name');
			// ajax in the data
			$('#made_dialog').load('quickbase_login', function(rsp){
				// animate the containers to show everything
				$(this).parent().css('width','430px').animate( {
					top: $(this).parent().offset().top - (screen.height/4) + 20,
					left: '50%',
					marginLeft: -($(this).width() / 2)
				}, 'fast');

				var buttons = {
					"Login": function(){
						$('#mainform').submit();
					},
					"Cancel": function() {
						$(this).dialog('close');
					}
				};
				$('#made_dialog').dialog('option','buttons', buttons);

			});

			return false;
	});

	// ** OUTLOOK *********
	// main page
	$('div.forecast_area').click(function(){
		var title = $(this).find('h2').text();
		var area_id = $(this).find('p.leadership_area_id').text();
		var el = $(this);

		makeOutlookDialog('<h3><img src="layout_imgs/ajax-loader.gif" alt="loading" /> Loading '+title+'</h3><p>please wait</p>', title);
		// ajax in the data
		$('#made_dialog').load('outlook-leadership_area/'+area_id, function(rsp){
			// handle buttons next/prev for the dialog
			$('#made_dialog').dialog({ dialogClass: 'ui-forecast-'+area_id });

		});
		return false;
	});

	$('a.load-area').live('click', function(){
		var title = $(this).attr('rel');
		var area_id = $(this).text();
		makeOutlookDialog('<h3><img src="layout_imgs/ajax-loader.gif" alt="loading" /> Loading '+title+'</h3><p>please wait</p>', title);
		// ajax in the data
		$('#made_dialog').load($(this).attr('href'), function(rsp){
			// handle buttons next/prev for the dialog
			$('#made_dialog').dialog({ dialogClass: 'ui-forecast-'+area_id });

		});
		return false;
	});


	// indicators
	$('a.show-indicator').live('click', function(){
		var el = $(this);
		var indicator_id = el.attr('rel') * 1;
		var title = $('span[rel="indicator_title_' + indicator_id + '"]').text();
		var img		= $('img[rel="img_' + indicator_id + '"]');
		var targ	=	$('#ajax_' + indicator_id);
		var indicators = 	$('div[id*="ajax_"]');
		if(targ.is(':visible') ) {
			targ.slideUp('fast');
			 $('div.indicator').each(function() {
					$(this).removeClass('bk-lines');
			});
			$('img[rel*="img_"]').attr('src','layout_imgs/plus.png');
		}else{
			indicators.slideUp('fast');
			$('img[rel*="img_"]').attr('src','layout_imgs/plus.png');
			launchForecastIndicator(indicator_id, title);
			targ.slideDown('fast');
			// remove all bkgd lines
			$('div.indicator').each(function() {
					$(this).removeClass('bk-lines');
			});
			$.scrollTo( el, {easing:'elasout'} );
			targ.parent('div').addClass('bk-lines');
			$(img).attr('src','layout_imgs/minus.png');

		}

		return false;
	});

	// toggle view
	$('.toggle').live('click', function(){
			// get the target class from this rel
			var targ = $(this).attr('rel');
			$('.'+ targ).toggle();
			return false;
	});

	$('.share-link').live('click', function(){
			var targ = $(this).attr('rel');
			$('h4.share-info').hide();
			$('div#sharelink-success').hide();
			$('#'+targ).show();

			return false;
	});
	$('#sharelink_to, #sharelink_from').live('focus', function(){
			$(this).val('');
			$(this).css({color:'#000'});
	});

	$('.sharelink-error-close, #sharelink-error').live('click',function(){
			$('#sharelink-error').hide();
	});

	$('#sharelink-form').live('submit', function(e){
			$.ajax({
					type: 'POST',
					data: $(this).serialize(),
					url: 'ajax_sharelink.php',
					success: function(msg) {
						if(msg.mailed == 1){
							$('#sharelink-form').hide();
							$('#sharelink-success').show();

						}else if (msg.mailed==0){
							$('#sharelink-error').show();
						}
					},
					dataType: 'json'
			});
			//prevent the browser to follow the link

			e.preventDefault();
			e.stopPropagation();
			return false;
	});

	$('#sharelink_submit').live('click', function(e){
				$('#sharelink-form').submit();
				return false;
	});



	//LINKS
	$('a[href^="http"]:not([href*="grfoundation.org"])').not('.internal').attr('target','_blank').click(function(){
		pageTracker._trackPageview($(this).attr('href'));
		pageTracker2._trackPageview($(this).attr('href'));
	}).not('.no_icon').append('<span class="icon external"></span>');
	$('a[href$="pdf"]').attr('target','_blank').not('.no_icon').append('<span class="icon pdf"></span>');
	$('a[href$="doc"],a[href$="docx"],a[href$="rtf"],a[href$="txt"]').attr('target','_blank').not('.no_icon').append('<span class="icon word"></span>');
	$('a[href$="xls"],a[href$="xlsx"],a[href$="csv"]').attr('target','_blank').not('.no_icon').append('<span class="icon excel"></span>');
	$('a[href$="ppt"],a[href$="pptx"]').attr('target','_blank').not('.no_icon').append('<span class="icon ppt"></span>');

	$('a[href="***back"]').click(function(){
		history.go(-1);
		return false;
	});


	// toggle hiding of print_p
	/*
	$('label.print_p').dblclick(function(){
		$(this).siblings('pre').toggle();
	});
	*/


}); // end document ready


function launchForecastIndicator(indicator_id, title){
	//console.log('launched',indicator_id, title );
	// ajax in the data
	$('#ajax_' + indicator_id).load('outlook-indicator/'+indicator_id, function(rsp){

			LazyLoader.load('js/highcharts.js', function(){
			indicator.init();
		});

	});
	return false;
}



function makeDialog(text, dialog_title, buttons, width, height, hideTitleBar){

	// make sure there isn't already a dialog open
	if($('#made_dialog').length){
		$('#made_dialog').dialog('close');
	}

	if(!buttons){
		buttons = {
			Ok: function() {
				$(this).dialog('close');
			}
		}
	}

	$('<div id="made_dialog">'+text+'</div>').dialog({
		title: dialog_title,
		//dialogClass: hideTitleBar ? 'hide_title' : 'alert',
		bgiframe: true,
		modal: true,
		stack:true,
		autoOpen:true,
		width: width ? width : 460,
		minHeight: height ? height : 220,
		draggable: true,
		resizable: true,
		buttons: buttons,
		close: function(event, ui){
			$(this).remove();
		}
	});
}


// for custom outlook
function makeOutlookDialog(text){
	// make sure there isn't already a dialog open
	if($('#made_dialog').length){
		$('#made_dialog').dialog('close');
	}

	$('<div id="made_dialog">'+text+'</div>').dialog({
		bgiframe: true,
		modal: true,
		stack:true,
		autoOpen:true,
		width: 740,
		minHeight: 540,
		draggable: true,
		resizable: true,
		close: function(event, ui){
			$(this).remove();
		}
	});
}


window.alert = function(txt){
	makeDialog(txt, 'The page said:');
}

//CATCH CONSOLE.LOG FOR NO-FIREBUG
if (typeof console == 'undefined' || typeof console.log == 'undefined') { console = { log : function (text) { return false; } } }

// http://bililite.com/blog/extending-jquery-ui-widgets/ Aspect Oriented Programming
$.extend($.ui.dialog.overlay, {
	yield: null,
	returnValues: { },
	before: function(method, f) {
		var original = this[method];
		this[method] = function() {
			f.apply(this, arguments);
			return original.apply(this, arguments);
		};
	},
	after: function(method, f) {
		var original = this[method];
		this[method] = function() {
			original.apply(this, arguments);
			return f.apply(this, arguments);
		}
	},
	around: function(method, f) {
		var original = this[method];
		this[method] = function() {
			var tmp = this.yield;
			this.yield = original;
			var ret = f.apply(this, arguments);
			this.yield = tmp;
			return ret;
		}
	}
});
// if a dialog epands the page height we want to expand the bottom bar as well
$.ui.dialog.overlay.after('resize', function(){
	$('#bottom_bar').height(38);
	$('#bottom_bar').height($(document).height() - $('#bottom_bar').offset().top);
});

// author of bubble tip recommends window.bind instead of document load
$(window).bind('load', function() {

	$(".forecast_area_img").each(function (i) {
			$(this).bubbletip($('#tip_' + $(this).attr('rel')),{
				offsetTop: 30
			});
	});

	$(".tooltip2").hover(
	function () {
		$('.' + $(this).attr('rel')).css({'display':'block'});
		},
	function(){
		$('.' + $(this).attr('rel')).css({'display':'none'});
	});

});

