﻿// JScript File
var scheduleTimeMsg = jMessage['SelectTime'];
var openCategorySetID = "";
var xmlRequester;

function trimString(str) {
    if(str != null) {
        var newStr = str.replace(/^\s*/, '').replace(/\s*$/, ''); 
        if(newStr != '') {
            return newStr;
        }
    }
    
    return null;
}

function redirect(targetURL) {
    
   
    
    window.location.replace(targetURL);


}



function submitSchedule(sender, form, cmd) {
    sender.disable;
    
    var fv = new FormValidator();
    
    fv.addValidator(new SelectValidator("scheduleTime", scheduleTimeMsg));
    
    
    if(fv.validate()) {
        form.cmd.value = cmd;
        form.submit();
    } else {
        sender.enable;
    }
}

function submitScheduleNow(sender, form, cmd) {
    form.cmd.value = cmd;
    form.submit();
}

function mouseOver(sender, className) {
    sender.className = className;
}

function mouseOut(sender, className) {
    sender.className = className;
}


function validateItemForm(sender, form) {
   
    sender.disabled = true;
    
    
    if(fv.validate()) {
        form.submit();
    } else {
        sender.disabled = false;
    }
    
}

function applyCoupon(form, cmd) {
    var fv = new FormValidator();
    
    fv.addValidator(new TextValidator('coupon', jMessage['CouponCodeIsRequired']));
    
    if(fv.validate()) {
        form.cmd.value = cmd;
        form.submit();
    }
}

function removeCoupon(form, cmd) {
    form.cmd.value = cmd;
    form.submit();
}

function validateFreeProudctForm(sender, form) {
    var fv = new FormValidator();
    
    fv.addValidator(new RadioValidator('freeProduct', jMessage['SelectAnItem']));
    
    if(fv.validate()) {
        form.submit();
    }
}





function toggleOrderType(senderID, amount, cartTotal, minDelivery) {
    var sender = document.getElementById(senderID);
    var locD = document.getElementById('locDiv');

    var distD = document.getElementById('distanceDiv');
    
    //window.alert(sender.checked);
    if(document.webForm.street == null){
            return;
    }
    
    if(sender != null && sender.checked) {
        var deliveryFee = document.getElementById('deliveryFee');
        var total = document.getElementById('cartTotal');
        var miniCartTotal = document.getElementById('miniCartTotal_pos');

        var locD = document.getElementById('locDiv');
        locD.innerHTML = "";

        //alert(document.getElementById('miniCartTotal_pos'));
        if(sender.value == 1 || sender.value == 2) {
	    //alert(minDelivery + " " + cartTotal + " " + parseFloat(cartTotal.split('$')[1]) );
	    
            deliveryFee.innerHTML = amount;
            total.innerHTML = cartTotal;
            if (miniCartTotal) {
                miniCartTotal.innerHTML = cartTotal;
            }
        }
        
        if(sender.value == 1) { // delivery order

            /*if (distD) {
                distD.style.display = 'block';
            }*/
            
            
            var t = 0;
            var ct;
            if(jMessage['decimalSign'] == ","){
                ct = cartTotal.toString().replace(".", "");
                ct = ct.replace(",", ".");
            }
            else{
                ct = cartTotal.toString().replace(",", "");
            }
            ct = ct.split(jMessage['MoneySign'])[1];
            ct = ct.replace(" ", "");
            t = parseFloat("" + ct);
            
	        if(minDelivery > t){
		        alert(jMessage['DeliveryMinNotMet'] + minDelivery + ".");
		        sender.checked = false;
		        return false;
		    }

		    //getDelFee();
		    document.webForm.street.disabled = false;
		    if (document.webForm.street2 != null) {
		        document.webForm.street2.disabled = false;
		    }
		    if (document.webForm.street3 != null) {
		        document.webForm.street3.disabled = false;
		    }

            document.webForm.street.disabled = false;
            document.webForm.city.disabled = false;
            document.webForm.state.disabled = false;
            document.webForm.zip.disabled = false;
            if(document.webForm.zipSub != null){
                document.webForm.zipSub.disabled = false;
            }
            document.webForm.crossStreet.disabled = false;
            
            //zip
            if(document.webForm.zip.options != null){
                overWriteStandardDeliveryFeeZip(document.webForm.zip.options[document.webForm.zip.selectedIndex].value);
            }
            else if(document.webForm.zipSub != null){
                
                //overWriteStandardDeliveryFeeZipSubRange(document.webForm.zip.value, document.webForm.zipSub.value);
            }
            
            if(delcheck){
                getDelFee();
            }
            
            togglePaymentMethod( getRadioValue(document.webForm.paymentMethod) );

        } else if (sender.value == 2) {
            //pick up
            //locD.innerHTML = "sdfdsf";
            getPKLocs();
            document.webForm.street.disabled = true;
            if (document.webForm.street2 != null) {
                document.webForm.street2.disabled = true;
            }
            if (document.webForm.street3 != null) {
                document.webForm.street3.disabled = true;
            }
            document.webForm.city.disabled = true;
            document.webForm.state.disabled = true;
            document.webForm.zip.disabled = true;
            if(document.webForm.zipSub != null){
                document.webForm.zipSub.disabled = true;
            }
            document.webForm.crossStreet.disabled = true;
            
            if(!cap){
                //alert("should close cc");
                togglePaymentMethod(2);
            }
        }
    }
    else {

        
        document.webForm.street.disabled = true;
        
        if (document.webForm.street2 != null) {
            document.webForm.street2.disabled = true;
        }
        if (document.webForm.street3 != null) {
            document.webForm.street3.disabled = true;
        }
        
        document.webForm.city.disabled = true;
        document.webForm.state.disabled = true;
        document.webForm.zip.disabled = true;
        if(document.webForm.zipSub != null){
                document.webForm.zipSub.disabled = true;
            }
        document.webForm.crossStreet.disabled = true;
        
        
    }
    
    
}

