/*
$Id: func.js,v 1.32.2.4 2009/04/03 12:47:49 avg Exp $
*/

var current_taxes = [];
var product_thumbnail = document.getElementById('product_thumbnail');
if (document.getElementById('product_avail')) {
var availObj = document.getElementById('product_avail');
}

/*
	Rebuild page if some options is changed
*/
function check_options() {
	var local_taxes = [];
	var is_rebuild_wholesale = false;
	var variantid = false;
    //alert( document.getElementById('product_avail').value);
	for (var t in taxes)
		local_taxes[t] = taxes[t][0];
	price = default_price;

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

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

		if (variantid)
			break;
	}

	if (availObj && availObj.tagName.toUpperCase() == 'SELECT') {
		var select_avail_ = availObj.options[availObj.selectedIndex].value;
	} else if (availObj && availObj.tagName.toUpperCase() == 'INPUT' && availObj.type.toUpperCase() == 'TEXT') {
		var select_avail_ = availObj.value;
	} else {
		var select_avail_ = 1.00;
	}

	/* If variant found ... */
	if (variantid) {
		var variant_true_cost_type = 'F';
		if (variants[variantid][0][6] == 'S' && document.getElementById('po'+width_elm_id) && document.getElementById('po'+height_elm_id)) {
			/* Cost type 'S'(Sq. meters)-price formula: height*width*variant_price. Height/Width fields are required */
			var width = Math.abs(parseFloat(document.getElementById('po'+width_elm_id).value));
			var height = Math.abs(parseFloat(document.getElementById('po'+height_elm_id).value));
			width = (width == 0) ? 1.00 : width;
			height = (height == 0) ? 1.00 : height;
			/* Height/Width in cm by default */
			price = round(width*height*variants[variantid][0][0]/100/100, 2);
			variant_true_cost_type = 'S';

		} else {
		price = variants[variantid][0][0];
		}
//		hw = variants[variantid][0][6];
		cost_type = variants[variantid][0][6];
		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]) {
				if (variant_true_cost_type == 'S') {
					/* Cost type 'S', Height/Width fields are exists */
					var var_wh_prc = round(width*height*variants[variantid][3][t][2]/100/100, 2);
				} else {
					var var_wh_prc = variants[variantid][3][t][2];
				}
				var _tmp = modi_price(var_wh_prc, cloneObject(variants[variantid][3][t][3]), variants[variantid][3][t][4]);
				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] && variant_true_cost_type == 'S') {
				local_taxes[t] = parseFloat(width*height*variants[variantid][2][t]/100/100);
			} else if (variants[variantid][2][t]) {
				local_taxes[t] = parseFloat(variants[variantid][2][t]);
		}
		}

		if (!product_thumbnail)
			product_thumbnail = document.getElementById('product_thumbnail');

		/* 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 (getImgSrc(product_thumbnail) != variants[variantid][0][2].src) {

					if (getImgSrc(product_thumbnail) == product_image.src && typeof(product_image.isPNG) == 'undefined') {
						product_image.isPNG = isPngFix(product_thumbnail);
						product_image.width = product_thumbnail.width;
						product_image.height = product_thumbnail.height;
					}

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

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

			} else if (getImgSrc(product_thumbnail) != 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;
					if (typeof(window.saved_product_thumbnail) != 'undefined' && saved_product_thumbnail)
						saved_product_thumbnail = false;
				}

				if (product_image.isPNG)
					pngFix(product_thumbnail);
			}

			if (max_image_width > 0 && product_thumbnail.width > max_image_width) {
				product_thumbnail.height = Math.round(product_thumbnail.height*max_image_width/product_thumbnail.width);
				product_thumbnail.width = max_image_width;
			}
			if (max_image_height > 0 && product_thumbnail.height > max_image_height) {
				product_thumbnail.width = Math.round(product_thumbnail.width*max_image_height/product_thumbnail.height);
				product_thumbnail.height = max_image_height;
			}
		}

		/* Change product weight */

		/* Weight correction for the variants with cost type 'S' */ 
		if (document.getElementById('product_weight') && variant_true_cost_type == 'S') {
			document.getElementById('product_weight').innerHTML = price_format(width/100*height/100*variants[variantid][0][3]*select_avail_);
		} else if (document.getElementById('product_weight')) {
			document.getElementById('product_weight').innerHTML = price_format(variants[variantid][0][3]*select_avail_);
		}

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

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

	}

	if (pconf_price > 0)
		price = pconf_price;

