
$(document).ready(function() {

	window.navTimeout = false;
	window.currentNav;
//	 main menu
	
	var timer;

	$('#menu li').hover(function(){

			if(timer) {
				clearTimeout(timer);
				timer = null
			}
			
			$(this).find('a').removeAttr('title');

			var currentNavExpanded = $(this).find('.navExpanded');

			$('#menu li .navExpanded').not(currentNavExpanded).hide();

			timer = setTimeout(function(){
				$(currentNavExpanded).fadeIn(100);
			}, 150 );
		},
		function() {
			if(timer) {
				clearTimeout(timer);
				timer = null
			}

			var currentNavExpanded = $(this).find('.navExpanded');

			timer = setTimeout(function(){
				$(currentNavExpanded).fadeOut(250);
			}, 300 );
		}
	);
	
	
	// search
	$("#search #query").val("SEARCH OUR SITE").focus(function(){
        if ($(this).val() == "SEARCH OUR SITE") {
            $(this).val("");
        }
    }).blur(function(){
        if ($(this).val() == "") {
            $(this).val("SEARCH OUR SITE");
        }
    });

	// popular tabs switch 
	$('a.tab').click(function() {
		$('#searched').toggle();
		$('#emailed').toggle();
		return false;
  });
  
	//add long bio toggle for blog pages
	$(".bloggerProfile .toggleBio").click(function(){
 		$(".bloggerProfileDescriptionText").toggle();
	});
	
//	//Hide ad sections without ad content
//	$(".ad").each(function(){
//		if ($(this).html().search('grey.gif') != -1){
//			$(this).hide();
//		}
//	});
	
	//add spacing to right column ads if they don't fill the full width
	$("#promoColumn .ad").each(function(){

		maxAdWidth = Math.max(
			$(this).find("img").width(),
			$(this).find("embed").width(),
			$(this).find("object").width()
		);

		if (maxAdWidth < 336){
			$(this).css("padding-bottom","20px");
			$(this).css("padding-top","20px");
		}
	});
	
	function removeCircLabel(inputBox){
		if ($(inputBox).val().toLowerCase() == $(inputBox).attr('longdesc').toLowerCase()){
			$(inputBox).val('');
		}
	}
	function addCirclLabel(inputBox){
		if ($(inputBox).val().toLowerCase() == ''){
			$(inputBox).val($(inputBox).attr('longdesc'));
		}
	}
	
	//toggle field labels on circ form if it exists
	$("#circForm input:text").focus(function(){
		removeCircLabel(this);
	});
	
	//Set all unfilled fields to blank before submitting
	$(".subscribeButton").bind("click", function(event){
		$("#circForm input:text").each(function(){
			removeCircLabel(this);
		});
		$("#circForm").submit();
	});
	
	$("#circForm").bind("keypress", function(event){
		if (event.keyCode == 13){ 
			$("#circForm input:text").each(function(){
				removeCircLabel(this);
			});
			$("#circForm").submit();
		}
	});

	$("#circForm input:text").blur(function(){
		addCirclLabel(this);
	});
	$("#circForm input:text").each(function(){
		addCirclLabel(this);
	});

	var selectDate = function() {
		var text = $("#calendar").DatePickerGetDate('formatted');
		var myText = new String(text);
		var range = myText.split(',');

		if (range[0] != range[1]) {
			window.location = baseLocation + 'date-filter/?startDate=' + range[0] + '&endDate=' + range[1];
			
			$('#byDateDropdown .expandingTitle').html('Loading...');
		}
	}

	$("#calendar").DatePicker({
		flat: true,
		date: ['YYYY-MM-DD','YYYY-MM-DD'],
		calendars: 1,
		mode: 'range',
		starts: 7,
		onChange: selectDate
	});

	// Expanding Menus
	$(".expandingMenu .expandingArrow").click(function() {
	
		var shouldOpen = true;
		if ( $(this).hasClass('open') == true ) {
			shouldOpen = false;
		}

		$(".expandingMenu .expandingContent").slideUp(80);
		$(".expandingMenu .expandingArrow").removeClass('open');

		if ( shouldOpen == true ) {
			$(this).parent().find('.expandingContent').slideDown(80);
			$(this).addClass('open');
		}

		return false;
	});

	$(".expandingMenu .expandingContent a").click(function() {
		$(this).parent().parent().parent().find('.expandingTitle').html('Loading...');
	});

	$("html").click(function(){
		$(".expandingMenu .expandingContent").slideUp(80);
		$(".expandingMenu .expandingArrow").removeClass('open');
	});

	setTimeout(function() {

		var promoColumnHeight = parseInt($("#promoColumn").height());

		 // If the page contains one of the following top content IDs we need to
		 // subtract its height form the height of the middle column to get it to
		 // line up with the bottom of promoContent
			var ids = ["topStory","magazineTopStories", "channelTopStories"];

			for ( var i in ids )
			{
				if( $("#" + ids[i]).length > 0 ) {
					if (ids[i] != 'magazineTopStories') {
						promoColumnHeight = promoColumnHeight + 200;
					}
					promoColumnHeight = promoColumnHeight - parseInt($("#" + ids[i]).height());
				}
			}

		//In case of three columns and right column is longer than the middle two, extend the middle column to same height as right
		if ($("#rightContent").height() != null){
			if (promoColumnHeight > $("#rightContent").height()){
				if ($.browser.msie && $.browser.version=="6.0" ){
//					$("#rightContent").css("height", promoColumnHeight - 200);
				}else {
					$("#rightContent").css("min-height", promoColumnHeight - 200 );
				}
			}
		}
	}, 300);

	// open print links in a new window
	$(".print").click(function(){
		window.open($(".print").attr("href"),'','width=800,height=480,scrollbars,resizable,location=no,menubar=no,toolbar=no');
		return false;
	});
	
	//decode email obfuscation
	if ($(".authorEmail").length){
		$(".authorEmail").each(function(){
			$(this).attr('href',$(this).attr('href').replace(' at ','@'));
		});
	}
	
	//############################
	//Carousel functions
	
	
	window.totalFeatures = $(".topStoryPlayer").length;
	window.currentFeature = 0;
	window.totalLoops = 1;
	window.currentFrame = 0;
	window.playing = true;
	
	//carousel function to show the ith feature
	function feature(i){
		//alert(i);
		window.currentFrame++;
		
		//hide all of the features except for this one
		$(".topStoryPlayer").fadeOut("slow");
		
		//unfocus the selected controller 
		$(".control a.number").removeClass("selected");
		
		$(".control").eq(i+1).find('a').addClass("selected");
		$("#topStoryPlayer" + (i+1)).fadeIn("slow");
	}
	
	function pauseCarousel(){
		clearTimeout();
		window.playing = false;
		$(".control a.play").css({
				'background-image':'url(/static/front/images/play-button.gif)',
				'background-repeat':'no-repeat',
				'background-color': '#e5ecf0',
				'background-position':'center center'
				});
	}
	
	$(".control a.play").click(function(){
		if (playing){
			pauseCarousel();
		}else {
			window.playing= true;
			$(".control a.play").css({
				'background-image':'url(/static/front/images/pause-button.gif)',
				'background-repeat':'no-repeat',
				'background-color': '#e5ecf0',
				'background-position':'center center'
				});
			rotateCarousel();
		}
		return false;
	});
	
	
	$(".control a.number").click(function(){
		feature(parseInt($(this).text()) - 1);
		pauseCarousel();
		return false;
	});
	
	//Carousel play functionality set to run with timeout
	function rotateCarousel(){ 
	
		//check to make sure its set to play and that it hasnt gone around too many times
		if (playing){
			//if its gone around too many times
			
			window.currentFeature++;
			feature( window.currentFeature % window.totalFeatures);
			window.setTimeout(rotateCarousel,7000);
			if  (((window.currentFrame +1)/window.totalFeatures) > window.totalLoops){
				pauseCarousel();
				window.currentFrame = 0;
			}
		}
	}
	window.setTimeout(rotateCarousel,6000);


	/**** functions to toggle through Our Latest Post **/
	window.latestOffset = 0;
	latestPostWidth = 335;
	function setLatestDate(){

		$("#ourLatestPost .date").html($("#olpEntry" + (window.latestOffset +1) + " .justInFormattedDate" ).html());
		Cufon.replace('#ourLatestPost h2');
		
	}
	setLatestDate();
	
	//Add function to toggle through Our Latest Post entries
	$("#ourLatestPost .nextEntryLink").live("click", function(){
	
		window.latestOffset++;
		
		$("#promoColumn #olpEntry" + window.latestOffset + "  .nextEntryLink").css('background' ,'url(/static/front/images/loadingSmall.gif) no-repeat left');
		
		var url = "/widget/recent/" + $("#olpEntry" + window.latestOffset + " .justInUnixDate").html() + "/" + window.latestOffset;
		
		$.getJSON(url,{} ,function(data){
			
			$("#ourLatestPost #olpScroll").append(data.output);
			$("#ourLatestPost #olpScroll").animate({
				marginLeft: '-=' + latestPostWidth + 'px'
			}, 800);
			setLatestDate();
			$("#promoColumn #olpEntry" + window.latestOffset + " .nextEntryLink").css("background", "url(/static/front/images/recentPostArrowRight.gif) center center no-repeat");
		});
		
		if (window.latestOffset == 1){
			$("#olp1 .previousEntryLink").fadeIn();
		}
		setLatestPostTimer();
		return false;
	});
	
	$("#ourLatestPost .previousEntryLink").live("click", function(){
		if (window.latestOffset >= 1){
			window.latestOffset--;
			$("#ourLatestPost #olpScroll").animate({
				marginLeft: '+=' + latestPostWidth + 'px'
			}, 800);
		}
		setLatestDate();
		setLatestPostTimer();
		return false;
	});
	
	$("#olpEntry1 .previousEntryLink").unbind("click");
	

	//Function to update ourlatest post with newest content after a certain amount of time
	function setLatestPostTimer(){
		window.clearTimeout(window.latestPostRefresh);
		window.latestPostRefresh = setTimeout(function() {
			
			var url = "/widget/recent/";
			
			$.getJSON(url,{} ,function(data){
				if ($(data.output).find(".justInUnixDate").html() > $("#olpEntry1 .justInUnixDate").html()){
					
					window.latestOffset = 0;
					$("#ourLatestPost #olpScroll").animate(
						{
						marginLeft:'0px'
						}, 1000 , function(){
							$("#ourLatestPost #olpScroll").html(data.output);
						});
					
					
				}
				setLatestDate();
				setLatestPostTimer();
			});
		
		}, 60000);
	}
	setLatestPostTimer();
	
	/******* DISQUS COMMENT COUNT ***********/
	$("a[href$='#disqus_thread']").each(function(i, element) {
		var disqusIdentifier = $(element).attr('disqus');

		$.getJSON('http://disqus.com/api/v1/get_num_posts/?thread_identifier=' + disqusIdentifier + '&forum_url=theatlantic&callback=?',
			function comments(data) {

				var numPosts    = data.num_posts;
				var commentText = 'Comment';
				if (numPosts != 0) {

					if (numPosts > 1) {
						commentText = commentText + 's';
					}

					commentText = commentText + ' (' + numPosts + ')';

					$(element).text(commentText);
				}
			}
		);		
	});

	omnitureClickTracking();
});