function validateDistance(){
    if(document.webForm.city.value != null && document.webForm.city.value != ""){
        return true;
    }
    window.alert(jMessage['DeliveryCityIsRequired']);
    document.getElementById('zipRangeDiv').innerHTML = jMessage['DeliveryCityIsRequired'];
    document.webForm.city.focus();
    return false;
   
}


function validateCityName(){
    if(document.webForm.city.value != null && document.webForm.city.value != ""){
        return true;
    }
    window.alert(jMessage['DeliveryCityIsRequired']);
    document.getElementById('zipRangeDiv').innerHTML = jMessage['DeliveryCityIsRequired'];
    document.webForm.city.focus();
    return false;
   
}

function validateZipCodeWithSub(){

        if(addDeliveryFeeBy == 'zipRange'){
                
                if(document.webForm.zip.value.search(zipCodeExp) == -1){
                    resetToStandardDeliveryFee();
                    document.getElementById('zipRangeDiv').innerHTML = jMessage['zipPartError'];
                    delcheck = false;
                    
                    window.alert(jMessage['zipPartError']);
                    document.webForm.zip.select();
                    return false;
                }
                
                if(document.webForm.zipSub.value.search(zipSubCodeExp) == -1){
                    resetToStandardDeliveryFee();
                    
                    document.getElementById('zipRangeDiv').innerHTML = jMessage['zipSubPartError'];
                    delcheck = false;
                    window.alert(jMessage['zipSubPartError']);
                    
                    document.webForm.zipSub.select();
                    return false;
                }
        }
                return true;
                
                
}

function validateSignup(sender, form, cmd) {
    sender.disabled = true;
    
    var fv = new FormValidator();
    
    fv.addValidator(new TextValidator('firstName', jMessage['FirstNameIsRequired']));
    fv.addValidator(new TextValidator('lastName', jMessage['LastNameIsRequired']));
    fv.addValidator(new TextValidator('phone', jMessage['PhoneNumberIsRequired']));
    fv.addValidator(new TextValidator('phoneAreaCode', jMessage['PhoneNumberIsRequired']));
    fv.addValidator(new EmailValidator('email', jMessage['EmailIsRequired'], jMessage['InvalidEmail']));
    fv.addValidator(new PasswordValidator('password1', 'password2', jMessage['PasswordIsRequired'], jMessage['PasswordMismatched']));
    
    if(fv.validate()) {
        form.cmd.value = cmd;
        form.submit();
    } else {
        sender.disabled = false;
    }
}

function validateLogin(sender, form, cmd) {
    sender.disabled = true;
    
    var fv = new FormValidator();
    
    fv.addValidator(new TextValidator('userName', jMessage['EmailIsRequired']));
    fv.addValidator(new TextValidator('password', jMessage['PasswordIsRequired']));
    
    if(fv.validate()) {
        form.cmd.value = cmd;
        form.submit();
    } else {
        sender.disabled = false;
    }
}

function validateAdminProductForm(sender, form){

    sender.disabled = true;
    var fv = new FormValidator();
    
    fv.addValidator(new TextValidator('name', jMessage['ProductNameIsRequired']));
    if(fv.validate()){
        form.submit();
    }else{
        sender.disabled = false;
    }


}

function validateAdminCategoryForm(sender, form){
    sender.disabled = true;
  
    var fv = new FormValidator();
    
    fv.addValidator(new TextValidator('name', jMessage['CategoryNameIsRequired']));
    if(fv.validate()){
        form.submit();
    }else{
        sender.disabled = false;
    }
}

function getRadioValue(radio) {
    for(var i = 0; i < radio.length; i++) {
        if(radio[i].checked) {
            return radio[i].value;
        }
    }
    
    return null;
}



function togglePaymentMethod(sender) {
    var form = document.webForm;
    var method = 2;
    method = getValueOfRadio(form.paymentMethod);
    if(method == ""){
        if(sender.value){
            method = sender.value;
        }
        else{
            method = sender;
        }
    }
    try {

        document.getElementById("div_cashChangeFor").style.display = "none";
        form.cashChangeFor.disabled = true;

    }
    catch (e) {

    }

    if (method == 1) { // credit card

        
        try{
            document.getElementById("div_cashChangeFor").style.display = "none";
            form.cashChangeFor.disabled = true;
        }
        catch (e) {

        }
        form.creditCard.disabled = false;
        form.expireMonth.disabled = false;
        form.expireYear.disabled = false;
        form.account.disabled = false;
        form.nameOnCard.disabled = false;

        try {
            form.ccZip.disabled = false;
        }
        catch (e) {
        }
        try {
            form.tips.disabled = false;
            form.tipsB0.disabled = false;
            form.tipsB1.disabled = false;
            form.tipsB2.disabled = false;
            form.tipsB3.disabled = false;
        }
        catch (e) {
            
        }
        
        
        if(form.ccStreet){
            form.ccStreet.disabled = false;
            form.ccCity.disabled = false;
            form.ccState.disabled = false;
            
        }
        else{
            form.securityCode.disabled = false;
        }
        
        toggleInfoReq(isCCInfoReq(form.creditCard.options[form.creditCard.selectedIndex].value));


    } else if (method == 2) {
        try{
        if (getRadioValue(form.orderType) == 1) {
                document.getElementById("div_cashChangeFor").style.display = "block";
                form.cashChangeFor.disabled = false;
                form.cashChangeFor.focus();
            }
        }
        catch (e) {

        }
        try{
        form.creditCard.disabled = true;
        form.expireMonth.disabled = true;
        form.expireYear.disabled = true;
        form.account.disabled = true;
        form.nameOnCard.disabled = true;

        try {
            form.ccZip.disabled = true;
        }
        catch (e) {
        }
        try {
            form.tips.disabled = true;
            form.tipsB0.disabled = true;
            form.tipsB1.disabled = true;
            form.tipsB2.disabled = true;
            form.tipsB3.disabled = true;
        }
        catch (e) {
            
        }
        
        if(form.ccStreet){
            form.ccStreet.disabled = true;
            form.ccCity.disabled = true;
            form.ccState.disabled = true;
            
        }
        else{
            form.securityCode.disabled = true;
            
        }
        }
        catch (e){
        
        }
    }
}

