/**
* @fileoverview ebiz.js: A module used for client specific functionality
*
* This module defines a single symbol named "Venda.Ebiz"
* all ebiz utility functions are stored as properties of this namespace
* functions that are spacific this site shoudl be added to this file only.
*/

//Declare namespace for ebiz
Venda.namespace("Ebiz");
/**
* Gets the value of a specified URL parameter
* @param {string} waitDiv this is the id of the element which contains the loading message html.
* @param {string} widthVal is the width of the loading message eg. 240px.
* @param {boolean} modalVal if true a lightbox effect will occur
* @author Oliver Secluna <osecluna@venda.com>
*/

Venda.Ebiz.loadingPanel = function(waitDiv,widthVal,modalVal){
	var waitMsg=document.getElementById(waitDiv).innerHTML;
	    if (!Venda.Ebiz.wait) {
	        Venda.Ebiz.wait = 
	                new YAHOO.widget.Panel("wait",  
	                                                { width: widthVal, 
	                                                  fixedcenter: true, 
	                                                  close: true, 
	                                                  draggable: false, 
	                                                  zindex:4,
	                                                  modal: modalVal,
	                                                  visible: false
	                                                } 
	                                            ); 
	        Venda.Ebiz.wait.setBody(waitMsg);
	        Venda.Ebiz.wait.render(document.body);
	
	    } 
	    // Show the Panel
	    Venda.Ebiz.wait.show();

}



 /**
 * Split a string so it can be displayed on multiple lines so it does not break display layout - used on order confirmation and order receipt page
 * @param {string} strToSplit string that needs to be split 
 * @param {Integer} rowLen length of row which will hold the string
 * @param {string} displayElem the html container which will display the splitted string
 */
 

Venda.Ebiz.splitString = function(strToSplit, rowLen, dispElem) {
	var stringlist = new Array();
	while (strToSplit.length > rowLen) {
	   stringlist.push( strToSplit.slice(0,rowLen));
	   strToSplit=strToSplit.substr(rowLen);
	}
	if (strToSplit.length) {
		stringlist.push(strToSplit);
	}
	document.getElementById(dispElem).innerHTML = stringlist.join('<br>');
};

 /**
 * Change region
 * @param {string} domain from venda_serveradd more reliable
 * @param {string} gotoRegion URL for region
 * @param {string} logValue based on ustype to decide whether to add &log=4 to end of URL
 * @param {integar} basketTotal for total items in basket, to warn users basket will be emptied
 */
Venda.Ebiz.allowEmpty = function(domain,gotoRegion,logValue,basketTotal) {
	var sURL = unescape(location.href);
	var msg = "This action will change your currency and default region. \nClick OK to continue or Cancel to retain the current currency and region.";
/* // comment out to force user redirect to homepage always
	if(sURL.indexOf("/uk/") > -1) { // This method returns -1 if the string value to search for never occurs
		sURL = sURL.replace(/\/uk\//, "/"+gotoRegion+"/");
	}
	else if(sURL.indexOf("/us/") > -1) {
		sURL = sURL.replace(/\/us\//, "/"+gotoRegion+"/");
	}
	else if(sURL.indexOf("/restofworld/") > -1) {
		sURL = sURL.replace(/\/restofworld\//, "/"+gotoRegion+"/");
	}
	// catch any urls that have no region but are a record
	else if(sURL.indexOf("/page/") > -1 || sURL.indexOf("/stry/") > -1 || sURL.indexOf("/invt/") > -1 || sURL.indexOf("/pcat/") > -1 || sURL.indexOf("/scat/") > -1 || sURL.indexOf("/icat/") > -1) { // This method returns -1 if the string value to search for never occurs
		var sURLArray = sURL.split(domain);
		if (sURLArray[1]) {
			sURL = domain+"/"+gotoRegion+sURLArray[1];
		}
	} else { */
		// if on any other screen redirect to home
		sURL = domain+"/"+gotoRegion+"/page/home";
		msg = "This action will change your currency and default region. \nClick OK to continue and load the home page or Cancel to retain the current currency and region.";
	/*}; */

	if (basketTotal>0){
		//If basket is not empty, warn user
		msg = msg+"\nClicking Continue will remove all items from your basket.";
	}
	
	var response = confirm(msg);
	if (response){
		//If user presses ok, change region
		window.location.href=sURL+logValue;
	}else{
		//If user cancels, don't change region
		return;
	};
};

 /**
 * Set region/location if user has no cookie set
 * when notify in URL, trigger function checkNotify
 * @param {string} venda_serveradd tag
 */
