/**
	Costants used to define debug output. Set isDebug to true to show
	debug output dialogs. Set isCheckTime to true in order to provide
	timestamps.
 */

/**
	Global variables:
	
	productItems		->	Array of ProductInfo objects (products) to be showned.
 */
var productItems = null;
var trolleyProductItems = null;
var changedFields = false;
var checkoutPage = null;

/**
	Option value that can influence product price.
*/
function priceOption(productOptionId, rate, optionString)
{
	this.productOptionId = productOptionId;
	this.rate = rate;
	this.optionString = optionString;
}

/**
	The object stores every information needed to display a single product
	(with additional informations about option values and groups):

	idProduct					product id.
	imageName					image file name.
	unitPrice			original product price for unit of size.
	unitPriceText				original unit price label.<b> 
	retailPrice					current retail price.
	originalRetailPrice			original retail price.
	maxOrderQuantity			maximum number of product items that can
								be added to the trolley.
	isPromotion					promotion flag (needed in order to show
								cutted prices).
	priceOptions				array of prices that can modify product
								price.	
 */
function productInfo(	storeId, idProduct, originalQuantity, outOfStock, hasExtendedDetails, imageName, unitPrice, unitPriceText, retailPrice, originalRetailPrice, maxOrderQuantity, isPromotion, priceOptions,
						isShowing, parentIndex, name, comboName, filter, bio, esselungaBrand, naturama, readyToCook, readyToEat, familyPack, ethicallySourced, light, fidelityBrand, esseExclusive, raee,
						relatedProductFlag, packaging, multipack, unitText, deliveryExceptionString, currentLeadTime, leadtimeImage, leadtimeTooltip, isLimitedGroup, limitedGroupDescription, bitmapFileName1, bitmapTooltip1, bitmapFileName2, bitmapTooltip2,
						promotionImages)
{
	this.storeId = storeId;

	this.originalQuantity = originalQuantity;

	this.idProduct = idProduct;
	this.hasExtendedDetails = hasExtendedDetails;

	this.outOfStock = outOfStock;

	this.imageName = imageName;

	this.unitPrice = unitPrice;
	this.unitPriceText = unitPriceText;
	
	this.retailPrice = retailPrice;
	this.originalRetailPrice = originalRetailPrice;
	
	this.maxOrderQuantity = maxOrderQuantity;

	this.isPromotion = isPromotion;
	
	this.priceOptions = priceOptions;
	
	this.isShowing = isShowing;
	this.parentIndex = parentIndex;

	this.name = name;
	this.comboName = comboName;
	this.filter = filter;

	this.packaging = packaging;
	this.multipack = multipack;
	this.unitText = unitText;

	this.bio = bio;
	this.esselungaBrand = esselungaBrand;
	this.naturama = naturama;
	this.readyToCook = readyToCook;
	this.readyToEat = readyToEat;
	this.familyPack = familyPack;
    this.raee = raee;
    this.ethicallySourced = ethicallySourced;
	this.light = light;
	this.fidelityBrand = fidelityBrand;
	this.esseExclusive = esseExclusive;
	this.relatedProductFlag = relatedProductFlag;
	this.deliveryDayException = deliveryExceptionString;
	this.currentLeadTime = currentLeadTime;
	this.leadtimeTooltip = leadtimeTooltip;
	this.leadtimeImage = leadtimeImage;

	this.isLimitedGroup = isLimitedGroup;
	this.limitedGroupDescription = limitedGroupDescription;

	this.bitmapFileName1 = bitmapFileName1;
	this.bitmapTooltip1 = bitmapTooltip1;
	this.bitmapFileName2 = bitmapFileName2;
	this.bitmapTooltip2 = bitmapTooltip2;
	
	this.promotionImages = promotionImages;
}


function productInfoSlot(idProduct, storeId, name, maxOrderQuantity, singleOption, priceOptions)
{
    this.idProduct = idProduct;
    this.storeId = storeId;
    this.name = name;

    this.maxOrderQuantity = maxOrderQuantity;

    this.singleOption = singleOption;
    this.priceOptions = priceOptions;
}


/**
	The object stores every information needed to display a single product
	(with additional informations about option values and groups):

	idProduct					product id.
	imageName					image file name.
	unitPrice			original product price for unit of size.
	unitPriceText				original unit price label.<b>
	retailPrice					current retail price.
	originalRetailPrice			original retail price.
	maxOrderQuantity			maximum number of product items that can
								be added to the trolley.
	isPromotion					promotion flag (needed in order to show
								cutted prices).
	priceOptions				array of prices that can modify product
								price.
 */
function productInfoTrly(	storeId, idProduct, quantity, imageName, unitPrice, unitPriceText, retailPrice, originalRetailPrice, maxOrderQuantity, isPromotion,
							priceOptionId, priceOptionRate, priceOptionString, otherOptionsArray,
							isShowing, parentIndex,
							name, bio, esselungaBrand, naturama, readyToCook, readyToEat, familyPack, ethicallySourced, light, fidelityBrand, esseExclusive, raee,
							relatedProductFlag, bitmapFileName1, bitmapTooltip1, bitmapFileName2, bitmapTooltip2)
{
	this.storeId = storeId;

	this.idProduct = idProduct;

	this.quantity = quantity;
	this.originalQuantity = quantity;

	this.imageName = imageName;

	this.unitPrice = unitPrice;
	this.unitPriceText = unitPriceText;

	this.retailPrice = retailPrice;
	this.originalRetailPrice = originalRetailPrice;

	this.maxOrderQuantity = maxOrderQuantity;

	this.isPromotion = isPromotion;

	this.priceOptionId = priceOptionId;
	this.priceOptionRate = priceOptionRate;
	this.priceOptionString = priceOptionString;
	this.otherOptionsArray = otherOptionsArray;

	this.isShowing = isShowing;
	this.parentIndex = parentIndex;

	this.name = name;
	this.bio = bio;
	this.esselungaBrand = esselungaBrand;
	this.naturama = naturama;
	this.readyToCook = readyToCook;
	this.readyToEat = readyToEat;
	this.familyPack = familyPack;
	this.ethicallySourced = ethicallySourced;
	this.light = light;
	this.fidelityBrand = fidelityBrand;
	this.esseExclusive = esseExclusive;
	this.relatedProductFlag = relatedProductFlag;
    this.raee = raee;

    this.bitmapFileName1 = bitmapFileName1;
	this.bitmapTooltip1 = bitmapTooltip1;
	this.bitmapFileName2 = bitmapFileName2;
	this.bitmapTooltip2 = bitmapTooltip2;
}


/**
	Initialize elements position and dimension.
 */
function initWorkArea()
{
    //	Set rows highlighting.
	initRowHighLight();

    //	Initialize products tree if needed.
    //noinspection JSUnusedLocalSymbols
    try {
        if(menuItems != null) initMenu();
    } catch(e) { /* nothing */ }

	//	Switch from standard alt titles for promotions to overdivs.
	switchDivDetails(null, checkoutPage ? DIVIMGOVER_DETAILS_ALL_TAGS : DIVIMGOVER_DETAILS_DEFAULT_TAGS);

	//	Perform final resize (Handle safari bug).
	resizeWorkArea();

	//	Scroll to the correct product if needed.
	scrollToProduct();
}

function initWorkAreaProducts()
{
	//	Set rows highlighting.
	initRowHighLight();
}
 

/**
	Scrolling to specified product if any.
*/
function scrollToProduct()
{
	var positionY = 0;

	//noinspection JSUnusedLocalSymbols
    try
	{
		//	Retrieve the index of the product to scroll to
		if(productScrollTo != null)
		{
			//	Retireve product container.
			var scrollToElement = document.getElementById("js-eviddiv-" + productScrollTo);

			if(scrollToElement != null)
			{
				//	Find position and perform scroll.
				positionY = parseInt(findPosY(scrollToElement));

				if(positionY > 0) {
					var workarea = document.getElementById("workareabody");
					workarea.scrollTop = positionY - 90;
				}
			}

			//	Open dialog popup.
            //var productId = productItems[productScrollToRealIndex].idProduct;
			//showProductInfoDialog(productId);

			//	Change style
			var productName = document.getElementById("js-name-content-" + productScrollTo);
			productName.className = "productnameinfoevid";
		}
	}
	catch(e) { /* Nothing */ }
}


/**
	Show order blocker
*/
function showOrderBlockerPopupIfAny()
{
	//	Show the order blocker popup.
	openPopup(showOrderBlockerPopupUrl, "orderblocker", 486, 185);
}

/**
 *  Show delivery errors
 */
function showDeliveryErrorsPopup()
{
    openPopupWithScroll(showDeliveryErrorsPopupUrl, "deliveryerrors", 486, 385);
}


/**
	Resize header and body div.
*/
var RESIZE_HEADER_TAG = "header";
var RESIZE_BODY_TAG = "header";

function resizeHeaderDiv()
{
    resizeDivs(RESIZE_HEADER_TAG);
}

function resizeBodyDiv()
{
    resizeDivs(RESIZE_BODY_TAG);
}

function resizeDivs(divToResize)
{
    var resizeHeader = true;
    var resizeBody = true;

    //noinspection JSUnusedLocalSymbols
    try {
        if(divToResize != null) {
            resizeHeader = (divToResize == RESIZE_HEADER_TAG);
            resizeBody = !resizeHeader;
        }
    } catch(e) { /* nothing */ }

    var frameHeight = document.body.clientHeight;

    var headerDiv = document.getElementById("workareaheader");
    var bodyDiv = document.getElementById("workareabody");

    if(headerDiv && bodyDiv)
    {
        var newHeaderHeight = 0;

        if(parseInt(frameHeight) < 90) {
            //	Reset header height - the only visible part will be the body.
            newHeaderHeight = 0;
        } else {
            //	Resize header height according to default height (if provided).
            //  DON'T EVEN CONSIDER ADDING VARIABLE DECLARATION ('var') - It would overwrite the actual value defined in the
            //  jsp...
            if(headerDivDefaultHeight == 'undefined') headerDivDefaultHeight = 0;
            newHeaderHeight = Math.round((headerDivDefaultHeight * 100) / parseInt(frameHeight));
        }

        if(resizeHeader) headerDiv.style.height = newHeaderHeight + "%";
        if(resizeBody) bodyDiv.style.height = (100 - newHeaderHeight) + "%";
    }
    else if(bodyDiv) {
        //	Resize body div.
        if(resizeBody) bodyDiv.style.height = "100%";
    }
}


/**
	Handle onResize event.
*/
function resizeWorkArea()
{
	//	Hide both dialogs.
	hideDialogs();

	//	Resize header and body divs.
	resizeDivs();
}


/**
	Provide row highlight. 
*/
function initRowHighLight()
{
    var targetIds = new Array("producttable", "weekProductTable", "trolleyProductTable");
    targetIds.each(function(element) {
        var targetTable = document.getElementById(element);
        if(targetTable != null) {
            var rowsArray = targetTable.getElementsByTagName("tr");

            for(var i = 0; i < rowsArray.length; i++)
            {
                if(rowsArray[i].className == "producttable")
                {
                    rowsArray[i].onmouseover = function() {this.className='producttableruled'; return false;};
                    rowsArray[i].onmouseout = function() {this.className='producttable'; return false;};
                }
            }
        }
    });
}


/**
	Switch image and euro flag.
*/
function switchProductImages(showImages)
{
    if(productItems != null) {
		//	Show images.
		for(var i = 0; i < productItems.length; i++)
		{
			if(productItems[i].isShowing) {
				var currentImageDiv = document.getElementById("js-image-" + productItems[i].parentIndex);
                if(currentImageDiv) {
                    var oldsrc = currentImageDiv.getElementsByTagName("img")[0].src;
                    var path = oldsrc.substr( 0, oldsrc.lastIndexOf('/') + 1 );
                    currentImageDiv.innerHTML = showImages ?
                                                '<img title="' + ((productItems[i].hasExtendedDetails) ? productDetailTooltip : productDetailTooltipSimple) + '" onclick="javascript: showProductInfoDialog(' + productItems[i].idProduct  + ', ' + productItems[i].storeId + ');" class="productextrainfo" src="' + path + productItems[i].imageName + '.jpg' + '" />' :
                                                '';
                }
			}
		}
	}
}

