﻿
var returnCountyID = "";
var returnCountyName = "";
var returnCityID = "";
var returnCityName = "";
var returnStateCode = "";
var returnZipCode = "";
var returnIjnQuoteID = "";
var latestRequestStep = "";


YAHOO.util.Event.onDOMReady(
    function() {
        returnCountyID = document.getElementById(__countyid).value;
        returnCountyName = document.getElementById(__countyname).value;
        returnCityID = document.getElementById(__cityid).value;
        returnCityName = document.getElementById(__cityname).value;
        returnStateCode = document.getElementById(__statecode).value;
        returnZipCode = document.getElementById(__zipcode).value;
    }
);

function summary() {
    var Dom = YAHOO.util.Dom;
    //document.getElementById(_lblShippingPrice).innerHTML = "0";
    //document.getElementById(_lblShippingOptionPrice).innerHTML = "0";

    //summary
    var subtotal = 0;
    var subtotal_nogift = 0;
    var insurance = 0;
    var appraisal = 0;
    var insurancefactor, appraisalfactor;
    var objs = Dom.getElementsByClassName("total");
    var dis = Dom.getElementsByClassName("discount");
    var alive = Dom.getElementsByClassName("isalive");
    for (var i = 0; i < objs.length; i++) {
        if (Dom.get('row_' + i).style.display != "none" && alive[i].value == "True") {
            subtotal += (tryParseFloat(objs[i]));
            
            if(Dom.get("producttype_" + i).value != "G"){
                subtotal_nogift += (tryParseFloat(objs[i]));
            }
            
            if (Dom.get("divinsurance_" + i).style.display != "none" && Dom.get("cbxinsurance_" + i).checked) {
                insurance += (parseFloat(Dom.get("premium_" + i).value) + parseFloat(Dom.get("conveniencefee_" + i).value));
            }
            if (Dom.get("divappraisal_" + i).style.display != "none" && Dom.get("cbxappraisal_" + i).checked) {
                appraisal += parseFloat(_appraisalamount) * parseFloat(Dom.get("quantity_" + i).value);
            }
        }
    }

    var couponamount = parseFloat(Dom.get(__couponAmount).value);
    var promotion = couponamount;
    var info = document.getElementById(_lblPromotionInfo).innerHTML;
    if (info != "") {
        promotion = subtotal * promotion / 100;
        document.getElementById(_lblPromotion).innerHTML = addCommas(promotion.toFixed(2));
    }

    var giftCertificate = tryParseFloat(document.getElementById(_lblGiftCertificate));
    var saleTax = getSaleTax();
    var totalSaleTax = (subtotal_nogift) * saleTax / 100;
    var total = subtotal + insurance - promotion - giftCertificate + totalSaleTax; //subtotal - promotion + totalSaleTax;

    //set text
    document.getElementById(_lblSubTotal).innerHTML = addCommas(subtotal.toFixed(2));
    document.getElementById(_lblSaleTax).innerHTML = addCommas(saleTax.toFixed(2));
    document.getElementById(_lblSaleTaxTotal).innerHTML = addCommas(totalSaleTax.toFixed(2));

    //get shipping options
    var messages = _optionJSON;
    var shippingOptions = document.getElementById(_ddlShippingOptions);
    var curShippingID = shippingOptions.options[shippingOptions.selectedIndex].id;
    
    for (i = shippingOptions.length - 1; i >= 0; i--) {
        shippingOptions.options[i] = null;
    }
    var op = document.createElement('option');
    op.text = 'Select Shipping';
    op.value = 0;
    shippingOptions.options.add(op);

//    var messages = _optionJSON;
    var ddlCountry = Dom.get(_ddlCountry);
    var countryCode = ddlCountry.options[ddlCountry.selectedIndex].value;
    var level = 1;
    var lowerbound, upperbound, m;
    var matchLevel = false;
    
    //check higest free level
    for (var i = 0; i < messages.length; i++) {
        m = messages[i];
        lowerbound = parseFloat(m.freefrom);
        upperbound = parseFloat(m.freeto);
        
        if (subtotal >= lowerbound && subtotal <= upperbound) {
            level = m.level;
            matchLevel = true;
            break;
        }
    }
    
    var foundFirstFree = false;
    var freeShippingID = 0;
    for (var i = 0; i < messages.length; i++) {
        m = messages[i]

        if (level == m.level) {
            op = document.createElement('option');
            
            if(matchLevel){
                op.text = m.shippingname + " - $" + getUpgradePrice(level, m.shippingprice);
                op.value = getUpgradePrice(level, m.shippingprice);
            }
            else{
                op.text = m.shippingname + " - $" + m.shippingprice;
                op.value = m.shippingprice;
            }
            op.id = m.shippingoptionid;

            lowerbound = parseFloat(m.freefrom);
            upperbound = parseFloat(m.freeto);

            //document.getElementById(_lblFreeShipping).innerHTML = "Free " + m.shippingname;
            if (subtotal >= lowerbound && subtotal <= upperbound && m.isfree == 'True') {
                op.text = "Free " + m.shippingname;
                op.style.color = "red";
                op.value = "0";
                
                if(!foundFirstFree){
                    freeShippingID = m.shippingoptionid;
                    foundFirstFree = true;
                }
            }

            shippingOptions.options.add(op);
        } 
    } // for

    document.getElementById(_lblShippingOptionPrice).innerHTML = "0";
    
    //default free
    for(var i = 0; i < shippingOptions.options.length; i++){
        if(shippingOptions.options[i].id == freeShippingID){
            shippingOptions.selectedIndex = i;
            break;
        }
    }
    
    //set to current
    for(var i = 0; i < shippingOptions.options.length; i++){
        if(shippingOptions.options[i].id == curShippingID && curShippingID){
            shippingOptions.selectedIndex = i;
            break;
        }
    }

    var myShoppingPrice;
    if (shippingOptions.selectedIndex == 0 || shippingOptions.options[shippingOptions.selectedIndex].value == "0") {
        Dom.get("ShippingOptionPriceDollarSign").innerHTML = "";
        document.getElementById(_lblShippingOptionPrice).innerHTML = "";
        myShoppingPrice = 0;
    } else {
        Dom.get("ShippingOptionPriceDollarSign").innerHTML = "$";
        document.getElementById(_lblShippingOptionPrice).innerHTML = shippingOptions.options[shippingOptions.selectedIndex].value;
        myShoppingPrice = parseFloat(shippingOptions.options[shippingOptions.selectedIndex].value);
    }
        
   

    //insurance & appraisal
    if (_isfree_insurance) {
        insurancefactor = 0;
        Dom.get("insurancetotal").innerHTML = "0";
        Dom.get("freeinsurancetotal").innerHTML = "($" + addCommas(insurance) + ")";
    } else {
        insurancefactor = 1;
        Dom.get("insurancetotal").innerHTML = addCommas(insurance);
        Dom.get("freeinsurancetotal").innerHTML = "";
    }

    if (_isfree_appraisal) {
        appraisalfactor = 0;
        Dom.get("appraisaltotal").innerHTML = "0";
        Dom.get("freeappraisaltotal").innerHTML = "($" + addCommas(appraisal) + ")";
    } else {
        appraisalfactor = 1;
        Dom.get("appraisaltotal").innerHTML = addCommas(appraisal);
        Dom.get("freeappraisaltotal").innerHTML = "";
    }
    //plus shipping price
    var baseShippingPrice = 0; //tryParseFloat(document.getElementById(_lblShippingPrice));
    var shippingOption = myShoppingPrice //(document.getElementById(_lblShippingOptionPrice));
    total = subtotal + (insurance * appraisalfactor) + (appraisal * appraisalfactor) + totalSaleTax + baseShippingPrice + shippingOption - promotion;
    setLabelText(document.getElementById(_lblTotal), addCommas(total.toFixed(2)));



    var potentialPromotion = parseFloat(document.getElementById(__giftAmount).value);
    if (total < potentialPromotion) {
        document.getElementById(_lblGiftCertificate).innerHTML = addCommas(total.toFixed(2));
        document.getElementById(_lblGrandTotal).innerHTML = "0";
    } else {
        document.getElementById(_lblGiftCertificate).innerHTML = addCommas(potentialPromotion.toFixed(2));
        total = total - parseFloat(potentialPromotion);
        document.getElementById(_lblGrandTotal).innerHTML = addCommas(total.toFixed(2));
    }

    //display on/off insurance total
    if (insurance > 0) {
        Dom.get("tdinsurance").style.display = "";
    } else {
        Dom.get("tdinsurance").style.display = "none";
    }
    if (appraisal > 0) {
        Dom.get("tdappraisal").style.display = "";
    } else {
        Dom.get("tdappraisal").style.display = "none";
    }
}

