﻿$(function() {

    $("html").bind("ajaxSend", function() {
        $(this).addClass('busy');
    }).bind("ajaxComplete", function() {
        $(this).removeClass('busy');
    });

    // Your Personal Details
    $("[ID$='divYourPersonalDetails']").click(function() {
        showYourPersonalDetails();
        return false;
    });

    // Your Login Details
    $("[ID$='divYourLoginDetails']").click(function() {
        showYourLoginDetails();
        return false;
    });

    // Your Order Status
    $("[ID$='divYourOrderStatus']").click(function() {
        showYourOrderStatus();
        return false;
    });

    // Your Address Book
    $("[ID$='divYourAddressBook']").click(function() {
        showYourAddressBook();
        return false;
    });

    // Your Payment Options
    $("[ID$='divYourPaymentOptions']").click(function() {
        showYourPaymentOptions();
        return false;
    });

    // Your Preferences
    $("[ID$='divYourPreferences']").click(function() {
        showYourPreferences();
        return false;
    });

    // Your Harrods Rewards
    $("[ID$='divYourHarrodsRewards']").click(function() {
        showYourHarrodsRewards('');
        return false;
    });

    // Continue Shopping
    $("[ID$='btnContinueShopping']").click(function() {
        ContinueShopping();
        return false;
    });

    var defaultSection = $("[ID$='DefaultSection']").val();
    var defaultAction = $("[ID$='DefaultAction']").val();

    if (defaultSection == 'rewards') {
        showYourHarrodsRewards(defaultAction);
    }
    if (defaultSection == 'preferences') {
        showYourPreferences(defaultAction);
    }
    if (defaultSection == 'login') {
        showLogin('#divActivePanel', '', '', '');
    }
    if (defaultSection == 'register') {
        showRegister('#divActivePanel', '', false);
    }

});

$.fn.selectItem = function() {

    $("a").each(function(i) {
        $(this).removeClass('selected');
    });
    $("[ID$='btnYourHarrodsAccount']").addClass('selected');
    return $(this).addClass('selected');
}

// Your Personal Details
$("[ID$='btnYourPersonalDetails']").live("click", function() {
    showYourPersonalDetails();
    return false;
});

// Your Login Details
$("[ID$='btnYourLoginDetails']").live("click", function() {
    showYourLoginDetails();
    return false;
});

// Your Order Status
$("[ID$='btnYourOrderStatus']").live("click", function() {
    showYourOrderStatus();
    return false;
});

// Your Address Book
$("[ID$='btnYourAddressBook']").live("click", function() {
    showYourAddressBook();
    return false;
});

// Your Payment Options
$("[ID$='btnYourPaymentOptions']").live("click", function() {
    showYourPaymentOptions();
    return false;
});

// Your Preferences
$("[ID$='btnYourPreferences']").live("click", function() {
    showYourPreferences();
    return false;
});

// Your Harrods Rewards
$("[ID$='btnYourHarrodsRewards']").live("click", function() {
    showYourHarrodsRewards('');
    return false;
});

function resetUpdates() {
    $(".fieldHighlight").each(function(i) {
        $(this).removeClass('fieldHighlight');
    });
}

function showYourPersonalDetails() {

    $(this).selectItem();
    $.dynamicLoader.loadUC({
        ucName: '/harrodsstore/UserControls/Account/YourPersonalDetails.ascx',
        eventBindings: {
            ready: function(data) {
                $('#divActivePanel').selectPanel(data);
                $('#divYourPersonalDetails').hide();
                $("[ID$='btnYourPersonalDetails']").selectItem();
                setSubSection("Your Personal Details");
            }
        }
    });
}

function showYourLoginDetails() {

    $(this).selectItem();
    $.dynamicLoader.loadUC({
        ucName: '/harrodsstore/UserControls/Account/YourLoginDetails.ascx',
        eventBindings: {
            ready: function(data) {
                $('#divActivePanel').selectPanel(data);
                $('#divYourLoginDetails').hide();
                $("[ID$='btnYourLoginDetails']").selectItem();
                setSubSection("Your Login Details");
            }
        }
    });
}

function showYourOrderStatus() {

    $(this).selectItem();
    $.dynamicLoader.loadUC({
        ucName: '/harrodsstore/UserControls/Account/YourOrderStatus.ascx',
        eventBindings: {
            ready: function(data) {
                $('#divActivePanel').selectPanel(data);
                $('#divYourOrderStatus').hide();
                $("[ID$='btnYourOrderStatus']").selectItem();
                setSubSection("Your Order Status");
            }
        }
    });
}

