﻿
var basketOrderArray = [];

$(function () {

    // Check cookies on shopping-cart items
    var cookie = $.cookie('Geodatabank_shoppingcart');
    if (cookie) { LoadCookie(cookie); }

    MakeDraggable();
    MakeDroppable();


    // Add a delete click function, to remove it from the shoppingcart again
    $(".delete-product").live('click', function () {
        var productid = $(this).parent().find("input#hidden-product-id").val();
        RemoveProduct(productid);
        RemoveShoppingCartItem(productid);
    });
    // Add an add click function, to add a single product to the shoppingcart
    $(".add-product").live('click', function () {
        var productid = $(this).parent().find("input#hidden-product-id").val();
        basketHint(false);
        AddProduct(productid);
        AddShoppingCartItem(productid);
    });

    // Clicking on an image with the CssClass 'add-all-products' this function will be triggered
    $(".add-all-products").click(function () {
        var itemcount = 0;
        $("#product-items ul li").each(function () { itemcount++ });
        if (confirm_move(itemcount, 50)) {
            basketHint(false);
            OrderAllProducts();
        }
    });
    // Clicking on an image with the CssClass 'remove-all-products' this function will be triggered
    $(".remove-all-products").click(function () {
        OrderNoProducts();
    });
});

// Make Products draggable
function MakeDraggable() {
    $("#product-items li").draggable({
        revert: "invalid",
        appendTo: "body",
        helper: "clone"
    });


}

function MakeDroppable() {
    $("#basket").droppable(
        {
            activeClass: "ui-state-default",
            hoverClass: "ui-state-hover",
            accept: ":not(.ui-sortable-helper)",
            drop: function (event, ui) {
                var pid = ui.draggable.find("input#hidden-product-id").val()
                if (pid) {
                    basketHint(false);
                    AddShoppingCartItem(pid);   // Add to shoppingcart - visually
                    AddProduct(pid);  // Add to cookie
                }
            }
        }).sortable({
            items: "li:not(.placeholder)",
            sort: function () {
                // Gets added unintentionally by droppable interacting with sortable
                // using connectWithSortable fixes this, but doesn't allow you to customize active/hoverClass options
                $(this).removeClass("ui-state-default");
            }
        }
    );
}

function basketHint(show) {
    if (show) { $("#basket li.hint").show(); }
    else { $("#basket li.hint").hide(); }
}

// Load shoppingcart cookie
function LoadCookie(cookieVal) {
    //$.cookie('Geodatabank_shoppingcart', null); // First, remove cookie itself
    var cookie = cookieVal.split(',');
    if (cookie) {
        cookie = removeDuplicateArrayElements(cookie);
        $.cookie('Geodatabank_shoppingcart', null);
        $.each(cookie, function (key, val) {
            AddProduct(val);
        });
        $("[id$='_btnUpdateShoppingCart']").click();
//        $.each(cookie, function (key, val) {
//            AddShoppingCartItem(val);
//            AddProduct(val);
//        });
    }
}

// Move all available products to shoppingcart
function OrderAllProducts() {
    $("#product-items ul li").each(function () {
        var productid = $(this).find("#hidden-product-id").val();
        if (productid) {
            AddShoppingCartItem(productid);
            AddProduct(productid);
        }
    });
}
function OrderNoProducts() {
    $("#basket-items ul li").each(function () {
        var productid = $(this).find("#hidden-product-id").val();
        if (productid) {
            RemoveShoppingCartItem(productid);
            RemoveProduct(productid);
        }
    });
}

// Add a product to the shoppingcart array & hiddenfield & cookie
function AddProduct(productid) {
    basketOrderArray.push({ "ProductID": productid });
    var basketCookie = ArrayToString(basketOrderArray, 'ProductID', ',');
    $("#hiddenfieldwrapper").find(":hidden").val(basketCookie);
    $.cookie('Geodatabank_shoppingcart', basketCookie, { expires: 7 });
}

