function storenamefun(key) {
    var strname = '';
    $.each(arrJsonCountiesStores, function (nokeyparam, countystoreobj) {
        if (countystoreobj.StrTheaterCode == key) {
            strname = countystoreobj.StrStoreName;
        }
    });
    return strname;
}



// Determine if we need to display the product price for the selected store
// as we may not be in the same currency zone.
function differentCurrencyRequired(county) {
    differentPage = false;
    var IECounty = true;
    // Find out what site we are on
    var currentPage = window.location.host.split('/');
    // Find out if we are on a UK site.
    switch (county) {
        case 'Antrim':
            IECounty = false;
            break;
        case 'Armagh':
            IECounty = false;
            break;
        case 'Down':
            IECounty = false;
            break;
        case 'Fermanagh':
            IECounty = false;
            break;
        case 'Londonderry / Derry':
            IECounty = false;
            break;
        case 'Tyrone':
            IECounty = false;
            break;
        default:
            IECounty = true;
            break;
    }
    if (currentPage[0].indexOf(".co.uk") > -1) {
        if (IECounty) differentPage = true;
    } else {
        if (!IECounty) differentPage = true;
    }
    return differentPage;
}


// Get the currency symbol for the select county
function priceSymbol(county) {
    switch (county) {
        case 'Antrim':
        case 'Armagh':
        case 'Down':
        case 'Fermanagh':
        case 'Londonderry / Derry':
        case 'Tyrone':
            symbol = '\u00A3';
            break;
        default:
            symbol = '\u20AC';
            break;
    }
    return symbol;
}

function initiateEpos() {
    var isLoggedInDetails = {};
    var userDetails = {};

    //If user is logged in, grab their details and prefill them is, also disable those fields.
    var amiloggedin = ajaxServiceCall('WebServices/MonadelAccess.asmx/IsLoggedIn', isLoggedInDetails, "json", false);
    userDetails['varToRetrieve'] = 'HomeStoreID';

    if (typeof amiloggedin != 'undefined') {
        if (amiloggedin == true) {

            //update store
            var mystoreid = ajaxServiceCall('WebServices/MonadelAccess.asmx/getUserVar', userDetails, "json", false);
            $("#checkstockcounty select#stores").toggle();
            $("#checkstockcounty select#stores").append($("<option></option>").attr("value", mystoreid).attr("selected", "selected").text(storenamefun(mystoreid)));

            //call getcardholder to return users details if we are logged in
            //Receive details for user from Abinitio
            var abinitioCall = {};
            var abinitioParameters = {};

            abinitioCall['operation'] = 'GETCARDHOLDER';
            abinitioCall['anydata'] = '';
            abinitioCall['parameters'] = abinitioParameters;
            abinitioCall['captchaResponse'] = '';
            var result1 = ajaxServiceCall('WebServices/Epos.asmx/RequestAsNodes', abinitioCall, "xml", false);
            if (result1) {
                $(result1).find("cardholder").each(function () {

                    $("input#clickcollectfirstname").attr("value", $(this).find("firstName").text()).attr("disabled", "disabled");
                    $("input#clickcollectsecondname").attr("value", $(this).find("lastName").text()).attr("disabled", "disabled");
                    $("input#clickcollectemail").attr("value", $(this).find("email").text()).attr("disabled", "disabled");
                    $("input#clickcollectphone").attr("value", $(this).find("mobileNumber").text()).attr("disabled", "disabled");
                    //force prefix to have selected null value
                    $("select#MobilePrefix").append($("<option></option>").attr("value", "").attr("selected", "selected").text("")).css("display", "none");

                    if ($(this).find("allowCommunicationsByPost").text() == 'true') {
                        $("#loginform table #sendinfo").prop("checked", true);
                    }
                });
            }
        }
    }

}

