//Shipping form ajax validation class.
var ShippingFormValidation = {};
ShippingFormValidation.submitStateFresh = 0;
ShippingFormValidation.submitStatePending = 1;
ShippingFormValidation.submitStateNeedsRefresh = 2;

var updateShippingOk = false;
var shippingCalcOk = false;

ShippingFormValidation.submitState = ShippingFormValidation.submitStateFresh;
ShippingFormValidation.sendShippingFormToServer = function (){

    if (allItemsFilled() && (ShippingFormValidation.submitState == ShippingFormValidation.submitStateFresh) )
    {
        ShippingFormValidation.submitState = ShippingFormValidation.submitStatePending;
        var shippingElements=jQuery("#co-shipping-form .tax-field").serialize();
        ajaxBusyOn();
        shippingCalcOk = false;
        hidePayButton();
        jQuery.ajax({
            "data" : shippingElements,
            "url"  : "/lockerzom/ajax/shippingCalc/",
            "dataType" : "json",
            "success": function(data){
                ajaxBusyOff();
                hideErrorMessage();
                if(ShippingFormValidation.submitState == ShippingFormValidation.submitStateNeedsRefresh) {
                    // Make a new request w/ updated fields
                    ShippingFormValidation.submitState = ShippingFormValidation.submitStateFresh;
                    return ShippingFormValidation.sendShippingFormToServer();
                }
                else {
                    if (data){
                        if (data.status_message === "OK"){
                            shippingCalcOk = true;
                            showPayButton(true);
                            updateTotals(data);
                        }
                        else
                        {
                            showErrorMessage(data.message);
                            shippingCalcOk = false;
                            hidePayButton(true);
                        }
                        // Set back to the initial state.
                        ShippingFormValidation.submitState = ShippingFormValidation.submitStateFresh;
                    }
                }
            },
            "type" : "POST"
        });
    }
};

function updateShippingMethods(countryId, postCode, dontHideErrorMessage) {
	ajaxBusyOn();
    updateShippingOk = false;
    hidePayButton();
	jQuery("#shipping_method").html("<option value=''>loading...</option>");
	jQuery("#shipping_method").attr("disabled", "disabled");

		// don't hate me
		if ("US" == countryId) {
			jQuery("#chk_banner").attr("class", "checkout-banner free-shipping");
			if ("undefined" != typeof usUrl) {
				jQuery("#chk_banner").html("<img src=\""+ usUrl +"\" alt=\"\" usemap=\"#free-sku\" />");
			}
		} else {
			jQuery("#chk_banner").attr("class", "checkout-banner");
			if ("undefined" != typeof intlUrl) {
				jQuery("#chk_banner").html("<img src=\""+ intlUrl +"\" alt=\"\" usemap=\"#free-sku\" />");
			}
		}

    jQuery.ajax({
        "data" : {"country_id": countryId, "postcode": postCode},
        "cache" : false,
        "url"  : "/lockerzom/ajax/updateShippingMethods/",
        "dataType" : "json",
        "success": function(data){
            ajaxBusyOff();
	    if (typeof(dontHideErrorMessage) == 'undefined' || !dontHideErrorMessage) {
		    hideErrorMessage();
	    }
            if (data){
                if (data.status_message === "OK"){
                    updateTotals(data);
                    updateShippingOk = true;
                    showPayButton();
                    jQuery("#shipping_method").removeAttr("disabled");
                    jQuery("#shipping_method").html(data.options);
                }
                else
                {
                    updateShippingOk = false;
                    hidePayButton();
                    showErrorMessage(data.message);
                    jQuery("#quote_shipping_price").html('-');
                    jQuery('#shipping_method').html("<option value=''>None Available.</option>");
                }
            }
        },
        "type" : "POST"
	});

}


