var current_taxes = [];
var product_wholesale_gl = [];

/* getElementById caching */
function gebic(i) {
  return arguments.callee.$cache[i] || (arguments.callee.$cache[i] = document.getElementById(i))
}
gebic.$cache = {}

function check_options2(pid, opt_id, o_sel, id, color) {
	var id_select_size = 'display_after_choose_color_'+id;
	var id_select_size_disable = 'display_before_choose_color_'+id;
	var amount_select = 'amount_'+id;

    if (o_sel && -1 == o_sel.value && color == 'Y') {
        document.getElementById(id_select_size).style.display = 'none';
        document.getElementById(id_select_size_disable).style.display = '';
        document.getElementById(amount_select).disabled = true;
        return false;
    }
    if (o_sel && -1 == o_sel.value && color == 'N') {
        document.getElementById(amount_select).disabled = true;
        return false;
    }

    document.getElementById(id_select_size_disable).style.display = 'none';
	document.getElementById(id_select_size).style.display = '';

    if (check_options(pid, this, id)) {
        var _cached = gebic(opt_id);
        if(!_cached) return false;
        var val_am=_cached.value;
        check_wholesale(val_am, pid, 0);
    }
    return true;
}

/*
Rebuild page if some options is changed
*/
function check_options(pid, qty, id) {
    //var current_taxes = [];
    var product_thumbnail = gebic('product_thumbnail'+pid);
    var availObj = gebic('product_avail'+pid);
    var taxes = window['taxes'+pid];
    var default_price = window['default_price'+pid];
    var variants = window['variants'+pid];
    var modifiers = window['modifiers'+pid];
    var pconf_price = window['pconf_price'+pid];
    var orig_price = window['orig_price'+pid];
    var product_wholesale = window['product_wholesale'+pid];
    var _product_wholesale = window['_product_wholesale'+pid];
    var list_price = window['list_price'+pid];
    var taxes = window['taxes'+pid];
    var product_avail = window['product_avail'+pid];
    var avail = window['avail'+pid];
    var min_avail = window['min_avail'];

    var local_taxes = [];
    var is_rebuild_wholesale = false;
    var variantid = false;

    for (var t in taxes)
     local_taxes[t] = taxes[t][0];
    price = default_price;

    // Find variant
    for (var x in variants) {
        if ('object' != typeof(variants[x]) || undefined == variants[x].length || undefined == variants[x][1] || variants[x][1].length == 0)
        continue;

        variantid = x;
        for (var c in variants[x][1]) {
            var _pv = getPOValue(c)
            if (_pv != variants[x][1][c]) {
                if (-1 == _pv) {
                    return false;
                }
                variantid = false;
                break;
            }
        }

        if (variantid)
        break;
    }



    if (!variantid) return false;

    // If variant found ...
    if (variantid) {
        if (id && document.getElementById('amount_'+id).value == '0') {
                var id_el = id;

				if (document.getElementById('tr_'+id))
                	document.getElementById('tr_'+id).style.backgroundColor = "#ebebf1";
                if (document.getElementById('div_'+id))
                	document.getElementById('div_'+id).style.backgroundColor = "#ebebf1";

                if (document.getElementById('amount_'+id)) {
                	if (document.getElementById('amount_'+id).options[0])
	              		document.getElementById('amount_'+id).options[0].selected = false;

	              	if (document.getElementById('amount_'+id).options[1])
               			document.getElementById('amount_'+id).options[1].selected = true;
                }

        }

		if (document.getElementById('amount_'+id)) {
        	document.getElementById('amount_'+id).disabled = false;
        }

        price = variants[variantid][0][0];
        list_price = variants[variantid][0][6];
        product_list_price = variants[variantid][0][7];


        if(window.ActiveXObject) {
          if(variants[variantid][3]) {
            var qty_vars = variants[variantid][3];
            for (var t in qty_vars) {
              if(qty >= qty_vars[t][0])
                price = qty_vars[t][2]
            }
          }

          var _temp = gebic('product_price'+pid)
          if (_temp)
          _temp.innerHTML = currency_symbol + price_format(price);

if (list_price > 0) {
          var _temp1 = gebic('list_price'+pid)
          if (_temp1)
          _temp1.innerHTML = currency_symbol + price_format(list_price);
}
else {
          var _temp1 = gebic('list_price'+pid)
          if (_temp1)
          _temp1.innerHTML = currency_symbol + price_format(product_list_price);
}

//          return true;
        }
        orig_price = variants[variantid][0][4];
        avail = variants[variantid][0][1];


        // Get variant wholesale prices
        if (variants[variantid][3]) {
            product_wholesale = [];
            for (var t in variants[variantid][3]) {
                var _tmp = modi_price(variants[variantid][3][t][2], cloneObject(variants[variantid][3][t][3]), variants[variantid][3][t][4], pid);
                product_wholesale[t] = [variants[variantid][3][t][0], variants[variantid][3][t][1], _tmp[0], []];

                // Get variant wholesale taxes
                for (var c in _tmp[1]) {
                    product_wholesale[t][3][c] = _tmp[1][c];
                }
            }
            is_rebuild_wholesale = true;
        }

        // Get variant taxes
        for (var t in local_taxes) {
            if (variants[variantid][2][t])
            local_taxes[t] = parseFloat(variants[variantid][2][t]);
        }

        if (!product_thumbnail)
        product_thumbnail = gebic('product_thumbnail'+pid);

        // Change product thumbnail
        if (product_thumbnail) {
            if (variants[variantid][0][2].src && variants[variantid][0][2].width > 0 && variants[variantid][0][2].height > 0) {
                if (product_thumbnail.src != variants[variantid][0][2].src) {
                    product_thumbnail.src = variants[variantid][0][2].src;
                    product_thumbnail.width = variants[variantid][0][2].width;
                    product_thumbnail.height = variants[variantid][0][2].height;
                }
            } else if (gebic('product_thumbnail'+pid).src != product_image.src) {
                product_thumbnail.src = product_image.src;
                if (product_image.width > 0 && product_image.height > 0) {
                    product_thumbnail.width = product_image.width;
                    product_thumbnail.height = product_image.height;
                }
            }
        }

        // Change product weight
        if (gebic('product_weight'+pid))
        gebic('product_weight'+pid).innerHTML = variants[variantid][0][3];
        if (gebic('product_weight_box'+pid))
        gebic('product_weight_box'+pid).style.display = parseInt(variants[variantid][0][3]) > 0 ? "" : "none";

        // Change product code
        if (gebic('product_code'+pid))
        gebic('product_code'+pid).innerHTML = variants[variantid][0][5];

    }

    if (pconf_price > 0)
    price = pconf_price;

    /* Find modifiers */
    var _tmp = modi_price(price, local_taxes, orig_price, pid);
    price = _tmp[0];
    local_taxes = _tmp[1];
    if (!variantid) {
        product_wholesale = [];
        for (var t in _product_wholesale) {
            _tmp = modi_price(_product_wholesale[t][2], _product_wholesale[t][3], _product_wholesale[t][4], pid);
            product_wholesale[t] = [_product_wholesale[t][0], _product_wholesale[t][1], _tmp[0],_tmp[1]];
        }
        is_rebuild_wholesale = true;
    }
    /* Update taxes */
    for (var t in local_taxes) {
        if (gebic(pid+'tax_'+t)) {
            gebic(pid+'tax_'+t).innerHTML = currency_symbol+price_format(local_taxes[t]);
        }
        current_taxes[t] = local_taxes[t];
    }

    if (is_rebuild_wholesale)
      setTimeout(function(){ rebuild_wholesale(product_wholesale,pid) }, 500);

    product_wholesale_gl = product_wholesale;
    /* Update form elements */
    /* Update price */
    var _temp = gebic('product_price'+pid)
    if (_temp)
    _temp.innerHTML = currency_symbol+price_format(price);


if (list_price > 0) {
          var _temp1 = gebic('list_price'+pid)
          if (_temp1)
          _temp1.innerHTML = currency_symbol + price_format(list_price);
}
else {
          var _temp1 = gebic('list_price'+pid)
          if (_temp1)
          _temp1.innerHTML = currency_symbol + price_format(product_list_price);
}

    /* Update alt. price */
    var _temp = gebic('product_alt_price'+pid)
    if (alter_currency_rate > 0 && alter_currency_symbol != "" && _temp)
    _temp.innerHTML = " ("+alter_currency_symbol+" "+price_format(price*alter_currency_rate)+")";

    /* Update Save % */
    var _temp = gebic('save_percent'+pid);
    if (_temp /*&& gebic('save_percent_box'+pid) && list_price > 0 && dynamic_save_money_enabled*/) {
        var save_percent = Math.round(100-(price/list_price)*100);
        if (save_percent > 0) {
            _temp.innerHTML = save_percent;
        } else {
            _temp.innerHTML = '0';
        }
    }

    /* Update product quantity */
    if (gebic('product_avail_txt'+pid)) {
        if (avail > 0) {
            gebic('product_avail_txt'+pid).innerHTML = substitute(txt_items_available, "items", (variantid ? avail : product_avail));
        } else {
            gebic('product_avail_txt'+pid).innerHTML = lbl_no_items_available;
        }
    }

	var min_avail = 1;

    if ((mq > 0 && avail > mq+min_avail) || is_unlimit)
    avail = mq+min_avail-1;

    var select_avail = min_avail;
    /* Update product quantity selector */
    if (!availObj)
    	availObj = gebic('amount_'+id);

    if (availObj && availObj.tagName.toUpperCase() == 'SELECT') {
        if (!isNaN(min_avail) && !isNaN(avail)) {
            var first_value = -1;
            if (availObj.options[0])
            first_value = availObj.options[0].value;

            if (first_value == min_avail) {

                /* New and old first value in quantities list is equal */
                if ((avail-min_avail) != availObj.options.length) {
                    if (availObj.options.length > avail-min_avail) {
                        var cnt = availObj.options.length;
                        for (var x = avail-min_avail; x < cnt-1; x++)
                        availObj.options[availObj.options.length-1] = null;
                    } else {
                        var cnt = availObj.options.length;
                        for (var x = cnt+min_avail; x <= avail; x++)
                        availObj.options[cnt++] = new Option(x, x);
                    }
                }
            } else {

                /* New and old first value in quantities list is differ */
                while (availObj.options.length > 0)
                availObj.options[0] = null;
                var cnt = 0;
                for (var x = min_avail; x <= avail; x++)
                availObj.options[cnt++] = new Option(x, x);
            }

            if (availObj.options.length == 0) {
            	availObj.options[0] = new Option(txt_out_of_stock, 0);
				if (document.getElementById('tr_'+id))
                	document.getElementById('tr_'+id).style.backgroundColor = "#ffffff";
                if (document.getElementById('div_'+id))
                	document.getElementById('div_'+id).style.backgroundColor = "#ffffff";
            }
        }
        select_avail = availObj.options[availObj.selectedIndex].value;
    }

    check_wholesale(select_avail,pid,1);

    if ((alert_msg == 'Y') && (min_avail > avail))
    alert(txt_out_of_stock);

    /* Check exceptions */
    var ex_flag = check_exceptions(pid);
    if (!ex_flag && (alert_msg == 'Y'))
    alert(exception_msg);

    if (gebic('exception_msg'+pid))
    gebic('exception_msg'+pid).innerHTML = (ex_flag ? '' : exception_msg_html+"<br /><br />");

    return true;
}