function getUpgradePrice(level, shippingPrice)
{
    if(level == 1) return parseFloat(shippingPrice) - 8;
    if(level == 2) return parseFloat(shippingPrice) - 16;
    if(level == 3) return parseFloat(shippingPrice) - 20;
    return parseFloat(shippingPrice);
}

function calculatePrice(i) {
    var Dom = YAHOO.util.Dom;
    var quantity = YAHOO.util.Dom.get('quantity_' + i).value;
    var insurance_quantity = YAHOO.util.Dom.get('insurance_quantity_' + i).value;
    var unitprice = tryParseFloat(YAHOO.util.Dom.get('unitprice_' + i));
    var discount = tryParseFloat(YAHOO.util.Dom.get('discount_' + i));
    var newprice = quantity * (unitprice - discount);

    Dom.get('total_' + i).innerHTML = addCommas(newprice.toFixed(2));
    Dom.get('appraisal2_' + i).innerHTML = "$" + addCommas((parseFloat(_appraisalamount) * quantity).toFixed(2));

    //must to request new appraisal
    Dom.get("cbxinsurance_" + i).checked = false;
    if (_hasAppraisal_certificate) {
        if (unitprice >= 500) {
            Dom.get('linkappriasal_' + i).style.display = "";
            Dom.get('divlinkappriasal_' + i).style.display = "";
        }
        YAHOO.util.Dom.get('divappraisal_' + i).style.display = "none";

        //count insurnace
        var hasInsurance = false;
        for (var count = 0; count < _total_line_item; count++) {
            if (Dom.get("cbxinsurance_" + count).checked) {
                hasInsurance = true;
                break;
            }
        }

        if (hasInsurance == false) {
            Dom.get(_ddlState).disabled = false;
            Dom.get(_ddlCountry).disabled = false;

            //reset
            Dom.get(__zipcode).value = "";
            returnCityID = "";
            returnCityName = "";
            returnCountyID = "";
            returnCountyName = "";
        }
    }
}

function getSaleTax() {
    var ddlState = YAHOO.util.Dom.get(_ddlState);
    var saleTax = _saleTax;
    var taxState = _taxState
    var taxType = _taxType
    if ((taxType == "A") || (taxState == ddlState.options[ddlState.selectedIndex].value && taxType == "L")) {
        return parseFloat(saleTax);
    } else {
        return 0;
    }
    return 0;
}

function bindState(country) {
    var states = YAHOO.util.Dom.get(_ddlState);
    for (i = states.length - 1; i >= 0; i--) {
        states.options[i] = null;
    }

    var messages = _optionJSON;
    var op, m;
    var countryCode = country.options[country.selectedIndex].value;

    op = document.createElement('option');
    op.text = "Select State of Residence";
    op.value = "0";
    states.options.add(op);

    for (var i = 0; i < messages.length; i++) {
        m = messages[i];
        if (m.countrycode == countryCode) {
            op = document.createElement('option');
            op.text = m.statename;
            op.value = m.statecode;
            states.options.add(op);
        }
    }
    summary();
}

function resetState() {
    var states = YAHOO.util.Dom.get(_ddlState);
    for (i = states.length - 1; i >= 0; i--) {
        states.options[i] = null;
    }

    var messages = _stateJSON;
    var op, m;

    op = document.createElement('option');
    op.text = "Select State of Residence";
    op.value = "0";
    states.options.add(op);

    for (var i = 0; i < messages.length; i++) {
        m = messages[i];
        if (m.countrycode == "US") {
            op = document.createElement('option');
            op.text = m.statename;
            op.value = m.statecode;
            states.options.add(op);
        }
    }
}


