﻿// Coded by Ice Design
// © 2009 Ice Design bvba // info@icedesign.be

$(function() {
    // no cache for all AJAX functions
    $.ajaxSetup({
        cache: false
    });

    // global variables
    var itemToDelete = "";
    var deleteId = "";
    var orderId = "";
    var pagePath = window.location.pathname;
    var orderStep = 1;

    // just do some stuff by every page-load
    SetListItemColors();
    $.updateBasket();
    $.updateSummary();

    // hover line in list
    $(".listItem").hover(function() {
        $(this).css("background-color", "#f6f6f6");
    }, function() {
        $(this).css("background-color", "#ffffff");
    });

    // begin in the picture

    $(".inThePictureIcon").click(function(e) {
        orderItemId = $(this).parents(".listItem").attr('id');
        var data = "id=" + orderItemId;

        $.ajax({
            type: "POST",
            url: "/Product/AddInThePicture",
            data: data,
            dataType: "html",
            success: function(result) {
                getInThePicture();
            }
            //,
            //error: function(xhr, status, error) {
            //}
        });
        return false;
    });

    getInThePicture();

    function getInThePicture() {
        $.get("/Product/GetInThePicture", function(result) { showInThePicture(eval(result)); }, "json");
    }

    function showInThePicture(inThePicture) {
        $(".inThePictureIcon").attr("src", "../../Content/Images/star.png");
        for (var i in inThePicture) {
            $("#item_" + inThePicture[i].Id).children(".listItemIconsLeft").children(".inThePictureIcon").attr("src", "../../Content/Images/star-red.png");
        }
    }

    // end in the picture

    // begin suggestions

    $(".suggestionIcon").click(function(e) {
        orderItemId = $(this).parents(".listItem").attr('id');
        var data = "id=" + orderItemId;

        $.ajax({
            type: "POST",
            url: "/Product/AddSuggestion",
            data: data,
            dataType: "html",
            success: function(result) {
                getSuggestions();
            }
            //,
            //error: function(xhr, status, error) {
            //}
        });
        return false;
    });

    getSuggestions();

    function getSuggestions() {
        $.get("/Product/GetSuggestions", function(result) { showSuggestions(eval(result)); }, "json");
    }

    function showSuggestions(suggestions) {
        $(".suggestionIcon").attr("src", "../../Content/Images/star.png");
        for (var i in suggestions) {
            $("#item_" + suggestions[i].ProductId).children(".listItemIconsLeft").children(".suggestionIcon").attr("src", "../../Content/Images/star-highlight.png");
        }
    }

    // end suggestions

    //  // get full menu through ajax (in seperate js file)
    //    $(".loading").show();
    //    $.get("/Menu/GetCategories", function(result) { loadFullMenu(eval(result)); }, $(".loading").remove(), "json");

    //    function loadFullMenu(categories) {
    //        for (var i in categories) {
    //            var rows = "";
    //            for (var j in categories[i].Products) {
    //                rows += "<div class='row'>"
    //                     + "<div class='rowColumnLeft'>" + categories[i].Products[j].Name + "<br/><span class='description'>" + categories[i].Products[j].Description + "</span></div>";

    //                if (categories[i].Products[j].Prices[1].Amount != 0)
    //                    rows += "<div class='rowColumnRight priceTag' style='width: 60px' id='item_" + categories[i].Products[j].Prices[1].Id + "'>" + categories[i].Products[j].Prices[1].Amount.toFixed(2) + " €</div>";

    //                rows += "<div class='rowColumnRight priceTag' style='width: 60px' id='item_" + categories[i].Products[j].Prices[0].Id + "'>" + categories[i].Products[j].Prices[0].Amount.toFixed(2) + " €</div>"
    //                     + "</div>";
    //            }

    //            $("#accordion").append('<div class="header"><a href="#">' + categories[i].Name + '</a></div><div class="accordionDiv">' + rows + '</div>');
    //        }

    //        $.setupAccordion();
    //    }

    // menu accordion
    $.setupAccordion = function() {
        $("#accordion").accordion({
            active: false,
            autoHeight: false,
            collapsible: true,
            header: "div.header",
            changestart: function(event, ui) {
                //alert(ui.newHeader.attr("id"));
                $.get("/Menu/GetProdsForCategory?categoryId=" + ui.newHeader.attr("id"), function(result) {

                    var products = eval(result);
                    var rows = "";

                    for (var j in products) {
                        rows += "<div class='row'>"
                                         + "<div class='rowColumnLeft'>" + products[j].Name + "<br/><span class='description'>" + products[j].Description + "</span></div>";

                        if (products[j].Prices[1].Amount != 0)
                            rows += "<div class='rowColumnRight priceTag' style='width: 60px' id='item_" + products[j].Prices[1].Id + "'>" + products[j].Prices[1].Amount.toFixed(2) + " €</div>";

                        if (products[j].Prices[0].Amount != 0)
                            rows += "<div class='rowColumnRight priceTag' style='width: 60px' id='item_" + products[j].Prices[0].Id + "'>" + products[j].Prices[0].Amount.toFixed(2) + " €</div>"

                        rows += "</div>";
                    }

                    ui.newHeader.next("div.accordionDiv").html(rows);

                }, "json");
            }
        });

        // IE shit
        //if ($.browser.msie) {
        //    $('#accordion').css('zoom', '1');
        //} 

        // color price tags in menu on hover
        $(".priceTag").livequery(function() {
            $(this)
            .hover(function() {
                $(this).toggleClass('hoveredPrice');
            }, function() {
                $(this).toggleClass('hoveredPrice');
            });
        }, function() {
            $(this)
            .unbind('mouseover')
            .unbind('mouseout');
        });


        // order item by clicking on its price
        $(".priceTag").livequery('click', function(e) {
            //$(".priceTag").click(function(e) {
            orderItemId = $(this).attr('id');
            var data = "id=" + orderItemId;

            $.ajax({
                type: "POST",
                url: "/Order/ItemToBasket",
                data: data,
                dataType: "html",
                success: function(result) {
                    $.updateBasket();
                }
                //,
                //error: function(xhr, status, error) {
                //}
            });
            return false;
        });
    }

    // masked input fields
    $("#deliveryDate").mask("99/99/9999");
    $("#deliveryHour").mask("99:99");

    // order date picker
    $("#deliveryDate").datepicker({
        dateFormat: 'dd/mm/yy',
        dayNamesMin: ['Zo', 'Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za'],
        monthNames: ['Januari', 'Februari', 'Maart', 'April', 'Mei', 'Juni', 'Juli', 'Augustus', 'September', 'Oktober', 'November', 'December'],
        duration: '',
        firstDay: 1,
        onSelect: function() { CheckDate($(this)); }
    });

    // hide all order steps higher than 1
    $("#step2part").hide();
    $("#step3part").hide();
    $("#step4part").hide();

    // mark order step 1 and the first deleveryType
    $("#step1").addClass('selectedOrderStep');
    $("#deliveryType1").addClass('selectedOrderStep');

    // preload images
    $.preloadImages("../../Content/Images/detail-lgray.png",
    "../../Content/Images/detail-dgray.png",
    "../../Content/Images/delete-lgray.png",
    "../../Content/Images/delete-dgray.png",
    "../../Content/Images/check-dgray.png",
    "../../Content/Images/check-green.png");

    // begin ingredients popup screen

    $(".ingredientsTrigger").click(function() {
        centerPopup();

        ingredientItem = $(this).parents('.listItem');
        itemId = ingredientItem.attr('id');

        loadPopup(itemId);
    });

    $("#popupContactClose").click(function() {
        disablePopup();
    });

    $("form#extraInfo").submit(function() {
        hijack(this, extraInfoSaved, "html");
        return false;
    });

    function extraInfoSaved(result) {
        disablePopup();
    };

    //    $("#backgroundPopup").click(function() {
    //        disablePopup();
    //    });

    // press escape button on keyboard 
    $(document).keypress(function(e) {
        if (e.keyCode == 27 && popupStatus == 1) {
            disablePopup();
        }
    });

    // end ingredients popup screen

    // sortable list
    $("#sortableList").sortable({
        cursor: "move",
        axis: 'y',
        update: function(e, ui) {
            var items = $(this).sortable("serialize");
            $.post("../../Category/Move", items, function(result) { }, "json");
            SetListItemColors();
        }
    });
    $("#sortableList").disableSelection();

    // sortable list
    $("#sortableListProducts").sortable({
        cursor: "move",
        axis: 'y',
        update: function(e, ui) {
            var items = $(this).sortable("serialize");
            $.post("../../Product/Move", items, function(result) { }, "json");
            SetListItemColors();
        }
    });
    $("#sortableListProducts").disableSelection();

    // sortable list
    
    $("#sortableListSuggestions").sortable({
        cursor: "move",
        axis: 'y',
        update: function(e, ui) {
            var items = $(this).sortable("serialize");
            $.post("../../Product/MoveSuggestion", items, function(result) { }, "json");
            SetListItemColors();
        }
    });
    $("#sortableListsuggestions").disableSelection();

    // search function in search text box
    $('input#inline-search').search('#sortableList > li.listItem');
    $('input#inline-search').search('#List > li.listItem');
    $('input#inline-search-2').search('#sortableListProducts > li.listItem');

    // color the selected menu item from the right menu
    if (typeof (model) !== 'undefined') {
        $('li#' + model).addClass('selectedLeftMenu');
        $('li#' + model + ' a').css("color", "#fff");
    }

    // dialog box for deleting
    $('#dialog').dialog({
        autoOpen: false,
        resizable: false,
        buttons: {
            "Nee, niet verwijderen": function() {
                $(this).dialog('close');
            },
            "Ja": function() {
                $(this).dialog('close');

                var url = "/" + model + "/Delete";
                var data = "id=" + deleteId;

                $.ajax({
                    type: "POST",
                    url: url,
                    data: data,
                    dataType: "html",
                    success: function(result) {
                        itemToDelete.fadeOut(750, function() {
                            itemToDelete.remove();
                            SetListItemColors();
                        });
                        $.updateBasket();
                    }
                    //,
                    //error: function(xhr, status, error) {
                    //}
                });
                return false;
            }
        }
    });

    // remove an item from a list in the back-end with effect
    $('.removeItem').click(function(e) {
        if (subModel != "")
            model = subModel;

        itemToDelete = $(this).parents('.listItem');
        deleteId = itemToDelete.attr('id');

        $('#dialog').dialog('open');
    });

    // remove an item from a list in the website without confirmation and with effect
    $('.deleteItem').click(function(e) {
        itemToDelete = $(this).parents('.listItem');
        deleteId = itemToDelete.attr('id');

        $.ajax({
            type: "POST",
            url: "/order/DeleteLine",
            data: "id=" + deleteId,
            dataType: "html",
            success: function(result) {
                itemToDelete.fadeOut(750, function() {
                    itemToDelete.remove();
                    SetListItemColors();
                });
                $.updateSummary();
                $.updateBasket();
            }
            //,
            //error: function(xhr, status, error) {
            //}
        });
        return false;
    });

    // color the line of a selected item in a list
    //    $('.listItem').click(function() {
    //        SetListItemColors();
    //        $(this).addClass('listSelectedItem');
    //    });

    // select the first item in a list
    //    $('.listItem:first').addClass('listSelectedItem');

    // show darker image on hover over the delete icon in a list
    $('.deleteIcon').hover(function() {
        $(this).attr('src', '../../Content/Images/delete-dgray.png');
    }, function() {
        $(this).attr('src', '../../Content/Images/delete-lgray.png');
    });

    // show a darker image on hover over the edit icon in a list
    $('.editIcon').hover(function() {
        $(this).attr('src', '../../Content/Images/detail-dgray.png');
    }, function() {
        $(this).attr('src', '../../Content/Images/detail-lgray.png');
    });

    // check an order line
    $(".checkIcon").click(function(e) {
        itemToCheck = $(this).parents('.listItem');
        checkId = itemToCheck.attr('id');

        var data = "id=" + checkId;

        $.ajax({
            type: "POST",
            url: "/Order/CheckOrder",
            data: data,
            dataType: "html",
            success: function(result) {
                getCheckedOrders();
                $.updateBasket();
            }
            //,
            //error: function(xhr, status, error) {
            //}
        });
        return false;
    });

    getCheckedOrders();

    function getCheckedOrders() {
        $.get("/Order/GetCheckedOrders", function(result) { showCheckedOrders(eval(result)); }, "json");
    }

    function showCheckedOrders(orders) {
        $(".checkIcon").attr("src", "../../Content/Images/check-lgray.png");
        for (var i in orders) {
            $("#item_" + orders[i].Id).children(".listItemIconsLeft").children(".checkIcon").attr("src", "../../Content/Images/check-green.png");
        }
    }

    // send an order to Pain Deco

    //    $("form#sendOrder").submit(function() {
    //        hijack(this, orderSubmitted, "html");
    //        return false;
    //    });

    function orderSubmitted(result) {
        // after submit order to Pain-Deco
    };

    $("#submitOrder").click(function(e) {
        $.ajax({
            type: "POST",
            url: "/Order/SendOrder",
            data: "deliveryDate=" + $("input#deliveryDate").val() + "&deliveryHour=" + $("input#deliveryHour").val(),
            dataType: "html",
            success: function(result) {
                $("#step3part").fadeOut("slow", function() { $("#step4part").fadeIn("fast"); });
                $.updateBasket();
            }
            //,
            //error: function(xhr, status, error) {
            //}
        });
        return false;
    });



    // navigate by keyboard trough the items in a list
    $().keydown(function(e) {
        if ($('.listSelectedItem').length > 0) {
            var divs = $(".listItem:visible");
            var newSelectedItem = -1;

            switch (e.which) {
                case 38: // up
                    divs.each(function(i) {
                        if (i > 0) {
                            if ($(divs.get(i)).hasClass("listSelectedItem")) {
                                newSelectedItem = i - 1;
                            }
                        }
                    });
                    break;
                case 40: // down
                    divs.each(function(i) {
                        if (i < divs.size() - 1) {
                            if ($(divs.get(i)).hasClass("listSelectedItem")) {
                                newSelectedItem = i + 1;
                            }
                        }
                    });
                    break;
                case 13: // enter
                    var itemPosition = -1;
                    divs.each(function(i) {
                        if (i < divs.size()) {
                            if ($(divs.get(i)).hasClass("listSelectedItem")) {
                                itemPosition = i;
                            }
                        }
                    });

                    var id = $(divs.get(itemPosition)).attr('id');

                    if (subModel != "")
                        model = subModel;

                    window.location = "/" + model + "/Edit/" + id;

                    //$.getJSON("/" + model + "/Edit/" + id);

                    break;
                //default:                                                                                                                                                                                                                           
                //    alert(e.which);                                                                                                                                                                                                                           
            }

            if (newSelectedItem != -1) {
                SetListItemColors();
                $(divs.get(newSelectedItem)).addClass('listSelectedItem');
            }
        }
    });

    $(".toStep1").click(function(e) {
        $.toStep1();
    });

    $(".toStep2").click(function(e) {
        $.toStep2();
    });

    $(".toStep3").click(function(e) {
        if (checkStep2() == true) {
            $.toStep3();
        }
    });

    //    // order step 1
    //    $("#step1").click(function(e) {
    //        $.toStep1();
    //    });

    //    // order step 2
    //    $("#step2").click(function(e) {
    //        $.toStep2();
    //    });

    //    // order step 3
    //    $("#step3").click(function(e) {
    //        $.toStep3();
    //    });

    // begin change deliveryType

    $("#deliveryType1").click(function(e) {
        $.ajax({
            type: "POST",
            url: "/Order/ChangeDeliveryType",
            data: "id=1",
            dataType: "html",
            success: function(result) {
                $("#deliveryType1").addClass('selectedOrderStep');
                $("#deliveryType2").removeClass('selectedOrderStep');
                $("#deliveryType3").removeClass('selectedOrderStep');

                $("#deliveryComment").html("Afhalen omstreeks");
            }
        });
    });

    $("#deliveryType2").click(function(e) {
        $.ajax({
            type: "POST",
            url: "/Order/ChangeDeliveryType",
            data: "id=2",
            dataType: "html",
            success: function(result) {
                $("#deliveryType1").removeClass('selectedOrderStep');
                $("#deliveryType2").addClass('selectedOrderStep');
                $("#deliveryType3").removeClass('selectedOrderStep');

                $("#deliveryComment").html("Thuisleveren omstreeks");
            }
        });
    });

    $("#deliveryType3").click(function(e) {
        $.ajax({
            type: "POST",
            url: "/Order/ChangeDeliveryType",
            data: "id=3",
            dataType: "html",
            success: function(result) {
                $("#deliveryType1").removeClass('selectedOrderStep');
                $("#deliveryType2").removeClass('selectedOrderStep');
                $("#deliveryType3").addClass('selectedOrderStep');

                $("#deliveryComment").html("Reserveren omstreeks");
            }
        });
    });

    $.toStep1 = function() {
        if (orderStep != 1) {
            $("#step2part").hide();
            $("#step3part").hide();


            orderStep = 1;

            $("#step1").addClass('selectedOrderStep');
            $("#step2").removeClass('selectedOrderStep');
            $("#step3").removeClass('selectedOrderStep');

            $("#step1part").show();
        }
    }

    $.toStep2 = function() {
        if (orderStep != 2) {
            $("#step1part").hide();
            $("#step3part").hide();

            orderStep = 2;

            $("#step1").removeClass('selectedOrderStep');
            $("#step2").addClass('selectedOrderStep');
            $("#step3").removeClass('selectedOrderStep');

            $("#step2part").show();
        }
    }

    $.toStep3 = function() {
        if (orderStep != 3) {
            $("#step1part").hide();
            $("#step2part").hide();

            orderStep = 3;

            $("#step1").removeClass('selectedOrderStep');
            $("#step2").removeClass('selectedOrderStep');
            $("#step3").addClass('selectedOrderStep');

            $("#step3part").show();
        }
    }

    // register new contact
    //    $("form#registerContact").submit(function() {
    //        hijack(this, contactRegistered, "html");
    //        return false;
    //    });

    function hijack(form, callback, format) {
        $("#indicator").show();
        $.ajax({
            url: form.action,
            type: form.method,
            dataType: format,
            data: $(form).serialize(),
            completed: $("#indicator").hide(),
            success: callback
        });
    }

    function contactRegistered(result) {
        $("#registerContactPart").html(result);
    }

    // check date and hour in order flow
    $("input#deliveryDate").checkDate();
    $("input#deliveryHour").checkHour();
});

