/*********************************************************************
(c) Copyright Comet Plc 2009. All rights reserved.
	Last updated: 2009/07/21 - Stewart Orr	
	THIS FILE SHOULD ONLY CONTAIN JAVASCRIPT THAT IS USED ACROSS
	THE ENTIRE SITE.
----------------------------------------------------------------------
	comet.js - Used across the entire new comet design
*********************************************************************/

/*********************************************************************
	General functions - PLEASE REUSE THESE AS MUCH AS POSSIBLE
*********************************************************************/

/* simple function to get elements */
function $(id) {
	return document.getElementById(id);	
}
function gID(id) {
	return document.getElementById(id);	
}

/*	clever function to add multiple "window.onloads" */
function addLoadEvent(func) {

if(window.addEventListener && !window.opera) { 
// Firefox 1.5+, Gecko/Mozilla 1.0.1+, Konqueror, Safari 3.0
window.addEventListener('load', func, false)
}
else if(window.attachEvent) {
// Microsoft IE 5+, Opera 8.0+
window.attachEvent('onload', func)
}

else{
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
	}
	
}

/*********************************************************************
	Other functionality
*********************************************************************/
function prepareSearchBar() {
	if (gID("searchTerm")) {
		var searchTerm = gID("searchTerm");
		searchTerm.form.action = cometHost + "/shopcomet/search.do";
		searchTerm.onfocus = function() {
			if (this.value == "e.g. Plasma TV") {
				this.value = "";
			}
		}
		searchTerm.onblur = function() {
			if (this.value == "") {
				this.value = "e.g. Plasma TV";
			}
		}
	}
}

// set up the host name to redirect to secure
var host = window.location.host;
var secureHost = "";
var cometHost = "";

/* 	detect secure host for testing:
	Links are hard-coded for live to ensure they do not need javascript	*/
switch (host) {
	case "ev2origin.ekingfisher.com":
		secureHost = "https://ev2secure.ekingfisher.com";
		break;
	case "test.comet.co.uk":
		secureHost = "https://ev2secure.ekingfisher.com";
		break;	
	case "www.comet.co.uk":
		secureHost = "https://secure.comet.co.uk";
		break;
	case "mobile.comet.co.uk":
		secureHost = "https://secure.comet.co.uk";
		break;		
	default:
		secureHost= "https://" + host;
}

/* 	detect secure host for testing:
	Links are hard-coded for live to ensure they do not need javascript	*/
switch (host) {
	case "secure.comet.co.uk":
		cometHost = "http://www.comet.co.uk";
		break;
	case "ev2secure.ekingfisher.com":
		cometHost = "http://ev2origin.ekingfisher.com";
		break;	
	default:
		cometHost= "http://" + host;
}

/* multimap tests: checks if we are viewing multimap page */
if (host == "preview.multimap.com" || host == "classic.multimap.com") {
	secureHost= "https://secure.comet.co.uk";
	cometHost = "http://www.comet.co.uk";
}

/*--------------------------------------------------------------------*/
/*	Add rollover to images and inputs that have a class of "button".
	This simply adds some javascript to swap the image filenames.
	An example of this is the "addtobasket" buttons */
function roll(o) {
	var srcRegEx = /_on.[gif|png]/gi;
	if(srcRegEx.test(o.src)) {
		o.src = o.src.replace("_on.","_off.");
	} else {
		o.src = o.src.replace("_off.", "_on.");
	}  
}
/*	function used to create rollover effect for buttons 
	(imgs & inputs with class="button") created by stewart orr 08/05/2007 */
function addRollOverToBtns() {
	var searchRegEx = /[button]/gi;
	var imgs = document.getElementsByTagName("img");
	for (var i = 0; i < imgs.length; i++) {
		if (searchRegEx.test(imgs[i].className)) {
			imgs[i].onmouseover = function() { roll(this); }
			imgs[i].onmouseout = function() { roll(this); }
		}
	}
	var inputs = document.getElementsByTagName("input");
	for(var j = 0; j < inputs.length; j++) {
		if(/button/.test(inputs[j].className)) {
			inputs[j].onmouseover = function() { roll(this); }
			inputs[j].onmouseout = function() { roll(this); }
		}
	}
}

/*--------------------------------------------------------------------*/
/*	Function to check if string is in email format.
	s.orr: Reduced version as previous one was stupidly long */