function checkCertificate() {
    var Dom = YAHOO.util.Dom;
    var cert = YAHOO.util.Dom.get(_txtGiftCertificate).value;
    if (cert == "") return;

    YAHOO.util.Dom.setStyle("totalProgress", "display", "");
    YAHOO.util.Connect.asyncRequest(
                'get'
                , "AjaxStation.aspx?method=checkcertificate&certificate=" + cert + "&rnd=" + Math.random()
                , {
                    success: function(o) {
                        var msg = o.responseText.split('|');
                        var giftCertificate = YAHOO.util.Dom.get(_lblGiftCertificate);
                        var total = YAHOO.util.Dom.get(_lblTotal);
                        setLabelText(giftCertificate, parseFloat(msg[0]));
                        YAHOO.util.Dom.get(__giftAmount).value = msg[0];

                        if (msg[0] == "0") {
                            YAHOO.util.Dom.get(_txtGiftCertificate).value = "";
                            YAHOO.util.Dom.setStyle("tdgiftcertificate", "display", "none");
                        } else {
                            YAHOO.util.Dom.setStyle("tdgiftcertificate", "display", "");
                        }

                        summary();
                        Dom.get('responseText').innerHTML = msg[1];
                        Dom.get(_btnMessage).click();
                        YAHOO.util.Dom.setStyle("totalProgress", "display", "none");
                    }
                    , failure: function(o) {
                        YAHOO.util.Dom.setStyle("totalProgress", "display", "none");
                        YAHOO.util.Dom.setStyle("tdgiftcertificate", "display", "none");
                        alert(o.responseText);
                        document.location.reload(true);
                    }
                }
            );
}

function checkCoupon() {
    var Dom = YAHOO.util.Dom;
    var coupon = YAHOO.util.Dom.get(_txtCoupon).value;
    if (coupon == "") return;

    YAHOO.util.Dom.setStyle("totalProgress", "display", "");
    YAHOO.util.Connect.asyncRequest(
                'get'
                , "AjaxStation.aspx?method=checkcoupon&coupon=" + coupon + "&rnd=" + Math.random()
                , {
                    success: function(o) {
                        var msg = o.responseText.split('|');
                        var discount = YAHOO.util.Dom.get(_lblPromotion);
                        var total = YAHOO.util.Dom.get(_lblTotal);
                        var subtotal = YAHOO.util.Dom.get(_lblSubTotal);
                        var info = YAHOO.util.Dom.get(_lblPromotionInfo);
                        var amount = YAHOO.util.Dom.get(__couponAmount);

                        var discountVal = parseFloat(msg[0]);
                        amount.value = discountVal;

                        setLabelText(info, "");

                        setLabelText(discount, addCommas(discountVal.toFixed(2)));

                        if (msg[0] == "0") {
                            var txtcoupon = YAHOO.util.Dom.get(_txtCoupon);
                            txtcoupon.value = "";
                            YAHOO.util.Dom.setStyle("tdcoupon", "display", "none");
                        } else {
                            YAHOO.util.Dom.setStyle("tdcoupon", "display", "");
                        }

                        summary();
                        Dom.get('responseText').innerHTML = msg[1];
                        Dom.get(_btnMessage).click();
                        YAHOO.util.Dom.setStyle("totalProgress", "display", "none");
                    }
                    , failure: function(o) {
                        YAHOO.util.Dom.setStyle("totalProgress", "display", "none");
                        YAHOO.util.Dom.setStyle("tdcoupon", "display", "none");
                        alert(o.responseText);
                    }
                }
            );
}

function getInsurance(i, container) {
    if (document.getElementById("divinsurance_" + i).style.display != "none" && document.getElementById("cbxinsurance_" + i).checked) {
        return parseFloat(document.getElementById(container + i).value);
    } else {
        return 0;
    }
}

function getAppraisal(i) {
    if (document.getElementById("divappraisal_" + i).style.display != "none" && document.getElementById("cbxappraisal_" + i).checked) {
        return parseFloat(document.getElementById("appraisal_" + i).value);
    } else {
        return 0;
    }
}