function showYourAddressBook() {

    $(this).selectItem();
    $.dynamicLoader.loadUC({
        ucName: '/harrodsstore/UserControls/Account/YourAddressBook.ascx',
        eventBindings: {
            ready: function(data) {
                $('#divActivePanel').selectPanel(data);
                $('#divYourAddressBook').hide();
                $("[ID$='btnYourAddressBook']").selectItem();
                setSubSection("Your Address Book");
            }
        }
    });
}

function showYourPaymentOptions() {

    $(this).selectItem();
    $.dynamicLoader.loadUC({
        ucName: '/harrodsstore/UserControls/Account/YourPaymentOptions.ascx',
        eventBindings: {
            ready: function(data) {
                $('#divActivePanel').selectPanel(data);
                $('#divYourPaymentOptions').hide();
                $("[ID$='btnYourPaymentOptions']").selectItem();
                setSubSection("Your Payment Options");
            }
        }
    });
}

function showYourPreferences(Action) {

    $(this).selectItem();
    $.dynamicLoader.loadUC({
        ucName: '/harrodsstore/UserControls/Account/YourPreferencesScratch.ascx',
        queryString: 'action=' + Action,
        eventBindings: {
            ready: function(data) {
                $('#divActivePanel').selectPanel(data);
                $('#divYourPreferences').hide();
                $("[ID$='btnYourPreferences']").selectItem();
                setSubSection("Your Preferences");
            }
        }
    });
}

function showYourHarrodsRewards(Action) {

    $(this).selectItem();
    $.dynamicLoader.loadUC({
    ucName: '/harrodsstore/UserControls/Account/YourHarrodsRewards.ascx',
        queryString: 'action=' + Action,
        eventBindings: {
            ready: function(data) {
                $('#divActivePanel').selectPanel(data);
                $('#divYourHarrodsRewards').hide();
                $("[ID$='btnYourHarrodsRewards']").selectItem();
                setSubSection("Your Harrods Rewards");
            }
        }
    });
}

function showYourPreferences(Action) {

    $(this).selectItem();
    $.dynamicLoader.loadUC({
        ucName: '/harrodsstore/UserControls/Account/YourPreferencesScratch.ascx',
        queryString: 'action=' + Action,
        eventBindings: {
            ready: function(data) {
                $('#divActivePanel').selectPanel(data);
                $('#divYourPreferences').hide();
                $("[ID$='btnYourPreferences']").selectItem();
                setSubSection("Your Preferences");
            }
        }
    });
}

function GetRegionalLabels(countryShortCode) {

    var DTO = { 'countryShortCode': countryShortCode };

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/harrodsstore/Services/Account/AddressService.svc/GetRegionalLabels",
        data: JSON.stringify(DTO),
        dataType: "json",
        error: function(xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            $('#ErrorAdd').html(err.Message).show();
            return false;
        },
        success: function(msg) {
            if (msg.d.isValid && null != msg.d.entityData) {
                $("#CityLabel").text(msg.d.entityData.CityLabel);
                $("#RegionLabel").text(msg.d.entityData.RegionLabel);
                $("#PostcodeLabel").text(msg.d.entityData.PostcodeLabel);
            }
            else {
                $('#ErrorAdd').html(msg.d.errorMessage).show();
            }
            return false;
        }
    });

}

function LoadCountryCodes(countryCode) {
    // Load country codes if not already loaded.
    if ($("[ID$='ddCountryList'] option").size() == 2) {

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/harrodsstore/Services/Account/AddressService.svc/GetCountryCodes",
            data: {},
            dataType: "json",
            error: function(xhr, status, error) {
                var err = eval("(" + xhr.responseText + ")");
                $('#ErrorView').text(err.Message).show();
                $('#btnChange').hide();
                return false;
            },
            success: function(msg) {

                if (msg.d.isValid && null != msg.d.entityData) {
                    // Clear the list.
                    $("[ID$='ddCountryList']").children().remove();
                    // Add default option.
                    $("[ID$='ddCountryList']").append($('<option></option>').val("").html("Please Select"));
                    // Load list.
                    $.each(msg.d.entityData.items, function(key, item) {
                        $("[ID$='ddCountryList']").append($('<option></option>').val(item.Value).html(item.Text));
                    });

                    // Choose specified country.
                    $("[ID$='ddCountryList']").val(countryCode);
                }
                else {
                    $('#ErrorView').html(msg.d.errorMessage).show();
                }
                return false;
            }
        });
    }
    else {
        // Choose specified country.
        $("[ID$='ddCountryList']").val(countryCode);
    }
}