function updateServerSideFlags() {
    //	Update server side flags.
    var newSubmitDataUrl = submitDataUrl;

    if(top.imageFlag != null && top.euroFlag != null)
    {
        newSubmitDataUrl += "?imageFlag=" + (top.imageFlag ? "TRUE" : "FALSE") +
                            "&euroFlag=" + (top.euroFlag ? "TRUE" : "FALSE");
    }
    else
    {
        if(top.imageFlag != null) newSubmitDataUrl += "?imageFlag=" + (top.imageFlag ? "TRUE" : "FALSE");
        if(top.euroFlag != null) newSubmitDataUrl += "?euroFlag=" + (top.euroFlag ? "TRUE" : "FALSE");
    }

    top.submitframe.location.href = newSubmitDataUrl;
}

function switchImageFlag(imageCheckBox)
{
	//	Hide dialogs.
	hideDialogs();

    var showImages = imageCheckBox.checked == 1;

    imageCheckBox.value = showImages ? 1 : 0;
    top.imageFlag = showImages;
    switchProductImages(showImages);

    var associatedMessage = document.getElementById("switchImagesText");
	if(showImages) {
        imageCheckBox.title = hideImagesCheckboxTooltip;
        associatedMessage.title = hideImagesMsgTooltip;
	} else {
		imageCheckBox.title = showImagesCheckboxTooltip;
		associatedMessage.title = showImagesMsgTooltip;
	}

    updateServerSideFlags();
}

function switchEuroFlag(euroCheckBox)
{
	//	Hide dialogs.
	hideDialogs();

    var showLire = euroCheckBox.checked == 1;

    euroCheckBox.value = showLire ? 0 : 1;
    top.euroFlag = !showLire;

    //	Update product prices.
    updateProductPrices();
    //top.bottomframeleft.updateTotalPrice();

    var associatedMessage = document.getElementById("switchEuroText");
	if(showLire) {
		euroCheckBox.title = euroCheckboxTooltip;
		associatedMessage.title = euroMsgTooltip;
	} else {
		euroCheckBox.title = liraCheckboxTooltip;
		associatedMessage.title = liraMsgTooltip;
	}

    updateServerSideFlags();
}


