/*
--------------------------------------------------

Federal Reserve Bank of Chicago
Javascript Application Code [application.js]

Joe Morrow [joe.morrow@acquitygroup.com]
6/26/2009

Copyright ? 2009 Acquity Group LLC

--------------------------------------------------
*/


$(function() {
	
	// Browser & OS Detection
	if (isSafari()) $("body").addClass("safari");
	
	if (isLteFF30()) $("body").addClass("ff30");

	if (isMac()) $("body").addClass("mac");


	// Auto-clear inline prompt text, stored in "title" attribute
	$(".inline-prompt").each(function() {
		if ($(this).attr("title").length == 0)
			$(this).attr("title", $(this).val());
	}).focus(function() {
		if ($(this).val() == $(this).attr("title"))
			$(this).val("").removeClass("inline-prompt");
	}).blur(function() {
		if ($(this).val() == "")
			$(this).val($(this).attr("title")).addClass("inline-prompt");
	});


	// Carousel Scroller
	if ($(".carouselItem").size() > 0) {

		var carouselTime = 8000;
		$playpause = $('#carousel-playPause')
		$playpause.addClass('play'); // initial value
		
		var promoTimeout = setInterval("promoSwitchTo($('a#carouselNext').attr('href'))", carouselTime);
		
		$(".carouselItem.hidden").hide().removeClass("hidden");
		$("#carouselController a").click(function() {
			$playpause.removeClass('play')
			clearTimeout(promoTimeout);
			if (!$(this).parent().hasClass("selected"))
				promoSwitchTo($(this).attr("href"));
			return false;
		});
		$("a#carouselPrev, a#carouselNext").click(function() {
			$playpause.removeClass('play')
			clearTimeout(promoTimeout);
			promoSwitchTo($(this).attr("href"));
			return false;
		});
		
		$playpause.click(function(){
			if ($(this).hasClass('play'))
			{
				//pause
				$(this).removeClass('play')
				clearTimeout(promoTimeout);
			}
			else
			{
				// play
				$(this).addClass('play')
				promoSwitchTo($('#carouselController li.selected').next().length > 0 ? $($('#carouselController li.selected').next().children('a')[0]).attr('href') : $($('#carouselController li a')[0]).attr('href'))
				promoTimeout = setInterval("promoSwitchTo($('a#carouselNext').attr('href'))", carouselTime);
			}
			return false;
		})
		
		// Quick IE6 display fix
		$('#carousel.home div.controller').css('margin-top','167px')
	}


	// Print buttons
	$("a.print").click(function() {
		window.print();
		return false;
	});


	// Text Resize buttons
	var resizeFactor = 1.2;
//	var resizeProperties = ["font-size", "line-height"];
	var resizeProperties = ["font-size"];
	var resizeContext = "#content";
	var resizeExcluded = ".utilButtons";
	var isResizePreset = false;

	$(".utilButtons a.increase").click(function() {
		resizeStyle(resizeFactor, resizeProperties, resizeContext, resizeExcluded, isResizePreset);
		isResizePreset = true;
		return false;
	});

	$(".utilButtons a.decrease").click(function() {
		resizeStyle(1 / resizeFactor, resizeProperties, resizeContext, resizeExcluded, isResizePreset);
		isResizePreset = true;
		return false;
	});
	
	
	// homepage hero rotation
	$("ul.rotate li").click(function(){
		$.browser.msie && $.browser.version <= 6 ? fadeTime = 0 : fadeTime = 300
		if (!$(this).hasClass("active")) {
			$clickedLi = $(this);
			target = $("#hero div.hero")[$(this).prevAll().length];
			$(target).css("display", "block");
			$("#hero div.active").fadeOut(fadeTime, function() {
				$(this).removeClass("active");
				$(target).css("display", "").addClass("active");
			});
			$("#hero li.active").removeClass("active");
			$clickedLi.addClass("active");
		}
		return false;
	})


	// "Addthis"
	$('a.addthis').each(function(){setAddThis($(this))});

	// Google Map
	if ($('dl.eventDetails').length != 0) {
		if (GBrowserIsCompatible()) {
			//construct dd and dt structure
			dt = $(document.createElement('dt'));
			dd = $(document.createElement('dd'));
			divmap = $(document.createElement('div'));
			dt.text('Map');
			dd.append(divmap);
			divmap.attr('id', 'mapContainer');
			$('dl.eventDetails').after($(document.createElement('dl')).addClass('eventDetails map').append(dt).append(dd));
			drawMap($('dl.eventDetails').find('#mapContainer').attr('id'), $('#mapAddress').val());
		}
	}

	// Remove the right margin from the last economist in each row
	$('ul.economists').each(function(){
		for (i = 0; i <	$(this).children('li').length; i++) {
			if ((i+1)%4==0) $($(this).children('li')[i]).addClass('end')
		}
	})	

	// in IE6, empty #features has to have a content character for correct display
	if (isIE6() && ($('#features').html().length == 0)) $('#features').html('&nbsp;')
	
	//Add first and last classes
	$('#features .feature:first').addClass("first");	
	$('.resources .resourceGroup:last').addClass("last");	

	
	//Hide all tabs whose content is empty or display tabs whose class is current
	$('.pTabContent').each(function(i){
	
		if ($(this).text() == '' && $(this).children('.text').text() == '') {
			$('.ptabs li:eq(' + i + ')').hide();
			
		} else if ($(this).hasClass('current')) {
			$(this).css('display', 'block');
			
		}
		
	});
	
	$('.tabContent').each(function(i){
    	if ($.trim($(this).text()) == '') $('.tabs li:eq('+i+')').css('display','none');
	});
 
	$('.tabContent:eq('+$('.tabs li:visible:first').addClass('current').prevAll().length+')').css('display','block');
	
	//Add Tab Functionality for People and Events
	$('.tabs li a').click(function(){
		
		//Remove the active treatment from the current tab and hide its content
		$('.tabs li.current').removeClass('current');
		$('.tabContent').css('display', 'none');
		
		//Add the active treatment to the new current tab and its content
		$(this).parent().addClass('current');
		var curTabIndex = $('.tabs li').index($(this).parent());		
		$('.tabContent:eq(' + curTabIndex + ')').css('display', 'block');
	});
	
	//Add Tab Functionality for tabs that are written in to the VFE
	$('.pTabs li a').click(function(){
		
		//Remove the active treatment from the current tab and hide its content
		$('.pTabs li.current').removeClass('current');
		$('.pTabContent').css('display', 'none');
		
		//Add the active treatment to the new current tab and its content
		$(this).parent().addClass('current');
		var curTabIndex = $('.pTabs li').index($(this).parent());		
		$('.pTabContent:eq(' + curTabIndex + ')').css('display', 'block');
	});
	
	//toggle to the speakers tab when the view all speakers link is clicked
	$('#viewAllSpeakers').click(function(){
		//Remove the active treatment from the current tab and hide its content
		$('.tabs li.current').removeClass('current');
		$('.tabContent').css('display', 'none');
		
		//Add the active treatment to the new current tab and its content
		$("#speakersTab").addClass('current');
		$('#speakers').css('display', 'block');
	});
	
	// Toggle all comments
 	$('.allComments').hide();
 	$('.seeAllComments').click(function() {
 		$('.allComments').slideToggle();
 		$('.seeAllComments').toggle();
 		return false;
 	});

	//toggle to the registration tab when the register link is clicked
	$('.register').click(function(){
		//Remove the active treatment from the current tab and hide its content
		$('.tabs li.current').removeClass('current');
		$('.tabContent').css('display', 'none');
		
		//Add the active treatment to the new current tab and its content
		$("#registrationInfoTab").addClass('current');
		$('#registrationInfo').css('display', 'block');
	});
	
	//reformat all links for their external attachment icon
	$('#content a:not(.utilButtons a, .comments a, .tabs a, .pTabs a, a.register, a.viewAll, a.iTitle, a.more, .sectionLinks a, #carouselController a, a.backToTop, .synopsis a, a.all, a.noFormat)').each(function() {
	
		//if the link has a class that matches the name of one of the
		//doc types then it already contains an icon and nothing should
		//be done.
		var docTypes = new Array("pdf", "zip", "dat", "doc", "docx", "flv", "gif", "jpg", "mdb", "mov", "mp3", "png", "ppt", "pptx", "swf", "wmv", "xls", "xlsx");
		var isAlreadyFormatted = false;
		var linkSrc = $(this).attr('href');
		var chiFedRegExp = new RegExp("(^http[s]?:\/\/.*.chicagofed\.org|^http[s]?:\/\/.*.chicagofedblogs\.org)");
		var urlRegExp = new RegExp("^http[s]?:\/\/");
		
		for (var dtInd = 0; dtInd < docTypes.length; dtInd++) {
			var tempDocType = docTypes[dtInd];
			
			if($(this).hasClass(tempDocType)) {			
			
				//if the link is not wrapping an image, format it to display the link type icon
				if($(this).children('img').size() == 0){
					
					//append span for ADA compliance
					$(this).append('<span class="' + tempDocType + '">(' + tempDocType + ')</span>');
					
					//if the link doesnt contain chicagofed.org or chicagofedblogs.org and it begins with http:// or https://
					//then add the external-LINKTYPE class to it and format for accessiblity
					if (linkSrc != null && !linkSrc.match(chiFedRegExp) && linkSrc.match(urlRegExp)){
						
						$(this).removeClass(tempDocType);
						$(this).addClass('external-' + tempDocType);
						
						$(this).children($('span.' + tempDocType)).addClass('external-' + tempDocType).removeClass(tempDocType);
						$(this).children($('span.' + tempDocType)).text('(external-' + tempDocType + ')');
					}
			
				} else {
					$(this).removeClass(tempDocType);
				}	
				
				isAlreadyFormatted = true;
				break;				
			}			
		}
	
		if (!isAlreadyFormatted) {		
			
			//if the link doesnt contain chicagofed.org or chicagofedblogs.org and it begins with http:// or https://
			//then add the external class to it and format for accessiblity
			if (linkSrc != null && !linkSrc.match(chiFedRegExp) && linkSrc.match(urlRegExp)) {
				
				$(this).addClass('external');
				$(this).append('<span class="external">(external)</span>');
			}
		}	
	});
	
	//generate popups for all external links
	$('a').each(function(){
		
		var linkSrc = $(this).attr('href');
		var chiFedRegExp = new RegExp("(^http[s]?:\/\/.*.chicagofed\.org|^http[s]?:\/\/.*.chicagofedblogs\.org)");
		var urlRegExp = new RegExp("^http[s]?:\/\/");
		
		//if the link source is an external link then generate a popup when clicked
		if (!linkSrc.match(chiFedRegExp) && linkSrc.match(urlRegExp)){
								
			//generate popup
			$(this).click(function(){
				window.open($(this).attr('href'), '_blank', 'location=1, toolbar=1, menubar=1, status=1, scrollbars=1, resizable=1, width=924, height=668, top=100, left=100');		
				return false;	
			});						
		}	
	});
	
	//color all table headings from the vfe
	$('.VFE tbody tr:first-child td, .vfe tbody tr:first-child td').css({"background-color" : "#C5D3D9", "font-weight" : "bold"});

	//color all table headings from the vfe data sub class
	$('.data tbody tr:first-child td, .vfe tbody tr:first-child td').css({"background-color" : "#C5D3D9", "font-weight" : "bold"});
	
	$('ul.utilButtons li:eq(1) a').click(function() {
		window.print();
	});
	
	// form reset button
	$('.reset, #filter-reset, a.clearForm').click(function(){
		form = $(this).parents('form');
		form.find('input[type=text]').val('');
		form.find('input[type=checkbox]').checked = false;
		form.find('input[type=radio').checked = false;
		form.find('select').each(function(){
			$(this)[0].selectedIndex = 0;
		})
		return false;
	})
	
});

