var subtotal_counter = 0;

function updateNumInCart(qtd){
    if(num = document.getElementById("num-in-cart")){
        var newNum = Number(num.innerHTML) + qtd;
        num.innerHTML = newNum;
    }
}

function analyticsEvent(mode, category, action, opt, val){
    if (typeof(_gaq) != "undefined"){
        if(mode == "all" || mode == "event"){
            // remember val is an int
            //_trackEvent(category, action, opt_label, opt_value, opt_noninteraction)
            _gaq.push(['_trackEvent', category, action, opt, val]);
        }
        if(mode == "all" || mode == "view"){
            _gaq.push(['_trackPageview', '/event/'+category+'/'+action]);
        }
    }
}

function adjustShipDate(){
    var time_dd;
    if(time_dd = document.getElementById("ship_date_time")){
        service = document.getElementById("shipper");
        var ship_name = service.options[service.selectedIndex].text;
        if(ship_name.indexOf('In Store') > -1){
            time_dd.style.visibility = "visible";
            time_dd.style.width = "";
        }else{
            time_dd.style.visibility = "hidden";
            time_dd.style.width = "0px";
        }
    }
}

function setCheckoutValues(val){
    if(!val){
        document.getElementById("ajax_ship").innerHTML = "ERROR!";
        document.getElementById("tax_amount").innerHTML = "ERROR!";
        document.getElementById("order_total").innerHTML = "ERROR!";
        return;
    }

    //TAX
    document.getElementById("tax_amount").innerHTML = usd(val.tax);
    if(Number(val.tax) != 0){
        //document.getElementById("tax_descr").innerHTML = "State Tax";
        document.getElementById("ajax_tax1").className = "tax_show";
    }else{
        document.getElementById("ajax_tax1").className = "tax_hide";
    }

    //SHIPPING
    document.getElementById("ajax_ship").innerHTML = usd(val.shipping);
    if(val.fields.shipper){
        if(document.getElementById("shipper")){
            sh = document.getElementById("shipper");
            if(sh.parentNode){
                pn = document.getElementById("shipper").parentNode;
                var t = document.createElement('div');
                t.innerHTML = val.fields.shipper;
                pn.innerHTML = "";
                pn.appendChild(t);
            }
        }
        //document.getElementById("shipper").parentNode.innerHTML = val.fields.shipper;
    }

    //HANDLING
    var value_fee_total = 0;
    var x = 0;
    for(x = x; val.handling[x]; x++){
        document.getElementById("handle_amount" + Number(x +1)).innerHTML = usd(val.handling[x].fee);
        document.getElementById("handle_descr" + Number(x +1)).innerHTML = val.handling[x].descr;
        value_fee_total += Number(val.handling[x].fee);
        document.getElementById("ajax_handling" + Number(x +2)).className = "handle_show";
    }
    for(x = x; x < 5; x++){
        document.getElementById("ajax_handling" + Number(x +2)).className = "handle_hide";
        document.getElementById("handle_amount" + Number(x +1)).innerHTML = "0";
    }

    //SUB TOTAL - added to allow qty change from checkout.php
    document.getElementById("subtotal").innerHTML = usd(val.sub_total);

    //MAINTENANCE
    var total = getOrderTotal();
	document.getElementById("order_total").innerHTML = total + "<input name=\"chk_total\" type=\"hidden\" value=\""+remDol2(total)+"\" />";
    nothingStatus(true);
}

function getFieldValue(fld){
    fld = document.getElementById(fld);
    if(fld){
        return fld.value;
    }else{
        return "";
    }
}

function getCheckoutValues2(){
    if(!checkUniqueCall(true)){
        return;
    }

    adjustShipDate();

    state = getFieldValue("state");
    shipper = getFieldValue("shipper");
    zip = getFieldValue("zip");
    alt_address = getFieldValue("alt_address");
    email = getFieldValue("email");
    exempt = getFieldValue("exempt");

    if(!zip || zip.lnegth == 0){
        return;
    }
    
    nothingStatus(false);
    document.getElementById("tax_amount").innerHTML = "Calculating..."; 
    document.getElementById("ajax_ship").innerHTML = "Calculating...";
    x_getCheckoutValues(state, shipper, zip, alt_address, email, exempt, setCheckoutValues);
}

