// JavaScript Functions

// Global Variables
var previousCommercial = "1";
var previousDiv;

var navID = new Array(); // define page names for function highlightNavButton()

// Main nav
navID[0] = "Breakthroughs";
navID[1] = "Our_Collection";
navID[2] = "ProductBuzz";
navID[3] = "Promotions";

// Sub Nav - Our Collection
navID[4] = "Smooth";
navID[5] = "Glow";
navID[6] = "Nourish";
navID[7] = "Preserve";
navID[8] = "Cleanse";
navID[9] = "Soften";
navID[10] = "Naturals";

// Sub Nav - Beauty Breakthroughs
navID[11] = "Naturals";
navID[12] = "Sensitive_Skin";


// Description: tests whether the substring is contained within the string
// Returns: boolean
String.prototype.contains = function (testString)
{
	if(this.indexOf(testString) > -1)
	{
		return true;
	}
	else
	{
		return false;
	}
}

// Description: prints browser specific css file links
// Returns: Nothing
function printBrowserCSS()
{
	// get user's browser 
	var userAgentString = navigator.userAgent.toLowerCase();
	
	// only display special styles for Safari and FireFox	
	if(userAgentString.contains("safari") || userAgentString.contains("firefox"))
	{ 
//		document.write('<link rel="stylesheet" type="text/css" href="/CSS/FireFox.css" />');
	}
}

function highlightCommercial(commercial)
{ // home page 	
	document.getElementById("CommercialLink" + previousCommercial).style.backgroundImage = "url('/Images/Navigation/bg_Commercial.gif')";
	document.getElementById("CommercialLink" + commercial).style.backgroundImage = "url('/Images/Navigation/bg_Commercial_On.gif')";

	// remember active commercial
	previousCommercial = commercial;
}

function checkFor(string)
{ // returns the starting character position or -1 if not found
	position = UserAgent.indexOf(string) + 1;	
	return position;
}

function displayDiv(divID)
{ // toggles divs
  if(divID != previousDiv)
	{  // do not turn off same div
		document.getElementById(divID).style.display = 'block';
		// hide from user
		try
		{
			document.getElementById(previousDiv).style.display = 'none';
		}
		catch(err)
		{
		  /* ignore undefined previousDiv error */
		}
	}
	previousDiv = divID
}
// ** NOTE: Had to keep capitalized due to content in DB **
// Commented function would be better to use, but FAQ in DB must be modified
/*
function DisplayAnswer(elementId, question, answer)
{ // used in FAQs on Product Details page
	// display Answer div
	document.getElementById(elementId).style.display = 'block';
	
	// build content
	var Content = "<div id='Close' onclick=\"document.getElementById('" + elementId + "').style.display='none'\"> X Close </div>";
	Content += "<div class='HeaderQuestion'>" + question + "</div>";
	Content += "<div style='height: 6px;'><!-- line space --></div>";
	Content += answer;
	
	// update "Answer" div content
	document.getElementById(elementId).innerHTML = Content;
}
*/
// function displayAnswer(Question, Answer)
function DisplayAnswer(Question, Answer)
{ // used in FAQs on Product Details page
	// display Answer div
	document.getElementById("Answer").style.display = 'block';
	
	// build content
	var Content = "<div id='Close' onclick=\"document.getElementById('Answer').style.display='none'\"> X Close </div>";
	Content += "<div class='HeaderQuestion'>" + Question + "</div>";
	Content += "<div style='height: 6px;'><!-- line space --></div>";
	Content += Answer;
	
	// update "Answer" div content
	document.getElementById("Answer").innerHTML = Content;
}
	
function displayProductDetail(productDetail)
{	
  //alert("previousProductDetail = " + previousProductDetail); // test***
	document.getElementById(previousProductDetail).style.display = 'none';
	document.getElementById(productDetail).style.display = 'block';
	previousProductDetail = productDetail;
}

function hideDiv(divID)
{ // display div initially so search engines can read content
  // hide from user
	document.getElementById(divID).style.display = 'none';
}
	
function highlightNavButton()
{  // highlight top and sub nav buttons that correspond to the page
	var thisPageName = window.location.toString().toLowerCase();
	var stringToMatch;
	var nav;

	for (var i = 0; i < navID.length; i++)
	{
		stringToMatch = thisPageName.indexOf(navID[i].toLowerCase());
		if(stringToMatch > 0)
		{ // nav button name found in url
			if(i < 4)
			{ // top nav button
				nav = "Top";
			}
			else
			{ // sub nav button
				nav = "Sub";
				
			}
			if (document.getElementById(navID[i] + "_Off")) {
    			document.getElementById(navID[i] + "_Off").src="/Images/Navigation/" + nav + "Nav/" + navID[i] + "_On.gif";				
    		}
		}
	}
}

