/**
 * Cart Maker
 * Copyright (C) 2008 Axis
 * @version:  02.01.01 Alpha
 * @modified: 2009-02-02
 */
var oCart = {
    orderList : null,
    //id        : null,

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

    isShow : false,
    timer  : null,

    language : null,

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

    showPrice  : 1,
    showWeight : 1,
    showVolume : 1,
	update_cart : false,
	ordered_goods_id : null,

    init : function (lng, cur, login)
    {
		if (!isDefined(cur)) {
			cur = this.config.currency;
		}
    	if (!isDefined(lng)) {
			lng = this.config.language
		}
        this.language = lng;
        this.currency = cur;

        this.loader  = this.getLoadWrapper(this.config.loader, "get", false);
        this.loader.setMode(0);
        this.loader.addListener(this, "ondataload", "onDataLoad");
    },
    
    onready : function ()
    {
		this.send("init");
    	// -- this.cartMain = this.$(this.config.cartId);

        elm = this.$$("form#" + this.config.formIdPrefix + "*");
        if (elm) elm.addListener(this, "onsubmit", "onAddGoods");
    },
    
    send : function (mode, id, qtt)
    {
        this.isSending = true;
        var data = {"mode" : mode};
        if (id) {
            data.id = id;
        }
        if (qtt) {
            data.qtt = qtt;
        }
        this.loader.send(data);
    },
    
    onDataLoad : function (json, dom, txt)
    {
        this.isSending = false;
        if (txt == "ok") {
            this.orderList = json.goods;
    		
    		// this.showTotalInfo();

            if (isDefined(json, "cookie")) {
                var cdt = new Date();
                var y = cdt.getYear();
                this.setCookie("aGoods", json.cookie, new Date(y < 2000 ? y + 1900 : y, cdt.getMonth() + 1, cdt.getDate()), "/");
            }

			if (this.update_cart) {
				counter = jQuery($('#cart_items_count'));
				counter.text(
					parseInt(counter.text()) + 1
				);
				this.update_cart = false;

				this.showMessage(this.ordered_goods_id);
			}
        } else {
            alert(txt);
        }
    },
	showMessage : function (goods_id)
	{
            root = jQuery($(
                        '#rate_element_' + goods_id.slice(goods_id.indexOf('_') + 1)
                    ));

            if (root.find('.info').length > 0) {
                    root.find('.info').remove();
            }
            if (root.parent().find('span.info').length == 0) {
                $('<span class="info">' +
                        this.config.text[this.language]['successfully_added'] +
                '</span>').appendTo(root.parent());
            }
	},
    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) {
                if (isDefined(this.orderList, res[1])) {
                    //propA(this.orderList[res[1]]);
                    //this.msg("goods_is_exist", this.orderList[res[1]].qtt + this.config.text[this.language]['total_info']['count']);
                    
                    if (confirm(this.config.text[this.language].goods_is_exist + this.orderList[res[1]].qtt + this.config.text[this.language]['total_info']['count'] + this.config.text[this.language].sure2add + elms[i].value + this.config.text[this.language]['total_info']['count'] + "?")) {
                    	v = elms[i].value;
	                    if (!v || /^\d+$/.exec(v) == null) {
	                        this.msg("incorrect_qtt");
	                    } else {
	                        this.send("add_plus", res[1], v);
							this.ordered_goods_id = evtWr.elmWr.elm.id;
	                    }
                    }
                } else {
                    v = elms[i].value;
                    if (!v || /^\d+$/.exec(v) == null) {
                        this.msg("incorrect_qtt");
                    } else {
                        this.send("add", res[1], v);
						this.ordered_goods_id = evtWr.elmWr.elm.id;
                    }
                }
                break;
            }
        }

		this.update_cart = true;
    },

    onIncrement : function(evtWr, obj)
    {
        evtWr.eventDrop();
        if  (!this.isSending) {
            this.send("add", obj.id, parseInt(this.orderList[obj.id].qtt) + 1);
        }
    },

    showTotalInfo : function()
    {
        div_total = this.$("#total_info");

        code = this.config.htmlCode.totalInfoSpan;
        text = this.config.text[this.language]['total_info'];

        n = 0;
        tsum = 0;
        tweight = 0;
        tvolume = 0;
        // Make HTML-code of
        var arr = [];
        var k=0;
        if (this.orderList) {
            for (id in this.orderList) {
                var qtt  = this.orderList[id].qtt;
                tsum    += this.orderList[id].price  * qtt;
                //tweight += this.orderList[id].weight * qtt;
                //tvolume += this.orderList[id].volume * qtt;
                n += qtt;

                arr[k] = [qtt, this.orderList[id].price  * qtt, tsum];
                k++;
            }
        }
        // alert(arr)

        // th tpl
        /*code = code.replace('[total_cnt]',  text.total_cnt);
        code = code.replace('[total]', text.total_sum);
        code = code.replace('[total_weight]', text.total_weight);
        code = code.replace('[total_volume]', text.total_volume);
        // values
        code = code.replace('{total_cnt}',    n);
        code = code.replace('{total_sum}',    this.priceFormat(tsum, 2) );
        code = code.replace('{total_weight}', this.num2text(tweight,100000)  );
        code = code.replace('{total_volume}', this.num2text(tvolume,100000)  );*/

        // th tpl
        code = code.replace('[total_goods]',  text.total_goods);
        // code = code.replace('[total_sum]', text.total_sum);
        code = code.replace('[count]', text.count);
        //code = code.replace('[currency]', this.currency);
        // values
        code = code.replace('{total_cnt}', n);
        //code = code.replace('{total_sum}', this.priceFormat(tsum, 2) );

        

        if (div_total) div_total.elm.innerHTML = code;
    },

    msg : function(key, add_value)
    {
		var text = this.config.text[this.language][key];
		if (add_value) {
			text += add_value;
		}
    	this.$w0.alert(text);
    },
    
    priceFormat : function(txt, fl)
    {
        // return txt;

        var intp0, intp1, fractp, a, l, n, i;
        fractp = ",";
        for (i = 0; i < fl; i++) {
            fractp += "0";
        }
        if (!txt || txt == 0) {
            return '0' + fractp;
        }
        
        // v1 txt = parseInt(txt * 100).toString();
        // v2 
        var t1,t2,t3,t4;
        //t1 = txt;
        txt = txt * 100;
        //t2 = txt;
        txt = Math.round(txt);
        //t3 = txt;
        txt = parseInt(txt);
        txt = txt.toString();
        //t4 = txt;
        //alert([t1,t2,t3,t4])

        a = /^([0-9\-]+)/.exec(txt);
        if (a) {
            l = a[1].length - fl;
            intp0 = l < 1 ? '0' : a[1].substr(0, l);
            fractp = "," + a[1].substr(l);
            for (i = fl + 1 - fractp.length; i > 0; i--) {
                fractp += "0";
            }
        } else {
            intp0 = 0;
        }
        intp1 = "";
        l = intp0.length;
        for (i = 0; i < l; i += 3) {
            n = l - i;
            intp1 = intp0.substring((n < 3 ? 0 : n - 3), n) + " " + intp1;
        }
        
        var ret = intp1.substring(0, intp1.length - 1) + fractp;
        // alert(ret)
        return ret;
    },

    num2text : function(num, frac)
    {
        var s,s1,s2;

        if (!frac) {frac=100;}

        s  = this.dig(num, frac);
        s2 = s1 = "";

        var k=0;
        var a=s.split(".");
        s2=a[0];
        for (var i=s2.length-1;i>=0;i--) {
            s1=s2.substring(i,i+1)+s1;
            k++;
            if(k%3==0 && i>0)s1="&nbsp;"+s1;
        }
        a[0]=s1;
        s1=a.join(",");
        return s1;
    },

    dig : function(n, frac)
    {
        if (!frac) {frac=100;}

        n = n * frac;
        n = Math.round(n);
        n = n / frac;
        var ns = n + '';

        var ps = ns.indexOf(".");
        var zero = '';
        if (ps>0) {
            zero = ns.substring(ps+1);
            ns = ns.substring(0, ps+1);
            if (zero.length==1) zero += '0';
        }
        else {
            zero = '.00'
        }
        ns = ns + zero;

        return ns;
    },


    config : {
        "loader" : "/cart_list.php",
        "cartId" : "#cart",
        "shiftTop" : 290,
        "shiftAdd" : -35,
        "formIdPrefix" : "goods_",
        "ctrlLink" : {"del" : "onDelete", "incr" : "onIncrement", "decr" : "onDecrement"},
        "showByOver" : true,
        "delay"  : {'showCart' : 200, 'hideCart' : 1250},
        "language" : 'ru',
        "currency" : 'UAH',
        
        "htmlCode" : {
            'global'        : '<form action="#">{cart_list}</form>',
            'isEmpty'       : '<div>[no_goods]</div>',

            'totalInfo'     : '<table><tr><th>[total_cnt]:</th><th>[total]:</th><th>[total_weight]:</th><th>[total_volume]:</th></tr><tr>'
            + '<td class="right pad15">{total_cnt}</td><td class="right pad15">{total_sum}</td><td class="right pad15">{total_weight}</td><td class="right pad15">{total_volume}</td></tr></table>',

            //'totalInfoSpan' : '<span>[total_goods]: {total_cnt}[count]</span><span>[total_sum]: {total_sum}</span><a id="order_show" href="/order/order_main.html">Посмотреть заказ</a>'
            'totalInfoSpan' : '<span>[total_goods]: {total_cnt}[count]</span>'
        },

        "text" : {
            'ru' : {
                'successfully_added' : 'Позиция успешно добавлена',
                'no_goods' : 'Нет товаров в корзине',
                'num'   : '№',
                'name'  : 'Артикул',
                'qtt'   : 'Кол-во',
                'price' : 'Цена',
                'sum'   : 'Сумма',
                'weight'     : 'Вес',
                'sum_weight' : 'Вес',
                'volume'     : 'Объем',
                'sum_volume' : 'Объем',
                'delete': 'Удалить товар',
                'increment' : 'Увеличить кол-во на 1',
                'decrement' : 'Уменьшить кол-во на 1',
                'total'        : 'Всего',
                'total_sum'    : 'Общая сумма',
                'total_cnt'    : 'Всего товаров',
                'total_weight' : 'Общий вес',
                'total_volume' : 'Общий объем',
                'continue'     : 'Продолжить заказ',
                'delete_order' : 'Очистить заказ',
                'ordering'     : 'Отправить заказ',
                'save_order'   : 'Сохранить заказ',
                'continue_t'     : 'Закрыть окно корзины',
                'delete_order_t' : 'Очистить заказ',
                'ordering_t'     : 'Отправить заказ на оформление',
                'save_order_t'   : 'Сохранить заказ, но не отправлять на оформление',
                'incorrect_qtt'  : 'Неправильно указано количество',
                'goods_is_exist' : 'Такая позиция в заказе присутствует в количестве ',
                'sure2del'    : 'Вы уверены, что хотите удалить данный товар?',
                'sure2delAll' : 'Вы уверены, что хотите удалить весь заказ?',
                'sure2add'    : '\nУвеличить ее количество еще на ',
                'total_info' : {
                	'total_goods' : 'Товаров в корзине',
                	'total_sum'   : 'На общую сумму',
	                'count'       : 'шт.',
	                'currency'    : '' //'грн.'
                }
            },
            'en' : {
				'successfully_added' : 'Position successfully added',
                'no_goods' : 'There are not commodities in a basket',
                'num'   : '№',
                'name'  : 'Name',
                'qtt'   : 'Amount',
                'price' : 'Price',
                'sum'   : 'Sum',
                'weight' : 'Weight',
                'delete': 'Delete a commodity',
                'increment' : 'Increase an amount upon 1',
                'decrement' : 'Decrease an amount upon 1',
                'total' : 'In all',
                'continue'     : 'Continue an order',
                'delete_order' : 'Delete an order',
                'ordering'     : 'Process an order',
                'save_order'   : 'Save an order',
                'continue_t'     : 'Close the window of basket',
                'delete_order_t' : 'Delete an order',
                'ordering_t'     : 'Send an order to registration',
                'save_order_t'   : 'Save an order, but don\'t send to registration',
                'goods_is_exist' : 'Such goods already exists in your order',
                'incorrect_qtt' : 'There is incorrect declared an amount',
                'sure2del' : 'Are you sure would you delete this goods?',
				'total_info' : {
                	'total_goods' : 'Товаров в корзине',
                	'total_sum'   : 'На общую сумму',
	                'count'       : 'шт.',
	                'currency'    : '' //'грн.'
                }
            },
            'sp' : {
				'successfully_added' : 'Position successfully added',
				'no_goods' : 'Нет товаров в корзине',
                'num'   : '№',
                'name'  : 'Артикул',
                'qtt'   : 'Кол-во',
                'price' : 'Цена',
                'sum'   : 'Сумма',
                'weight'     : 'Вес',
                'sum_weight' : 'Вес',
                'volume'     : 'Объем',
                'sum_volume' : 'Объем',
                'delete': 'Удалить товар',
                'increment' : 'Увеличить кол-во на 1',
                'decrement' : 'Уменьшить кол-во на 1',
                'total'        : 'Всего',
                'total_sum'    : 'Общая сумма',
                'total_cnt'    : 'Всего товаров',
                'total_weight' : 'Общий вес',
                'total_volume' : 'Общий объем',
                'continue'     : 'Продолжить заказ',
                'delete_order' : 'Очистить заказ',
                'ordering'     : 'Отправить заказ',
                'save_order'   : 'Сохранить заказ',
                'continue_t'     : 'Закрыть окно корзины',
                'delete_order_t' : 'Очистить заказ',
                'ordering_t'     : 'Отправить заказ на оформление',
                'save_order_t'   : 'Сохранить заказ, но не отправлять на оформление',
                'incorrect_qtt'  : 'Неправильно указано количество',
                'goods_is_exist' : 'Такая позиция в заказе присутствует в количестве ',
                'sure2del'    : 'Вы уверены, что хотите удалить данный товар?',
                'sure2delAll' : 'Вы уверены, что хотите удалить весь заказ?',
                'sure2add'    : '\nУвеличить ее количество еще на ',
                'total_info' : {
                	'total_goods' : 'Товаров в корзине',
                	'total_sum'   : 'На общую сумму',
	                'count'       : 'шт.',
	                'currency'    : '' //'грн.'
                }
			},
            'de' : {
				'successfully_added' : "Position erfolgreich hinzugefugt",
				'no_goods' : 'Нет товаров в корзине',
                'num'   : '№',
                'name'  : 'Артикул',
                'qtt'   : 'Кол-во',
                'price' : 'Цена',
                'sum'   : 'Сумма',
                'weight'     : 'Вес',
                'sum_weight' : 'Вес',
                'volume'     : 'Объем',
                'sum_volume' : 'Объем',
                'delete': 'Удалить товар',
                'increment' : 'Увеличить кол-во на 1',
                'decrement' : 'Уменьшить кол-во на 1',
                'total'        : 'Всего',
                'total_sum'    : 'Общая сумма',
                'total_cnt'    : 'Всего товаров',
                'total_weight' : 'Общий вес',
                'total_volume' : 'Общий объем',
                'continue'     : 'Продолжить заказ',
                'delete_order' : 'Очистить заказ',
                'ordering'     : 'Отправить заказ',
                'save_order'   : 'Сохранить заказ',
                'continue_t'     : 'Закрыть окно корзины',
                'delete_order_t' : 'Очистить заказ',
                'ordering_t'     : 'Отправить заказ на оформление',
                'save_order_t'   : 'Сохранить заказ, но не отправлять на оформление',
                'incorrect_qtt'  : 'Неправильно указано количество',
                'goods_is_exist' : 'Такая позиция в заказе присутствует в количестве ',
                'sure2del'    : 'Вы уверены, что хотите удалить данный товар?',
                'sure2delAll' : 'Вы уверены, что хотите удалить весь заказ?',
                'sure2add'    : '\nУвеличить ее количество еще на ',
                'total_info' : {
                	'total_goods' : 'Товаров в корзине',
                	'total_sum'   : 'На общую сумму',
	                'count'       : 'шт.',
	                'currency'    : '' //'грн.'
                }
			},
            'fr' : {
				'successfully_added' : "Position d'ajouter",
				'no_goods' : 'Нет товаров в корзине',
                'num'   : '№',
                'name'  : 'Артикул',
                'qtt'   : 'Кол-во',
                'price' : 'Цена',
                'sum'   : 'Сумма',
                'weight'     : 'Вес',
                'sum_weight' : 'Вес',
                'volume'     : 'Объем',
                'sum_volume' : 'Объем',
                'delete': 'Удалить товар',
                'increment' : 'Увеличить кол-во на 1',
                'decrement' : 'Уменьшить кол-во на 1',
                'total'        : 'Всего',
                'total_sum'    : 'Общая сумма',
                'total_cnt'    : 'Всего товаров',
                'total_weight' : 'Общий вес',
                'total_volume' : 'Общий объем',
                'continue'     : 'Продолжить заказ',
                'delete_order' : 'Очистить заказ',
                'ordering'     : 'Отправить заказ',
                'save_order'   : 'Сохранить заказ',
                'continue_t'     : 'Закрыть окно корзины',
                'delete_order_t' : 'Очистить заказ',
                'ordering_t'     : 'Отправить заказ на оформление',
                'save_order_t'   : 'Сохранить заказ, но не отправлять на оформление',
                'incorrect_qtt'  : 'Неправильно указано количество',
                'goods_is_exist' : 'Такая позиция в заказе присутствует в количестве ',
                'sure2del'    : 'Вы уверены, что хотите удалить данный товар?',
                'sure2delAll' : 'Вы уверены, что хотите удалить весь заказ?',
                'sure2add'    : '\nУвеличить ее количество еще на ',
                'total_info' : {
                	'total_goods' : 'Товаров в корзине',
                	'total_sum'   : 'На общую сумму',
	                'count'       : 'шт.',
	                'currency'    : '' //'грн.'
                }
			},
            'ua' : {
				'successfully_added' : 'Позиція успішно додана',
                'no_goods' : 'Немає товарів в корзині',
                'num'   : '№',
                'name'  : 'Найменування',
                'qtt'   : 'Кількість',
                'price' : 'Ціна',
                'sum'   : 'Сума',
                'weight' : 'Вага',
                'delete': 'Видалити товар',
                'increment' : 'Збільшити к-ть на 1',
                'decrement' : 'Зменшити к-ть на 1',
                'total' : 'Всього',
                'continue'     : 'Продовжити замовлення',
                'delete_order' : 'Очистити замовлення',
                'ordering'     : 'Оформити замовлення',
                'save_order'   : 'Зберегти замовлення',
                'continue_t'     : 'Закрити вікно корзини',
                'delete_order_t' : 'Очистити замовлення',
                'ordering_t'     : 'Відправити замовлення на оформлення',
                'save_order_t'   : 'Зберегти замовлення, але не відправляти на оформлення',
                'goods_is_exist' : 'Такий товар вже є у Вашому замовленні ',
                'incorrect_qtt' : 'Неправільно вказана кількість',
                'sure2del' : 'Ви упевнені, що хочете видалити даний товар?',
				'sure2delAll' : 'Вы уверены, что хотите удалить весь заказ?',
                'sure2add'    : '\nУвеличить ее количество еще на ',
				'total_info' : {
                	'total_goods' : 'Товаров в корзине',
                	'total_sum'   : 'На общую сумму',
	                'count'       : 'шт.',
	                'currency'    : '' //'грн.'
                }
            }
        }
    }
}

var cart = newObject(oCart);
