/*
 * Library for javacript used in the store header
 */


/****** Overlay login functions ********/
var liteLogonFeedback = null;

$(document).ready(function() {
	$('#loadLoginOverlay').overlay({expose: '#555555', closeSpeed: 1000, finish : {top:5},
		onBeforeLoad: function(){
			var loginOverlayContent = $('#overlayLoginContent');	
			var url = 'https://' + document.domain + '/webapp/wcs/stores/servlet/LiteLogonDisplay?storeId=10001&catalogId=10751&langId=-1&URL=LiteLogonDisplay&reLogonURL=LiteLogonDisplay';
			if (liteLogonFeedback) {
				url += '&getSatFeedback=' + liteLogonFeedback;
			}
			var content = '<iframe src="' + url + '" width="600" height="476" scrolling="no" frameborder="0" />';
			loginOverlayContent.html(content)
		},
		onBeforeClose: function(){
			var loginOverlayContent = $('#overlayLoginContent');
			var content = '';
	        loginOverlayContent.html(content);           
		}
	});
});

function showLoginOverlay(loginForFeedback) {
	if (loginForFeedback == null) {
		// no parameter setting so no GetSatisfaction overlay needed after login
		liteLogonFeedback = null;
	} else if (loginForFeedback == 'productQuestion') {
		// product question pass PQ in parameter string for iframe
		liteLogonFeedback = 'PQ';
	} else if (loginForFeedback == 'feedback') {
		// feedback pass FB in parameter string for iframe
		liteLogonFeedback = 'FB';
	}	
	$('#loadLoginOverlay').overlay().load();
}

function closeLoginOverlay() {
	$('#loadLoginOverlay').overlay().close();
}

