function escapeHTML(s){
    return s.replace(/&/g, "&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g, "&quot;");
    /* fix syntax highlighting " */
}


/* unhides the tell a friend form */
function showTellFriend(){
    show("email_to_friend");
    return false;
}

/* Hides all Elements in array A */
function hideAll(A){
    for (var i = 0; i < A.length; i++){
        document.getElementById(A[i]).style.display="none";
    }
}

/* Shows all Elements in array A */
function showAll(A){
    for (var i = 0; i < A.length; i++){
        document.getElementById(A[i]).style.display="block";
    }
}

/* Show just one element */
function show(E){
    document.getElementById(E).style.display="block";
}

/* hide just one element */
function hide(E){
    document.getElementById(E).style.display="none";
}

/* shows hides the correct affiliate forms fields */
function showAffFields(selectOption){
    /* payment_check is also there but not implemented in our HTML */
    if (selectOption.value == "check"){
        hideAll(Array("payment_bank"));
        show("payment_check");
    } else if (selectOption.value == "bank"){
        hideAll(Array("payment_check"));
        show("payment_bank");
    } else {
        /* throw error, should never happen */
        alert("You Must Select either Check or Direct Deposite");
        showAll(array("payment_bank", "payment_check"));
    }
}

function selectTextInID(id){
    var element = document.getElementById(id);
    element.focus();
    element.select();
}

/* Pass strength Meter */
var MaxPassStrength = 200;
function passStrength(pass){
	var strength = 0;
	/* length 10pts */
	if (pass.length < 16){
	    strength += (pass.length/15)*0.10;
	} else {
	    strength += 0.10;
	}

	/* length (extra) 20pts, extra for those over 8 */
	if (pass.length > 6 && pass.length < 16){
	    strength += ((pass.length - 6)/9)*0.2;
	} else if (pass.length > 15){
	    strength += 0.2;
	}

	/* characters (25) */
	if (pass.match(/[a-z]/)){
	    strength += 0.05;
	}
	if(pass.match(/[A-Z]/)){
	    strength += 0.05;
	}
	if (pass.match(/[0-9]/)){
	    strength += 0.05;
	}
	if (pass.match(/[^a-zA-Z0-9]/)){
	    strength += 0.10;
	}

	/* 3 or more of anything (25) */
	if (pass.match(/[a-z].*?[a-z].*?[a-z]/)){
	    strength += 0.05;
	}
	if (pass.match(/[A-Z].*?[A-Z].*?[A-Z]/)){
	    strength += 0.05;
	}
	if (pass.match(/[0-9].*?[0-9].*?[0-9]/)){
	    strength += 0.05;
	}
	if (pass.match(/[^a-zA-Z0-9].*?[^a-zA-Z0-9].*?[^a-zA-Z0-9]/)){
	    strength += 0.10;
	}
	/*
	20pts (5pts/3 junctions)
	letter/number letter/symbol, and cap/lower, sym/num
	*/
	var re = "([a-zA-Z][0-9]|[0-9][a-zA-Z])";
	if (pass.match(new RegExp(re + ".*?" + re + ".*?" + re))){
	    strength += 0.05;
	}
	var re = "([a-zA-Z][^a-zA-Z0-9]|[^a-zA-Z0-9][a-zA-Z])";
	if (pass.match(new RegExp(re + ".*?" + re + ".*?" + re))){
		strength += 0.05;
	}
	var re = "([a-z][A-Z]|[A-Z][a-z])";
	if (pass.match(new RegExp(re + ".*?" + re + ".*?" + re))){
	    strength += 0.05;
	}
	var re = "([0-9][^a-zA-Z0-9]|[^a-zA-Z0-9][0-9])";
	if (pass.match(new RegExp(re + ".*?" + re + ".*?" + re))){
	    strength += 0.05;
	}
	return strength;
}


function checkPass(pass){
    var strength = passStrength(pass);
    var str_strength = "Very Weak";
    if (strength > 0.20){
	str_strength = "Weak";
    }
    if (strength > 0.35){
	str_strength = "Moderate";
    }
    if (strength > 0.55){
	str_strength = "Strong";
    }
    if (strength > 0.70){
	str_strength = "Very Strong";
    }
    var box = document.getElementById("pass_strength_box");
    document.getElementById("pass_strength_len").innerHTML = str_strength;
    document.getElementById("pass_strength_len").style.width = Math.floor(strength*MaxPassStrength) + "px";
    var r = 255;
    var g = 0;
    var b = 0;
    r -= strength*255;
    g += strength*255;
    
    if (strength < 0.5){
	b = strength*512;
    } else {
	b = 255 - (strength-0.5)*512
    }
    
    var color = "#";
    var colorRGB = (parseInt(r)*65536 + parseInt(g)*256 + parseInt(b)).toString(16);
    for (var i = colorRGB.length; i < 6; i++){
	color += "0";
    }
    document.getElementById("pass_strength_len").style.backgroundColor = color + colorRGB ;
    if (pass.length == 0){
	document.getElementById("passwordGen").type="password";
    }
}

function genNewPass(){
    var letters = new Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
			    'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
			    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
			    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
			    '`', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '~', '!',
			    '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '-', '=',
			    '[', ']', '\\', '{', '}', '|', ';', '\'', ':', '"', ',', '.', '/',
			    '<', '>', '?');
    var pass = "";
    for (var i = 0; i < 10; i++){
	pass += letters[Math.floor(Math.random()*(letters.length))];
    }
    return pass;
}

