/**
 * Cart Maker
 * Copyright (C) 2008 Axis
 * @version:  01.01.01 Alpha
 * @modified: 2008-02-18
 */
var cart = {
    orderList : null,

    cartMain : null,
    cartIcon : null,
    cartList : null,
    winWr : null,

    isShow : false,
    timer  : null,

    cartTop : 0,
    specTop : 0,
    loader  : null,
    cartVoile : null,
    isSending : true,

    init : function (winWr)
    {
        this.winWr  = typeof(winWr) != "undefined" ? winWr : _wrapper;
        this.cartMain = this.winWr.getElement(this.config.cartId);

        this.loader  = this.winWr.getLoadWrapper(this.config.loader, "get", false);
        this.loader.setMode(1);
        this.loader.addListener(this, "ondataload", "onDataLoad");
        this.send("init");
    },
    send : function (mode, id, qtt)
    {
        this.isSending = true;
        var data = {"mode" : mode};
        if (id) {
            data.id = id;
        }
        if (qtt) {
            data.qtt = qtt;
        }
        if  (this.isShow && this.cartVoile) {
            this.cartVoile.show();
        }
        this.loader.send(data);
    },
    onDataLoad : function (json, dom, txt)
    {
        this.isSending = false;
        if (txt == "ok") {
            if (!this.cartIcon) {
                this.basicSubscribe();
            }
            this.orderList = json.goods;
            this.drawCartList();
            if (this.specTop) {
                this.showCart();
                this.cartList.setAbsTop(this.specTop - this.cartTop + this.config.shiftTop + this.config.shiftAdd);
                this.specTop = 0;
            }
            if (isDefined(json, "cookie")) {
                var cdt = new Date();
                var y = cdt.getYear();
                this.winWr.setCookie("aGoods",json.cookie, new Date(y < 2000 ? y + 1900 : y, cdt.getMonth() + 1, cdt.getDate()), "/");
            }
        } else {
            alert(txt);
        }
    },

    basicSubscribe : function ()
    {
        var winWr, pref, pl, elm, i;
        winWr = this.winWr;
        this.cartIcon = winWr.getElmWrapper(this.cartMain.elm.firstChild);
        this.cartList = winWr.makeElement("div",{"id":"cart_list"});
        this.cartMain.elm.appendChild(this.cartList.elm);
        this.cartTop = this.cartIcon.getAbsTop();

        if (this.config.showByOver) {
            this.cartIcon.addListener(this, "onmouseover", "onCartOver");
            //this.cartIcon.addListener(this, "onmouseout", "onCartOut");
            this.cartList.addListener(this, "onmouseover", "onCartOver");
            //this.cartList.addListener(this, "onmouseout", "onCartOut");
        //} else {
        }
        winWr.addListener(this, "onclick", "onBodyClick");
        this.cartList.addListener(this, "onclick", "onListClick");
        this.cartIcon.addListener(this, "onclick", "onCartClick");

        pref = this.config.formIdPrefix;
        pl  = pref.length;
        elm = winWr.doc.body.getElementsByTagName("form");
        for (i in elm) {
            if (elm[i].id && elm[i].id.substr(0, pl) == pref) {
                winWr.getElmWrapper(elm[i]).addListener(this, "onsubmit", "onAddGoods");
            }
        }
    },

    drawCartList : function ()
    {
        var conf, html, text, code, rows, row, id, tsum, n, k, re, res, aRe, tags, i;

        conf = this.config;
        html = conf.htmlCode;
        text = conf.text[conf.language];

        // Make HTML-code of
        if (this.orderList) {
            rows  = "";
            n = 1;
            tsum = 0;
            for (id in this.orderList) {
                row = html.rowGoods.replace('{num}', n);
                row = row.replace(/\{id\}/g, id);
                for (k in this.orderList[id]) {
                    row = row.replace('{' + k + '}', this.orderList[id][k]);
                }
                row = row.replace('{sum}', this.orderList[id].qtt * this.orderList[id].price);
                tsum += this.orderList[id].qtt * this.orderList[id].price;
                rows += row;
                n++;
            }
            code = html.isGoods.replace('{total_sum}', tsum);
            code = code.replace('{row_goods}', rows);
        } else {
            code = html.isEmpty;
            this.cartVoile = null;
        }
        code = html.global.replace('{cart_list}',code);

        re = /\[(\w+)\]/g;
        while ((res = re.exec(code)) != null) {
            code = code.replace(res[0], isDefined(text, res[1]) ? text[res[1]] : "_" + res[1] + "_");
        }
        this.cartList.elm.innerHTML = code;

        //Subscribe for events of cart-elements
        if (this.orderList) {
            this.cartVoile = this.winWr.getElement("cart_voile");

            aRe = {};
            for (k in conf.ctrlLink) {
                aRe[k] = new RegExp(k + "\\_(\\d+)");
            }
            tags = this.cartList.elm.getElementsByTagName("a");
            for (i = 0; i < tags.length; i++) {
                if (tags[i].id) {
                    for (k in aRe) {
                        if ((res = aRe[k].exec(tags[i].id)) != null) {
                            this.winWr.getElmWrapper(tags[i]).addListener(this, "onclick", conf.ctrlLink[k]).id = res[1];
                            break;
                        }
                    }
                }
            }
            tags = this.cartList.elm.getElementsByTagName("input");
            for (i = 0; i < tags.length; i++) {
                this.winWr.getElmWrapper(tags[i]).addListener(this, "onchange", "onQttChange").id = tags[i].name.substr(3);
            }
            this.winWr.getElement("cart_continue").addListener(this, "onclick", "onContinueClick");
        }
    },

    onAddGoods : function(evtWr, obj)
    {
        var elms, re, res, v, i;
        evtWr.eventDrop();
        this.specTop = evtWr.elmWr.getAbsTop();
        re = /^id\[(\d+)\]$/;
        elms = evtWr.elmWr.elm.elements;
        for (i = 0; i < elms.length; i++) {
            if (isDefined(elms[i], "name") && (res = re.exec(elms[i].name)) != null) {
                v = elms[i].value;
                if (!v || /^\d+$/.exec(v) == null) {
                    this.msg("incorrect_qtt");
                } else {
                    this.send("add", res[1], v);
                }
                break;
            }
        }
    },
    onQttChange : function(evtWr, obj)
    {
        var q, nq, s, v, i;
        q = this.orderList[obj.id].qtt;
        s = "";
        v = evtWr.elmWr.elm.value + "";
        for (i = 0; i < v.length; i++) {
            if (v.charCodeAt(i) > 47 && v.charCodeAt(i) < 58) {
                s += v.charAt(i);
            }
        }
        evtWr.elmWr.elm.value = s;
        nq = parseInt(s);
        if (q == nq) {
            return;
        }
        if (nq > 0) {
            this.send("add", obj.id, nq);
        } else if(confirm(this.config.text[this.config.language].sure2del)) {
            this.send("del", obj.id);
        } else {
            evtWr.elmWr.elm.value = 1;
            if (q != 1) {
                this.send("add", obj.id, 1);
            }
        }
    },
    onIncrement : function(evtWr, obj)
    {
        evtWr.eventDrop();
        if  (!this.isSending) {
            this.send("add", obj.id, parseInt(this.orderList[obj.id].qtt) + 1);
        }
    },
    onDecrement : function(evtWr, obj)
    {
        evtWr.eventDrop();
        if  (!this.isSending) {
            var q = this.orderList[obj.id].qtt;
            if (q < 2) {
                this.onDelete(null, obj);
            } else {
                this.send("add", obj.id, q - 1);
            }
        }
    },
    onDelete : function(evtWr, obj)
    {
        if (evtWr) {
            evtWr.eventDrop();
        }
        if(!this.isSending && confirm(this.config.text[this.config.language].sure2del)) {
            this.send("del", obj.id);
        }
    },

    onListClick : function(evtWr, obj)
    {
        evtWr.stopBubbling();
    },
    onCartClick : function(evtWr, obj)
    {
        evtWr.eventDrop();
        evtWr.stopBubbling();
        evtWr.elmWr.elm.blur();
        if (!this.isShow) {
            this.showCart();
        }
    },
    onContinueClick : function(evtWr, obj)
    {
        evtWr.eventDrop();
        evtWr.elmWr.elm.blur();
        this.hideCart();
    },
    onBodyClick : function(evtWr, obj)
    {
        this.hideCart();
    },
    onCartOver : function(evtWr, obj)
    {
        this.setTimer(this.isShow ? null : 'showCart');
    },
    onCartOut : function(evtWr, obj)
    {
        this.setTimer(this.isShow ? 'hideCart' : null);
    },

    setTimer : function(method)
    {
        if(this.timer) {
            clearTimeout(this.timer);
        }
        this.timer = method ? this.winWr.setTimeout(this.config.delay[method],this,method) : null;
    },

    showCart : function()
    {
        this.setTimer();
        if  (this.isSending && this.cartVoile) {
            this.cartVoile.show();
        }
        this.cartList.show();
        this.isShow = true;
    },
    hideCart : function()
    {
        this.setTimer();
        this.cartList.setAbsTop(this.config.shiftTop);
        this.cartList.hide();
        if  (this.cartVoile) {
            this.cartVoile.hide();
        }
        this.isShow = false;
    },
    msg : function(key)
    {
        this.winWr.alert(this.config.text[this.config.language][key]);
    },

    config : {
        "loader" : "/cart_list.php",
        "cartId" : "cart",
        "shiftTop" : 31,
        "shiftAdd" : -35,
        "formIdPrefix" : "goods_",
        "ctrlLink" : {"del" : "onDelete", "incr" : "onIncrement", "decr" : "onDecrement"},
        "showByOver" : true,
        "delay"  : {'showCart' : 200, 'hideCart' : 1250},
        "language" : 'ru',
        "htmlCode" : {
            'global'   : '<form action="#">{cart_list}</form>',
            'isEmpty'  : '<div>[no_goods]</div>',
            'isGoods'  : '<table><tr><th>[num]</th><th>[name]</th><th>[qtt]</th><th>[price]</th><th>[sum]</th><th> </th></tr>{row_goods}<tr id="total_row"><td> </td><td colspan="3">[total]:</td><td class="right">{total_sum}</td><td> </td></tr></table><div id="cart_footer"><a href="#" title="[continue_t]" id="cart_continue">[continue]</a><a href="/order/pay.html" title="[ordering_t]" id="ordering">[ordering]</a><a href="/order/save_order.html" title="[save_order_t]" id="save_order">[save_order]</a></div><div id="cart_voile"></div>',
            'rowGoods' : '<tr><td class="right">{num}.</td><td class="goods_name">{name}</td><td><input name="id_{id}" value="{qtt}" /></td><td class="right">{price}</td><td class="right"><span id="sum_{id}">{sum}</span></td><td><div class="c_but"><a href="#" id="del_{id}" class="del" title="[delete]">Del</a><a href="#" id="incr_{id}" class="incr" title="[increment]">Incr</a><a href="#" id="decr_{id}" class="decr" title="[decrement]">Decr</a></div></td></tr>'
        },
        "text" : {
            'ru' : {
                'no_goods' : 'Нет товаров в корзине',
                'num'   : '№',
                'name'  : 'Наименование',
                'qtt'   : 'Кол-во',
                'price' : 'Цена',
                'sum'   : 'Сумма',
                'delete': 'Удалить товар',
                'increment' : 'Увеличить кол-во на 1',
                'decrement' : 'Уменьшить кол-во на 1',
                'total' : 'Всего',
                'continue'   : 'Продолжить покупки',
                'ordering'   : 'Оформить заказ',
                'save_order' : 'Сохранить заказ',
                'continue_t'   : 'Закрыть окно корзины',
                'ordering_t'   : 'Отправить заказ на оформление',
                'save_order_t' : 'Сохранить заказ, но не отправлять на оформление',
                'incorrect_qtt' : 'Неправильно указано количество',
                'sure2del' : 'Вы уверены, что хотите удалить данный товар?'
            }
        }
    }

};