/*		if (document.getElementById('product_avail')) {
        var qty = document.getElementById('product_avail').value;
		}*/
	/* Find modifiers */
	var _tmp = modi_price(price, local_taxes, orig_price);
//	var _tmp = modi_price(price, local_taxes, orig_price, qty);
	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].slice(0), _product_wholesale[t][4]);
//			_tmp = modi_price(_product_wholesale[t][2], _product_wholesale[t][3].slice(0), _product_wholesale[t][4], qty);
			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 (document.getElementById('tax_'+t)) {
			document.getElementById('tax_'+t).innerHTML = price_format(Math.max(local_taxes[t]*select_avail_, 0));
		}
		current_taxes[t] = local_taxes[t];
	}

	if (is_rebuild_wholesale)
		rebuild_wholesale();

	/* Update form elements */
	/* Update price */
	if (document.getElementById('product_price'))
		document.getElementById('product_price').innerHTML = price_format(Math.max(price*select_avail_, 0));

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

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

		} else {
			document.getElementById('save_percent_box').style.display = 'none';
			document.getElementById('save_percent').innerHTML = '0';
		}
	}

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

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

	avail = Math.min(mq, avail);

	var select_avail = min_avail;
	/* Update product quantity selector */
	if (!availObj)
		if (document.getElementById('product_avail')) {
		availObj = document.getElementById('product_avail');
		}

	if (availObj && availObj.tagName.toUpperCase() == 'SELECT') {

		// Select box
		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+1) != availObj.options.length) {
					if (availObj.options.length > avail-min_avail+1) {
						var cnt = availObj.options.length;
						for (var x = (avail-min_avail+1 < 0 ? 0 : avail-min_avail+1); x < cnt; x++)
							availObj.options[availObj.options.length-1] = null;

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

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

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

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

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

	check_wholesale(select_avail);

	if ((alert_msg == 'Y') && (min_avail > avail))
		alert(txt_out_of_stock);
	
	/* Check exceptions */
	var ex_flag = check_exceptions();
	if (!ex_flag && (alert_msg == 'Y'))
		alert(exception_msg);

	if (document.getElementById('exception_msg')) {
		if (ex_flag) {
			document.getElementById('exception_msg').style.display = 'none';

		} else {
			document.getElementById('exception_msg').innerHTML = exception_msg_html;
			document.getElementById('exception_msg').style.display = '';
		}
	}

	return true;
}

/*
	Calculate product price with price modificators 
*/
function modi_price(_price, _taxes, _orig_price) {
//function modi_price(_price, _taxes, _orig_price, _qty) {
	var return_price = round(_price, 2);
/*    var qty = _qty;
     var height = product_option_value("Height");
    var width = product_option_value("Width");
    var calhw = ((height * width)/10000); 
	var return_price1 = return_price*calhw;
*/	
	/* 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];

		/* special type 'Q' - modifier has a amount selector */
		if (modifiers[x2][value][3] && modifiers[x2][value][3] == 'Q') {
			var opt_amount =  getPOValue(x2, 'amounts_po');
			if (!opt_amount) {
				var opt_amount = 1.00;
			}

			return_price += parseFloat(elm[1] == '$' ? (opt_amount*elm[0]) : (opt_amount*(_price*elm[0]/100)));
			
		/* special type 'S' (Sq. meters). Modifier formula: height*width*price_modifier. Height/Width fields are required */
		} else if (modifiers[x2][value][3] == 'S' && document.getElementById('po'+width_elm_id) && document.getElementById('po'+height_elm_id)) {
			var _width = Math.abs(parseFloat(document.getElementById('po'+width_elm_id).value));
			var _height = Math.abs(parseFloat(document.getElementById('po'+height_elm_id).value));
			/* Height/Width in cm by default */
			return_price += round(_width/100*_height/100*parseFloat(elm[1] == '$' ? elm[0] : (_price*elm[0]/100)), 2);

		/* special type 'R' (Perimeter). Modifier formula: X*Y*Z. Height/Width fields are required  */
		} else if (modifiers[x2][value][3] == 'R' && document.getElementById('po'+width_elm_id) && document.getElementById('po'+height_elm_id)) {
			var _width = Math.abs(parseFloat(document.getElementById('po'+width_elm_id).value));
			var _height = Math.abs(parseFloat(document.getElementById('po'+height_elm_id).value));
			var width_height_mult = modifiers[x2][value][6] == 'B' ? _width/100*_height/100 : (
					modifiers[x2][value][6] == 'W' ? _width/100 : (
						modifiers[x2][value][6] == 'H' ? _height/100 : 1
					)
				);
			return_price += round(width_height_mult*parseFloat(elm[0]), 2);

		/* all common modifiers and special type 'P' modifiers with absolute type instead of persentage */
		} else if (modifiers[x2][value][3] != 'P' || modifiers[x2][value][1] == '$') {
			return_price += parseFloat(elm[1] == '$' ? elm[0] : (_price*elm[0]/100));

		/* special type 'P' - modifier with an absolute percentage - applies to filnal price. (must be persentage and single)*/
		} else {
			var abs_perc_elm = modifiers[x2][value];
		}

/*		var elmn = x2;
		//return_price += parseFloat(elm[1] == '$' ? elm[0] : (_price*elm[0]/100));
        // return_price += parseFloat(elm[1] == '$' ? (elm[0]*_qty) : ((return_price*2)-return_price));  
		 if(hw == 'Fix')
		{
				if(document.getElementById('pobis'+x2)) {
				
					conto = elm[0]*document.getElementById('pobis'+x2).value;
				}else {
					conto = elm[0];
				}
				totale = conto*_qty;

			
		//return_price += parseFloat(elm[1] == '$' ? elm[0] : ((return_price*2)-return_price));
		 return_price += parseFloat(elm[1] == '$' ? (totale) : ((return_price*2)-return_price));
		}
		else
		{
		
		
				if(document.getElementById('pobis'+x2)) {
					conto = elm[0]*document.getElementById('pobis'+x2).value;
				}else {
					conto = elm[0];
				}
				totale = conto*_qty;
			
		         if((height == 0) || (width == 0))	
				 {
					//return_price += parseFloat(elm[1] == '$' ? elm[0] : ((return_price*2)-return_price)); 
					return_price += parseFloat(elm[1] == '$' ? (totale) : ((return_price*2)-return_price)); 
				 }
				 else
				 {
					   // return_price1 = return_price1 + parseFloat(elm[1] == '$' ? elm[0] : ((return_price1*2)-return_price1));
					   //return_price = return_price1;
					   return_price1 = return_price1 + parseFloat(elm[1] == '$' ? elm[0] : ((return_price1*2)-return_price1));
					   return_price = return_price1;
					  
				 }
		}*/
		/* Get tax extra charge */
		for (var t2 in _taxes) {
			if (elm[2][t2] && elm[3] == 'Q') {
				_taxes[t2] += parseFloat(elm[1] == '$' ? (opt_amount*elm[2][t2]) : (opt_amount*(_orig_price*elm[2][t2]/100)));
			} else if (elm[2][t2] && elm[3] == 'S' && document.getElementById('po'+width_elm_id) && document.getElementById('po'+height_elm_id)) {
				_taxes[t2] += round(_width/100*_height/100*parseFloat(elm[1] == '$' ? elm[2][t2] : (_orig_price*elm[2][t2]/100)), 2);
			} else if (elm[2][t2] && elm[3] == 'R' && document.getElementById('po'+width_elm_id) && document.getElementById('po'+height_elm_id)) {

				_taxes[t2] += round(width_height_mult*parseFloat(elm[2][t2]), 2);

			} else if (elm[2][t2] && (elm[3] != 'P' || elm[1] == '$')) {
				_taxes[t2] += parseFloat(elm[1] == '$' ? elm[2][t2] : (_orig_price*elm[2][t2]/100));
			}
		}
	}

	/* Add a absolute percentage modifier */
	if (abs_perc_elm && abs_perc_elm[1] != '$') {

		for (var t2 in _taxes) {
			if (abs_perc_elm[2][t2]) {
				_taxes[t2] += parseFloat(_taxes[t2]*abs_perc_elm[0]/100);
			}
		}
		return_price += parseFloat(return_price*abs_perc_elm[0]/100);
	}

	return [return_price, _taxes];
	
}