function setDivFocus(objDiv) {
    scroll(0, objDiv.offsetTop);
    objDiv.style.border = "solid 2px yellow";
    objDiv.style.padding = "5px 5px 5px 5px";
    
}

function validateCheckout(sender, form) {
    
    sender.disabled = true;
    
    var orderType = getRadioValue(form.orderType);
    
    var fv = new FormValidator();


    
    
    if (orderType == 2 && (document.webForm.sdl == null || document.webForm.sdl.value == "") ){
        sender.disabled = false;
       
        setDivFocus(document.getElementById('locDiv'));
        alert(jMessage['StoreLocationIsRequired']);
        return false;
    }
    
    
    fv.addValidator(new RadioValidator('orderType', jMessage['orderType']));
    fv.addValidator(new TextValidator('firstName', jMessage['FirstNameIsRequired']));
    fv.addValidator(new TextValidator('lastName', jMessage['LastNameIsRequired']));
    if (document.webForm.phoneAreaCode != null) {
        fv.addValidator(new TextValidator('phoneAreaCode', jMessage['PhoneAreaCodeIsRequired']));
        try {
            var ac = document.webForm.phoneAreaCode.value;

            if (ac.length > 5) {
                alert(jMessage['PhoneAreaCodeIsRequired']);
                document.webForm.phoneAreaCode.focus();
                sender.disabled = false;
                return false;
            }
        }
        catch (eex) {
            sender.disabled = false;
        }
    }
    fv.addValidator(new TextValidator('phone', jMessage['PhoneNumberIsRequired']));

   // if(trimString(form.email.value) != null) {
        fv.addValidator(new EmailValidator('email', jMessage['EmailRequired'], jMessage['InvalidEmail']));
  //  }
    
    if(orderType == 1) {
        fv.addValidator(new TextValidator('street', jMessage['DeliveryStreetIsRequired']));

        if (document.webForm.street2 != null) {
            fv.addValidator(new TextValidator('street2', jMessage['DeliveryStreet2IsRequired']));
        }

        fv.addValidator(new TextValidator('city', jMessage['DeliveryCityIsRequired']));
        fv.addValidator(new TextValidator('state', jMessage['DeliveryStateIsRequired']));
        fv.addValidator(new TextValidator('zip', jMessage['DeliveryZipCodeIsRequired']));

        if (addDeliveryFeeBy == 'distance' && !delcheck) {

            sender.disabled = false;
            alert(jMessage['checkDeliveryAddress']);
            document.webForm.street.select();
            return false;
        }
        
    }
    
    fv.addValidator(new RadioValidator('paymentMethod', jMessage['SelectPaymentMethod']));
    var paymentMethod = getRadioValue(form.paymentMethod);
    if(paymentMethod == 1) {
        fv.addValidator(new TextValidator('creditCard', jMessage['SelectCreditCard']));
        fv.addValidator(new TextValidator('expireMonth', jMessage['InvalidExpirationDate']));
        fv.addValidator(new TextValidator('expireYear', jMessage['InvalidExpirationDate']));
        fv.addValidator(new TextValidator('account', jMessage['CardNoIsRequired']));
        fv.addValidator(new TextValidator('nameOnCard', jMessage['NameOnCardIsRequired']));
        
        if(document.webForm.ccStreet){
            fv.addValidator(new TextValidator('ccStreet', jMessage['BillingStreetIsRequired']));
            fv.addValidator(new TextValidator('ccCity', jMessage['BillingCityIsRequired']));
            fv.addValidator(new TextValidator('ccState', jMessage['BillingStateIsRequired']));
            fv.addValidator(new TextValidator('ccZip', jMessage['BillingZipCodeIsRequired']));
        }
        else{
            fv.addValidator(new TextValidator('securityCode', jMessage['BillingSecurityCodeIsRequired']));
            if( document.webForm.ccZip  && document.getElementById('ccDateDiv2').style.display != 'none'){
                fv.addValidator(new TextValidator('ccZip', jMessage['BillingZipCodeIsRequired']));
            }
        }
    }


    if (orderType == 1 && document.webForm.zipSub != null) {
        if (!delcheck && addDeliveryFeeBy == 'zipRange') {
            sender.disabled = false;
            alert(jMessage['locationNotAvailableForDelivery']);
            document.webForm.zip.select();
            return false;
        }
        else if (!delcheck && addDeliveryFeeBy == 'city') {
            sender.disabled = false;
            alert(jMessage['locationNotAvailableForDelivery']);
            document.webForm.city.select();
            return false;
        }

    }

    
    
    if(fv.validate()) {
        form.submit();
    } else {
        sender.disabled = false;
    }
}


