/*
$Id: func_list.js,v 1.32 2009/03/26 12:36:23 valentinka Exp $
*/

/*
	Rebuild page if some options is changed
*/
function check_options_list(pid) {
	var local_taxes = [];
	var is_rebuild_wholesale = false;
	var variantid = false;
	
	if (taxes[pid]) {
	for (var t in taxes[pid])
		local_taxes[t] = taxes[pid][t][0];
	}	
	price[pid] = default_price[pid];

	/* Find variant */
	for (var x in variants[pid]) {
		if (variants[pid][x][1].length == 0)
			continue;

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

		if (variantid)
			break;
	}
	
	/* If variant found ... */
	if (variantid) {
		price[pid] = variants[pid][variantid][0][0];
		orig_price[pid] = variants[pid][variantid][0][4];
		avail[pid] = variants[pid][variantid][0][1];

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

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

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

		if (!product_thumbnail[pid])
			product_thumbnail[pid] = document.getElementById('product_thumbnail_'+pid);

		/* Change product thumbnail */
		if (product_thumbnail[pid]) {
			if (variants[pid][variantid][0][2].src && variants[pid][variantid][0][2].width > 0 && variants[pid][variantid][0][2].height > 0) {
				if (getImgSrc(product_thumbnail[pid]) != variants[pid][variantid][0][2].src) {

					product_thumbnail[pid].src = variants[pid][variantid][0][2].src;
					product_thumbnail[pid].width = variants[pid][variantid][0][2]._x;
					product_thumbnail[pid].height = variants[pid][variantid][0][2]._y;
					if (typeof(window.saved_product_thumbnail) != 'undefined' && saved_product_thumbnail)
						saved_product_thumbnail = false;

					if (variants[pid][variantid][0][6] && $.browser.msie)
						pngFix(product_thumbnail[pid]);
				}

			}
			else if (getImgSrc(product_thumbnail[pid]) != default_tmbn[pid].src) {
				product_thumbnail[pid].src = default_tmbn[pid].src;
				if (default_tmbn[pid].width > 0 && default_tmbn[pid].height > 0) {
					product_thumbnail[pid].width = default_tmbn[pid].width;
					product_thumbnail[pid].height = default_tmbn[pid].height;
					if (typeof(window.saved_product_thumbnail) != 'undefined' && saved_product_thumbnail)
						saved_product_thumbnail = false;
				}

				if (default_tmbn[pid].isPNG)
					pngFix(product_thumbnail[pid]);
			}
		}

		/* Change product weight */
		if (document.getElementById('product_weight_'+pid))
			document.getElementById('product_weight_'+pid).innerHTML = price_format(variants[pid][variantid][0][3]);

		if (document.getElementById('product_weight_box_'+pid))
			document.getElementById('product_weight_box_'+pid).style.display = parseFloat(variants[pid][variantid][0][3]) > 0 ? "" : "none";

		/* Change product code */
		if (document.getElementById('product_code_'+pid))
			document.getElementById('product_code_'+pid).innerHTML = variants[pid][variantid][0][5];

	}

	if (pconf_price[pid] > 0)
		price[pid] = pconf_price[pid];

	/* Find modifiers */
	var _tmp = modi_price_list(pid, price[pid], local_taxes, orig_price[pid]);
	price[pid] = _tmp[0];
	local_taxes = _tmp[1];
	if (!variantid) {
		product_wholesale[pid] = [];
		for (var t in _product_wholesale[pid]) {
			_tmp = modi_price_list(pid, _product_wholesale[pid][t][2], _product_wholesale[pid][t][3].slice(0), _product_wholesale[pid][t][4]);
			product_wholesale[pid][t] = [
				_product_wholesale[pid][t][0],
				_product_wholesale[pid][t][1],
				_tmp[0],
				_tmp[1]
			];
		}
		is_rebuild_wholesale = true;
	}

	/* Update taxes */
	for (var t in local_taxes) {
		if (document.getElementById('tax_'+pid+'_'+t)) {
			document.getElementById('tax_'+pid+'_'+t).innerHTML = price_format(Math.max(local_taxes[t], 0));
		}
		current_taxes[pid][t] = local_taxes[t];
	}

	if (is_rebuild_wholesale)
		rebuild_wholesale_list(pid);

	/* Update form elements */
	/* Update price */
	if (document.getElementById('product_price_'+pid))
		document.getElementById('product_price_'+pid).innerHTML = price_format(Math.max(price[pid], 0));

	/* Update alt. price */
	if (alter_currency_rate > 0 && document.getElementById('product_alt_price_'+pid)) {
		var altPrice = price[pid]*alter_currency_rate;
		document.getElementById('product_alt_price_'+pid).innerHTML = price_format(Math.max(altPrice, 0));
	}

	/* Update Save % */
	if (document.getElementById('save_percent_'+pid) && document.getElementById('save_percent_box_'+pid) && list_price[pid] > 0 && dynamic_save_money_enabled) {
		var save_percent = Math.round(100 - (price[pid] / list_price[pid]) * 100);
		if (save_percent > 0) {
			document.getElementById('save_percent_box_'+pid).style.display = '';
			document.getElementById('save_percent_'+pid).innerHTML = save_percent;

		} else {
			document.getElementById('save_percent_box_'+pid).style.display = 'none';
			document.getElementById('save_percent_'+pid).innerHTML = '0';
		}
	}

	/* Update product quantity */
	if (document.getElementById('product_avail_txt_'+pid)) {
		document.getElementById('product_avail_txt_'+pid).innerHTML = avail[pid] > 0 ? substitute(txt_items_available, "items", (variantid ? avail[pid] : product_avail[pid])) : lbl_no_items_available;
	}

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

	avail[pid] = Math.min(mq, avail[pid]);

	var select_avail = min_avail[pid];
	/* Update product quantity selector */
	if (!availObj[pid])
		availObj[pid] = document.getElementById('product_avail_'+pid);
	
	if (availObj[pid] && availObj[pid].tagName.toUpperCase() == 'SELECT') {

		// Select box
		if (!isNaN(min_avail[pid]) && !isNaN(avail[pid])) {
			var first_value = -1;
			if (availObj[pid].options[0])
				first_value = availObj[pid].options[0].value;

			if (first_value == min_avail[pid]) {

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

					} else {
						var cnt = availObj[pid].options.length;
						for (var x = cnt+1; x <= avail[pid]; x++)
							availObj[pid].options[cnt++] = new Option(x, x);
					}
				}
			} else {

				/* New and old first value in quantities list is differ */
				var cnt = availObj[pid].options.length - 1;
				while (cnt >= 0)
					availObj[pid].options[cnt--] = null;

				cnt = 0;
				for (var x = min_avail[pid]; x <= avail[pid]; x++)
					availObj[pid].options[cnt++] = new Option(x, x);
			}
			if (availObj[pid].options.length == 0 || min_avail[pid] > avail[pid])
				availObj[pid].options[0] = new Option(txt_out_of_stock, 0);
		}
		select_avail = availObj[pid].options[availObj[pid].selectedIndex].value;

	} else if (availObj[pid] && availObj[pid].tagName.toUpperCase() == 'INPUT' && availObj[pid].type.toUpperCase() == 'TEXT') {

		// Input box
        if (!isNaN(min_avail[pid]) && !isNaN(avail[pid])) {
			availObj[pid].minQuantity = min_avail[pid];
			availObj[pid].maxQuantity = avail[pid];
		}
        select_avail = availObj[pid].value;
	}

	check_wholesale_list(pid, select_avail);

	if ((alert_msg == 'Y') && (min_avail[pid] > avail[pid]))
		alert(txt_out_of_stock);
	
	/* Check exceptions */
	var ex_flag = check_exceptions_list(pid);
	if (!ex_flag && (alert_msg == 'Y'))
		alert(exception_msg);
	
	if (document.getElementById('exception_msg_'+pid)) {
		if (ex_flag) {
			document.getElementById('exception_msg_'+pid).style.display = 'none';

		} else {
			document.getElementById('exception_msg_'+pid).innerHTML = exception_msg_html;
			document.getElementById('exception_msg_'+pid).style.display = '';
		}
	}

	return true;
}

