﻿// 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;
// 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 {
        $("#postcode-result").removeClass();        
        $("#postcode-result").html("<img src='/assets/images/loading.gif' /> Loading...");        
        
        createCookie("userPostCode", $("#postCodeText").val(), 30);
        $.ajax({
            type: "GET",
            url: "/DeliveryInformation/AJAXCheckDelivery.aspx?ProductOptionID=" + $("#postCodeText").attr("rel") + "&PostCode=" + $("#postCodeText").val(),
            error: function(ajaxObj, textStatus, errorThrown) {
                $("#postcode-result").html("Sorry, server error, please try again!");
                return false;
            },
            success: function(response) {
                var extraID = response;
                // If found the suitable sub-option
                if (extraID.indexOf(",") > -1) {
                    $("#postcode-result").addClass("extra-del-charge");
                    $("#postcode-result").html("<strong>Surcharge delivery  +" + extraID.split(',')[1] + "</strong><br/>This surcharge will be added during check-out.<br /><small><b>Please Note:</b> delivery times may be extended by an additional 5-10 working days.</small>");
                    $("#add-button").show();
                } else {
                    extraID = parseInt(extraID);
                    if (extraID > 0) {
                        // select the option checkbox for this delivery
                        $("#sub-option-" + extraID).attr("checked", true);
                        SelectOptionalExtraChanged($("#sub-option-" + extraID).get());
                        // Edit the form to show the extra charge
                        $("#postcode-result").addClass("extra-del-charge");
                        $("#postcode-result").html($("#sub-option-" + extraID).attr("text") + "<br/>This amount has been added to the total price.<br /><small><b>Please Note:</b> Delivery times may be extended by an additional 5 working days.</small>");
                        $("#add-button").show();
                    }
                    // If it's free delivery
                    else if (extraID == -2) {
                        $("#postcode-result").addClass("free-del-area");
                        $("#postcode-result").html("<strong>Delivery to your area is Free.</strong> Please add this product to basket and continue to checkout");
                        $("#add-button").show();
                    }
                    else if (extraID == -3) {
                        $("#postcode-result").addClass("free-del-area");
                        $("#postcode-result").html("<strong>Delivery to your area is Free.</strong> Please add this product to basket and continue to checkout.<br /><strong>Please Note: Delivery times may be extended by an additional 5 working days to your area.");
                        $("#add-button").show();
                    }
                    // If we can't delivery to this post code
                    else if (extraID == -1) {
                        $("#postcode-result").addClass("no-del-area");
                        $("#postcode-result").html("Sorry, we are currently unable to offer delivery to this area. Please call us on <b>" + getSalesNumber() + "</b> if you would like more information.");
                        $("#add-button").hide();
                    }
                    else if (extraID == -10) {
                        $("#postcode-result").addClass("no-del-area");
                        $("#postcode-result").html("Please call <b>" + getSalesNumber() + "</b> for delivery information as we are unable to process orders for this area online due to delivery restrictions and surcharges on certain products.");
                        $("#add-button").hide();
                    }
                }
                GetInstallationForm();
                ResetForm = $("#postcode-form").html();
                $("#postcode-entered").val($("#postCodeText").val());
                $("#postcode-form").html("<b class=\"confirmed-postcode\">" + $("#postCodeText").val() + "</b><br /><a href='#' onclick='ResetCheckForm(); return false;'>Not your post code?</a>");
            }
        });
    }
};
function getSalesNumber() {
    if (getStoreID) {
        var storeId = getStoreID();
        storeId = parseInt(storeId);
        switch (storeId) {
            case 1:
                return "0800 0482 441";
            case 2:
                return "0800 652 7752";
            case 51:
                return "0800 652 7752";
            default:
                return "0800 169 6016";
        }
    }
    else {
        return "0800 169 6016";
    }
}
function ResetCheckForm(){
    // Clear any delivery option checked before
    if($("#delivery-details-container input[type=checkbox]:checked").length > 0)
    {
        $("#delivery-details-container input[type=checkbox]:checked").each(function(){
            $(this).attr("checked", false);
            SelectOptionalExtraChanged(this);
        });
    }
    if($("#assembly-result input[type=checkbox]:checked").length > 0)
    {
        $("#assembly-result input[type=checkbox]:checked").each(function(){
            $(this).attr("checked", false);
            SelectServiceChanged($(this).val());
        });
    }
    // Reset the form to original state
    $("#postcode-form").html(ResetForm);
    initPostCodeTextEvent();
    $("#add-button").show();
    $("#postcode-entered").val("");
    $("#postcode-result").removeClass();
    $("#postcode-result").html("");
    //get a list of possible service ids and make sure they're not in the selected array
    var services = $("#optional-services input");
	$("#assembly-result").html(ResetAssemblyForm);
    eraseCookie("userPostCode");
}
var ResetAssemblyForm;
function GetInstallationForm(){
    var postcode = $("#postCodeText").val();
    if ((postcode == undefined) || (postcode.length == 0)) {
        return;
    }
    var optionID = GetSelectedOption().ID;
    $.ajax({
        type: "GET",
        url: "/ProductPage4/AJAX/AJAXInstallationOptions.aspx?ProductOptionID=" + optionID + "&PostCode=" + postcode,
        error: function(){
            $("#postcode-result").html("Sorry, server error, please try again!");
            return false;
        },
        success: function(response){
            ResetAssemblyForm = $("#assembly-result").html();
            if (response.length != 0) {
                $("#assembly-result").html(response);
            }
        }
    });
}
function initPostCodeTextEvent() {
    $("#postCodeText").keypress(function(e){
        if (e.which == 13) {
            e.preventDefault();
            CheckPostCode();
        }
    });
}
function createPostCodeCheckerPopup() {
    //create a new rollover element
    var container = document.createElement("div");
    $("body").append(container);
    $(container).attr("id", "postcode-checkbox-message");
    var topLeft = document.createElement("div");
    $(topLeft).attr("class", "top-left");
    container.appendChild(topLeft);
    var topRight = document.createElement("div");
    $(topRight).attr("class", "top-right");
    container.appendChild(topRight);
    var middle = document.createElement("div");
    $(middle).attr("class", "middle");
    container.appendChild(middle);
    var right = document.createElement("div");
    middle.appendChild(right);
    $(right).attr("class", "right");
    var content = document.createElement("div");
    right.appendChild(content);
    $(content).attr("class", "content");
    var bottomLeft = document.createElement("div");
    $(bottomLeft).attr("class", "bottom-left");
    container.appendChild(bottomLeft);
    var bottomRight = document.createElement("div");
    $(bottomRight).attr("class", "bottom-right");
    container.appendChild(bottomRight);
    
    //make an overlay for the background
    var overlay = document.createElement("div");
    $(overlay).attr("id", "postcode-checkbox-message-overlay");
    $(overlay).height($(document).height());
    $("body").append(overlay);
    
    //set events
    $("#postcode-checkbox-message, #postcode-checkbox-message-overlay").click(function(){
        $("#postcode-checkbox-message").hide();
        $("#postcode-checkbox-message-overlay").hide();
    });
    
    //get its content
    var htmlContent = "";
    htmlContent += "<p>Please enter your postcode in the Free Delivery Checker so that we can confirm availability to your area.</p>";
    $(content).html(htmlContent);
}
function showPleaseEnterPostCodeBox() {
    if ($("#postcode-checkbox-message").get(0) == null) {
        createPostCodeCheckerPopup();
    }
    var top = $("#postCodeText").offset().top - $("#postcode-checkbox-message").height();
    var left = $("#postCodeText").offset().left;
    $("#postcode-checkbox-message").css("top", top);
    $("#postcode-checkbox-message").css("left", left);
    $("#postcode-checkbox-message").show();
    $("#postcode-checkbox-message-overlay").show();
    $("html, body").animate({
        scrollTop: $("#postcode-checkbox-message").offset().top - ($(window).height() / 2) + ($("#postcode-checkbox-message").height() / 2)
    }, 750);
}

