﻿$(document).ready(function () {

    // Init Search dropdown
    /* $('#searchinput').autocomplete({
    source: function (e, r) {
    data = $.ajax(
    {
    url: '/Services/Product.asmx/Search',
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    data: '{search:\'' + e.term + '\'}',
    dataType: 'json',
    success: function (result) { r(result.d) }
    }
    )
    },
    select: function (event, ui) {
    //alert(ui.item.sku);
    },
    delay: 500,
    minLength: 3,
    width: 530,
    max: 15,
    highlight: true
    }).watermark('Search...');*/

    $('.list-product').mouseover(function () {
        $(this).find('.list-product-description').show();
    });

    $('.list-product').mouseout(function () {
        $(this).find('.list-product-description').hide();
    });

    $('.tab-controls a').click(function () {
        if(!$(this).hasClass('size-guide')){
            $(this).parent('.tab-controls').find('a').each(function () {
                $(this).removeClass('selected-tab');
            });

            $(this).addClass('selected-tab');

            var $tabs = $(this).parents('.tab-container').find('.tab');
            $tabs.each(function () {
                $(this).removeClass('active-tab');
            });
            $('#' + $(this).data('tab')).addClass('active-tab');
            return false;
        }
    });

    $('#popupContainer').hover(function () {
        $('#customerServicesMenu').fadeIn();
    }, function () {
        $('#customerServicesMenu').fadeOut();
    });

    //Video Dropdowns
    $('.video_dropdown_head').click(function () {
        if (!$(this).hasClass("noSlide")) {
            if ($(this).data("active") != true) {
                $(this).data("active", true).children('p.active').show();
                $(this).children("p.inactive").hide();
                $(this).next().slideDown("slow");
            }
            else {
                $(this).data("active", false).children('p.active').hide();
                $(this).children("p.inactive").show();
                $(this).next().slideUp("slow");
            }
        }

    });
});

function fixLocation() {
    var i = $(this);
    var o = i.parent().offset();
    i.css('left', o.left);
    i.css('top', o.top + i.parent().outerHeight(false));

    var s = i.offset().left + i.outerWidth(false) - $(window).width();
    if (s > 0)
        i.css('left', i.offset().left - s);
}

function toggleTab(item) {
    var p = $(item).parents(".tabcontainer");

    p.find(".box").hide();
    p.find(".tabs li").removeClass("active");

    $(item).parent("li").addClass("active");

    var href = $(item).attr('href');
    $(href).show();
}

function activateTabs() {
    $(".tabcontainer .tabs a").click(function () {
        if ($(this).is(".nottab"))
            return;
        toggleTab(this);
        return false;
    });
}

function confirmProductAdded() {
    $('.productAdded').dialog({
        show: 'blind',
        title: 'Product Added'
    });
}

var matrix = {};
matrix.mode = 's';

function initializeMultiMatrix() {

    matrix.mode = 'm';

    matrix.selection = new Array();

    $(".configure").each(function () {
        matrix.selection.push({
            template: parseSku(this),
            selected: ''
        });
    }).click(function () {
        initializeMatrix(parseSku(this));
        $(".kititem.selected").removeClass('selected');
        $(this).parent().addClass('selected');
        $(this).find(".help").text('Selecting product');
    });

    $("#addToBasket").click(function () {
        var count = 0;
        $(matrix.selection).each(function (key, value) {
            if (value.selected == '') count++;
        });

        if (count > 0) {
            alert('You still have ' + count + ' items in this pack left to configure.');
            return false;
        } else {
            var f = $('form');
            $(matrix.selection).each(function (key, value) {
                var sku = value.selected;
                f.append('<input type="hidden" name="sku' + sku + '" value="' + sku + '" />');
            });
        }
    });
}

