/// <reference path="jquery-1.3.2-vsdoc2.js" />

$(document).ready(
    function() {

        /* Get JSON and render on page */
        var dataCondoms = eval($('#ctl00_bodyTag_PlaceholderMain_dataElementCondoms').val());

        var dataLubes = eval($('#ctl00_bodyTag_PlaceholderMain_dataElementLubes').val());


        //make sure both display divs are empty
        $('.navigator.condoms .item-holder').empty();
        $('.navigator.lubes .item-holder').empty();

        DoRender(dataCondoms, "condoms");

        DoRender(dataLubes, "lubes");

        // Empty Selected items div to make sure no unrequire whitespace interferes with selection empty check
        $('.selection .items').empty();
        selectionEmpty();

        //resets selection in submit element - main use is to wipe selection when users hit back button
        var jsonStartData = eval($('#ctl00_bodyTag_PlaceholderMain_submitElement').val());
        var templateJsonObject = jsonStartData[0];
        $('#ctl00_bodyTag_PlaceholderMain_submitElement').val('[' + JSON.stringify(templateJsonObject) + ']'); 


        /* set width of item-holder div based on number of container items */
        $('.condoms .item-holder').width($('.condoms .item').size() * 155);
        $('.lubes .item-holder').width($('.lubes .item').size() * 155);

        /* Load horizontal scroll styling */
        $('.scroll-box').jScrollHorizontalPane({
            scrollbarHeight: 26,
            scrollbarMargin: 5,
            wheelSpeed: 40,
            dragMaxWidth: 48
        });

        // Hide main content area
        $('.main').hide();

        /* Hide splash show main page */
        $('a.get-picking').click(
            function() {
                $('.intro').hide();
                $('.main').animate({ 'foo': 'bar' }, 10).show();
                $('.add-to-basket a').hide();
                return false;
            }
        );

        /* Hover Short Description */
        $('.item .image').hover(
        function() {
            var shortDesc = $(this).find('.short-desc').html();
            $('#tool-hover .short-desc .bd').html(shortDesc);
            $(this).mousemove(function(e) {
                $('#tool-hover .short-desc').css({ 'left': e.pageX + 10, 'top': e.pageY + 0 - $('#tool-hover .short-desc').height() }).show();
            })
        }
        ,
        function() {
            $(this).unbind('mousemove');
            $('#tool-hover .short-desc').hide();

        });

        // Click Full Description
        $('.item .image').click(
                function() {
                    //var img = $(this).find('img').html();
                    var imgUrl = $(this).find('img').attr('src');
                    var title = $(this).find('.item-name').html();
                    var shortDesc = $(this).find('.short-desc').html();
                    var longDesc = $(this).find('.long-desc').html();

                    $('#product-details .bd .product-image').attr('src', imgUrl);
                    //$('#product-details .bd .product-image').html(img);
                    $('#product-details .bd .item-name').html(title);
                    //$('#product-details .bd .short-desc').html(shortDesc);
                    $('#product-details .bd .long-desc').html(longDesc);

                    $('#product-details').show();
                });

        // Close Full Description
        $('#product-details .close').click(
                function() {
                    $('#product-details').hide();
                    return false;
                });





        /* Add item to selection */
        $('.select-link a').click(function() {

            var jsonObject = eval($('#ctl00_bodyTag_PlaceholderMain_submitElement').val());

            var temp = jsonObject[0];

            jsonObject = eval($('#ctl00_bodyTag_PlaceholderMain_submitElement').val());

            //Lets get the current selected product if any
            var productCode = $(this).parent().parent().find('.item-info .item-sku').text();

            var existingElement = jsonPath(jsonObject, "$..[?(@.ProductId==" + productCode + ")]");

            if (existingElement == false) {
                temp.ProductId = $(this).parent().parent().find('.item-info .item-sku').text();

                temp.ProductName = $(this).parent().parent().find('.item-info .item-name').text();

                temp.Quantity = 1;

                jsonObject.push(temp);
            }
            else {
                existingElement[0].Quantity++;

            }

            $('#ctl00_bodyTag_PlaceholderMain_submitElement').val(JSON.stringify(jsonObject));

            //$('#selected').html(JSON.stringify(jsonObject)); //use for debugging

            $('.selection .items').empty();

            updateSelection(jsonObject);

            itemCount();

            selectionEmpty();

            return false;
        });

        /* Add to basket */
        $('.add-to-basket a').click(function() {
            $('.hidden-button').click();
        });

        /* Hover Add to Basket */
        $('.add-to-basket a').hover(
        function() {
            var shortDesc = $(this).find('.short-desc').html();
            $('#tool-hover .short-desc .bd').html('If you wish to change your mix at a later stage you will need to remove your selection from your basket and start picking again');
            $(this).mousemove(function(e) {
                $('#tool-hover .short-desc').css({ 'left': e.pageX + 10, 'top': e.pageY + 0 - $('#tool-hover .short-desc').height() }).show();
            })
        }
        ,
        function() {
            $(this).unbind('mousemove');
            $('#tool-hover .short-desc').hide();

        });

        //end of doc ready
    }
);


