/*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

    le.utility.js - Generic functions that are good to have around

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*/
/*==============================================
    Check the query string to see if debug=true.
    If ?debug=true, set global DEBUG = true.
==============================================*/
var DEBUG = false;
function checkDebugState() {
    if (getQueryVariable("debug").match(/true/i) ) {
        DEBUG = true;
    }
}
checkDebugState();
/*=======================================================
    Called from within the code to display a debug window
    with debug information.  If DEBUG == false, nothing
    happens.
=======================================================*/
function doDebug(msg) {
    if (DEBUG === false) return; 
    if (typeof debugLine == 'undefined') {
        debugLine = 1;
    } else {
        debugLine ++;
    }
    bgcolor = '';
    if (debugLine % 2 == 0) {
        bgcolor = '#cccc99';
    } 
    var debugWindow = window.open("", "debugWindow", "width=700,height=600,resizable=yes,scrollbars=yes,status=no");
    var now = new Date();
    var dateString = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
    var cLog = "<div style='background-color:"+bgcolor+";font-size:small;'>" + dateString + " - " + msg + "</div>\n";
    debugWindow.document.writeln(cLog);
    debugWindow.scrollTo(0,999999999);
}


function getReferForLink() {
    var referLink;
    var newURL;
	var testSid = getQueryVariable("sid");
	// if single item, no fit change, and the sid is the same 
	if(! multiItem && currentBuyGridUrl == null && testSid != theSid){
		refereLink = ppPath;
		return refereLink;
	}

	// if multi-item page construct new url
	if(multiItem){
		newURL = hostname + '/pp/MultiItem.html' + multiItem.reloadPage();
	}
	
	// if single item product page and there was a fit change
	if(! multiItem && currentBuyGridUrl != null){
		var edit = new RegExp('\\/(\\w*)\\-');
		var productName = window.location.href.match(edit)[1];
		newURL = currentBuyGridUrl.replace(/ProdPageBG/,productName);
		newURL = hostname + newURL + window.location.search;
	}
	// if single item product page and there was not a fit change
	else if(!multiItem){
		newURL = window.location.href;
	}

    // if new sid added or a sid added to replace nothing
    if (testSid != theSid) {
        // sid not found on the url, so append it
        if (window.location.search.search(/sid=/) == -1) {
            var divider;
            if (window.location.search == "") {
                divider = "?";
            } else {
                divider = "&";
            }
            referLink = newURL + divider;
        } 
        // sid found on url, so it needs to be replaced
        else {
            var parseSearch = newURL.split("?")[1].split("&");
            var newSearch = "";
            var i;
            
            // build new search string by adding all other search values to the new sid id value
            for (i = 0; i < parseSearch.length; i++) {
                if (parseSearch[i].search(/sid=/) == -1) {
                    newSearch += "&" + parseSearch[i];
                }
            }
            referLink = newURL.split("?")[0] + newSearch;
        }
    }
    // if no new sid, then just reload the page using the new url
    else{
    	referLink = newURL;
    }    
    
	return referLink;
}

function addReferToLink(anchorTag) {
	if (anchorTag.href.indexOf("?") == -1) {
		anchorTag.href = anchorTag.href + "?";
	} else {
		anchorTag.href = anchorTag.href + "&";
	}
	anchorTag.href = anchorTag.href + "refer=" + encodeURIComponent(getReferForLink());
}
/*=========================================================
    Compares two single-dimensional arrays.  If they match,
    returns true, or else it returns false. 
=========================================================*/
compareArrays = function(arr1, arr2) {
    if (arr1.length != arr2.length) return false;
    for (var i = 0; i < arr1.length; i++) {
        if (arr1[i] != arr2[i]) return false;
    }
    return true;
}

/*================================================================
    Converts a float to $ddd.cc. Doesn't add commas for thousands.
    Returns a string.
    
    numToConv - The float to convert.  It can also be a number
    as a string.
    
    sign - show the dollar sign?  If blank, it's assumed yes.
    If false, well, you know... 
================================================================*/
toUSCurrency = function(numToConv, sign) {
    var dollars;
    var cents;
    var amount;
    
    // convert the float to a string if it's not already one.
    numToConv += "";
    
    // 0-9 and decimals
    // make sure that there aren't extra decimals or other strange characters stuck in there
    if (numToConv.match("^[0-9\.]*$") && parseFloat(numToConv) == numToConv) {
        // check if there is a decimal
        if (numToConv.search(/\./) > -1) {
            dollars = numToConv.substr(0, parseInt(numToConv.search(/\./)));
            cents = numToConv.substr(parseInt(numToConv.search(/\./) + 1), 2);
            if (cents.length == 1) {
                cents += "0";
            } else if (cents.length == 0) {
                cents += "00";
            }
        // if there is no decimal, then it's a whole number
        } else {
            dollars = numToConv;
            cents = "00";
        }
        
        if (sign == false) {
            amount = dollars + "." + cents;
        } else {
            amount = "$" + dollars + "." + cents;
        }
        
        return amount;
    }
};