function checkStep2() {
    if (CheckDate($("input#deliveryDate")) == false || CheckHour($("input#deliveryHour")) == false) {
        return false;
    }
    else {
        return true;
    }
}

// check date
$.fn.checkDate = function() {
    $(this).keyup(function() {
        CheckDate(this);
    });
};

$.fn.checkHour = function() {
    $(this).keyup(function() {
        CheckHour(this);
    });
};

function CheckDate(dateField) {
    $("#noValidDate").hide();
    if (!isDate($(dateField).val())) {
        $("#noValidDate").show();
        $(dateField).css("background-color", "#ffebe8");
        return false;
    }
    else {
        $(dateField).css("background-color", "White");
        return true;
    }
}

function CheckHour(hourField) {
    $("#noValidHour").hide();
    if (!isHour($(hourField).val())) {
        $("#noValidHour").show();
        $(hourField).css("background-color", "#ffebe8");
        return false;
    }
    else {
        $(hourField).css("background-color", "White");
        return true;
    }
}

// Search function in search text box
$.fn.search = function(searchElements) {
    $(this).keyup(function() {
        var searchString = $(this).val().toLowerCase();

        if (searchString.length > 0) {
            $(searchElements).hide();
            $(searchElements + ':Contains(' + searchString + ')').show();
        }
        else {
            $(searchElements).show();
        }

        SetListItemColors();
    });
};