var brandMenuDisplayed = false;
var keypressLetter = "A";
var pattern = /[A-Z]/i;
$(document).ready(function(){  
	$("#brandmenu ul.subnav").parent().append("<span></span>"); //Only shows drop down trigger when js is enabled (Adds empty span tag after ul.subnav*)  
	$("ul.brandnav li span").click(function() { //When trigger is clicked...  
		 //Following events are applied to the subnav itself (moving subnav up and down)  
		brandMenuDisplayed = true;
		$(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click  		
		$(this).parent().hover(function() {  
		}, function(){  
			$(this).parent().find("ul.subnav").slideUp('fast'); //When the mouse hovers out of the subnav, move it back up
			brandMenuDisplayed = false;  
		});  
	});  
	$(document).keypress(function(key) {
		if (brandMenuDisplayed) {
			var newKeyPressLetter = String.fromCharCode(key.which).toUpperCase();
			if (pattern.test(newKeyPressLetter)) {
				if (keypressLetter != newKeyPressLetter) {
					keypressLetter = newKeyPressLetter;	
				 	if ($("a[name="+keypressLetter+"]").offset().top != 0) {
						$("#brandmenu ul.brandnav li ul.subnav").animate({scrollTop: '+=' + (($("a[name="+keypressLetter+"]").offset().top - $('#brandmenu').offset().top) - 40) + 'px'},'fast');
					}
				}
			}
		}		
	});
});


/****** NavBar functions **********/
var busy = false;
function submitCategorySelection(selectCategoryForm){
	if (!busy) {
		busy = true;
	    if (selectCategoryForm.categoryId.options[selectCategoryForm.categoryId.selectedIndex].value != 0) {
			var optionSelectedString = selectCategoryForm.categoryId.options[selectCategoryForm.categoryId.selectedIndex].value;
			selectCategoryForm.categoryId.options[selectCategoryForm.categoryId.selectedIndex].value = optionSelectedString.substring(0,optionSelectedString.indexOf('&N='));
			selectCategoryForm.N.value=endecaSelectedString = optionSelectedString.substring((optionSelectedString.indexOf('&N=')+3),optionSelectedString.length);
	   	    selectCategoryForm.submit();
		}
	}
	return false;
}

function submitBrandSelection(selectBrandForm){
	if (!busy) {
		busy = true;
		if (selectBrandForm.N.options[selectBrandForm.N.selectedIndex].value != 0) {
	         selectBrandForm.submit();
		}
	}
	return false;
}

function parseSearchString(searchForm){
   	if (searchForm.Ntt.value == "Search by keyword or item") {
   		return false;
   	}
   	var temp = searchForm.Ntt.value;
	temp = temp.replace(/[%-&>]/g,'');
	temp = temp.replace(/</g,'');
   	temp = temp.replace(/ and /gi,' ');
   	temp = temp.replace(/ or /gi,' ');
	temp = temp.replace(/ drop /gi,' ');
	temp = temp.replace(/ select /gi,' ');
	temp = temp.replace(/ insert /gi,' ');
	temp = temp.replace(/ delete /gi,' ');
	temp = temp.replace(/ update /gi,' ');
	
	// The following is necessary as certain characters cannot be used within
	// a .js file within the replace method.
	var temptwo = "";
	var index = temp.indexOf(String.fromCharCode(233))
	if (index != -1) {
		temptwo = temp.substring(0,index) + "e" + temp.substring(index+1, temp.length);
		temp = temptwo;
	}
	index = temp.indexOf(String.fromCharCode(225))
	if (index != -1) {
		temptwo = temp.substring(0,index) + "a" + temp.substring(index+1, temp.length);
		temp = temptwo;
	}
	index = temp.indexOf(String.fromCharCode(237))
	if (index != -1) {
		temptwo = temp.substring(0,index) + "i" + temp.substring(index+1, temp.length);
		temp = temptwo;
	}
	index = temp.indexOf(String.fromCharCode(163))
	if (index != -1) {
		temptwo = temp.substring(0,index) + temp.substring(index+1, temp.length);
		temp = temptwo;
	}
   	searchForm.Ntt.value = temp;
   	searchForm.submit();
}


/*******  DropDownMenus functions *********/
var isIe = 0;

function startList() {
	if (navigator.userAgent.toLowerCase().indexOf("msie") != -1) {
		isIe = 1;
		if (document.all && document.getElementById) {
			var navRoot = document.getElementById("nav");
			if (navRoot != null) {			
				for (i=0; i<navRoot.childNodes.length; i++) {
					var node = navRoot.childNodes[i];
					if (node.nodeName=="LI") {
						node.onmouseover=function() {
							this.className+=" over";
						}
						node.onmouseout=function() {
							this.className=this.className.replace(" over", "");
						}
					}
				}
			}
			var navRoot = document.getElementById("essentialsnav");
			if (navRoot != null) {
				for (j=0; j<navRoot.childNodes.length; j++) {
					var node = navRoot.childNodes[j];
					if (node.nodeName=="LI") {
						node.onmouseover=function() {
							this.className+=" sfhover";
						}
						node.onmouseout=function() {
							this.className=this.className.replace(" sfhover", "");
						}
					}
				}
			}
		}
	}
}

window.onload = function(e) {
  startList();
}

function highlight(element) {
	if (isIe > 0) {
		element.style.background = "#DFA4C2";
	}
}

function unhighlight(element) {
	if (isIe > 0) {
		element.style.background = "#FFFFFF";
	}
}

// variable to ensure each request is only made once
var busy = false;

// this is a boiler plate method for creating the XMLHttpRequest (cross browser)
function newXMLHttpRequest() {
	var xmlreq = false;
	if (window.XMLHttpRequest) {
		xmlreq = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		try {
			xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
			}
		}
	}
	return xmlreq;
}


// function for submitting the request and receiving the response
function doCompletion() {
	if (busy == false) {
		var searchString = document.autoCompleteSearchForm.Ntt.value;
		if (searchString.length < 3) {
			hideSearchOptionsBox();
		}
		// if ((searchString.charAt(searchString.length-1) == ' ' && searchString.length > 3) || searchString.length == 6) {
		if (searchString.length > 3) {
			busy = true;
			var url = "SearchBoxAutoPopulateCmd?action=complete&Ntt=" + escape(searchString);
			var req = newXMLHttpRequest();
			req.onreadystatechange = function() {
				if (req.readyState == 4) {
					if (req.status == 200) {
						parseMessages(req.responseXML);
					} else if (req.status == 204){
						hideSearchOptionsBox();
					}
				}
			};
			req.open("GET", url, true);
			req.send(null);
		}
	}
}


/********* SearchBoxAutoPopulate functions ***********/

