$(document).ready(function(){

    //Gets the height of body to compared to window height in positionFooter function
    var content_height = 0;
    if($('#contentHolder').length > 0)
    {
    	content_height = $('#contentHolder').height() + $("#header").height();
    }
    else
    {
    	content_height = $('body').height() + $("#header").height();
    	
    	//DEBUG
    	//console.log("Content Height: "+content_height);
    }
    
    /* Hack - have to do this because for some reason when the footer was set to absolute 
     * positioning, the body height would turn to 0 
     ***********************************************/
    if($('#homepage').length!=0)
    {
        $('body').css('height',content_height+'px');
    }
    
    //Positions the footer on the very bottom of the page
    positionFooter(); 
    
    $('#mainNav > li').bind('mouseover', jsddm_open);
    $('#mainNav > li').bind('mouseout',  jsddm_timer);
    document.onclick = jsddm_close;
    
    
    //IE 7 Centering second nav HACK
	if($.browser.msie && $.browser.version==7) 
	{
		if($('#centerNav').length != 0)
	    {
		 	$('#centerNav').css('display','inline');

			var cssWidth = $("#centerNav").width()+"px";

			$('#centerNav').css('display','inline-block');
			$('#centerNav').css('width',cssWidth);
		}
	
	}
    
    // Check to see if the mobile version should come up on initial load
    /*if($('#dasIstUnd_modalWindow').length == 0)
    {
	    if(jQuery(window).width() < 952)
	    {
	        $("link[rel=stylesheet]").attr({href : "css/mobile.css"});
	    }
	}*/
	
	 //Add scrollbar to the modal if it is bigger than the popup window.
	 if($('#dasIstUnd_modalWindow').length != 0)
	 {
		var modalBodyHeight = $('#modalContentHolder').height();
		var windowHeight = $(window).height();
		
		if(modalBodyHeight > windowHeight)
		{
			$('.scroll-pane').css('height',windowHeight+'px');
		}

		//DEBUG
		//console.log("Modal Height: "+modalBodyHeight);
		//console.log("Window Height: "+windowHeight);
	 }
    
    
    // Search Field Hide/Show
    $('#btn_search').click(function(event)
    {
    	$('#btn_search').css('display','none');
    	
    	$('#SearchForm_SearchForm_action_results').css('display','block');
    	$('#SearchForm_SearchForm_Search').fadeIn("fast");
    	
    	return false;
    });
    
    // Team Member Hide/Show Functionality
    if(location.href.indexOf("management")!=-1) {
    // Show first two
    var how_many_to_show = 2;
    
    $("#content .teamMember .teamMemberHeader").filter(function(index) {
    	if(index < how_many_to_show)
    	{
    		$(this).find('> div').addClass('down');
     		var teamMemeberDiv = $(this).next();
     		teamMemeberDiv.slideDown(
     			
     			function()
     			{
     				//For added height for positionFooter to figure out where to put the footer
     				//content_height = content_height + teamMemeberDiv.height();
     				
     				//console.log("Content Height ADDED: "+teamMemeberDiv.height());
     				positionFooter(); 
     			}
     		);
    		 
    	}

    });
    }
    
    // global functionality
    $('.teamMemberHeader').click(function(){
    	
    	if($(this).find('> div').attr("class")=="down") {
        	
        	content_height = content_height - $(this).next().height();
    		//console.log("Content Height SUBTRACTED: "+$(this).next().height());
    		
    		$(this).next().slideUp(
    			function()
    			{
    				positionFooter(); 
    			}
    		);
    		$(this).find('> div').removeClass('down');
        }
    	else
    	{
    		$(this).find('> div').addClass('down');
    		var teamMemeberDiv = $(this).next();
    		teamMemeberDiv.slideDown(
    			
    			function()
    			{
    				//For added height for positionFooter to figure out where to put the footer
    				//content_height = content_height + teamMemeberDiv.height();
    				
    				//console.log("Content Height ADDED: "+teamMemeberDiv.height());
    				positionFooter(); 
    			}
    		);
    	}
    	
    	
    });
    
   
    
    
//    $('.teamMemberHeader').toggle(
//    	function()
//    	{
//    		$(this).find('> div').addClass('down');
//    		var teamMemeberDiv = $(this).next();
//    		teamMemeberDiv.slideDown(
//    			
//    			function()
//    			{
//    				//For added height for positionFooter to figure out where to put the footer
//    				//content_height = content_height + teamMemeberDiv.height();
//    				
//    				//console.log("Content Height ADDED: "+teamMemeberDiv.height());
//    				positionFooter(); 
//    			}
//    		);
//    		
//  
//   					
//       	},
//    	function()
//    	{
//    		content_height = content_height - $(this).next().height();
//    		//console.log("Content Height SUBTRACTED: "+$(this).next().height());
//    		
//    		$(this).next().slideUp(
//    			function()
//    			{
//    				positionFooter(); 
//    			}
//    		);
//    		$(this).find('> div').removeClass('down');
//    		
//    		
//    	}	
//    );
    
    // Homepage Cycle
    if($('#hp_mediaHolder_cycle').length > 0 && $('#hp_mediaHolder_cycle img').length > 1) {
	    $('#hp_mediaHolder_cycle').cycle({ 
	        fx:     'scrollHorz', 
	        speed:  'slow', 
	        pager:  '#hp_mediaHolder_nav',
	        timeout: 10000,
	        pause: 1,
	        before:  onBefore
	    });
    }
    
    function onBefore() { 
        
        $('#hp_mediaTagHolder #lhs').fadeOut('fast');
        
        $('#hp_mediaTagHolder #lhs').html(this.alt); 
        $('#hp_learnMoreLink').attr({href : this.title}); 
        
        $('#hp_mediaTagHolder #lhs').fadeIn('slow');
    } 
    
    function onAfter() { 
        
        $('#hp_mediaTagHolder #lhs').html(this.alt); 
        $('#hp_learnMoreLink').attr({href : this.title});
    } 

       
    //On resize checks the size of the size and switch css if the size is mobile
    $(window).resize(function() {
        /*
		if(jQuery(window).width() < 952)
        {
            $("link[rel=stylesheet]").attr({href : "css/mobile.css"});
        }
        else
        {
            $("link[rel=stylesheet]").attr({href : "css/desktop.css"});
        }
		*/
        
        //If the window is changed, make the footer follow the changes
        positionFooter();
        
    });
    
    
     
    //Changes the position of the footer to stick to the very bottom of the site
	function positionFooter()
	{
		
		if($("#footerBGHolder").length > 0) 
		{
			var padding_top = $("#footerBGHolder").css("padding-top").replace("px", "");
			var page_height = $(document).height();
			var window_height = $(window).height() - $("#footerBGHolder").height();
	       
	       
	       if($('#contentHolder').length > 0)
		   {
		    	var content_height = $('#contentHolder').height() + $("#header").height()+40;
		   }
		   else
		   {
		    	var content_height = $('#hp_mediaHolder').height() + $("#header").height() + $("#hp_homeToActions").height() + $("#hp_secondaryContent").height();
		   }
			        
	        
	        //console.log("Window Height: "+window_height+" Page Height: "+page_height+" Content Height:"+content_height);
			 
			//If the page height is less than window height, then push footer to the bottom
			if(window_height > content_height)
			{
	            $("#footerBGHolder").css("position","absolute");
				$("#footerBGHolder").css("bottom", "0px");
	             //console.log("Absolute");
	        }
			else
			{
	            $("#footerBGHolder").css({position:"static"});
	            //console.log("Static");
				// $("#footer").css("top", $(document).height()+"px");sdfsdf
			}
		}
	
	}


	/*
	 * Products Page - goes through each product ( if exists ) and makes each block 
	 * a link to whatever is the H1 href of that block
	 ******************/
	 if(jQuery('.productHolder').length != 0)
     {

		 jQuery(".productHolder").each(
			function() { 
				//console.log(jQuery(this).find('> h1 a').attr("href"));
				//alert(jQuery("h1 a").attr("href"));
				jQuery(this).hover(
					function() {
						jQuery(this).css({"cursor":"pointer"});
					});
				jQuery(this).click(
					function() {
						var the_link = jQuery(this).find('> h1 a').attr("href");
						top.location=the_link;
					});
			}
		);
	}

	/*
	 * Drop Down Menu 
	 ******************/
	var timeout    = 500;
	var closetimer = 0;
	var ddmenuitem = 0;
	var dd = 0;
	
	function jsddm_open()
	{  
	   jsddm_canceltimer();
	   jsddm_close();
	   dd = $(this).find('> a');
	   ddmenuitem = $(this).find('ul').css('visibility', 'visible');
	   $(this).find('> a').css('background-color','#016ac2');
	}
	
	function jsddm_close()
	{  
	    if(ddmenuitem)
	    {
	        //alert("test");
	        ddmenuitem.css('visibility', 'hidden');
	        $(dd).css('background-color','transparent');
	    }
	    
	}
	function jsddm_timer()
	{  closetimer = window.setTimeout(jsddm_close, timeout);}
	
	function jsddm_canceltimer()
	{  if(closetimer)
	   {  window.clearTimeout(closetimer);
	      closetimer = null;
	   }
	}

	// give 3rd-tier page titles smaller font
	//$("#breadcrumb:has(br)").$("#breadcrumb span").css({"font-size":"30px"});
	$("#breadcrumb:has(br)").addClass("is-third");
	
    // form modal open/close	
	if($("a.form-modal").length > 0) {
		$("a.form-modal").fancybox({
			'width'				: 540,
			'height'			: 850,
			'margin' 			: 80,
			//'padding' 		: 80,
			'scrolling'         : 'no',
			'overlayOpacity'    : .5,
			'overlayColor'      : '#000000',
			'autoScale'			: false,
			'transitionIn'		: 'elastic',
			'transitionOut'		: 'fade',
			'type'				: 'iframe',
			'centerOnScroll'    : false,
			'hideOnContentClick': true,
			'showCloseButton'   : true/*,
			'onClosed'          : function() {
									 if(top.location.href.indexOf('pertrac-research')!=-1) 
									 	top.location.reload();
								  }*/
		});
		
	}
	
	//Gallery Plugin	
	if($(".gallery").length > 0) {
	
		//To fit the gallery, the first few content items need to be smaller
		$("#content p:first").css("width","420px");
		$("#content h2:first").css("width","420px");
		$("#content ul:first").css("width","420px");
		$("#content ul:first").css("overview","hidden");
		
		$(".gallery #thumb").show();
	
		//When the thumbnail is clicked
		$(".gallery").click(function(){
				
				var imagesArray = new Array();
				
				//goes through each image, grabs its SRC and pushes it into the imagesArray array
				$(".gallery_content img").each(
					function()
					{
						imagesArray.push($(this).attr("src"));
					}
				);
				
				//Activates Fancybox using the imagesArray 
				$.fancybox(
					imagesArray
				, {
					'padding'			: 15,
					'transitionIn'		: 'elastic',
					'transitionOut'		: 'fade',
					'type'              : 'image',
					'changeFade'        : 150
				});
							
		});
	}
	 
	//Preload Images
	function preload(arrayOfImages) {
	    $(arrayOfImages).each(function()
	    {
	        $('<img/>')[0].src = this;
	    });
	}
	
	preload([
	         "themes/pertrac/images/bg_smallSideBar_over.png",
	         "themes/pertrac/images/bg_bigSideBar_over.png",
	         "themes/pertrac/images/bg_blue_btn_over.png",
	         "themes/pertrac/images/bg_tab_hover.png",
	         "themes/pertrac/images/btn_alpha-hover.png",
	         "themes/pertrac/images/btn_arrows-hover.png",
	         "themes/pertrac/images/btn_chart-hover.png",
	         "themes/pertrac/images/btn_cogs-hover.png",
	         "themes/pertrac/images/btn_hub-hover.png",
	         "themes/pertrac/images/btn-content-cta-over.png",
	         "themes/pertrac/images/btn-content-cta-small-over.png",
	         "themes/pertrac/images/btn_hpColumn_on.png", 
	         "themes/pertrac/images/bg_support_btn_hover.png",
	         "themes/pertrac/images/bg_learnMore_btn_hover.png"
    ]);

	jQuery.setLeadSourceCookies();

	// Detect if a hidden field is present in the current page
	var leadSourceField = jQuery("input[title=WhereHear]");
	if (leadSourceField.length > 0) {
		
		// If the lead source field is present populate it with the cookie value
		var leadSource = jQuery.getLeadSourceFromCookie();
		if (typeof leadSource != 'undefined' && leadSource.length > 0) {
			leadSourceField.val(leadSource);
		}
	}
	
	// Set United States as the default country option
	var countryDropDown = jQuery("[id*=EditableCountryDropdownField]");
	if (countryDropDown.length) {
		jQuery("[id*=EditableCountryDropdownField] option[value='United States']").attr('selected', 'selected');
	}
});