function isValidEmailAddress(str) {
	var emailRegEx = /^([\w\-\.]+)@((\[([0-9]{1,3}\.){3}[0-9]{1,3}\])|(([\w\-]+\.)+)([a-zA-Z]{2,4}))$/;
	return emailRegEx.test(str);
}

/*--------------------------------------------------------------------*/
/*	Cookie functions  
	use as follows:
		setCookie("name", "value", "optional_var", optional_var);
		var	myCookie = getCookie("name_of_cookie");
*/
function setCookie(name, value, expires, path, domain, secure) {
	//alert("name: " + name + " value: " + value);
	document.cookie= name + "=" + escape(value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
}
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);

    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }

    var end = document.cookie.indexOf(";", begin);

    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/*--------------------------------------------------------------------*/
/* static window references: these are used to define window size and features */
var CIC_WIN = {name:"cic_win",features:"scrollbars=1,resizable=1,width=600,height=300,left="+(screen.width-600)/2+",top="+(screen.height-300)/2};
var CIC_WIN_L = {name:"cic_winbig",features:"scrollbars=1,resizable=1,width=800,height=500,left="+(screen.width-500)/2+",top="+(screen.height-420)/2};
/* Changes done by Cognizant: 10075 - Image pop up banner - Start */
//Modified the width of the window launched from product page
//var WIN = {name:"comet_win",features:"scrollbars=1,width=550,height=580,left="+(screen.width-550)/2+",top="+(screen.height-580)/2};
var WIN = {name:"comet_win",features:"scrollbars=1,width=768,height=580,left="+(screen.width-768)/2+",top="+(screen.height-580)/2};
var WIN_PACK = {name:"comet_win_pack",features:"scrollbars=1,width=550,height=580,left="+(screen.width-550)/2+",top="+(screen.height-580)/2};
/* Changes done by Cognizant: 10075 - Image pop up banner - End */
var WIN_S = {name:"comet_win_small",features:"scrollbars=1,width=580,height=250,left="+(screen.width-580)/2+",top="+(screen.height-250)/2};
var WIN_M = {name:"winmedium",features:"scrollbars=1,width=550,height=400,left="+(screen.width-550)/2+",top="+(screen.height-400)/2};
var WIN_M_RESIZE = {name:"winmedium",features:"scrollbars=1,resizable=1,width=600,height=500,left="+(screen.width-600)/2+",top="+(screen.height-500)/2};
var MYC_HELP = {name:"comet_mychelp",features:"scrollbars=1,resizable=1,width=570,height=580,left="+(screen.width-570)/2+",top="+(screen.height-580)/2};
var MYCOMET_FORGOTTEN_PASSWORD_WIN = {name:"comet_win",features:"width=550,height=280,left="+(screen.width-550)/2+",top="+(screen.height-280)/2};
var CC_POP_RESIZE = {name:"winmedium",features:"scrollbars=1,resizable=1,width=796,height=551,left="+(screen.width-796)/2+",top="+(screen.height-551)/2};

/* Function to open window */
function win(url,windowType){	
	newwin = window.open(url,windowType.name,windowType.features);
	newwin.focus();
	return false;
}

/*--------------------------------------------------------------------*/
/* Change the top links in case we are using testing env */
function prepareTopLinks() {
	try {
		if (gID('linkmycomet') && gID('linkmybasket')) {
			var linkmycomet = gID('linkmycomet');
			var linkmybasket = gID('linkmybasket');
			var cometTracking = gID('cometTracking');
			
			var loginCookie = unescape(getCookie("userLoggedIn"));
			if (loginCookie != "nocookie") {
				linkmycomet.title = "My Comet: logged in";
				// If we need a logout:
				// xxx.href = secureHost + '/webapp/wcs/stores/servlet/MyCometLogout'; 
			}
			linkmycomet.href = secureHost + "/webapp/wcs/stores/servlet/MyCometLoginView?storeId=10001"; 
			linkmybasket.href = secureHost + "/webapp/wcs/stores/servlet/CometOrderItemDisplay?langId=-1&storeId=10001&catalogId=10001&orderId=.";
			if (cometTracking) {
				cometTracking.childNodes[0].href = secureHost + "/webapp/wcs/stores/servlet/GeneralOrderTrackingDataEntryView?storeId=10001&langId=-1&calalogId=10001";
			}
		}
	} 
	catch(e) { }
}