function LoadStateCodes(countryCode) {

    $("[ID$='ddStateList']").children().remove();

    var DTO = { 'countryCode': countryCode };

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/harrodsstore/Services/Account/AddressService.svc/GetStateCodes",
        data: JSON.stringify(DTO),
        dataType: "json",
        error: function(xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            $('#ErrorView').text(err.Message).show();
            return false;
        },
        success: function(msg) {

            if (msg.d.isValid && null != msg.d.entityData) {
                if (msg.d.entityData.items.length > 0) {
                    // Add default option.
                    $("[ID$='ddStateList']").append($('<option></option>').val("").html("Please Select"));
                    // Load list.
                    $.each(msg.d.entityData.items, function(key, item) {
                        $("[ID$='ddStateList']").append($('<option></option>').val(item.Value).html(item.Text));
                    });
                    $("[ID$='ddStateList']").show();
                    $("[ID$='txtRegion']").hide();
                }
                else {
                    $("[ID$='ddStateList']").hide();
                    $("[ID$='txtRegion']").show();
                }
            }
            else {
                $('#ErrorView').html(msg.d.errorMessage).show();
            }
            return false;
        }
    });
}

function FindAddress(errorMsg) {

    // Customer is searching for an address based on postcode.
    errorMsg.hide();
    $("[ID$='ddAddressList']").children().remove();
    $("[ID$='divFindAddress']").hide();
    $("[ID$='HiddenPostcodeSearch']").val($("[ID$='txtPostcode']").val());

    var countryCode = $("[ID$='ddCountryList']").val();
    var houseNumber = '';
    var postCode = $("[ID$='txtPostcode']").val();

    var DTO = { 'countryCode': countryCode, 'houseNumber': houseNumber, 'postCode': postCode };

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/harrodsstore/Services/Account/AddressService.svc/FindAddress",
        data: JSON.stringify(DTO),
        dataType: "json",
        error: function(xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            errorMsg.html(err.Message).show();
            return false;
        },
        success: function(msg) {
            if (msg.d.isValid && null != msg.d.entityData) {
                if (msg.d.entityData.addressCount == 1) {
                    // One address found.
                    $("[ID$='ddAddressList']").append($('<option></option>').html(msg.d.entityData.addressMaster.AddressLine1));
                    $("[ID$='HiddenPostcodeResult']").val(msg.d.entityData.addressMaster.Postcode);
                    $("[ID$='HiddenPostcodeExtended']").val(msg.d.entityData.addressMaster.Postcode);
                    showSelectedAddress(errorMsg);
                }
                else {
                    // multiple addresses found.
                    $("[ID$='ddAddressList']").append($('<option></option>').val("0").html("Please Select"));
                    $.each(msg.d.entityData.items, function(key, item) {
                        $("[ID$='ddAddressList']").append($('<option></option>').html(item));
                    });
                    $("[ID$='HiddenPostcodeResult']").val(msg.d.entityData.addressMaster.Postcode);
                    $("[ID$='HiddenPostcodeExtended']").val(msg.d.entityData.addressMaster.PostcodeExtended);
                    $("[ID$='divFindAddress']").show();
                }
            }
            else {
                errorMsg.html(msg.d.errorMessage).show();
            }
            return false;
        }
    });
}

function showSelectedAddress(errorMsg) {

    errorMsg.hide();

    var address = $("[ID$='ddAddressList'] option:selected").html();
    var countryCode = $("[ID$='ddCountryList']").val();
    var postCodeResult = $("[ID$='HiddenPostcodeResult']").val();
    var postCodeExtended = $("[ID$='HiddenPostcodeExtended']").val();

    var DTO = { 'address': address, 'countryCode': countryCode, 'postCodeResult': postCodeResult, 'postCodeExtended': postCodeExtended };

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/harrodsstore/Services/Account/AddressService.svc/SelectAddress",
        data: JSON.stringify(DTO),
        dataType: "json",
        error: function(xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            errorMsg.html(err.Message).show();
            return false;
        },
        success: function(msg) {

        if (msg.d.isValid && null != msg.d.entityData) {
            
                $.each(msg.d.entityData.addressMaster, function(key, value) {
                if ($("[ID$='txt"+key+"']") && value != null) {
                        $("[ID$='txt"+key+"']").val(value);
                    }
                });

                LoadCountryCodes(msg.d.entityData.addressMaster.CountryCode);

                $("[ID$='Full']").show();
                $(".full").show();
                $("[ID$='Short']").hide();
                $('#Options1, #Options3').hide();
                $("[ID$='divFindAddress']").hide();
            }
            else {
                errorMsg.html(msg.d.errorMessage).show();
            }
            return false;
        }
    });
}