function getStateRate(stateAbbr){

    for(var i = 0; i < sdArray.length; i++){
    
        if(sdArray[i].stateAbbr == stateAbbr){
            return sdArray[i];
        }
    }

}

function getZipRate(zipCode){
    for(var i=0; i < dzcArray.length; i++){
        if(dzcArray[i].zipCode == zipCode){
            return dzcArray[i];
        }
    }
}


function getCityRate(cityName){
    for(var i=0; i < dcArray.length; i++){
        if(dcArray[i].cityName == cityName){
            return dcArray[i];
        }
    }
}

function getDistanceRate(distance) {
    for (var i = 0; i < ddcArray.length; i++) {
        if (ddcArray[i].distance == distance) {
            return ddcArray[i];
        }
    }
}


function overWriteStandardDeliveryFeeCity(cityName){
    
    var cityObj = null;
    try{
    cityObj = getCityRate(cityName);
    if(cityObj != null && cityObj.rate > 0.00){
        
        document.webForm.deliveryFeeField.value = cityObj.rate;
        document.getElementById('stateRateDiv').innerHTML = "";
        document.getElementById('deliveryFee').innerHTML = cityObj.rateLabel;
        document.getElementById('cartTotal').innerHTML = cityObj.cartTotalWithRate;
        /*alert(document.getElementById('miniCartTotal_pos'));
        if (document.getElementById('miniCartTotal_pos')) {
            document.getElementById('miniCartTotal_pos').innerHTML = cityObj.cartTotalWithRate;
        }
        */
    }
    else if(cityObj != null && cityObj.rate < 0.01){
        resetToStandardDeliveryFee();
    }
    }
    catch(ex){
        resetToStandardDeliveryFee();
    }
    
}

function getDelFee(){

    
    if (addDeliveryFeeBy == 'zipRange') {
        if (validateZipCodeWithSub()) {
            setDeliveryFeeWithSub();

        }
    }
    else if (addDeliveryFeeBy == 'city') {
        if (validateCityName()) {
            setDeliveryFeeWithCity();
        }
    }
    else if (addDeliveryFeeBy == 'distance') {
        
        if (validateDistance()) {
            
            setDeliveryFeeWithDistance();
        }
       
    }
    
    return false;
}

function setWait(obj) {
    var img = imagePath + "/Label/wait.gif";
    //alert(img);
    obj.innerHTML = "<img src='" + img + "'  style='border: 0px; margin: 10px 10px 10px 10px;' />";
    
}


function setDeliveryFeeWithCity(){
    
    var url = "GetDeliveryFee.aspx?city=" + encodeURI(document.webForm.city.value) + "&n=" + Math.ceil(1000*Math.random());
    getXmlRequester();
    xmlRequester.onreadystatechange = proccessXMLResponseCity;
    xmlRequester.open("GET", url, true);
    xmlRequester.send(null);

}

function setDeliveryFeeWithDistance() {
    var url = "GetDeliveryFee.aspx?dSt=" + encodeURI(document.webForm.street.value) + "&dCity=" + encodeURI(document.webForm.city.value) + "&dState=" + encodeURI(document.webForm.state.value) + "&dZip=" + encodeURI(document.webForm.zip.value) + "&n=" + Math.ceil(1000 * Math.random());
    getXmlRequester();
    xmlRequester.onreadystatechange = proccessXMLResponseDistance;
    xmlRequester.open("GET", url, true);
    xmlRequester.send(null);
    
}



function setDeliveryFeeWithSub(){
    var url = "GetDeliveryFee.aspx?zSub=" + document.webForm.zip.value + document.webForm.zipSub.value + "&n=" + Math.ceil(1000*Math.random());
    
    getXmlRequester();
    xmlRequester.onreadystatechange = proccessXMLResponse;
    xmlRequester.open("GET", url, true);
    xmlRequester.send(null);
}

function getPKLocs() {
    var url = "GetLoc.aspx?n=" + Math.ceil(1000 * Math.random());
    getXmlRequester();
    xmlRequester.onreadystatechange = proccessLocs;
    xmlRequester.open("GET", url, true);
    xmlRequester.send(null);
    var locD = document.getElementById('locDiv');
    setWait(locD);
    if (document.webForm.sdl != null) {
        window.document.webForm.sdl.value = null;
        
    }
}

function proccessLocs() {
   
    
    document.webForm.submitB.disabled = true;
    var locD = document.getElementById('locDiv');
    
    if(xmlRequester.readyState == 4){
        locD.innerHTML = xmlRequester.responseText;
        document.webForm.submitB.disabled = false;
    }

}



function setPKLoc(loc) {
    
    var url = "GetLoc.aspx?l=" + loc + "&n=" + Math.ceil(1000 * Math.random());
    getXmlRequester();
    xmlRequester.onreadystatechange = proccessLocs;
    xmlRequester.open("GET", url, true);
    xmlRequester.send(null);
    var locD = document.getElementById('locDiv');
    setWait(locD);
}

