/**
 *	Common functions and objects used across the whole site.
 */

function trimString( string ) {
    return(string.replace('&nbsp;', ' ').replace(/^\s*/g, '').replace(/\s*$/g, ''));
}


/**
* sets the value of the checked attribute for a control
*/
function setChecked( controlName, state ) {
    var control = document.getElementById(controlName);
    control.checked = state != null ? state : true;
}


/**
* sets the given param to the given value into the form of given id, and submits the form
*/
function submitForm( formId, param, value, param2, value2 ) {
    var form = document.forms[ formId ];
    if ( form == null ) {
        alert( "Errore: la pagina non contiene un form di nome '" + formId + "'" );
        return;
    }
    if ( param ) form.elements[ param ].value = value;
    if ( param2 ) form.elements[ param2 ].value = value2;
    form.submit();
}


/**
* switches the display style for the box boxName to "inline" if state is true and none state is false
*/
function changeBoxState( boxName, state ) {
    var element = document.getElementById( boxName );
    element.style.display = state ? 'inline' : 'none';
}

function switchBoxState( boxName ) {
    var element = document.getElementById( boxName );
    element.style.display = element.style.display == 'none' ? 'inline' : 'none';
}


function getSourceByEvent(currentEvent)
{
	var sourceTag = null;
	if(!currentEvent) currentEvent = window.event;
	if(currentEvent.target) sourceTag = currentEvent.target;
	else if(currentEvent.srcElement) sourceTag = currentEvent.srcElement;

	return sourceTag;
}


function getKeyCodeByEvent(currentEvent)
{
    //	Retrieve keycode (handle mozilla and internet explorer difference).
    return(currentEvent.which != null ? currentEvent.which : currentEvent.keyCode);
}


/**
	Provide emulation for push method (not supported by Explorer 5.0).
*/
function emulatePush()
{
	for(var A_p = 0; A_p < arguments.length; A_p++) {
		this[this.length] = arguments[A_p];
	}

	return this.length;
}

if(typeof(Array.prototype.push) == "undefined")
{
	Array.prototype.push = emulatePush;
}


/**
	Compute an html object X and Y coordinates.
*/
function findPosX(element)
{
	if(element == null) return(0);

	if(element.offsetParent) {
		var currentLeft = 0;
		while(element.offsetParent) {
			currentLeft += element.offsetLeft;
			element = element.offsetParent;
		}
		return(currentLeft);
	}
	else {
		if(element.x) return(element.x);
		else return(0);
	}
}


function findPosY(element)
{
	if(element == null) return(0);

	if(element.offsetParent) {
		var currentTop = 0;
		while(element.offsetParent) {
			currentTop += element.offsetTop;
			element = element.offsetParent;
		}
		
		return(currentTop);
	}
	else {
		if(element.y) return(element.y);
		else return(0);
	}
}


/**
	Submit the frame formName setting up all the given parameters.
*/
function submitFormInOtherFrame(document, formName, actionUrl, targetFrame, paramArray)
{
	if(document && formName) {
        var form = document.forms[formName];
        submitFormExtendedPrivate(form, actionUrl, targetFrame, paramArray);
    }
}

function submitFormExtended(formName, actionUrl, targetFrame, paramArray)
{
	if(formName) {
		var form = document.forms[formName];
		submitFormExtendedPrivate(form, actionUrl, targetFrame, paramArray);
	}
}

function submitFormExtendedPrivate(form, actionUrl, targetFrame, paramArray)
{
    if(form) {
		//	Setup form parameters (even number -> paramName, paramValue).
		if(paramArray && (paramArray.length % 2) == 0) {
            for(var i = 0; i < paramArray.length; i += 2) {
                if(form.elements[paramArray[i]]) form.elements[paramArray[i]].value = paramArray[i + 1];
            }
        }

		if(actionUrl) form.action = actionUrl;
		if(targetFrame) form.target = targetFrame;
		form.submit();
	}
}