/*
	Check product options exceptions
*/
function check_exceptions() {
	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() {
	var div = document.getElementById('wl-prices');
	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 || product_wholesale.length == 0) {
		div.style.display = 'none';
		return false;
	}

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

		r = wl_table.insertRow(-1);
		r.insertCell(-1).innerHTML = product_wholesale[i][0] + '+&nbsp;' + (product_wholesale[i][0] == 1 ? lbl_item : lbl_items);
		r.insertCell(-1).innerHTML = price_format(product_wholesale[i][2] < 0 ? 0 : product_wholesale[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.length > 0) {
        for (i in taxes) {
            if (current_taxes[i] > 0)
                tax_str += substitute(lbl_including_tax, 'tax', taxes[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(qty) {
	
	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; x < product_wholesale.length; 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;

		}

		if (document.getElementById('wp' + x)) {
			var wPrice = price-default_price+product_wholesale[x][2];

			document.getElementById('wp' + x).innerHTML = price_format(Math.max(wPrice, 0));
		}
	}

	if (document.getElementById('product_price'))
		document.getElementById('product_price').innerHTML = price_format(Math.max(wl_price * qty, 0));
		
      
	if (alter_currency_rate > 0 && document.getElementById('product_alt_price')) {
		document.getElementById('product_alt_price').innerHTML = price_format(Math.max(wl_price * qty * alter_currency_rate, 0));
	}

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

		} else {
			document.getElementById('save_percent_box').style.display = 'none';
			document.getElementById('save_percent').innerHTML = '0';
		}
	}


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

// Check quantity input box
function check_quantity_input_box(inp) {
	if (isNaN(inp.minQuantity))
		inp.minQuantity = min_avail;

	if (isNaN(inp.maxQuantity))
		inp.maxQuantit = avail;

	if (!isNaN(inp.minQuantity) && !isNaN(inp.maxQuantity)) {
		var q = parseInt(inp.value);
		if (isNaN(q)) {
			alert(substitute(lbl_product_quantity_type_error, "min", inp.minQuantity, "max", inp.maxQuantity));
			return false;
		}

		if (q < inp.minQuantity) {
			alert(substitute(lbl_product_minquantity_error, "min", inp.minQuantity));
			return false;
		}

		if (q > inp.maxQuantity) {
			alert(substitute(lbl_product_maxquantity_error, "max", inp.maxQuantity));
			return false;
		}

		check_wholesale(inp.value);
	}
	return true;
}

/*
	Get product option value
*/
function getPOValue(c, prefix) {
	var prefix = (prefix == null) ? "po" : prefix;

	if (!document.getElementById(prefix + c) || document.getElementById(prefix + c).tagName.toUpperCase() != 'SELECT')
		return false;

	return document.getElementById(prefix+c).options[document.getElementById(prefix+c).selectedIndex].value;
}

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

	if (!names)
		return false;

	for (var x in names) {
		if (names[x]['class_name'] != classid)
			continue;

		return document.getElementById('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;
}

function check_Width_Height(objid) {
	if(!document.getElementById(objid)) {
		return false;
	}

	size = Math.abs(parseFloat(document.getElementById(objid).value));

	if (isNaN(size)) {
		document.getElementById(objid).value = 1.00;
	} else {
		document.getElementById(objid).value = size;
	}

}