function createDeliveryInfoPopup() {
    //create a new rollover element
    var container = document.createElement("div");
    $("body").append(container);
    $(container).attr("id", "delivery-info-message");
    $(container).attr("class", "rollover");
    var topLeft = document.createElement("div");
    $(topLeft).attr("class", "top-left");
    container.appendChild(topLeft);
    var topRight = document.createElement("div");
    $(topRight).attr("class", "top-right");
    container.appendChild(topRight);
    var middle = document.createElement("div");
    $(middle).attr("class", "middle");
    container.appendChild(middle);
    var right = document.createElement("div");
    middle.appendChild(right);
    $(right).attr("class", "right");
    var content = document.createElement("div");
    right.appendChild(content);
    $(content).attr("class", "content");
    var bottomLeft = document.createElement("div");
    $(bottomLeft).attr("class", "bottom-left");
    container.appendChild(bottomLeft);
    var bottomRight = document.createElement("div");
    $(bottomRight).attr("class", "bottom-right");
    container.appendChild(bottomRight);
    
    //get its content
    var htmlContent = "";
    htmlContent += "<p>Telling us your postcode now enables us to give you accurate delivery information straight away and allows us to notify you of any delivery surcharges or restrictions.</p>";
    $(content).html(htmlContent);
}
function showDeliveryInfoPopup() {
    if ($("#delivery-info-message").get(0) == null) {
        createDeliveryInfoPopup();
    }
    var top = $("#postcode-map").offset().top - $("#delivery-info-message").height();
    var left = $("#postcode-map").offset().left;
    $("#delivery-info-message").css("top", top);
    $("#delivery-info-message").css("left", left);
    $("#delivery-info-message").show();
}
function createAssemblyInfoPopup() {
    //create a new rollover element
    var container = document.createElement("div");
    $("body").append(container);
    $(container).attr("id", "assembly-info-message");
    $(container).attr("class", "rollover");
    var topLeft = document.createElement("div");
    $(topLeft).attr("class", "top-left");
    container.appendChild(topLeft);
    var topRight = document.createElement("div");
    $(topRight).attr("class", "top-right");
    container.appendChild(topRight);
    var middle = document.createElement("div");
    $(middle).attr("class", "middle");
    container.appendChild(middle);
    var right = document.createElement("div");
    middle.appendChild(right);
    $(right).attr("class", "right");
    var content = document.createElement("div");
    right.appendChild(content);
    $(content).attr("class", "content");
    var bottomLeft = document.createElement("div");
    $(bottomLeft).attr("class", "bottom-left");
    container.appendChild(bottomLeft);
    var bottomRight = document.createElement("div");
    $(bottomRight).attr("class", "bottom-right");
    container.appendChild(bottomRight);
    
    //get its content
    var htmlContent = "";
    htmlContent += "<p>Telling us your postcode enables us to notify you of any assembly services that may be available to your area.</p>";
    $(content).html(htmlContent);
}
function showAssemblyInfoPopup() {
    if ($("#assembly-info-message").get(0) == null) {
        createAssemblyInfoPopup();
    }
    var top = $("#postcode-assembly-img").offset().top - $("#assembly-info-message").height();
    var left = $("#postcode-assembly-img").offset().left;
    $("#assembly-info-message").css("top", top);
    $("#assembly-info-message").css("left", left);
    $("#assembly-info-message").show();
}

// 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();
}