/**
	Provide formatting for euro prices.
*/
function formatEuro(price)
{
	if(price != null) {
		//	Convert price to a string and split it.
		var priceArray = ("" + price).split(".");

        var integerPart = priceArray[0];
        var decimalPart = "00";

        if(priceArray.length != 1) {
			decimalPart = priceArray[1];
			if(priceArray[1].length == 1) {
				decimalPart += "0";
			}
		}

		var finalIntegerPart = "";
		var splittedIntegerPart = integerPart.split("");

		for(var i = (splittedIntegerPart.length - 1), j = 0; i >= 0; i--, j++)
		{
			if((j % 3) == 0 && j != 0) finalIntegerPart = "." + finalIntegerPart;
			finalIntegerPart = splittedIntegerPart[i] + finalIntegerPart;
		}
	
		return(finalIntegerPart + "," + decimalPart);
	} else {
		return(null);
	}
}


/**
	Provide formatting for lira prices.
*/
function formatLire(price)
{
	if(price != null) {
		var splittedPriceString = ("" + price).split("");
        var finalString = "";

		for(var i = (splittedPriceString.length - 1), j = 0; i >= 0; i--, j++)
		{
			if((j % 3) == 0 && j != 0) finalString = "." + finalString;
			finalString = splittedPriceString[i] + finalString;
		}
	
		return(finalString);
	}
	else {
		return(null);
	}
}


/**
 *  Methods used to open popups.
 */
function openPopupPrivate(dialogUrl, popupName, width, height, options)
{
    if(popupName != null && dialogUrl != null && width != null && height != null)
    {
        //	Compute dialog position.
        var relativeWidth = 0;
        var relativeHeight = 0;

        //noinspection JSUnusedLocalSymbols
        try {
            relativeWidth = screen.width;
            relativeHeight = screen.height;
        } catch(e) {}

        //noinspection JSUnusedLocalSymbols
        try {
            relativeWidth = top.document.getElementById('mainFrameSet').offsetWidth;
            relativeHeight = top.document.getElementById('mainFrameSet').offsetHeight;
        } catch(e) {}

        var posX = (relativeWidth - width) / 2;
        var posY = (relativeHeight - height) / 2;

        var winPopUp = window.open(dialogUrl, popupName, 'resizable=no, width=' + width + ', height=' + height + ', left=' + posX + ', top=' + posY + ', status=no, location=no, toolbar=no' + (options != null ? ", " + options : ""));
        winPopUp.focus();

        return(winPopUp);
    } else return(null);
}

function openPopup(dialogUrl, popupName, width, height)
{
    return(openPopupPrivate(dialogUrl, popupName, width, height, "scrollbars=no"));
}

function openPopupWithScroll(dialogUrl, popupName, width, height)
{
    return(openPopupPrivate(dialogUrl, popupName, width, height, "scrollbars=yes"));
}


function popupDispoConsegnaPrivate(dialogUrl, width, height)
{
	var relativeWidth = screen.width;
	var relativeHeight = screen.height;

	var posX = (relativeWidth - width) / 2;
    var posY = (relativeHeight <= 601) ? 2 : (608 - height) / 2;

	var winPopUp = window.open(dialogUrl, "deliverypopup", 'width=' + width + ',height=' + height + ',left=' + posX + ',top=' + posY + ',scrollbars=no');
    return(winPopUp);
}

function popupDispoConsegna(dialogUrl)
{
    return(popupDispoConsegnaPrivate(dialogUrl, 620, 460));
}

function popupDispoConsegnaFreeVisit(dialogUrl)
{
	return(popupDispoConsegnaPrivate(dialogUrl, 620, 432));
}


/**
 * Preload images.
 */
function performImagesPreload() {
    //noinspection JSUnusedLocalSymbols
    try {
        if(document.images) {
            var loadedImages = new Array(preloadImagesArray.length);

            for(var i = 0; i < preloadImagesArray.length; i++)
            {
                loadedImages[i] = new Image();
                loadedImages[i].src = preloadImagesArray[i];
            }

            return(loadedImages);
        }
    } catch(e) {}

    return(null);
}


