/**
* @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");

 /**
 * 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>');
};
//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>' ));
}
 /**
 * A skeleton function for validating user extened fields - needs to be amended by the build team
 * @param {object} frmObj HTML form containing user extended field elements
 */
Venda.Ebiz.validateUserExtendedFields = function(frmObj) {
	if(frmObj) {
		if (frmObj.usxtdobday.selectedIndex == 0) {
		alert("Please select Day for Date Of Birth");
		frmObj.usxtdobday.focus()
		return;
	}
	if (frmObj.usxtdobmonth.selectedIndex == 0) {
		alert("Please select Month for Date Of Birth");
		frmObj.usxtdobmonth.focus()
		return;
	}
	if (document.wizform.usemail.value != document.wizform.usemail2.value) {
        alert("Email addresses do not match.  Please retype them to make sure they are the same.");
		wizform.usemail2.focus()
		return;
	}
	var Year=document.wizform.usxusxtdobyear
	
	if ((Year.value==null)||(Year.value=="")){
		alert("Please Enter Year for Date Of Birth")
		Year.focus()
		return;
	}
	if (checkInternationalYear(Year.value)==false){
		alert("Please Enter a Valid Year")
		Year.value=""
		Year.focus()
		return;
	}			
	
		nextPage();		
	} 
	return false;
}


// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in Year numbers
var YearNumberDelimiters = "()- ";
// characters which are allowed in international Year numbers
// (a leading + is OK)
var validWorldYearChars = YearNumberDelimiters + "+";
// Minimum no of digits in an international Year no.
var minDigitsInIYearNumber = 4;

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}
function trim(s)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not a whitespace, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (c != " ") returnString += c;
    }
    return returnString;
}
function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkInternationalYear(strYear){
var bracket=3
strYear=trim(strYear)
if(strYear.indexOf("+")>1) return false
if(strYear.indexOf("-")!=-1)bracket=bracket+1
if(strYear.indexOf("(")!=-1 && strYear.indexOf("(")>bracket)return false
var brchr=strYear.indexOf("(")
if(strYear.indexOf("(")!=-1 && strYear.charAt(brchr+2)!=")")return false
if(strYear.indexOf("(")==-1 && strYear.indexOf(")")!=-1)return false
s=stripCharsInBag(strYear,validWorldYearChars);
return (isInteger(s) && s.length >= minDigitsInIYearNumber);
}


function validateQty(iform){
var iNum = /\D/;
var qty = iform.qty;

    if(iNum.test(qty.value)==true){
        alert("Please enter numbers only");
        return false;
    }
    else if(qty.value < "1"){
        alert("Please enter numbers more than 0."); 
    }
    else{
         iform.submit();
    }		
}	

// This function is used for defaulting the quantity to 1 or to make the quantity positive incase the user enters it wrong by mistake
function qtyValidate(thisBox,item){
  var regExp = /\D/g;
  var nonNum= thisBox.value.match(regExp);

    if(item > 0) {
        if ((nonNum != null) && (nonNum.length > 0) || (thisBox.value == "")) {
             thisBox.value = item;       
        }
    }else{
        if ((nonNum != null) && (nonNum.length > 0) || (thisBox.value == 0)) {
            thisBox.value = 1;        
        }
    }

}  
 /**
 * Check the on hand status of each attribute then preventing the user to buy ouf of stock product also show eta date if available for in stock attribute product
 * @param {string} id of div or any element which covers the attribute dropdown
 */