/**
	Update product prices.
*/
function updateProductPrices()
{
	//	Show prices for all the products in list (if any).
	if(productItems != null)
	{
		for(var i = 0; i < productItems.length; i++)
		{
			if(productItems[i].isShowing && productItems[i].storeId != -1)
			{
				//	Update unit prices (below product description).
				var currentOrgPriceSpan = document.getElementById("js-orgUnitPrice-" + productItems[i].parentIndex);
				var currentPriceSpanText = document.getElementById("js-unitPriceText-" + productItems[i].parentIndex);

				if(currentOrgPriceSpan && currentPriceSpanText && productItems[i].unitPrice != 0)
				{
					if(top.euroFlag)
					{
						currentOrgPriceSpan.innerHTML = "Euro " + formatEuro(productItems[i].unitPrice) + " ";
						currentPriceSpanText.innerHTML = "" + productItems[i].unitPriceText.substring(4);
					}
					else
					{
						currentOrgPriceSpan.innerHTML = "Lire " + formatLire(Math.round(productItems[i].unitPrice * 1936.27)) + " ";
						currentPriceSpanText.innerHTML = "" + productItems[i].unitPriceText.substring(4);
					}
				}

				//	Update unit prices... if any (combo box for products associated by group id).
				var productsByGroupSelect = document.getElementById("js-productInGroup-" + productItems[i].parentIndex);

				if(productsByGroupSelect != null)
				{
					var arrayOfIndex = new Array();

					for(var z = 0; z < productsByGroupSelect.options.length; z++)
					{
						arrayOfIndex.push(productsByGroupSelect.options[z].value);
					}

					//	Build new options.
					for(var eraseIndex = productsByGroupSelect.options.length - 1; eraseIndex >= 0; eraseIndex--)
					{
						productsByGroupSelect.options[eraseIndex] = null;
					}

					for(var jk = 0; jk < arrayOfIndex.length; jk++)
					{
						var optionString = "";
						var priceString = "";

						if(top.euroFlag)
						{
							priceString = (productItems[arrayOfIndex[jk]].unitPrice != 0.0 ? "  " + formatEuro(productItems[arrayOfIndex[jk]].unitPrice)+ " Euro" + productItems[arrayOfIndex[jk]].unitPriceText.substring(4) : "");
						}
						else
						{
							priceString = (productItems[arrayOfIndex[jk]].unitPrice != 0.0 ? "  " + formatLire(Math.round(productItems[arrayOfIndex[jk]].unitPrice * 1936.27))+ " Lire" + productItems[arrayOfIndex[jk]].unitPriceText.substring(4) : "");
						}

						//	Used to change html entities to their corresponding values (in order to handle ' and ").
						var comboNameValue = productItems[arrayOfIndex[jk]].comboName;
						comboNameValue = comboNameValue.replace(/&#039;/g, "'");
						comboNameValue = comboNameValue.replace(/&#034;/g, '"');
						comboNameValue = comboNameValue.replace(/&amp;/g, '&');

						if(productItems[arrayOfIndex[jk]].priceOptions != null)
						{
							optionString = 	(productItems[arrayOfIndex[jk]].packaging != "" ? productItems[arrayOfIndex[jk]].packaging + " " : "") +
											productItems[arrayOfIndex[jk]].priceOptions[0].optionString +
											priceString;
						}
						else
						{
							optionString = 	comboNameValue +
											(productItems[arrayOfIndex[jk]].packaging != "" ? productItems[arrayOfIndex[jk]].packaging : "") +
											(productItems[arrayOfIndex[jk]].multipack != "" ? " " + productItems[arrayOfIndex[jk]].multipack + " " + productItems[arrayOfIndex[jk]].unitText : "") +
											priceString;
						}

						productsByGroupSelect.options[jk] = new Option(optionString, arrayOfIndex[jk]);
					}
				}

				//	Update actual prices.
				var currentActualPrice = document.getElementById("js-actualPrice-" + productItems[i].parentIndex);
				var currentActualPriceText = document.getElementById("js-actualPriceText-" + productItems[i].parentIndex);
	
				var currentCutPrice = document.getElementById("js-cutPrice-" + productItems[i].parentIndex);
				var currentCutPriceText = document.getElementById("js-cutPriceText-" + productItems[i].parentIndex);

				if(currentActualPrice && currentCutPrice && currentActualPriceText && currentCutPriceText)
				{
					var currentRate = 1.0;

					if(productItems[i].priceOptions != null)
					{
						if(productItems[i].priceOptions.length > 1)
						{
							var currentOptionPriceSelected = document.getElementById("js-optionPrice-" + productItems[i].parentIndex);
	
							for(var j = 0; j < productItems[i].priceOptions.length; j++)
							{
								if(productItems[i].priceOptions[j].productOptionId == currentOptionPriceSelected.value)
								{
									currentRate = productItems[i].priceOptions[j].rate;
									break;
								}
							}
						}
						else
						{
							currentRate = productItems[i].priceOptions[0].rate;
						}
					}

					if(productItems[i].retailPrice != productItems[i].originalRetailPrice)
					{
						if(top.euroFlag)
						{
							currentActualPrice.innerHTML = formatEuro(Math.round(productItems[i].retailPrice * currentRate * 100) / 100);
							currentActualPriceText.innerHTML = "Euro&nbsp;";

							currentCutPrice.innerHTML = formatEuro(Math.round(productItems[i].originalRetailPrice * currentRate * 100) / 100);
							currentCutPriceText.innerHTML = "Euro&nbsp;";
						}
						else
						{
							currentActualPrice.innerHTML = formatLire(Math.round(productItems[i].retailPrice * 1936.27 * currentRate));
							currentActualPriceText.innerHTML = "Lire&nbsp;";

							currentCutPrice.innerHTML = formatLire(Math.round(productItems[i].originalRetailPrice * 1936.27 * currentRate));
							currentCutPriceText.innerHTML = "Lire&nbsp;";
						}
					}
					else
					{					
						if(top.euroFlag)
						{
							currentActualPrice.innerHTML = formatEuro(Math.round(productItems[i].retailPrice * currentRate * 100) / 100);
							currentActualPriceText.innerHTML = "Euro&nbsp;";

							currentCutPrice.innerHTML = "";
							currentCutPriceText.innerHTML = "";
						}
						else
						{
							currentActualPrice.innerHTML = formatLire(Math.round(productItems[i].retailPrice * 1936.27 * currentRate));
							currentActualPriceText.innerHTML = "Lire&nbsp;";

							currentCutPrice.innerHTML = "";
							currentCutPriceText.innerHTML = "";
						}
					}
				}
			}
		}
	}
}


/**
	Update single price.
*/
function updateSinglePrice(currentEvent, productInfo)
{
    productInfo = (productInfo != null ? productInfo : productItems);

    //	Retrieve source tag and its identifier.
	var sourceTag = getSourceByEvent(currentEvent);

	var sourceTagId = sourceTag.id;
	var sourceTagComponents = sourceTagId.split("-");

	var productIndex = sourceTagComponents[2];
    var arrayIndex = checkoutPage ? productIndex - firstWeekItem : productIndex;

	//	Update actual prices.
	var currentActualPrice = document.getElementById("js-actualPrice-" + productIndex);
	var currentActualPriceText = document.getElementById("js-actualPriceText-" + productIndex);
			
	var currentCutPrice = document.getElementById("js-cutPrice-" + productIndex);
	var currentCutPriceText = document.getElementById("js-cutPriceText-" + productIndex);

	if(currentActualPrice && currentCutPrice && currentActualPriceText && currentCutPriceText)
	{
		var currentRate = 1.0;

		for(var j = 0; j < productItems[arrayIndex].priceOptions.length; j++)
		{
			if(productItems[arrayIndex].priceOptions[j].productOptionId == sourceTag.value)
			{
				currentRate = productItems[arrayIndex].priceOptions[j].rate;
				break;
			}
		}
	}

	if(productItems[arrayIndex].retailPrice != productItems[arrayIndex].originalRetailPrice)
	{
		if(top.euroFlag || checkoutPage)
		{
			currentActualPrice.innerHTML = formatEuro(Math.round(productItems[arrayIndex].retailPrice * currentRate * 100) / 100);
			currentActualPriceText.innerHTML = "Euro ";
						
			currentCutPrice.innerHTML = formatEuro(Math.round(productItems[arrayIndex].originalRetailPrice * currentRate * 100) / 100);
			currentCutPriceText.innerHTML = "Euro ";
		}
		else
		{
			currentActualPrice.innerHTML = formatLire(Math.round(productItems[arrayIndex].retailPrice * 1936.27 * currentRate));
			currentActualPriceText.innerHTML = "Lire ";
					
			currentCutPrice.innerHTML = formatLire(Math.round(productItems[arrayIndex].originalRetailPrice * 1936.27 * currentRate));
			currentCutPriceText.innerHTML = "Lire ";
		}
	}
	else
	{					
		if(top.euroFlag || checkoutPage)
		{
			currentActualPrice.innerHTML = formatEuro(Math.round(productItems[arrayIndex].retailPrice * currentRate * 100) / 100);
			currentActualPriceText.innerHTML = "Euro ";
						
			currentCutPrice.innerHTML = "";
			currentCutPriceText.innerHTML = "";
		}
		else
		{
			currentActualPrice.innerHTML = formatLire(Math.round(productItems[arrayIndex].retailPrice * 1936.27 * currentRate));
			currentActualPriceText.innerHTML = "Lire ";
				
			currentCutPrice.innerHTML = "";
			currentCutPriceText.innerHTML = "";
		}
	}
}


/**
	Update single price.
*/
function updateProductInGroupPrice(productIndex)
{
	//	Update actual prices.
	var currentActualPrice = document.getElementById("js-actualPrice-" + productItems[productIndex].parentIndex);
	var currentActualPriceText = document.getElementById("js-actualPriceText-" + productItems[productIndex].parentIndex);
			
	var currentCutPrice = document.getElementById("js-cutPrice-" + productItems[productIndex].parentIndex);
	var currentCutPriceText = document.getElementById("js-cutPriceText-" + productItems[productIndex].parentIndex);

	var currentRate = 1.0;

	if(productItems[productIndex].priceOptions != null)
	{
		currentRate = productItems[productIndex].priceOptions[0].rate;
	}

	if(productItems[productIndex].retailPrice != productItems[productIndex].originalRetailPrice)
	{
		if(top.euroFlag || checkoutPage)
		{
			currentActualPrice.innerHTML = formatEuro(Math.round(productItems[productIndex].retailPrice * currentRate * 100) / 100);
			currentActualPriceText.innerHTML = "Euro&nbsp;";
						
			currentCutPrice.innerHTML = formatEuro(Math.round(productItems[productIndex].originalRetailPrice * currentRate * 100) / 100);
			currentCutPriceText.innerHTML = "Euro&nbsp;";
		}
		else
		{
			currentActualPrice.innerHTML = formatLire(Math.round(productItems[productIndex].retailPrice * 1936.27 * currentRate));
			currentActualPriceText.innerHTML = "Lire&nbsp;";
					
			currentCutPrice.innerHTML = formatLire(Math.round(productItems[productIndex].originalRetailPrice * 1936.27 * currentRate));
			currentCutPriceText.innerHTML = "Lire&nbsp;";
		}
	}
	else
	{					
		if(top.euroFlag || checkoutPage)
		{
			currentActualPrice.innerHTML = formatEuro(Math.round(productItems[productIndex].retailPrice * currentRate * 100) / 100);
			currentActualPriceText.innerHTML = "Euro&nbsp;";
						
			currentCutPrice.innerHTML = "";
			currentCutPriceText.innerHTML = "";
		}
		else
		{
			currentActualPrice.innerHTML = formatLire(Math.round(productItems[productIndex].retailPrice * 1936.27 * currentRate));
			currentActualPriceText.innerHTML = "Lire&nbsp;";
				
			currentCutPrice.innerHTML = "";
			currentCutPriceText.innerHTML = "";
		}
	}
}


/**
	Change product being showned in a group.
*/
function updateProductInGroup(currentEvent)
{
	//	Retrieve source tag and its identifier.
	var sourceTag = getSourceByEvent(currentEvent);

	var sourceTagId = sourceTag.id;
	var sourceTagComponents = sourceTagId.split("-");

	var productIndex = sourceTagComponents[2];
    var parentIndex = checkoutPage ? productIndex - firstWeekItem : productIndex;

	for(var i = parentIndex; i < productItems.length; i++)
	{
		if(productItems[i].parentIndex == productIndex)
		{
			if(sourceTag.value == (checkoutPage ? i + firstWeekItem : i))
			{
				productItems[i].isShowing = true;

				//	Product details tooltip.
				var tooltip = ( productItems[i].hasExtendedDetails ? productDetailTooltip : productDetailTooltipSimple );

				//	Update product.
				var formWeekItem = document.forms["bodyForm"].elements["weekItemId-" + productItems[i].parentIndex];
				if(formWeekItem != null) {
					formWeekItem.value = productItems[i].idProduct;
				}

				//	Update image.
				if(top.imageFlag || checkoutPage)
				{
					var currentImageDiv = document.getElementById("js-image-" + productItems[i].parentIndex);
                    var oldsrc = currentImageDiv.getElementsByTagName("img")[0].src;
                    var path = oldsrc.substr( 0, oldsrc.lastIndexOf('/') + 1 );
					currentImageDiv.innerHTML = '<img title="' + tooltip + '" onclick="javascript: showProductInfoDialog(' + productItems[i].idProduct + ', ' + productItems[i].storeId + ');" class="' + (checkoutPage ? 'weekproductextrainfo' : 'productextrainfo') + '" src="' + path + productItems[i].imageName + '.jpg' + '"/>';
				}

				//	Update info flag.
				var currentInfoTextDiv = document.getElementById("js-infoprod-" + productItems[i].parentIndex);
				if(currentInfoTextDiv)
				{
					if(productItems[i].hasExtendedDetails)
					{
						currentInfoTextDiv.innerHTML = '<img title="' + tooltip + '" onclick="javascript: showProductInfoDialog(' + productItems[i].idProduct + ', ' + productItems[i].storeId + ');" class="' + (checkoutPage ? 'weekproductextrainfo' : 'productextrainfo') + '" src="' + layoutImagesUrl + 'info_scheda.gif" width="16" height="16" border="0" alt="">';
					}
					else
					{
						currentInfoTextDiv.innerHTML = '<img src="' + layoutImagesUrl + 's.gif" width="16" height="16" border="0" alt="" />';
					}
				}

				//	Update name status.
				currentInfoTextDiv = document.getElementById("js-name-" + productItems[i].parentIndex);
				if(currentInfoTextDiv)
				{
					currentInfoTextDiv.innerHTML = '<a title="' + tooltip + '" class="productnameinfo" href="javascript: showProductInfoDialog(' + productItems[i].idProduct + ', ' + productItems[i].storeId + ');"><b>' + productItems[i].name + '</b></a>';
				}

                //	Update raee information.
                currentInfoTextDiv = document.getElementById("js-raee-info-" + productItems[i].parentIndex);
                if(currentInfoTextDiv)
                {
                    currentInfoTextDiv.innerHTML = (productItems[i].raee ?
                                                    '- <a class="raeeinfo" title="' + raeeTooltip + '" target="_eco_contributo_raee" href="/docs/eco_contributo_raee.pdf">Eco contributo RAEE incluso</a> '+
                                                    '- <a class="raeeinfo" title="' + raee1contro1Tooltip + '" target="_eco_1_contro_1_raee" href="/docs/uno_contro_uno.pdf">Informativa RAEE 1 contro 1</a> -'
                                                    :
                                                    '');
                }

				//	Update price.
				updateProductInGroupPrice(i);

				//	Update flags.
				var flagAreaDiv = document.getElementById("js-flags-" + productItems[i].parentIndex);

				var newFlagConfiguration = 	(productItems[i].esseExclusive ? '<img title="' + prezblocTooltip + '" class="flagimg" src="' + layoutImagesUrl + 'prod_icons/bloccato.gif"/>': '') +
											((productItems[i].bio && !productItems[i].esselungaBrand) ? '<img title="' + prodagrbioTooltip + '" class="flagimg" src="' + layoutImagesUrl + 'prod_icons/bio.gif"/>' : '') +
											((productItems[i].bio && productItems[i].esselungaBrand) ? '<img title="' + essbioTooltip + '" class="flagimg" src="' + layoutImagesUrl + 'prod_icons/essbio.gif"/>' : '') +
											(((!productItems[i].bio && productItems[i].esselungaBrand) || productItems[i].naturama) ? '<img title="' + essbrandTooltip + '" class="flagimg" src="' + layoutImagesUrl + 'prod_icons/essbrand.gif"/>' : '') +
											(productItems[i].naturama ? '<img title="' + naturamaTooltip + '" class="flagimg" src="' + layoutImagesUrl + 'prod_icons/naturama.gif"/>': '') +
											(productItems[i].readyToCook ? '<img title="' + readytocookTooltip + '" class="flagimg" src="' + layoutImagesUrl + 'prod_icons/readytocook.gif"/>': '') +
											(productItems[i].readyToEat ? '<img title="' + readytoeatTooltip + '" class="flagimg" src="' + layoutImagesUrl + 'prod_icons/readytoeat.gif"/>': '') +
											(productItems[i].familyPack ? '<img title="' + fampackTooltip + '" class="flagimg" src="' + layoutImagesUrl + 'prod_icons/fampack.gif"/>': '') +
											(productItems[i].ethicallySourced ? '<img title="' + ethsourceTooltip + '" class="flagimg" src="' + layoutImagesUrl + 'prod_icons/ethsource.gif"/>': '') +
											(productItems[i].light ? '<img title="' + liteTooltip + '" class="flagimg" src="' + layoutImagesUrl + 'prod_icons/lite.gif"/>': '') +
											(productItems[i].fidelityBrand ? '<img title="' + fidelbrandTooltip + '" class="flagimg" src="' + layoutImagesUrl + 'prod_icons/fidelbrand.gif"/>': '');

											if(productItems[i].currentLeadTime != 0)
											{
												newFlagConfiguration += '<img class="flagimg" src="' + layoutImagesUrl + 'prod_icons/' + productItems[i].leadtimeImage + '" title="' + productItems[i].leadtimeTooltip + '" />';
											}
											
											if(productItems[i].isLimitedGroup != 0)
											{
												newFlagConfiguration += '<img class="flagimg" src="' + layoutImagesUrl + 'prod_icons/deliveryGL.gif" title="' + limitedProductGroupTooltip + ' \'' + productItems[i].limitedGroupDescription +  '\'" />';
											}

											if(productItems[i].deliveryDayException != "")
											{
												newFlagConfiguration += productItems[i].deliveryDayException;
											}

				//	Update filter flag.
				flagAreaDiv.innerHTML = newFlagConfiguration;

				//	Update filter flag.
				var filterAreaSpan = document.getElementById("js-filter-" + productItems[i].parentIndex);
				if(filterAreaSpan != null) {
					filterAreaSpan.innerHTML = productItems[i].filter;
				}

				//	Update promotions.
				var promoAreaDiv = document.getElementById("js-offerte-" + productItems[i].parentIndex);

				var newPromoArea = "";
				if(productItems[i].bitmapFileName1 != null)
				{
					newPromoArea += '<img src="' + layoutImagesUrl + 'prod_icons/' + productItems[i].bitmapFileName1 + '" title="' + productItems[i].bitmapTooltip1.replace(/^\s*/g, '').replace(/\s*$/g, '') + '" class="promoimg" />';
				}
				if(productItems[i].bitmapFileName2 != null)
				{
					if(productItems[i].bitmapFileName1 != null) newPromoArea += '&nbsp;';

					newPromoArea += '<img src="' + layoutImagesUrl + 'prod_icons/' + productItems[i].bitmapFileName2 + '" title="' + productItems[i].bitmapTooltip2.replace(/^\s*/g, '').replace(/\s*$/g, '') + '" class="promoimg" />';
				}
				if(productItems[i].promotionImages != '')
				{
					newPromoArea += productItems[i].promotionImages;
				}
				promoAreaDiv.innerHTML = newPromoArea;

				//	Retrieve all tags having.
				switchDivDetails(promoAreaDiv, checkoutPage ? DIVIMGOVER_DETAILS_ALL_TAGS : DIVIMGOVER_DETAILS_DEFAULT_TAGS);

				//	Update fields related to 'outOfStock'.
				var quantityArea = document.getElementById("js-quantity-" + productItems[i].parentIndex);
				var increaseArea = document.getElementById("js-div-increase-" + productItems[i].parentIndex);
				var decreaseArea = document.getElementById("js-div-decrease-" + productItems[i].parentIndex);
				var addToTrolleyArea = document.getElementById("js-div-addtotrolley-" + productItems[i].parentIndex);

				if(productItems[i].outOfStock)
				{
					quantityArea.innerHTML = '<input readonly="readonly" title="' + notAvailTooltip + '" class="productinputqtydisabled" type="text" size="1" maxlength="3" value="X" />';
					increaseArea.innerHTML = '<img width="12" height="12" border="0" title="' + notAvailTooltip + '" src="' + layoutImagesUrl + 'piu_disab.gif" />';
					decreaseArea.innerHTML = '<img width="12" height="12" border="0" title="' + notAvailTooltip + '" src="' + layoutImagesUrl + 'meno_disab.gif" />';
					addToTrolleyArea.innerHTML = '<img width="19" height="19" border="0" title="' + notAvailTooltip + '" src="' + layoutImagesUrl + 'carrello_disab.gif" />';
				}
				else
				{
					if(checkoutPage) {
						quantityArea.innerHTML = '<input title="' + inputQuantityTooltip + '" class="productinputqty" id="js-prodinputqty-' + productItems[i].parentIndex + '" onchange="javascript: newQuantityCheckout(' + productItems[i].parentIndex + ');" onkeypress="return pressReturnOnInputTextCheckout(event)" type="text" size="1" maxlength="3" value="1" />';
						increaseArea.innerHTML = '<img title="' + incQuantityTooltip + '" class="weekselectableimage" width="12" height="12" border="0" id="js-increase-' + productItems[i].parentIndex + '" onclick="javascript: increaseQuantity(' + productItems[i].parentIndex + ');" title="Incrementa la quantita\'" src="' + layoutImagesUrl + 'piu.gif" />';
						decreaseArea.innerHTML = '<img title="' + decQuantityTooltip + '" class="weekselectableimage" width="12" height="12" border="0" id="js-decrease-' + productItems[i].parentIndex + '" onclick="javascript: decreaseQuantity(' + productItems[i].parentIndex + ');" title="Decrementa la quantita\'" src="' + layoutImagesUrl + 'meno.gif" />';
						addToTrolleyArea.innerHTML = '<img title="' + addToTrolleyTooltip + '" class="weekselectableimage" width="19" height="19" border="0" id="js-addtotrolley-' + productItems[i].parentIndex + '" onclick="javascript: addToTrolleyCheckout(event);" title="Inserisci a carrello" src="' + layoutImagesUrl + 'carrello.gif" />';
					} else {
						quantityArea.innerHTML = '<input title="' + inputQuantityTooltip + '" class="productinputqty" id="js-prodinputqty-' + i + '" onchange="javascript: newQuantity(' + i + ');" onkeypress="return pressReturnOnInputText(event)" type="text" size="1" maxlength="3" value="1" />';
						increaseArea.innerHTML = '<img title="' + incQuantityTooltip + '" class="selectableimage" width="12" height="12" border="0" id="js-increase-' + i + '" onclick="javascript: increaseQuantity(' + i + ');" title="Incrementa la quantita\'" src="' + layoutImagesUrl + 'piu.gif" />';
						decreaseArea.innerHTML = '<img title="' + decQuantityTooltip + '" class="selectableimage" width="12" height="12" border="0" id="js-decrease-' + i + '" onclick="javascript: decreaseQuantity(' + i + ');" title="Decrementa la quantita\'" src="' + layoutImagesUrl + 'meno.gif" />';
						addToTrolleyArea.innerHTML = '<img title="' + addToTrolleyTooltip + '" class="selectableimage" width="19" height="19" border="0" id="js-addtotrolley-' + i + '" onclick="javascript: addToTrolley(' + i + ');" title="Inserisci a carrello" src="' + layoutImagesUrl + 'carrello.gif" />';
					}
				}

				//	Update flag.
				var relatedAreaDiv = document.getElementById("js-related-" + productItems[i].parentIndex);

				if(relatedAreaDiv)
				{
                    var newRelatedAreaDiv = '';
                    if(productItems[i].relatedProductFlag) {
                        newRelatedAreaDiv = isRelatedPage ? '<img width="11" height="14" border="0" id="js-relatedprod-' + productItems[i].parentIndex + '" onclick="javascript: showRelatedProducts(event);" title="Visualizza la lista dei prodotti correlati" src="' + layoutImagesUrl + 'ico_lamp_att.gif"/>' :
                                                            '<img width="11" height="14" border="0" id="js-relatedprod-' + productItems[i].parentIndex + '" onclick="javascript: showRelatedProducts(event);" title="Visualizza la lista dei prodotti correlati" src="' + layoutImagesUrl + 'ico_lamp.gif"/>';
                    }
                    relatedAreaDiv.innerHTML = newRelatedAreaDiv;
				}
			}
			else
			{
				productItems[i].isShowing = false;
			}
		}
		else
		{
			break;
		}
	}
}


function updateWeekFieldsAndSubmit(productIndex)
{
	var optionIdArray = new Array();

	//	Check if grouped by groupid.
	var productInGroupSelect = document.getElementById("js-productInGroup-" + productIndex);

    var prodStoreId = null;

    if(productInGroupSelect == null)
	{
		//	Retrieve no price options.
		var currentSelectBox = null;
		var i = 0;

		do
		{
			currentSelectBox = document.getElementById("js-optionNoPrice" + i + "-" + productIndex);

			if(currentSelectBox != null)
			{
				if(currentSelectBox.value == "")
				{
					alert("Attenzione: selezionare una voce per ogni opzione disponibile");
					return;
				}

				optionIdArray.push(currentSelectBox.value);
			}
			
			i++;
		}
		while(currentSelectBox != null);

		//	Retrieve price option.
		if(productItems[productIndex - firstWeekItem].priceOptions != null)
		{
			currentSelectBox = document.getElementById("js-optionPrice-" + productIndex);
	
			if(currentSelectBox)
			{
				optionIdArray.push(currentSelectBox.value);
			}
			else
			{
				optionIdArray.push(productItems[productIndex - firstWeekItem].priceOptions[0].productOptionId);
			}
		}
	
		for(var i = 0; i < optionIdArray.length; i++)
		{
			document.forms["bodyForm"].elements["weekItemOpt-" + productIndex + "-" + i].value = optionIdArray[i];
		}
	
		for(; i < 4; i++)
		{
			document.forms["bodyForm"].elements["weekItemOpt-" + productIndex + "-" + i].value = "";
		}

        prodStoreId = productItems[productIndex - firstWeekItem].storeId;
    }
	else
	{
		//	Retrieve selected index.
		var selectedProductIndex = productInGroupSelect.value;

		//	Retrieve price option.
		if(productItems[selectedProductIndex - firstWeekItem].priceOptions != null)
		{
			optionIdArray.push(productItems[selectedProductIndex - firstWeekItem].priceOptions[0].productOptionId);
		}

		for(var i = 0; i < optionIdArray.length; i++)
		{
			document.forms["bodyForm"].elements["weekItemOpt-" + productIndex + "-" + i].value = optionIdArray[i];
		}
	
		for(; i < 4; i++)
		{
			document.forms["bodyForm"].elements["weekItemOpt-" + productIndex + "-" + i].value = "";
		}

        prodStoreId = productItems[selectedProductIndex - firstWeekItem].storeId;
    }

	//	Update
	var inputProdQty = document.getElementById("js-prodinputqty-" + productIndex);
	document.getElementById("weekItemQty-" + productIndex).value = inputProdQty.value;
    document.getElementById("weekItemStore-" + productIndex).value = prodStoreId;


    putInTrolley(	document.getElementById("weekItemStore-" + productIndex).value,
                    document.getElementById("weekItemId-" + productIndex).value,
					document.getElementById("weekItemQty-" + productIndex).value,
					(optionIdArray.length > 0 ? optionIdArray : null));
}


function resetQuantity(productIndex, inputProdQty) {
	if(checkoutPage) {
		if(productIndex < firstWeekItem)
		{
			inputProdQty.value = trolleyProductItems[productIndex].quantity;
			document.forms["bodyForm"].elements["trolleyItemQty-" + productIndex].value = trolleyProductItems[productIndex].quantity;
		}
		else
		{
			inputProdQty.value = "1";
			document.forms["bodyForm"].elements["weekItemQty-" + productIndex].value = 0;
		}
	} else {
		inputProdQty.value = "1";
	}
}


function setQuantity(productIndex, inputTag, newQuantity)
{
    if(checkoutPage) {
        if(productIndex < firstWeekItem)
        {
            trolleyProductItems[productIndex].quantity = newQuantity;
            inputTag.value = newQuantity;
            document.forms["bodyForm"].elements["trolleyItemQty-" + productIndex].value = newQuantity;
        }
        else
        {
            productItems[productIndex - firstWeekItem].quantity = newQuantity;
            inputTag.value = newQuantity;
            document.forms["bodyForm"].elements["weekItemQty-" + productIndex].value = newQuantity;
        }
    }
}


/**
	Change quantity.
*/
function newQuantity(productIndex, originalQuantity, currentPrefix)
{
    //	Hide dialogs.
    hideDialogs();

    //  Set original quantity to the default value if none has been provided.
    originalQuantity = (originalQuantity != null ? originalQuantity: 1);

    //  Set default prefix if none has been provided.
    currentPrefix = (currentPrefix != null ? currentPrefix : "js-");

	//	Retrieve source tag.
    var sourceTag = document.getElementById(currentPrefix + "prodinputqty-" + productIndex);

	//	Check that it's a integer value.
	if(	sourceTag.value != parseInt(sourceTag.value) ||
		parseInt(sourceTag.value) < 0)
	{
		alert(trolleyPutNotIntegerMsg);
		sourceTag.value = "" + originalQuantity;
	}
}


/**
	Change quantity.
*/
function newQuantityCheckout( productIndex )
{
	//	Hide dialogs.
	hideDialogs();

	//	Check that quantity is an integer value.
    var productQuantityTag = document.getElementById( 'js-prodinputqty-' + productIndex );
    var productQuantityValue = productQuantityTag.value;
    var productQuantityAsInt = parseInt(productQuantityValue);

    if(	productQuantityValue != productQuantityAsInt || productQuantityAsInt < 0)
	{
		alert(trolleyPutNotIntegerMsg);
        resetQuantity(productIndex, productQuantityTag);
		return(false);
	}
	else
	{
        setQuantity(productIndex, productQuantityTag, productQuantityAsInt);
		return(true);
	}
}


/**
	Increase product quantity.
*/
function increaseQuantity(productIndex, currentDocument, currentPrefix)
{
	//	Hide dialogs.
	hideDialogs();

    //  Set default document if none has been provided.
    currentDocument = (currentDocument != null ? currentDocument : document);

    //  Set default prefix if none has been provided.
    currentPrefix = (currentPrefix != null ? currentPrefix : "js-");

	//	Increase quantity.
	var inputProdQty = currentDocument.getElementById(currentPrefix + "prodinputqty-" + productIndex);
	var currentQuantity = parseInt(inputProdQty.value);

	if(isNaN(currentQuantity))
	{
		if(inputProdQty.value == "") inputProdQty.value = "" + 1;
		else
		{
			resetQuantity(productIndex, inputProdQty);
			alert(trolleyPutNotIntegerMsg);
			return;
		}
	}
	else
	{
		if(	(inputProdQty.value == currentQuantity) &&
			(inputProdQty.value >= 0))
		{
			inputProdQty.value = (currentQuantity == 999 ? "999" : (currentQuantity + 1));
		}
		else
		{
			resetQuantity(productIndex, inputProdQty);
			alert(trolleyPutNotIntegerMsg);
			return;
		}
	}

    setQuantity(productIndex, inputProdQty, inputProdQty.value);
}


/**
	Decrease product quantity.
*/
function decreaseQuantity(productIndex, currentDocument, currentPrefix)
{
	//	Hide dialogs.
	hideDialogs();

    //  Set default document if none has been provided.
    currentDocument = (currentDocument != null ? currentDocument : document);

    //  Set default prefix if none has been provided.
    currentPrefix = (currentPrefix != null ? currentPrefix : "js-");

	//	Decrease quantity.
	var inputProdQty = currentDocument.getElementById(currentPrefix + "prodinputqty-" + productIndex);
	var currentQuantity = parseInt(inputProdQty.value);

	if(isNaN(currentQuantity))
	{
		if(inputProdQty.value == "") inputProdQty.value = "" + 0;
		else
		{
			resetQuantity(productIndex, inputProdQty);
			alert(trolleyPutNotIntegerMsg);
			return;
		}
	}
	else
	{
		if(	(inputProdQty.value == currentQuantity) &&
			(inputProdQty.value >= 0))
		{
			if(currentQuantity != 0) inputProdQty.value = "" + (currentQuantity - 1);
		}
		else
		{
			resetQuantity(productIndex, inputProdQty);
			alert(trolleyPutNotIntegerMsg);
			return;
		}
	}

    setQuantity(productIndex, inputProdQty, inputProdQty.value);
}


function pressReturnOnInputTextCheckout(currentEvent)
{
    //	Retrieve keycode (handle mozilla and internet explorer difference).
    var keyCode = (currentEvent.which != null ? currentEvent.which : currentEvent.keyCode);

    if (keyCode == 13)
    {
        //	Cancel or shift keys are always enabled.
        addToTrolleyCheckout(currentEvent);

        return(false);
    }
    else
    {
        // Others keys are always disabled.
        return(true);
    }
}


/**
	Put in trolley (and associated function used to restore quantity class).
*/
function restoreQuantityStyle(idToRestore)
{
	var inputProdQty = document.getElementById(idToRestore);
	
	if(inputProdQty != null)
	{
		inputProdQty.className = "productinputqty";
	}
}


function getProductIndexByEvent(currentEvent) {
    //	Retrieve source tag and its id.
    var sourceTag = getSourceByEvent(currentEvent);

    //	Retrieve product index from tag identifier.
    var sourceTagId = sourceTag.id;
    var sourceTagIdArray = sourceTagId.split("-");
    var productIndex = sourceTagIdArray[2];
    
    return(productIndex);
}


function pressReturnOnInputText(currentEvent, originalQuantity, productsInfo, currentDocument, currentPrefix)
{
    originalQuantity = (originalQuantity != null ? originalQuantity : 1);
    productsInfo = (productsInfo != null ? productsInfo : productItems);
    currentDocument = (currentDocument != null ? currentDocument : document);
    currentPrefix = (currentPrefix != null ? currentPrefix : "js-");

    //	Retrieve keycode (handle mozilla and internet explorer difference).
	var keyCode = (currentEvent.which != null ? currentEvent.which : currentEvent.keyCode);

	if (keyCode == 13) {
		//	Cancel or shift keys are always enabled.
        var productIndex = getProductIndexByEvent(currentEvent);
        addToTrolleyPrivate(productsInfo, productIndex, currentDocument, originalQuantity, currentPrefix);
 		return(false);
	} else {
		// Others keys are always disabled.
		return(true);
	}
}


function addToTrolley( productIndex ) {
    addToTrolleyPrivate(productItems, productIndex, document, 1, null);
}


function getSelectedProductOptions(isGrouped, currentDocument, currentPrefix, productInfo, productIndex) {
    //  Array containing all options identifiers.
    var optionIdArray = new Array();

    if(!isGrouped)
	{
		//	Retrieve no price options.
		var currentSelectBox = null;
		var i = 0;

		do {
			currentSelectBox = currentDocument.getElementById(currentPrefix + "optionNoPrice" + i + "-" + productIndex);

			if(currentSelectBox != null) {
				if(currentSelectBox.value == "") {
                    alert(trolleyPutSelectAllOptionsMsg);
                    throw(trolleyPutSelectAllOptionsMsg);
				}

				optionIdArray.push(currentSelectBox.value);
			}

			i++;
		} while(currentSelectBox != null);

		//	Retrieve price option.
		if(productInfo.priceOptions != null || currentDocument.getElementById(currentPrefix + "optionPrice-" + productIndex) != null) {
			currentSelectBox = currentDocument.getElementById(currentPrefix + "optionPrice-" + productIndex);

			if(currentSelectBox) {
				optionIdArray.push(currentSelectBox.value);
			} else {
				optionIdArray.push(productInfo.priceOptions[0].productOptionId);
			}
		}

        //  Handle special case of single product options - TODO REFACTOR AS SOON AS POSSIBLE.
        //noinspection JSUnusedLocalSymbols
        try {
            if(productInfo.singleOption != null) {
                optionIdArray = productInfo.singleOption;
            }
        } catch(e) { /* Nothing */ }
    }
	else
	{
		//	Retrieve price option.
		if(productInfo.priceOptions != null) {
			optionIdArray.push(productInfo.priceOptions[0].productOptionId);
		}
	}

    return optionIdArray;
}


function addToTrolleyPrivate(productsInfo, productIndex, currentDocument, originalQuantity, currentPrefix)
{
    //	Hide dialogs.
	hideDialogs();

    //  Set default prefix if none has been provided.
    currentPrefix = (currentPrefix != null ? currentPrefix : "js-");

    //	Get quantity.
	var inputProdQty = currentDocument.getElementById(currentPrefix + "prodinputqty-" + productIndex);
	var currentQuantity = parseInt(inputProdQty.value);

    if(isNaN(currentQuantity)) {
        inputProdQty.value = "" + originalQuantity;

        if(inputProdQty.value == "") {
			currentQuantity = originalQuantity;
		} else {
			alert(trolleyPutNotIntegerMsg);
			return;
		}
	}

	if(	!((inputProdQty.value == currentQuantity) && (inputProdQty.value >= 0) && (inputProdQty.value <= 999)))	{
		alert(trolleyPutWrongRangeMsg);
		inputProdQty.value = "" + originalQuantity;
		return;
	}

    //	Check if grouped by groupid.
    var productInGroupSelect = currentDocument.getElementById(currentPrefix + "productInGroup-" + productsInfo[productIndex].parentIndex);
    var selectedProductIndex = (productInGroupSelect != null && productInGroupSelect.value != null) ? productInGroupSelect.value : productIndex;
    var productInfo = productsInfo[selectedProductIndex];

    //noinspection JSUnusedLocalSymbols
    try {
        var optionIdArray = getSelectedProductOptions(productInGroupSelect != null, currentDocument, currentPrefix, productInfo, selectedProductIndex);
    } catch(e) {
        //  Stop here and return immediatly.
        return;
    }

    //	Check max order quantity.
    if(	productInfo.maxOrderQuantity != 0 && currentQuantity > productInfo.maxOrderQuantity) {
        alert(trolleyPutMaxQuantityErrorMsg.replace(/X/, productInfo.maxOrderQuantity).replace(/Y/, productInfo.name));
        return;
    }

    //	Check warning quantity.
    if( currentQuantity > trolleyPutQuantityWarning) {
        if(!confirm(trolleyPutQuantityWarningMsg.replace(/X/, trolleyPutQuantityWarning))) {
            return;
        }
    }

    //	Change style class and set timer in order to restore the previous one.
    inputProdQty.className = "productinputqtyred";
    /*var idToRestore = "js-prodinputqty-" + productIndex;
    setTimeout('restoreQuantityStyle("' + idToRestore + '")', highlightQuantityTime);*/

    //noinspection JSUnusedLocalSymbols
    try {
        if(opener != null && opener.putInTrolley != null) {
            opener.putInTrolley(productInfo.storeId, productInfo.idProduct, currentQuantity, (optionIdArray.length > 0 ? optionIdArray : null));
        } else {
            putInTrolley(productInfo.storeId, productInfo.idProduct, currentQuantity, (optionIdArray.length > 0 ? optionIdArray : null));
        }
	}
	catch(e) { /* Nothing */ }
}


function addToTrolleyCheckout(currentEvent)
{
	//	Disable continue button.
	disableContinueToSlotPage();

	//	Hide dialogs.
	hideDialogs();

	//	Retrieve source tag and its id.
	var sourceTag = getSourceByEvent(currentEvent);

	//	Retrieve product index from tag identifier.
	var sourceTagId = sourceTag.id;
	var sourceTagIdArray = sourceTagId.split("-");
	var productIndex = sourceTagIdArray[2];

	//alert("firstWeekItem: " + firstWeekItem);
	if(productIndex < firstWeekItem)
	{
		//	Get quantity.
		var inputProdQty = document.getElementById("js-prodinputqty-" + productIndex);
		var currentQuantity = parseInt(inputProdQty.value);

		if(isNaN(currentQuantity))
		{
			if(inputProdQty.value == "")
			{
				inputProdQty.value = "" + 1;
				currentQuantity = 1;
			}
			else
			{
				//	Enable continue button.
				enableContinueToSlotPage();

				alert(trolleyPutNotIntegerMsg);
				inputProdQty.value = "";

				sourceTag.value = trolleyProductItems[productIndex].quantity;
				document.forms["bodyForm"].elements["trolleyItemQty-" + productIndex].value = trolleyProductItems[productIndex].quantity;

				return;
			}
		}

		if(	!((inputProdQty.value == currentQuantity) &&
			  (inputProdQty.value >= 0) &&
			  (inputProdQty.value <= 999)))
		{
			//	Enable continue button.
			enableContinueToSlotPage();

			alert(trolleyPutWrongRangeMsg);
			inputProdQty.value = "";

			sourceTag.value = trolleyProductItems[productIndex].quantity;
			document.forms["bodyForm"].elements["trolleyItemQty-" + productIndex].value = trolleyProductItems[productIndex].quantity;

			return;
		}

		//	Check if quantity = 0 use function RemoveFrom Trolley
		if(	currentQuantity == 0)
		{
			removeFromTrolley( productIndex );

			return;
		}
		
		//	Check max order quantity.
		if(	trolleyProductItems[productIndex].maxOrderQuantity != 0 &&
			currentQuantity > trolleyProductItems[productIndex].maxOrderQuantity)
		{
			//	Enable continue button.
			enableContinueToSlotPage();

			alert(trolleyPutMaxQuantityErrorMsg.replace(/X/, trolleyProductItems[productIndex].maxOrderQuantity).replace(/Y/, trolleyProductItems[productIndex].name));

			return;
		}

		//	Check warning quantity.
		if( currentQuantity > trolleyPutQuantityWarning)
		{
			if(!confirm(trolleyPutQuantityWarningMsg.replace(/X/, trolleyPutQuantityWarning)))
			{
				//	Enable continue button.
				enableContinueToSlotPage();

				return;
			}
		}

		//	Retrieve options.
		var index = 0;
		var optionIdArray = new Array();
		var currentOptionTag = document.getElementById("trolleyItemOpt-" + productIndex + "-" + index);
		while(currentOptionTag != null)
		{
			optionIdArray.push(currentOptionTag.value);

			index++;
			currentOptionTag = document.getElementById("trolleyItemOpt-" + productIndex + "-" + index);
		}

		//	Change style class and set timer in order to restore the previous one.
		inputProdQty.className = "productinputqtyred";
		var idToRestore = "js-prodinputqty-" + productIndex;
		//setTimeout('restoreQuantityStyle("' + idToRestore + '")', highlightQuantityTime);

        putInTrolley(trolleyProductItems[productIndex].storeId, trolleyProductItems[productIndex].idProduct, currentQuantity, (optionIdArray.length > 0 ? optionIdArray : null));
	}
	else
	{
		//alert("prodotto della settimana! productIndex: " + productIndex);

		//	Get quantity.
		var inputProdQty = document.getElementById("js-prodinputqty-" + productIndex);
		var currentQuantity = parseInt(inputProdQty.value);

		//alert("currentQuantity: " + currentQuantity);
		var productInGroupSelect = document.getElementById("js-productInGroup-" + productIndex);

		if(isNaN(currentQuantity))
		{
			if(inputProdQty.value == "")
			{
				inputProdQty.value = "" + 1;
				currentQuantity = 1;

				if(productInGroupSelect == null)
				{
					productItems[productIndex - firstWeekItem].quantity = 1;
					document.forms["bodyForm"].elements["weekItemQty-" + productIndex].value = 1;
				}
				else
				{
					//	Retrieve selected index.
					var selectedProductIndex = productInGroupSelect.value;

					productItems[selectedProductIndex - firstWeekItem].quantity = 1;
					document.forms["bodyForm"].elements["weekItemQty-" + productIndex].value = 1;
				}
			}
			else
			{
				//	Enable continue button.
				enableContinueToSlotPage();

				alert(trolleyPutNotIntegerMsg);
				inputProdQty.value = "1";
				document.forms["bodyForm"].elements["weekItemQty-" + productIndex].value = 1;

				return;
			}
		}

		if(	!((inputProdQty.value == currentQuantity) &&
			  (inputProdQty.value >= 0) &&
			  (inputProdQty.value <= 999)))
		{
			//	Enable continue button.
			enableContinueToSlotPage();

			alert(trolleyPutWrongRangeMsg);
			inputProdQty.value = "1";
			document.forms["bodyForm"].elements["weekItemQty-" + productIndex].value = 1;

			return;
		}

		if(productInGroupSelect == null)
		{
			//alert("Non raggruppato!");

			//	Check max order quantity.
			if(	productItems[productIndex - firstWeekItem].maxOrderQuantity != 0 &&
				currentQuantity > productItems[productIndex - firstWeekItem].maxOrderQuantity)
			{
				//	Enable continue button.
				enableContinueToSlotPage();

				alert(trolleyPutMaxQuantityErrorMsg.replace(/X/, productItems[productIndex - firstWeekItem].maxOrderQuantity).replace(/Y/, productItems[productIndex - firstWeekItem].name));

				return;
			}

			//	Check warning quantity.
			if( currentQuantity > trolleyPutQuantityWarning)
			{
				if(!confirm(trolleyPutQuantityWarningMsg.replace(/X/, trolleyPutQuantityWarning)))
				{
					//	Enable continue button.
					enableContinueToSlotPage();

					return;
				}
			}
		}
		else
		{
			//	Retrieve selected index.
			var selectedProductIndex = productInGroupSelect.value;

			//alert("Raggruppato" + selectedProductIndex);

			//	Check max order quantity.
			if(	productItems[selectedProductIndex - firstWeekItem].maxOrderQuantity != 0 &&
				currentQuantity > productItems[selectedProductIndex - firstWeekItem].maxOrderQuantity)
			{
				//	Enable continue button.
				enableContinueToSlotPage();

				alert(trolleyPutMaxQuantityErrorMsg.replace(/X/, productItems[selectedProductIndex - firstWeekItem].maxOrderQuantity).replace(/Y/, productItems[selectedProductIndex - firstWeekItem].name));

				return;
			}

			//	Check warning quantity.
			if( currentQuantity > trolleyPutQuantityWarning)
			{
				if(!confirm(trolleyPutQuantityWarningMsg.replace(/X/, trolleyPutQuantityWarning)))
				{
					//	Enable continue button.
					enableContinueToSlotPage();

					return;
				}
			}
		}

		//	Change style class and set timer in order to restore the previous one.
		inputProdQty.className = "productinputqtyred";
		var idToRestore = "js-prodinputqty-" + productIndex;

		//alert("proma di updateweek");
		updateWeekFieldsAndSubmit(productIndex);
	}
}


/**
	Put in trolley
*/
function removeFromTrolley( productIndex )
{
	//	Disable continue button.
	disableContinueToSlotPage();

	//	Retrieve source tag.
	if(window.confirm("Attenzione, procedere con la rimozione del prodotto da carrello?"))
	{
		if(productIndex < firstWeekItem)
		{
			document.forms["bodyForm"].elements["trolleyItemQty-" + productIndex].value = 0;

			//	Retrieve options.
			var index = 0;
			var optionIdArray = new Array();
			var currentOptionTag = document.getElementById("trolleyItemOpt-" + productIndex + "-" + index);
			while(currentOptionTag != null)
			{
				optionIdArray.push(currentOptionTag.value);
	
				index++;
				currentOptionTag = document.getElementById("trolleyItemOpt-" + productIndex + "-" + index);
			}

            putInTrolley(trolleyProductItems[productIndex].storeId, trolleyProductItems[productIndex].idProduct, 0, (optionIdArray.length > 0 ? optionIdArray : null));
		}
		else
		{
			// error...
		}
	}
	else
	{
		//	Disable continue button.
		enableContinueToSlotPage();
	}
}


// Put in trolley
function removePayloadFromTrolley(payloadIdentifier)
{
	//	Disable continue button.
	disableContinueToSlotPage();

	//	Retrieve source tag.
	if(window.confirm("Attenzione, procedere con la rimozione del prodotto da carrello?")) {
        removePayload(payloadIdentifier);
	}
	else {
		//	Disable continue button.
		enableContinueToSlotPage();
	}
}



/*
	Show order by dialog.
*/
function openOrderByDialog()
{
	//	Dialog size.
	var dialogWidth = 387;
	var dialogHeight = 170;

	//	Compute dialog position.
	var relativeWidth = top.document.getElementById('mainFrameSet').offsetWidth;
	var relativeHeight = top.document.getElementById('mainFrameSet').offsetHeight;
	var posX = (relativeWidth - dialogWidth) / 2;
	var posY = (relativeHeight - dialogHeight) / 2;

	//	Build url.
	var dialogUrl = loadOrderByDialogUrl;

	winPopUp = window.open(dialogUrl, 'orderby', 'scrollbars=no, resizable=no, width=' + dialogWidth + ', height=' + dialogHeight + ', left=' + posX + ', top=' + posY + ', status=no, location=no, toolbar=no');
	winPopUp.focus();
}

function loadSelectDeliveryPage()
{
	//	button disabled?
	if(continueToSlotPageDisabled)
	{
		//alert("test");

		return;
	}

	//	Changed quantity?
	var changedQty = false;

	for(var i = 0; i < trolleyProductItems.length; i++)
	{
		if(trolleyProductItems[i].originalQuantity != trolleyProductItems[i].quantity)
		{
			changedQty = true;
			break;
		}
	}

	if(changedQty)
	{
		if(!window.confirm("E' stata modificata la quantita' associata ad alcuni prodotti presenti a carrello. Procedendo si perderanno queste modifiche. Per non perdere queste modifiche occorre cliccare sul bottone 'Ricalcola carrello'.\nContinuare?"))
		{
			return;
		}
	}

	submitFormExtended("bodyForm", selectDeliveryPageUrl, null, null);
}


function showOldOrderContent(orderId, currentPage)
{
	submitFormExtended("confirmOrder", showOldOrderUrl, null, ["orderId", orderId, "currentPage", currentPage]);
}


function addAllProductsToTrolley()
{
	//	Disable continue button.
	disableContinueToSlotPage();

	//	Hide dialogs.
	hideDialogs();

	//	Retrieve product index from tag identifier.
	var productIndex = firstWeekItem;

	//	Get quantity.
	var inputProdQty = document.getElementById("js-prodinputqty-" + productIndex);
	var currentQuantity = parseInt(inputProdQty.value);

	var productInGroupSelect = document.getElementById("js-productInGroup-" + productIndex);

	if(isNaN(currentQuantity))
	{
		if(inputProdQty.value == "")
		{
			inputProdQty.value = "" + 1;
			currentQuantity = 1;

			if(productInGroupSelect == null)
			{
				productItems[productIndex - firstWeekItem].quantity = 1;
				document.forms["bodyForm"].elements["weekItemQty-" + productIndex].value = 1;
			}
			else
			{
				//	Retrieve selected index.
				var selectedProductIndex = productInGroupSelect.value;

				productItems[selectedProductIndex - firstWeekItem].quantity = 1;
				document.forms["bodyForm"].elements["weekItemQty-" + productIndex].value = 1;
			}
		}
		else
		{
			//	Enable continue button.
			enableContinueToSlotPage();

			alert(trolleyPutNotIntegerMsg);
			inputProdQty.value = "1";
			document.forms["bodyForm"].elements["weekItemQty-" + productIndex].value = 1;

			return;
		}
	}

	if(	!((inputProdQty.value == currentQuantity) &&
		  (inputProdQty.value >= 0) &&
		  (inputProdQty.value <= 999)))
	{
		//	Enable continue button.
		enableContinueToSlotPage();

		alert(trolleyPutWrongRangeMsg);
		inputProdQty.value = "1";
		document.forms["bodyForm"].elements["weekItemQty-" + productIndex].value = 1;

		return;
	}

	if(productInGroupSelect == null)
	{
		//	Check max order quantity.
		if(	productItems[productIndex - firstWeekItem].maxOrderQuantity != 0 &&
			currentQuantity > productItems[productIndex - firstWeekItem].maxOrderQuantity)
		{
			//	Enable continue button.
			enableContinueToSlotPage();

			alert(trolleyPutMaxQuantityErrorMsg.replace(/X/, productItems[productIndex - firstWeekItem].maxOrderQuantity).replace(/Y/, productItems[productIndex - firstWeekItem].name));

			return;
		}

		//	Check warning quantity.
		if( currentQuantity > trolleyPutQuantityWarning)
		{
			if(!confirm(trolleyPutQuantityWarningMsg.replace(/X/, trolleyPutQuantityWarning)))
			{
				//	Enable continue button.
				enableContinueToSlotPage();

				return;
			}
		}
	}
	else
	{
		//	Retrieve selected index.
		var selectedProductIndex = productInGroupSelect.value;

		//	Check max order quantity.
		if(	productItems[selectedProductIndex - firstWeekItem].maxOrderQuantity != 0 &&
			currentQuantity > productItems[selectedProductIndex - firstWeekItem].maxOrderQuantity)
		{
			//	Enable continue button.
			enableContinueToSlotPage();

			alert(trolleyPutMaxQuantityErrorMsg.replace(/X/, productItems[selectedProductIndex - firstWeekItem].maxOrderQuantity).replace(/Y/, productItems[selectedProductIndex - firstWeekItem].name));

			return;
		}

		//	Check warning quantity.
		if( currentQuantity > trolleyPutQuantityWarning)
		{
			if(!confirm(trolleyPutQuantityWarningMsg.replace(/X/, trolleyPutQuantityWarning)))
			{
				//	Enable continue button.
				enableContinueToSlotPage();

				return;
			}
		}
	}

	updateWeekFieldsAndSubmit(productIndex);
}

/*
	Show filter by dialog.
*/
function openFilterByDialog()
{
	//	Dialog size.
	var dialogWidth = 406;
	var dialogHeight = 170;

	//	Compute dialog position.
	var relativeWidth = top.document.getElementById('mainFrameSet').offsetWidth;
	var relativeHeight = top.document.getElementById('mainFrameSet').offsetHeight;
	var posX = (relativeWidth - dialogWidth) / 2;
	var posY = (relativeHeight - dialogHeight) / 2;

	//	Build url.
	var dialogUrl = loadFilterByDialogUrl;

	winPopUp = window.open(dialogUrl, 'filterby', 'scrollbars=no, resizable=no, width=' + dialogWidth + ', height=' + dialogHeight + ', left=' + posX + ', top=' + posY + ', status=no, location=no, toolbar=no');
	winPopUp.focus();
}

function modifyPopUp(orderId, currentPage)
{
    var relativeWidth = screen.width;
    var relativeHeight = screen.height;
	
	var posX = relativeWidth/2;
	var posY = relativeHeight/2;
	
	winPopUp=window.open(modifyOrderUrl + "?orderId=" + orderId + "&currentPage=" + currentPage, 'browseList', 'width=387,height=290,left='+posX+',top='+posY+',scrollbars=no');
}


/**
 * Opens the "delivery exception detail" popup..
 */
function popupDeliveryExceptions(deliUrl)
{
	var relativeWidth = screen.width;
	var relativeHeight = screen.height;

	var posX = (relativeWidth - 460) / 2;
	var posY = (relativeHeight - 300) / 2;
	
	winPopUp = window.open(deliUrl, "deliveryexceptionspopup", 'width=' + 460 + ',height=' + 300 + ',left=' + posX + ',top=' + posY + ', scrollbars=yes');
}


/*
	Function used to handle related products functionalities.
*/
function showRelatedProducts(currentEvent)
{
	//	Hide dialogs.
	hideDialogs();

	//	Retrieve source tag and its id.
	var sourceTag = getSourceByEvent(currentEvent);

	//	Retrieve product index from tag identifier.
	var sourceTagId = sourceTag.id;
	var sourceTagIdArray = sourceTagId.split("-");
	var productIndex = sourceTagIdArray[2];

	//	Check if grouped by groupid.
	var productInGroupSelect = document.getElementById("js-productInGroup-" + productIndex);
	
	if(productInGroupSelect == null)
	{
		//	Prepare parameters for the LoadTrolleyRight action.
		var newWorkAreaUrl = handleRelatedListUrl;

		newWorkAreaUrl += "?storeId=" + productItems[productIndex].storeId + "&productId=" + productItems[productIndex].idProduct;

		top.workframe.location.href = newWorkAreaUrl;
	}
	else
	{
		//	Retrieve selected index.
		selectedProductIndex = productInGroupSelect.value;

		//	Prepare parameters for the LoadTrolleyRight action.
		var newWorkAreaUrl = handleRelatedListUrl;

		newWorkAreaUrl += "?storeId=" + productItems[selectedProductIndex].storeId + "&productId=" + productItems[selectedProductIndex].idProduct;

		top.workframe.location.href = newWorkAreaUrl;
	}
}

function backToPreviousRelated()
{
	top.workframe.location.href = handleRelatedListUrl + "?actionMethod=backRelated";
}


function updateFormItems(productIndex)
{
	//	Get quantity.
	var inputProdQty = document.getElementById("js-prodinputqty-" + productIndex);

	if(!productItems[productIndex].storeId || !inputProdQty)
	{
		document.forms["bodyForm"].elements["productItemId-" + productIndex].value = -1;
		document.forms["bodyForm"].elements["productItemQty-" + productIndex].value = -1;
		document.forms["bodyForm"].elements["productItemStore-" + productIndex].value = 1;
		document.forms["bodyForm"].elements["productItemOpt-" + productIndex + "-0"].value = "";
		document.forms["bodyForm"].elements["productItemOpt-" + productIndex + "-1"].value = "";
		document.forms["bodyForm"].elements["productItemOpt-" + productIndex + "-2"].value = "";
		document.forms["bodyForm"].elements["productItemOpt-" + productIndex + "-3"].value = "";

		return(true);
	}

	//	Hide dialogs.
	hideDialogs();

	//	Get quantity.
	var currentQuantity = parseInt(inputProdQty.value);

	if(isNaN(currentQuantity))
	{
		currentQuantity = -1;
	}

	if(	!((inputProdQty.value == currentQuantity) &&
		  (inputProdQty.value >= 0) &&
		  (inputProdQty.value <= 999)))
	{
		currentQuantity = -1;
	}

	//	Check if grouped by groupid.
	var productInGroupSelect = document.getElementById("js-productInGroup-" + productIndex);

	//	Check max order quantity.
	if(	productItems[productIndex].maxOrderQuantity != 0 &&
		currentQuantity > productItems[productIndex].maxOrderQuantity)
	{
		alert(trolleyPutMaxQuantityErrorMsg.replace(/X/, productItems[productIndex].maxOrderQuantity).replace(/Y/, productItems[productIndex].name));
		return(false);
	}

	//	Check warning quantity.
	if( currentQuantity > trolleyPutQuantityWarning)
	{
		if(!confirm(trolleyPutQuantityWarningMsg.replace(/X/, trolleyPutQuantityWarning)))
		{
			return(false);
		}
	}

	//	Retrieve all options identifiers.
	var optionIdArray = new Array();

	//	Retrieve no price options.
	var currentSelectBox = null;
	var i = 0;

	do
	{
		currentSelectBox = document.getElementById("js-optionNoPrice" + i + "-" + productIndex);

		if(currentSelectBox != null)
		{
			if(currentSelectBox.value == "")
			{
				alert(trolleyPutSelectAllOptionsWithNameMsg.replace(/X/, productItems[productIndex].name));

				return(false);
			}

			optionIdArray.push(currentSelectBox.value);
		}

		i++;
	}
	while(currentSelectBox != null);

	//	Retrieve price option.
	if(productItems[productIndex].priceOptions != null)
	{
		currentSelectBox = document.getElementById("js-optionPrice-" + productIndex);

		if(currentSelectBox)
		{
			optionIdArray.push(currentSelectBox.value);
		}
		else
		{
			optionIdArray.push(productItems[productIndex].priceOptions[0].productOptionId);

		}
	}

	var optionsString = "";
	for(i = 0; i < optionIdArray.length; i++)
	{
		if(i != 0) optionsString += " ";
		optionsString += optionIdArray[i];
	}

	//	Put product in trolley.
	document.forms["bodyForm"].elements["productItemId-" + productIndex].value = productItems[productIndex].idProduct;
	document.forms["bodyForm"].elements["productItemQty-" + productIndex].value = currentQuantity;
	document.forms["bodyForm"].elements["productItemStore-" + productIndex].value = productItems[productIndex].storeId;
	document.forms["bodyForm"].elements["productItemOpt-" + productIndex + "-0"].value = "";
	document.forms["bodyForm"].elements["productItemOpt-" + productIndex + "-1"].value = "";
	document.forms["bodyForm"].elements["productItemOpt-" + productIndex + "-2"].value = "";
	document.forms["bodyForm"].elements["productItemOpt-" + productIndex + "-3"].value = "";
	if(optionIdArray.length > 0) document.forms["bodyForm"].elements["productItemOpt-" + productIndex + "-0"].value = optionIdArray[0];
	if(optionIdArray.length > 1) document.forms["bodyForm"].elements["productItemOpt-" + productIndex + "-1"].value = optionIdArray[1];
	if(optionIdArray.length > 2) document.forms["bodyForm"].elements["productItemOpt-" + productIndex + "-2"].value = optionIdArray[2];
	if(optionIdArray.length > 3) document.forms["bodyForm"].elements["productItemOpt-" + productIndex + "-3"].value = optionIdArray[3];

	return(true);
}


function backToPersonalListsPage()
{
	submitFormExtended("headerForm", loadPersonalListUrl, null, null);
}

function educationalPopUp(Url)
{
	var relativeWidth = top.document.getElementById('mainFrameSet').offsetWidth;
	var relativeHeight = top.document.getElementById('mainFrameSet').offsetHeight;
	var posX = relativeWidth/2 - 387/2;
	var posY = relativeHeight/2 - 180/2;
	
	//@Todo: eliminare i parametri passati su url 
	winPopUp=window.open(Url, 'browseList', 'width=387,height=180,left='+posX+',top='+posY+',scrollbars=no');
}

function openPopUp(isFromCatalog)
{
	var relativeWidth = top.document.getElementById('mainFrameSet').offsetWidth;
	var relativeHeight = top.document.getElementById('mainFrameSet').offsetHeight;
	var posX = relativeWidth/2;
	var posY = relativeHeight/2;
	var newListUrl=openNewListUrl;
	
	if(isFromCatalog) newListUrl=newListUrl+'?fromCatalog=true';
	else newListUrl=newListUrl+'?fromCatalog=false';
	winPopUp=window.open(newListUrl, 'browseList', 'width=370, height=185,left='+posX+',top='+posY+',scrollbars=no');
	winPopUp.focus();
}


function renPopUp(listId,listName)
{
	var relativeWidth = top.document.getElementById('mainFrameSet').offsetWidth;
	var relativeHeight = top.document.getElementById('mainFrameSet').offsetHeight;
	var posX = relativeWidth/2;
	var posY = relativeHeight/2;
	
	//@Todo: eliminare i parametri passati su url 
    winPopUp=window.open(openRenListUrl+'?renListId='+listId+'&renListName='+listName, 'browseList', 'width=387,height=120,left='+posX+',top='+posY+',scrollbars=no');
	winPopUp.moveTo(posX,posY);
	winPopUp.focus();
}

function copyPopUp(listId,listName)
{
	var relativeWidth = top.document.getElementById('mainFrameSet').offsetWidth;
	var relativeHeight = top.document.getElementById('mainFrameSet').offsetHeight;
	var posX = relativeWidth/2 - 387/2;
	var posY = relativeHeight/2 - 120/2;

	//@Todo: eliminare i parametri passati su url
	winPopUp=window.open(openCopyListUrl+'?srcListId='+listId+'&srcListName='+listName, 'browseList', 'width=387,height=120,left=' + posX + ',top=' + posY + ',scrollbars=no');
}

function askConfirmation(url,listId)
{
	var newUrl = url+'?remListId='+listId;
	a = confirm("Confermare l'operazione\?");
	if (a) {
	 	top.workframe.location.href = newUrl;
	}
}

function askConfirmationDelete(url,listId,ListName,Msg1,Msg2)
{
	var newUrl = url+'?remListId='+listId;
	a = confirm(Msg1 + ListName + Msg2 + "\?");
	if (a) {
	 	top.workframe.location.href = newUrl;
	}
}


/*
	Show homepage.
*/
function showHomePage()
{
	//	Carico nel frame centrale la homepage dello store e aggiungo come parametri lo stato
	//	attuale dei checkbox immagini e lire (nella workarea).
	var newWorkAreaUrl = loadHomeAreaUrl;
	top.workframe.location.href = newWorkAreaUrl;
}



/**
	Retrieve ordering or filtering params from the dialog and propagate the
	submit.
*/
function propagateDialogsSubmit(paramArray)
{
	//	Perform a filter of sort action.
	submitFormExtended("sortFilterForm", null, null, paramArray);
}



/**
	Back to order list.
*/
function backToOrder(pageParamName, currentPage)
{
	document.location.href = backToOrderUrl + "?" + pageParamName + "=" + currentPage;
}


/**
	Handle category path click (synchronize tree and load the corresponding
	product list).
*/
function handleCategoryPath(idArray) {
	//	Load corresponding product list.
	synchronizeTree(idArray);
}


function showFavorites()
{
	//	Hide dialogs.
	hideDialogs();

	//	Get the value of the list
	var viewMode = document.getElementById("js-viewselect").value;

	//	Prepare parameters for the LoadTrolleyRight action.
	var newWorkAreaUrl = visFavoritesUrl;

	if(viewMode!=null && viewMode != 0)
	{
		newWorkAreaUrl+="?viewMode=" + viewMode;
		top.workframe.location.href = newWorkAreaUrl;
	}
}

/**
	Code used to get promotion history details (promo target of other promos with history conditions)
*/
function showPromoHistoryDetails(divContent)
{
	try
	{
		//	Set dialog content.
		overlib(divContent, STICKY, CAPTION, '&nbsp;Dettagli promozione', LEFT, ABOVE, OFFSETX, 10, OFFSETY, 10, WIDTH, 330, HEIGHT, 60, CLOSECLICK, TIMEOUT, 8000, FGCOLOR, '#f5c838', BGCOLOR, '#e60003', CAPCOLOR, '#ffffff', CLOSECOLOR, '#ffffff', TEXTCOLOR, '#021c5c', CLOSETEXT, 'Chiudi&nbsp;');
	}
	catch(e) { /* Ignore exception */ }
}


function getPromoHistoryDetails(promoId)
{
	try
	{
		//	Prepare url.
		urlToCall = historyDetailsPromoUrl + "?promoId=" + promoId;

		//	Build response wrapper function e call it.
		ajaxWrapper = new ajaxCallWrapper(urlToCall, showPromoHistoryDetails, false);
		ajaxWrapper();
	}
	catch(e) { /* Nothing. */ }
}


function showInfoSearchPopUp(url)
{
	window.open(url,'nome','scrollbars=yes,resizable=no,width=387,height=360,status=no,location=no,toolbar=no');
}

/**
	Load library advanced search page.
*/

function loadAdvancedSearch()
{
	submitFormExtended('headerForm', simpleSearchLibraryUrl, null, ['actionMethod', 'loadAdvancedSearch']);
}



function loadCatalogHome(libraryFormId, catalogHomeAction)
{
	var libraryForm = document.getElementById(libraryFormId);

	libraryForm.action = catalogHomeAction;
	libraryForm.submit();
}

function performAuthorSearch(authorString)
{
	submitFormExtended('headerForm', simpleSearchLibraryUrl, null, ['actionMethod', 'simpleSearch', 'simpleCriterium', 0, 'simpleText', authorString]);
}


function performPublisherSearch(publisherString)
{
	submitFormExtended('headerForm', simpleSearchLibraryUrl, null, ['actionMethod', 'simpleSearch', 'simpleCriterium', 2, 'simpleText', publisherString]);
}

function performSeriesSearch(seriesString)
{
	submitFormExtended('headerForm', searchSeriesUrl, null, ['actionMethod', 'searchSeries', 'advancedSeriesCriteria', seriesString]);
}


function performSimpleSearchCheck()
{
	var headerForm = document.forms["headerForm"];
	var searchedString = headerForm.elements["simpleText"].value

	//	Trim spaces.
	searchedString = searchedString.replace(/^\s*/g, '').replace(/\s*$/g, '');
	searchedString = searchedString.replace(/[\s]+/g, ' ');

	//	Check string validity.
	if(searchedString == null || searchedString == "")
	{
		alert("Inserire i termini da ricercare");
		headerForm.elements["simpleText"].value = '';
		return(false);
	}

	/*var tokenArray = searchedString.split(" ");

	for(var i = 0; i < tokenArray.length; i++)
	{
		if(tokenArray[i].length <= 0)
		{
			alert("Inserire il termine da ricercare");
			return(false);
		}
	}*/
}

function performSimpleSearch()
{
	var headerForm = document.forms["headerForm"];
	var searchedString = headerForm.elements["simpleText"].value

	//	Trim spaces.
	searchedString = searchedString.replace(/^\s*/g, '').replace(/\s*$/g, '');
	searchedString = searchedString.replace(/[\s]+/g, ' ');

	//	Check string validity.
	if(searchedString == null || searchedString == "")
	{
		alert("Inserire i termini da ricercare");
		headerForm.elements["simpleText"].value = '';
		return(false);
	}

	/*var tokenArray = searchedString.split(" ");

	for(var i = 0; i < tokenArray.length; i++)
	{
		if(tokenArray[i].length <= 3)
		{
			alert("Ogni termine della ricerca deve essere lungo almeno 4 caratteri");
			return;
		}
	}*/

	submitFormExtended('headerForm', simpleSearchLibraryUrl, null, ['actionMethod', 'simpleSearch']);
}

function performAdvancedSearch()
{
	submitFormExtended('bodyForm', null, null, null);
}

function showSimpleSearchPage(newPage, TotalPages)
{
	newPage = (newPage < 0 ? 0 : newPage);
	newPage = (newPage > TotalPages ? TotalPages : newPage);

	submitFormExtended('bodyForm', simpleSearchLibraryUrl, null, ['actionMethod','simpleSearchPage', 'simpleSearchPageNumber', newPage]);
}

function showAdvancedSearchPage(newPage, TotalPages)
{
	newPage = (newPage < 0 ? 0 : newPage);
	newPage = (newPage > TotalPages ? TotalPages : newPage);

	submitFormExtended('bodyForm', advancedSearchLibraryPageUrl, null, ['actionMethod','advancedSearchPage', 'advancedSearchPageNumber', newPage]);
}

function loadAdvancedSearch()
{
	submitFormExtended('bodyForm', simpleSearchLibraryUrl, null, ['actionMethod', 'loadAdvancedSearch']);
}

function showByCategory(storeId)
{
	var categorySelected = document.getElementById("showByCategoryId");
	synchronizeTreeOnly([storeId, categorySelected.value]);
	submitFormExtended('bodyForm', loadLibraryListUrl, null, ['actionMethod','showByCategory']);
}

function showByCategoryPage(newPage, TotalPages)
{
	newPage = (newPage < 0 ? 0 : newPage);
	newPage = (newPage > TotalPages ? TotalPages : newPage);

	submitFormExtended('bodyForm', loadLibraryListUrl, null, ['actionMethod','showByCategoryPage', 'showByCategoryPageNumber', newPage]);
}


function loadBookDetails(currentEvent)
{
	//	Retrieve source tag and its id.
	if(!currentEvent) var currentEvent = window.event;
	if(currentEvent.target) var sourceTag = currentEvent.target;
	else if(currentEvent.srcElement) var sourceTag = currentEvent.srcElement;

	//	Retrieve product index from tag identifier.
	var sourceTagId = sourceTag.id;
	var sourceTagIdArray = sourceTagId.split("-");
	var productIndex = sourceTagIdArray[2];

	//	Show product details.
	submitFormExtended('bodyForm', loadBookDetailsUrl, null, ['productDetailId', productItems[productIndex].idProduct]);
}

function loadBookDetailsFromId(productId)
{
	//	Show product details.
	submitFormExtended('bodyForm', loadBookDetailsUrl, null, ['productDetailId', productId]);
}

function showInfoSearchPopUp(url)
{
	window.open(url,'nome','scrollbars=yes,resizable=no,width=390,height=360,status=no,location=no,toolbar=no');
}

function checkAdvancedSearch(formId)
{
	var titolo = document.getElementById('titolo');
	var author = document.getElementById('author');
	var keyword = document.getElementById('keyword');
	var editor = document.getElementById('editor');
	var series = document.getElementById('series');
	var isbn = document.getElementById('isbn');
	var publicationYearFrom = document.getElementById('publicationYearFrom');
	var publicationYearTo = document.getElementById('publicationYearTo');
	var priceInEuroFrom = document.getElementById('priceInEuroFrom');
	var priceInEuroTo = document.getElementById('priceInEuroTo');

	formObj = document.getElementById(formId);

	if(titolo.value=="" && author.value=="" &&
		keyword.value=="" && editor.value=="" &&
		series.value=="" && isbn.value=="" &&
		publicationYearFrom.value=="" && publicationYearTo.value=="" &&
		priceInEuroFrom.value=="" && priceInEuroTo.value=="")

		alert(needFieldAlertText);
	else
	{
		formObj.submit();
	}
}







/**
	Send order action.
 */
function sortProductList()
{
	//	Get sorting criteria.
	var criteriaTag = document.getElementById("js-criteria");
	var criteriaValue = criteriaTag.value.split("-")[0];

	//	Get sort order.
	var sortOrderValue = "";
	for(var i = 0; i < document.chooseordering.sortorder.length; i++)
	{
		if(document.chooseordering.sortorder[i].checked == true) sortOrderValue = document.chooseordering.sortorder[i].value;
	}

	var parametersArray = new Array();

	//	Reload work area.
	if(criteriaValue != "orderByCustom")
	{
		//	Standard criteria.
		parametersArray.push("actionMethod");
		parametersArray.push(criteriaValue);
		parametersArray.push("orderOption");
		parametersArray.push(sortOrderValue);
		parametersArray.push("orderCriteriaString");
		parametersArray.push((criteriaValue == "orderByName" ? "Nome" : "Prezzo"));
	}
	else
	{
		//	Custom criteria.
		parametersArray.push("actionMethod");
		parametersArray.push(criteriaValue);
		parametersArray.push("orderCustomId");
		parametersArray.push(criteriaTag.value.split("-")[1]);
		parametersArray.push("orderOption");
		parametersArray.push(sortOrderValue);
		parametersArray.push("orderCriteriaString");
		parametersArray.push(criteriaTag.value.split("-")[2]);
	}

	//	Prepare parameters for LoadProductList action.
	opener.propagateDialogsSubmit(parametersArray);

	//	Close this dialog.
	this.close();
}



/**
	Change filtering criteria.
 */
function changeFilterCriteria(criteriaTag)
{
	var currentCriteriaValue = criteriaTag.value;
	var currentCriteriaArray = currentCriteriaValue.split("-");

	var currentCriteria = currentCriteriaArray[0];
	var currentCriteriaNumber = currentCriteriaArray[1];

	for(var i = 0; i < document.choosefilter.criteria.length; i++)
	{
		if(currentCriteriaNumber == (i + 1))
		{
			var currentHeader = document.getElementById("js-header-" + (i + 1));
			var currentCompo = document.getElementById("js-compo-" + (i + 1));

			currentHeader.style.display = "block";
			currentCompo.style.display = "block";
		}
		else
		{
			var currentHeader = document.getElementById("js-header-" + (i + 1));
			var currentCompo = document.getElementById("js-compo-" + (i + 1));

			currentHeader.style.display = "none";
			currentCompo.style.display = "none";
		}
	}
}


function filterProductList()
{
	//	Get filtering criteria.
	var criteriaTag = document.getElementById("js-criteria");
	var criteriaValue = criteriaTag.value.split("-")[0];
	var customOptionId = "";

	var parametersArray = new Array();

	if(criteriaValue == "filterByPrice")
	{
		var criteriaOption = document.getElementById("criteria" + criteriaValue);
		var criteriaOptionNewValue = "" + criteriaOption.value;
		criteriaOptionNewValue = criteriaOptionNewValue.replace(/\./g, 'a');
		criteriaOptionNewValue = criteriaOptionNewValue.replace(/\,/g, '.');
		criteriaOptionNewValue = criteriaOptionNewValue.replace(/a/g, ',');

		var parsedInteger = parseInt(criteriaOptionNewValue);
		var parsedFloat = parseFloat(criteriaOptionNewValue);

		if(	criteriaOptionNewValue == '' ||
			!(	(parsedInteger == criteriaOptionNewValue && parsedInteger >= 0) ||
				(parsedFloat == criteriaOptionNewValue && parsedFloat >= 0)))
		{
			alert("Inserire un numero");
			criteriaOption.value = "";
			return(false);
		}

		criteriaOption.value = criteriaOptionNewValue;

		parametersArray.push("actionMethod");
		parametersArray.push(criteriaValue);
		parametersArray.push("filterOption");
		parametersArray.push(criteriaOptionNewValue);
		parametersArray.push("filterCriteriaString");
		parametersArray.push("Prezzo");
		parametersArray.push("filterCriteriaValueString");
		parametersArray.push(criteriaOptionNewValue);
	}
	else if(criteriaValue == "filterByCustom")
	{
		var criteriaOption = document.getElementById("criteria" + criteriaValue + "-" + criteriaTag.value.split("-")[1]);
		var criteriaOptionNewValue = criteriaOption.value.split("-")[0];

		parametersArray.push("actionMethod");
		parametersArray.push(criteriaValue);
		parametersArray.push("filterCustomId");
		parametersArray.push(criteriaTag.value.split("-")[2]);
		parametersArray.push("filterCustomOption");
		parametersArray.push(criteriaOptionNewValue);
		parametersArray.push("filterCriteriaString");
		parametersArray.push(criteriaTag.value.split("-")[3]);
		parametersArray.push("filterCriteriaValueString");
		parametersArray.push(criteriaOption.value.split("-")[1]);
	}
	else
	{
		var criteriaOption = document.getElementById("criteria" + criteriaValue);
		var criteriaOptionNewValue = criteriaOption.value;

		parametersArray.push("actionMethod");
		parametersArray.push(criteriaValue);
		parametersArray.push("filterOption");
		parametersArray.push(criteriaOptionNewValue);
		parametersArray.push("filterCriteriaString");
		parametersArray.push("Marca");
		parametersArray.push("filterCriteriaValueString");
		parametersArray.push(criteriaOptionNewValue);
	}

	//	Prepare parameters for LoadProductList action.
	opener.propagateDialogsSubmit(parametersArray);

	//	Close this dialog.
	this.close();
}


function deleteFilter()
{
	//	Get current store and category id.
	var storeId = opener.storeIdNumber;
	var categoryId = opener.categoryIdNumber;

	var parametersArray = new Array();

	parametersArray.push("actionMethod");
	parametersArray.push("deleteFilter");

	//	Prepare parameters for LoadProductList action.
	opener.propagateDialogsSubmit(parametersArray);

	//	Close this dialog.
	this.close();
}






/**	Global variables. */
var logoffUrl = null;
var logoutConfirmString = "[handleSearchClick] Attenzione! La stringa di conferma logout non e' stata definita";

var searchStringError = "[handleSearchClick] Attenzione! La stringa di errore non e' stata definita";

var minimumSearchStringLength = "error";


/** Submit search string and perform search. */
function handleSearchClick()
{
	//	Retrieve text input tag value.
	var stringTag = document.getElementById("searchString");

	if(stringTag != null)
	{
		var searchString = stringTag.value;

		//	Check string validity.
		if(handleSearchStringCheck(searchString))
		{
			//	Load default top image.
			loadDefaultShelfImage();

			//	Submit search.
			submitFormExtended("searchForm", null, null, null);
			return(true);
		}
		else
		{
			return(false);
		}
	}

	return(false);
}


/** Check product search string validity. */
function handleSearchStringCheck(searchString)
{
	if(isNaN(minimumSearchStringLength))
	{
		alert("[handleSearchClick] Attenzione! La lunghezza minima dei token non e' stata definita");
	}

	//	Check string validity.
	if(searchString == null || searchString == "") return(false);

	//	Trim spaces.
	searchString = searchString.replace(/^\s*/g, '').replace(/\s*$/g, '');
	searchString = searchString.replace(/[\s]+/g, ' ');

	//	Retrieve tokens.
	var splittedString = searchString.split(" ");

	for(i = 0; i < splittedString.length; i++)
	{
		if(splittedString[i].length < minimumSearchStringLength)
		{
			//	Show an error message.
			alert(searchStringError);
			return(false);
		}
	}

	return(true);
}

/**	Direct logoff */
function userLogout()
{
	top.location.href = logoffUrl;
}

/** Ask for logout confirmation. */
function confirmUserLogout()
{
	if(logoffUrl != null)
	{
		if(confirm(logoutConfirmString))
		{
			top.location.href = logoffUrl;
		}
	}
}


/**
	Submit Form ConfirmOrder
*/
function submitConfirmOrder(image)
{
	document.forms[0].submit();
	image.onclick= 'function dummy {return(0);}'
}


/**
	Check delivery instructions text area.
*/
function checkDeliveryChar(currentEvent)
{
	var textareaTag = document.getElementById("sendIndications");

	if(textareaTag != null)
	{
		//	Get current content of textarea.
		var currentString = textareaTag.value;

		//	Retrieve current event if needed.
		if(!currentEvent) currentEvent = window.event;

		//	Retrieve keycode (handle mozilla and internet explorer difference).
		var keyCode = (currentEvent.which != null ? currentEvent.which : currentEvent.keyCode);

		if(keyCode == 8 || keyCode == 46 || keyCode == 16)
		{
			//	Cancel or shift keys are always enabled.
			return(true);
		}

        return (currentString.length <= 399);
	}
}

function formatDeliveryText(textArea)
{
	var textString = (textArea.value != undefined ? textArea.value : "");
	textString = textString.replace(/\r/g, '');
	textArea.value = textString.replace(/\n\n/g, '\n');
}