/*
Calculate product price with price modificators
*/
function modi_price(_price, _taxes, _orig_price,pid) {
    var return_price = round(_price, 2);
    var modifiers = window['modifiers'+pid];

    /* List modificators */
    for (var x2 in modifiers) {
        var value = getPOValue(x2);
        if (!value || !modifiers[x2][value])
        continue;

        /* Get selected option */
        var elm = modifiers[x2][value];
        return_price += parseFloat(elm[1] == '$' ? elm[0] : (_price*elm[0]/100));

        /* Get tax extra charge */
        for (var t2 in _taxes) {
            if (elm[2][t2]) {
                _taxes[t2] += (elm[1] == '$' ? elm[2][t2] : (_orig_price*elm[2][t2]/100));
            }
        }
    }

    return [return_price, _taxes];
}

/*
Check product options exceptions
*/
function check_exceptions(pid) {
    var exceptions = window['exceptions'+pid];
    if (!exceptions)
    return true;

    /* List exceptions */
    for (var x in exceptions) {
        if (isNaN(x))
        continue;

        var found = true;
        for (var c in exceptions[x]) {
            var value = getPOValue(c);
            if (!value)
            return true;

            if (value != exceptions[x][c]) {
                found = false;
                break;
            }
        }
        if (found)
        return false;
    }

    return true;
}