function initializeMatrix(templateSku) {

    matrix.templateSku = templateSku;
    matrix.xml = $('body').data('matrix-' + templateSku);
    matrix.supplierMsg = $('body').data('supplierMsg-' + templateSku);

    loadXml(matrix.xml);

    var m = $('#matrix_select');

    if (matrix.mode == 's') {

        m.find("#matrixA").remove();
        m.find("#matrixB").remove();

        var mC = m.find("#matrixC");

        if (matrix.arrC.length <= 1) {
            mC.remove();
            createMatrixTable(m);
        } else {
            createMatrixTable(m);
            mC.find("#elementC").change(function () {
                createMatrixTable();
                _gaq.push(['_trackEvent', 'StockGrid', 'ElementC', templateSku + ' ' + $(this).val()]);
            }).val(setDefault).change();
        }

        $("#addToBasket").click(function () {
            if (m.find("#variantSku").val() == "") {
                alert("Please select a colour/size first");
                return false;
            }
        });
    } else {
        m.empty();

        if (matrix.arrC.length > 1) {

            var cHtml = '<span id="definitionC" class="definition">Style:</span> ';

            cHtml += '<select id="elementC" name="elementC">';
            for (i = 0; i < matrix.arrC.length; i++)
                cHtml += '<option value="' + matrix.arrC[i].element + '">' + matrix.arrC[i].desc + '</option>';
            cHtml += '</select>';

            m.append(cHtml);

            m.find("#elementC").change(function () {
                createMatrixTable();
                _gaq.push(['_trackEvent', 'StockGrid', 'ElementC', templateSku + ' ' + $(this).val()]);
            }).val(setDefault).change();
        } else {
            var cHtml = '<input name="elementC" type="hidden" value="' + matrix.arrC[0].element + '" />';
            m.append(cHtml);
        }

        createMatrixTable(m);


    }
}

function setDefault(index, value) {
    var e = new Array();

    for (i = 0; i < matrix.arrC.length; i++)
        e.push(matrix.arrC[i].element);

    if ($.inArray('R', e) > -1)
        return 'R';
    else
        return 'S';
}

function createMatrixTable() {

    var m = $('#matrix_select');
    var elementC = m.find("#elementC").val();
    if (elementC == undefined)
        elementC = m.find("input[name=elementC]").val();

    m.find("#matrixGrid").remove();

    var title = "Select your ";

    var combo = "";
    if (matrix.arrA.length > 1)
        combo += "Colour, ";
    if (matrix.arrB.length > 1)
        combo += "Size, ";
    if (matrix.arrC.length > 1)
        combo += "Length, ";

    if (combo != "")
        combo = combo.substring(0, combo.lastIndexOf(', ')) + ' ';

    title += combo + "combination";
    m.find("#matrixTitle").text(title);

    var tbl = "<div id=\"matrixGrid\">";
    tbl += "<div id=\"msgcontainer\"><div id=\"stockmsg\"></div></div>";
    tbl += "<div id=\"scroll\">";
    tbl += "<table id=\"matrixTable\">";
    tbl += "<thead><tr>";
    tbl += "<td>&nbsp;</td>";
    for (i = 0; i < matrix.arrB.length; i++)
        tbl += "<td class=\"t\">" + matrix.arrB[i].desc + "</td>";
    tbl += "</tr></thead>";
    tbl += "<tbody>";

    for (i = 0; i < matrix.arrA.length; i++) {
        tbl += "<tr>";
        tbl += "<td><span class=\"colour\" style=\"background-color:" + matrix.arrA[i].colour + "\" >&nbsp;</span>" + matrix.arrA[i].desc + "</td>";

        for (j = 0; j < matrix.arrB.length; j++) {
            var thisSku = matrix.templateSku + matrix.arrA[i].element + matrix.arrB[j].element + elementC;
            if (thisSku.length > 20)
                thisSku = thisSku.substring(0, 20);

            var c = "out";
            var msg = "Colour/size currently un-available";

            for (k = 0; k < matrix.skus.length; k++) {
                var item = matrix.skus[k];
                if (item.sku == thisSku) {

                    if (item.inStock == '2') {
                        c = "nd";
                    } else if (item.inStock == '1') {
                        c = "in";
                    } else {
                        c = "out";
                    }

                    if (item.inStock != '0') {
                        if (item.qty > 3)
                            msg = "Plenty left in stock.";
                        else if (item.qty > 0)
                            msg = "In Stock";
                        else
                            msg = "";
                    }

                    break;
                }
            }

            tbl += "<td><a class=\"" + c + "\" href=\"#" + thisSku + "\" title=\"" + msg + "\"></a></td>";
        }

        tbl += "</tr>";
    }

    tbl += "</tbody>";
    tbl += "</table>";
    tbl += "</div>";
    tbl += "</div>";

    m.append(tbl);

    m.find("a.in, a.nd").click(function () {
        m.find("a").removeClass('selected');

        var sku = parseSku(this);
        var price = 0;
        var title = "";

        for (i = 0; i < matrix.skus.length; i++)
            if (matrix.skus[i].sku == sku) {
                price = matrix.skus[i].price;
                title = matrix.skus[i].title;
                break;
            }

        if (matrix.mode == 's') {
            m.find("#variantSku").val(sku);
            $("#price").html("&#163;" + new Number(price).toFixed(2));
        } else {
            var t = $('#matrix_select_multi').find('a[href=#' + matrix.templateSku + ']').parent();
            t.addClass('configured');
            t.find(".title").text(title);
            t.find(".help").text('Product Selected');

            $(matrix.selection).each(function (index, value) {
                if (value.template == matrix.templateSku) {
                    value.selected = sku;
                    return false;
                }
            });
        }

        $(this).addClass('selected');

        _gaq.push(['_trackEvent', 'StockGrid', 'Select', sku]);

        return false;
    });

    if (matrix.skus.length == 1) {
        m.find("#matrixTitle").hide();
        m.find("a.in, a.nd").click();
    }

    m.find("a").mouseover(function () {

        if ($(this).attr('title') != "") {
            $.data(this, 'title', $(this).attr('title'));
            $(this).attr('title', "");
        }

        var title = $.data(this, 'title');
        if (title == undefined)
            title = "";

        if ($(this).is(".in") && matrix.supplierMsg != "") {
            title = "<span class=\"nextday\">" + matrix.supplierMsg + "</span> " + title;
        } else if ($(this).is(".nd")) {
            title = "<span class=\"nextday\">Next day delivery available.</span> " + title;
        }

        m.find("#stockmsg").fadeIn().html(title);
    });

    m.find("a").mouseout(function () {
        m.find("#stockmsg").hide().text("");
    });
}