/* Remove item from selection - Event get's bound on add to selection */
function removeHandler() {

    var productCode = $(this).parent().parent().find('.item-sku').html();

    var jsonObject = eval($('#ctl00_bodyTag_PlaceholderMain_submitElement').val());

    var elementIndex = -1;

    $.each(jsonObject, function(index, entry) {

        if (entry['ProductId'] == productCode) {
            elementIndex = index;
        }

    });


    if (elementIndex > -1) {
        jsonObject.splice(elementIndex, 1)
        $(this).parent().parent().remove();
    }

    $('#ctl00_bodyTag_PlaceholderMain_submitElement').val(JSON.stringify(jsonObject));

    //$('#selected').html(JSON.stringify(jsonObject)); //use for debugging

    itemCount();

    selectionEmpty();

    return false;
}

/* Increment Quantity */
function incHandler() {

    var productCode = $(this).parent().parent().find('.item-sku').html();

    var jsonObject = eval($('#ctl00_bodyTag_PlaceholderMain_submitElement').val());

    var existingElement = jsonPath(jsonObject, "$..[?(@.ProductId==" + productCode + ")]");

    if (existingElement[0].Quantity < 1) {
        existingElement[0].Quantity = 1;
    }
    else {
        existingElement[0].Quantity++;
    }

    $('#ctl00_bodyTag_PlaceholderMain_submitElement').val(JSON.stringify(jsonObject));

    //$('#selected').html(JSON.stringify(jsonObject)); //use for debugging

    updateSelection(jsonObject);

    itemCount();

    return false;
}

/* Decrement Quantity */
function decHandler() {

    var productCode = $(this).parent().parent().find('.item-sku').html();

    var jsonObject = eval($('#ctl00_bodyTag_PlaceholderMain_submitElement').val());

    var existingElement = jsonPath(jsonObject, "$..[?(@.ProductId==" + productCode + ")]");

    if (existingElement[0].Quantity <= 1) {
        existingElement[0].Quantity = 1;
    }
    else {
        existingElement[0].Quantity--;
    }


    $('#ctl00_bodyTag_PlaceholderMain_submitElement').val(JSON.stringify(jsonObject));

    // $('#selected').html(JSON.stringify(jsonObject)); //use for debugging

    updateSelection(jsonObject);

    itemCount();

    return false;
}

