// shopping javacript

function confirmBuy(itemForm, buttonType)
{
	if (buttonType == "wishlist") {
		itemForm.cart.value = "WISHLIST";
	} else {
		itemForm.cart.value = "ADD";
	}
	var params = getProductParams(itemForm);
	var basePrice = params["base_price"];

	var productName = params["item_name"];

	var productPrice = basePrice;
	if (params["zero_product_action"] == 2 && productPrice == 0) {
		alert(params["zero_product_warn"]);
		return false;
	}
	if (buttonType == "wishlist") {
		var savedTypeId = itemForm.saved_type_id.value;
		if (savedTypeId == "") {
			popupSavedTypes(itemForm);
			return false;
		} else {
			itemForm.submit();
		}
	} else if (confirmAdd == "1") {
		return confirm(addProduct);
	} else {
		return true;
	}
}

function addToWishlist()
{
	var formId = document.saved_types.form_id.value;
	if (formId != "") {
		var formName = "form_" + formId
		var itemForm = document.forms[formName];
		var typesTotal = parseInt(document.saved_types.saved_types_total.value);
		var typeId = "";
		if (typesTotal == 1) {
			var typeId = document.saved_types.type_id.value;
		} else if (typesTotal > 1) {
			var typeId = document.saved_types.type_id.options[document.saved_types.type_id.selectedIndex].value;
		}
		if (typeId != "") {
			itemForm.saved_type_id.value = typeId;
			hideSavedTypes();
			confirmBuy(itemForm, "wishlist");
		} else {
			alert("Please select a type");
		}
	} else {
		alert("Product wasn't selected");
	}
}

function popupSavedTypes(itemForm)
{                              	
	var params = getProductParams(itemForm);
	var formId = params["form_id"];
	document.saved_types.form_id.value = formId;
	var savedTypesShadow = document.getElementById("saved_types_shadow");
	var savedTypesWin = document.getElementById("saved_types_win");
	if (formId != "") {
		var wishlistButton = document.getElementById("wishlist_" + formId);
		savedTypesWin.style.left = (findPosX(wishlistButton, 0) - 150) + "px";
		savedTypesWin.style.top = (findPosY(wishlistButton, 0) - 100) + "px";
		var arrayPageSizeWithScroll = getPageSizeWithScroll();
		savedTypesShadow.style.height = arrayPageSizeWithScroll[1] + "px";
	}

	savedTypesWin.style.display = "block";			
	savedTypesShadow.style.display = "block";			
	hideSelectBoxes("saved_types_win", new Array("type_id"));
}

function hideSavedTypes()
{                              	
	document.saved_types.form_id.value = "";
	var savedTypesShadow = document.getElementById("saved_types_shadow");
	var savedTypesWin = document.getElementById("saved_types_win");
	savedTypesWin.style.display = "none";			
	savedTypesShadow.style.display = "none";			
	showSelectBoxes("saved_types_win");
}

function changeSavedType()
{
	var prevTypeId = document.saved_types.prev_type_id.value;
	var typeIdControl = document.saved_types.type_id;
	var selectedTypeId = typeIdControl.options[typeIdControl.selectedIndex].value;
	document.saved_types.prev_type_id.value = selectedTypeId;
	if (prevTypeId != selectedTypeId) {
		if (prevTypeId != "") {
			var typeDescBlock = document.getElementById("type_desc_" + prevTypeId);
			typeDescBlock.style.display = "none";			
		}
		if (selectedTypeId != "") {
			var typeDescBlock = document.getElementById("type_desc_" + selectedTypeId);
			typeDescBlock.style.display = "block";			
		}
	}
}