function checkOut(obj) {
    var xml = "";
    var conf;
    var Dom = YAHOO.util.Dom;
    quans = YAHOO.util.Dom.getElementsByClassName("quantity");
    if (quans.length == 0) {
        conf = new YAHOO.widget.SimpleDialog(
                            "conf",
					         { width: "300px",
					             fixedcenter: true,
					             visible: false,
					             draggable: false,
					             modal: true,
					             close: false,
					             text: _checkoutNoProduct,
					             icon: YAHOO.widget.SimpleDialog.ICON_WARN,
					             constraintoviewport: true,
					             buttons: [{ text: "Ok", handler: function() { this.hide(); }, isDefault: true}]
					         });

        conf.setHeader("Alert");
        conf.render(document.body);
        conf.show();
        return;
    }

    conf = new YAHOO.widget.SimpleDialog(
                            "conf",
					         { width: "300px",
					             fixedcenter: true,
					             visible: false,
					             draggable: false,
					             modal: true,
					             close: false,
					             text: "Please Select State of Residence.",
					             icon: YAHOO.widget.SimpleDialog.ICON_WARN,
					             constraintoviewport: true,
					             buttons: [{ text: "Ok", handler: function() { this.hide(); YAHOO.util.Dom.get(_ddlState).focus(); }, isDefault: true}]
					         });

    var ddlState = YAHOO.util.Dom.get(_ddlState);
    if (ddlState.selectedIndex == 0) {
        conf.setHeader("Alert");
        conf.render(document.body);
        conf.show();
        return;
    }

    // shipping validate
    var ddlShippingOptions = YAHOO.util.Dom.get(_ddlShippingOptions);
    conf = new YAHOO.widget.SimpleDialog(
                            "conf",
					         { width: "300px",
					             fixedcenter: true,
					             visible: false,
					             draggable: false,
					             modal: true,
					             close: false,
					             text: "Please Select Shipping Option.",
					             icon: YAHOO.widget.SimpleDialog.ICON_WARN,
					             constraintoviewport: true,
					             buttons: [{ text: "Ok", handler: function() { this.hide(); YAHOO.util.Dom.get(_ddlShippingOptions).focus(); }, isDefault: true}]
					         });

    if (ddlShippingOptions.selectedIndex == 0) {
        conf.setHeader("Alert");
        conf.render(document.body);
        conf.show();
        return;
    }

    //waiting ..
    wait = new YAHOO.widget.Panel(
                        "wait",
                        { width: "240px",
                            fixedcenter: true,
                            close: false,
                            draggable: false,
                            zindex: 4,
                            modal: true,
                            visible: false
                        }
                    );

    wait.setHeader("Processing.. Please wait..");
    wait.setBody("<img src='pics/ajax-loader3.gif' title='loading..' />");
    wait.render(document.body);
    wait.show();

    var ddlCountry = YAHOO.util.Dom.get(_ddlCountry);

    var shippingOtpion = ddlShippingOptions.options[ddlShippingOptions.selectedIndex].text;
    var shippingOtpionID = ddlShippingOptions.options[ddlShippingOptions.selectedIndex].id;
//    if (ddlShippingOptions.selectedIndex > 0) {
//        shippingOtpion = ddlShippingOptions.options[ddlShippingOptions.selectedIndex].text
//    }

    var ids = YAHOO.util.Dom.getElementsByClassName("shoppingcartid");
    var pids = YAHOO.util.Dom.getElementsByClassName("productid");
	var objs = Dom.getElementsByClassName("total");
	
    for (i = 0; i < objs.length; i++) {
			if(Dom.get('row_' + i).style.display != "none"){
			//calculatePrice(i);
			xml += ids[i].value + ';' + YAHOO.util.Dom.get('quantity_' + i).value + ';' + pids[i].value + ';' + getInsurance(i, "premium_") + ';' + getInsurance(i, "conveniencefee_") + ';' + getAppraisal(i) + ';' + Dom.get("ijnquoteid_" + i).value + '|';
		}
    }

    var cert = YAHOO.util.Dom.get(_txtGiftCertificate).value;
    var coupon = YAHOO.util.Dom.get(_txtCoupon).value;
    YAHOO.util.Connect.asyncRequest(
                'get'
                , "AjaxStation.aspx?method=checkout&data="
                    + encodeURIComponent(xml)
                    + "&certificate=" + cert
                    + "&rnd=" + Math.random()
                    + '&countyid=' + encodeURIComponent(returnCountyID)
                    + '&countyName=' + encodeURIComponent(returnCountyName)
                    + '&cityid=' + encodeURIComponent(returnCityID)
                    + '&cityname=' + encodeURIComponent(returnCityName)
                    + '&zipcode=' + encodeURIComponent(Dom.get(__zipcode).value)
                , {
                    success: function(o) {
                        var msg = o.responseText;
                        var url = 'checkout.aspx'
                                + '?country=' + encodeURIComponent(ddlCountry.options[ddlCountry.selectedIndex].value)
                                + '&state=' + encodeURIComponent(ddlState.options[ddlState.selectedIndex].value)
                                + '&shippingoption=' + encodeURIComponent(shippingOtpion)
                                + '&shippingoptionid=' + shippingOtpionID
                                + '&certificate=' + encodeURIComponent(cert)
                                + '&coupon=' + encodeURIComponent(coupon)
                                + '&countyid=' + encodeURIComponent(returnCountyID)
                                + '&countyName=' + encodeURIComponent(returnCountyName)
                                + '&cityid=' + encodeURIComponent(returnCityID)
                                + '&cityname=' + encodeURIComponent(returnCityName)
                                + '&zipcode=' + encodeURIComponent(Dom.get(__zipcode).value)
                                + '&xuid=' + Math.random() + "_" + Math.random();
                        if (msg == "SUCCESS") {
                            document.location = url;
                        } else {
                            wait.hide();
                            conf = new YAHOO.widget.SimpleDialog(
                                        "conf",
					                     { width: "300px",
					                         fixedcenter: true,
					                         visible: false,
					                         draggable: false,
					                         modal: true,
					                         close: false,
					                         text: msg,
					                         icon: YAHOO.widget.SimpleDialog.ICON_ALARM,
					                         constraintoviewport: true,
					                         buttons: [{ text: "Ok", handler: function() { this.hide(); }, isDefault: true}]
					                     });
                            conf.setHeader("Warning");
                            conf.render(document.body);
                            conf.show();
                            return;
                        }
                    }
                    , failure: function(o) {
                        wait.hide();
                        //alert(o.responseText);
                        alert(_requestUnSuccesfull);
                    }
                }
            );
}


function shippingOptionChange(ddl) {
    var Dom = YAHOO.util.Dom;

    if (ddl.selectedIndex == 0 || ddl.options[ddl.selectedIndex].value == "0") {
        Dom.get("ShippingOptionPriceDollarSign").innerHTML = "";
        setLabelText(Dom.get(_lblShippingOptionPrice), "");
    }
    else {
        Dom.get("ShippingOptionPriceDollarSign").innerHTML = "$";
        setLabelText(Dom.get(_lblShippingOptionPrice), ddl.options[ddl.selectedIndex].value);
    }

    var subtotal = parseFloat(getLabelText(Dom.get(_lblSubTotal)));
    var shippingPrice = parseFloat(ddl.options[ddl.selectedIndex].value);
    var shippingOptionPrice = 0;
    var saleTaxTotal = parseFloat(getLabelText(Dom.get(_lblSaleTaxTotal)));
    var promotion = parseFloat(getLabelText(Dom.get(_lblPromotion)));

    
    var total = subtotal + shippingPrice + shippingOptionPrice + saleTaxTotal - promotion;
    setLabelText(Dom.get(_lblTotal), addCommas(total.toFixed(2)));

    var potentialPromotion = parseFloat(Dom.get(__giftAmount).value);
    if (total < potentialPromotion) {
        setLabelText(Dom.get(_lblGiftCertificate), addCommas(total.toFixed(2)));
        setLabelText(Dom.get(_lblGrandTotal), "0");
    } else {
        setLabelText(Dom.get(_lblGiftCertificate), addCommas(potentialPromotion.toFixed(2)));
        total = total - parseFloat(potentialPromotion);
        setLabelText(Dom.get(_lblGrandTotal), addCommas(total.toFixed(2)));
    }
}