// function for handling the response XML and displaying to the screen
function parseMessages(responseXML) {
	var displaypictures = true;
	var searchTermDisplay = "";
	var seeAllResults = "";
	var hideSuggestions = "";
	document.getElementById('searchOptionsBox').innerHTML = "";
	var products = responseXML.getElementsByTagName("products")[0];
	if (products != null) {
		if (products.childNodes.length > 0) {
			searchTermDisplay = "<div class=\"searchTermDisplay\"><p>Quick search results for <span class=\"strong\">'" + document.forms.autoCompleteSearchForm.Ntt.value + "'</strong></p></div>";
			hideSuggestions = "<div class=\"hideSuggestions\"><a href=\"javascript:hideSearchOptionsBox()\">Hide suggestions</a></div>";
			if (products.childNodes.length > 9 ) {
				seeAllResults = "<div class=\"seeAllResults\"><a href=\"javascript:setSearchTerm()\">See all search results</a></div>";
			}	
			document.getElementById('searchOptionsBox').innerHTML = "<div class=\"searchSuggestionsHeader\">" + searchTermDisplay + "<div style=\"clear:both;\"></div><div class=\"seeAllResults\">" + seeAllResults + "</div><div class=\"hideSuggestions\">" + hideSuggestions + "</div><div style=\"clear:both;\"></div>";
		}
		for (loop = 0; loop < products.childNodes.length; loop++) {
			var product = products.childNodes[loop];
			var productName = product.getElementsByTagName("productName")[0];
			var productImage = product.getElementsByTagName("productImage")[0];
			var productId = product.getElementsByTagName("productId")[0];
			var productUrl = product.getElementsByTagName("productUrl")[0];			
			if (displaypictures) {
				var productImageURLLink = "";
				if (productImage.childNodes[0].nodeValue != null && productImage.childNodes[0].nodeValue != "null") {
					productImageURLLink = "<a href=\""+ productUrl.childNodes[0].nodeValue + "?cm_sp=search-_-search_suggestion-_-product_suggestion\"><img src=\"" + document.forms.autoCompleteSearchForm.imageDomain.value + "" + productImage.childNodes[0].nodeValue + "\" /></a>";
				}
				var productNameLink = "<a href=\""+ productUrl.childNodes[0].nodeValue + "?cm_sp=search-_-search_suggestion-_-product_suggestion" + "\" onmouseover=\"highlightSearchElement(this)\" onmouseout=\"unhighlightSearchElement(this)\">" + productName.childNodes[0].nodeValue + "</a>";
				document.getElementById('searchOptionsBox').innerHTML = document.getElementById('searchOptionsBox').innerHTML + "<div class=\"searchSuggestionImage\">" + productImageURLLink + "</div><div class=\"searchSuggestionName\">" + productNameLink + "</div><div class=\"searchSuggestionBreak\"></div>";			
			} else {
				var productUrl = product.getElementsByTagName("productUrl")[0];
				document.getElementById('searchOptionsBox').innerHTML = document.getElementById('searchOptionsBox').innerHTML + "<div class=\"searchSuggestionNameOnly\"><a href=\""+ productUrl.childNodes[0].nodeValue + "?cm_sp=search-_-search_suggestion-_-product_suggestion" + "\" onmouseover=\"highlightSearchElement(this)\" onmouseout=\"unhighlightSearchElement(this)\">" + productName.childNodes[0].nodeValue + "</a></div>";			
			}
		}

		if (products.childNodes.length > 0) {
			document.getElementById('searchOptionsBox').innerHTML = document.getElementById('searchOptionsBox').innerHTML + "<div class=\"searchSuggestionsHeader\"><div class=\"seeAllResults\">" + seeAllResults + "</div><div class=\"hideSuggestions\">" + hideSuggestions + "</div><div style=\"clear:both;\"></div></div>";	
        	document.getElementById('searchOptionsBox').style.display = "block";
		} else {
			hideSearchOptionsBox();
		}
	}
	busy = false;
}


// Set the selected search term into search box and submit
function setSearchTerm() {
	// document.autoCompleteSearchForm.Ntt.value = productName;
	hideSearchOptionsBox();
	document.autoCompleteSearchForm.submit();
}


// hide the product name options display box
function hideSearchOptionsBox() {
	document.getElementById('searchOptionsBox').style.display = "none";
}

function clearSearch() {
	if (document.forms.autoCompleteSearchForm.Ntt.value == 'Search by keyword or item') {
		document.forms.autoCompleteSearchForm.Ntt.value='';
		hideSearchOptionsBox();
	}
}
	
function highlightSearchElement(element) {
	//if (isIe > 0) {
	//	element.style.background = "#EEEEEE";
	//}
}

function unhighlightSearchElement(element) {
	//if (isIe > 0) {
	//	element.style.background = "#FFFFFF";
	//}
}


