/// <reference path="../../../Scripts/_references.js" />
/// <reference path="shop_helpers.js" />
/// <reference path="shop_basket.js" />
/// <reference path="shop_checkout.js" />

/// prointernet Grid Shop
/// Version: 2.0.8006.30174

function GridShop() {
    this.config = {
        offsetTop: 0,
        basketOpenTime: 4000,
        scrollToItem: true,
        dataUrl: "/shop/",
        dataType: "",
        masterSelector: "#master",
        detailPages: true,
        listCountBox: true,
        checkoutCountBox: true,
        autoCreateDetailButton: true,
        autoCreateListButton: false,
        autoLoadLessFile: true,
        showCheckoutAfterAdd: false,
        toggleAddToBasket: false,
        useBasketLayer: true,
        basketLayerTarget: "body"
    }

    this.culture = "ru-RU";
    this.list = $();

    this.initComplete = false;
    this.initFunctions = [];
    this.basketLayer = $("#basketLayer");

    this.basket = new GridShopBasket(this);
    this.checkout = new GridShopCheckout(this);

    this.lastState = "";
    this.state = "";

    this.master = function () {
        return $(this.config.masterSelector);
    }
}

var GridShopEvents = {
    addToBasket: "addToBasket"
}

GridShop.getCurrent = function () {
    /// <returns value='new GridShop()' ></returns>
    return document.shop;
}

GridShop.prototype.init = function () {
    var base = this;

    if (base.initComplete) {
        return;
    }

    $(document).ready(function () {

        if (base.config.autoLoadLessFile && $("link[href*='shop.less']").length == 0) {
            $("head").append('<link rel="stylesheet" href="/frontend/composite/grid/shop/styles/shop.less" type="text/css" media="all" />');
        }

        // Langswitcher static reload
        $("#langSwitcher a").addClass("static");

        // Nav
        AjaxNav.setClientParams("s");
        AjaxNav.onShopNavChange = function (e) {
            base.lastState = base.state;
            base.state = "";

            if (e && e.state && e.state.s) {
                // New State
                base.state = e.state.s;
            } else {
                base.state = AjaxNav.getState("s");
            }

            for (var pKey in base) {
                var pObj = base[pKey];
                if (pObj && pObj.stateChanged) {
                    pObj.stateChanged(base.state);
                }
            }

            base.stateChanged(base.state);

        }
        AjaxNav.bind("shopStateChange", "statechanged", AjaxNav.onShopNavChange);

        // DataLoad
        base.load(function () {
            AjaxNav.onShopNavChange();
        });

        $.each(base.initFunctions, function (eventIdx, event) {
            event();
        });

        base.initComplete = true;

    });

}
GridShop.prototype.initFunctions = [];

GridShop.prototype.stateChanged = function () {
    this.initList();
}

GridShop.prototype.load = function (callback) {
    var base = this;

    base.basket.load(function () {
        base.initList();
        base.basket.init();

        if (base.showCheckout) {
            base.checkout.show();
            base.showCheckout = false;
        }

        if (callback) {
            callback();
        }

    });
}

GridShop.prototype.initList = function () {
    this.createButtons();
}

GridShop.prototype.createButtons = function () {
    var base = this;
    var listState = this.getListState();
    var createButtons = false;


    // Button für Auflistung
    if (listState == "list" && base.config.autoCreateListButton) {
        createButtons = true;
    }

    // Button für Detailseite
    if (listState == "details" && base.config.autoCreateDetailButton) {
        createButtons = true;
    }

    // Basketbutton erstellen
    if (createButtons) {
        var items = base.list.find(".item");

        if (listState == "details") {
            items = base.list.find(".listDetails");
        }

        items.each(function () {
            var item = $(this);

            var btnAdd = item.find(".addtobasket");
            var inputCount = item.find("input.count");

            var itemControls = item.find("controls");
            if (itemControls.length == 0) {
                itemControls = $("<div class='controls'></div>").appendTo(item);
            }

            if (base.config.listCountBox && inputCount.length == 0) {
                inputCount = $("<input type='number' class='count' value='1' min='0' />");
                itemControls.append(inputCount);
            }

            if (btnAdd.length == 0) {
                btnAdd = $("<button class='btn addtobasket'><span>Inquiry</span></button>");
                itemControls.append(btnAdd);
            }

        });
    }

    // Basketbutton Events
    if (!base.onAddToBasketClick) {

        base.onAddToBasketClick = function () {

            var targetButton = $(this);
            var targetInput = targetButton.parent().find("input.count");


            var addCount = (targetInput.length > 0 ? targetInput.val() : 1);

            base.basket.add($(this).getDataId(), addCount, function () {

                if (base.config.showCheckoutAfterAdd) {
                    base.checkout.show();
                }

            });

            if (targetInput.length > 0) {
                targetInput.val(1);
            }

            return false;

        }

        $(document).on("click", ".addtobasket", base.onAddToBasketClick);
    }

}

GridShop.prototype.getListState = function () {
    if (this.list.hasClass("activeitem")) {
        return "details";
    } else {
        return "list";
    }
}

GridShop.prototype.query = function (method, data, callback) {

    $.ajax({
        url: this.config.dataUrl + method,
        type: "POST",
        data: JSON.stringify(data),
        headers: {
            culture: this.culture
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            callback(result);
            AjaxNav.events.callHandlers("afterGridShopQuery", method);
        }
    });
}

GridShop.prototype.setState = function (state, subState) {
    var newState = { s: null };
    if (state) {
        newState.s = state;
        if (subState) {
            newState = $.extend(newState, subState);
        }
    }
    AjaxNav.pushState(newState);
}

GridShop.prototype.ready = function (event) {
    if (!this.initComplete) {
        this.initFunctions.push(event);
    } else {
        event();
    }
}

GridShop.on = function (eventName, event) {
    var currentShop = GridShop.getCurrent();

    currentShop.ready(function () {
        currentShop.list.on(eventName, event);
    });

}

GridShop.prototype.trigger = function (eventName, data) {
    this.list.trigger(eventName, data);
}

// jQuery Plugin
$.fn.GridShop = function (config) {
    var element = $(this);

    var doInit = function () {

        if (!element.hasClass("shop-init")) {
            var shop = document.shop;
            shop.list = element;

            if (config) {
                shop.config = $.extend(shop.config, config);
            }

            shop.init();

            AjaxNav.bind("shop", "live", function () {
                $(".list.shop").each(function () {
                    if ($(this).data("shop")) {
                        $(this).data("shop").initList();
                    }
                });
            });

            element.addClass("shop-init");
            element.addClass("shop");
        }

    }

    if (!document.shop) {
        document.shop = new GridShop();

        if (document.shopConfig) {
            document.shop.config = $.extend(document.shop.config, document.shopConfig);
        }

        document.shop.query("GetConfig", null, function (serverConfig) {
            document.shop.config = $.extend(document.shop.config, serverConfig);
            doInit();
        });
    } else {
        doInit();
    }

    return $(this);
}