// Remove a product from the shoppingcart array & hiddenfield & cookie
function RemoveProduct(productid) {
    if (basketOrderArray) {
        basketOrderArray.remove("ProductID", productid);
    }
    $("#hiddenfieldwrapper").find(":hidden").val("");
    if (basketOrderArray.length >= 1) {
        var sCookie = ArrayToString(basketOrderArray, 'ProductID', ',')
        $("#hiddenfieldwrapper").find(":hidden").val(sCookie);
        $.cookie('Geodatabank_shoppingcart', sCookie, { expires: 7 });
    }
    else {
        //basket empty, so clean up cookie
        $.cookie('Geodatabank_shoppingcart', null);
        basketHint(true);
    }
}

// Visually add shoppingcart item
function AddShoppingCartItem(productid) {
    // Remove placeholder
    $("#basket-items ul").find(".placeholder").remove();

    // Move item from productlist to shoppingcart
    $("#product-items ul li").each(function () {
        var hv = $(this).find("#hidden-product-id");
        if (hv) {
            if (hv.val() == productid) {
                $(this).removeClass("ui-draggable");
                $(this).html($(this).html() + "<div class='delete-product' />");
                $(this).appendTo("#basket-items ul");
            }
        }
    });
    addCSSToCartItems();
}

// Visually move shoppingcart item back to productlist
function RemoveShoppingCartItem(productid) {
    $("#basket-items ul li").each(function () {
        var hv = $(this).find("#hidden-product-id");
        if (hv) {
            if (hv.val() == productid) {
                $(this).addClass("ui-draggable");
                $(this).find(".delete-product").remove();
                $(this).appendTo("#product-items ul");
            }
        }
    });
    
    // Products in shopping cart from cookie were not yet draggable
    MakeDraggable();
    addCSSToCartItems();
}

// Visually change color of items in the map
function addCSSToCartItems() {
    // First, clear all coloured markers (if a product is removed from list)
    $(".type-1").attr("src", "grfx/icons/marker_sondering_medium.png");
    $(".type-2").attr("src", "grfx/icons/marker_boring_medium.png");

    // Now, change all basket item img sources (if a product is added)
    $("#basket-items ul li").each(function () {
        var x = $(this).find("input#hidden-product-x").val();
        var y = $(this).find("input#hidden-product-y").val();
        var proefsoort = $(this).find("input#hidden-product-method").val();

        var $sonderingimage = $(".1-" + x + "-" + y).find("img");
        if ($sonderingimage.attr("src") == "grfx/icons/marker_sondering_medium.png" && proefsoort == "Sondering")
            $sonderingimage.attr("src", "grfx/icons/marker_sondering_medium_orange.png");

        var $boringimage = $(".2-" + x + "-" + y).find("img");
        if ($boringimage.attr("src") == "grfx/icons/marker_boring_medium.png" && proefsoort == "Boring")
            $boringimage.attr("src", "grfx/icons/marker_boring_medium_orange.png");
    });

    // Color the product details item
    $(".balloon-addItem").show();
    $(".balloon-removeItem").hide();
    $(".map-product-infowindow-productitem").each(function () {
        var $item = $(this).find(".balloon-addToShoppingCart a");
        var itemid = $item.attr("id");
        $("#basket-items ul li").each(function () {
            if ($item.hasClass($(this).find("#hidden-product-id").val())) {
                $("." + itemid).toggle();
                return false;
            }
        });
    });
}

// Prototyping to remove an item from an array
Array.prototype.remove = function (name, value) {
    var rest = $.grep(this, function (item) {
        return (item[name] != value); // <- You may or may not want strict equality
    });

    this.length = 0;
    this.push.apply(this, rest);
    return this; // <- This seems like a jQuery-ish thing to do but is optional
};

// Convert an jscript array to a string
function ArrayToString(sArray, key, separator) {
    if (!separator) separator = ',';
    var s = '';
    $.each(sArray, function (k, val) {
        if (k != 0) s += separator;
        s += val[key];
    });
    return s;
}

function removeDuplicateArrayElements(arrayName) {
    var newArray = new Array();
    label: for (var i = 0; i < arrayName.length; i++) {
        for (var j = 0; j < newArray.length; j++) {
            if (newArray[j] == arrayName[i])
                continue label;
        }
        newArray[newArray.length] = arrayName[i];
    }
    return newArray;
}