var nonUsTaxCopy = "*Sales tax shown is Estimated vat (Value-Added Tax).";
var intlTaxLabel = "Estimated Duties & Taxes:";
var usTaxLabel = "Estimated Sales Tax:";
var cautionIcon = "<img src='http://static.lockerz.com/commerce/images/caution.gif'alt='So you know.'/>";
var usTaxCopy = "*Sales tax will be added to orders from New Jersey, Pennsylvania, California and Washington.";
var regionRequired = new Array('AU', 'BR', 'CA', 'IT', 'ES', 'JP', 'US');
var zipRequired = new Array('AU', 'BR', 'CA', 'DE', 'ES', 'FR', 'GB', 'IT', 'JP', 'NL', 'PL', 'SE', 'SG', 'US');

/* Update Text Outside of the Form */
function drawInternationalCopy() {
    /* jQuery("#sales_tax_label").html(cautionIcon + intlTaxLabel); */
    jQuery("#sales_tax_label").html(intlTaxLabel);
    jQuery("#tax-copy").html(nonUsTaxCopy);
    jQuery(".intl-ex").html(" (Excluding Tax)");
    jQuery("#flyout-holder").html("<div class='duties-flyout'></div>");
}
/* Update Text Outside of the Form */
function drawCanadianCopy() {
    drawNorthAmericanCopy();
    jQuery("#tax-copy").html(nonUsTaxCopy);
}
/* Update Text Outside of the Form */
function drawAmericanCopy() {
    drawNorthAmericanCopy();
    jQuery("#tax-copy").html(usTaxCopy);
}
/* Update Text Outside of the Form */
function drawNorthAmericanCopy() {
    jQuery("#sales_tax_label").html(usTaxLabel);
    jQuery(".intl-ex").html("");
    jQuery("#flyout-holder").html("");
}

/* Update Text In Checkout Form */
function drawInternationalForm(country_id) {
    drawInternationalCopy();
    // hide US phone format
    jQuery("#phone-trifield input").hide();
    // Make it not required
    jQuery("#phone-trifield input").removeClass("required-entry tax-field");
    jQuery("#phone-trifield input").attr("disabled", "disabled");
    // show telephone freeform box
    jQuery("#telephone-row").show();
    jQuery("#phone-freeform").show();
    // Make it required
    jQuery("#phone-freeform input").addClass("required-entry tax-field");
    jQuery("#phone-freeform input").removeAttr("disabled");

    if (jQuery.inArray(country_id, regionRequired) >= 0) {
        jQuery('#state_label').html('<em>*</em> Province');
    } else {
        jQuery('#state_label').html('Province');
    }

    jQuery('#zip_freeform input').attr('maxlength', 20);

    if (jQuery.inArray(country_id, zipRequired) >= 0) {
        jQuery('#zip_freeform input').addClass('required-entry tax-field');
        jQuery('#zip_label').html('<em>*</em> Postal Code');
    } else {
        jQuery('#zip_freeform input').removeClass('required-entry tax-field');
        jQuery('#zip_label').html('Postal Code');
    }
}

/* Update Text In Checkout Form */
function drawCanadianForm() {
    drawNorthAmericanForm();
    drawCanadianCopy();
    jQuery('#zip_freeform input').attr('maxlength', 7);
    jQuery('#state_label').html('<em>*</em> Province');
    jQuery('#zip_label').html('<em>*</em> Postal Code');
    jQuery("#tax-copy").html(nonUsTaxCopy);
    jQuery("#telephone-row").show();
    jQuery("#phone-trifield input").show();
    jQuery("#phone-trifield input").addClass("required-entry tax-field");
    jQuery("#phone-trifield input").removeAttr("disabled");
}

/* Update Text In Checkout Form */
function drawAmericanForm() {
    drawNorthAmericanForm();
    drawAmericanCopy();
    jQuery('#zip_freeform input').attr('maxlength', 5);
    jQuery('#state_label').html('<em>*</em> State');
    jQuery('#zip_label').html('<em>*</em> ZIP Code');
}