function getCheckoutValues(){
    if(!checkUniqueCall(false)){
        return;
    }
    sajax_cancel();
    getCheckoutValues2();
}

function checkUniqueCall(save){
    state = getFieldValue("state");
    shipper = getFieldValue("shipper");
    zip = getFieldValue("zip");
    alt_address = getFieldValue("alt_address");
    email = getFieldValue("email");
    exempt = getFieldValue("exempt");

    //alert("got form values: state="+state+"; shipper="+shipper+"; zip="+zip+"; alt="+alt_address+"; email="+email+"; exempt="+exempt);
    //alert("static values: state="+this.state2+"; shipper="+this.shipper2+"; zip="+this.zip2+"; alt="+this.alt_address2+"; email="+this.email2+"; exempt="+this.exempt2);
    
    ret = false;
    
    //Only continue if we are send a request with different input, this is more efficient, doesn't re-show the same errors over and over if they occur
    if(this.state2 != state || this.shipper2 != shipper || this.zip2 != zip || this.alt_address2 != alt_address || this.email2 != email || this.exempt2 != exempt || this.subtotal_counter2 != subtotal_counter){
        ret = true;
        //alert("go");
    }else{
        //alert("stop");
    }

    if(save){
        //Keep track of values from call to compare for next time:
        this.state2 = state;
        this.shipper2 = shipper;
        this.zip2 = zip;
        this.alt_address2 = alt_address;
        this.email2 = email;
        this.exempt2 = exempt;
        this.subtotal_counter2 = subtotal_counter;
    }
    
    return ret;
}

function handleNoAjax(){
    alert("Your browser does not support AJAX.  Please check your security settings.  This site requires Javascript and Cookies.");
    location.href = "problem.php?err=AX1";
}

function toggleTextCounter(textAreaId, counterDivId, maxlimit) {
    var textarea = document.getElementById(textAreaId);
    var div = document.getElementById(counterDivId);
    
    if (textarea.value.length > maxlimit) {
        // if too long...trim it!
        textarea.value = textarea.value.substring(0, maxlimit);
    }
    else { 
        // update 'characters left' counter
        var len = maxlimit - textarea.value.length;
        if (len > 999) {
            div.innerHTML = formatNumber(len, "##,###") + ' characters left';
        }
        else if (len == 0) {
            div.innerHTML = "You have reached the limit for this field (" + formatNumber(maxlimit, "##,###") + " characters).";
        }
        else {
            s = (len == 1 ? "" : "s");
            div.innerHTML = len + ' character' + s + ' left';
        }
    }
    div.style.display = (textarea.value.length > 0) ? 'block' : 'none';
}

function showCartContents(par){
    return false;
    var elem = document.getElementById("mini_cart");
    elem.style.top = par.offsetTop;
    elem.style.right = par.offsetLeft;
    elem.className = "mini_cart_show";
}

function hideCartContents(){
    document.getElementById("mini_cart").className = "mini_cart_hide";
}

function doXHRProxy(func) {
    setTimeout(func, 0);
}

function var_dump(obj) {
   if(typeof obj == "object") {
      return "Type: "+typeof(obj)+((obj.constructor) ? "\nConstructor: "+obj.constructor : "")+"\nValue: " + obj;
   } else {
      return "Type: "+typeof(obj)+"\nValue: "+obj;
   }
}

function remDol(num){
	return num.toString().replace(/\$|\,/g,'');
}

function remDol2(num){
	return num.toString().replace(/\$/g,'');
}

