﻿jQuery.fn.rotate = function () {
    var t = $(this);
    var n = t.next();
    setTimeout(function () {
        t.animate({ width: 'toggle' }, 750, function () {
            t.animate({ width: 'toggle' }).appendTo(t.parent());
            n.rotate();
        });
    }, 5000);
};

$(function () {
    // Handle the progression through the checkout process
    $('#main #deliveryInformationStart').click(function (e) {
        e.preventDefault();

        if (!$('#deliveryInformation').is(':visible')) {
            $('.step').slideUp();
            gotoNextStepLink($('#deliveryInformation'));
        }
        return false;
    });

    // Handle the progression through the checkout process
    $('#cartpage h1').click(function (e) {
        e.preventDefault();

        if (!$('#main #cart').is(':visible')) {
            $('.step').slideUp();
            gotoNextStepLink($('#main #cart'));
        }
        return false;
    });

    $('#main .buttons a.checkoutBtnLrg').click(function (e) {
        e.preventDefault();
        gotoNextStepLink($('#deliveryInformation'), $('#main #cart'));
        return false;
    });

    // Handle the remove from basket
    $('#the_cart tr.lineItem td.sku input.rem').click(function (e) {
        var t = $(this);
        var r = t.parents('tr.lineItem');

        $.ajax({
            url: "/webservices/Store.svc/RemoveCartItem",
            data: '{ "catalogName": "EmmatCatalog", "sku": "' + t.data('sku') + '", "variantSku": "' + t.data('variantsku') + '"}',
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataFilter: function (data) { return data; },
            success: function (data) {
                if (data) {
                    var item = data.d;
                    if (item) {
                        r.slideUp();

                        t.attr('checked', '');

                        var nr = $('<tr />', { "class": "removed" }).insertAfter(r);
                        var td = $('<td />', { "colspan": 4 }).appendTo(nr);
                        var p = $('<p />', { text: t.data('variantsku') + " has been removed from your cart. " }).appendTo(td);

                        // Create a new table row with the undo stuff
                        $('<a />', {
                            "href": "#",
                            text: "Undo",
                            click: function (e) {
                                e.preventDefault();

                                // Add the items to the cart
                                $.ajax({
                                    url: "/webservices/Store.svc/AddItemToCart",
                                    data: '{ "catalogName": "EmmatCatalog", "sku": "' + t.data('sku') + '", "variantSku": "' + t.data('variantsku') + '", "quantity": ' + $('input.qty', r).val() + '}',
                                    dataType: "json",
                                    type: "POST",
                                    contentType: "application/json; charset=utf-8",
                                    dataFilter: function (data) { return data; },
                                    success: function (data) {
                                        if (data) {
                                            var item = data.d;
                                            if (item) {
                                                nr.slideUp();
                                                r.slideDown();
                                                nr.remove();
                                            } else {
                                            }
                                        } else {
                                        }
                                    }
                                });
                                return false;
                            }
                        }).appendTo(p);
                    } else {
                    }
                } else {
                }
            }
        });
    });

    $('#nav-product #products-search .inp')
        .autocomplete({
            open: function (event, ui) {
                $('ul.ui-autocomplete').css('zIndex', 9999);

            },
            select: function (event, ui) {
                if (ui.item.option)
                    window.location = ui.item.option.Url;
            },
            source: function (request, response) {
                $.ajax({
                    url: "/webservices/Store.svc/KeywordSearch",
                    data: '{ "searchPhrase": "' + request.term + '", "pageSize": "10" }',
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataFilter: function (data) { return data; },
                    success: function (data) {
                        var searchterms = request.term.toLowerCase().replace(/\s/g, '+');
                        if (data.d) {
                            response($.map(data.d, function (item) {
                                var highlightTermRegexp = new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + jQuery.ui.autocomplete.escapeRegex(request.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi");
                                var hightlightTextMarkup = '<strong>$1</strong>';

                                var highlightedTitle = item.Title.replace(highlightTermRegexp, hightlightTextMarkup);
                                var highlightedIntro = item.Intro.replace(highlightTermRegexp, hightlightTextMarkup);

                                var title = "<h2 class='title'>" + highlightedTitle + '</h2>';
                                var intro = "<p class='intro'>" + highlightedIntro + '</p>';

                                var labelText = '';
                                if (item.ImageUrl != '')
                                    labelText = "<img src='" + item.ImageUrl + "' alt='Image of " + item.Title + "' class='prodImage'/><div>";
                                labelText = labelText + title + intro;
                                if (item.ImageUrl != '')
                                    labelText = labelText + '</div>';
                                labelText = "<a class='" + item.ResultType + "' href='" + item.Url + "'>" + labelText + '</a>';

                                return {
                                    label: labelText,
                                    value: item.Title,
                                    option: item,
                                    terms: searchterms
                                };
                            }));

                        } else {
                            var noitems = [{
                                label: '<p class="tip">Sorry, we couldn\'t find any results for <strong><em>' + searchterms + '</em></strong>. Please try something else.</p>',
                                value: searchterms,
                                option: null,
                                terms: searchterms
                            }];

                            response(noitems);
                        }
                    }
                });
            },
            search: function () {
                showSearchTip($(this), 'Searching, please wait...');
            },
            minLength: 4,
            delay: 300,
            max: 10,
            autoSelect: true,
            autoFill: true,
            html: true
        })
        .focus(function () {
            // Show the "type to search" message
            var t = $(this);
            if (t.val() == '') {
                showSearchTip(t, 'Start typing to search and your results will appear here.');
            }
        })
        .keypress(function (e) {
            // Disable the enter key
            return (e.keyCode != 13);
        });
    
    if ($('#banner li').length > 1)
        $('#banner li:first').rotate();

    /*-----------------------------------------------------------------------------------------------------------------

    Product Details

    -----------------------------------------------------------------------------------------------------------------*/
    //Handle the jump to variants link
    $('#jumptoVariants').click(function (e) {
        e.preventDefault();
        $.scrollTo($('#variations'), 500);
        return false;
    });

    // Handle the add to basket code
    $('#product-variants td.buttons button.addToBasket').click(function (e) {
        e.preventDefault();
        var t = $(this);
        var r = t.parents('tr');

        t.hide();

        //Show a preloader to let the user know there is something going on
        var loading = showSaving("Saving.");
        loading.insertAfter(t);

        // Add the items to the cart
        $.ajax({
            url: "/webservices/Store.svc/AddItemToCart",
            data: '{ "catalogName": "EmmatCatalog", "sku": "' + $('input[name=sku]', r).val() + '", "variantSku": "' + $('input[name=variantSku]', r).val() + '", "quantity": 1}',
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataFilter: function (data) { return data; },
            success: function (data) {
                //console.log(data);
                if (data) {
                    var item = data.d;
                    if (item) {
                        // Create a new row
                        var addedRow = $('<tr />').insertAfter(r);

                        _gaq.push(['_setCustomVar', 1, 'Items Added', 'Yes', 2]);
                        _gaq.push(['_trackEvent', 'Shopping', 'Item Added']);

                        $('<td />', {
                            "class": "item-added",
                            "colspan": "3",
                            html: 'Added to quote. <a href="/quote/">Click here to view now</a>.'
                        }).appendTo(addedRow);

                        t.fadeIn();
                        loading.remove();

                        // Hide the add to basket row
                        addedRow.show();
                        setTimeout(function () {
                            addedRow.find('td')
                                .wrapInner('<div style="display: block;" />')
                                .parent()
                                .find('td > div').slideUp('slow', function () {
                                    addedRow.remove();
                                });
                        }, 15000);
                    } else {
                        // Nothing came back at all
                        //console.log("No item");
                    }
                } else {
                    // Nothing came back at all
                    //console.log("No data");
                }
            }
        });

        return false;
    });
});

function showSearchTip(searchInput, message) {
    var ac = searchInput.data("autocomplete");

    var ul = $('.ui-autocomplete').zIndex(ac.element.zIndex() + 1);

    ul.empty();

    // Add the "start typing" item
    $('<li />', {
        "class": "ui-menu-item",
        "role": "menuitem",
        html: '<p class="tip">' + message + '</p>'
    }).appendTo(ul);

    ac.menu.deactivate();
    ac.menu.refresh();

    // size and position menu
    ul.show();
    ac._resizeMenu();
    ul.position($.extend({
        of: ac.element
    }, ac.options.position));
}

function gotoNextStepLink(nextStep, from) {
    var scroll = nextStep.prev('h2');

    if (scroll.length <= 0)
        scroll = $('#cartpage h1');

    $.scrollTo($('.container'), 0);
    $('.step').slideUp();


    nextStep.slideDown(500, function () {
        $.scrollTo(scroll, 800);
    });
}
function showSaving(textToShow) {
    var loading = $('<p />', { "class": "saving" });

    if (!textToShow || textToShow.length === 0) {
        textToShow = " Saving, one moment please.";
    }

    //Show a preloader to let the user know there is something going on
    $('<img />', {
        "src": "/img/spinner.gif",
        "width": "10",
        "height": "10",
        "alt": "Spinning circle."
    }).appendTo(loading).after(textToShow);

    return loading;
}