function addToWishList(obj, shoppingcartid, producttype) {
    if (YAHOO.util.Dom.get(__wishlishName).value == '') {
        document.location.href = 'WishList.aspx';
    }
    else {
        YAHOO.util.Dom.get('cartprogress').style.display = '';
        YAHOO.util.Connect.asyncRequest(
                    'get'
                    , "AjaxStation.aspx?method=addtowishlist&shoppingcartid=" + shoppingcartid + '&producttype=' + producttype + '&rnd=' + Math.random()
                    , {
                        success: function(o) {
                            if (o.responseText == 'SUCCESS')
                                document.location = "WishList.aspx";
                            else if (o.responseText == 'SOLDOUT')
                                document.location = "SoldOut.aspx";
                            else {
                                alert(o.responseText);
                            }
                            YAHOO.util.Dom.get('cartprogress').style.display = 'none'
                        }
                        , failure: function(o) {
                            alert(o.responseText);
                            YAHOO.util.Dom.get('cartprogress').style.display = 'none'
                        }
                    }
                );
    }
}

function removeFromCart(id, shoppingcartid, productid) {
    var handleYes = function() {
        this.hide();

        YAHOO.util.Dom.get('cartprogress').style.display = '';


        YAHOO.util.Connect.asyncRequest(
                    'get'
                    , "AjaxStation.aspx?method=removefromcart&shoppingcartid=" + shoppingcartid + "&productid=" + productid + '&rnd=' + Math.random()
                    , {
                        success: function(o) {
                            YAHOO.util.Dom.get('row_' + id).style.display = 'none';
                            YAHOO.util.Dom.get('quantity_' + id).className = '';
                            summary();
                        }
                        , failure: function(o) { alert(o.responseText); document.location.reload(true); }
                    }
                );

        window.setTimeout(
                    function() {
                        YAHOO.util.Dom.get('cartprogress').style.display = 'none';
                    }
                    , 500
                );
    };

    var handleNo = function() {
        this.hide();
    };

    var conf = new YAHOO.widget.SimpleDialog(
                            "conf",
					         { width: "300px",
					             fixedcenter: true,
					             visible: false,
					             draggable: false,
					             modal: true,
					             close: false,
					             text: "Are you sure you want to remove this item from shopping cart?",
					             icon: YAHOO.widget.SimpleDialog.ICON_WARN,
					             constraintoviewport: true,
					             buttons: [{ text: "Yes", handler: handleYes, isDefault: true }, { text: "No", handler: handleNo}]
					         });

    conf.setHeader("Confirm Remove");
    conf.render(document.body);
    conf.show();
}


function popupEmail(productid, producttype) {
    var Dom = YAHOO.util.Dom;
    Dom.get(_btnEmailFriend).click();
    Dom.get(__productID).value = productid;
    Dom.get(__productType).value = producttype;
}


function email() {
    var Dom = YAHOO.util.Dom;
    var from = Dom.get(_txtEmail);
    var to = Dom.get(_txtTo);
    var vldFrom = Dom.get('vldFrom');
    var vldTo = Dom.get('vldTo');
    var isValid = true;

    //validate required
    if (from.value == "") {
        setLabelText(vldFrom, "(*)");
        isValid = false;
    }
    if (to.value == "") {
        setLabelText(vldTo, "(*)");
        isValid = false;
    }

    if (isValid == false) {
        return;
    }
    setLabelText(vldFrom, "");
    setLabelText(vldTo, "");

    //validate required;
    var regexp = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
    if (regexp.test(from.value) == false) {
        setLabelText(vldFrom, "(*invalid email format)");
        return;
    }

    Dom.setStyle("email-loading", "display", "");
    var data = "to=" + encodeURIComponent(to.value)
                     + "&from=" + encodeURIComponent(from.value)
                     + "&message=" + encodeURIComponent(Dom.get(_txtMessage).value)
                     + "&name=" + encodeURIComponent(Dom.get(_txtName).value)
                     + "&productid=" + Dom.get(__productID).value
                     + "&producttype=" + Dom.get(__productType).value;

    YAHOO.util.Connect.asyncRequest(
                'post'
                , "AjaxStation.aspx?method=email&rnd=" + Math.random()
                , {
                    success: function(o) {
                        var msg = o.responseText;
                        if (msg == "SUCCESS") {
                            Dom.setStyle("email-loading", "display", "none");
                            Dom.setStyle(_lblMessage, "display", "block");
                            setLabelText(Dom.get(_lblMessage), "Email successfully sent to " + to.value);
                        } else {
                            var conf = new YAHOO.widget.SimpleDialog(
                            "conf",
					         { width: "300px",
					             fixedcenter: true,
					             visible: false,
					             draggable: false,
					             modal: true,
					             close: false,
					             text: msg,
					             icon: YAHOO.widget.SimpleDialog.ICON_WARN,
					             constraintoviewport: true,
					             buttons: [{ text: "Ok", handler: function() { this.hide(); }, isDefault: true}]
					         });

                            conf.setHeader("Error");
                            conf.render(document.body);
                            conf.show();
                            Dom.setStyle("email-loading", "display", "none");
                        }
                    }
                    , failure: function(o) {
                        alert(o.responseText);
                        Dom.setStyle("email-loading", "display", "none");
                    }
                }
                , data
            );
}

function imgbtnCancel_Click() {
    var Dom = YAHOO.util.Dom;
    var imgbtnCancel = Dom.get(_imgBtnCancel);
    imgbtnCancel.click();
}