/*--------------------------------------------------------------------*/
/* Process MultiBuy items */
function addToMultibuy() {
	var url = window.location.href;
	var urlsplit = url.split("product");
	var items = urlsplit[1].split("/");
	var sku = items[1];
	url = secureHost + '/webapp/wcs/stores/servlet/AddToWishList?storeId=10001&listtype=multibuy&sku=' + sku;
	window.location = url;
}

/*********************************************************************
	Legacy functions
	These have been left in as I don't know if they are being used
	elsewhere or not.
*********************************************************************/

// Remove 'http://www.comet.co.uk' from front of url
// Need to remove this for running locally - full domain needs to be in the href in case they have js switched off
// (Used in checkout)
function removeDomain(url,windowType){
	var returnUrl = url;
	if (url.indexOf("http://www.comet.co.uk") >= 0) {
		returnUrl = url.substr(22);
	}
	return returnUrl;
}

// Open a window containing a page from the non-secure (browse) part of the site
// (Used in checkout)
function winNonSec(url,windowType){
	url = removeDomain(url);
	return win(cometHost + url, windowType);
}


function forgottenPwd(windowType){
	url = "/webapp/wcs/stores/servlet/MyCometForgottenPasswordView";
	return win(secureHost + url, windowType);
}

// Forward to another page on the non-secure (browse) part of the site
// (Used in checkout)
function forwardNonSec(url){
	url = removeDomain(url);
	top.location.replace(cometHost + url);
	return false;
}

function forwardCICNonSec(url, orderId){
	url = removeDomain(url);
	top.location.replace(cometHost + url+"?orderId="+orderId+"&orgOrderId="+orderId);
	return false;
}

function clearDefaultText(defaultText, el) {
	if(el.value == defaultText) {
		el.value = "";
	}
}

// (Used in checkout - copied from checkout.js)
function getRadioValue(radio) {
	if (radio.length == null) {
	    if(radio.checked == true)
		return true;
	    else
		return false;
	}
	for (index=0; index<radio.length; index++) {
	   if (radio[index].checked == true) {
		return true;

	   }
	}
	return false;
}
// (Used by checkout)
function getRadioName(radio) {
	var vName = 'noConnection';
	for (index=0; index<radio.length; index++) {
	   if (radio[index].checked == true) {
		vName = radio[index].value ;

	   }
	}
	return vName;
}



// Return true if in web mode - whether we should display web price etc.
//
// Note:
// We can not tell the difference between web users and internal users acting as web users, because
// the 'usertype' cookie also gets set to 'N' for external users when they click 'make further selections' on 
// the basket page. If this was fixed, we could check for usertype = 'null', meaning that they are an external web user.
//
// Author: Chris Cook 4/7/05
// (Used in checkout)
function isWebMode() {
	var webMode = true;
	var cookieprice = getCookie("mainprice");
	if (cookieprice != null && cookieprice == "National") {
		// CIC / store user or manager who wants to see 'national' price
		webMode = false;
	}
	return webMode;
}

// Return true if this is a store user.
// Author: Chris Cook 4/7/05
// (Used in checkout)
function isStoreMode() {
	var usertype = getCookie("usertype");
	if (usertype == "ST") {
		return true;
	} else {
		return false;
	}
}

// Return true if this is an internal (CIC) sales user.
// Author: Chris Cook 4/7/05
// (Used in checkout)
function isSalesMode() {
	var usertype = getCookie("usertype");
	if (usertype == "S") {
		return true;
	} else {
		return false;
	}
}

function changeDiv(headerID_off, headerID_on) {
	var elemOff = document.getElementById(headerID_off);
	if (elemOff != null) {
		elemOff.style.visibility= 'hidden'
		elemOff.style.display= 'none'
	}
	var elemOn = document.getElementById(headerID_on);
	if (elemOn != null) {
		elemOn.style.visibility = "visible";
		elemOn.style.display= 'block'
	}
}

