

$(document).ready(function(){
	// CALL FUNCTION FOR DYNAMIC PHONE SWAPPING
	swapPhone();
	

// THE LOGIC BELOW IS A STOP GAP UNTIL THE NEW INQ PAGE ERRORS ARE PUBLISHED AND THEN CAN BE REMOVED

	// Adds a class to the DIV that surrounds the textbox inputs on the INQ form
	$('#inq-form-first-name-field').addClass("form-field-style");
	$('#inq-form-last-name-field').addClass("form-field-style");
	$('#inq-form-email-field').addClass("form-field-style");
	$('#inq-form-address1-field').addClass("form-field-style");
	$('#inq-form-city-field').addClass("form-field-style");
	$('#inq-form-zip-field').addClass("form-field-style");
	
	// Adds a class to the actual textbox inputs/selects on the INQ form
	$('#inq-form-first-name-field input').addClass("form-input-style");
	$('#inq-form-last-name-field input').addClass("form-input-style");
	$('#inq-form-email-field input').addClass("form-input-style");
	$('#inq-form-address1-field input').addClass("form-input-style");
	$('#inq-form-city-field input').addClass("form-input-style");
	$('#inq-form-zip-field input').addClass("form-input-style");
	$('#inq-form-howheard-field  select').addClass("form-select-style"); 
	$('#inq-form-country-field select').addClass("form-select-style");
	$('#inq-form-state-field select').addClass("form-select-style");

	// Modifys the form wrapper specifically to add a background image
	/* $('#inq-form-wrapper').css("width","240");
	$('#inq-form-wrapper').addClass("inq-form-wrapper-mod");
	$('#inq-form-wrapper').before('<div id="inq-form-top"></div>');
	$('#inq-form-wrapper').after('<div id="inq-form-bottom"></div>');
	*/

	// Adds padding to the bottom of every element wrapper
	$('#inq-form-first-name-wrapper').addClass("el-pad");
	$('#inq-form-last-name-wrapper').addClass("el-pad");
	$('#inq-form-address-wrapper ').addClass("el-pad");
	$('#inq-form-city-wrapper').addClass("el-pad");
	$('#inq-form-stateandzip-wrapper').addClass("el-pad");
	$('#inq-form-country-wrapper').addClass("el-pad");
	$('#inq-form-email-wrapper').addClass("el-pad");
	$('#inq-form-howheard-wrapper').addClass("el-pad");







	// checks for the presence of a image gallery and handles it	
	if($("#product-image-wrapper ul").length != 0) {productImageGallery()};

	// checks for the presence of tabbed content and handles it	
	if($("#product-extras-wrapper").length != 0) {productTabbedInfo()};

	// checks to see if a modal link was clicked and handles it	
	$(".popup-active").bind('click', launchModal);

	//Close Popups and Fade Layer (REFACTOR THIS)
	//$('.modal-close-button, #modal-background').live('click', function() { //When clicking on the close or fade layer...
		//$('#modal-background , .modal-base').fadeOut(function() { $('#modal-background, .modal-close-button').remove(); });
		//return false;
	//});


	$(".modal-close-button, #modal-background").die( "click" )

	//$('.modal-close-button, #modal-background').live('click', function() { //When clicking on the close or fade layer...
	//	$('#modal-background , .modal-base').fadeOut(function() {
	//		$('#modal-background, .modal-close-button').remove();
	//		var modalVid = $('.modal-base');
	//		stopYouTubePlayer(modalVid);
	//	});
	//	return false;
	//});
	
	$('.modal-close-button, #modal-background').live('click', function() { //When clicking on the close or fade layer...
		$('#modal-background , .modal-base').hide();
		$('#modal-background, .modal-close-button').remove();
		var modalVid = $('.modal-base');
		stopYouTubePlayer(modalVid);
		return false;
	});
	
	


// This function contains all the logic for the auto display of a modal on page load 
$.fn.popOpen = function(){

    var popID = $(this).attr('rel'); //Get Popup Name
    var popURL = $(this).attr('href'); //Get Popup href to define size

    //Pull Query & Variables from href URL
    var query= popURL.split('?');
    var dim= query[1].split('&');
    var popWidth = dim[0].split('=')[1]; //Gets the first query string value

    //Fade in the Popup and add close button
    $('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<a href="#" class="modal-close-button"><img src="images/close_pop.png" border="0" /></a>');
	

    //Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
    var popMargTop = ($('#' + popID).height() + 80) / 2;
    var popMargLeft = ($('#' + popID).width() + 80) / 2;

    //Apply Margin to Popup
    $('#' + popID).css({
        'margin-top' : -popMargTop,
        'margin-left' : -popMargLeft
    });

    //Fade in Background
    $('body').append('<div id="modal-background"></div>');
	//.css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies 
    $('#modal-background').css({'filter' : 'alpha(opacity=80)'}).fadeIn();


};


// This calls the above function
$('a.inqautopop[href=#?w=800]').popOpen(); //Run popOpen function once on load



});