function popupInsurance(cartid, lineitem) {
    if (Sys.Application._initialized) {
        var Dom = YAHOO.util.Dom;
        Dom.get(__ijnLineItem).value = lineitem;
        Dom.get(__ijnShoppingCartID).value = cartid;
        Dom.get("tdzipcode").style.display = "";
        Dom.get(_txtZipCode).value = "";
        Dom.get("tdcity").style.display = "none";
        Dom.get("tdcounty").style.display = "none";
        Dom.get(_btnIjnRequest).click();

        var ddlCounty = Dom.get(_ddlCounty);
        var ddlCity = Dom.get(_ddlCity);

        //reset county and city
        for (var count = ddlCounty.length - 1; count >= 0; count--) {
            ddlCounty.options[count] = null;
        }

        //reset city
        for (var count = ddlCity.length - 1; count >= 0; count--) {
            ddlCity.options[count] = null;
        }

        //reset questionnair
        Dom.get("questionnairmessage").innerHTML = "";
        Dom.setStyle("btnQuestionNairClose", "display", "none");
        Dom.setStyle("btnQuestionNairSubmit", "display", "");
        Dom.setStyle("questionnairzone2", "display", "none");
        Dom.setStyle("questionnairzone1", "display", "");
        Dom.get("no1").checked = false;
        Dom.get("no2").checked = false;
        Dom.get("no3").checked = false;
        Dom.get("no4").checked = false;
        Dom.get("no5").checked = false;
        Dom.get("yes1").checked = false;
        Dom.get("yes2").checked = false;
        Dom.get("yes3").checked = false;
        Dom.get("yes4").checked = false;
        Dom.get("yes5").checked = false;
        Dom.get("vq1").style.display = "none";
        Dom.get("vq2").style.display = "none";
        Dom.get("vq3").style.display = "none";
        Dom.get("vq4").style.display = "none";
        Dom.get("vq5").style.display = "none";
        Dom.get("questionnair").disabled = "";
        Dom.get(_cbxAppraisal).checked = false;

        Dom.get("questionnair").style.display = "";
        Dom.get("tbgemshieldinfo").style.display = "";
        Dom.get("tddisclosure").style.display = "none";
        Dom.get("vagree").style.display = "none";
        Dom.get("vagree2").style.display = "none";
        Dom.get("radagree").checked = false;
        Dom.get("raddisagree").checked = false;
        Dom.get("radagree2").checked = false;
        Dom.get("raddisagree2").checked = false;
    }
}

function popupAppraisal(link, lineitem) {
    var Dom = YAHOO.util.Dom;
    link.style.display = 'none';
    Dom.get("divlinkappriasal_" + lineitem).style.display = "none";
    Dom.get("cbxappraisal_" + lineitem).checked = false;
    Dom.get("appraisalctv_" + lineitem).style.display = "none";
    Dom.get("divappraisal_" + lineitem).style.display = "";
}

function ijnGetRates() {
    var Dom = YAHOO.util.Dom;

    //validate required
    if (Dom.get(_txtZipCode).value == "") {
        Dom.get("vzipcode").style.display = "";
        return;
    } else {
        Dom.get("vzipcode").style.display = "none";
    }

    var loader = Dom.get("requestrate-loader");
    var loader2 = Dom.get("requestrate-loader2");
    var loader3 = Dom.get("requestrate-loader3");
    var i = Dom.get(__ijnLineItem).value;
    var quantity = Dom.get("quantity_" + i).value;
    var ddlCounty = document.getElementById(_ddlCounty);
    var ddlCity = document.getElementById(_ddlCity);
    var selectedCounty = "";
    var selectedCountyName = "";
    var selectedCity = "";
    var premium = Dom.get("premium");
    var conveniencefee = Dom.get("conveniencefee");

    Dom.get("insurance_quantity_" + i).value = quantity;
    loader.style.display = "";
    loader2.style.display = "";
    loader3.style.display = "";
    returnIjnQuoteID = "";
    
    //set city
    if (ddlCity.selectedIndex >= 0) {
        selectedCity = ddlCity.options[ddlCity.selectedIndex].value;
    }

    //set county
    if (ddlCounty.selectedIndex >= 0) {
        selectedCounty = ddlCounty.options[ddlCounty.selectedIndex].value;
        selectedCountyName = ddlCounty.options[ddlCounty.selectedIndex].text;
    }

    YAHOO.util.Connect.asyncRequest(
                'get'
                , "AjaxStation.aspx?method=ijnrequest&shoppingcartid="
                    + Dom.get(__ijnShoppingCartID).value
                    + "&quantity=" + quantity
                    + "&city=" + selectedCity
                    + "&countyid=" + selectedCounty
                    + "&countyname=" + selectedCountyName
                    + "&zipcode=" + Dom.get(_txtZipCode).value
                    + "&rnd=" + Math.random()
                , {
                    success: function(o) {
                        var val = o.responseText.split('|');

                        if (val[0] == "SUCCESS") {
                            Dom.get(_btnIjnRequestCancel).click();
                            Dom.get(_btnIjn2).click();

                            if (latestRequestStep != "MULTICITY") {
                                latestRequestStep = "SUCCESS";
                            }

                            premium.value = val[1];
                            conveniencefee.value = val[2];
                            returnCountyID = val[3];
                            returnCountyName = val[4];
                            returnStateCode = val[5];
                            returnIjnQuoteID = val[6]; //convert # back to |
                            Dom.get("insuranceamount").innerHTML = addCommas((parseFloat(val[1]) + parseFloat(val[2])).toFixed(2));
                            Dom.get("questionNairAppraisal").innerHTML = addCommas(parseFloat(_appraisal_certificate_amount) * parseFloat(quantity));
                        } else if (val[0] == "MULTICITY") {
                            latestRequestStep = "MULTICITY";
                            //bind counties
                            Dom.get("tdzipcode").style.display = "none";
                            Dom.get("tdcity").style.display = "";
                            Dom.get("tdcounty").style.display = "none";

                            var cityList = val[1].split(';');
                            var op = document.createElement('option');
                            for (var count = 0; count < cityList.length; count++) {
                                var cityVal = cityList[count].split(':');
                                if (cityList[count] != "") {
                                    op = document.createElement('option');
                                    op.text = cityVal[0];
                                    op.value = cityVal[1];
                                    ddlCity.options.add(op);
                                }
                            }
                        } else if (val[0] == "MULTICOUNTY") {
                            //pickup city
                            if (latestRequestStep != "MULTICITY") {
                                latestRequestStep = "MULTICOUNTY";
                            }

                            //bind counties
                            Dom.get("tdzipcode").style.display = "none";
                            Dom.get("tdcity").style.display = "none";
                            Dom.get("tdcounty").style.display = "";

                            var countyList = val[1].split(';');
                            var op = document.createElement('option');
                            for (var count = 0; count < countyList.length; count++) {
                                var countyVal = countyList[count].split(':');
                                if (countyList[count] != "") {
                                    op = document.createElement('option');
                                    op.text = countyVal[0];
                                    op.value = countyVal[1];
                                    ddlCounty.options.add(op);
                                }
                            }
                        } else {
                            latestRequestStep = "FAILURE";

                            Dom.get(_txtZipCode).value == "";
                            Dom.get(_btnIjnRequestCancel).click();
                            var notify = new YAHOO.widget.SimpleDialog(
                                    "notify",
					                 { width: "300px",
					                     fixedcenter: true,
					                     visible: false,
					                     draggable: false,
					                     modal: true,
					                     close: false,
					                     text: val[1],
					                     icon: YAHOO.widget.SimpleDialog.ICON_WARN,
					                     constraintoviewport: true,
					                     buttons: [{ text: "Ok", handler: function() { this.hide(); }, isDefault: true}]
					                 });

                            notify.setHeader("Warning");
                            notify.render(document.body);
                            notify.show();
                        }
                        loader.style.display = "none";
                        loader2.style.display = "none";
                        loader3.style.display = "none";
                    }
                    , failure: function(o) {
                        alert(o.responseText);
                        Dom.get(_txtZipCode).value == "";
                        loader.style.display = "none";
                        loader2.style.display = "none";
                        loader3.style.display = "none";
                    }
                }
            );
}