$(document).ready(function () {


    $(".infobubblebutton").hover(function () {
        $('#infobubble').toggle();
    }, function () {
        $('#infobubble').delay(3000).fadeToggle()
    });


    $('select#counties').change(function () {
        if ($("select#stores").is(":hidden")) {
            $('select#stores').toggle();
        }
    });

    $("#clickcollectemail").onClickClearField();
    $("#clickcollectphone").onClickClearField();
    $("#clickcollectfirstname").onClickClearField();
    $("#clickcollectsecondname").onClickClearField();

    //Show quantity, hidden for initial release
    /*$('select#selectproduct').change(function () {
    if ($("div#quantityholder").is(":hidden")) {
    $('div#quantityholder').toggle();
    }
    });*/

    $('input#clickcollectsubmit').click(function (event) {

        event.preventDefault();

        if ($("div#realtimeprice").is(":visible")) {
            $('div#realtimeprice').toggle();
        }

        var quantityRequired = $('select#selectedQuantity').val();

        if (quantityRequired <= 0) {
            alert('Must specify a quantity of 1 or more.');
            return false;
        }

        if ($('select#selectproduct').val() == '0') {
            alert('Please select a product.');
            return false;
        }

        if ($('select#stores').val() == '0') {
            alert('Please select a store.');
            return false;
        }

        $('#selectedproduct').attr('value', $('select#selectproduct').val());
        $('#selectedproductname').attr('value', $('select#selectproduct option[value=' + $('select#selectproduct').val() + ']').text());
        $('#selectedcounty').attr('value', $('select#counties').val());
        $('#selectedstore').attr('value', $('select#stores').val());
        $('#selectedstorename').attr('value', $('select#stores option[value=' + $('select#stores').val() + ']').text());
        $('#selectedquantity').attr('value', '1'); //$('select#selectedQuantity').val());

        if (quantityRequired > 3) {
            alert('Can can order a quantity between 1 and 3.');
            return false;
        }

        var abinitioCall = {};
        var abinitioParameters = {};
        // Abinito Store ID
        abinitioParameters['storeid'] = $('select#stores').val();
        // Produce Code
        abinitioParameters['skucode'] = $('select#selectproduct').val();

        abinitioCall['operation'] = 'GETSTOCK';
        abinitioCall['anydata'] = '';
        abinitioCall['parameters'] = abinitioParameters;
        abinitioCall['captchaResponse'] = '';

        // Turn on the ajax image waiting
        var currentImage = $("input#clickcollectsubmit").attr('src');
        var currentImageHeight = $("input#clickcollectsubmit").attr('height');
        var currentImageWidth = $("input#clickcollectsubmit").attr('width');
        $("input#clickcollectsubmit").attr('src', findRelativeBasePath() + 'gr/waiting.gif');
        $("input#clickcollectsubmit").attr('width', 16);
        $("input#clickcollectsubmit").attr('height', 16);
        /////////////////////////////////////////////////////
        $('span#mainmessage').html("");
        var result1 = ajaxServiceCall('WebServices/Epos.asmx/RequestAsNodes', abinitioCall, "xml", false);
        /////////////////////////////////////////////////////
        $("input#clickcollectsubmit").attr('src', currentImage);
        $("input#clickcollectsubmit").attr('height', currentImageHeight);
        $("input#clickcollectsubmit").attr('width', currentImageWidth);
        /////////////////////////////////////////////////////
        if (result1 == null) {
            $('span#mainmessage').html("<b><font color=\"red\">An error occurred retrieving available stock, the Administrator has been informed. Please try again later.</font></b>");
            return false;
        }
        var stockAvail = 0;
        if (result1) {
            $(result1).find("stockrecord").each(function () {
                stockAvail = parseInt($(this).find("onhand").text());
            });
        }
        // Incorrect SKU will return -1
        // Use GETZONESTOCK to see if there are other stores with what we are looking for.
        //var StoresAndStock = [];
        var StoresAndStock = new Array();

        if (stockAvail <= 0 || stockAvail < $('#selectedquantity').val()) {

            abinitioCall['operation'] = 'GETZONESTOCK';
            // calling with GETZONESTOCK
            var result2 = ajaxServiceCall('WebServices/Epos.asmx/RequestAsNodes', abinitioCall, "xml", false);
            $(result2).find("stockrecord").each(function () {
                var tempStockAvail = 0;
                tempStockAvail = $(this).find("onhand").text();
                // add to our list including no stock and as less stock may also work for the user.
                var storeID = $(this).find("storecode").text();
                //StoresAndStock[storeID] = stockAvail;
                StoresAndStock.push({ key: storeID, value: tempStockAvail });
            });

            //fill product div with message explaining product is not available
            //$('span#mainmessage').text("Unfortunately the product you have chosen is not available in your selected store at present. Please choose another store that has confirmed availability.");
            //$('span#mainmessage').text("");
        }
        else {
            // We have available stock, proceed to next step.
            if ($("div#productavailable").is(":visible")) {
                $('div#productavailable').toggle();
            }
            if ($("div#checkstockcounty").is(":visible")) {
                $('div#checkstockcounty').toggle();
            }
            if ($("input#clickcollectsubmit").is(":visible")) {
                $('input#clickcollectsubmit').toggle();
            }

            $('span#mainmessage').html('<b><font color=\"blue\">The product you have selected is available to Click &amp; Collect at your chosen store</font></b>');

            if ($("#RadCaptcha1").is(":hidden")) {
                $("#RadCaptcha1").toggle();
            }

            if ($("#contactdetails").is(":hidden")) {
                $('#contactdetails').toggle();
            }

            var theCaptchaControl = $("#RadCaptcha1").detach();
            theCaptchaControl.appendTo("div#captcha");
        }

        var validStockInStores = 0;
        //StoresAndStock.push({ key: '109', value: 0 });
        //StoresAndStock.push({ key: '111', value: -1 });
        //StoresAndStock.push({ key: '112', value: 1 });
        //StoresAndStock.push({ key: '114', value: 2 });
        //StoresAndStock.push({ key: '119', value: 3 });
        //StoresAndStock.push({ key: '121', value: 4 });
        // sort descending.
        StoresAndStock.sort(function (a, b) {
            return a.value > b.value ? -1 : a.value < b.value ? 1 : 0;
        });

        var relativeLocation = findRelativeBasePath();
        $.each(StoresAndStock, function (index, storeStock) {

            var key = storeStock.key;
            var value = storeStock.value;

            //use this to call the light img function showLight(quantityRequired)
            // Create div to display each store, traffic light with tool tip and reserve button.
            //alert(value);
            // Get store name using key into JSON array.
            if (value <= 0) {
                // Red – not in stock  Out of Stock remaining stock would be less than zero
                //$('div#alternativeStores ul#listofaltstores').append('<li><p alt="No stock available" title="No stock available"><img src="' + relativeLocation + 'gr/site/trafficlight/red.png" alt="No stock available" title="No stock available" /> ' + storenamefun(key) + '</p></li>');
                $('table#alternativeStores tr td table#listofaltstores').append('<tr><td class="left">' + storenamefun(key) + '</td><td class="middle"><img src="' + relativeLocation + 'images/check_no.gif"/></td><td></td></tr>');
            }

            if (value > 0) {
                // Amber less than     Low Stock remaining stock would be less than 3
                //$('div#alternativeStores ul#listofaltstores').append('<li><a href="' + key + '" class="altstores" rel="' + storenamefun(key) + '" alt="' + value + ' items available"  title="' + value + ' items available" ><img src="' + relativeLocation + 'gr/site/trafficlight/amber.png" alt="' + value + ' items available" title="' + value + ' items available" /> ' + storenamefun(key) + '</a></li>');
                $('table#alternativeStores tr td table#listofaltstores').append('<tr><td class="left"><a href="' + key + '" class="altstores" rel="' + storenamefun(key) + '" alt="' + value + ' items available"  title="' + value + ' items available" >' + storenamefun(key) + '</a></td><td class="middle"><a href="' + key + '" class="altstores" rel="' + storenamefun(key) + '" alt="' + value + ' items available"  title="' + value + ' items available" ><img src="' + relativeLocation + 'images/check_yes.gif"/></a></td><td class="right"><a href="' + key + '" class="altstores" rel="' + storenamefun(key) + '" alt="' + value + ' items available"  title="' + value + ' items available" ><img src="' + relativeLocation + 'gr/clickcollectsmall.png"/></a></td></tr>');
                validStockInStores++;
            }
            /*if (value > 3) {
            // Green               In Stock remaining stock would be greater than 3
            $('div#alternativeStores ul#listofaltstores').append('<li><a href="' + key + '" class="altstores" rel="' + storenamefun(key) + '" alt="' + value + ' items available"  title="' + value + ' items available" ><img src="' + relativeLocation + 'gr/site/trafficlight/green.png" alt="' + value + ' items available" title="' + value + ' items available" /> ' + storenamefun(key) + '</a></li>');
            validStockInStores++;
            }*/
        });
        //alert("stock=" + validStockInStores + " in  " + StoresAndStock.length  + " stores");
        //add the striped effect to the table
        //$('table.stripe tbody tr:odd').addClass('odd');
        $('table#alternativeStores tr td table#listofaltstores tbody tr:even').addClass('even');

        $('.chosenstorename').text($('#selectedstorename').val());

        //show div with alternative stores
        if (validStockInStores > 0) {
            if ($("table#alternativeStores").is(":hidden")) {
                $('table#alternativeStores').toggle();
            }
            //hide div with stores drop down
            if ($("div#checkstockcounty").is(":visible")) {
                $('div#checkstockcounty').toggle();
            }
            if ($("div#productavailable").is(":visible")) {
                $('div#productavailable').toggle();
            }
            if ($("input#clickcollectsubmit").is(":visible")) {
                $('input#clickcollectsubmit').toggle();
            }
        } else {
            if (stockAvail <= 0) {
                // no stock available in nearby stores.
                $('span#mainmessage').html("<b><font color=\"red\">Unfortunately the product you have chosen is not available in your selected store or nearby stores at present. Please choose another store that has confirmed availability.</font></b>");
            }
        }

        //Update users account details at top of page
        //$("span#spanSalutation").text($(this).find("firstName").text());
        $("span#spanFirstname").text($(this).find("firstName").text());
        $("span#spanLastname").text($(this).find("lastName").text());
        $("span#spanHomeAddress1").text($(this).find("street").text());
        //call abinitio
    });



    $('a.altstores').live('click', function (event) {
        event.preventDefault();

        $('input#selectedstore').attr('value', $(this).attr("href"));
        $('input#selectedstorename').attr('value', $(this).attr("rel"));

        // Move the control to where we want it...
        $("table#alternativeStores").hide();
        $('span#mainmessage').html('The product you have selected is available for Click &amp; Collect');

        if ($("#RadCaptcha1").is(":hidden")) {
            $("#RadCaptcha1").toggle();
        }
        if ($("#contactdetails").is(":hidden")) {
            $('#contactdetails').toggle();
        }

        var theCaptchaControl = $("#RadCaptcha1").detach();
        theCaptchaControl.appendTo("div#captcha");
    });

    $('select#stores').change(function () {
        // Only execute if we have a selected store.
        $('div#realtimeprice').text('');
        if ($('select#selectproduct').val() != '0' && $('select#stores').val() != '0' && $('select#counties').val() != '0') {
            if (differentCurrencyRequired($('select#counties').val())) {
                var abinitioParameters = {};
                abinitioParameters['skucode'] = $('select#selectproduct').val();
                abinitioParameters['storeID '] = $('select#stores').val();

                var abinitioCall = {};
                abinitioCall['operation'] = 'GETSKU';
                abinitioCall['anydata'] = '';
                abinitioCall['parameters'] = abinitioParameters;
                abinitioCall['captchaResponse'] = '';

                var result2 = ajaxServiceCall('WebServices/Epos.asmx/RequestAsDictionary', abinitioCall, "json", false);
                if (result2['price'] == undefined) {
                    $('div#realtimeprice').text('Current price not available, please try again later');
                } else {
                    $('div#realtimeprice').text('Current price: ' + priceSymbol($('select#counties').val()) + result2['price']);
                }
            }
        }
    });

    $('input#clickcollectsendcontact').live('click', function (event) {
        event.preventDefault();

        var currentImage = $("input#clickcollectsendcontact").attr('src');
        var currentImageHeight = $("input#clickcollectsendcontact").attr('height');
        var currentImageWidth = $("input#clickcollectsendcontact").attr('width');
        $("input#clickcollectsendcontact").attr('src', findRelativeBasePath() + 'gr/waiting.gif');
        $("input#clickcollectsendcontact").attr('width', 16);
        $("input#clickcollectsendcontact").attr('height', 16);
        /////////////////////////////////////////////////////
        sendToAbinitio();
        /////////////////////////////////////////////////////
        $("input#clickcollectsendcontact").attr('src', currentImage);
        $("input#clickcollectsendcontact").attr('height', currentImageHeight);
        $("input#clickcollectsendcontact").attr('width', currentImageWidth);
        /////////////////////////////////////////////////////
    });

    //Press enter in captcha box
    $("#RadCaptcha1_CaptchaTextBox").keypress(function (event) {
        if (event.which == 13) {
            event.preventDefault();
            var currentImage = $("input#clickcollectsendcontact").attr('src');
            var currentImageHeight = $("input#clickcollectsendcontact").attr('height');
            var currentImageWidth = $("input#clickcollectsendcontact").attr('width');
            $("input#clickcollectsendcontact").attr('src', findRelativeBasePath() + 'gr/waiting.gif');
            $("input#clickcollectsendcontact").attr('width', 16);
            $("input#clickcollectsendcontact").attr('height', 16);
            /////////////////////////////////////////////////////
            sendToAbinitio();
            /////////////////////////////////////////////////////
            $("input#clickcollectsendcontact").attr('src', currentImage);
            $("input#clickcollectsendcontact").attr('height', currentImageHeight);
            $("input#clickcollectsendcontact").attr('width', currentImageWidth);
            /////////////////////////////////////////////////////
        }
    });

    function sendToAbinitio() {
        errorset = 'false';

        if ($("#clickcollectemail").validateEmail() == false) {
            $("#clickcollectemail").attr('style', 'border:1px solid #ff0000;');
            errorset = 'true';
        } else {
            $("#clickcollectemail").removeAttr("style");
        }

        if ((!$("#clickcollectphone").val()) || ($("#clickcollectphone").val() == 'Mobile')) {
            $("#clickcollectphone").attr('style', 'border:1px solid #ff0000;');
            errorset = 'true';
        } else {
            $("#clickcollectphone").removeAttr("style");
        }

        if ((!$("#clickcollectfirstname").val()) || ($("#clickcollectfirstname").val() == 'Firstname')) {
            $("#clickcollectfirstname").attr('style', 'border:1px solid #ff0000;');
            errorset = 'true';
        } else {
            $("#clickcollectfirstname").removeAttr("style");
        }

        if ((!$("#clickcollectsecondname").val()) || ($("#clickcollectsecondname").val() == 'Surname')) {
            $("#clickcollectsecondname").attr('style', 'border:1px solid #ff0000;');
            errorset = 'true';
        } else {
            $("#clickcollectsecondname").removeAttr("style");
        }

        if ((!$("#RadCaptcha1_CaptchaTextBox").val()) || (IsCaptchaValid($("#RadCaptcha1_CaptchaTextBox").val()) == 0)) {
            $("#RadCaptcha1_CaptchaTextBox").attr('style', 'border:1px solid #ff0000;');
            errorset = 'true';
        } else {
            $("#RadCaptcha1_CaptchaTextBox").removeAttr("style");
        }

        if (errorset == 'false') {

            //Generate the order
            var abinitioCall = {};
            var abinitioParameters = {};

            // Abinito Store ID
            abinitioParameters['storeid'] = $('select#stores').val();
            //////////////////////////////////////////////////////////////////
            // NB Peter: first name and surname are mandatory....
            //////////////////////////////////////////////////////////////////
            abinitioParameters['customerfirstname'] = $('#clickcollectfirstname').val();
            abinitioParameters['customersurname'] = $('#clickcollectsecondname').val();
            abinitioParameters['email'] = $('#clickcollectemail').val();
            abinitioParameters['phone'] = $('#MobilePrefix').val() + $('#clickcollectphone').val();
            abinitioParameters['storeid'] = $('#selectedstore').val();

            abinitioCall['parameters'] = abinitioParameters;
            abinitioCall['skuid'] = $('select#selectproduct').val();
            //////////////////////////////////////////////////////////////////
            // NB Peter: can you reference hidden field of what we have selected as the price.
            //////////////////////////////////////////////////////////////////
            abinitioCall['unitprice'] = '19.99'; // to be replaced with hidden field.
            abinitioCall['captchaResponse'] = $("#RadCaptcha1_CaptchaTextBox").val();
            //////////////////////////////////////////////////////////////////
            // NB Peter: Will return the OrderID. We could display on screen?
            //////////////////////////////////////////////////////////////////
            // -1 Captcha failed
            // -2 Error creating order, unspecified, will be in log.
            // -3 No more stock left...
            // 
            var result1 = ajaxServiceCall('WebServices/Epos.asmx/reserveItem', abinitioCall, "json", false);

            //hide contact detailed as we are complete
            if ($("#contactdetails").is(":visible")) {
                $('#contactdetails').toggle();
            }
            if (result1 == '-3') {
                $('span#mainmessage').html('<p><b><font color=\"red\">We apologize that there is no available stock that can be reserved for the Click and Collect process. Please try a different store.</font></b></p>');
            }
            else if (result1 == '-2') {
                $('span#mainmessage').html('<p><b><font color=\"red\">Unfortunately, your reservation could not be completed for the Click and Collect process. The administrator has been notified, please try again later.</font></b></p>');
            }
            else {
                $('span#mainmessage').html('<p>Thank you for completing the Click and Collect process. Your product will now be reserved in your chosen store. Your Reservation Number is <b>' + result1 + '</b></p> <p>We will contact you shortly to confirm your product is ready for collection.</p>');
            }
            //$('span#mainmessage').html('<p>Thank you for completing the Click & Collect process. Your product will now be reserved in your chosen store.</p> <p>Please note your order number is: <b>' + result1 + '</b>.</p> <p>Please keep note of this as it will help track your order more quickly instore.</p>');
        }
    }

});
