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
	$('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;
	});
	$('.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;
	});



	//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;
	});


});


function makeDialog(text, dialog_title, buttons, width, height, hideTitleBar){
	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();
		}
	});
}

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; } } }