Venda.Ebiz.getOnhand = function(selectElement){
	var attrString="";
	var attrOptionValue = document.getElementById(selectElement).getElementsByTagName("select");
    var defaultValueOFS = Venda.Ebiz.getOnhand.stockInstruction.defaultValueOutOfStock;
	for (var i=0;i<attrOptionValue.length;i++){
		attrString+=attrOptionValue[i].value;
	}
	if(product.attributeValues[attrString]!=undefined){
		if(product.attributeValues[attrString].data["atronhand"]<=0){
			Venda.Ebiz.getOnhand.stockInstruction.hideAddtoBasketButton.style.display = "none";
			Venda.Ebiz.getOnhand.stockInstruction.messageTarget.innerHTML = Venda.Ebiz.getOnhand.stockInstruction.outOfStockMessage;
		}
		else if(product.attributeValues[attrString].data["atronhand"]>0 && product.attributeValues[attrString].data["atretady"]!="" && product.attributeValues[attrString].data["atretamn"]!="" && product.attributeValues[attrString].data["atretayr"]!=""){
			Venda.Ebiz.getOnhand.stockInstruction.hideAddtoBasketButton.style.display = "inline";
			var etaDate = product.attributeValues[attrString].data["atretady"]+"/"+product.attributeValues[attrString].data["atretamn"]+"/"+product.attributeValues[attrString].data["atretayr"];			
			if(Venda.Ebiz.getOnhand.checkDate(etaDate)==false){
				Venda.Ebiz.getOnhand.stockInstruction.messageTarget.innerHTML = Venda.Ebiz.getOnhand.stockInstruction.etaDateMessage+" "+etaDate;
			}else{
				Venda.Ebiz.getOnhand.stockInstruction.messageTarget.innerHTML = '';
			}
		}else{
			Venda.Ebiz.getOnhand.stockInstruction.hideAddtoBasketButton.style.display = "inline";
			Venda.Ebiz.getOnhand.stockInstruction.messageTarget.innerHTML = '';
		}
	}else{
		Venda.Ebiz.getOnhand.stockInstruction.hideAddtoBasketButton.style.display = "inline";
		Venda.Ebiz.getOnhand.stockInstruction.messageTarget.innerHTML = defaultValueOFS;
	}
};
 /**
 * Check the on hand preventing the user add out of stock attr product by pressing enter button when qty textbox is focused 
 * @param {string} id of div or any element which covers the attribute dropdown
 * return the boolean with showing the popup message
 */
Venda.Ebiz.checkAddProd = function(selectElement){
	var attrString="";
	var attrOptionValue = document.getElementById(selectElement).getElementsByTagName("select");
	for (var i=0;i<attrOptionValue.length;i++){
		attrString+=attrOptionValue[i].value;
	}
	if(product.attributeValues[attrString]!=undefined){
		if(product.attributeValues[attrString].data["atronhand"]>0){
			return true;
		}else{
			alert(Venda.Ebiz.getOnhand.stockInstruction.outOfStockMessage);
			return false;
		}
	}else{
		alert(Venda.Ebiz.getOnhand.stockInstruction.combinationMessage);
		return false;
	}
};
 /**
 * Take the eta date of the attribute then compare to now date 
 * @param {string} the eta date of attribute product
 * return the result of eta date is less than now date
 */
Venda.Ebiz.getOnhand.checkDate = function(chkDate){
		var chkDate = chkDate.split("/");
		var curDate = Venda.Ebiz.getOnhand.stockInstruction.currentDate.split("/");
		var etaDate = new Date(chkDate[2],chkDate[1],chkDate[0]);
		var nowDate = new Date(curDate[2],curDate[1],curDate[0]);
		return (etaDate<nowDate);
};

Venda.Ebiz.showSavingPriceAttr = function(elementId) {
    var divSaveId = "savingDiv_"+elementId;
    var divSaveLabel = document.getElementById("defaultsaveLabel").innerHTML;
    var invtsell = document.getElementById("PriceDiv_"+elementId).innerHTML;
    var invtwas = document.getElementById("wasDiv_"+elementId).innerHTML;
          invtwas = invtwas.replace("€", '');
          invtsell = invtsell.replace("€", '');
//alert(invtwas+" "+invtsell);
    if(invtwas!=0){
        if ( invtwas > invtsell ) {
             var invtsaving = invtwas - invtsell;
            if (document.getElementById(divSaveId)) {
                    document.getElementById(divSaveId).innerHTML = "&euro;" + invtsaving.toFixed(2);
                    document.getElementById(divSaveId+"Label").innerHTML = divSaveLabel + " ";
            }
        }
    }
	else{
                    document.getElementById(divSaveId).innerHTML = "";
                    document.getElementById(divSaveId+"Label").innerHTML = " ";
    }
};

Venda.Ebiz.showSavingPriceAttrList = function(elementId) {
    var divSaveId = 'savingPrice_'+elementId;
    var invtsell = document.getElementById("sellPrice_"+elementId).innerHTML;
    var invtwas = document.getElementById("wasPrice_"+elementId).innerHTML;
         invtwas = invtwas.replace("€", '');
          invtsell = invtsell.replace("€", '');
//alert(divSaveId+" "+invtsell+" "+invtwas);
    if(invtwas!=0){
             var invtsaving = invtwas - invtsell;
            if (document.getElementById(divSaveId)) {
                    document.getElementById(divSaveId).innerHTML = invtsaving.toFixed(2);
            }
    }
};