function genPass(){
    var pass = genNewPass();
    checkPass(pass);
    document.getElementById("passwordGen").value = pass;
    document.getElementById("passwordGen").type="text";
}

function toggleLayer( whichLayer )
{
  var elem, vis;
  if( document.getElementById ) /* this is the way the standards work */
    elem = document.getElementById( whichLayer );
  else if( document.all ) /* this is the way old msie versions work */
      elem = document.all[whichLayer];
  else if( document.layers ) /* this is the way nn4 works */
    elem = document.layers[whichLayer];
  vis = elem.style;
  /* if the style.display value is blank we try to figure it out here */
  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}

function OpenExclusiveDiv(id) { 
    var high_div = getHighestHiddenDiv()+1;
    for (i=1;i<high_div;i++) { /* The amount of divs you have. */
	var divname = 'magic'+i; 
	var divstyle = document.getElementById(divname).style; 
	divstyle.display=(id==divname)?'block':'none'; 
    } 
} 

function getHighestHiddenDiv()
{
    var div_dex = 0;
    cn = document.getElementById( "allhide" ).childNodes;
    for (var i = 0; i < cn.length; i++) 
	{
	    if( cn[i].nodeType==1 && cn[i].nodeName=="DIV"){
		var result = cn[i].id.match("magic([0-9]+)");
		if(result[1]>div_dex){
		    div_dex=result[1];
		}
	    }
	}
    return div_dex;
}

function loadMagic(){
    if(location.hash){
	var o = document.getElementById(location.hash.split("#")[1]);
	if(o && o.tagName.toLowerCase()=='div'){
	    OpenExclusiveDiv(o.id);
	}else{
	    return false;
	}
    }else{
	return false;
	/* Fall through ..all divs should be shown by default. */
    }
}

function showBannerHtml(image, url){
    document.getElementById("aff_banner_link").innerHTML = "<h3>Use this HTML to use the image you just selected</h3>"
        + "<a href=\"#\" onclick=\"selectTextInID('aff_banner_link_txt');return false;\">Select this HTML</a><br />"
        + "<textarea id=\"aff_banner_link_txt\" cols=\"80\" rows=\"5\">"
        + escapeHTML("<a href=\"" + escapeHTML(url) + "\">")
        + escapeHTML(image)
        + escapeHTML("</a>")
        + "</textarea>";
    return false;

}

var coupons_updating = 0;
var xmlReq;

function addCoupon(inputBox){
    var couponList = new Array();
    var couponBx = document.getElementById("coupon_input_bx");
    var childern = couponBx.getElementsByTagName("input");
    for (var i = 0; i < childern.length; i++){
        
        couponList.push(childern[i].value);
    }
    couponBx.innerHTML += inputBox;
    var childern = couponBx.getElementsByTagName("input");
    for (var i = 1; i < childern.length; i++){
        childern[i].value = couponList[i-1];
    }
}

function scheduleCouponUpdate(arg){
    if (coupons_updating){
        /* wait for it to finish
         * 
         * FIXME!!!!!!!!!!!!!!!!!!!!!!!
         * need to pass the url
         */
        setTimeout(function(){ scheduleCouponUpdate(arg); }, 500);
    } else {
        updateCoupons(arg);
    }
}

function updateShippingQuote(quote, subtotalUrl){
    document.getElementById("active_shipping_quote_name").innerHTML = document.getElementById("shipping_quote_name_" + quote.value).innerHTML;
    document.getElementById("active_shipping_quote_price").innerHTML = document.getElementById("shipping_quote_price_" + quote.value).innerHTML;
    document.getElementById("active_quote_total").innerHTML = document.getElementById("shipping_quote_total_" + quote.value).innerHTML;
    document.getElementById("hidden_ship_sugg").value = quote.value;

    if (subtotalUrl != null){
        scheduleCouponUpdate(subtotalUrl);/* stuff can be complicated....do this too to solve some of the advanced problems (amount saved can change...) */
    }
    /*alert(quote.value);*/
}

