// $Id: func.js,v 1.16.2.15 2007/01/05 08:06:25 max Exp $

var current_taxes = [];
var product_thumbnail = [];
var availObj = [];
var alert_msg = [];

var pconf_price = [];
var default_price = [];
var list_price = [];
var price = [];
var orig_price = [];

var wl_taxes = [];
var wl_price = [];
var local_taxes = [];

var variants = [];
var modifiers = [];
var names = [];
var taxes = [];
var exceptions = [];
var product_wholesale = [];
var _product_wholesale = [];
var product_image = [];
var product_color_selector = [];
//current_taxes[productid] = [];
//var product_thumbnail[productid] = document.getElementById('product_thumbnail');
//var availObj = document.getElementById('product_avail');

/*
	Rebuild page if some options is changed
*/
function make_color_selection(obj, productid, classid) {
	for(var i in product_color_selector[productid][classid]) {
			var colorObj = document.getElementById('product_color_selector_'+productid+classid+product_color_selector[productid][classid][i]);
			var tdObj = document.getElementById('product_color_selector_td_element_'+productid+classid+product_color_selector[productid][classid][i]);
			

			if (colorObj)
				colorObj.className = 'not_selected_color';

			if (tdObj && colorObj == obj)
                tdObj.className = 'td_selected_color';
			else if (tdObj) {
				tdObj.className = 'td_not_selected_color';
			}
	}

	if (obj)
		obj.className = 'selected_color';
}