/*
	Calculate product price with price modificators 
*/
function modi_price_list(pid, _price, _taxes, _orig_price) {
	var return_price = round(_price, 2);

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

		/* Get selected option */
		var elm = modifiers[pid][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] += parseFloat(elm[1] == '$' ? elm[2][t2] : (_orig_price*elm[2][t2]/100));
			}
		}
	}

	return [return_price, _taxes];
}

/*
	Check product options exceptions
*/
function check_exceptions_list(pid) {
	if (!exceptions[pid])
		return true;

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

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

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

	return true;
}

/*
	Rebuild wholesale tables
*/
function rebuild_wholesale_list(pid) {
	var div = document.getElementById('wl-prices_'+pid);
	var wl_table = $('table', div).get(0);
	var wl_taxes = $('div', div).get(0);

	if (!div || !wl_table || !wl_taxes)
		return false;

	/* Clear wholesale span object if product wholesale prices service array is empty */
	var i = wl_table.rows.length - 1;
	while (i > 0)
		wl_table.deleteRow(i--);

	if (!product_wholesale[pid] || product_wholesale[pid].length == 0) {
		div.style.display = 'none';
		return false;
	}

	/* Display wholesale prices table */
	var str = '';
	var r;
	for (i in product_wholesale[pid]) {
		if (product_wholesale[pid][i][0] == 0)
			continue;

		r = wl_table.insertRow(-1);
		r.insertCell(-1).innerHTML = product_wholesale[pid][i][0] + '+&nbsp;' + (product_wholesale[pid][i][0] == 1 ? lbl_item : lbl_items);
		r.insertCell(-1).innerHTML = price_format(product_wholesale[pid][i][2] < 0 ? 0 : product_wholesale[pid][i][2], false, false, false, true);
	}

	if (wl_table.rows.length <= 1) {
        div.style.display = 'none';
		return false;
	}

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

	if (tax_str.length > 0) {
		for (i = wl_taxes.childNodes.length - 1; (i >= 0 && wl_taxes.childNodes[i].nodeType == 3); i--)
			wl_taxes.removeChild(wl_taxes.childNodes[i]);

		wl_taxes.appendChild(document.createTextNode(tax_str));
		wl_taxes.style.display = '';

	} else {
		wl_taxes.style.display = 'none';
	}

    div.style.display = '';

	return true;
}