/*********** TrackOrder functions **************/
function trackorderpopup(popcontentname, stylesheet, message1, message2) {
	popup = window.open('','','height=300,width=300,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,directories=no,status=no');
	popup.document.writeln('<html><head><title>'+popcontentname+'</title>');
	popup.document.writeln('<link rel="stylesheet" href="'+stylesheet+'" type="text/css"/></head><body>');
	popup.document.writeln('<div id="track_order_popup"><h2>'+popcontentname+'</h2>');
	popup.document.writeln('<p>'+message1+'</p>');
	popup.document.writeln('<p>'+message2+'</p>');
	popup.document.writeln('<form name="input" action="//www.interlinkexpress.com/service/tracking" target="_new" method="post">');
	popup.document.writeln('<input type="hidden" name="account" value="1423158" />');
	popup.document.writeln('<input type="text" name="orderNumber" value="Order Number" onFocus="document.forms.input.orderNumber.value=\'\'" size="20" />');
	popup.document.writeln('<input type="submit" value="Submit" />');
	popup.document.writeln('</form><br/>');
	popup.document.writeln('<div align="center"><a href="#" onClick="window.close()">Close</a></div>');
	popup.document.writeln('</div></body></html>');
	popup.document.close();
}


/************ CookieCheck functions ***********/
function _cookiesAreEnabled() {
  CreateCookie( "test", "cookie" );
  if ( ObtainCookie( "test" ) ) {
    RemoveCookie( "test" );
    return true;
  } else {
    return false;
  }
}
navigator.cookiesAreEnabled = _cookiesAreEnabled;

function ObtainCookie( name ) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while ( i < clen ) {
    var j = i + alen;
    if ( document.cookie.substring(i, j) == arg ) return getCookieVal(j);
    i = document.cookie.indexOf( " ", i ) + 1;
    if ( i == 0 ) break;
  }
  return null;
}

function RemoveCookie( name, path, domain ) {
  if ( ObtainCookie( name ) ) {
    document.cookie = name + "=" +
    ( ( path ) ? "; path=" + path : "" ) +
    ( ( domain ) ? "; domain=" + domain : "" ) +
    "; expires=Thu, 01-Jan-50 00:00:01 GMT";
  }
}

function CreateCookie( name, value, expires, path, domain, secure ) {
  document.cookie = name + "=" + escape (value) +
  ( ( expires ) ? "; expires=" + expires.toGMTString() : "" ) +
  ( ( path ) ? "; path=" + path : "" ) +
  ( ( domain ) ? "; domain=" + domain : "" ) +
  ( ( secure ) ? "; secure" : "" );
}

function getCookieVal( offset ) {
  var endstr = document.cookie.indexOf ( ";", offset );
  if ( endstr == -1 ) endstr = document.cookie.length;
  return unescape( document.cookie.substring( offset, endstr ) );
}

if ( !navigator.cookiesAreEnabled() ) {
  document.write('<div style="text-align:center; width:100%; background:#FAE5E5; padding:4px 0 4px 0;"><p style="margin:0 0 0 -10px; color:#F00; font-weight:bold; text-align:center !important">Kiddicare.com requires cookies to be enabled on your browser - please enable your cookies</p></div>');
}



/************ Affiliate Cookie functions ***********/
function setAffiliateCookie(cookie_name, cookie_value, cookie_expire_time, cookie_path) {
  var cookie_expire_date = new Date();
  cookie_expire_date.setTime(cookie_expire_date.getTime() + (cookie_expire_time*24*60*60*1000));
  var cookie_expire_string = cookie_expire_date.toGMTString();
  var cookie_string = cookie_name + "=" + cookie_value + "; expires=" + cookie_expire_string + "; path=" + cookie_path;
  document.cookie = cookie_string;
}

// the trade doubler cookie is set through the trade doubler redirect page
// via the affiliate helper java file
function isAffiliateReferal() {
	if(document.URL.indexOf("source=") > -1) {
		if(document.URL.indexOf("source=shopzilla") > -1){
			setAffiliateCookie("AFFCOOK", "SHOPZILLA", 1, "/");
		}
		if(document.URL.indexOf("source=aw") > -1) {
			setAffiliateCookie("AFFCOOK", "AFFWIN", 30, "/");
		}
		if(document.URL.indexOf("source=buyat") > -1) {	
			setAffiliateCookie("AFFCOOK", "BUYAT", 30, "/");
		}
	} else if(document.URL.indexOf("rw.cm=") > -1) {
		if(document.URL.indexOf("PPC") > -1 
			|| document.URL.indexOf("ppc") > -1
			|| document.URL.indexOf("CSE") > -1
			|| document.URL.indexOf("cse") > -1) {	
			setAffiliateCookie("AFFCOOK", "PPC", 30, "/");
		}
	}
}

isAffiliateReferal();



