uzEsOrderingCustom = {
    page: "",
    editScriptLink: "",
    cartClassDeliveryTime: "uz_cart_delivery_time",
    cartClassDiscount: "uz_cart_discount",
    grp: 0,

    cookieName: "uz_order_custom_data",

    roundPrec: 2,

    aData: new Array(),

    orderingUrl: "",
    recalcActionCmplete: true,
    needOrdering: false,

    init: function(hOpt){
        // Set options
        if(typeof(uzEsOrderingCustomOptions) != 'undefined'){
            this.setOptions(uzEsOrderingCustomOptions);
        }
        // Set forced options
        if(typeof(hOpt) != 'undefined'){
            this.setOptions(hOpt);
        }

        if(this.grp == 3){
            //
            // On load restore saved params or recalc
            //
            var t = AMI.Browser.Cookie.get(this.cookieName);
            if(t != null){
                eval("ht = "+t);
                this.aData = ht;
            }

            if(this.page == "cart"){
                this.applyDataToForm();
                this.onCartExtraParamsChanged(1,1);
            }
        } else {
            // Force clean extra data
            AMI.Browser.Cookie.del(this.cookieName);
        }

        if(this.page == "cart"){
            //
            // Register listeners
            //
            AMI.Message.addListener("uz_on_cart_extra_params_changed", function(p1,p2){return uzEsOrderingCustom.onCartExtraParamsChanged(p1,p2);});
            AMI.Message.addListener("uz_on_cart_click_action", function(p1,p2){return uzEsOrderingCustom.onCartClickAction(p1,p2);});
            AMI.Message.addListener("uz_on_cart_loaded", function(p1,p2){return uzEsOrderingCustom.onCartLoaded(p1,p2);});
        }

        if(this.grp == 3){
            if(this.page == "order"){
                //uz_delivery_time_##id##_##num_price##

                this.applyDataToorderForm();
            }
        }
    },

    setOptions: function(opt){
        for(var key in opt){
            this[key] = opt[key];
        }
    },

    applyDataToForm: function(){
        if(this.aData.length){
            $("input."+this.cartClassDeliveryTime).each(function(){uzEsOrderingCustom.applyDataToItem(this);});
        }
    },

    applyDataToItem: function(oItem){
        oItem = $(oItem);

        var id = oItem.attr("uz_id");
        var pNum = oItem.attr("uz_num_price");

        var hData = this.getItemData(id, pNum);
        if(hData != null){
            oItem.val(hData.deliveryTime);
            $("#uz_cart_discount_"+id+"_"+pNum).val(hData.discount);
        }
    },

    getItemData: function(id, pNum){
        if(this.aData.length){
            for(i = 0; i < this.aData.length; i++){
                if(this.aData[i].id == id && this.aData[i].pNum == pNum){
                    return this.aData[i];
                }
            }
        }
        return null;
    },


    onCartExtraParamsChanged: function(p1, p2){
        if(this.grp == 3){
            this.aData = new Array();
            $("input."+this.cartClassDeliveryTime).each(function(){uzEsOrderingCustom.addCartItemData(this);});
            AMI.Browser.Cookie.set(this.cookieName, this.toJsonString(this.aData), 24);
            this.recalcCart();
            /*
            var t = AMI.Browser.Cookie.get(this.cookieName);
            if(t != null){
                eval("ht = "+t);
                alert(this.toString(ht));
            }
            //*/
        }
        return p2;
    },

    addCartItemData: function(oItem){
        oItem = $(oItem);
        var id = oItem.attr("uz_id");
        var pNum = oItem.attr("uz_num_price");

        // Validate discount value
        var oDiscount = $("#uz_cart_discount_"+id+"_"+pNum);
        var discount = oDiscount.val();
        //alert("orig = "+discount);
        discount = this.validateFloat(discount);
        //alert("validated = "+discount);
        oDiscount.val(discount);

        var hItem = {
            id: id,
            pNum: pNum,
            deliveryTime: oItem.val(),
            discount: discount
        };
        this.aData.push(hItem);
    },

    recalcCart: function(oItem){
        var total = 0;
        var totalDiscount = 0;
        var rowTotal = 0;
        var rowDiscount = 0;
        var postfix = "";

        var i, price, priceStr, qty, hItem;

        if(this.aData.length){
            for(i = 0; i < this.aData.length; i++){
                hItem = this.aData[i];
                //alert(this.toString(hItem));
                pricePlain = $("#uz_cart_price_"+hItem.id+"_"+hItem.pNum).val()
                price = this.validateFloat(pricePlain);

                if(postfix == ""){
                    priceStr = "" + price;
                    postfix = pricePlain.substr(priceStr.length);
                }

                qty = this.validateFloat($("#uz_cart_qty_"+hItem.id+"_"+hItem.pNum).val(), 0);
                //alert(price+", "+qty);

                rowDiscount = this.round(price / 100 * hItem.discount * qty);
                rowTotal = price * qty - rowDiscount;
                total += rowTotal;
                totalDiscount += rowDiscount;

                $("#uz_cart_abs_discount_"+hItem.id+"_"+hItem.pNum).html(rowDiscount + postfix);
                $("#uz_cart_row_total_"+hItem.id+"_"+hItem.pNum).html(rowTotal + postfix);
            }
            $("#uz_cart_total_abs_discount").html(totalDiscount + postfix);
            $("#uz_cart_total").html(total + postfix);
        }

    },


    onCartClickAction: function(action, p2){
        //alert(action);
        frm = document.entryform;
        frm.action.value = action;

        switch(action){
            case "recalc":
                this.recalcActionCmplete = false;
                frm.submit();
                if(this.grp != 3){
                    // Disable fields
                    $("input.uz_cart_qty_field").attr("disabled","disabled");
                }
                break;
            case "empty":
                if(confirm(p2)) {
                    this.recalcActionCmplete = false;
                    this.needOrdering = false;
                    document.location.replace(active_module_link + "?action=empty");
                }
                break;
            case "order":
                //alert(p2);
                this.orderingUrl = p2;
                if(this.recalcActionCmplete){
                    this.goToOrdering();
                } else {
                    this.needOrdering = true;
                }
                break;
            default:
                break;
        }
        return true;
    },

    
    goToOrdering: function(){
        if(this.orderingUrl != ""){
            window.location=this.orderingUrl;
        }
    },

    onCartLoaded: function(p1, p2){
        this.recalcActionCmplete = true;
        if(this.needOrdering){
            this.goToOrdering();
        }
    },





    applyDataToorderForm: function(){
        var num, i, hItem, pricePlain, price, priceStr, qty, tax;
        var postfix = "";
        var total = 0;
        var totalDiscount = 0;
        var rowTotal = 0;
        var rowDiscount = 0;

        if(this.aData.length){
            for(i = 0; i < this.aData.length; i++){
                num = i+1;
                hItem = this.aData[i];

                pricePlain = $("#uz_item_price_"+num).text();
                price = this.validateFloat(pricePlain);

                if(postfix == ""){
                    priceStr = "" + price;
                    postfix = pricePlain.substr(priceStr.length);
                }

                qty = this.validateFloat($("#uz_item_qty_"+num).text(), 0);

                //alert(this.toString(this.aData));

                rowDiscount = this.round(price / 100 * hItem.discount * qty);
                rowTotal = price * qty - rowDiscount;
                total += rowTotal;
                totalDiscount += rowDiscount;

                $("#uz_delivery_time_"+num).text(hItem.deliveryTime);
                $("#uz_item_discount_"+num).text(hItem.discount);
                $("#uz_item_abs_discount_"+num).html(rowDiscount + postfix);
                $("#uz_item_total_"+num).html(rowTotal + postfix);
            }

            totalDiscount = this.round(totalDiscount);
            total = this.round(total);
            tax = this.round(total * 18 / (100 + 18));

            $("#uz_total_discount").html(totalDiscount + postfix);
            $("#uz_order_total1").html(total + postfix);
            $("#uz_order_total2").val(total + postfix);
            $("#uz_total_tax").html(tax + postfix);

            
        }
    },










    validateFloat: function(val, roundPrecision){
        var re = /-?[0-9]+\.?[0-9]*/;
        var aVal = re.exec(val);
        //alert("validateFloat aVal = "+this.toString(aVal));
        if(aVal == null){
            val = 0;
        } else {
            val = parseFloat(aVal[0]);
        }

        /*
        if(isNaN(val) || val == ""){
            val = 0;
        }
        val = parseFloat(val);
        if(val < 0 ){
            val = 0;
        }
        //*/

        if(typeof(roundPrecision) == 'undefined'){
            var roundPrecision = this.roundPrec;
        }
        val = this.round(val, roundPrecision);
        return val;
    },

    round: function(val, prec){
        if(typeof(prec) == 'undefined'){
            prec = this.roundPrec;
        }
        //alert(val);
        var rounder = Math.pow(10, prec);
        val = Math.round(val * rounder);
        val = val / rounder;
        //alert(val);
        return val;
    },


    toString: function(oData, indent){
        if(typeof(indent) == 'undefined'){
            var indent = "";
        }
        var res = "";
        if(typeof(oData) == 'object'){
            for(var i in oData){
                if(typeof(oData[i]) == 'object'){
                  res += indent + i+": {\n"+this.toString(oData[i], indent + "  ")+indent + "}\n";
                } else {
                  res += indent + i+":"+oData[i]+"\n";
                }
            }
        } else {
            res += indent + oData+"\n";
        }
        return res;
    },

    toJsonString: function (mixed_val) {
        var retVal, json = window.JSON;
        try {
            if (typeof json === 'object' && typeof json.stringify === 'function') {
                retVal = json.stringify(mixed_val); // Errors will not be caught here if our own equivalent to resource
                //  (an instance of PHPJS_Resource) is used
                if (retVal === undefined) {
                    throw new SyntaxError('json_encode');
                }
                return retVal;
            }

            var value = mixed_val;

            var quote = function (string) {
                var escapable = /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
                var meta = { // table of character substitutions
                    '\b': '\\b',
                    '\t': '\\t',
                    '\n': '\\n',
                    '\f': '\\f',
                    '\r': '\\r',
                    '"': '\\"',
                    '\\': '\\\\'
                };

                escapable.lastIndex = 0;
                return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
                    var c = meta[a];
                    return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                }) + '"' : '"' + string + '"';
            };

            var str = function (key, holder) {
                var gap = '';
                var indent = '    ';
                var i = 0; // The loop counter.
                var k = ''; // The member key.
                var v = ''; // The member value.
                var length = 0;
                var mind = gap;
                var partial = [];
                var value = holder[key];

                // If the value has a toJSON method, call it to obtain a replacement value.
                if (value && typeof value === 'object' && typeof value.toJSON === 'function') {
                    value = value.toJSON(key);
                }

                // What happens next depends on the value's type.
                switch (typeof value) {
                case 'string':
                    return quote(value);

                case 'number':
                    // JSON numbers must be finite. Encode non-finite numbers as null.
                    return isFinite(value) ? String(value) : 'null';

                case 'boolean':
                case 'null':
                    // If the value is a boolean or null, convert it to a string. Note:
                    // typeof null does not produce 'null'. The case is included here in
                    // the remote chance that this gets fixed someday.
                    return String(value);

                case 'object':
                    // If the type is 'object', we might be dealing with an object or an array or
                    // null.
                    // Due to a specification blunder in ECMAScript, typeof null is 'object',
                    // so watch out for that case.
                    if (!value) {
                        return 'null';
                    }
                    if ((this.PHPJS_Resource && value instanceof this.PHPJS_Resource) || (window.PHPJS_Resource && value instanceof window.PHPJS_Resource)) {
                        throw new SyntaxError('json_encode');
                    }

                    // Make an array to hold the partial results of stringifying this object value.
                    gap += indent;
                    partial = [];

                    // Is the value an array?
                    if (Object.prototype.toString.apply(value) === '[object Array]') {
                        // The value is an array. Stringify every element. Use null as a placeholder
                        // for non-JSON values.
                        length = value.length;
                        for (i = 0; i < length; i += 1) {
                            partial[i] = str(i, value) || 'null';
                        }

                        // Join all of the elements together, separated with commas, and wrap them in
                        // brackets.
                        v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']';
                        gap = mind;
                        return v;
                    }

                    // Iterate through all of the keys in the object.
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }

                    // Join all of the member texts together, separated with commas,
                    // and wrap them in braces.
                    v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}';
                    gap = mind;
                    return v;
                case 'undefined':
                    // Fall-through
                case 'function':
                    // Fall-through
                default:
                    throw new SyntaxError('json_encode');
                }
            };

            // Make a fake root object containing our value under the key of ''.
            // Return the result of stringifying the value.
            return str('', {
                '': value
            });

        } catch (err) { // Todo: ensure error handling above throws a SyntaxError in all cases where it could
            // (i.e., when the JSON global is not available and there is an error)
            if (!(err instanceof SyntaxError)) {
                throw new Error('Unexpected error type in json_encode()');
            }
            this.php_js = this.php_js || {};
            this.php_js.last_error_json = 4; // usable by json_last_error()
            return null;
        }
    },

    chokeIE: null
}

$(document).ready(function(){
    uzEsOrderingCustom.init();
});

