// shopping javacript

function reloadCartBlocks(responseText, cartParams) {

	var equalPos = responseText.indexOf("=");
	var msgType = ""; var msgText = ""; 
	if(equalPos == -1) {
		msgType = "errors";
		msgText = responseText;
	} else {
		msgType = responseText.substring(0, equalPos);
		msgText = responseText.substring(equalPos + 1, responseText.length);
	}
	var messageId = cartParams[0];
	var messageObj = document.getElementById(messageId);

	var msgLeft = findPosX(messageObj);
	var msgTop = findPosY(messageObj, true);
	showPopupBlock(msgType, msgText, msgLeft, msgTop);

	// set all quantity controls to zero if multi-add active
	var multiAdd = "";
	var formName = cartParams[1];
	var itemsForm = document.forms[formName];
	if (itemsForm.multi_add) {
		multiAdd = itemsForm.multi_add.value;
	}
	if (multiAdd == 1 && itemsForm.items_indexes && itemsForm.items_indexes.value != "") {
		var indexes = itemsForm.items_indexes.value.split(",");
		for (var i = 0; i < indexes.length; i++) {
			var idx = indexes[i];
			var controlName = "quantity" + idx;
			if (itemsForm.elements[controlName]) {
				var elementType = itemsForm.elements[controlName].type;
				if (elementType == "text") {
					itemsForm.elements[controlName].value = 0;
				} else if (elementType == "select-one") {
					itemsForm.elements[controlName].selectedIndex = 0;
				}
			}
		}
	}

	if (msgType == "success") {
		var checkNames = new Array("small_cart", "shopping_cart");
		for (var cn = 0; cn < checkNames.length; cn++) {
			var checkName = checkNames[cn];
			// refresh block in the active window
			var foundBlocks = document.getElementsByName(checkName);
			for (var b = 0; b < foundBlocks.length; b++) {
				var formObj = foundBlocks[b];
				var pbId = formObj.pb_id.value;
				initProgress("pb_"+pbId);
				reloadBlock(pbId);
			}
			// check if we add products from some popup window to refresh cart blocks in parent window
			if (window.opener) { 
				var foundBlocks = window.opener.document.getElementsByName(checkName);
				for (var b = 0; b < foundBlocks.length; b++) {
					var formObj = foundBlocks[b];
					var pbId = formObj.pb_id.value;
					window.opener.initProgress("pb_"+pbId);
					window.opener.reloadBlock(pbId);
				}
			}
		}
	}
}