function changeProperty(itemForm)
{
	var priceControl = "";
	var htmlControl = false;
	var itemId = "";
	var taxPercent = 0;
	var offerPrice = 0;

	var params = getProductParams(itemForm);
	var taxNote = params["tax_note"];
	var pointsBase = params["base_points_price"];
	var formId = params["form_id"];

	if (itemForm.tax_percent && itemForm.tax_percent.value != "") {
		taxPercent = parseFloat(itemForm.tax_percent.value);
		if (isNaN(taxPercent)) { taxPercent = 0; }
	}

	if (itemForm.add_id) {
		itemId = itemForm.add_id.value;
	} else if (itemForm.item_id) {
		itemId = itemForm.item_id.value;
	}
	if (itemId != "" && document.getElementById) {
		priceControl = document.getElementById("sales_price_" + itemId);
		if (!priceControl) {
			priceControl = document.getElementById("price_" + itemId);
		}
	} 
	var pointsPriceControl = document.getElementById("points_price_" + itemId);

	var basePrice = params["base_price"];
	// check product quantity
	var quantity = 1;
	if (itemForm.quantity) {
		if (itemForm.quantity.selectedIndex) {
			quantity = parseInt(itemForm.quantity.options[itemForm.quantity.selectedIndex].value);
		} else {
			quantity = parseInt(itemForm.quantity.value);
		}
		if (isNaN(quantity)) { quantity = 1; } 
	}
	if(params["quantity_price"]) { 
		var prices = params["quantity_price"]; 
		if (prices != "") {
			prices = prices.split(",");
			for (var p = 0; p < prices.length; p = p + 4) {
				var minQuantity = parseInt(prices[p]);
				var maxQuantity = parseInt(prices[p + 1]);
				if (quantity >= minQuantity && quantity <= maxQuantity) {
					offerPrice = parseFloat(prices[p + 2] * quantity);
					break;
				}
			}
		}
	}
	
	var price = basePrice;
	var taxAmount = 0; var productPrice = 0; var taxPrice = 0; var priceExcl = 0;
	if (params["tax_prices_type"] == 1) {
		// price already includes tax
		taxPrice = Math.round((price) * 100) / 100; 
		taxAmount = (Math.round(price * 100) - Math.round(price * 10000 / ( 100 + taxPercent))) / 100; 
		productPrice = Math.round((price - taxAmount) * 100) / 100;
		priceExcl = productPrice;
	} else {
		taxAmount = Math.round(price * taxPercent) / 100; 
		productPrice = Math.round((price) * 100) / 100;
		taxPrice = Math.round((productPrice + taxAmount) * 100) / 100; 
		priceExcl = productPrice;
	}

	if (params["show_prices"] == 2) {
		productPrice = taxPrice;
		taxPrice = priceExcl;
	} else if (params["show_prices"] == 3) {
		productPrice = taxPrice;
	}

	if (priceControl) {
		if (params["zero_price_type"] != 0 && productPrice == 0) {
			if (params["zero_price_type"] == 1) { params["zero_price_message"] = ""; }
			priceControl.innerHTML = params["zero_price_message"];
		} else {
			priceControl.innerHTML = decode_utf8(params["cleft"]) + formatNumber(productPrice * params["crate"], params["cdecimals"], params["cpoint"], params["cseparator"]) + decode_utf8(params["cright"]);
		}
		priceBlockControl = document.getElementById("price_block_" + itemId);
		if (priceBlockControl) {
			if (params["zero_price_type"] == 1 && productPrice == 0) {
				priceBlockControl.style.display = "none";
			} else {
				priceBlockControl.style.display = "block";
			}
		}
	}
	taxPriceControl = document.getElementById("tax_price_" + itemId);
	if (taxPriceControl) {
		if (params["zero_price_type"] != 0 && taxPrice == 0) {
			taxPriceControl.innerHTML = "";
		} else {
			if (taxNote != "") { taxNote = " " + taxNote; }
			taxPriceControl.innerHTML = "(" + decode_utf8(params["cleft"]) + formatNumber(taxPrice * params["crate"], params["cdecimals"], params["cpoint"], params["cseparator"]) + decode_utf8(params["cright"]) + taxNote + ")";
		}
	}
	if (pointsPriceControl) {
		var pointsPrice = pointsBase + (price * params["points_rate"]);
		pointsPriceControl.innerHTML = formatNumber(pointsPrice, params["points_decimals"]);
	}
	
	if (offerPrice > 0) {
		offerPriceBlock = document.getElementById("offer_price_block_" + itemId);
		offerPriceControl = document.getElementById("offer_price_" + itemId);
		offerPriceControl.innerHTML = decode_utf8(params["cleft"]) + formatNumber(offerPrice * params["crate"], params["cdecimals"], params["cpoint"], params["cseparator"]) + decode_utf8(params["cright"]);
		offerPriceBlock.style.display = "block";
	} else {
		offerPriceBlock = document.getElementById("offer_price_block_" + itemId);
		if(offerPriceBlock)
			offerPriceBlock.style.display = "none";
	}
}


function changeQuantity(itemForm)
{
	changeProperty(itemForm);
}

function offerChangeQty(item_id, quantity) {
	$('select#quantity_'+item_id+' option[value="'+quantity+'"]').attr("selected","selected");
	$('select#quantity_'+item_id).trigger("change");
}