/* Update Text In Checkout Form */
function drawNorthAmericanForm() {
    // hide phone freeform and region freeform boxes
    jQuery("#phone-freeform").hide();
    jQuery("#phone-freeform input").removeClass("required-entry tax-field");
    jQuery("#phone-freeform input").attr("disabled", "disabled");

    jQuery('#zip_freeform input').addClass('required-entry tax-field');
    jQuery("#phone-trifield input").hide();
    jQuery("#telephone-row").hide();
    jQuery("#phone-trifield input").removeClass("required-entry tax-field");
    jQuery("#phone-trifield input").attr("disabled", "disabled");
}

function drawForm(country_id) {
    if (country_id == "" || country_id == null) {
        country_id = "US"
    }

    if (country_id == "US") {
        drawAmericanForm();
    } else if (country_id == "CA") {
        drawCanadianForm();
    } else {
        drawInternationalForm(country_id);
    }

    var countryRequiresRegion = jQuery.inArray(country_id, regionRequired);
    
    // Logic for region/province/state
    //if (jQuery("#region-container select").is(":visible")) {
    if (country_id == "US" || country_id == 'CA') {
        jQuery("#region-container select").show();
        // In here means magento auto-populated the region dropdown
        if (countryRequiresRegion >= 0) {
            jQuery("#region-container select").addClass("required-entry tax-field");
        } else {
            jQuery("#region-container select").removeClass("required-entry tax-field");
        }
        // Hide freeform
        jQuery("#region-freeform").hide();
        jQuery("#region-freeform input").removeClass('required-entry tax-field');
    } else {
        // Show freeform
        jQuery("#region-freeform").show();
        jQuery("#region-freeform input").show();
        jQuery("#region-container select").val("");
        if (countryRequiresRegion >= 0) {
            jQuery("#region-freeform input").addClass("required-entry tax-field");
        } else {
            jQuery("#region-freeform input").removeClass("required-entry tax-field");
        }
        // Disable region dropdown
        jQuery("#region-container select").hide();
        jQuery("#region-container select").removeClass("required-entry tax-field");
    }
}

function hideErrorMessage() {
    jQuery("#ajax-messages").html("");
}

function showErrorMessage(message) {
    jQuery("#ajax-messages").html("<ul class='messages'><li class='error-msg'><ul><li>" + message + "</li></ul></li></ul>");
}

var counter = 0;

function showPayButton(isFields){
    if (updateShippingOk == true && shippingCalcOk == true){
        $('pay_now').show();
    }
    isFieldsCorrect = true;
}

function hidePayButton(isFields){
    isFieldsCorrect = false;
    $('pay_now').hide();
}

function ajaxBusyOn() {
    jQuery("#shipping-please-wait").show();
}

function ajaxBusyOff() {
    jQuery("#shipping-please-wait").hide();
}

function updateTotals(data) {
    if (typeof(data.shipping_total) != 'undefined') {
        jQuery("#quote_shipping_price").html( data.shipping_total );
    }
    
    if (typeof(data.order_total) != 'undefined') {
        jQuery("#cart-total-price").html( data.order_total );
        jQuery("#sidebar-total-price").html( data.order_total );
    }

    if (typeof(data.ptz_used_total) != 'undefined') {
        jQuery("#cart_total_ptz_used_val").html(data.ptz_used_total);
    }
    
    if (typeof(data.tax_total) != 'undefined') {
        jQuery("#quote_sales_tax").html(data.tax_total);
    }

    if (data.zero_shipping_eligible)
    {
        jQuery("#pay_option_zero").show();
        jQuery("#pay_option_pp").hide();
    }
    else
    {
        jQuery("#pay_option_zero").hide();
        jQuery("#pay_option_pp").show();
    }
}

function allItemsFilled() {
    var items = jQuery("#co-shipping-form .required-entry.tax-field");
    var allItemsFilled = true;
    jQuery(items).each( function(index, item){
        if (!item.value)
        {
            allItemsFilled = false;
        }
    });
    return allItemsFilled;
}