function proccessXMLResponseDistance() {

    delcheck = false;
    document.webForm.submitB.disabled = true;
    resetToStandardDeliveryFee();
    if (xmlRequester.readyState == 4) {
        
        if (xmlRequester.responseText && xmlRequester.responseText.replace(" ", "") != "" && xmlRequester.responseText.replace(" ", "") != "NA" && xmlRequester.responseText.replace(" ", "") != "MIN") {
            dRate = xmlRequester.responseText;
            
            var rateObj = getDistanceRateByRate(dRate.toString().split("|")[0]);
            if (rateObj) {
                document.getElementById('zipRangeDiv').innerHTML = "<span class='miscTitle'>" + jMessage['deliveryFeeIs'] + " " + rateObj.rateLabel + "</span>";

                delcheck = true;
                
                overWriteStandardDeliveryFeeDistance(rateObj.distance);

                document.webForm.submitB.disabled = false;
            }
            else {
                rateObj = createDistanceRateObj(dRate);

                document.getElementById('zipRangeDiv').innerHTML = "<span class='miscTitle'>" + jMessage['deliveryFeeIs'] + " " + rateObj.rateLabel + "</span>";

                delcheck = true;
                overWriteStandardDeliveryFeeDistanceWithDistanceObj(rateObj);

                document.webForm.submitB.disabled = false;
            }
        }

        else if (xmlRequester.responseText && xmlRequester.responseText.replace(" ", "") != "" && xmlRequester.responseText.replace(" ", "") == "MIN") {
            
            document.getElementById('zipRangeDiv').innerHTML = "<span class='miscTitle'>" + jMessage['MinForDeliveryNotMet'] + "</span>";
            document.webForm.submitB.disabled = false;
        }
        else{
            document.getElementById('zipRangeDiv').innerHTML = "<span class='miscTitle'>" + jMessage['locationNotAvailableForDelivery'] + "</span>";
            document.webForm.submitB.disabled = false;
        }

    }
    else {

    }
}

function proccessXMLResponseCity(){
    
    delcheck = false;
    document.webForm.submitB.disabled = true;
    
    
    resetToStandardDeliveryFee();

    
    if(xmlRequester.readyState == 4){
        
        if(xmlRequester.responseText && xmlRequester.responseText.replace(" ", "") != "" && xmlRequester.responseText.replace(" ", "") != "NA"){
            dRate = xmlRequester.responseText;
            var rateObj = getCityRateByRate(dRate.toString().split("|")[0]);
            if(rateObj){
                document.getElementById('zipRangeDiv').innerHTML = "<span class='miscTitle'>" + jMessage['deliveryFeeIs'] + " " + rateObj.rateLabel + "</span>";
                
                delcheck = true;
                overWriteStandardDeliveryFeeCity(rateObj.cityName);
                
                document.webForm.submitB.disabled = false;
            }
            else{
                rateObj = createCityRateObj(dRate);
                
                document.getElementById('zipRangeDiv').innerHTML = "<span class='miscTitle'>" + jMessage['deliveryFeeIs'] + " " + rateObj.rateLabel + "</span>";
                
                delcheck = true;
                overWriteStandardDeliveryFeeCityWithCityObj(rateObj);
                
                document.webForm.submitB.disabled = false;
            }
        }
        else{
            document.getElementById('zipRangeDiv').innerHTML = "<span class='miscTitle'>" + jMessage['locationNotAvailableForDelivery'] + "</span>";
            document.webForm.submitB.disabled = false;
            
        }
    }
    else{
        
    }

}

function createCityRateObj(text){
    var arrayObj = text.toString().split("|");
    var cityObj = new DeliveryCityRate(arrayObj[1], arrayObj[0], arrayObj[2], arrayObj[3]);
    return cityObj;
}

function createDistanceRateObj(text) {
    var arrayObj = text.toString().split("|");
    var distanceObj = new DeliveryDistanceRate(arrayObj[1], arrayObj[0], arrayObj[2], arrayObj[3]);
    return distanceObj;
}


function proccessXMLResponse(){

   
    delcheck = false;
    document.webForm.submitB.disabled = true;
    
    
    resetToStandardDeliveryFee();

    
    if(xmlRequester.readyState == 4){
        
        if(xmlRequester.responseText && xmlRequester.responseText.replace(" ", "") != "" && xmlRequester.responseText.replace(" ", "") != "NA"){
            dRate = xmlRequester.responseText;
            var rateObj = getZipRateByRate(dRate);
            document.getElementById('zipRangeDiv').innerHTML = "<span class='miscTitle'>" + jMessage['deliveryFeeIs'] + " " + rateObj.rateLabel + "</span>";
            
            delcheck = true;
            overWriteStandardDeliveryFeeZip(rateObj.zipCode);
            
            document.webForm.submitB.disabled = false;
        }
        else{
            document.getElementById('zipRangeDiv').innerHTML = "<span class='miscTitle'>" + jMessage['locationNotAvailableForDelivery'] + "</span>";
            document.webForm.submitB.disabled = false;
            
        }
    }
    else{
        
    }
    
}

function getZipRateByRate(rate){
    
    for(var i=0; i < dzcArray.length; i++){
        if(dzcArray[i].rate == rate){
            return dzcArray[i];
        }
    }

}

function getCityRateByRate(rate){
    for(var i=0; i < dcArray.length; i++){
        if(dcArray[i].rate == rate){
            return dcArray[i];
        }
    }
}

function getDistanceRateByRate(distance) {
    for (var i = 0; i < ddcArray.length; i++) {
        if (ddcArray[i].distance == distance) {
            return ddcArray[i];
        }
    }
}