function usd(num) {
	//num = num.toString().replace(/\$|\,/g,'');
	num = num.toString().replace(/\$|\,|\&nbsp\;/g,'');
	if(isNaN(num))
		num = "0";
	
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
			num.substring(num.length-(4*i+3));
	
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function nothingStatus(bool){
    var n = 0;
    while(obj = document.getElementById("nothing" + n)){
        obj.disabled = !bool;
        n++;
    }
}

function setDynamicForm(fields_obj){
    var prefix = "ajax_pay";
    var fields = new Array();
    var y = 0;
    for(x in fields_obj){
        fields[y] = fields_obj[x];
        y++;
    }
    //alert(fields);
    for(i =0; i < fields.length/2; i++){
        var fXa = document.getElementById(prefix + i + "a");                    
        var fXb = document.getElementById(prefix + i + "b");
        
        if(fields[i] && (fXb || fXa)){
            if(fXa)
                fXa.innerHTML = fields[i+(fields.length/2)];
            if(fXb)
                fXb.innerHTML = fields[i];
        }else if(fXa || fXb){
            if(fXa)
                fXa.innerHTML = "";
            if(fXb)
                fXb.innerHTML = "";
        }
    }
    for(i=i; i < 15; i++){
        var fXa = document.getElementById(prefix + i + "a");
        var fXb = document.getElementById(prefix + i + "b");
                                    
        if(fXa || fXb){
            if(fXa)
                fXa.innerHTML = "";
            if(fXb)
                fXb.innerHTML = "";                        
        }
    }
}

function setPaymentType(ptype_id){
    setDynamicForm(srv_pay_forms[srv_pay_types[ptype_id]]);
    return true;    
}

function addGiftMessage(){
    var handle = window.open('pop_gift.php', 0, 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=375,height=250,left = 490,top = 262');
    if(!handle){
        alert("The gift message window could not be opened due to a popup blocker.  Please disable it and try again");
    }
    return false;
}

function addBoxGiftMessage(){
    var handle = window.open('pop_gift.php?gift_box=1', 0, 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=375,height=250,left = 490,top = 262');
    if(!handle){
        alert("The gift message window could not be opened due to a popup blocker.  Please disable it and try again");
    }
    return false;
}

function addNotes(){
    var handle = window.open('pop_notes.php', 0, 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=375,height=250,left = 490,top = 262');
    if(!handle){
        alert("The notes window could not be opened due to a popup blocker.  Please disable it and try again");
    }
    return false;
}

function setAltAddress(dummy, mode){
    //we use to pass in addr_id, but just dummy the arg and do it here... select objects suck
    addr_obj = document.getElementById("alt_address");
    addr_id = addr_obj.options[addr_obj.selectedIndex].value;
	if((addr_id == 0 && mode != "quiet") || mode == "edit"){
		//var handle = window.open('alt_address.php?id='+addr_id, 0, 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=375,height=310,left = 490,top = 262');
		dialog('iframe', '350px', '400px', true, 'Shipping Address', 'alt_address.php?id='+addr_id, false, false, false, false, false, false);
		//if(!handle){
		//	alert("The shipping address window could not be opened due to a popup blocker.  Please disable it and try again");
		//}
		if(mode != "edit"){
			document.getElementById("ajax_alt_ship").innerHTML = "";
		}
	}else if(addr_id <= 0){
		document.getElementById("ajax_alt_ship").innerHTML = "";
	}else{
		document.getElementById("ajax_alt_ship").innerHTML = "&nbsp;&nbsp;<a href=\"#\" onclick=\"return setAltAddress("+addr_id+", 'edit')?false:false;\">Edit</a>";
	}
	zip_f = document.getElementById('zip');
	isCart = document.getElementById("order_total");
    getCheckoutValues();
    return false;
}

function getAltAddress(addr_id){
	location.href = "?id="+addr_id;
	return true;
}

function cancelPopup(){
	window.close();
	return true;
}

function getTaxFromState(state){
    getCheckoutValues();
}

function getShippingRate(zip_dd, service){
    getCheckoutValues();
}

function getOrderTotal(){
    var handling_fees = false;
    var handling = 0;
    for(var x = 1; x < 6; x++){
        handling_fees = document.getElementById("handle_amount" + x);
        if(handling_fees){
            fee = handling_fees.innerHTML;
            if(fee.length > 0){
                handling += Number(remDol(fee));
            }
        }
    }
    return usd(handling + Number(remDol(document.getElementById("ajax_ship").innerHTML)) + Number(remDol(document.getElementById("tax_amount").innerHTML)) + Number(remDol(document.getElementById("subtotal").innerHTML)));
}

function getHandlingFees(state_dd, zip_dd, email_dd, service_dd){
    getCheckoutValues();
}

function delItem(item, descr, qtd){
    if(qtd == "" || qtd == null){
        qtd = 1;   
    }
    if(confirm("Are you sure you want to remove "+qtd+"x "+descr+" from your cart?")){
        var ci = new CartItem(item, qtd);
        x_acDelItem(item,qtd,null);
        location.reload();
    }
}

function delItemByIndex(index, descr, qtd){
    if(qtd == "" || qtd == null){
        qtd = 1;   
    }
    if(confirm("Are you sure you want to remove "+qtd+"x "+descr+" from your cart?")){
        x_acDelByIndex(index,reloadMe);
        updateNumInCart(-1*qtd);
    }
}

function qtyByIndex(index, qtd, recompute){
    if(qtd == "" || qtd == null){
        qtd = 1;
    }
    if(recompute == "" || recompute == null){
        recompute = false;
    }
    if(isNaN(qtd) || qtd < 1 || qtd != Math.floor(qtd)){
        alert("Invalid quantity, please re-enter the desired quantity and try again.");
    }else{
        if(recompute){ // specifically for checkout.php
            //problem in here, amount doesn't get updated!
            var old_q = remDol(document.getElementById("cart_item_qty_"+index).innerHTML);
            var old_p = remDol(document.getElementById("cart_item_amount_"+index).innerHTML);
            var up = old_p/old_q;
            
            //alert("old_p: " +old_p);
            //alert("old_q: " +old_q);
            //alert("up: " +up);
            //alert("up formatted: " + remDol(usd(qtd*up)));
            
            old_qtd = document.getElementById("cart_item_qty_"+index).innerHTML;
            document.getElementById("cart_item_qty_"+index).innerHTML = qtd;
            updateNumInCart(qtd - old_qtd);
            document.getElementById("cart_item_amount_"+index).innerHTML = remDol2(usd(qtd*up));
            document.getElementById("subtotal").innerHTML = "Calculating...";
            subtotal_counter++;
            
            x_acQtyByIndex(index,qtd,getCheckoutValues2);
        }else{
            x_acQtyByIndex(index,qtd,reloadMe);
        }
    }
}

function qtyByIndexFromCheckout(index, qtd){
    qtyByIndex(index, qtd, true);
}
function reloadMe(){
    location.reload();
}

function infoItem(item, descr, qtd){
    location.href = "/info/" + item;
    return false;
}

function addItem(item, descr, qtd){
    if(qtd == "" || qtd == null){
        qtd = 1;   
    }
    if(isNaN(qtd) || qtd < 1 || qtd != Math.floor(qtd)){
        alert("Invalid quantity, please re-enter the desired quantity and try again.");
        return false;
    }
    if(srv_enable_cart_confirm){
        cnfm = confirm("Are you sure you want to remove "+qtd+"x "+descr+" from your cart?");
    }else{
        cnfm = true;
    }
    if(cnfm){
        x_acAddItem(item, qtd, addItem_cb);
        updateNumInCart(qtd);
        analyticsEvent("all", "shop", "add-to-cart", item, qtd);
	}
	return false;
}

function addItem_cb(){
    fade("CartItemAddedBanner");
}

function cart_noneOnSubmit(sbutton){
    sbutton.disabled = true;
    sbutton.form.submit();
    return true;
}

function cart_existOnSubmit(sbutton){
    sbutton.disabled = true;
    sbutton.form.submit();
    return true;
}

function cart_newOnSubmit(sbutton){
    sbutton.disabled = true;
    sbutton.form.submit();
    return true;
}

function alt_addressOnSubmit(sbutton){
	sbutton.disabled = true;
    sbutton.form.submit();
	return true;
}

function commit_cart_existOnSubmit(sbutton){
	sbutton.disabled = true;
    sbutton.form.submit();
	return true;
}

function commit_cart_newOnSubmit(sbutton){
      sbutton.disabled = true;
    sbutton.form.submit();
      return true;
}

function commit_cart_noneOnSubmit(sbutton){
      sbutton.disabled = true;
    sbutton.form.submit();
      return true;
}

function giftOnSubmit(sbutton){
      sbutton.disabled = true;
    sbutton.form.submit();
      return true;
}

function notesOnSubmit(sbutton){
      sbutton.disabled = true;
    sbutton.form.submit();
      return true;
}

function infoOnSubmit(sbutton){
      sbutton.disabled = true;
    sbutton.form.submit();
      return true;
}

function commit_infoOnSubmit(sbutton){
      sbutton.disabled = true;
    sbutton.form.submit();
      return true;
}