/************ Single Sign On Cookie functions ***********/
var SINGLE_SIGN_ON_COOKIE_NAME = "SSOCOOK";

// function to write a single sign-on client to the single sign-on cookie
function writeToSingleSignOnCookie(clientName) {
	var singleSignOnCookieValue = obtainSingleSignOnCookieValue(SINGLE_SIGN_ON_COOKIE_NAME);
	if (singleSignOnCookieValue != null) {
		if (singleSignOnCookieValue.indexOf(clientName) == -1) {
			singleSignOnCookieValue = singleSignOnCookieValue + "," + clientName;
			createSingleSignOnCookie(SINGLE_SIGN_ON_COOKIE_NAME, singleSignOnCookieValue);	
		} else {
			return false;
		}
	} else {
		createSingleSignOnCookie(SINGLE_SIGN_ON_COOKIE_NAME, clientName);	
	}
}

// function to read the single sign-on cookie
function obtainSingleSignOnCookieValue(cookieName) {
	var searchName = cookieName + "=";
	var cookies = document.cookie.split(';');
	for(var i=0; i<cookies.length; i++) {
		var cookie = cookies[i];
		while (cookie.charAt(0)==' ') {
			cookie = cookie.substring(1,cookie.length);
			if (cookie.indexOf(searchName) == 0) { 
				return cookie.substring(searchName.length,cookie.length);
			}
		}
	}
	return null;
}

function doesSingleSignOnCookieContain(searchName) {
	var singleSignOnCookieValue = obtainSingleSignOnCookieValue('SSOCOOK');
	if (singleSignOnCookieValue != null && singleSignOnCookieValue.indexOf(searchName) > -1) {
		return true;	
	} else {
		return false;
	}
}

// function to delete the single sign-on cookie
function deleteSingleSignOnCookie() {
	document.cookie = escape(SINGLE_SIGN_ON_COOKIE_NAME) + "=" + SINGLE_SIGN_ON_COOKIE_NAME + "; path=/" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
}

// function to create cookie
function createSingleSignOnCookie(cookieName, cookieValue, expires) {
	document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; path=/";
}

//functions to insert dynamic promotions
function outputResult(xml){		
	$.each($("div.dynamic_promotion"), function(i, data) {
		var zoneName = $(data).attr('rel');		
		$(xml).find('products').each(function(){
			$(xml).find("productGroup[name='" + zoneName + "']").each(function(){							
				$(this).find('product').each(function(){
					var id = $(this).find('productID').text();
					var temp1 = $(this).find('SpecialPrice').text();
					var temp2 = $(this).find('Price').text();
					temp1 = temp1.replace(/[^.0-9]/g,'');
					temp2 = temp2.replace(/[^.0-9]/g,'');
					
					var desc = $(this).find('Title').text();					
					if (desc.length > 55) {  
						desc =  desc.slice(0, 55) + "..."; 
					} 
					calc = 100 - (Math.round(temp1 / temp2 * 100)); 
					var displayDisc = "<div class=\"product_discount\"><p>" + calc + "%<br>OFF</P></div>";							
					if (calc  < 10) {	
						displayDisc="";
					}							
					var tempstr = "";
					var calc = "";
					var tempstrStart = "<div class=\"product_box\"><div class=\"product_box_inner\">";
					var tempstrEnd = "</div></div>";
					var imgStr ="<a href=\"" + $(this).find('Url').text() +  "\"><div class=\"product_Img\" style=\"background:  url('" + $(this).find('MediumImage').text() + "') no-repeat top center \">" + displayDisc + "</div></a>";
					var prodName ="<div class=\"product_desc\"><a href=\""  + $(this).find('Url').text() +  "\">" + desc +  "</a></div>";
					var price ="<div class=\"product_price\">" + $(this).find('SpecialPrice').text() +  "</div>";
					var rrp ="<div class=\"product_RRP\">RRP: " + $(this).find('Price').text() +  "</div>";
					$(data).append(tempstrStart + imgStr +  prodName + price + rrp +  tempstrEnd);							
				});						
			});
		});
	});	
}

$(document).ready(function() {
	if ($("div.dynamic_promotion").length >0){			
		$.ajax({
			url: "http://" + document.domain + "/webapp/wcs/stores/servlet/EndecaPromotionLookupPage?storeId=10001&catalogId=10751&N=0&Ntk=primary&Ntt=&endecaZone=ListerPageFlashSliderZone",
			dataType:"xml",
			success: function(resp){
		 	xml = resp;
			outputResult(xml);
			}
		});
	}
});