function QuestionNairSubmit() {
    var Dom = YAHOO.util.Dom;
    var validate = true;

    /*
    if (Dom.get("tddisclosure").style.display == "none") {
        Dom.get("questionnair").style.display = "none";
        Dom.get("tddisclosure").style.display = "";
        return;
    }

    if (Dom.get("raddisagree").checked) {
        QuestionNairClose();
        return;
    }

    if (Dom.get("radagree").checked == false && Dom.get("raddisagree").checked == false) {
        Dom.get("vagree").style.display = "";
        return;
    }*/

    //validate question
    if (!Dom.get("yes1").checked && !Dom.get("no1").checked) { validate = false; Dom.get("vq1").style.display = ""; } else { Dom.get("vq1").style.display = "none"; }
    if (!Dom.get("yes2").checked && !Dom.get("no2").checked) { validate = false; Dom.get("vq2").style.display = ""; } else { Dom.get("vq2").style.display = "none"; }
    if (!Dom.get("yes3").checked && !Dom.get("no3").checked) { validate = false; Dom.get("vq3").style.display = ""; } else { Dom.get("vq3").style.display = "none"; }
    if (!Dom.get("yes4").checked && !Dom.get("no4").checked) { validate = false; Dom.get("vq4").style.display = ""; } else { Dom.get("vq4").style.display = "none"; }
    if (!Dom.get("yes5").checked && !Dom.get("no5").checked) { validate = false; Dom.get("vq5").style.display = ""; } else { Dom.get("vq5").style.display = "none"; }

    
    
    if (validate) {
        if (Dom.get("no1").checked && Dom.get("no2").checked && Dom.get("no3").checked && Dom.get("no4").checked && Dom.get("no5").checked) {
            
            Dom.get("tddisclosure").style.display = "";
            Dom.get("questionnair").style.display = "none";
            
            Dom.get("questionnairmessage").innerHTML = "";
            Dom.setStyle("questionnairzone2", "display", "");
            Dom.setStyle("questionnairzone1", "display", "none");

            var i = Dom.get(__ijnLineItem).value;
            var quantity = YAHOO.util.Dom.get('quantity_' + i).value;
            var unitprice = tryParseFloat(YAHOO.util.Dom.get('unitprice_' + i));
            var discount = tryParseFloat(YAHOO.util.Dom.get('discount_' + i));
            var newprice = quantity * (unitprice + discount);

            Dom.get("questionNairProductPrice").innerHTML = "$" + addCommas(newprice.toFixed(2));
            Dom.get("questionNairInsurance").innerHTML = "$" + addCommas(Dom.get("insuranceamount").innerHTML);
            Dom.get("cbxinsurance_" + i).checked = true;

            //on/off line stoke
            if (_isfree_insurance) Dom.get("questionNairInsurance").style.textDecoration = "line-through"; else Dom.get("questionNairInsurance").style.textDecoration = "";
            if (_isfree_appraisal) Dom.get("questionNairAppraisal").style.textDecoration = "line-through"; else Dom.get("questionNairAppraisal").style.textDecoration = "";
        }
        else {
            Dom.get("questionnair").disabled = "true";
            Dom.get("tbgemshieldinfo").style.display = "none";
            Dom.get("questionnairmessage").innerHTML = "We are unable to process your request for insurance at this time, please contact Gemshield at 866-207-9482 or gemshield@ijb-usa.com to have your policy submission personally reviewed and underwritten.";
            Dom.setStyle("btnQuestionNairClose", "display", "");
            Dom.setStyle("btnQuestionNairSubmit", "display", "none");
            Dom.setStyle("questionnairzone2", "display", "none");
            Dom.setStyle("questionnairzone1", "display", "");
        }
    }
}