function overWriteStandardDeliveryFeeCityWithCityObj(cityObj){
     
    try{
        
        if(cityObj != null && cityObj.rate > 0.00){
            document.webForm.deliveryFeeField.value = cityObj.rate;
            document.getElementById('stateRateDiv').innerHTML = "";
            document.getElementById('deliveryFee').innerHTML = cityObj.rateLabel;
            document.getElementById('cartTotal').innerHTML = cityObj.cartTotalWithRate;

        }
        else if(cityObj != null && cityObj.rate < 0.01){
            resetToStandardDeliveryFee();
        }
    }
    catch(ex){
        resetToStandardDeliveryFee();
    }
}


function overWriteStandardDeliveryFeeDistanceWithDistanceObj(distanceObj) {

    try {

        if (distanceObj != null && distanceObj.rate > 0.00) {
            document.webForm.deliveryFeeField.value = distanceObj.rate;
            document.getElementById('stateRateDiv').innerHTML = "";
            document.getElementById('deliveryFee').innerHTML = distanceObj.rateLabel;
            document.getElementById('cartTotal').innerHTML = distanceObj.cartTotalWithRate;

        }
        else if (distanceObj != null && distanceObj.rate < 0.01) {
            resetToStandardDeliveryFee();
        }
    }
    catch (ex) {
        resetToStandardDeliveryFee();
    }
}

function overWriteStandardDeliveryFeeDistance(distance) {
    
    var distanceObj = null;
    try {
        distanceObj = getDistanceRate(distance);
        if (distanceObj != null && distanceObj.rate > 0.00) {
            document.webForm.deliveryFeeField.value = distanceObj.rate;
            document.getElementById('stateRateDiv').innerHTML = "";
            document.getElementById('deliveryFee').innerHTML = distanceObj.rateLabel;
            document.getElementById('cartTotal').innerHTML = distanceObj.cartTotalWithRate;

        }
        else if (distanceObj != null && distanceObj.rate < 0.01) {
            resetToStandardDeliveryFee();
        }
    }
    catch (ex) {
        resetToStandardDeliveryFee();
    }
}

function overWriteStandardDeliveryFeeCity(cityName){
    var cityObj = null;
    try{
        cityObj = getCityRate(cityName);
        if(cityObj != null && cityObj.rate > 0.00){
            document.webForm.deliveryFeeField.value = cityObj.rate;
            document.getElementById('stateRateDiv').innerHTML = "";
            document.getElementById('deliveryFee').innerHTML = cityObj.rateLabel;
            document.getElementById('cartTotal').innerHTML = cityObj.cartTotalWithRate;
        
        }
        else if(cityObj != null && cityObj.rate < 0.01){
            resetToStandardDeliveryFee();
        }
    }
    catch(ex){
        resetToStandardDeliveryFee();
    }
}

function overWriteStandardDeliveryFeeZip(zipCode){

    var zipObj = null;
    try{
    zipObj = getZipRate(zipCode);
    if(zipObj != null && zipObj.rate > 0.00){
       
        document.webForm.deliveryFeeField.value = zipObj.rate;
        document.getElementById('stateRateDiv').innerHTML = "";
        document.getElementById('deliveryFee').innerHTML = zipObj.rateLabel;
        document.getElementById('cartTotal').innerHTML = zipObj.cartTotalWithRate;

    }
    else if(zipObj != null && zipObj.rate < 0.01){
        resetToStandardDeliveryFee();
    }
    }
    catch(ex){
        resetToStandardDeliveryFee();
    }
    
}


function overWriteStandardDeliveryFee(stateAbbr){

    var rateRow = null;
    
    resetToStandardDeliveryFee();
    
    if( stateAbbr != null && trimString(stateAbbr) != null){
     
    }
}

function resetToStandardDeliveryFee(){
    
       

        document.getElementById('deliveryFee').innerHTML = stdDelFee;

        document.webForm.deliveryFeeField.value = stdDelFee;
        
        document.getElementById('stateRateDiv').innerHTML = "";

        document.getElementById('cartTotal').innerHTML = cartTotalWithStdDelFee;

/*
        alert(document.getElementById('miniCartTotal_pos'));
        if (document.getElementById('miniCartTotal_pos')) {
            document.getElementById('miniCartTotal_pos').innerHTML = cartTotalWithStdDelFee;
        }
  */      
        
   
    
}

function setOpenCategorySetID(id){
    
}


function changePricePerItemBoxes(num){
            
            changeDiv(num);
}
          
          

function changeDiv(num){
          
          
          
          if (document.all) { 
              
              i = 1;
             
              
              while(i <= 7){
                document.getElementById("p" + i).style.visibility = 'hidden';
                i++;
              }
              
              i = 1;
              while(i <= num){
                document.getElementById("p" + i).style.visibility = 'visible';
                i++;
              }
              
          }
          else if (document.layers) { 

                i = 1;
                while(i <= 7){
                  document.layers["p" + i].visibility = "hidden";
                  i++;
                }


                i = 1;
                while(i <= num){
                  document.layers["p" + i].visibility = "visible";
                  i++;
                }
                
          }
}


function validateNewCat(sender, form){

    sender.disabled = true;
    form.CMD.value = 'newCat'; 
    
   
    var fv = new FormValidator();
    
     
    
    fv.addValidator(new TextValidator('categoryName', jMessage['NewCategoryNameIsRequired']));
    fv.addValidator(new TextValidator('indexOrder', jMessage['IndexOrderNumberIsRequired']));
    
    var i = 1;
    while(i <= form.pricingPerItem.value){
        fv.addValidator(new TextValidator('pricing_' + i, jMessage['NameForItemSizePrice'] + i +  jMessage['IsRequired']));
        i++;
    }
    
    
    if(fv.validate()) {
        form.submit();
    } else {
        sender.disabled = false;
    }
    

}