Venda.Ebiz.pushLocation = function(domain) {
var vendaLocation = YAHOO.util.Cookie.get("locn"); //set by venda
	if(vendaLocation===null){
		// if venda location not set use Maxmind's JS to detect country
		var countryCode = geoip_country_code();
		var gotoRegion;
		
		if (countryCode === 'AS' || countryCode === 'MH' || countryCode === 'PR' || countryCode === 'UM' || countryCode === 'US' || countryCode === 'VI' || countryCode === 'VG'){
			gotoRegion="us";
		} else if (countryCode === 'GB' || countryCode === 'GG' || countryCode === 'GS' || countryCode === 'JE'){;
			gotoRegion="uk";
		} else {
			gotoRegion="restofworld";
		}
		
		var sURL = unescape(location.href);
		sURL = domain+"/"+gotoRegion+"/page/home";
		window.location.href=sURL+"?notify=yes";
	};
};

 /**
 * Change region popup message
 * Sourced by templates/menu/flags
 */
Venda.Ebiz.checkNotify = function() { 
	var query = window.location.search.substring(1);
	var params = query.split('&');
		for (var i=0; i<params.length; i++) {
		var pos = params[i].indexOf('=');
			if (pos > 0) {
			var key = params[i].substring(0,pos);
			var val = params[i].substring(pos+1);
			qsParam[key] = val;
			}
		}
};

/**
* from general.js
*/

//order confirmation and order receipt page - split the email address on the RHN if too long
function splitEmailAdd(usemail) {
	var stringlist = new Array();
	while (usemail.length > 30) {
	   stringlist.push( usemail.slice(0,30));
	   usemail=usemail.substr(30);
	}
	if (usemail.length) {
	  stringlist.push(usemail);
	}
	document.write(stringlist.join( '<br>' ));
};

/* Find and add class last to the last element */
/* This is made in order to hilight the last element of crumtrail. It might be reused in other purpose but the same way of use. */
/* findElement: The element that jQuery will go through */
/* className: The class name that would like to add as last element */
/* countwhen: jQuery will add class name when this return more than this amount */
Venda.Ebiz.addClassLast = function(findElement,className,countwhen){
	var elementCount = jQuery(findElement).length;
	if ((countwhen > 0) && (elementCount > 0) && (countwhen < elementCount)){
		jQuery(findElement+":last").addClass(className);
	}
};

 /**
 * SearchresultLightbox using on searchresult required by client (JCLOG-57, JCLOG-115), 
 * This function required jQuery.
 * This function work by using create over-layers and move on top of each "div.prods li". 
 * Then if move mouse hover over-layer the script'll active modal layer and set z-index of "div.prods li" to topmost and display none to over-layer
 * This function is also required element #searchmodal and #overlay
 */
Venda.Ebiz.searchResultLightbox=function(){
	/* Initial: set overlay position */
    if(jQuery("div.prods li").length>0){
		var plusFF = 0;
		if (!jQuery.browser.msie && jQuery.browser.version.substr(0,3)=="1.9") {
			plusFF = 1;
		}
        jQuery("div.prods li").each(function(){
            var ids=jQuery(this).attr("id");
            var Offset=jQuery(this).offset();
            jQuery("#overlaysearchResult").append("<div id='overlay-"+ids+"' class='searchoverlay'> </div>");	
            jQuery("#overlay-"+ids).css({"left":Offset.left+plusFF,"top":Offset.top+plusFF,"position":"absolute","height":jQuery(this).height()+"px","width":jQuery(this).width()+"px"});		
        });
		if (jQuery(".myaccpredictor").length > 0) {
			jQuery("#searchmodal").css({"height":jQuery(".prods ul").height()+"px","width":jQuery(".prods ul").width()+"px"});
			jQuery("#searchmodal").css({"left":jQuery(".prods ul").offset().left+plusFF,"top":jQuery(".prods ul").offset().top+plusFF,"position":"absolute"});
		} else {
			jQuery("#searchmodal").css({"height":jQuery(".prods").height()+"px","width":jQuery(".prods").width()+"px"});
			jQuery("#searchmodal").css({"left":jQuery(".prods").offset().left+plusFF,"top":jQuery(".prods").offset().top+plusFF,"position":"absolute"});
		}
        /* End initial */
        jQuery(".searchoverlay").hover(function(){
            /* Move mouse hover overlay: active modal,set z-index of li */
			if (jQuery(".myaccpredictor").length > 0) {
				jQuery("#searchmodal").css({"height":jQuery(".prods ul").height()+"px","width":jQuery(".prods ul").width()+"px"});
			} else {
				jQuery("#searchmodal").css({"height":jQuery(".prods").height()+"px","width":jQuery(".prods").width()+"px"});
			}
            jQuery("div.prods li .view").css({"display":"none"});
            jQuery("#searchmodal").css({"display":"block"});
            jQuery("div.prods li").css({"z-index":"0"});
            var P=jQuery(this).attr("id").replace("overlay-","");
            jQuery("#"+P+" .view").css({"display":"block"});
            jQuery("#"+P).css({"z-index":"11"});
            jQuery(this).css({"display":"none"});
        },function(){
            /* Move mouse out of #searchmodal:do nothing */
        });
        jQuery("div.prods li").hover(function(){
            /* Move mouse hover li: active modal */
            jQuery("#searchmodal").css({"display":"block"});
            
        },function(){
            /* Move mouse out of li: hide overlay,modal and reset li z-index */
			if (jQuery(".myaccpredictor").length > 0) {
				jQuery("#searchmodal").css({"height":jQuery(".prods ul").height()-1+"px","width":jQuery(".prods ul").width()-1+"px"});
			} else {
				jQuery("#searchmodal").css({"height":jQuery(".prods").height()-1+"px","width":jQuery(".prods").width()-1+"px"});
			}
            var P=jQuery(this).attr("id");
            jQuery(this).find(".view").css({"display":"none"});
            jQuery(this).css({"z-index":"0"});
            jQuery("#overlay-"+P).css({"display":"block"});
            jQuery("#searchmodal").css({"display":"none"});
        });
    }
};