/*
Rebuild wholesale tables
*/
function rebuild_wholesale(product_wholesale,pid) {
    var taxes = window['taxes'+pid];
    var obj = gebic('wl_table'+pid);
    var td_obj = gebic('wl_td'+pid);
    if (!obj) {
        return false;
    }
    /* Clear wholesale span object if product wholesale prices service array is empty */
    if (!product_wholesale || product_wholesale.length == 0) {
        obj.innerHTML = "";
        td_obj.style.display='none';
        return false;
    }
    else { td_obj.style.display=''; }

    /* Display headline */
    var str = '<table cellpadding="2" cellspacing="2"><tr class="TableHead"><td align="right"><b>'+lbl_quantity+':&nbsp;</b></td>';
    for (var x in product_wholesale) {
        if (product_wholesale[x][0] == 0)
        continue;
        str += '<td>'+product_wholesale[x][0];
        if (x == product_wholesale.length-1)
        str +='+';
        else if (product_wholesale[x][0] > product_wholesale[x][1]+1)
        str += '-'+(product_wholesale[x][1]-1);
        str += '&nbsp;'+(product_wholesale[x][0] == 1 ? lbl_item : lbl_items)+'</td>';
    }

    /* Display wholesale prices taxes */
    var tax_str = '';
    if (taxes.length > 0) {
        for (var x in taxes) {
            if (current_taxes[x] > 0)
            tax_str += substitute(lbl_including_tax, 'tax', taxes[x][1])+'<br />';
        }
    }

    /* Display wholesale prices */
    str += '</tr><tr bgcolor="#EEEEEE"><td align="right"><b>'+lbl_price+(tax_str.length > 0 ? '*' : '')+':&nbsp;</b></td>';
    for (var x in product_wholesale) {
        if (product_wholesale[x][0] == 0)
        continue;
        str += '<td>'+price_format(product_wholesale[x][2])+'</td>';
    }

    str += '</tr></table>';

    if (tax_str.length > 0)
    str += '<br /><table><tr><td class="FormButton" valign="top"><b>*'+txt_note+':</b>&nbsp;</td><td nowrap="nowrap" valign="top">'+tax_str+'</td></tr></table>';

    obj.innerHTML = str;

    return true;
}