function toggleStyleDisplay(divObj){
   try{
       if(document.getElementById(divObj).style.display != "block"){
        document.getElementById(divObj).style.display = "block";
        document.getElementById(divObj + "_IMG").src = imagePath + "/label/block.png";
       }
       else{
        document.getElementById(divObj).style.display = "none";
        document.getElementById(divObj + "_IMG").src = imagePath + "/label/none.png";
       }
   }
   catch (e){
   
   }
   
}

function getXmlRequester(){

     var xmlhttp=false;
     try {
            xmlRequester = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) {
            try {
        xmlRequester = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (E) {
            xmlhttp = false;
            }
     }
            if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
            try {
                        xmlRequester = new XMLHttpRequest();
            } catch (e) {
                        xmlhttp=false;
            }
            }
            if (!xmlhttp && window.createRequest) {
            try {
                        xmlRequester = window.createRequest();

            } catch (e) {
                        xmlhttp=false;
            }

            }

}


function changeCCSCPic(selectObj, rootPath, nonePath){
  try{
	toggleInfoReq(isCCInfoReq(selectObj.options[selectObj.selectedIndex].value));
	if(selectObj.options[selectObj.selectedIndex].value != ""){
		document.getElementById("ccscPic").src = rootPath + selectObj.options[selectObj.selectedIndex].value + "-sc.gif";
	}
	else{
		document.getElementById("ccscPic").src = nonePath;
	}
  }
  catch(e){
  
  }
	
}

function getValueOfRadio(obj){

    if(!obj){
        return "";
    }
    if(obj.length == undefined){
        if(obj.checked){
            return obj.value;
        }
        else{
            return "";
        }
    }
    for(var i = 0; i < obj.length; i++){
    
        if(obj[i].checked){
            return obj[i].value;
        }
    }

}

function isCCInfoReq(cardName){
    
    var i = 0;
    while(i < ccArray.length){
        if( (ccArray[i].cardName == cardName) && (ccArray[i].requireInfo) ){
            return true;
        }
        i++;
    }
    return false;
}

function toggleInfoReq(isReq) {
    var form = document.webForm;
    
       
        if(isReq && ( (getRadioValue(form.orderType) == null && cap) || (cap && getRadioValue(form.orderType) == '2') || ( getRadioValue(form.orderType) == '1') )) { 
           
            form.expireMonth.selectedIndex = 0;
            form.expireYear.selectedIndex = 0;
            
            document.getElementById('ccDateDiv1').style.display = 'block';
            document.getElementById('ccDateDiv2').style.display = 'block';
            
            form.account.disabled = false;
            if(form.account.value == "."){
                form.account.value = "";
            }
            form.nameOnCard.disabled = false;
            if(form.nameOnCard.value == "."){
                form.nameOnCard.value = "";
            }
            
            
            if(form.ccStreet){
                form.ccStreet.disabled = false;
                form.ccCity.disabled = false;
                form.ccState.disabled = false;
                form.ccZip.disabled = false;
            }
            else{
                form.securityCode.disabled = false;
                if(form.securityCode.value == "."){
                    form.securityCode.value = "";
                }
            }
        } else {
            
            form.expireMonth.selectedIndex = 1;
            form.expireYear.selectedIndex = 2;
            document.getElementById('ccDateDiv1').style.display = 'none';
            document.getElementById('ccDateDiv2').style.display = 'none';
            form.account.value = ".";
            form.nameOnCard.value = ".";
            if(form.ccStreet){
                
                form.ccStreet.value = "";
                
                form.ccCity.value = "";
                
                form.ccState.value = "";
                
                form.ccZip.value = "";
            }
            else{
                
                form.securityCode.value = ".";
                if(form.ccZip){
                    form.ccZip.value = "";
                }
            }
        }
    
    
}

function lte(max, min, group, item){
    selects = document.webForm.getElementsByTagName("select");
    var selectedTotal = 0;
    var text = "";
    for(var i = 0; i < selects.length; i++){
        if(selects[i].name.indexOf(group, 0) > -1){
            
            //selectedTotal += selects[i].selectedIndex;
            if(selects[i].selectedIndex > 0){
                selectedTotal++;
            }

        }
        
    }
    //alert(selectedTotal);
}

function eil(max, min, group, obj){

    selects = document.webForm.elements[group];

    var tol = 0;
    for(var i = 0; i < selects.length; i++){
        
        if(selects[i].checked){
            tol++;
        }
    }
    
    if(tol > max){
        if(obj.checked){
            obj.checked = false;
        }
    }


}