/*
	Display current wholesale price as product price
*/
function check_wholesale_list(pid, qty) {
	if (product_wholesale.length == 0)
		return true;

	var wl_taxes = current_taxes[pid].slice(0);
	var wl_price = price[pid];
	var found = false;
	for (var x = 0; x < product_wholesale[pid].length; x++) {
		if (product_wholesale[pid][x][0] <= qty && (product_wholesale[pid][x][1] >= qty || product_wholesale[pid][x][1] == 0)) {
			wl_price = product_wholesale[pid][x][2];
			wl_taxes = product_wholesale[pid][x][3].slice(0);
			found = true;
		}

		if (document.getElementById('wp_'+pid+'_'+ x)) {
			var wPrice = price-default_price+product_wholesale[x][2];
			document.getElementById('wp_'+pid+'_'+ x).innerHTML = price_format(Math.max(wPrice, 0));
		}
	}

	if (document.getElementById('product_price_'+pid))
		document.getElementById('product_price_'+pid).innerHTML = price_format(Math.max(wl_price, 0));

	if (alter_currency_rate > 0 && document.getElementById('product_alt_price_'+pid)) {
		document.getElementById('product_alt_price_'+pid).innerHTML = price_format(Math.max(wl_price * alter_currency_rate, 0));
	}

	/* Update Save % */
	if (document.getElementById('save_percent_'+pid) && document.getElementById('save_percent_box_'+pid) && list_price[pid] > 0 && dynamic_save_money_enabled) {
		var save_percent = Math.round(100 - (Math.max(wl_price, 0) / list_price[pid]) * 100);
		if (save_percent > 0) {
			document.getElementById('save_percent_box_'+pid).style.display = '';
			document.getElementById('save_percent_'+pid).innerHTML = save_percent;

		} else {
			document.getElementById('save_percent_box_'+pid).style.display = 'none';
			document.getElementById('save_percent_'+pid).innerHTML = '0';
		}
	}


	for (var x in taxes[pid]) {
		if (document.getElementById('tax_'+pid+'_'+x) && wl_taxes[x] && current_taxes[pid][x]) {
			document.getElementById('tax_'+pid+'_'+x).innerHTML = price_format(Math.max(wl_taxes[x], 0));
		}
	}

	return true;
}

/*
	Get product option value
*/
function getPOValue(pid, c) {
	if (!document.getElementById('po' + pid + c) || document.getElementById('po' + pid + c).tagName.toUpperCase() != 'SELECT')
		return false;

	return document.getElementById('po' + pid + c).options[document.getElementById('po' + pid + c).selectedIndex].value;
}

function FormValidationList(pid) {
	
	if (variants[pid] || modifiers[pid]) {
		if (!check_exceptions_list(pid)) {
			alert(exception_msg);
			return false;
		}

		if (product_options_js[pid]) {
			var str = product_options_js[pid].toString();
			eval(str);
		}
	}

	if (document.getElementById('product_avail_'+pid)) {
		if (document.getElementById('product_avail_'+pid).value == 0) {
			alert(txt_out_of_stock);
			return false;
		}
	}

	return true;
}