/**	Check name length and cut the string adding '...' if needed. */
function checkStringLengthNew(checkString, className, maxSize)
{
	//	Check string valitidy.
	if(checkString == null || maxSize == null) return 0;

	//	Replace &nbsp; with a simple space and trim spaces.
    checkString = trimString(checkString);

	//	Retrieve ruler span tag and set its class.
	var rulerSpan = document.getElementById('ruler');
	rulerSpan.className = className;

	var buildedString = "";
	var index = 0;
	var previousSize = -1;
	var addString = "";

	rulerSpan.innerHTML = buildedString;

	while(parseInt(rulerSpan.offsetWidth) < maxSize && index < checkString.length)
	{
		previousSize = parseInt(rulerSpan.offsetWidth);

		addString = "";
		if(checkString.charAt(index) == ' ')
		{
			addString = ' ';
			while(index < checkString.length && checkString.charAt(index) == ' ')
			{
				addString += checkString.charAt(index);
				index++;
			}
		}

		if(checkString.charAt(index) == '&')
		{
			while(index < checkString.length && checkString.charAt(index) != ';')
			{
				addString += checkString.charAt(index);
				index++;
			}
			buildedString += addString + ";";
			rulerSpan.innerHTML = buildedString;
			index++;
		}
		else
		{
			buildedString = buildedString + addString + checkString.charAt(index);
			rulerSpan.innerHTML = buildedString;
			index++;
		}
	}

	return((buildedString.length < checkString.length ? buildedString + "..." : checkString));
}


/**	Check name length and cut the string adding '...' if needed. */
function checkStringLength(checkString, maxSize)
{
	if(checkString == null || maxSize == null) return 0;

	//	Replace &nbsp; with a simple space.
	checkString = trimString(checkString);

	//	Compute real string length.
	var realStringLength = 0;
	var htmlStringLength = 0;
	for(var i = 0; i < checkString.length; i++)
	{
		if(checkString.charAt(i) == '&') htmlStringLength = 0;
		if(checkString.charAt(i) == ';') {
			realStringLength -= htmlStringLength;
			htmlStringLength = 0;
		}

		realStringLength++;
		htmlStringLength++;
	}

	if(realStringLength > (maxSize + 3))
	{
		//	Cut string and put '...' at the end.
		var lastChar = 0;
		for(i = 0; i < maxSize; i++)
		{
			if(checkString.charAt(lastChar) == '&') {
				while(checkString.charAt(lastChar) != ';') lastChar++;
			}
			lastChar++;
		}

		checkString = checkString.substr(0, lastChar) + "...";
	}

	return(checkString);
}


/**	Open help Pop up in the login page */
function openOnlineShoppingAdvsPopup(popupUrl)
{
	winPopUp=window.open(popupUrl, 'vantaggispesaonline', 'width=386, height=376,scrollbars=no');
}

function openSpecialDeliveryPopup(popupUrl)
{
	winPopUp=window.open(popupUrl, 'popupspecialdelivery', 'width=446, height=478, scrollbars=yes');
}

function openProductFlagsPopup(popupUrl)
{
	winPopUp=window.open(popupUrl, 'popupproductflags', 'width=580, height=390, scrollbars=yes');
}

function openHelpPopUp(fromPage, errors)
{
	var newHelpUrl=openHelpUrl + "?fromPage=" + fromPage + "&errors=" + errors;
	
	openHelpPopUpGlobal(newHelpUrl);
}

function openHelpPopUpFromCustomer()
{
	var newHelpUrl=openHelpUrl + "?fromPage=customerCare&targetFormName=customerFormId";

	openHelpPopUpGlobal(newHelpUrl);
}

function openHelpPopUpGlobal(popupUrl)
{
	winPopUp=window.open(popupUrl, 'browseList', 'width=457,height=450,scrollbars=no');
}


/**	Show product info popup. */
function showProductInfoDialog(productId, storeId)
{
	//	Hide dialogs.
	hideDialogs();

	//	Dialog size.
	var dialogWidth = 408;
	var dialogHeight = 251;

	//	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 = top.loadProductInfoUrl + "?productId=" + productId + "&storeId=" + storeId;

	if(	top.productInfoPopUpHandle && !top.productInfoPopUpHandle.closed &&	top.productInfoPopUpHandle.close) {
		top.productInfoPopUpHandle.close();
	}

	top.productInfoPopUpHandle = window.open(dialogUrl, 'productinfo', 'scrollbars=no, resizable=no, width=' + dialogWidth + ', height=' + dialogHeight + ', left=' + posX + ', top=' + posY + ', status=no, location=no, toolbar=no');
	top.productInfoPopUpHandle.focus();
}


/** Check Numeric for Telephone Number. */
function checkNumericTypedChar(currentEvent)
{
    //	Retrieve keycode (handle mozilla and internet explorer difference).
    var keyCode = getKeyCodeByEvent(currentEvent);

    if((keyCode == 0 || keyCode == 8 || keyCode == 16) || (keyCode >= 48 && keyCode <=57)) {
        //	Tab, cancel or shift keys are always enabled.
        return(true);
    } else {
        // Others keys are always disabled.
        return(false);
    }
}