// begin first block

// create a preload function for images
$.preloadImages = function() {
    for (var i = 0; i < arguments.length; i++) {
        $("<img>").attr("src", arguments[i]);
    }
}

$.updateBasket = function() {
    //$('#BasketItems').fadeOut("fast");
    $('#BasketItems').load("../../Order/GetBasket", function() {  });
}

$.updateSummary = function() {
    $('#Summary').load("../../Order/GetSummary");
}

// style all items in a list
function SetListItemColors() {
    $('#sortableList > .listItem').removeClass('listFirstItem');
    $('#sortableList > .listItem').removeClass('listLastItem');
    $('#sortableList > .listItem:visible:first').addClass('listFirstItem');
    $('#sortableList > .listItem:visible:last').addClass('listLastItem');

    $('#sortableListProducts > .listItem').removeClass('listFirstItem');
    $('#sortableListProducts > .listItem').removeClass('listLastItem');
    $('#sortableListProducts > .listItem:visible:first').addClass('listFirstItem');
    $('#sortableListProducts > .listItem:visible:last').addClass('listLastItem');

    $('#sortableListSuggestions > .listItem').removeClass('listFirstItem');
    $('#sortableListSuggestions > .listItem').removeClass('listLastItem');
    $('#sortableListSuggestions > .listItem:visible:first').addClass('listFirstItem');
    $('#sortableListSuggestions > .listItem:visible:last').addClass('listLastItem');

    $('#List > .listItem:visible:first').addClass('listFirstItem');

    //$('.deleteIcon').attr('src', '../../Content/Images/delete-lgray.png');
}