function confirmBuy(formName, selectedIndex, buttonType, messageId)
{
	var itemsForm = document.forms[formName];
	itemsForm.item_index.value = selectedIndex; // assign index of product to be added to cart
	var startIndex = 1;
	if (itemsForm.start_index) {
		startIndex = itemsForm.start_index.value;
	}
	var idx = selectedIndex;
	// check global redirect option
	var redirectToCart = "";
	if (itemsForm.redirect_to_cart) {
		redirectToCart = itemsForm.redirect_to_cart.value;
	}

	if (buttonType == "wishlist") {
		itemsForm.cart.value = "WISHLIST";
	} else if (buttonType == "shipping") {
		itemsForm.cart.value = "SHIPPING";
	} else {
		itemsForm.cart.value = "ADD";
	}
	if (itemsForm.originalAction) {
		itemsForm.target = "";
		itemsForm.action = itemsForm.originalAction;
	}
	// check initial index if it wasn't selected
	var indexes = new Array();
	if (!itemsForm.elements["item_id"+idx]) {
		if (itemsForm.items_indexes && itemsForm.items_indexes.value != "") {
			indexes = itemsForm.items_indexes.value.split(",");
			idx = indexes[0];
		} else {
			idx = startIndex;
		}
	}

	// check products one by one
	var selectedItems = 0;
	var itemNo = 0;
	do {
		itemNo++;

		// check product quantity
		var quantity = 1;
		if (itemsForm.elements["quantity"+idx]) {
			if (itemsForm.elements["quantity"+idx].selectedIndex) {
				quantity = parseInt(itemsForm.elements["quantity"+idx].options[itemsForm.elements["quantity"+idx].selectedIndex].value);
			} else {
				quantity = parseInt(itemsForm.elements["quantity"+idx].value);
			}
			if (isNaN(quantity)) { quantity = 1; } 
		}

		if (quantity > 0) {
			selectedItems++;
			var params = getProductParams(itemsForm, idx);
			var basePrice = params["base_price"];
			
			// check what options were selected and what options is active
			var returnedValues = checkOptions(itemsForm, idx);
			var selectedOptions = returnedValues[0];
			var activeOptions = returnedValues[1];
			// check options for requirements
			var prMessage = requiredProperty;
    
			var productName = params["item_name"];
			for (prID in activeOptions) {
				if (itemsForm.elements["property_control"+idx+"_" + prID]) { // check if it is property control
					var prRequired = itemsForm.elements["property_required"+idx+"_" + prID].value;
					var prControl = itemsForm.elements["property_control"+idx+"_" + prID].value;
					if (prRequired == 1 && activeOptions[prID] && !selectedOptions[prID]) {
						var propertyName = itemsForm.elements["property_name"+idx+"_" + prID].value;
						prMessage = prMessage.replace("\{property_name\}", propertyName);
						prMessage = prMessage.replace("\{product_name\}", productName);
						alert(prMessage);	
						if (prControl != "RADIOBUTTON" && prControl != "CHECKBOXLIST" && prControl != "TEXTBOXLIST" && prControl != "LABEL") {
							itemsForm.elements["property"+idx+"_" + prID].focus();
						}
						return false;
					}
				}
			}
	  
			// calculate price for selected options
			var propertiesPrice = calculateOptionsPrice(itemsForm, idx, selectedOptions);
			var isPriceEdit = params["pe"];
			var productPrice = 0;
			if (isPriceEdit) {
				var userPrice = parseFloat(itemsForm.elements["price"+idx].value);
				productPrice = userPrice + params["comp_price"] + propertiesPrice;
			} else {
				productPrice = basePrice + params["comp_price"] + propertiesPrice;
			}
	  
			if (params["zero_product_action"] == 2 && productPrice == 0) {
				alert(params["zero_product_warn"]);
				return false;
			}
		}

		// check next index
		idx = "";
		if (selectedIndex == "") {
			var nextIndex = "";
			if (indexes.length > 0) {
				nextIndex = (indexes.length > itemNo) ? indexes[itemNo] : "";
			} else {
				nextIndex = startIndex + itemNo;
			}
			if (nextIndex != "" && itemsForm.elements["item_id"+nextIndex]) {
				idx = nextIndex;
			}
		}
		// end index check
		
	} while (idx != "");

  // submit form
	if (buttonType == "wishlist") {
		var savedTypesHidden = "0";
		if (document.saved_types.saved_types_hidden) {
			// check if we don't need to show popup win
			savedTypesHidden = document.saved_types.saved_types_hidden.value; 
		}
		if (savedTypesHidden == "1") {
			// assign default type_id from hidden popup
			itemsForm.saved_type_id.value = document.saved_types.type_id.value;
		}
		// check if type_id was selected 
		var savedTypeId = itemsForm.saved_type_id.value;
  
		if (savedTypeId == "") {
			popupSavedTypes(itemForm);
		} else {
			itemsForm.submit();
		}
		return false;
	} else if (buttonType == "shipping") {
		popupShippingFrame();
		itemsForm.originalAction = itemsForm.action; // save original action value
		itemsForm.action = "shipping_calculator.php";
		itemsForm.target = "shipping_frame";
		itemsForm.submit();
		return false;
	} else {
		if (selectedItems > 0) {
			// check and submit form to add product to the cart
			var submitForm = true;
			if (confirmAdd == "1") {
				submitForm = confirm(addProduct);
			}
			if (submitForm) {
				if (redirectToCart == 3) {
					// AJAX option selected
					submitForm = false; // don't need to submit form
					itemsForm.rnd.value = ""; // don't need random values for AJAX
					var cartParams = new Array(messageId, formName);
					postAjax("cart_add.php", reloadCartBlocks, cartParams, itemsForm);
				} else {
					itemsForm.submit();
				}
			}
		}
		return false;
	}
}