/*
	Functions used to manage personal list functionalities.
*/
function createPersonalList()
{
	//	Hide dialogs.
	hideDialogs();

	//	Get the value of the list
	var listId = document.getElementById("js-listselect").value;
	if(listId == 'New') openPopUp(true);
}


function addToPersonalList(productIndex)
{
	//	Hide dialogs.
	hideDialogs();

    //	Get the value of the list
    var listId = parseInt(document.getElementById("js-listselect").value);
    if(isNaN(listId)) {
        alert(listPutSelectPersonalListMsg);
        return;
    }

	//	Check if grouped by groupid.
	var productInGroupSelect = document.getElementById("js-productInGroup-" + productIndex);
    var selectedProductIndex = (productInGroupSelect != null && productInGroupSelect.value != null) ? productInGroupSelect.value : productIndex;
    var productInfo = productItems[selectedProductIndex];

    var optionsString = "";
    //noinspection JSUnusedLocalSymbols
    try {
        var optionIdArray = getSelectedProductOptions(productInGroupSelect != null, document, "js-", productInfo, selectedProductIndex);
        if(optionIdArray != null && optionIdArray.length > 0) {
            optionsString = "&options=";
            for(var i = 0; i < optionIdArray.length; i++)
            {
                if(i != 0) optionsString += "_";
                optionsString += optionIdArray[i];
            }
        }
    } catch(e) {
        //  Stop here and return immediatly.
        return;
    }

    incrementListSizeById(listId);
    top.submitframe.location.href = (submitListUrl + "?productId=" + productInfo.idProduct + optionsString + "&listId=" + listId);
}


function addToPersonalListFreeVisit()
{
    top.workframe.location.href = submitListUrl;
}


function removeSelectedProductsFromPersonalList( listId )
{
    //	Hide dialogs.
    hideDialogs();

    var selectedListLineIds = getSelectedListLineIds();

    if ( selectedListLineIds.length > 0 ) {
        removeProductsFromPersonalList( listId, selectedListLineIds );
    }
    else {
        alert( "Seleziona i prodotti da rimuovere cliccando sui relativi checkbox." );
    }
}

function removeProductFromPersonalList( listId, listLineId )
{
    var listLineIds = new Array(); listLineIds.push( listLineId );
    removeProductsFromPersonalList( listId, listLineIds );
}

function removeProductsFromPersonalList( listId, listLineIds )
{
    var finalRemoveListUrl = removeListUrl + "?listId=" + listId + "&selectedListLineIds=" + listLineIds.join( "," );

    document.getElementById("js-listselect").value = listId;
    decrementListSizeById( listId, listLineIds.length );

    top.workframe.location.href = finalRemoveListUrl;
}

function getSelectedListLineIds() {
    var selectedProductIndexes = getSelectedProductIndexes();

    var listLineIds = new Array();
    for ( var whichProductIndex = 0 ; whichProductIndex < selectedProductIndexes.length ; whichProductIndex++ ) {
        listLineIds.push( getSelectionCheckbox( selectedProductIndexes[ whichProductIndex ] ).value );
    }

    return listLineIds;
}


function getSelectedProductIndexes() {
    var productIndexes = new Array();

    var checkbox;
    for ( var productIndex = 0 ; ( checkbox = getSelectionCheckbox( productIndex ) ) != null ; productIndex++ ) {
        if ( checkbox.checked ) {
            productIndexes.push( productIndex );
        }
    }

    return productIndexes;
}

function getSelectionCheckbox( productIndex ) {
    return document.getElementById( "selectFromList-" + productIndex );
}


function showPersonalList()
{
	//	Hide dialogs.
	hideDialogs();

	//	Get the value of the list
	var listId = document.getElementById("js-listselect").value;

	if(listId=='NaN') {
		alert(listPutSelectPersonalListMsg);
		return;
	}

	if(listId=='New') {
		openPopUp(true);
	} else {
		// Get and checkthe size for the current list selected in the combo box
		if(shoppingListSize != null && shoppingListSize.length > 0){
			for(i = 0; i < shoppingListSize.length; i++) {
				if(shoppingListSize[i].id == listId) {
					if(shoppingListSize[i].size > 0) {
						loadDefaultShelfImage();
						top.workframe.location.href = visPersonalListUrl + "?visListId=" + listId;
					} else {
						educationalPopUp(educationalPopUpUrl);
					}
				}
			}
		}
	}
}


