﻿
// Cookie support functions
function createCookie(name,value,days) {
    if (days) {
	    var date = new Date();
	    date.setTime(date.getTime()+(days*24*60*60*1000));
	    var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
	    var c = ca[i];
	    while (c.charAt(0)==' ') c = c.substring(1,c.length);
	    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

var ResetForm;
var currentPostcode = "";
// This function will send an ajax request to check if we could delivery to this post code and with what fee
// After it get the result it change the layout of the form
function CheckPostCode(){
    $("#postCodeText").val( $("#postCodeText").val().replace(' ','').toUpperCase() );
    if(!$("#postCodeText").val().match("[A-Z]{1,2}[0-9R][0-9A-Z]?[0-9][ABD-HJLNP-UW-Z]{2}")){
        alert('The postcode you entered is incorrect. Please try again!');
    }
    else{
        $("#post-code-result").removeClass();
        $("#post-code-result").css("margin-top", "15px" );
        $("#post-code-check #post-code-form-container").attr("id", "post-code-form-container-w-result");              
        $("#post-code-result").html("<img src='/assets/images/loading.gif' /> Loading...");        
        
        var id = GetSelectedOption().ID;
        createCookie("userPostCode", $("#postCodeText").val(), 30);
        $.ajax({
            type: "GET",
            url: "/DeliveryInformation/AJAXCheckDelivery.aspx?ProductOptionID=" + id + "&PostCode=" + $("#postCodeText").val(),
            error: function() {
                $("#post-code-result").html("Sorry, server error, please try again!");
                return false;
            },
            success: function(response) {
                var extraID = response;
                $("#post-code-result").attr("style", "");
                // If found the suitable sub-option
                if (extraID.indexOf(",") > -1) {
                    $("#post-code-result").addClass("extra-del-charge");
                    $("#post-code-result").html("<strong>Surcharge delivery  +" + extraID.split(',')[1] + "</strong><br/>This surcharge will be added during check-out.<br />NOTE: delivery times may be extended in certain areas.");
                } else {
                    extraID = parseInt(extraID);
                    if (extraID > 0) {
                        // select the option checkbox for this delivery
                        $("#sub-option-" + extraID).attr("checked", true);
                        SelectExtraOptionChange($("#sub-option-" + extraID).get(0));
                        // Edit the form to show the extra charge
                        $("#post-code-result").addClass("extra-del-charge");
                        $("#post-code-result").html($("#sub-option-" + extraID).attr("text") + "<br/>This amount has been added to the price below.<br />NOTE: delivery times may be extended in certain areas.");
                    }
                    // If it's free delivery
                    if (extraID == -2) {
                        $("#post-code-result").addClass("free-del-area");
                        $("#post-code-result").html("<strong>Delivery to your area is Free.</strong> Please add this product to basket and continue to checkout");

                    }
                    // If we can't delivery to this post code
                    if (extraID == -1) {
                        $("#post-code-result").addClass("no-del-area");
                        $("#post-code-result").html("Sorry, we are currently unable to offer delivery to this area. Please check back again later.");
                    }
                }
                currentPostcode = $("#postCodeText").val();
                // Comment out as we don't use installation service in GCD yet
                GetInstallationForm();
                ResetForm = $("#post-code-form").html();
                $("#post-code-form").html("<b>" + $("#postCodeText").val() + "</b> <a onclick='ResetCheckForm()'>Not your post code?</a>");
            }
        });
    }
};

function ResetCheckForm(){
    // Clear any delivery option checked before
    if($("#deliver-service-checks input[type=checkbox]:checked").length > 0)
    {
        $("#deliver-service-checks input[type=checkbox]:checked").each(function(){
            $(this).attr("checked", false);
            SelectExtraOptionChange(this);
        });
    }   
    // Reset the form to original state
    $("#post-code-form").html(ResetForm);
    $("#post-code-check #post-code-form-container-w-result").attr("id", "post-code-form-container");
    $("#post-code-result").removeClass();
    $("#post-code-result").html("");
	$("#optional-services").remove();
    eraseCookie("userPostCode");
}

function GetInstallationForm(){
	if(currentPostcode.length > 0){
		var id = GetSelectedOption().ID;
		$.ajax({
			type: "GET",
			url: "/ProductPage4/AJAX/AJAXInstallationOptions.aspx?ProductOptionID=" + id + "&PostCode=" + currentPostcode,
			error: function(){
				$("#post-code-result").html("Sorry, server error, please try again!");
				return false;
			},
			success: function(response){
				$("#optional-services").remove();
				$("#post-code-check").after(response);
			}
		});
	}
}

// When user select or unselect a service checkbox
function SelectServiceChanged(serviceID){
    var serviceSelection = "#service-" + serviceID;
    //If service is checked
    if($(serviceSelection).attr("checked")){
        // find the services from the list of services and add it to the list
        for (var idx=0; idx< Services.length; idx++){
            if ((Services[idx] != undefined) && (Services[idx].ID == serviceID)) {
                SelectedServices.push(Services[idx]);
                break;
            }
        }
    } 
    else {
        // find the services from the list of services and remove it from the list
        for(var idx=0; idx< SelectedServices.length; idx++){
            if ((SelectedServices[idx] != undefined) && (SelectedServices[idx].ID == serviceID)) {
                SelectedServices.splice(idx, 1);
                break;
            }
        }        
    }
    var selectedServicesList = "";
    for(var idx =0;idx<SelectedServices.length; idx++){
        selectedServicesList += "," + SelectedServices[idx].ID;
    }
    selectedServicesList = selectedServicesList.substr(1, selectedServicesList.length-1);
    $("#services-values").val(selectedServicesList);
    UpdatePagePrices();
}