$(document).ready(function() {
  
   //Handle Login   
   $("#login").fancybox({
                'width' : 350,
                'height' : 275,
				'transitionIn'		: 'none',
				'transitionOut'		: 'none',
				'type'				: 'iframe'
    });
       $("#login2").fancybox({
                'width' : 350,
                'height' : 275,
				'transitionIn'		: 'none',
				'transitionOut'		: 'none',
				'type'				: 'iframe'
    });
    $("#txtEmail").focus();
   //END 
    //Handle the search
   $("#search").click(function (){
   var quickSearch = $(".txtAuxSearch").val();      
   $.cookies.set( 'searchKeyword', ''+quickSearch+'' )
   $.cookies.set( 'searchContent', ''+quickSearch+'' )
   });
  
  $('.txtAuxSearch').keypress(function(e){
			 var code = (e.keyCode ? e.keyCode : e.which);
			 if(code == 13) {
			     var quickSearch = $(".txtAuxSearch").val();      
                 $.cookies.set( 'searchKeyword', ''+quickSearch+'' );
                 window.location = 'http://' + document.domain + '/read-and-rate-stories.aspx';
				return false;
			 }			 
	});
    //END
   
    

    
        
    /* 	Auto event tagging. Ensure that the correct class and title attributes are applied.	*/
    var pageTitle = document.title
    $(function() {
        $("#auxNavItems a").click(function() {
            var label = $(this).attr("title");            
            pageTracker._trackEvent('Auxilary Nav', 'Click Event', 'Page Title: ' + pageTitle + ' Nav Item: ' + label + '');
        });

        $("#mainNav a").click(function() {
            var label = $(this).attr("title");            
            pageTracker._trackEvent('Main Nav', 'Click Event', 'Page Title: ' + pageTitle + ' Nav Item: ' + label + '');
        });

        $("#footerContent a").click(function() {
            var label = $(this).attr("title");            
            pageTracker._trackEvent('Footer', 'Click Event', 'Page Title: ' + pageTitle + ' Nav Item: ' + label + '');
        });
        

    //SPRITE ACTIVE STATES
   //grab pathname
     var currentPage = window.location.pathname;
          
     
     
     
            
    if(currentPage == "/default.aspx" || currentPage == "/" || currentPage == "/default_Temp.aspx")
    {
    runTimer();
    }
    else if (currentPage == "/the-story-of-timex.aspx")
    {
        $('a[href="' + currentPage + '"]').attr("ID","active");
        //Load The Tips
        loadTips();
    }
    else if (currentPage == "/read-and-rate-stories-details.aspx")
    {
        $('.read').attr("ID","active");
    }
    else
    $('a[href="' + currentPage + '"]').attr("ID","active");

            init();
            
       function runTimer(){
             var contestExpiry = new Date();
             var daylightSavingsTimeOffset = -1
             contestExpiry = new Date(contestExpiry.getFullYear() + 0, 6 - 1, 15);
              
            $('#defaultCountdown').countdown({until: contestExpiry,
            layout: '<div class="image{d100}"></div><div class="image{d10}"></div><div class="image{d1}"></div>' + 
        '<div class="imageSep"></div>' + 
        '<div class="image{h10}"></div><div class="image{h1}"></div>' + 
        '<div class="imageSep"></div>' + 
        '<div class="image{m10}"></div><div class="image{m1}"></div>' + 
        '<div class="imageSep"></div>' + 
        '<div class="image{s10}"></div><div class="image{s1}"></div>'}); 
            }
    });
    
//TIMELINE
    var totalYears = [];
    var cycleUp = 0

    function init(){
    loadStoryXML();
    };

    function loadStoryXML(){
        $.ajax({
                    type:"GET",
                    url:"../includes/xml/timeline.xml",
                    cache: false,
                    dataType:"xml",
                    success:function(xml)
                    {   
                        storylineXML = $(xml);
                        setupDots(xml);
                        loadStory("story_1850");
                        $('#timelineLeft').hide();
                    } 
            });
    }
    
    function setupDots(xml){
        //bind id's from xml to the dots on the page
        
        $(xml).find('story').each(function(){
            var storyId = $(this).attr('id');
            var titleId = $(this).attr('title');
            var tooltip = $(this).attr('tooltip');
            
            
            var redDot = '<li><img src="/images/global/redDot.png" id="'+storyId+'" class="redDot" /><div id="'+storyId+'_tooltip" class="featureBubble" style="display: none;"><div class="imageWrapper"><img height="32" width="49" alt="pic" src="'+tooltip+'"></div><p>'+titleId+'</p></div></li>'
            $('#timelineDotList').append(redDot);
            
            totalYears.push(storyId); 
        });
    }
    function loadStory(id){
        clearDots();
        var loadStoryId = $(storylineXML).find('story[id = '+id+']').text();
        $('#timelineContents').html(loadStoryId);
        $('#timelineDotList > li').children('#'+id+'').attr('src', '../images/global/redDot_hover.png');
    }
    //Timeline Event Handlers
    
    $('#timelineRight').click(function (){
        if(cycleUp == 0)
        {
            $('#timelineContents').html('');
            $('#timelineLeft').fadeIn();
            cycleUp++;
            loadStory(totalYears[cycleUp]);
        }
        else if(cycleUp == 1)
        {       
            $('#timelineContents').html('');
            cycleUp++;
            loadStory(totalYears[cycleUp]);
        }
        else if(cycleUp == 11)
        {
            $('#timelineContents').html('');
            cycleUp++;
            loadStory(totalYears[cycleUp]);
            $('#timelineRight').hide();
        }
        else
        {
            $('#timelineContents').html('');
            cycleUp++;
            loadStory(totalYears[cycleUp]);
        }
    });
    
    $('#timelineLeft').click(function (){
        if (cycleUp == 1)
        {
            $(this).hide();
            $('#timelineContents').html('');
            cycleUp--;
            loadStory(totalYears[cycleUp]);
        }
        else if(cycleUp == 12)
        {
            $('#timelineRight').fadeIn();
            $('#timelineContents').html('');
            cycleUp--;
            loadStory(totalYears[cycleUp]);
        }
        else
        {
            $('#timelineContents').html('');
            cycleUp--;
            loadStory(totalYears[cycleUp]);
        }
    });
    
    $('.redDot').live('click',
        function (){
        clearDots();
        $(this).attr('src', '../images/global/redDot_hover.png');
        
        var id = $(this).attr("ID");
        cycleUp = $(storylineXML).find('story[id = '+id+']').attr('cycleid');
        if(cycleUp == 12)
          {
            loadStory(id);
            $('#timelineRight').fadeOut('fast');
          }
        else if(cycleUp >= 1)
          {
            loadStory(id);
            $('#timelineLeft').fadeIn();
             $('#timelineRight').fadeIn();
          }
        else
          {
            loadStory(id);
            $('#timelineLeft').fadeOut('fast');
          }
        });
    
        $('#timelineDotList > li').live('mouseover',
        function(){
            $('.featureBubble:animated').stop(true, true).hide();
            $(this).children('.featureBubble').fadeIn();
        });
        
        $('.redDot').live('mouseout',
        function(){
            $('.featureBubble').fadeOut('fast');
        });

    function clearDots() {
        $('.redDot').attr('src', '../images/global/redDot.png');
        $('#timelineContents').html('');
    } 
    //HandleRating
    function handleRating() {
        //Turn all the select boxes into rating controls
    }
    
    //LoadTips
    function loadTips(){
        $.ajax({
            type:"GET",
            url:"../includes/xml/sideTipsConfig.xml",
            cache: false,
            dataType:"xml",
            success:function(xml)
            {
            timeForTips(xml);
            $("#rightCallTop").delay(13000).fadeOut(function() {
                timeForTips(xml);
                window.setInterval(function() {
                    $("#rightCallTop").fadeOut(function(){
                    timeForTips(xml)
                    
                    })}, 15000);
            
            });

            } 
    });
    
    }
    
    
    //MISC EVENTS


    
        //TIME FOR TIPS
        function timeForTips(xml) {        
                
                var tipsLengthArr = []                     
                var tipsLength = $(xml).find('tip').each(function(){tipsLengthArr.push($(this))});
                var randomTipNumber = Math.floor(Math.random()*tipsLength.length)
                var randomTip = $(xml).find('tip[id = '+randomTipNumber+']')
                var currentTipImage = $(randomTip).find('image').text();
                var currentTipContent = $(randomTip).find('content').text();
                
                $('#rightCallTop').html('<img src="'+currentTipImage+'" class="tipImage"/>'+currentTipContent+'')
                $('#rightCallTop').fadeIn("slow");
        }
    
        //HOME PAGE HOVERS
        $("#amazingButTrueImg").hover(function(){
        
            $(this).attr("src", "/images/global/amazingbutTrue_icon_ovr.png");
            $("#amazingButTrueLink").css("textDecoration", "Underline")
        
        }, 
        function (){
            
            $(this).attr("src", "/images/global/amazingbutTrue_icon.png");
            $("#amazingButTrueLink").css("textDecoration", "None")
        }
        );
        
        $("#rateStoryImg").hover(function(){
        
            $(this).attr("src", "/images/global/homePagebotCol_ovr.png");
            $("#rateStoryLink").css("textDecoration", "Underline")
        
        }, 
        function (){
            $(this).attr("src", "/images/global/homePagebotCol.png");
            $("#rateStoryLink").css("textDecoration", "None")
        }
        );
        
        
        //HOME PAGE LINK HOVERS
        $("#amazingButTrueLink").hover(function(){
        
            $("#amazingButTrueImg").attr("src", "/images/global/amazingbutTrue_icon_ovr.png");
            $(this).css("textDecoration", "Underline")
        
        }, 
        function (){
            
            $("#amazingButTrueImg").attr("src", "/images/global/amazingbutTrue_icon.png");
            $(this).css("textDecoration", "None")
        }
        );
    
    $("#rateStoryLink").hover(function(){
    
        $("#rateStoryImg").attr("src", "/images/global/homePagebotCol_ovr.png");
        $(this).css("textDecoration", "Underline")
    
    }, 
    function (){
        $("#rateStoryImg").attr("src", "/images/global/homePagebotCol.png");
        $(this).css("textDecoration", "None")
    }
    );
    
    
});