function decrementListSizeById(listId, howMany) {
	if(shoppingListSize != null && shoppingListSize.length > 0) {
		for(i=0; i < shoppingListSize.length; i++) {
			if(shoppingListSize[i].id == listId) {
				shoppingListSize[i].size = shoppingListSize[i].size - howMany;
			}
		}
	}
}

function incrementListSizeById(listId) {
	if(shoppingListSize != null && shoppingListSize.length > 0) {
		for(i=0; i < shoppingListSize.length; i++) {
			if(shoppingListSize[i].id == listId) {
				shoppingListSize[i].size = shoppingListSize[i].size + 1;
			}
		}
	}
}


function switchBox( which ) {
    var gp = ( which == 'gp' );
    var gold = ( which == 'gold' );
    var box = null;
    box = document.getElementById( 'gpText' );
    if (box.readOnly != !gp) {
	    box.readOnly = !gp;
	    box.value = gp ? box.value : '';
    }
    for ( var i = 1 ; i < 5 ; i++ ) {
        box = document.getElementById( 'goldText' + i );
        if (box.readOnly != !gold) {
	        box.value = gold ? box.value : '' ;
	        box.value = gold && i == 1 && box.value == '' ? '6017' : box.value;
	        box.value = gold && i == 2 && box.value == '' ? '00' : box.value;
	        box.readOnly = !gold;
	    }
    }
}


/** Function used to enable - disable continue to slot page button in checkout page. */
function disableContinueToSlotPage()
{
	//noinspection JSUnusedLocalSymbols
    try {
		//	Set continue button to disabled in checkout page (temporary).
		top.workframe.continueToSlotPageDisabled = true;
	} catch(e) {}
}

function enableContinueToSlotPage()
{
	//noinspection JSUnusedLocalSymbols
    try {
		//	Set continue button to disabled in checkout page (temporary).
		top.workframe.continueToSlotPageDisabled = false;
	} catch(e) {}
}


/** Load the corresponding image on the top menu. */
function loadDefaultShelfImage() {
	//noinspection JSUnusedLocalSymbols
    try {
		//	Load shelf images
        loadShelfImage(null);
	} catch(e) {}
}

function loadShelfImageForElement(foundItem) {
    //noinspection JSUnusedLocalSymbols
    try {
        if(foundItem.shelfImg && foundItem.shelfImg != '') {
            loadShelfImage(foundItem.shelfImg);
        }
	} catch(e) {}
}

function loadShelfImage(imgName) {
    //noinspection JSUnusedLocalSymbols
    try {
        imgName = (imgName == null || imgName == "") ? "default" : imgName;

        var shelfImageTableTag = top.topframe.document.getElementById("shelfImageTable");
        var newBackgroundImageUrl = cmsImagesUrl + 'head/' + imgName + '.jpg)';
                                           
        if(shelfImageTableTag.style.backgroundImage != 'url(' + newBackgroundImageUrl) {
            var headerImage = new Image();
            headerImage.src = newBackgroundImageUrl;
            shelfImageTableTag.style.backgroundImage = 'url(' + newBackgroundImageUrl;

        }
    } catch(e) {}
}


function printCurrentPage() {
	window.print();
}


/** Used by CMS **/
function e_openpop(url, feat) {
    window.open(url, "", feat);
}


/** Temporary Ajax support */
function ajaxCallWrapper(url, functionToCall, isXmlResponse)
{
	//	Create request object.
	var request = false;
    if(window.XMLHttpRequest) {
        request = new XMLHttpRequest();
    } else if(window.ActiveXObject) {
        request = new ActiveXObject("Microsoft.XMLHTTP");
    }

	//	Function used to perform call.
	function call() {
	    request.onreadystatechange = handleResponse;
	    request.open("GET", url, true);
	    request.send(null);
	    return(true);
	}
	
	//	Function used to handle response.
	function handleResponse() {
		if(request.readyState == 4 && request.status == 200) {
            if(isXmlResponse) functionToCall(request.responseXML);
            else functionToCall(request.responseText);
        }
	}

	return(call);
}