function parseSku(e) {
    return $(e).attr('href').substring($(e).attr('href').lastIndexOf('#') + 1);
}

function loadXml(xml) {

    xmlDoc = null;

    xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + xml;

    if (window.DOMParser) {
        parser = new DOMParser();
        xmlDoc = parser.parseFromString(xml, "text/xml");
    }
    else // Internet Explorer
    {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xml);
    }

    matrix.arrA = new Array();
    matrix.arrB = new Array();
    matrix.arrC = new Array();
    matrix.skus = new Array();

    populateArray(xmlDoc, matrix.arrA, 'ElementA');
    populateArray(xmlDoc, matrix.arrB, 'ElementB');
    populateArray(xmlDoc, matrix.arrC, 'ElementC');

    $(xmlDoc).find("Matrix").each(function () {
        var val = {
            sku: $(this).find('Sku').text(),
            qty: $(this).find('Qty').text(),
            inStock: $(this).find('InStock').text(),
            price: $(this).find('Price').text(),
            title: $(this).find('Title').text()
        };

        matrix.skus.push(val);
    });
}

function populateArray(xmlDoc, array, id) {

    $(xmlDoc).find(id).each(function () {
        var val = {
            element: $(this).find('Element').text(),
            desc: $(this).find('Description').text(),
            colour: $(this).find('Colour').text()
        };

        array.push(val);
    });
}

var slideMenu = function () {
    var sp, st, t, m, sa, l, w, sw, ot;
    return {
        build: function (sm, sw, mt, s, sl, h) {
            sp = s; st = sw; t = mt;
            m = document.getElementById(sm);
            sa = m.getElementsByTagName('li');
            l = sa.length; w = m.offsetWidth; sw = w / l;
            ot = Math.floor((w - st) / (l - 1)); var i = 0;
            for (i; i < l; i++) { s = sa[i]; s.style.width = sw + 'px'; this.timer(s) }
            if (sl != null) { m.timer = setInterval(function () { slideMenu.slide(sa[sl - 1]) }, t) }
        },
        timer: function (s) { s.onmouseover = function () { clearInterval(m.timer); m.timer = setInterval(function () { slideMenu.slide(s) }, t) } },
        slide: function (s) {
            var cw = parseInt(s.style.width, '10');
            if (cw < st) {
                var owt = 0; var i = 0;
                for (i; i < l; i++) {
                    if (sa[i] != s) {
                        var o, ow; var oi = 0; o = sa[i]; ow = parseInt(o.style.width, '10');
                        if (ow > ot) { oi = Math.floor((ow - ot) / sp); oi = (oi > 0) ? oi : 1; o.style.width = (ow - oi) + 'px' }
                        owt = owt + (ow - oi)
                    }
                }
                s.style.width = (w - owt) + 'px';
            } else { clearInterval(m.timer) }
        }
    };
} ();