/* return an object for XML requests */
function getXMLrequest(){
    /* thamks http://www.jibbering.com/2002/4/httprequest.html */
    var xmlhttp=false;
    /*@cc_on @*/
    /*@if (@_jscript_version >= 5)
    // JScript gives us Conditional compilation, we can cope with old IE versions.
    // and security blocked creation of the objects.
    try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
    try {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
    xmlhttp = false;
    }
    }
    @end @*/
    if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
        try {
            xmlhttp = new XMLHttpRequest();
        } catch (e) {
            xmlhttp=false;
        }
    }
    if (!xmlhttp && window.createRequest) {
        try {
            xmlhttp = window.createRequest();
        } catch (e) {
            xmlhttp=false;
        }
    }
    return xmlhttp;
}

function processCouponUpdate(){
    if (xmlReq.readyState == 4){
        /* alert(xmlReq.responseText);
        coupons_updating = 0;
        */
        var x = xmlReq.responseXML.documentElement;
        document.getElementById("active_shipping_quote_name").innerHTML = x.getElementsByTagName("shipName")[0].childNodes[0].nodeValue;
        document.getElementById("active_shipping_quote_price").innerHTML = x.getElementsByTagName("shipCost")[0].childNodes[0].nodeValue;
        document.getElementById("active_quote_total").innerHTML = x.getElementsByTagName("finalTotal")[0].childNodes[0].nodeValue;
        document.getElementById("hidden_ship_sugg").value = x.getElementsByTagName("selectedShipping")[0].childNodes[0].nodeValue;
        document.getElementById("cart_save_value").innerHTML = x.getElementsByTagName("totalSavings")[0].childNodes[0].nodeValue;
        document.getElementById("cart_save_p").innerHTML = x.getElementsByTagName("totalSavingsP")[0].childNodes[0].nodeValue;
        document.getElementById("cart_subtotal").innerHTML = x.getElementsByTagName("subtotal")[0].childNodes[0].nodeValue;
        var couponBox = document.getElementById("shopping_cart_coupons_st");
        var coupons = x.getElementsByTagName("coupons")[0].childNodes;
        couponBox.innerHTML = "";
        var couponName;
        var couponPrice;
        /* alert(coupons.length); */
        for (var i = 0; i < coupons.length; i++){
            var parts = coupons[i].childNodes;
            for (var j = 0; j < parts.length; j++){
                if (parts[j].nodeName == "couponName"){
                    couponName = parts[j].childNodes[0].nodeValue;
                } else if (parts[j].nodeName == "couponPrice"){
                    couponPrice = parts[j].childNodes[0].nodeValue;
                }
            }
            couponBox.innerHTML += "<span class=\"left\">" + couponName + ":</span><span class=\"right\">" + couponPrice + "</span> ";
        }
    
        var ship_totals = x.getElementsByTagName("shippingQuotes")[0].childNodes;
        for (var i = 0; i < ship_totals.length; i++){
            /* alert("shipping_quote_total_" + ship_totals[i].getAttribute("id") + " -> " + ship_totals[i].childNodes[0].nodeValue);*/
            document.getElementById("shipping_quote_total_" + ship_totals[i].getAttribute("id")).innerHTML = ship_totals[i].childNodes[0].nodeValue;
        }

        
        coupons_updating = 0;
    }
    

}




function updateCoupons(url){
    
    if (coupons_updating){
        return;/* no race conditions allowed */
    }

    coupons_updating = 1;
    /*alert(document.getElementById("hidden_ship_sugg").value);*/
    var adjusted_values = "clear_coupons=1&shipping_sugg=" + document.getElementById("hidden_ship_sugg").value;
    var inputs = document.getElementsByTagName("input");

    for (var i = 0; i < inputs.length; i++){
        if (inputs[i].name == "coupon_code[]" && inputs[i].value != ""){
            adjusted_values += "&coupon_code[]=" + escape(inputs[i].value);
        }
    }
    
    xmlReq = getXMLrequest();
    xmlReq.onreadystatechange = processCouponUpdate;
    xmlReq.open("POST", url, true);
    /* Send the proper header information along with the request */
    xmlReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    /* xmlReq.setRequestHeader("Content-length", adjusted_values.length); */
    xmlReq.send(adjusted_values);
    


}