// Set up the host name to redirect to secure
function getSecureHost() {
	return secureHost;
}
// Function for forwarding out of the secure area of the site
function getNonSecureHost() {
	return cometHost;
}
// This function adds a single item to the wish list
function AddToWishList(sku) {
	location.href = secureHost + '/webapp/wcs/stores/servlet/AddToWishList?storeId=10001&sku=' + sku;
}
//added for mycomet links dynamic population
function onLoadCallWithRecentlyViewedProductsBox(id) {
	drawRecentlyViewedProductsBox(id);
}
function onLoadCallWithProductPackagePageInit() {
	productPackagePageInit();
}
function onLoadCallWithSetupAddToBasket() {
	setupAddToBasket();
}
function onLoadCallWithAdvancedSearchInit (){
	advancedSearchInit();
}
function onLoadCallFunction (){
	//drawMyCometLoginLink();	
}
// Reevoo link
function openReevoo(id) {
	url = "http://www.revieworld.com/affiliate/reviews/CMT?id=" + id;
	window.open(url,"reevoo","scrollbars=yes,menubar=no,location=no,resizeable=no,status=no,toolbar=no,dependent=yes,width=424,height=645,left=100,top=100"); 
}
function openWindowForWebStudio(url) {
	window.open(url, 'winmedium','width=600,height=500,scrollbars=1,resizable=1');
}
// This function is for the giftfinder box which is used by content.
function submitGiftFinder() {
	giftFinderURL = '/shopcomet/giftFinder.do?&n=601';
	if (document.giftfinder.agegroup.value && document.giftfinder.agegroup.value != "nopreference") {
		giftFinderURL =  giftFinderURL + "\+" + document.giftfinder.agegroup.value;
	}
	if (document.giftfinder.budget.value && document.giftfinder.budget.value != "nopreference") {
		giftFinderURL =  giftFinderURL + "\+" + document.giftfinder.budget.value;
	}
	if (document.giftfinder.who.value && document.giftfinder.who.value != "nopreference") {
		giftFinderURL =  giftFinderURL + "\+" + document.giftfinder.who.value;
	}
	if (document.giftfinder.budgetamount.value && document.giftfinder.budgetamount.value != "nopreference") {
		giftFinderURL =  giftFinderURL + "\+" + document.giftfinder.budgetamount.value;
	}
	//alert(giftFinderURL);
	location.href = cometHost + giftFinderURL;
}
function sendEmail(inForm)	{
	if (!isValidEmailAddress(inForm.recipientEmail.value)) {
		alert('Error:\n\nYou have not entered a valid email address.');
	} else if (!isValidEmailAddress(inForm.senderEmail.value)) {
		alert('Error:\n\nYour own email address is not valid.');
	} else {
		inForm.submit();
	}
}
/*	Display/hide elements by swapping classes */
function switchOff(headerID) {
	gID(headerID).className = "off"; 
}
function switchOn(headerID) { 
	gID(headerID).className = "on"; 
}


/*********************************************************************
	CIC functions
	These are used by the CIC and must be included
*********************************************************************/
// This function allows the CIC to start a new customer
function NewCustomer() {
	location.href = secureHost + "/webapp/wcs/stores/servlet/TeleSalesSearchOptonView";
}
// This function allows the CIC to log out
function LogOut() {
	location.href = secureHost + "/webapp/wcs/stores/servlet/Logoff?page=logoff&URL=/webapp/wcs/stores/servlet/CometCICMenu";
}
/* search form */
function validateSearchFormMobile(frm) {
	var searchTerm = document.getElementById("searchTerm")
	//alert('ttt'+searchTerm.value)
	//alert('tttt '+searchTerm.value.trim)
	if (searchTerm.value.trim() == "" || searchTerm.value == "e.g. Plasma TV") {
		alert("Error:\n\nPlease enter a keyword or product code before pressing search.");
		return false;
	}
	return true;
}

/*********************************************************************
	Form validation functions
*********************************************************************/

/* search form */
function validateSearchForm(frm) {

	var searchTerm = document.getElementById("searchTerm")

	if (searchTerm.value == "" || searchTerm.value == "e.g. Plasma TV") {
		alert("Error:\n\nPlease enter a keyword or product code before pressing search.");
		return false;
	}
	return true;
}

/*********************************************************************
	On page load actions
*********************************************************************/

/**
 * Function that can be used to stop the Enter key from submitting
 * a form when pressed in a text field, happens on IE mainly. Add
 * the following to each text field in form:
 * 		onkeypress="return noenter();" 
 */
function noenter() {
var key;

         if(window.event)
              key = window.event.keyCode;     //IE

         else
              key = e.which;     //firefox
 if (key == 13)
        {
            //Get the button the user wants to have clicked

            var btn = document.getElementById("go");
            if (btn != null)
            { //If we find the button click it

                btn.click();
                event.keyCode = 0
            }
        }
 return !(window.event && window.event.keyCode == 13);
 
}


addLoadEvent(prepareSearchBar);
addLoadEvent(prepareTopLinks);
addLoadEvent(addRollOverToBtns);