/*
Display current wholesale price as product price
*/
function check_wholesale(qty,pid,no_recurs) {

    if (no_recurs == 0) { check_options(pid, qty); }

    var product_wholesale = product_wholesale_gl;
    var taxes = window['taxes'+pid];

    if (product_wholesale.length == 0) return true;

    var wl_taxes = current_taxes.slice(0);
    var wl_price = price;
    var found = false;

    for (var x = 0,len=product_wholesale.length; x < len; x++) {
        if (product_wholesale[x][0] <= qty && (product_wholesale[x][1] >= qty || product_wholesale[x][1] == 0)) {
            wl_price = product_wholesale[x][2];
            wl_taxes = product_wholesale[x][3].slice(0);
            found = true;
        }
        var _tmp = gebic(pid+'wp'+x)
        if (_tmp)
          _tmp.innerHTML = currency_symbol+price_format(price-default_price+product_wholesale[x][2]);
    }

    var _ppp = gebic('product_price'+pid)
    if (_ppp)
    _ppp.innerHTML = currency_symbol+price_format(wl_price);

    var _papp = gebic('product_alt_price'+pid)
    if (alter_currency_rate > 0 && alter_currency_symbol != "" && _papp)
    _papp.innerHTML = " ("+alter_currency_symbol+" "+price_format((wl_price)*alter_currency_rate)+")";

    for (var x in taxes) {
        var _cached = gebic(pid+'tax_'+x)
        if (_cached && wl_taxes[x] && current_taxes[x]) {
            _cached.innerHTML = currency_symbol+price_format(wl_taxes[x]);
        }
    }

    return true;
}

/*
Get product option value
*/
function getPOValue(c) {
    var _cached = gebic('po'+c);
    if (!_cached || _cached.tagName.toUpperCase() != 'SELECT')
    return false;
    return _cached.options[_cached.selectedIndex].value;
}

/*
Get product option object by class name / class id
*/
function product_option(classid) {
    if (!isNaN(classid))
    return gebic("po"+classid);

    if (!names)
    return false;

    for (var x in names) {
        if (names[x]['class_name'] != classid)
        continue;
        return gebic('po'+x);
    }

    return false;
}

/*
Get product option value by class name / or class id
*/
function product_option_value(classid) {
    var obj = product_option(classid);
    if (!obj)
    return false;

    if (obj.type != 'select-one')
    return obj.value;

    var classid = parseInt(obj.id.substr(2));
    var optionid = parseInt(obj.options[obj.selectedIndex].value);
    if (names[classid] && names[classid]['options'][optionid])
    return names[classid]['options'][optionid];

    return false;
}