//allow all content to load before manipulating images
$(window).load(function(){
	
	// Create captions for images
	// 20101103 VH -- No captionImage class for inline help buttons

	$('.articleText img:not(img.noCaption)').each(function(){
		
		if (($(this).attr('src').split('/').pop()=='icn_help_templ.gif') || ($(this).attr('src').split('/').pop()=='arrow.gif')) {

		} else if ($(this).attr('title').length > 0) {
			
			if ($('body').hasClass('safari')) {
				$(this).load(function(){
					// Build caption
					$p = $(document.createElement('p'));
					$p.text($(this).attr('title')).insertAfter($(this));
					
					// Wrap DIV
					$div = $(document.createElement('div'));
					$div.css('width', $(this).width() + 'px').addClass('captionImage');
					$(this).add($p).wrapAll($div);
				})
			} else {
				// Build caption
				$p = $(document.createElement('p'));
				$p.text($(this).attr('title')).insertAfter($(this));
				
				// Wrap DIV
				$div = $(document.createElement('div'));
				$div.css('width', $(this).width() + 'px').addClass('captionImage');
				$(this).add($p).wrapAll($div);
			}
		} else {
			$div = $(document.createElement('div'));
			$div.css('width', $(this).width() + 'px').addClass('captionImage');
			$(this).wrapAll($div);
		}
	});	
	
});