/* Keyboard quantity change */
function keyHandler() {

    var productCode = $(this).parent().parent().find('.item-sku').html();

    var newQuantity = $(this).val();

    var jsonObject = eval($('#ctl00_bodyTag_PlaceholderMain_submitElement').val());

    var existingElement = jsonPath(jsonObject, "$..[?(@.ProductId==" + productCode + ")]");

    if (newQuantity == '' || newQuantity == null || isNaN(newQuantity)) {
        $(this).val(1);
        existingElement[0].Quantity = 1;
        $(this).parent().parent().find('.item-price').html('&pound;' + GetPrice(1));
        itemCount();
        return false;
    }

    newQuantity = parseInt(newQuantity);

    if (newQuantity < 1) {
        existingElement[0].Quantity = 1;
        $(this).val(1);
        $(this).parent().parent().find('.item-price').html('&pound;' + GetPrice(1));
    }
    else {
        existingElement[0].Quantity = newQuantity;
        $(this).parent().parent().find('.item-price').html('&pound;' + GetPrice(newQuantity));
    }

    $('#ctl00_bodyTag_PlaceholderMain_submitElement').val(JSON.stringify(jsonObject));

    itemCount();

    return false;
}

/* Quantity input field select on click */
function selectHandler() {

    $(this).select();

    return false;
}



function GetPrice(Qty) {

    var price = (Qty * 100) / 100;

    return price.toFixed(2);
}



function itemCount() {

    var totalItems = 0;

    $('.selection .items .item-holder').each(function(index) {
        var itemQuantity;
        itemQuantity = $(this).find('.item-quantity input.qty-input').attr('value') - 0;
        totalItems += itemQuantity;
    });

    if (totalItems < 5) {
        $('.add-to-basket a').hide();
    }
    else {
        $('.add-to-basket a').show();
    }

    $('.selection .number span.no-of-items').text(totalItems);
}


function updateSelection(jsonObject) {
    $('.selection .items').empty();

    $.each(jsonObject, function(index, entry) {

        if (entry['ProductId'] != '') {
            var html = '<div class="item-holder">';
            html += '<div class="item-sku">' + entry['ProductId'] + '</div>';
            html += '<div class="item-name">' + entry['ProductName'] + '</div>';
            html += '<div class="item-quantity">Quantity: <input type="text" class="qty-input" value="' + entry['Quantity'] + '" />';
            html += '<input type="button" class="up" value="Up" /><input type="button" class="down" value="Down" />';
            html += '</div>'; //item-quantity

            html += '<div class="item-price">&pound;' + GetPrice(entry['Quantity']) + '</div>';
            html += '<div class="remove-link">' + '<a href="#">Remove</a> ' + '</div>';
            html += '</div>'; //item-holder
            $('.selection .items').append(html);
            $('.remove-link a').bind('click', removeHandler);
            $('input.up').bind('click', incHandler);
            $('input.down').bind('click', decHandler);
            $('input.qty-input').bind('keyup', keyHandler);
            $('input.qty-input').bind('blur', keyHandler);
            $('input.qty-input').bind('click', selectHandler);
        }
    });
}

function doSubmit() {


}

function DoRender(data, type) {

    //loop through json objects and extract info
    $.each(data, function(index, entry) {
        var html = '<div class="item">';
        html += '<div class="name">' + entry['Name'] + '</div>';
        html += '<div class="image"> <img src="' + entry['PrimaryProductImage'].LargeImage + '" alt="' + entry['PrimaryProductImage'].AltText + '" />';
        html += '<div class="item-info">';
        html += '<div class="item-sku">' + entry['ProductCode'] + '</div>';
        html += '<div class="item-name">' + entry['Name'] + '</div>';
        html += '<div class="short-desc">' + entry['ShortDescription'] + '</div>';
        html += '<div class="long-desc">' + entry['LongDescription'] + '</div>';
        html += '</div>'; //item-info
        html += '</div>'; //image
        html += '<div class="select-link">' + '<a href="#">Select</a></div>';
        html += '</div>'; //item
        //$('.navigator.condoms .item-holder').append(html);

        $('.navigator.' + type + ' .item-holder').append(html);
    });
}

function selectionEmpty() {
    if ($('.selection .items').html() == '') {
        $('.selection .items').html('No products selected');
    }
}