/* Function used on product detail page to check QTY textbox that it has to be number or more, cannot be 0, negative value, or text. */
/* obj: textbox element */
/* return true if QTY is valid, else return false. */
Venda.Ebiz.qtyValidate=function(obj){
	if (obj){
		if ((obj.value=="")||(obj.value<=0)||isNaN(obj.value)){
			alert("QTY must be valid number and more than 0.");
			obj.focus();
			return false;
		} else {return true;}
	} else {return false;}
};

//#############################################################
//   Start RT 118949	
//#############################################################
/*Initial variable*/
var arrZone = new Array(); //Keep postcode list from page.
var zone = {}; //Zone object.

function pushArray(area, code) {
	zone = {area:area,code:code};
	arrZone.push(zone);
}

function trimAll(sString) {
	while (sString.substring(0,1) == ' ') {
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ') {
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

function matchZone(upostcode) {
	var postcode1 = /^[a-z][0-9]$/i;	//A9 9AA
    var postcode2 = /^[a-z][0-9][0-9]$/i;	//A99 9AA
    var postcode3 = /^[a-z][0-9][a-z]$/i;	//A9A 9AA
    var postcode4 = /^[a-z][a-z][0-9]$/i;	//AA9 9AA
    var postcode5 = /^[a-z][a-z][0-9][0-9]$/i;	//AA99 9AA
    var postcode6 = /^[a-z][a-z][0-9][a-z]$/i;	//AA9A 9AA 
	
	if (postcode1.test(upostcode)||postcode2.test(upostcode)||postcode3.test(upostcode)||postcode4.test(upostcode)||postcode5.test(upostcode)||postcode6.test(upostcode)){
		if (postcode3.test(upostcode)){
			upostcode = upostcode.substring(0,2);
		} else if (postcode6.test(upostcode)){
			upostcode = upostcode.substring(0,3);
		}
		var i = 0;
		var foundItem = {found:false,value:-1};
		
		while(i<arrZone.length && !foundItem.found){
			if (upostcode.toUpperCase()==arrZone[i].code.toUpperCase()) {
				foundItem.found = true;
				foundItem.value = i;
			} else {
				i++;
			}
		}
		if (foundItem.found){
			return arrZone[foundItem.value].area;
		} else {
			return "";
		}
	} else {
		return "";
	}
}

function trimZone(fullpostcode) {
	var strZone = trimAll(fullpostcode);
	if (strZone != '') {
		//if user post code lenght > 3 = expect a correct formatted postcode
		if (strZone.length > 3) {
			strZone = trimAll(strZone.substring(0, strZone.length-3));
		}
		else {
		//postcode is not correct formatted.
			strZone = '';
		}
	}
	return strZone;
}

function getPostcodeZone(fullpostcode) {
	var userFullPostCodeStem = '';
	var userZone = "";

	userFullPostCode = trimZone(fullpostcode);
	return matchZone(userFullPostCode);
}

//#############################################################
//   End RT 118949	
//#############################################################

/* Duty Message */
var arrDuty = new Array(); //DDU/DDP country list.

function pushDuty(country, dutyType) {
	arrDuty.push({country:trimAll(country),dutyType:trimAll(dutyType)});
}

function displayDutyMessage(findCountry) {
	var i = 0;
	var found = false;
	while (i<arrDuty.length && !found) {
		if (arrDuty[i].country.toUpperCase()==findCountry.toUpperCase()) {
			found = true;
		} else{
			i++;
		}
	}
	if (found) {
		return arrDuty[i].dutyType;
	} else {
		return "";
	}
}
Venda.Ebiz.displayview = function(){
	if(jQuery("div.prods li").length>0){
		jQuery("div.prods li").hover(function(){
            jQuery(this).find(".view").css({"display":"block"});			
        },function(){
            jQuery(this).find(".view").css({"display":"none"});
        });
	}
}
Venda.Ebiz.RemoveAttribute = function(){
    jQuery("#productdetail select[name=att1],#productdetail select[name=att2]").each(function(){
        var optionLength = jQuery(this).find("option").length;
        if (optionLength < 3) {
            jQuery(this).find("option:first").remove();
        }
    });
};