/**
	Switch all defined div over images from a standard alt visualization to a floating div containing
	all related informations.
	The operation will be performed for custom tags only (ie: to the tags
	having class 'divimgover').

	Pay attention to the following two things:
	1) let the height of the overlib element be a little less than size of a single
	   line. That way the container div (whose style class is 'divImgOver') will
	   stretch to surround the content being displayed.
	2) dodgy javascript code playing around here, involving closures and
	   therefore variables scope!! Due to the way javascript define variables scope (ie:
	   saving the whole context of evaluation of the function, therefore blocking gc and
	   at the same time keeping all variables and their references), we have to force
	   a function closure (ie: let a function with free variables get an evaluation context
	   well defined during its definition).
	   If we define the function used to handle 'over' events in switchPromotionDetails
	   function, we would have a single evaluation context for every method defined during
	   the iteration, pointing to the same instance of the 'alt' variable, the last
	   one defined... that way every 'popup' would have the same content... What a pity!
	   Providing the function as the result of another function we force closure of every
	   involved variable in an indipendent context, an we can preserve content identity!
 */
var DIVIMGOVER_DETAILS_CLASS = 'divimgover';
var DIVIMGOVER_DETAILS_RIGHT_CLASS = 'divimgoverright';
var DIVIMGOVER_DETAILS_DEFAULT_TAGS = ['IMG'];
var DIVIMGOVER_DETAILS_ALL_TAGS = ['IMG', 'SPAN'];

function divOverFunction(mediumIcon, content, position)
{
	function innerOverFunctionClosure()
	{
		overlib("<div class='divImgOver'>" +
				"<table><tr><td style='vertical-align: middle;'>" +
                (mediumIcon != null ? "<img src='" + layoutImagesUrl + "promo_icons/" + mediumIcon + "' /></td><td>&nbsp;</td><td>" : "") +
				content +
				"</td></div>", position, ABOVE, WIDTH, 255, HEIGHT, 10);
	}

	return innerOverFunctionClosure;
}

function switchDivDetails(container, tagsArray)
{
    //  Check wheteher a valid parameter has been provided. Otherwise
    //  initialize them with default values.
    if(container == null) container = (document.getElementById("workareabody"));
    if(tagsArray == null) tagsArray = DIVIMGOVER_DETAILS_DEFAULT_TAGS;

    if(container != null && tagsArray != null && tagsArray.length > 0)
    {
        //  Iterate over all target tags.
        for(var tagIdx = 0; tagIdx < tagsArray.length; tagIdx++)
        {
            //	Retrieve all elements matching selected class.
            var allTags = container.getElementsByTagName(tagsArray[tagIdx]);

            //	Store all matching elements.
            var elements = [];
            for(var elementsIdx = 0; allTags != null && elementsIdx < allTags.length; elementsIdx++)
            {
                if(allTags[elementsIdx].className == DIVIMGOVER_DETAILS_CLASS ||
                   allTags[elementsIdx].className == DIVIMGOVER_DETAILS_RIGHT_CLASS) elements.push(allTags[elementsIdx]);
            }

            switchElementsDivDetails(elements);
        }
    }
}

function switchElementsDivDetails(elements)
{
    if(elements != null && elements.length > 0)
    {
        //	Iterate over all found elements.
        for(var elementIndex = 0; elementIndex < elements.length; elementIndex++)
        {
            //	Retrive current alt content.
            var title = elements[elementIndex].title;
            var alt = elements[elementIndex].alt;
            var mediumIcon = elements[elementIndex].id;

            //	Reset 'alt' and 'title' attributes.
            elements[elementIndex].title = "";
            elements[elementIndex].alt = "";

            //	Register handler in order to show the detailed informations on mouse over.
            elements[elementIndex].onmouseover = divOverFunction( mediumIcon, (alt != null ? alt : title),
                                                                  (elements[elementIndex].className == DIVIMGOVER_DETAILS_CLASS ? LEFT : RIGHT));
            elements[elementIndex].onmouseout = function() { nd(); };
        }
    }
}


/** Initialize arrays */
var singleSlotProductsInfo = new Array();
var fullSlotProductsInfo = new Array();


function slotAddToTrolley(productId) {
    addToTrolleyPrivate(singleSlotProductsInfo, productId, document, 1, "jsslot-");
}


function fullslotAddToTrolley(productId) {
    addToTrolleyPrivate(fullSlotProductsInfo, productId, document, 1, "jsslot-");
}