// Draw a circle on map around center (radius in miles)
// Modified by Jeremy Schneider based on http://maps.huge.info/dragcircle2.htm
function drawCircle(map, center, radius, numPoints, fillColor, edgeColor) {
    var poly = [];
    var line;
    var lat = center.lat();
    var lng = center.lng();
    var d2r = Math.PI / 180;                // degrees to radians
    var r2d = 180 / Math.PI;                // radians to degrees
    var Clat = (radius / 3963) * r2d;      //  using 3963 as earth's radius
    var Clng = Clat / Math.cos(lat * d2r);

    //Add each point in the circle
    for (var i = 0; i < numPoints; i++) {
        var theta = Math.PI * (i / (numPoints / 2));
        Cx = lng + (Clng * Math.cos(theta));
        Cy = lat + (Clat * Math.sin(theta));
        poly.push(new GLatLng(Cy, Cx));
    }

    //Remove the old line if it exists
    if (line) {
        map.removeOverlay(line);
    }

    //Add the first point to complete the circle
    poly.push(poly[0]);

    //Create a line with teh points from poly, red, 3 pixels wide, 80% opaque
    //line = new GPolyline(poly, '#FF0000', 2, 0.5);
    line = new GPolygon(poly, edgeColor, 1, .5, fillColor, 0.3); 

    map.addOverlay(line);
}






         var map = null;
         var shapeLayer;
         var lineLayer;
         var polyPoints = new Array();
         var down=0;
         var X=0,Y=0;
         var origin;
         
         function GetMap()
         {
            map = new VEMap('myMap');
            map.LoadMap();
            
            //load shapelayer
            shapeLayer = new VEShapeLayer();
            var veLayerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS,document.form1.Input.value, shapeLayer);
            map.ImportShapeLayerData(veLayerSpec);
            map.EnableShapeDisplayThreshold(false);
            lineLayer = new VEShapeLayer();
            map.AddShapeLayer(lineLayer);
            
            map.AttachEvent("onmouseup",MouseUpHandler);
            map.AttachEvent("onmousedown",MouseDownHandler);
            map.AttachEvent("onmousemove",MouseMoveHandler);
            map.AttachEvent("onmouseover",MouseOverHandler);
         }
        
          //used to load geoRSS data from alternative source
        function loadLayer()
        {
            shapeLayer.DeleteAllShapes();
            var veLayerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS,document.form1.Input.value, shapeLayer);
            map.ImportShapeLayerData(veLayerSpec);
        }
        
        function drawPolygon()
        {
            //remove the polygon that is on the map
            lineLayer.DeleteAllShapes();
            
            //draw polyline if there is only two points in the array
            if(polyPoints.length<3)
            {
                var polygon = new VEShape(VEShapeType.Polyline, polyPoints);
            }
            else
            {
                //create a new polygon
                var polygon = new VEShape(VEShapeType.Polygon, polyPoints);
            }
            
            polygon.HideIcon();
            
            //draw the new polygon on the map
             lineLayer.AddShape(polygon); 
        }
        
        function polygonSearch()
        {
            document.form1.Results.value = "Found locations\r\n\r\n";
            
            var counter=0;
            
            //loop through shapes on the shape layer and see if they are within the polygon
            for(var i=0; i < shapeLayer.GetShapeCount(); i++)
            {
                var shape = shapeLayer.GetShapeByIndex(i);
                var latlong = shape.GetPoints()[0];
                var lat = latlong.Latitude;
                var lon = latlong.Longitude;
                
                if(pointInPolygon(polyPoints,lat,lon))
                {
                    //shape is in the polygon, output useful infromation
                    document.form1.Results.value += shape.GetTitle()+"\r\n";
                    counter++
                }
            }
            
            document.form1.Results.value += "\r\nTotal number of locations found: "+ counter;
        }
        
        function pointInPolygon(points,lat,lon) 
         {
              var i;
              var j=points.length-1;
              var inPoly=false;

              for (i=0; i<points.length; i++) 
              {
                if (points[i].Longitude<lon && points[j].Longitude>=lon ||  points[j].Longitude<lon && points[i].Longitude>=lon) 
                {
                      if (points[i].Latitude+(lon-points[i].Longitude)/(points[j].Longitude-points[i].Longitude)*(points[j].Latitude-points[i].Latitude)<lat) 
                      {
                        inPoly=!inPoly; 
                      }
                }
                j=i; 
              }

            return inPoly; 
        }
          
          function MouseUpHandler(e)
        {
            if (e.leftMouseButton && down==1)
            {
               down=0;
               polyPoints.push(origin);
               polygonSearch();  
                X=0;
                Y=0;
               }
        }
        
        function MouseDownHandler(e)
        {
            if (e.rightMouseButton)
            {
               X = e.mapX;
               Y = e.mapY;
               
               var point = map.PixelToLatLong(new VEPixel(X,Y));
               
               if(down==0)
               {   
                   //intialize the map and variables.           
                   lineLayer.DeleteAllShapes(); 
                   polyPoints = new Array(0);
                   
                   origin = point;
                   polyPoints.push(origin);
                   down=1;
                  }
                  
                  //add the new point to the array
                  polyPoints.push(point);
                       
               return true;
               }
        }
        
        function MouseMoveHandler(e)
        {
            if (down==1)
            {
               var x = e.mapX;
               var y = e.mapY;
               
               var dx = Math.abs(X)-Math.abs(x);
               var dy = Math.abs(Y)-Math.abs(y);
               
               //do not want to redraw polygon unless we move a significant amount
               if(Math.abs(dx) > 5 || Math.abs(dy) > 5)
               {
                       var latlong = map.PixelToLatLong(new VEPixel(x, y));
                    polyPoints.pop();
                       polyPoints.push(latlong);
                            
                       drawPolygon();
                   }
               }
        }
        
        function MouseOverHandler(e)
        {
            if(down==1)
            {
                //disable popups when drawing polygon to make drawing the polygon easier
                return true;    
            }
        }

        function SetTips(v) {
          
            document.getElementById("tips").value = v;
           
        }
      