function confirmSubscription(itemForm)
{
	if (confirmAdd == "1") {
		return confirm(addSubscription);
	} 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 popupShippingWin(shippingUrl)
{
	var shippingWin = window.open (shippingUrl, 'shippingWin', 'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=600,height=400');
	shippingWin.focus();
}

function popupShippingFrame(itemForm)
{                              	
	var shippingOpacity = document.getElementById("shipping_opacity");
	shippingOpacity.style.opacity    = "0.6";
	shippingOpacity.style.mozOpacity = "0.6";
	shippingOpacity.style.filter     = "alpha(opacity=60)";
	var shippingShadow = document.getElementById("shipping_shadow");

	var pageSize = getPageSize();
	var pageScroll = getScroll();
	var arrayPageSizeWithScroll = getPageSizeWithScroll();

	var winLeft = 5; var winTop = 5;
	if (pageSize[0] > 620) {
		winLeft = pageScroll[0] + (pageSize[0]-600) / 2;
	}
	if (pageSize[1] > 420) {
		winTop = pageScroll[1] + (pageSize[1]-400) / 2;
	}
	shippingShadow.style.left = winLeft + "px";
	shippingShadow.style.top = winTop + "px";

	shippingOpacity.style.width = arrayPageSizeWithScroll[0] + "px";
	shippingOpacity.style.height = arrayPageSizeWithScroll[1] + "px";

	shippingShadow.style.display = "block";			
	shippingOpacity.style.display = "block";			

	hideSelectBoxes("shipping_shadow", new Array("shipping_frame"));
}

function hideShippingFrame()
{                              	
	var shippingOpacity = document.getElementById("shipping_opacity");
	var shippingShadow = document.getElementById("shipping_shadow");
	var shippingPage = document.getElementById("shipping_page");

	shippingOpacity.style.display = "none";			
	shippingShadow.style.display = "none";			
	shippingPage.src = "";
	showSelectBoxes("shipping_shadow");
}

function popupSavedTypes(formName, idx)
{                              	
	var params = getProductParams(itemsForm, formId);
	var formId = params["form_id"];
	document.saved_types.form_id.value = formId;
	var savedTypesShadow = document.getElementById("saved_types_shadow");
	savedTypesShadow.style.opacity    = "0.6";
	savedTypesShadow.style.mozOpacity = "0.6";
	savedTypesShadow.style.filter     = "alpha(opacity=60)";
	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(formName, idx)
{
	var itemsForm = document.forms[formName];

	var selectedOptions = new Array();
	var priceControl = "";
	var htmlControl = false;
	var itemId = itemsForm.elements["item_id"+idx].value;;
	var taxPercent = 0;

	var params = getProductParams(itemsForm, idx);
	var taxNote = params["tax_note"];
	var pointsBase = params["base_points_price"];
	var prIDs = params["properties_ids"];
	var formId = params["form_id"];
	var stockLevel = getParamValue(params, "sl", "int");
	var useStockLevel = getParamValue(params, "use_sl", "int")
	var inStock = getParamValue(params, "in_sm", "txt");
	var outStock = getParamValue(params, "out_sm", "txt")

	if (itemsForm.elements["tax_percent"+idx] && itemsForm.elements["tax_percent"+idx].value != "") {
		taxPercent = parseFloat(itemsForm.elements["tax_percent"+idx].value);
		if (isNaN(taxPercent)) { taxPercent = 0; }
	}

	if (itemId != "" && document.getElementById) {
		priceControl = document.getElementById("sales_price" + idx);
		if (!priceControl) {
			priceControl = document.getElementById("price" + idx);
		}
	} 
	var pointsPriceControl = document.getElementById("points_price" + idx);

	// check what options were selected and what options is active
	var returnedValues = checkOptions(itemsForm, idx);
	var selectedOptions = returnedValues[0];
	var activeOptions = returnedValues[1];
	// calculate price for selected options
	var totalAdditionalPrice = calculateOptionsPrice(itemsForm, idx, selectedOptions);

	// check stock levels for options
	var optionUseStock = 0; var optionStockLevel = 0; 
	for (prID in selectedOptions) {
		if (itemsForm.elements["property_control"+idx+"_" + prID]) { // check if it is property control
			var prControl = itemsForm.elements["property_control"+idx+"_" + prID].value;
			if (prControl == "LISTBOX" || prControl == "RADIOBUTTON") {
				optionUseStock = getOptionValue(itemsForm, "use_sl_" + selectedOptions[prID]);
				if (optionUseStock == 1) {
					optionStockLevel = getOptionValue(itemsForm, "sl_" + selectedOptions[prID]);
					if (useStockLevel == 0 || stockLevel > optionStockLevel) {
						stockLevel = optionStockLevel;
						useStockLevel = 1;
					}
				}
			} else if (prControl == "CHECKBOXLIST" || prControl == "TEXTBOXLIST") {
				var values = selectedOptions[prID];
				for (valueId in values) {
					optionUseStock = getOptionValue(itemsForm, "use_sl_" + valueId);
					if (optionUseStock == 1) {
						optionStockLevel = getOptionValue(itemsForm, "sl_" + valueId);
						if (useStockLevel == 0 || stockLevel > optionStockLevel) {
							stockLevel = optionStockLevel;
							useStockLevel = 1;
						}
					}
				}	
			}
		}
	}
	// end options stock levels

	// change stock level and stock message
	var obj = document.getElementById("sl" + idx);
	var blockObj = document.getElementById("block_sl" + idx);
	if (obj) {
		if (useStockLevel == 1) {
			obj.innerHTML = stockLevel;
			if (blockObj) { blockObj.style.display = "block"; }
		} else {
			obj.innerHTML = "";
			if (blockObj) { blockObj.style.display = "none"; }
		}
	}
	obj = document.getElementById("sm" + idx);
	blockObj = document.getElementById("block_sm" + idx);
	if (obj) {
		var stockMessage = "";
		if (useStockLevel == 0 || stockLevel > 0) {
			stockMessage = inStock;
		} else {
			stockMessage = outStock;
		}
		obj.innerHTML = stockMessage;
		if (blockObj) { 
			if (stockMessage == "") {
				blockObj.style.display = "none";
			} else {
				blockObj.style.display = "block"; 
			}
		}
	}

	// hide or show property blocks
	for (prID in activeOptions) {
		if (itemsForm.elements["property_control" + idx + "_" + prID]) { // check if it is property control
			var propertyBlock = document.getElementById("pr" + idx + "_" + prID);
			if (activeOptions[prID]) {
				propertyBlock.style.display = "block";				
			} else {
				propertyBlock.style.display = "none";				
			}
		}
	}

	// show hide image for subcomponents
	for (prID in activeOptions) {
		if (itemsForm.elements["property_control"+idx+"_" + prID]) { // check if it is property control
			var prControl = itemsForm.elements["property_control"+idx+"_" + prID].value;
			if (activeOptions[prID] && (prControl == "LISTBOX" || prControl == "RADIOBUTTON")) {
				var prValue = selectedOptions[prID];
	  
				var objId = formId + "_" + prID; // id for current product option
				if (prValue != "") {
					var image_button = document.getElementById("option_image_action"+idx+"_" + prID);
					if (!image_button) {
						var image_button       = document.createElement('a');				
						image_button.id        = "option_image_action"+idx+"_" + prID;
						image_button.href      = "#";
						image_button.onclick   = popupImage;
						image_button.style.display = "none";
						image_button.innerHTML = "<img src='images/icons/view_page.gif' alt='View' border='0'/>";
						var propertyObj = document.getElementById("pr"+idx+"_" + prID);
						if (propertyObj) { propertyObj.appendChild(image_button); }
					}				
					if (itemsForm.elements["option_image"+idx+"_" + prValue]) {
						var image = itemsForm.elements["option_image"+idx+"_" + prValue].value;
						if (itemsForm.elements["option_image_action"+idx+"_" + prValue]) {
							image_button.onclick = (itemsForm.elements["option_image_action"+idx+"_" + prValue].onclick);
						}					
						image_button.style.display = "inline";
						image_button.href  = image;
						image_button.title = itemsForm.elements["property"+idx+"_" + prID].options[itemsForm.elements["property"+idx+"_" + prID].selectedIndex].text;
					} else {
						image_button.style.display = "none";
					}
				} else {
					var image_button = document.getElementById("option_image_action"+idx+"_" + prID);
					if (image_button) {
						image_button.style.display = "none";
					}
				}
			}
		}
	}

	var basePrice = params["base_price"];
	var baseTax = 0;
	// check product quantity
	var quantity = 1;
	if (itemsForm.elements["quantity"+idx]) {
		if (itemsForm.elements["quantity"+idx].selectedIndex) {
			quantity = parseInt(itemsForm.elements["quantity"+idx].options[itemsForm.elements["quantity"+idx].selectedIndex].value);
		} else {
			quantity = parseInt(itemsForm.elements["quantity"+idx].value);
		}
		if (isNaN(quantity)) { quantity = 1; } 
	}
	var isQuantityPrice = false;
	if(params["quantity_price"]) { 
		var prices = params["quantity_price"]; 
		if (prices != "") {
			prices = prices.split(",");
			for (var p = 0; p < prices.length; p = p + 5) {
				var minQuantity = parseInt(prices[p]);
				var maxQuantity = parseInt(prices[p + 1]);
				if (quantity >= minQuantity && quantity <= maxQuantity) {
					isQuantityPrice = true;
					basePrice = parseFloat(prices[p + 2]);
					baseTax = parseFloat(prices[p + 3]);
					var propertiesDiscount = parseFloat(prices[p + 4]);
					if (propertiesDiscount > 0) {
						totalAdditionalPrice -= (Math.round(totalAdditionalPrice * propertiesDiscount) / 100);
					}
					break;
				}
			}
		}
	}
	
	var price = basePrice + totalAdditionalPrice;
	var taxAmount = 0; var productPrice = 0; var taxPrice = 0; var priceExcl = 0;
	if (params["tax_prices_type"] == 1) {
		// price already includes tax
		if (isQuantityPrice) {
			taxPrice = Math.round((price) * 100) / 100; 
			taxAmount = baseTax; 
		} else {
			taxPrice = Math.round((price + params["comp_price"]) * 100) / 100; 
			taxAmount = (Math.round(price * 100) - Math.round(price * 10000 / ( 100 + taxPercent))) / 100; 
		}
		if (isQuantityPrice) {
			productPrice = Math.round((price - taxAmount) * 100) / 100;
		} else {
			productPrice = Math.round((price - taxAmount + params["comp_price"] - params["comp_tax"]) * 100) / 100;
		}
		priceExcl = productPrice;
	} else {
		if (isQuantityPrice) {
			taxAmount = baseTax; 
			productPrice = Math.round((price) * 100) / 100;
			taxPrice = Math.round((productPrice + taxAmount) * 100) / 100; 
		} else {
			taxAmount = Math.round(price * taxPercent) / 100; 
			productPrice = Math.round((price + params["comp_price"]) * 100) / 100;
			taxPrice = Math.round((productPrice + taxAmount + params["comp_tax"]) * 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["pe"] == "1") {
			// if user can edit price check and update textbox value
			if (itemsForm.elements["price"+idx]) {
				itemsForm.elements["price"+idx].value = productPrice * params["crate"];
			}
		} else {
			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 = params["cleft"] + formatNumber(productPrice * params["crate"], params["cdecimals"], params["cpoint"], params["cseparator"]) + params["cright"];
			}
			priceBlockControl = document.getElementById("price_block"+idx);
			if (priceBlockControl) {
				if (params["zero_price_type"] == 1 && productPrice == 0) {
					priceBlockControl.style.display = "none";
				} else {
					priceBlockControl.style.display = "block";
				}
			}
		}
	}
	taxPriceControl = document.getElementById("tax_price" + idx);
	if (taxPriceControl) {
		if (params["zero_price_type"] != 0 && taxPrice == 0) {
			taxPriceControl.innerHTML = "";
		} else {
			if (taxNote != "") { taxNote = " " + taxNote; }
			taxPriceControl.innerHTML = "(" + params["cleft"] + formatNumber(taxPrice * params["crate"], params["cdecimals"], params["cpoint"], params["cseparator"]) + params["cright"] + taxNote + ")";
		}
	}
	if (pointsPriceControl) {
		var pointsPrice = pointsBase + (totalAdditionalPrice * params["points_rate"]);
		pointsPriceControl.innerHTML = formatNumber(pointsPrice, params["points_decimals"]);
	}

}

function checkOptions(itemsForm, idx)
{
	var params = getProductParams(itemsForm, idx);
	var prIDs = params["properties_ids"];
	var selectedOptions = new Array();
	var activeOptions = new Array();
	var returnValues = new Array();

	// first check of all selected options if properties available for the product block
	if (prIDs && prIDs != "") {
		var properties = prIDs.split(",");
		for ( var i = 0; i < properties.length; i++) {
			var prID = properties[i];
			var prValue = ""; 
			if (itemsForm.elements["property_control"+idx+"_" + prID]){  //P
				var prControl = itemsForm.elements["property_control"+idx+"_" + prID].value;
			}

			if (prControl == "LISTBOX") {
				prValue = itemsForm.elements["property"+idx+"_" + prID].options[itemsForm.elements["property"+idx+"_" + prID].selectedIndex].value;
				if (prValue != "") {
					selectedOptions[prID] = prValue;
				}
			} else if (prControl == "RADIOBUTTON") {
				var radioControl = itemsForm.elements["property"+idx+"_" + prID];
				if (radioControl.length) {
					for ( var ri = 0; ri < radioControl.length; ri++) {
						if (radioControl[ri].checked) {
							prValue = radioControl[ri].value;
							break;
						}
					}
				} else {
					if (radioControl.checked) {
						prValue = radioControl.value;
					}
				}
				if (prValue != "") {
					selectedOptions[prID] = prValue;
				}
			} else if (prControl == "CHECKBOXLIST") {
				if (itemsForm.elements["property_total"+idx+"_" + prID]) {
					var totalOptions = parseInt(itemsForm.elements["property_total"+idx+"_" + prID].value);
					for ( var ci = 1; ci <= totalOptions; ci++) {
						if (itemsForm.elements["property"+idx+"_" + prID + "_" + ci].checked) {
							var checkedValue = itemsForm.elements["property"+idx+"_" + prID + "_" + ci].value;
							if (!selectedOptions[prID]) {
								selectedOptions[prID] = new Array();
							}
							selectedOptions[prID][checkedValue] = 1;
						}
					}
				} 
			} else if (prControl == "TEXTBOXLIST") {
				if (itemsForm.elements["property_total"+idx+"_" + prID]) {
					var totalOptions = parseInt(itemsForm.elements["property_total"+idx+"_" + prID].value);
					for ( var ci = 1; ci <= totalOptions; ci++) {
						if (itemsForm.elements["property"+idx+"_" + prID + "_" + ci].value != "") {
							var valueId = itemsForm.elements["property_value"+idx+"_" + prID + "_" + ci].value;
							var valueText = itemsForm.elements["property"+idx+"_" + prID + "_" + ci].value;
							if (!selectedOptions[prID]) {
								selectedOptions[prID] = new Array();
							}
							selectedOptions[prID][valueId] = valueText;
						}
					}
				} 
			} else if (prControl == "LABEL"){
				// get from hidden control
				if (itemsForm.elements["property"+idx+"_" + prID]) {
					prValue = itemsForm.elements["property"+idx+"_" + prID].value;
					if (prValue != "") {
						selectedOptions[prID] = prValue;
					}
				}
			} else {
				prValue = itemsForm.elements["property"+idx+"_" + prID].value;
				if (prValue != "") {
					selectedOptions[prID] = prValue;
				}
			}
		}
	}

	// second check for active options and correct selected options if necessary
	if (prIDs && prIDs != "") {
		do {
			// save how many selected options we have at start
			var startSelectedNumber = selectedOptions.length;
			// check availability of parent options		
			var properties = prIDs.split(",");
			for ( var i = 0; i < properties.length; i++) {
				var prID = properties[i];
				if (itemsForm.elements["property_parent_id"+idx+"_" + prID]){ //P
					var parentPropertyId = itemsForm.elements["property_parent_id"+idx+"_" + prID].value;
				}				
				if (itemsForm.elements["property_parent_value_id"+idx+"_" + prID]){ //P
					var parentValueId = itemsForm.elements["property_parent_value_id"+idx+"_" + prID].value;
				}				
				var showProperty = true;
				if (parentPropertyId != "") {
					if (!selectedOptions[parentPropertyId]) {
						showProperty = false;
					} else if (parentValueId != "") {
						if (!selectedOptions[parentPropertyId][parentValueId] && selectedOptions[parentPropertyId] != parentValueId) {
							showProperty = false;
						}
					}
				}
				activeOptions[prID] = showProperty;
				if (!showProperty) {
					// delete from selected
					if (selectedOptions[prID]) {
						delete selectedOptions[prID];
					}
	  
					// clear all options
					var prControl = itemsForm.elements["property_control"+idx+"_" + prID].value;
					if (prControl == "LISTBOX") {
						var selectedIndex = itemsForm.elements["property"+idx+"_" + prID].selectedIndex;
						if (selectedIndex > 0) {
							itemsForm.elements["property"+idx+"_" + prID].options[0].selected = true;
						}
					} else if (prControl == "RADIOBUTTON") {
						var radioControl = itemsForm.elements["property"+idx+"_" + prID];
						if (radioControl.length) {
							for ( var ri = 0; ri < radioControl.length; ri++) {
								radioControl[ri].checked = false;
							}
						} else {
							radioControl.checked = false;
						}
	  
					} else if (prControl == "CHECKBOXLIST") {
						var totalOptions = parseInt(itemsForm.elements["property_total"+idx+"_" + prID].value);
						for ( var ci = 1; ci <= totalOptions; ci++) {
							itemsForm.elements["property"+idx+"_" + prID + "_" + ci].checked = false;
						}
					} else if (prControl == "TEXTBOXLIST") {
						var totalOptions = parseInt(itemsForm.elements["property_total"+idx+"_" + prID].value);
						for ( var ci = 1; ci <= totalOptions; ci++) {
							// don't erase user or default text in textbox controls
							//itemsForm.elements["property"+idx+"_" + prID + "_" + ci].value = "";
						}
					} else if (prControl == "TEXTBOX" || prControl == "TEXTAREA") {
						// don't erase user or default text in textbox controls
						//itemsForm.elements["property"+idx+"_" + prID].value = "";
					}
				}
			}
		} while (startSelectedNumber != selectedOptions.length);
	}

	returnValues[0] = selectedOptions;
	returnValues[1] = activeOptions;

	return returnValues;
}

function calculateOptionsPrice(itemsForm, idx, selectedOptions)
{
	var params = getProductParams(itemsForm, idx);
	var propertiesPrice = 0;
	var prPrice = 0;
	for (prID in selectedOptions) {
		if (itemsForm.elements["property_control"+idx+"_" + prID]) { // check if it is property control
			var usedControls = 0; var controlText = ""; var freeLetters = 0;
			var priceType = parseInt(itemsForm.elements["property_price_type"+idx+"_" + prID].value);
			var priceAmount = parseFloat(itemsForm.elements["property_price"+idx+"_" + prID].value);
			if (isNaN(priceAmount)) { priceAmount = 0; }
			var freePriceType = parseInt(itemsForm.elements["property_free_price_type"+idx+"_" + prID].value);
			var freePriceAmount = itemsForm.elements["property_free_price_amount"+idx+"_" + prID].value;
			var freeControls = 0;
			if (freePriceType == 1) {
				freePriceAmount = parseFloat(freePriceAmount);
			} else {
				freePriceAmount = parseInt(freePriceAmount);
			}
			if (isNaN(freePriceAmount)) { freePriceAmount = 0; }
			if (freePriceType == 2) {
				freeControls = freePriceAmount;
			} else if (freePriceType == 3 || freePriceType == 4) {
				freeLetters = freePriceAmount;
			}
	    
			var prControl = itemsForm.elements["property_control"+idx+"_" + prID].value;
			if (prControl == "LISTBOX" || prControl == "RADIOBUTTON") {
				usedControls++;
				prPrice = getOptionPrice(itemsForm, selectedOptions[prID]);
				propertiesPrice += prPrice;
			} else if (prControl == "CHECKBOXLIST" || prControl == "TEXTBOXLIST") {
				var values = selectedOptions[prID];
				for (valueId in values) {
					usedControls++;
					prPrice = getOptionPrice(itemsForm, valueId);
					propertiesPrice += prPrice;
					if (prControl == "TEXTBOXLIST") {
						controlText += selectedOptions[prID][valueId];
						if (freeControls >= usedControls) {
							if (priceType == 3) {
								freeLetters = controlText.length;
							} else if (priceType == 4) {
								freeLetters = controlText.replace(/[\n\r\t\s]/g, "").length;
							}
						}
					}
				}	
			} else {
				usedControls++;
				if (prControl == "TEXTAREA" || prControl == "TEXTBOX") {
					controlText = selectedOptions[prID];
					if (freeControls >= usedControls) {
						if (priceType == 3) {
							freeLetters = controlText.length;
						} else if (priceType == 4) {
							freeLetters = controlText.replace(/[\n\r\t\s]/g, "").length;
						}
					}
				}
			}
			if (priceType == 1) {
				propertiesPrice += priceAmount;
			} else if (priceType == 2) {
				if (usedControls > freeControls) {
					propertiesPrice += (priceAmount * (usedControls - freeControls));
				}
			} else if (priceType == 3) {
				var textLength = controlText.length;
				if (textLength > freeLetters) {
					propertiesPrice += (priceAmount * (textLength - freeLetters));
				}
			} else if (priceType == 4) {
				var textLength = controlText.replace(/[\n\r\t\s]/g, "").length;
				if (textLength > freeLetters) {
					propertiesPrice += (priceAmount * (textLength - freeLetters));
				}
			}
			if (freePriceType == 1) {
				propertiesPrice -= freePriceAmount;
			}
		}
	}	
	return propertiesPrice;
}

function changeQuantity(formName, itemIndex)
{
	changeProperty(formName, itemIndex);
}

function productsWin(pagename)
{
	var productsWin = window.open (pagename, 'productsWin', 'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=600,height=400');
	productsWin.focus();
}

function properyImageUpload(uploadUrl)
{
	var uploadWin = window.open (uploadUrl, 'uploadWin', 'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=600,height=400');
	uploadWin.focus();
}

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 getOptionPrice(itemForm, prValue)
{
	var optionPrice = 0;
	if (prValue != "") {
		if(itemForm.elements["option_price_" + prValue]) {
			optionPrice = parseFloat(itemForm.elements["option_price_" + prValue].value);
			if(isNaN(optionPrice)) {
				optionPrice = 0;
			}
		}
	}
	return optionPrice;
}

function getOptionValue(itemForm, valueName)
{
	var optionPrice = 0;
	if (valueName != "") {
		if(itemForm.elements[valueName]) {
			optionPrice = parseInt(itemForm.elements[valueName].value);
			if(isNaN(optionPrice)) {
				optionPrice = 0;
			}
		}
	}
	return optionPrice;
}

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 getParamValue(params, paramName, paramType)
{
	var paramValue = "";
	if (params[paramName]) {
		paramValue = params[paramName];
	}
	if (paramType == "int") {
		paramValue = parseInt(paramValue);
		if(isNaN(paramValue)) { paramValue = 0; }
	} else if (paramType == "float") {
		paramValue = parseFloat(paramValue);
		if(isNaN(paramValue)) { paramValue = 0; }
	}
	return paramValue;
}

function getProductParams(itemsForm, idx)
{
	var params = new Array();
	var paramsList = itemsForm.elements["product_params"+idx].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 = paramPair.substring(0, equalPos);
			var paramValue = paramPair.substring(equalPos + 1, paramPair.length);
			paramValue = paramValue.replace(/%0D/g, "\r");
			paramValue = paramValue.replace(/%0A/g, "\n");
			paramValue = paramValue.replace(/%27/g, "'");
			paramValue = paramValue.replace(/%22/g, "\"");
			paramValue = paramValue.replace(/%26/g, "&");
			paramValue = paramValue.replace(/%2B/g, "+");
			paramValue = paramValue.replace(/%25/g, "%");
			paramValue = paramValue.replace(/%3D/g, "=");
			paramValue = paramValue.replace(/%7C/g, "|");
			paramValue = paramValue.replace(/%23/g, "#");
			params[paramName] = paramValue;
		}
	}
	// check params values
	var checkParams = new Array();
	checkParams["base_price"] = 0;
	checkParams["crate"] = 1;
	checkParams["pe"] = 0;
	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["comp_price"] = 0;
	checkParams["comp_tax"] = 0;
	checkParams["base_points_price"] = 0;
	checkParams["base_reward_points"] = 0;
	checkParams["base_reward_credits"] = 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(e, obj, maxLength, limitType)
{
	var key;
	if (window.event) {
		key = window.event.keyCode; //IE
	} else {
		key = e.which; //Firefox
	}
	var objText = obj.value;
	var selectedText = "";
  if (obj.selectionEnd) {
    selectedText = objText.substring(obj.selectionStart, obj.selectionEnd);
  } else if (document.selection && document.selection.createRange) {
    selectedText = document.selection.createRange().text;
  } 
	if (limitType == 3 || limitType == 4) {
		selectedText = selectedText.replace(/[\n\r\t\s]/g, "");
	}
	if (selectedText.length > 0) {
		return true;
	}
	if (key == 0 || key == 8 || key == 9 || key == 16 || key == 17 || key == 35 || key == 36 || key == 37 || key == 39 || key == 46 || key == 116) {
		return true;
	}

	if (limitType == 3 || limitType == 4) {
		objText = objText.replace(/[\n\r\t\s]/g, "");
	}
  return (objText.length < maxLength);
}

function checkBoxesMaxLength(e, obj, formName, idx, prID, maxLength, limitType)
{
	var itemsForm = document.forms[formName];

	var key;
	if (window.event) {
		key = window.event.keyCode; //IE
	} else {
		key = e.which; //Firefox
	}

	var objText = obj.value;
	var selectedText = "";
	var selectedText = "";
  if (obj.selectionEnd) {
    selectedText = objText.substring(obj.selectionStart, obj.selectionEnd);
  } else if (document.selection && document.selection.createRange) {
    selectedText = document.selection.createRange().text;
  } 
	if (limitType == 3 || limitType == 4) {
		selectedText = selectedText.replace(/[\n\r\t\s]/g, "");
	}
	if (selectedText.length > 0) {
		return true;
	}

	if (key == 0 || key == 8 || key == 9 || key == 16 || key == 17 || key == 35 || key == 36 || key == 37 || key == 39 || key == 46 || key == 116) {
		return true;
	}

	var totalOptions = parseInt(itemForm.elements["property_total"+idx+"_" + prID].value);
	var totalLength = 0;
	for ( var ci = 1; ci <= totalOptions; ci++) {
		if (itemForm.elements["property"+idx+"_" + prID+ "_" + ci].value != "") {
			var valueText = itemForm.elements["property"+idx+"_" + prID+ "_" + ci].value;
			if (limitType == 3 || limitType == 4) {
				valueText = valueText.replace(/[\n\r\t\s]/g, "");
			}
			totalLength += valueText.length;
		}
	}
  return (totalLength < maxLength);
}

function moveSpecialOffer(e)
{
	var mousePos = getMousePos(e);
	var pageSize = getPageSize();
	var scrollSize = getScroll();

	var popObj = document.getElementById("popupBlock");
	if (popObj) {           
		popObj.style.display = "block";
		var blockWidth = popObj.offsetWidth;
		var blockHeight = popObj.offsetHeight;
		// get default position
		var posX = mousePos[0] + 30;
		var posY = mousePos[1] - blockHeight/2;
		// check better position 
		if (posY < scrollSize[1]) {
			posY = scrollSize[1];
		} else if (posY + blockHeight > pageSize[1] + scrollSize[1]) {
			posY -= (posY + blockHeight - pageSize[1] - scrollSize[1]);
		} 
		if (posX > pageSize[0] / 2) {
			posX = mousePos[0] - blockWidth - 30;
		}
		popObj.style.left = posX + "px";
		popObj.style.top  = posY + "px";
	}
}

function popupSpecialOffer(objName, displayValue)
{
	var scrollSize = getScroll();
	var itemObj = document.getElementById(objName);
	var popObj = document.getElementById("popupBlock");
	var soObj = document.getElementById("soPopupBox");
	if (displayValue == "block") {
		// delete popup block if it was initialized before
		var divTag = document.getElementById("popupBlock");
		if (divTag) {
			document.body.removeChild(divTag);
		}

		divTag = document.createElement("div");
		divTag.id = "popupBlock";
		divTag.className = itemObj.className;
		divTag.style.zIndex = "999";
		divTag.style.position = "absolute";
		divTag.style.left = "10px";
		divTag.style.top  = "10px";
		divTag.innerHTML = itemObj.innerHTML;
		document.body.insertBefore(divTag, document.body.firstChild);
	} else {
		var popupObj = document.getElementById("popupBlock");
		if (popupObj) {
			document.body.removeChild(popupObj);
		}
	}
}