function highlightNav()
{ 
	// loop through all "TopNav" links
	for(var i = 0; i < document.getElementsByTagName("a").length; i++)
	{
		// check if link id exists in URL only for links with ids
		if(document.getElementsByTagName("a").item(i).id.length > 0 && location.href.indexOf(document.getElementsByTagName("a").item(i).id) > -1)
		{
			// highlight link
			document.getElementsByTagName("a").item(i).style.color = "#063b55" /* dark blue */
		}
	}			
}

function highlightTab(divID)
{	// highlights tab and displays corresponding div
	// unhighlight previous Tab	
	var formattedLastTabName = previousDivId.split("Tab")[0];	
	document.getElementById(previousDivId).style.width = "81px"; // shorten width
	document.getElementById(previousDivId).style.backgroundImage = "url('/Images/Navigation/bg_tab.gif')";
	document.getElementById(formattedLastTabName).style.display = 'none'; //'none' ; // hide previous div
			
	// highlight Tab
	var formattedThisTabName = divID.split("Tab")[0];	
	document.getElementById(divID).style.width = "96px"; // widen width
	document.getElementById(divID).style.backgroundImage = "url('/Images/Navigation/bg_tab_On.gif')";
	document.getElementById(formattedThisTabName).style.display = 'block'; // display selected div	
		
	previousDivId = divID; // save previous highlight in a global variable
}

function navMouseOver(elementID){
	// skip mouse over function if user is on this page
	if(window.location.toString().toLowerCase().indexOf(elementID.toLowerCase()) < 0){ 
		document.getElementById(elementID + "_On" ).style.display = "inline";
		document.getElementById(elementID + "_Off").style.display = "none" ;	
	}
}
	
function navMouseOut(elementID)
{	
	 document.getElementById(elementID + "_Off").style.display = "inline";
	 document.getElementById(elementID + "_On" ).style.display = "none" ;	  
}

function playCommercial(commercialNumber)
{	
	document.getElementById("CommercialContainer").style.visibility = 'visible' ; // display 
	document.getElementById("CommercialContainer").innerHTML = "&nbsp;Loading Commercial " + commercialNumber + "...";
}

function replaceSpace(entry)
{
	var out = " "; // replace spaces
	var add = "_"; // with an underscore
	var temp = "" + entry; // temporary holder
	
	while (temp.indexOf(out) > -1)
	{	
		pos = temp.indexOf(out);
		temp = "" + (temp.substring(0, pos) + add + temp.substring((pos + out.length), temp.length));		
	}
	
	return temp;
}

/*
 * ========================================================
 * Form Related Functions - Sign Up, etc.
 * ========================================================
 */

function clearSubscribeField(theFormElement, defaultText){
	if (theFormElement.value == defaultText){
		theFormElement.value = "";
	}
}

function isValidEmail (emailStr){
	var emailPat=/^(.+)@(.+)$/
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	var validChars="\[^\\s" + specialChars + "\]"
	var quotedUser="(\"[^\"]*\")"	
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	var atom=validChars + '+'
	var word="(" + atom + "|" + quotedUser + ")"
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")	
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	var matchArray=emailStr.match(emailPat)

	if (matchArray==null)
	{
		alert("Email address seems incorrect (check @ and .'s)")
		return false
	}

	var user=matchArray[1]
	var domain=matchArray[2]

	if (user.match(userPat)==null)
	{
		alert("Your username (the part before the '@') doesn't seem to be valid.")
		return false
	}

	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null)
	{
		for (var i=1;i<=4;i++)
		{
			if (IPArray[i]>255)
			{
				alert("Destination IP address is invalid!")
				return false
			}
		}
		return true
	}

	var	domainArray=domain.match(domainPat)
	if (domainArray==null)
	{
		alert("The domain name doesn't seem to be valid.")
		return false
	}

	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3)
	{
		alert("The address must end in a three-letter domain, or two letter country.")
		return false
	}

	if (len<2)
	{
		alert("This address is missing a hostname.")
		return false
	}	

	return true;
}	

//  Subscribe/Unsubscribe validation
function resetSubscribeField(theFormElement, defaultText)
{
	// if there is nothing in the text area, reset default text
	if (theFormElement.value.length < 1 || theFormElement == "")
	{
		theFormElement.value = defaultText;
	}			
}
	