function check_options(productid) {
	var is_rebuild_wholesale = false;
	var variantid = false;

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

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

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

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

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

				/* Get variant wholesale taxes */
				for (var c in _tmp[1]) {
					product_wholesale[productid][t][3][c] = _tmp[1][c];
				}
			}
			is_rebuild_wholesale = true;
		}
		
		/* Get variant taxes */
		for (var t in local_taxes[productid]) {
			if (variants[productid][variantid][2][t])
				local_taxes[productid][t] = parseFloat(variants[productid][variantid][2][t]);
		}

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

		/* Change product weight */
		if (document.getElementById('product_weight'+productid))
			document.getElementById('product_weight'+productid).innerHTML = price_format(variants[productid][variantid][0][3]);
		if (document.getElementById('product_weight_box'+productid))
			document.getElementById('product_weight_box'+productid).style.display = parseFloat(variants[productid][variantid][0][3]) > 0 ? "" : "none";

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

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

	/* Update taxes */
	for (var t in local_taxes[productid]) {
		if (document.getElementById('tax_'+t+productid)) {
			document.getElementById('tax_'+t+productid).innerHTML = currency_symbol+price_format(local_taxes[productid][t] < 0 ? 0 : local_taxes[productid][t]);
		}
		if (!current_taxes[productid])
			current_taxes[productid] = [];
		current_taxes[productid][t] = local_taxes[productid][t];
	}

	if (is_rebuild_wholesale)
		rebuild_wholesale(productid);
	
	/* Update form elements */
	/* Update price */
	if (document.getElementById('product_price'+productid))
		document.getElementById('product_price'+productid).innerHTML = currency_symbol+price_format(price[productid] < 0 ? 0 : price[productid]);

	/* Update alt. price */
	if (alter_currency_rate > 0 && alter_currency_symbol != "" && document.getElementById('product_alt_price'+productid)) {
		var altPrice = price[productid]*alter_currency_rate;
		document.getElementById('product_alt_price'+productid).innerHTML = "("+alter_currency_symbol+" "+price_format(altPrice < 0 ? 0 : altPrice)+")";
	}

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

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

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

	var select_avail = eval('min_avail'+productid);
	/* Update product quantity selector */
	if (!availObj[productid])
		availObj[productid] = document.getElementById('product_avail'+productid);

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

			if (first_value == eval('min_avail'+productid)) {

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

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

	check_wholesale(select_avail, productid);

	if ((alert_msg[productid] == 'Y') && (eval('min_avail'+productid) > eval('avail'+productid)))
		alert(txt_out_of_stock);
	
	/* Check exceptions */
	var ex_flag = check_exceptions();
	if (!ex_flag && (alert_msg[productid] == 'Y'))
		alert(exception_msg);
			
	if (document.getElementById('exception_msg'+productid))
		document.getElementById('exception_msg'+productid).innerHTML = (ex_flag ? '' : exception_msg_html+"<br /><br />");

	return true;
}

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

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

		/* Get selected option */
		var elm = modifiers[productid][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(productid) {
	if (!exceptions[productid])
		return true;

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

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

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

	return true;
}

/*
	Rebuild wholesale tables
*/
function rebuild_wholesale(productid) {

	var obj = document.getElementById('wl_table'+productid);
	if (!obj)
		return false;
	
	/* Clear wholesale span object if product wholesale prices service array is empty */
	if (!product_wholesale[productid] || product_wholesale[productid].length == 0) {
		obj.innerHTML = "";
		return false;
	}

	/* Display headline */
	var str = '';
	var i = 0;
	for (var x in product_wholesale[productid]) {
		if (product_wholesale[productid][x][0] == 0)
			continue;

		if (i == 0)
			str += '<br /><table cellpadding="2" cellspacing="2"><tr class="TableHead"><td align="right"><b>'+lbl_quantity+':&nbsp;</b></td>';

		str += '<td>'+product_wholesale[productid][x][0];
		if (x == product_wholesale.length-1) {
			str += '+';
		} else if (product_wholesale[productid][x][0] < product_wholesale[productid][x][1]) {
			str += '-'+product_wholesale[productid][x][1];
		}
		str += '&nbsp;'+(product_wholesale[productid][x][0] == 1 ? lbl_item : lbl_items)+'</td>';
		i++;
	}

	if (i == 0)
		return false;

    /* Display wholesale prices taxes */
	var tax_str = '';
    if (taxes[productid].length > 0) {
        for (var x in taxes[productid]) {
            if (current_taxes[productid][x] > 0)
                tax_str += substitute(lbl_including_tax, 'tax', taxes[productid][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[productid]) {
		if (product_wholesale[productid][x][0] == 0)
			continue;
		str += '<td>'+price_format(product_wholesale[productid][x][2] < 0 ? 0 : product_wholesale[productid][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>';

	str += '<br />';
	obj.innerHTML = str;

	return true;
}

/*
	Display current wholesale price as product price
*/
function check_wholesale(qty, productid) {
	if (!product_wholesale[productid])
		return true;

	if (product_wholesale[productid].length == 0)
		return true;
	
	wl_taxes[productid] = current_taxes[productid].slice(0);
	wl_price[productid] = price[productid];
	var found = false;
	for (var x = 0; x < product_wholesale[productid].length; x++) {
		if (product_wholesale[productid][x][0] <= qty && (product_wholesale[productid][x][1] >= qty || product_wholesale[productid][x][1] == 0)) {
			wl_price[productid] = product_wholesale[productid][x][2];
			wl_taxes[productid] = product_wholesale[productid][x][3].slice(0);
			found = true;
		}
		if (document.getElementById('wp'+x+productid)) {
			var wPrice = price[productid]-default_price[productid]+product_wholesale[productid][x][2];
			document.getElementById('wp'+x+productid).innerHTML = currency_symbol+price_format(wPrice < 0 ? 0 : wPrice);
		}
	}
	
	if (document.getElementById('product_price'+productid))
		document.getElementById('product_price'+productid).innerHTML = currency_symbol+price_format(wl_price[productid] < 0 ? 0 : wl_price[productid]);
	
	if (alter_currency_rate > 0 && alter_currency_symbol != "" && document.getElementById('product_alt_price'+productid)) {
		var altPrice = wl_price[productid]*alter_currency_rate;
		document.getElementById('product_alt_price'+productid).innerHTML = "("+alter_currency_symbol+" "+price_format(altPrice < 0 ? 0 : altPrice)+")";
	}

	/* Update Save % */
	if (document.getElementById('save_percent'+productid) && document.getElementById('save_percent_box'+productid) && list_price[productid] > 0 && dynamic_save_money_enabled) {
		var save_percent = Math.round(100-((wl_price[productid] < 0 ? 0 : wl_price[productid])/list_price[productid])*100);
		if (save_percent > 0) {
			document.getElementById('save_percent_box'+productid).style.display = '';
			document.getElementById('save_percent'+productid).innerHTML = save_percent;
		} else {
			document.getElementById('save_percent_box'+productid).style.display = 'none';
			document.getElementById('save_percent'+productid).innerHTML = '0';
		}
	}


	for (var x in taxes[productid]) {
		if (document.getElementById('tax_'+x+productid) && wl_taxes[productid][x] && current_taxes[productid][x]) {
			document.getElementById('tax_'+x+productid).innerHTML = currency_symbol+price_format(wl_taxes[productid][x] < 0 ? 0 : wl_taxes[productid][x]);
		}
	}

	return true;
}

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

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

	if (!names[productid])
		return false;

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

	return false;
}

/*
	Get product option value by class name / or class id
*/
function product_option_value(classid, productid) {
	var obj = product_option(classid, productid);
	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[productid][classid] && names[productid][classid]['options'][optionid])
		return names[productid][classid]['options'][optionid];

	return false;
}