function getSID() {
    var funcName = "[getSID] ";
    var val = readCookie("SID");
    if (val == null || val == "") {
        val = getQueryVariable("sid");
    } else {
        doDebug(funcName + "found SID in cookie ");
    }
    doDebug(funcName + " getSID() returns " + val);
    return val;
}

/*=================================================================

    Gets a query string variable and returns the variable's 
    value as a string.
    
    Taken from landsend.com core site, so this probably be removed
    during integration testing.

    variable - The variable in the query string to get.
    
=================================================================*/
function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0;i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
          return pair[1];
        }
    } 
    return "";
}

/*==================================================================

    Gets HTML tags by looking at their class names.  Returns an
    array of tags matching the criteria.

    Written by Jonathan Snook, http://www.snook.ca/jonathan
    Add-ons by Robert Nyman, http://www.robertnyman.com
    
    oElm - The scope of where to search, such as document, body,
    a specific div tag referenced by document.getElementById().
    Usually set to document.
    
    strTagName - The type of tag to look for, such as <div>, <span>,
    <p>, etc.
    
    oClassNames - A single class name as a string or an array of
    class names.
    
==================================================================*/
function getElementsByClassName(oElm, strTagName, oClassNames){
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    var arrRegExpClassNames = new Array();
    if(typeof oClassNames == "object"){
        for(var i=0; i<oClassNames.length; i++){
            arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
        }
    }
    else{
        arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
    }
    var oElement;
    var bMatchesAll;
    for(var j=0; j<arrElements.length; j++){
        oElement = arrElements[j];
        bMatchesAll = true;
        for(var k=0; k<arrRegExpClassNames.length; k++){
            if(!arrRegExpClassNames[k].test(oElement.className)){
                bMatchesAll = false;
                break;                      
            }
        }
        if(bMatchesAll){
            arrReturnElements.push(oElement);
        }
    }
    return (arrReturnElements)
}

/*==================================================================
	Makes a cookie
    This script was originally written by Scott Andrew  http://www.scottandrew.com/   
=================================================================*/
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

/*==================================================================
	Reads a cookie
    This script was originally written by Scott Andrew  http://www.scottandrew.com/  
==================================================================*/
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

/*==================================================================
	Erases a cookie
    This script was originally written by Scott Andrew  http://www.scottandrew.com/   
==================================================================*/
function eraseCookie(name) {
	createCookie(name,"",-1);
}

function lTrim(str){
	if (str==null){return null;}
	for(var i=0;str.charAt(i)==" ";i++);
	return str.substring(i,str.length);
}
function rTrim(str){
	if (str==null){return null;}
	for(var i=str.length-1;str.charAt(i)==" ";i--);
	return str.substring(0,i+1);
}
function trim(str){return lTrim(rTrim(str));}
function lTrimAll(str) {
	if (str==null){return str;}
	for (var i=0; str.charAt(i)==" " || str.charAt(i)=="\n" || str.charAt(i)=="\t"; i++);
	return str.substring(i,str.length);
}
function rTrimAll(str) {
	if (str==null){return str;}
	for (var i=str.length-1; str.charAt(i)==" " || str.charAt(i)=="\n" || str.charAt(i)=="\t"; i--);
	return str.substring(0,i+1);
}
function trimAll(str) {
	return lTrimAll(rTrimAll(str));
}
function isBlank(val){
	if(val==null){return true;}
	for(var i=0;i<val.length;i++) {
		if ((val.charAt(i)!=' ')&&(val.charAt(i)!="\t")&&(val.charAt(i)!="\n")&&(val.charAt(i)!="\r")){return false;}
		}
	return true;
}
function isInteger(val){
	if (isBlank(val)){return false;}
	for(var i=0;i<val.length;i++){
		if(!isDigit(val.charAt(i))){return false;}
	}
	return true;
}

//-------------------------------------------------------------------
// isNumeric(value)
//   Returns true if value contains a positive float value
//-------------------------------------------------------------------
function isNumeric(val){return(parseFloat(val,10)==(val*1));}

//-------------------------------------------------------------------
// isArray(obj)
// Returns true if the object is an array, else false
//-------------------------------------------------------------------
function isArray(obj){return(typeof(obj.length)=="undefined")?false:true;}

//-------------------------------------------------------------------
// isDigit(value)
//   Returns true if value is a 1-character digit
//-------------------------------------------------------------------
function isDigit(num) {
	if (num.length>1){return false;}
	var string="1234567890";
	if (string.indexOf(num)!=-1){return true;}
	return false;
}