function openPreviewWin(previewUrl, width, height)
{
	var previewWin = window.open (previewUrl, 'previewWin', 'left=0,top=0,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=' + width + ',height=' + height);
	previewWin.focus();
	return false;
}

function openSuperImage(imageUrl, width, height)
{
	var scrollbars = "no";
	// add margins to image size
	if (width > 0 && height > 0) {
		width += 30; height += 30;
	}
	// check available sizes
	var availableHeight = window.screen.availHeight - 60;
	var availableWidth = window.screen.availWidth - 20;
	if (isNaN(availableHeight)) { availableHeight = 520; } 
	if (isNaN(availableWidth)) { availableWidth = 760; } 
	if (height > availableHeight || height == 0) { 
		height = availableHeight;
		scrollbars = "yes"; 
	}
	if (width > availableWidth || width == 0) {
		width = availableWidth;
		scrollbars = "yes";
	}
	var superImageWin = window.open (imageUrl, 'superImageWin', 'left=0,top=0,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=' + scrollbars + ',resizable=yes,width=' + width + ',height=' + height);
	superImageWin.focus();
	return false;
}

function setFilePath(filepath, filetype, controlName, formId)
{
	if(filepath != "" && controlName != "" && formId != "")
	{
		var formName = "form_" + formId;
		document.forms[formName].elements[controlName].value = filepath;
		document.forms[formName].elements[controlName].focus();
	}
}

function formatNumber(numberValue, decimals, decimalPoint, thousandsSeparator)
{
	if (decimals == undefined) {
		decimals = 0;
	}
	if (thousandsSeparator == undefined) {
		thousandsSeparator = ",";
	}

	var numberParts = "";
	var roundValue = 1;
	for (var d = 0; d < decimals; d++) {
		roundValue *= 10;
	}
	numberValue = Math.round(numberValue * roundValue) / roundValue;
	var numberSign = "";
	if (numberValue < 0) {
		numberSign = "-";
		numberValue = Math.abs(numberValue);
	} 

	var numberText = new String(numberValue);
	var numberParts = numberText.split(".");
	var beforeDecimal = numberParts[0];
	var afterDecimal = "";
	numberText = "";
	if (numberParts.length == 2) {
		afterDecimal = numberParts[1];
	}
	while (beforeDecimal.length > 0) {
		if (beforeDecimal.length > 3) {
			numberText = thousandsSeparator + beforeDecimal.substring(beforeDecimal.length - 3, beforeDecimal.length) + numberText;
			beforeDecimal = beforeDecimal.substring(0, beforeDecimal.length - 3);
		} else {
			numberText = beforeDecimal + numberText;
			beforeDecimal = "";
		}
	}
	if (decimals > 0) {
		while (afterDecimal.length < decimals) {
			afterDecimal += "0";
		}
		if (decimalPoint == undefined) {
			decimalPoint = ".";
		}
		numberText += decimalPoint + afterDecimal;
	}
	numberText = numberSign + numberText;

	return numberText;
}

function getProductParams(itemForm)
{
	var params = new Array();
	var paramsList = itemForm.product_params.value; 
	var paramsPairs = paramsList.split("&");
	for (var p = 0; p < paramsPairs.length; p++) {
		var paramPair = paramsPairs[p];
		var equalPos = paramPair.indexOf("=");
		if(equalPos == -1) {
			params[paramPair] = "";
		} else {
			var paramName = unescape(paramPair.substring(0, equalPos));
			var paramValue = paramPair.substring(equalPos + 1, paramPair.length);
			paramValue = unescape(paramValue.replace(/\+/g, " "));
			params[paramName] = paramValue;
		}
	}
	// check params values
	var checkParams = new Array();
	checkParams["base_price"] = 0;
	checkParams["crate"] = 1;
	checkParams["zero_product_action"] = 1;
	checkParams["zero_price_type"] = 0;
	checkParams["show_prices"] = 1;
	checkParams["tax_prices_type"] = 0;
	checkParams["points_rate"] = 1;
	checkParams["points_decimals"] = 0;
	checkParams["points_decimals"] = 0;
	checkParams["base_points_price"] = 0;
	checkParams["base_reward_points"] = 0;
	for (paramName in checkParams) {
		if (params[paramName]) {
			params[paramName] = parseFloat(params[paramName]);
			if (isNaN(params[paramName])) { params[paramName] = checkParams[checkParams]; }
		} else {
			params[paramName] = checkParams[checkParams];
		}
	}
	return params;
}

function checkMaxLength(obj, maxLength)
{
  return (obj.value.length <= maxLength);
}