// IMAGE GALLERY ON PRODUCT PAGE
function productImageGallery(evt) {	
	// Show the gallery if the user has javascript and add styles to the gallery
	$("#product-image-gallery").css("display", "block");
	$("#product-image-gallery li").css("margin-left", "0");
	$("#product-image-gallery img:first").addClass("current-pic");	
	$("#product-image-gallery li:last").addClass("last-thumb");
	
	// This is duplicative and needs to be refactored
	var fRel = $(".current-pic").attr("rel"); 
	if (fRel == 'popup-video') {
		$("#featured-image").attr({ rel: fRel }).css("cursor", "pointer").bind('click', launchModal);
		} else {
		$("#featured-image").attr({ rel: 'default' }).css("cursor", "default").unbind('click');
		};


	// Add an event handler to each of the images and change the images when clicked
	$("#product-image-gallery img").click(function() {												   
		$(".current-pic").removeClass("current-pic");		
		$(this).addClass("current-pic");
														   
		var srcValue = $(this).attr("src");
		var relValue = $(this).attr("rel"); 
		$("#featured-image").attr({ src: srcValue });
		
		// This needs to be made more generic to handle is ANY rel is present
		if (relValue == 'popup-video') {
			$("#featured-image").attr({ rel: relValue }).css("cursor", "pointer").bind('click', launchModal);
			} else {
			$("#featured-image").attr({ rel: 'default' }).css("cursor", "default").unbind('click');
			};
	
	});	
}



// TABBED INFORMATION ON PRODUCT PAGE
function productTabbedInfo(evt) {	

	// Show the tabbed area
	$("#tabbed-content-wrapper").css("display", "block");	

	// Located the specified default tab and show it, or just show the first tab if no default was specified
	if($(".default-tab").length == 0) {
		$("#tabbed-content-wrapper div:first").addClass("active-tab-content");	
		} else {
		$("div.default-tab").addClass("active-tab-content");	
		};
		
	$(".active-tab-content").css("display", "block"); // This is done here and not in the CSS sheet do to specificity rules

	// Create the tabbed navigation 
	$("#product-extras-wrapper").prepend('<ul style="margin-bottom:0px;" id="product-tabs"></ul>'); //Style hard coded due to specifity issues

	$(".tab-title").each(function() {
		var parentID = $(this).parent().attr("id");
		var liClass = '<li rel="' + parentID + '" style="margin-left:0px;padding:0 10px;">'; //Style hard coded due to specifity issues		
		if ($(this).parent().hasClass('active-tab-content'))
			liClass = '<li rel="' + parentID + '" style="margin-left:0px;padding:0 10px;" class="active">';	//Style hard coded due to specifity issues				 
		$("#product-tabs").append(liClass + $(this).text() + '</li>');
	});
		
	// When a visitor clicks on a tab, make it the active tab and switch the content
	$("#product-tabs li").click(function() {										 
		$("#product-tabs li").removeClass("active");
		$(this).addClass("active");
					
		// Hide the old content
		$(".active-tab-content").css("display", "none");
		$("#tabbed-content-wrapper div").removeClass("active-tab-content");
		
		// Show the new content (IE shows full path and FF doesn't so we are forced to split the string in this way to fix IE
		var activeTab = $(this).attr('rel');
		$('#' + activeTab).addClass("active-tab-content");
		$(".active-tab-content").fadeIn();
		
	});
}


// UNIVERSAL MODAL HANDLER
function launchModal(evt) {
	// Reset all videos, just in case one is playing in a tab. To be stopped, a YouTube iframe must have the class "youtubevid".
	//stopVideoPlayers();


	// Locate the DIV ID that we are going to pop, fade it in, and add the close button
    var modalWindow = "#" + $(this).attr('rel');
    $(modalWindow).fadeIn().prepend('<a href="#" class="modal-close-button"><img src="images/close_pop.png" border="0" /></a>');
	
	// Center the modal box
    var marginTop = ($(modalWindow).height() + 40) / 2;	
    var marginLeft = ($(modalWindow).width() + 40) / 2;	
    $(modalWindow).css({'margin-top' : -marginTop, 'margin-left' : -marginLeft});	
	
    //Fade in Background
    $('body').append('<div id="modal-background"></div>');
	//.css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies 
    $('#modal-background').css({'filter' : 'alpha(opacity=80)'}).fadeIn();

	return false;
}



// GET COOKIE INFO - this function accepts a cookie name and returns its paired value
function getCookie(c_name) {

	if (document.cookie.length>0) {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1) {
		c_start=c_start + c_name.length+1;
		c_end=document.cookie.indexOf(";",c_start);
		if (c_end==-1) c_end=document.cookie.length;
		return unescape(document.cookie.substring(c_start,c_end));
		}
	  }
	return "";
}