// begin popup window

// 0 means disabled; 1 means enabled;
var popupStatus = 0;

function loadPopup(itemId) {
    // loads popup only if it is disabled  
    if (popupStatus == 0) {
        $("#backgroundPopup").css({
            "opacity": "0.5"
        });
        $("#backgroundPopup").show(); // .fadeIn("fast");
        $("#popupContact").show(); // .fadeIn("fast");

        popupStatus = 1;
    }

    $("#ItemTitle").html(itemId);

    $('#IngredientList').load("../../Order/GetIngredientList/" + itemId);
}

function disablePopup() {
    // disables popup only if it is enabled  
    if (popupStatus == 1) {
        $("#backgroundPopup").hide(); // .fadeOut("fast");
        $("#popupContact").hide(); // .fadeOut("fast");
        popupStatus = 0;
        window.location = "../Order/FullBasket";
    }
}

function centerPopup() {
    // request data for centering  
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = $("#popupContact").height();
    var popupWidth = $("#popupContact").width();

    // centering  
    $("#popupContact").css({
        "position": "absolute",
        "top": windowHeight / 2 - popupHeight / 2,
        "left": windowWidth / 2 - popupWidth / 2
    });
    
    //only need force for IE6  
    $("#backgroundPopup").css({
        "height": windowHeight
    });
}

// end first block

// uncasesensitive selector (capital C!)
$.extend($.expr[":"], {
    "Contains": function(elem, i, match, array) {
        return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
    }
});

function gup(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}