function toggleProductCardTab(num) {
    for(var i = 1; i <= 6; i++) {
        var current = document.getElementById('img' + i);
        if(current != null) {
            if(i != num) {
                current.src = current.src.replace(/on(_c[0-9].gif)/, 'off$1');
            } else {
                current.src = current.src.replace(/off(_c[0-9].gif)/, 'on$1');
            }
        }

        current = document.getElementById('xml' + i);
        if(current != null) {
            if(i != num) {
                current.src = current.style.display='none';
            } else {
                current.src = current.style.display='block';
            }
        }
    }
}


/*
 *  Default product card dimensions provided. Put the following div inside cms layout to customize popup dimensions
 *  <div id="onlyDim" style="display: none; width: 640; height: 320;"></div>
 */
var DEFAULT_PRODUCT_CARD_WIDTH = 413;
var DEFAULT_PRODUCT_CARD_HEIGHT = 283;

var curWidth = DEFAULT_PRODUCT_CARD_WIDTH;
var curHeight = DEFAULT_PRODUCT_CARD_HEIGHT;

function resizeProductCard(newWidth, newHeight, descriptionHeight) {

    //  Retrieve custom cms popup size - UGLY SOLUTION - TO BE CHANGED AS SOON AS POSSIBLE
    var maximumWidth = 0;
    var maximumHeight = 0;
    if(document.getElementById('onlyDim') != null)
    {
        maximumWidth = parseInt(document.getElementById('onlyDim').style.width);
        maximumHeight = parseInt(document.getElementById('onlyDim').style.height);
        newWidth = maximumWidth;
        newHeight = maximumHeight;
    }

    if (document.getElementById('prodname') != null && parseInt(document.getElementById('prodname').offsetHeight) != 0) {
        descriptionHeight = parseInt(document.getElementById('prodname').offsetHeight);
    }

    newHeight += descriptionHeight;

    if(self.innerWidth) {
        frameWidth = self.innerWidth;
        frameHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientWidth) {
        frameWidth = document.documentElement.clientWidth;
        frameHeight = document.documentElement.clientHeight;
    } else if (document.body) {
        frameWidth = document.body.clientWidth;
        frameHeight = document.body.clientHeight;
    } else return;

    if(document.layers) {
        tmp1 = parent.outerWidth - parent.innerWidth;
        tmp2 = parent.outerHeight - parent.innerHeight;
        newWidth -= tmp1;
        newHeight -= tmp2;
    }

    if(document.getElementById('onlyDim') != null) {
        newWidth = (newWidth > maximumWidth ? maximumWidth : newWidth);
        newHeight = (newHeight > maximumHeight ? maximumHeight : newHeight);
    }

    diffWidth = newWidth-curWidth;
    diffHeight = newHeight-curHeight;
    window.resizeBy(diffWidth,diffHeight);

    curWidth = newWidth;
	curHeight = newHeight;

    if(document.getElementById('alldivOverflow') != null) {
        if ( self.innerWidth ) {
            frameHeight = self.innerHeight;
        } else if ( document.documentElement && document.documentElement.clientWidth ) {
            frameHeight = document.documentElement.clientHeight;
        } else if ( document.body ) {
            frameHeight = document.body.clientHeight;
        } else return;

        document.getElementById('alldivOverflow').style.height = frameHeight + "px";
    }
}


/** Method use to select a specific catalog in the left menu. */
var MAX_COUNTER_VALUE = 100;

function selectCatalogByStoreId(storeId) {
    if(top.leftframe.selectCatalogByStoreId && top.leftframe.menuInitialized) return(top.leftframe.selectCatalogByStoreId(storeId));
    else {
        setTimeout("selectCatalogByStoreId(" + storeId + ")", 200);
        return(false);
    }
}


/**	Method used to synchronize navigation menu and work area. */
function synchronizeTree(idArray) {
	if(top.leftframe.synchronizeTree) {
        return(top.leftframe.synchronizeTree(idArray));
    } else {
        return(false);
    }
}


/**	Method used to synchronize navigation menu only. */
function synchronizeTreeOnly(idArray)
{
	//noinspection JSUnusedLocalSymbols
    try {
		if(top.leftframe.synchronizeTreeOnly) return(top.leftframe.synchronizeTreeOnly(idArray));
	} catch(e) { /* Nothing */ }

    return(false);
}