// CREATE COOKIE 
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
		window.location.reload();
	}
	else var expires = "";
	document.cookie = name + "=" + value + expires + "; path=/";
	window.location.reload();
}




// GET URL PARAMETER - This function parses the URL string a builds Variable/Assignment pairs
function getVars() {
  
   document.$_GET = [];
   var urlHalves = String(document.location).split('?');
   
   if(urlHalves[1]){
      var urlVars = urlHalves[1].split('&');
      for(var i=0; i<=(urlVars.length); i++){
         if(urlVars[i]){
            var urlVarPair = urlVars[i].split('=');
            document.$_GET[urlVarPair[0]] = urlVarPair[1].toLowerCase();
         }
      }
   }  
}




// LOGIC FOR THE CPR TEST
function swapPhone() {

	
	var src1 = "vw72778ae3273933"; // PPC A Side source code for CPR Test
	var src2 = "vw72778be3273933"; // PPC B Side source code for CPR Test
	var src3 = "vw72779ae3173933"; // Ads A Side source code for CPR Test
	var src4 = "vw72779be3173933"; // Ads B Side source code for CPR Test 
	var tel1 = "1-877-285-1751"; // A Side phone number for CPR Test
	var tel2 = "1-877-285-1753"; // B Side phone number for CPR Test	
	var cprCookie = getCookie('cprside');

	getVars();
	
  	// Check to see if the CPR Test cookie is present. If not, determine which side the visitor is on and set the correct cookie value
	if(cprCookie.length <= 0) {	
	
		if(document.$_GET['src'] == src1 || document.$_GET['src'] == src3) {					
			createCookie('cprside','a',90);
		}
		if(document.$_GET['src'] == src2 || document.$_GET['src'] == src4) {					
			createCookie('cprside','b',90);
		}
						
	} else {
	
		if(cprCookie == 'a') {	
			document.getElementsByTagName("strong")[0].innerHTML = tel1;
		}		
		
		if(cprCookie == 'b') {
			document.getElementsByTagName("strong")[0].innerHTML = tel2;
		}	
	}
	

	
	
}



// Switches between tabs on product detail pages. This function is pulled into some pages as 'tabSwitch_2' from a separate file called "tabfunction.js".
// This is inefficient for such a small amount of code. I've moved it here and renamed it as 'tabSwitch to eliminate the extra http call. However, the  
// function name should be updated on a page-by-page basis. The other JavaScript file still exists to maintain function on other pages.
function tabSwitch(active, number, tab_prefix, content_prefix) {
	var currentTab;
	var currentContent;
	var ytContainers;
	
	for (var i=1; i < number+1; i++) { // Looping through tabs. Counting starts at one rather than zero.

		currentTab = $("#" + tab_prefix+i); // The tab whose ID matches the loop counter.
		currentContent = $("#" + content_prefix+i); // The tab content whose ID matches the loop counter.
		currentYoutubeContainers = $("#" + content_prefix+i + " .youtubevid").parent(); //Whatever element holds a youtube video embed. The embed must have the class 'youtubevid'.
		
		if(i != active) { // If the clicked tab is NOT active...
			currentContent.css('display','none'); // Hide content if the tab is not active.
			currentTab.removeClass('active'); // Removes the 'active' class from a non-active tab.
			stopYouTubePlayer(currentYoutubeContainers);
			//currentYoutubeContainers.removeClass('test');
		}
		else { // If the clicked tab IS active.
			currentContent.css('display','block'); // Show content for the active tab.
			currentTab.addClass('active'); // Add 'active' class to clicked tab.
			//currentYoutubeContainers.addClass('test');
		}
		
	} // Close loop.
}



// YouTube players don't stop when you move to another tab or close a modal box. Since they're just being hidden, the video object 
// still exists on the page, so the audio can be heard. Since the YouTube JavaScript API is problematic, we're saving the contents 
// of the video container, removing them from the DOM, and then putting them back a few miliseconds later.
// To use it, save a jQuery selector to a variable and pass it into the function. The selector should be an object whose direct child 
// is a YouTube iframe or embed.
function stopYouTubePlayer(targetSelector) {

	targetSelector.each(function(){ // looping through the jQuery object passed in. Remember, jQuery objects are actually arrays.
		var ytContainer = $(this); // caching 'this' as a variable.
		var ytplayerEmbed = ytContainer.html(); // saving the HTML contents of the target container to a variable.
		ytContainer.html(''); // erasing the contents
		//setTimeout(function() { // waiting a few miliseconds, then restoring the contents of the target container.
			ytContainer.html(ytplayerEmbed);
		//}, 300);		
				
	});

}










