﻿$(document).ready(function () {

    // Autohide message
    setTimeout(function () { $(".hideme").fadeOut('slow', function () { $(this).remove(); }); }, 5000);
    /*
    * Productlist stuff ----------------------------------------------------------------------------------------------------------
    */

    /* Products: OnDemand product list
    * loadOnDemandProducts() is run on document.ready. Fetches 20 products based on preselected sorting and filters
    * loadOnDemandProductSearch() is run on document.ready is list is found
    * $(".filter").change() when sorting or filter radio buttons are clicked
    * $(".onDemandAppend").click() when append button is click. Buttons is by default hidden. Shown if added items is >= 20 (standard take)
    */
    $(".noProductHits").hide();
    loadOnDemandProducts();
    //loadOnDemandProductSearch();

    function loadOnDemandProducts() {
        if ($("#onDemandProducts").length == 0) {
            //console.log("# loadOnDemandProducts(): No list found ...");
            return;
        }

        var list = $("#onDemandProducts");
        var appendButton = $(".onDemandAppend").hide();
        var split = list.attr("data-id").split('#');
        var websiteID = split[0];
        var categoryID = split[1];
        var first = false;

        var s; // Sort by
        var b; // Brand ID filter
        var p; // Price type filter
        var c; // Category filter

        killLoaders();
        $(".productSort").append("<span class='loading'> Laster ...</span>");
        $(".bigloader").append("<span class='loading ui-state-highlight ui-corner-all autohide' style='padding: 3px 3px 3px 21px;'> Vennligst vent. Produkter hentes inn...</span>");

        if (window.location.hash == "") {
            //console.log("# No hash in URL. Looking for hiddenSessionHash...");
            //console.log("# Hidden session hash: " + $("#hiddenSessionHash").val());

            if ($("#hiddenSessionHash").val() != null) {
                window.location.hash = $("#hiddenSessionHash").val();
            }
        }

        var split = window.location.hash.replace('#', '').split('/');
        if (split.length == 4) {
            s = parseInt(split[0]);
            b = parseInt(split[1]);
            p = parseInt(split[2]);
            c = parseInt(split[3]);
        }

        if (isFinite(s) && isFinite(b) && isFinite(p) && isFinite(c)) {
            //console.log("Hash er satt og alle verdier er gyldige");
            $(($(".sortingFilter option[value='" + s + "']").length > 0 ? ".sortingFilter option[value='" + s + "']" : ".sortingFilter option:first")).attr("selected", true);
            $(($(".brandFilter input[value='" + b + "']").length > 0 ? ".brandFilter input[value='" + b + "']" : ".brandFilter input:first")).attr("checked", true);
            $(($(".priceFilter input[value='" + p + "']").length > 0 ? ".priceFilter input[value='" + p + "']" : ".priceFilter input:first")).attr("checked", true);
            $(($(".categoryFilter input[value='" + c + "']").length > 0 ? ".categoryFilter input[value='" + c + "']" : ".categoryFilter input:first")).attr("checked", true);

        } else {
            //console.log("# Hash not set. Using defaults...");
            $(".sortingFilter option:first").attr("selected", true);
            $(".brandFilter input:first").attr("checked", true);
            $(".priceFilter input:first").attr("checked", true);
            $(".categoryFilter input:first").attr("checked", true); //[value='" + categoryID + "']

            s = parseInt($(".sortingFilter option:first").val());
            b = parseInt($(".brandFilter input:checked").val());
            p = parseInt($(".priceFilter input:checked").val());
            c = parseInt($(".categoryFilter input:checked").val());
        }



        //get brands on given category
        //if (first) 
        loadOnDemandProductBrand(c, b);

        if (!isNaN(categoryID) && !isNaN(s) && !isNaN(b) && !isNaN(p) && !isNaN(c)) window.location.hash = s + "/" + b + "/" + p + "/" + c;

        if (isNaN(categoryID) || isNaN(s) || isNaN(b) | isNaN(p) || isNaN(c)) {
            //console.log("# loadOnDemandProducts(): No filters found, category has no products. Cancelling request...");
            return;
        }

        //console.log("# loadOnDemandProducts() running for category " + categoryID + " with filters " + window.location.hash + "...");

        $.ajax({
            type: "POST",
            url: "/modules/ecommerce35/ECommerceAjaxWebService.asmx/GetProducts",
            data: "{'categoryID':" + categoryID + ",'s':" + s + ",'b':" + b + ",'p':" + p + ",'c':" + c + ",'skip':0}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                killLoaders();
                var hits = parseInt($(r.d).size());
                if (hits > 0) {
                    $(".noProductHits").hide();
                } else {
                    $(".noProductHits").show()
                }
                if (r.d != "") {
                    list.after("<ul id='tmpProducts' class='products' style='display: none'>" + r.d + "</ul>");
                    list.quicksand($("#tmpProducts li"), {}, function () {
                        $("#tmpProducts").remove();

                        var addedItems = parseInt(list.find("li").size());
                        if (addedItems >= 25) appendButton.slideDown();
                        //console.log("# loadOnDemandProducts() done! " + addedItems + " items added...");
                    });
                } else {
                    list.html("");
                }
            }
        });
    }

    function loadOnDemandProductBrand(categoryID, b) {
        if (isNaN(categoryID) || isNaN(b)) {
            return;
        }

        $.ajax({
            type: "POST",
            url: "/modules/ecommerce35/ECommerceAjaxWebService.asmx/GetBrands",
            data: "{'categoryID':" + categoryID + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {

                if (r.d != "") {
                    //alert('foo');
                    $("#productBrands").html("<li><input id='brands0' type='radio' name='brands' value='0' /><label for='brands0'>Alle</label></li>" + r.d);
                } else {
                    //list.html("<li><input id='brands0' type='radio' name='brands' value='0' /><label for='brands0'>Alle</label></li>");
                    $("#productBrands").html("<li><input id='brands0' type='radio' name='brands' value='0' /><label for='brands0'>Alle</label></li>");
                }

                $(($(".brandFilter input[value='" + b + "']").length > 0 ? ".brandFilter input[value='" + b + "']" : ".brandFilter input:first")).attr("checked", true);
            }
        });
    }

    // Radiobuttons for sorting and filters
    $(".filter").change(function () {
        var oldC;
        var split = window.location.hash.replace('#', '').split('/');
        if (split.length == 4) {
            oldC = parseInt(split[3]);
        }
        //hide no hits
        $(".noProductHits").hide();

        var s = parseInt($(".sortingFilter option:selected").val());
        var b = parseInt($(".brandFilter input:checked").val());
        var p = parseInt($(".priceFilter input:checked").val());
        var c = parseInt($(".categoryFilter input:checked").val());

        loadOnDemandProductBrand(c, b);

        if (oldC != c) {
            b = 0;
        }

        window.location.hash = s + "/" + b + "/" + p + "/" + c;
        //console.log("# Filters changed. Running loadOnDemandProducts() and loadOnDemandProductSearch() with hash " + window.location.hash + "...");
        loadOnDemandProducts();
        //loadOnDemandProductSearch();
    });

    function loadOnDemandProductSearch() {
        if ($("#onDemandProductSearch").length == 0) {
            //console.log("# loadOnDemandProductSearch(): No list found ...");
            return;
        }

        var list = $("#onDemandProductSearch");
        var appendButton = $(".onDemandAppend").hide();

        var split = list.attr("data-id").split('#');
        var w = split[0];
        var q = split[1];

        var s; // Sort by
        var b; // Brand ID filter
        var p; // Price type filter
        var c; // Category filter

        killLoaders();
        $("#noresults").remove();
        $(".productSort").append("<span class='loading'>Laster ...</span>");

        if (window.location.hash == "") {
            //console.log("# No hash in URL. Looking for hiddenSessionHash...");
            //console.log("# Hidden session hash: " + $("#hiddenSessionHash").val());
            if ($("#hiddenSessionHash").val() != null) window.location.hash = $("#hiddenSessionHash").val();
        }

        var split = window.location.hash.replace('#', '').split('/');
        if (split.length == 4) {
            s = parseInt(split[0]);
            b = parseInt(split[1]);
            p = parseInt(split[2]);
            c = parseInt(split[3]);
        }

        //console.log(s);
        //console.log(b);
        //console.log(p);
        //console.log(c);

        if (isFinite(s) && isFinite(b) && isFinite(p) && isFinite(c)) {
            $(($(".sortingFilter option[value='" + s + "']").length > 0 ? ".sortingFilter option[value='" + s + "']" : ".sortingFilter option:first")).attr("selected", true);
            $(($(".brandFilter input[value='" + b + "']").length > 0 ? ".brandFilter input[value='" + b + "']" : ".brandFilter input:first")).attr("checked", true);
            $(($(".priceFilter input[value='" + p + "']").length > 0 ? ".priceFilter input[value='" + p + "']" : ".priceFilter input:first")).attr("checked", true);
            $(($(".categoryFilter input[value='" + c + "']").length > 0 ? ".categoryFilter input[value='" + c + "']" : ".categoryFilter input:first")).attr("checked", true);
        } else {
            //console.log("# Hash not set. Using defaults...");
            $(".sortingFilter option:first").attr("selected", true);
            $(".brandFilter input:first").attr("checked", true);
            $(".priceFilter input:first").attr("checked", true);
            $(".categoryFilter input:first").attr("checked", true);
        }

        s = parseInt($(".sortingFilter option:selected").val());
        b = parseInt($(".brandFilter input:checked").val());
        p = parseInt($(".priceFilter input:checked").val());
        c = parseInt($(".categoryFilter input:checked").val());

        if (!isNaN(s) && !isNaN(b) && !isNaN(p) && !isNaN(c)) window.location.hash = s + "/" + b + "/" + p + "/" + c;

        //console.log("# loadOnDemandProductSearch() running for query '" + q + "' on websiteID " + w + " with filters " + window.location.hash + "...");

        $.ajax({
            type: "POST",
            url: "/modules/ecommerce35/ECommerceAjaxWebService.asmx/GetProductsBySearch",
            data: "{'q':'" + q + "','s':" + s + ",'b':" + b + ",'p':" + p + ",'c':" + c + ",'skip':0,'take':25,'w':" + w + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                killLoaders();

                list.after("<ul id='tmpProducts' class='products' style='display: none'>" + r.d + "</ul>");
                list.quicksand($("#tmpProducts li"), {}, function () {
                    $("#tmpProducts").remove();
                    var addedItems = parseInt(list.find("li").size());
                    if (addedItems >= 25) appendButton.slideDown();

                    //console.log("# loadOnDemandProductSearch() done! " + addedItems + " items added...");

                    if (addedItems == 0) list.after("<p id=\"noresults\" class=\"ui-state-highlight ui-corner-all\">Ingen produkter funnet ...</p>");

                    //list.find("li").size() > 0 ? list.height(273 * Math.round((list.find("li").size() / 5) + 0.4)) : list.height(0); // Setter høyde på listen fordi LIer floater.
                });
            }
        });
    }

    // Vis mer-knappen trykt. Finn sortering og filter samt antall produkter i nåværende liste (for å sette SKIP), append produkter...
    $(".onDemandAppend").click(function () {
        var button = $(this); // Append button
        var list = button.hasClass("onDemandSearchAppend") ? $("#onDemandProductSearch") : $("#onDemandProducts"); // List
        var skip = parseInt(list.find("li").size()); // Skip

        var s = parseInt($(".sortingFilter option:selected").val());
        var b = parseInt($(".brandFilter input:checked").val());
        var p = parseInt($(".priceFilter input:checked").val());
        var c = parseInt($(".categoryFilter input:checked").val());

        if (button.hasClass("onDemandSearchAppend")) {
            var split = list.attr("data-id").split('#');
            var w = parseInt(split[0]);
            var q = split[1];
            //console.log("# Appending products for search query '" + q + "'...");
            button.addClass("onDemandAppendLoader");

            $.ajax({
                type: "POST",
                url: "/modules/ecommerce35/ECommerceAjaxWebService.asmx/GetProductsBySearch",
                data: "{'q':'" + q + "','s':" + s + ",'b':" + b + ",'p':" + p + ",'c':" + c + ",'skip':" + skip + ",'take': 25,'w':" + w + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    list.append(r.d);

                    var addedItems = parseInt(list.find("li").size()) - skip;
                    //console.log("# loadOnDemandProductSearch() success! " + addedItems + " items added...");

                    button.removeClass("onDemandAppendLoader");
                    if (addedItems < 25) button.fadeOut(); // No more items. Hiding append button.

                    list.find("li").size() > 0 ? list.height(273 * Math.round((list.find("li").size() / 5) + 0.4)) : list.height(0); // Setter høyde på listen fordi LIer floater.
                }
            });

        } else {
            var split = list.attr("data-id").split('#');
            var websiteID = parseInt(split[0]);
            var categoryID = parseInt(split[1]);
            //console.log("# Appending products for category " + categoryID + "...");
            button.addClass("onDemandAppendLoader");

            $.ajax({
                type: "POST",
                url: "/modules/ecommerce35/ECommerceAjaxWebService.asmx/GetProducts",
                //data: "{'c':" + categoryID + ",'s':" + s + ",'b':" + b + ",'p':" + p + ",'skip':" + skip + "}",
                data: "{'categoryID':" + categoryID + ",'s':" + s + ",'b':" + b + ",'p':" + p + ",'c':" + c + ",'skip':" + skip + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    list.append(r.d);

                    var addedItems = parseInt(list.find("li").size()) - skip;
                    //console.log("# loadOnDemandProducts() success! " + addedItems + " items added...");

                    button.removeClass("onDemandAppendLoader");
                    if (addedItems < 25) button.fadeOut(); // No more items. Hiding append button.
                }
            });
        }

        return false;
    });

    /*
    * Product stuff ----------------------------------------------------------------------------------------------------------
    */

    // Product: Add to Cart function
    $(".add2cart").click(function () {
        var timeout;
        clearTimeout(timeout);

        killLoaders();
        $(".autohide").remove();

        var q = parseInt($(".quantity :selected").val()); // Selected quantity
        var qText = $(".quantity :selected").text(); // Quantity text (i.e. 1 stk)
        var vID = parseInt($(".variations :selected").val()); // Variation ID
        var vText = $(".variations :selected").text(); // Variation title

        var button = $(this).fadeTo("fast", 0.5).attr("disabled", true);
        //button.parent().after("<span class='blueloader loading'>Laster...</span>"); // Append loader
        $(".quantity").after("<div style='float: left; margin: 6px;' class='blueloader loading'>Laster...</div>"); // Append loader

        if (isNaN(q) || q <= 0 || isNaN(vID) || vID <= 0) {
            //console.log("# add2cart: Invalid quantity or variationID (q: " + q + ", vID: " + vID + "). Cancelling...");
            $(".ui-state-error").remove();
            button.fadeTo("fast", 1).attr("disabled", false).parent().after("<span class='ui-state-error ui-corner-all'>Ugyldig størrelse eller variasjon...</span>");

            var msg = button.parent().parent().find(".ui-state-error");
            if (msg != null) msg.effect("pulsate");
            killLoaders();
            return false;
        }

        $.ajax({
            type: "POST",
            url: "/modules/ecommerce35/ECommerceAjaxWebService.asmx/Add2Cart",
            data: "{'quantity':" + q + ",'variationID':" + vID + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                //console.log(r);
                if (r.d != "ERR") {
                    killLoaders();
                    var confirmText = qText + " " + $(".productTitle").text() + " lagt til din <a href='" + $(".fwCart").attr("href") + "' class=\"focusMe\">handlekurv</a>.";
                    button.fadeTo("fast", 1).attr("disabled", false); //.parent().before("<span style='padding: 3px;' class='ui-state-highlight ui-corner-all autohide'>" + confirmText + "</span>");
                    $(".quantity").after("<div style='padding: 3px; float: left; margin-top: 2px; margin-left: 10px;' class='ui-state-highlight ui-corner-all autohide'>" + confirmText + "</div>");
                    $("#cartQ").html(parseInt($("#cartQ:first").text()) + q); // Update cart quantity
                    //$("#cartS").html(r.d);
                    timeout = setTimeout(function () { $(".autohide").fadeOut("slow", function () { $(this).remove(); }); }, 10000);

                    if ($(".focusMe").length > 0) $(".focusMe").focus();
                }
            }
        });

        return false;
    });

    /*
    * Review stuff -----------------------------------------------------------------------------------------------------------
    */

    //    // Show review form
    //    $(".showReviewForm").click(function () { // Knapp for å vise review-skjemaet på produkt
    //        $(".showReviewForm").hide();
    //        $("#reviewForm").slideDown();
    //        $("#txtReviewTitle").focus();
    //        return false;
    //    });

    //    // Hide review form
    //    $(".hideReviewForm").click(function () {
    //        $("#reviewForm").slideUp(function () { $(".showReviewForm").show(); });
    //        return false;
    //    });

    //    function refreshReviews(scrollToReviewID) {
    //        var list = $("#onDemandReviews");
    //        var pID = parseInt(list.attr("data-id"));

    //        killLoaders();
    //        list.after("<span class='loading greenloader'>Laster...</span>");

    //        //console.log("# refreshReviews() runnning for product " + pID + "...");

    //        $.ajax({
    //            type: "POST",
    //            url: "/modules/ecommerce35/ECommerceAjaxWebService.asmx/GetReviews",
    //            data: "{'productID':" + pID + "}",
    //            contentType: "application/json; charset=utf-8",
    //            dataType: "json",
    //            success: function (r) {
    //                killLoaders();
    //                //console.log("# Reviews fetched. Quicksanding...");

    //                list.after("<ul id=\"appendList\" class='reviews cleanedlist ui-helper-clearfix' style='display: none'>" + r.d + "</ul>");
    //                list.quicksand($(".reviews:last li"), {}, function () {
    //                    // Quicksand finished. Clean up and scroll
    //                    $("#appendList").remove();

    //                    if (scrollToReviewID > 0) { // Scroll to this list item if set
    //                        var review = list.find("li[data-id='review" + scrollToReviewID + "']");
    //                        var prev = review.prev();
    //                        //console.log("# Animating scroll to " + review.offset().top + "...");
    //                        review.effect("highlight", {}, 3000);

    //                        if (prev != null && prev.offset() != null) { // Scroll til saken før hvis den finnes
    //                            $('html, body').animate({ scrollTop: prev.offset().top }, 800);
    //                        } else {
    //                            $('html, body').animate({ scrollTop: review.offset().top }, 800);
    //                        }
    //                    }
    //                });
    //            }
    //        });
    //    }

    //    $(".changevote").live('click', function () {
    //        var button = $(this);
    //        var reviewID = button.attr("data-id");
    //        var direction = button.hasClass("icon_thumbsup") ? "1" : "0";
    //        //console.log("# Changing vote for review " + reviewID + " direction " + direction);

    //        if (isNaN(reviewID)) {
    //            //console.log("# Unknown review ID. Cancelling...");
    //            return;
    //        }

    //        $.ajax({
    //            type: "POST",
    //            url: "/modules/ecommerce35/ECommerceAjaxWebService.asmx/ChangeReviewRating",
    //            data: "{'reviewID':" + reviewID + ",'direction':" + direction + "}",
    //            contentType: "application/json; charset=utf-8",
    //            dataType: "json",
    //            success: function (r) {
    //                if (r.d == "OK") refreshReviews(reviewID);
    //            }
    //        });
    //        return false;
    //    });

    //    $("#btnPostReview").click(function () {
    //        if (!Page_IsValid) return;
    //        var button = $(this);

    //        var productID = parseInt(button.attr("data-id"));
    //        var title = $("#txtReviewTitle").val();
    //        var score = parseInt($("#reviewRating input:checked").val());
    //        var review = $("#txtReview").val();

    //        //console.log("# Posting review for product " + productID + ", title:" + title + ", score:" + score + ", review:" + review);

    //        killLoaders();
    //        button.next().after("<span class='postReviewLoader smallblueloader right'></span>");

    //        $.ajax({
    //            type: "POST",
    //            url: "/modules/ecommerce35/ECommerceAjaxWebService.asmx/PostReview",
    //            data: "{'productID':" + productID + ",'title':'" + title + "','score':" + score + ",'review':'" + review + "'}",
    //            contentType: "application/json; charset=utf-8",
    //            dataType: "json",
    //            success: function (r) {
    //                $(".postReviewLoader").remove();
    //                $("#txtReviewTitle").val("");
    //                $("#txtReview").val("");
    //                $("#reviewForm").slideUp(function () {
    //                    $(".showReviewForm").show();
    //                    $("#reviewForm").after("<span class='ui-state-highlight ui-corner-all postReviewConfirmation'>" + r.d + "</span>");
    //                });

    //                setTimeout(function () {
    //                    $(".postReviewConfirmation").slideUp(function () {
    //                        $(this).remove();
    //                    });
    //                }, 5000);
    //            }
    //        });
    //        return false;
    //    });

    //    // Last reviews hvis standard tab er 4
    //    if ($(".ui-tabs").tabs('option', 'selected') == 4) refreshReviews(0);

    //    // Laster reviews hvis selected tab er #omtaler
    //    $(".ui-tabs").bind("tabsshow", function (event, ui) {
    //        if (ui.tab.hash == "#omtaler" && $(".reviews li").size() == 0) refreshReviews(0);
    //        return false;
    //    });

});