function omnitureClickTracking() {
	// Omniture Group Links
	$("#menu a").click(function(){
		s.tl(this,"o","Nav: main");
	});
	$("#menu .navExpanded a").click(function(){
		s.tl(this,"o","Nav: drop down");
	});
	$("#adHeaderCirc a").click(function(){
		s.tl(this, "o", "Ad: Mini Circ Unit");
	});
	$("#adTopleader a").click(function(){
		s.tl(this, "o", "Ad: Wide Circ Unit");
	});
	$("#menu .navExpanded .sponsor a").click(function(){
		var adChannel = $(this).parent().parent().parent().find('.navLink').text();
		s.tl(this, "o", "Ad: navLogo " + adChannel);
	});	
	$("#ourLatestPost a").click(function(){
		s.tl(this,"o","Module: Just in");
	});
	$("#newsstands a").click(function(){
		s.tl(this,"o","Module: On newstands now");
	});
	$("#circForm button").click(function(){
		s.tl(this,"o","Module: Circ Form");
	});
	$("#otherWorksOfGenius a").click(function(){
		s.tl(this,"o","Module: Other works of genius");
	});
	$("#choiceWords a").click(function(){
		s.tl(this,"o","Module: Choice words");
	});
	$("#newsletters button").click(function(){
		s.tl(this,"o","Module: News letters");
	});
	$("#breakingOpinions a").click(function(){
		s.tl(this,"o","Module: breaking opinions");
	});
	$("#voicesRiver a").click(function(){
		s.tl(this,"o","Module: homepage voices");
	});
	$("#voicesMenu a").click(function(){
		s.tl(this,"o","Module: channel all voices");
	});
	$("#channelVoice a").click(function(){
		s.tl(this,"o","Module: channel voice");
	});
	$("#video a").click(function(){
		s.tl(this,"o","Module: video");
	});
	$("#wire a").click(function(){
		s.tl(this,"o","Module: wire");
	});
	$("#dontMiss a").click(function(){
		s.tl(this,"o","Section: Dont Miss");
	});
	$("#carousel a").click(function(){
		s.tl(this,"o","Section: Carousel");
	});
	$("#channelTopStories a").click(function(){
		s.tl(this,"o","Section: Channel Top Stories");
	});
	$("#recentStories a").click(function(){
		s.tl(this,"o","Section: Recent stories");
	});
	$("#olderStories a").click(function(){
		s.tl(this,"o","Section: Less recent stories");
	});
	$("#filterArchive a").click(function(){
		s.tl(this,"o","Filter: Pop-up Menus");
	});
	$("#subchannelFilter a").click(function(){
		s.tl(this,"o","Filter: culture");
	});
	$("#storiesFromMagazine a").click(function(){
		s.tl(this,"o","Module: From Magazine");
	});
	$("#editorsPicks a").click(function(){
		s.tl(this,"o","Module: Editors Picks");
	});
	$("#backIssues a").click(function(){
		s.tl(this,"o","Module: Magazine back issues");
	});
	$("#premiumArchive button").click(function(){
		s.tl(this,"o","Module: Premium archive");
	});
	$("#foodAnchorPosts a").click(function(){
		s.tl(this,"o","Module: Corbys latest");
	});
	$("#recipeLibrary a").click(function(){
		s.tl(this,"o","Module: Recipe Library");
	});
	$("#followIcons a").click(function(){
		s.tl(this,"e","Follow: top right links");
	});
	$("#footer a").click(function(){
		s.tl(this,"e","Footer: links");
	});
}