function validateSubscribe(theForm)
{
	// validate friends email
	if (theForm.subscribeEmail.value == "")
	{
		alert("Please enter your E-Mail address.");
		theForm.subscribeEmail.focus();
		return(false);
	}

	if (isValidEmail(theForm.subscribeEmail.value))
	{
	}
	else
	{	
		theForm.subscribeEmail.focus();
		return(false);
	}
	return(true);
}

function validateUnsubscribe(theForm){
	// validate friends email
	if (theForm.unsubscribeEmail.value == "")
	{
		alert("Please enter your E-Mail address.");
		theForm.unsubscribeEmail.focus();
		return(false);
	}

	if (isValidEmail(theForm.unsubscribeEmail.value)){
	}
	else
	{	
		theForm.unsubscribeEmail.focus();
		return(false);
	}
	return(true);
}

// 3 Days to Glow Microsite functions
function openFeedWindow(url) {
    //window.open("http://heidi.com","feed");
    window.open(url,"feed");
}

function openExternalWindow(winName) {
    switch(winName) {
        case "jergens":
            window.open("/default.asp", winName);
            break;
        case "contest":
            window.open("http://jergens.eprize.net/glow", winName);
            break;
        case "privacy":
            window.open("/Privacy_Policy/Privacy_Policy.asp", winName);
            break;
        case "contact":
            window.open("/event.asp?action=entry&EventCode=jergenscontact", winName);
            break;
        case "legal":
            window.open("/Legal/Legal.asp", winName);
            break;
        case "natglowexp":
            window.open("/our_collection/Product_Detail.asp?ProductID=26", winName);
            break;
        case "natglowtips":
            window.open("/Our_Collection/Product_Detail.asp?ProductID=26&Tab=GlowTips", winName);
            break;
        case "rules":
            window.open("http://jergens.eprize.net/glow/index.tbapp?page=rules","rules","menu=no,toolbar=no,width=450,height=400,scrollbars=1,resizable=0,directories=no,location=no,screenX=0,screenY=0,top=88,left=124");
            break;
    }
    
}

function goToPage(pg) {
    dcsMultiTrack('DCS.dcsuri',pg,'DCS.dcsqry','','WT.ti',pg); 
    firstTracker._trackPageview(pg);
    secondTracker._trackPageview(pg);
}


function getCopyrightYear(){
    var today = new Date();
    var year = today.getYear();
    if(year<1000) 
        year+=1900;
    return year;
}

function changeCurrentWindow(winName) {
    switch(winName) {
        case "guarantee":
            document.location="/event.asp?eventcode=jergens_glowguarantee&action=entry";
            break;
        case "healthy":
            document.location="/Our_Collection/Product_Detail.asp?ProductID=36";
            break;
        case "foaming":
            document.location="/Our_Collection/Product_Detail.asp?ProductID=37";
            break;
        case "revitalizing":
            document.location="/Our_Collection/Product_Detail.asp?ProductID=34";
            break;
        case "firming":
            document.location="/Our_Collection/Product_Detail.asp?ProductID=35";
            break;
        case "express":
            document.location="/Our_Collection/Product_Detail.asp?ProductID=33";
            break;
    }
}





var safari_3_1_mac_popup_block_msg = 'You are using Safari 3.1 and it has blocked our Pop-Up Window.\nTo view the Pop-Up Window:\n1) disable your Pop-Up blocker by going into the Safari menu in your browser\'s menu bar and unselecting the Block Pop-Up Windows option\n2) then click on the link again';

var safari_3_1_win_popup_block_msg = 'You are using Safari 3.1 and it has blocked our Pop-Up Window.\nTo view the Pop-Up Window:\n1) disable your Pop-Up blocker by going into the Edit menu in your browser\'s menu bar and unselecting the Block Pop-Up Windows option\n2) then click on the link again';

function popUpNormal(filename,width,height) {
	if (width != null && height != null && width > 1 && height > 1) {
		popup3=window.open(filename,"popup3","height="+height+",width="+width);
	} else {
		popup3=window.open(filename,"popup3");
	}
}



function popUpNormalReturnStatus(filename,width,height) {
	if (width != null && height != null && width > 1 && height > 1) {
		popup3=window.open(filename,"popup3","height="+height+",width="+width);
	} else {
		popup3=window.open(filename,"popup3");
	}
	if (!popup3) {
		if (checkIfSafari3_1()) {
			n = navigator;
			na = n.appVersion;
			if ( na.indexOf( 'Mac' ) != -1 ) {
				alert(safari_3_1_mac_popup_block_msg);
			} else {
				alert(safari_3_1_win_popup_block_msg);
			}
		}
		return false;
	}
	else return true;
}