function addInsuranceToCart() {
    var Dom = YAHOO.util.Dom;

    //validate
    var testValidate = true;
    if (Dom.get("raddisagree").checked || Dom.get("raddisagree2").checked) {
        QuestionNairClose();
        return;
    }

    if (Dom.get("radagree2").checked == false && Dom.get("raddisagree2").checked == false) {
        Dom.get("vagree2").style.display = "";
        //document.location = "#agreement";
        testValidate = false; ;
    } else {
        Dom.get("vagree2").style.display = "none";
    }

    if (Dom.get("radagree").checked == false && Dom.get("raddisagree").checked == false) {
        Dom.get("vagree").style.display = "";
        testValidate = false; ;
    } else {
        Dom.get("vagree").style.display = "none";
    }

    if (testValidate == false) return;
    //end validate
    
    var default_cityid = Dom.get(__cityid).value;
    var default_countyid = Dom.get(__countyid).value;
    var default_zipcode = Dom.get(__zipcode).value;
    var ddlCounty = document.getElementById(_ddlCounty);
    var ddlCity = document.getElementById(_ddlCity);
    var selectedCounty = "";
    var selectedCountyName = "";
    var selectedCity = "";
    var selectedCityName = "";
    var selectZipCode = Dom.get(_txtZipCode).value
    var i = Dom.get(__ijnLineItem).value;

    if (ddlCity.selectedIndex >= 0) {
        selectedCity = ddlCity.options[ddlCity.selectedIndex].value;
        selectedCityName = ddlCity.options[ddlCity.selectedIndex].text;
    }
    
    if (ddlCounty.selectedIndex >= 0) {
        selectedCounty = ddlCounty.options[ddlCounty.selectedIndex].value;
        selectedCountyName = ddlCounty.options[ddlCounty.selectedIndex].text;
    } else {
        selectedCounty = returnCountyID;
        selectedCountyName = returnCountyName;
    }


    function doAddInsuranceToCart() {
        //set county
        Dom.get(__cityid).value = selectedCity;
        Dom.get(__countyid).value = selectedCounty;
        Dom.get(__zipcode).value = selectZipCode;

        returnCityID = selectedCity;
        returnCityName = selectedCityName;

        //set appearance
        Dom.get("divinsurance_" + i).style.display = "";
        Dom.get("insurancectv_" + i).style.display = "";
        Dom.get("insurance_" + i).innerHTML = "$" + Dom.get("insuranceamount").innerHTML;
        Dom.get("premium_" + i).value = Dom.get("premium").value;
        Dom.get("conveniencefee_" + i).value = Dom.get("conveniencefee").value;
        Dom.get("ijnquoteid_" + i).value = returnIjnQuoteID;

        //also country
        var ddlCountry = Dom.get(_ddlCountry);
        var ddlState = Dom.get(_ddlState);

        //bind US
        if (ddlCountry.options[ddlCountry.selectedIndex].value == "CA") resetState();
        
        ddlCountry.selectedIndex = 0;
        ddlCountry.disabled = true;
        
        
        //set state and disable
        for (var count = 0; count < ddlState.options.length; count++) {
            if (returnStateCode == ddlState.options[count].value) {
                ddlState.selectedIndex = count;
                ddlState.disabled = true;
                break;
            }
        }

       

        var ddlCity = Dom.get(_ddlCity);

        var cbx = Dom.get(_cbxAppraisal);
        if (cbx.checked) {
            Dom.get("cbxappraisal_" + i).checked = true;
            Dom.get("appraisal_" + i).value = parseFloat(_appraisal_certificate_amount) * parseFloat(Dom.get("quantity_" + i).value);
            Dom.get("appraisal2_" + i).innerHTML = "$" + addCommas((parseFloat(_appraisal_certificate_amount) * parseFloat(Dom.get("quantity_" + i).value)).toFixed(2));

            Dom.get("linkappriasal_" + i).style.display = "none";
            Dom.get("divlinkappriasal_" + i).style.display = "none";
            Dom.get("divappraisal_" + i).style.display = "";
            Dom.get("appraisalctv_" + i).style.display = "";
        }
        countAppraisal();
    }

    var handleNo = function() {
        this.hide();
        QuestionNairClose();
    };

    var handleYes = function() {
        this.hide();
        doAddInsuranceToCart();

        //discard item
        for (var discartindex = 0; discartindex < _total_line_item; discartindex++) {
            if (discartindex != i) {
                Dom.get("cbxinsurance_" + discartindex).checked = false;
                Dom.get("divinsurance_" + discartindex).style.display = "none";
            }
        }
        summary();
    };

    if ((default_countyid != "" || default_cityid != "") && (selectedCity != default_cityid || selectedCounty != default_countyid || default_zipcode != selectZipCode)) {
        var conf = new YAHOO.widget.SimpleDialog(
                            "conf",
					         { width: "300px",
					             fixedcenter: true,
					             visible: false,
					             draggable: false,
					             modal: true,
					             close: false,
					             text: "You selected difference insurance location, Do you want to discard previous insurance items?",
					             icon: YAHOO.widget.SimpleDialog.ICON_WARN,
					             constraintoviewport: true,
					             buttons: [{ text: "Yes", handler: handleYes, isDefault: true }, { text: "No", handler: handleNo}]
					         });

        conf.setHeader("Confirm Remove");
        conf.render(document.body);
        conf.show();
        QuestionNairClose();
    } else {
        doAddInsuranceToCart();
        summary();
        QuestionNairClose();
    }
}

function QuestionNairClose() {
    var Dom = YAHOO.util.Dom;
    Dom.get(_btnIjn2Cancel).click();
}

function visibleInsurance(cbx, i) {
    var Dom = YAHOO.util.Dom;
    var ddlState = Dom.get(_ddlState);
    var ddlCountry = Dom.get(_ddlCountry);

    if (cbx.checked) {
        Dom.get("insurancectv_" + i).style.display = "";

        //set state and disable
        if (ddlCountry.options[ddlCountry.selectedIndex].value == "CA") resetState();
        for (var count = 0; count < ddlState.options.length; count++) {
            if (returnStateCode == ddlState.options[count].value) {
                ddlState.selectedIndex = count;
                ddlState.disabled = true;
                break;
            }
        }

        //also country
        ddlCountry.selectedIndex = 0;
        ddlCountry.disabled = true;
    } else {
        Dom.get("insurancectv_" + i).style.display = "none";

        //count insurnace
        var hasInsurance = false;
        for (var count = 0; count < _total_line_item; count++) {
            if (Dom.get("cbxinsurance_" + count).checked) {
                hasInsurance = true;
                break;
            }
        }

        if (hasInsurance == false) {
            ddlCountry.disabled = false;
            ddlState.disabled = false;

            //reset
            Dom.get(__zipcode).value = "";
            returnCityID = "";
            returnCityName = "";
            returnCountyID = "";
            returnCountyName = "";
        }
    }
}

function visibleAppraisal(cbx, i) {
    var Dom = YAHOO.util.Dom;
    if (cbx.checked) {
        Dom.get("appraisal_" + i).value = parseFloat(Dom.get("quantity_" + i).value) * parseFloat(_appraisalamount);
        Dom.get("appraisalctv_" + i).style.display = "";
    } else {
        Dom.get("appraisal_" + i).value = "0";
        Dom.get("appraisalctv_" + i).style.display = "none";
    }
    countAppraisal();
}

function countAppraisal() {
    var count = 0;
    var Dom = YAHOO.util.Dom;
    var objs = Dom.getElementsByClassName("total");
    var alive = Dom.getElementsByClassName("isalive");
    for (var i = 0; i < objs.length; i++) {
        if (Dom.get('row_' + i).style.display != "none" && alive[i].value == "True") {
            if (Dom.get("divappraisal_" + i).style.display != "none" && Dom.get("cbxappraisal_" + i).checked) {
                count += 1;
            }
        }
    }

    document.getElementById("lblAppraisalCount").innerHTML = count;
}