jQuery.extend({
	getUrlVars: function() {
		var vars = {};
		var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, 
				function(m,key,value) {
					vars[key] = value;
				});
		return vars;
	},
	setLeadSourceCookies: function() {
		var leadSource = jQuery.getUrlVars()['source'];
		if (leadSource != null && typeof leadSource != 'undefined' && leadSource.length > 0) {
			leadSource = unescape(leadSource);
			jQuery.cookie("CampaignST", leadSource + " (ST)", { path: '/' }); // session cookie
			jQuery.cookie("CampaignLT", leadSource + " (LT)", { expires: 3700, path: '/' }); // persistent cookie, expires after roughly a decade
		}
	},
	getLeadSourceFromCookie: function() {
		// Check if there is a short-term PerTrac cookie (i.e. the session cookie)
		var leadSource = jQuery.cookie("CampaignST");
		// If not, check if there is a long-term PerTrac cookie
		if (leadSource == null || leadSource === 'undefined' || leadSource.length < 1) {
			leadSource = jQuery.cookie("CampaignLT");
		}
		// Otherwise, fill the element with the google-supplied information in the format "source / medium / campaign"
		if (leadSource == null || typeof leadSource === 'undefined' || leadSource.length < 1) {
			leadSource = jQuery.getLeadSourceFromUrchin();
		}
		return leadSource;
	},
	getLeadSourceFromUrchin: function() {
		var leadSource = "";
		var gc = jQuery.cookie("__utmz");
		if (gc != null && typeof gc != 'undefined' && gc.length > 0) {
			var z = gc.split('.');
			if (z.length >= 4) {
				var y = z[4].split('|');
				for (i = 0; i < y.length; i++) {
					if (y[i].indexOf('utmgclid=') >= 0) ga_adwords =  y[i].substring(y[i].indexOf('=') + 1);
					if (y[i].indexOf('utmcsr=') >= 0)   ga_source =   y[i].substring(y[i].indexOf('=') + 1);
					if (y[i].indexOf('utmccn=') >= 0)   ga_campaign = y[i].substring(y[i].indexOf('=') + 1);
					if (y[i].indexOf('utmcmd=') >= 0)   ga_medium =   y[i].substring(y[i].indexOf('=') + 1);
					if (y[i].indexOf('utmctr=') >= 0)   ga_term =     y[i].substring(y[i].indexOf('=') + 1);
					if (y[i].indexOf('utmcct=') >= 0)   ga_content =  y[i].substring(y[i].indexOf('=') + 1);
				}
			}
			leadSource = ga_source + " / " + ga_medium + " / " + ga_campaign;
		}
		return leadSource;
	},
	log: function(message) {
		//if('console' in window && 'log' in window.console)
		if (typeof window.console != 'undefined' && typeof window.console.log != 'undefined') {
			console.log(message);
		}
	}
});

