/*-------------------------------------------------------------------------------------------------------------------
        This javascript file contains functions used by productdisplaycommon.js.
        
        CVS Version     : $Id: temp04.js,v 1.15 2003/05/13 06:12:22 roym Exp $
        ---------------------------------------
        
        File history:
        $Log: temp04.js,v $
		
		Revision 1.17 2009/08/07 15:42  xmio
		- Updated matching functionality in findItemsByAttributes()-function to be more strict. SC#4782381
		
		Revision 1.16 2007/01/30 12:39  maqt
		- Added variable "urlInForms"
		- Changed url in the following functions to a non-relative path <- works both with friendly urls and old commerce links
		openPackageAndMeasurement  servlet: PackagePopUpView
		openEnlargeImage  servlet: ProductPopUpView
		openColorSample  servlet: SamplePopUpView
		openCheckAvailability  servlet:  StockAvailSearchForm

        Revision 1.15  2003/05/13 06:12:22  roym
        Cleaned up comments

        Revision 1.14  2003/04/29 12:07:57  bm13
        Roy's changes for lines

        Revision 1.13  2003/04/08 11:44:01  roym
        Fix for alignment of text buyinshop, removed combination not avail. text when attribute combination is not valid

-------------------------------------------------------------------------------------------------------------------*/
// CONSTANTS
var NUMBEROFBUTTONS = 8; //Maximum amount of variant image buttons
var INVALID_OPTION = "(N/A)";

// variable declarations
var allowSubmit = false;
var activeItemObject = null;
var activeImgBut;
var activeImgButNum;
var numOfDispImgBut;

// selection critera variable
var arrayW = new Array();
var selectedValidatedArray = new Array();
var selectedValidatedArrayIndexes = new Array();
var sliderTop = 0;

var is = new Object()
is.ie = (document.all) ? 1:0
is.ns4 = (document.layers) ? 1:0
is.w3c = (document.getElementById) ? 1:0
is.win = (navigator.userAgent.toLowerCase().indexOf("win") > 0) ? 1:0
is.mac = (navigator.userAgent.toLowerCase().indexOf("mac") > 0) ? 1:0


//-------------------------------------------------------------------------------------------------------------------
// function for initializing page
//-------------------------------------------------------------------------------------------------------------------
function initProductDisplay(chosenItem) {
	if(!chosenItem||chosenItem==null)
		chosenItem = item0;
	allowSubmit = true;
	activeImgButNum = 1; // initial active imgbut
	initImgButBar(chosenItem); // initiaize variantimage buttons
	//changeItem(chosenItem); // activate first item
	activeItemObject = chosenItem; 
	loadItemImgInBckgr(chosenItem); // load variant images for item in background
}

//-------------------------------------------------------------------------------------------------------------------
// function for initializing pop01b template
//-------------------------------------------------------------------------------------------------------------------
function init02b(newImgButNum){
	allowSubmit = true;
	
	if (!document.getElementById){
		return;
	}       
	
	if(document.getElementById('tdNav' + newImgButNum)) {
		// only perform this initialization if tdNav elements exist.
		tdOnClick('tdNav' + newImgButNum);
		activeImgBut = document.getElementById('tdNav' + newImgButNum);
	}
	changeImgSrc(imageArray[newImgButNum]);
}

//-------------------------------------------------------------------------------------------------------------------
// Calculates the image to display and calls changeImgSrc function to change image.
//-------------------------------------------------------------------------------------------------------------------
function changeVImage(imgNo) {
	// check if page is fully loaded befor allowing changes.
	if (!allowSubmit)
		return;
	
	// Calculate image number to display. 
		        
	if(activeItemObject != null) {
		changeImgSrc(activeItemObject.itemImg[imgNo]);  // swapImage
		activeImgButNum = imgNo+1; // set global activeImgButNum
	}
}


//------
// Initialise an array containing attributeValuesXXXXX (Select, Check and Input)
//------
function initialiseArrayW(formArg) {
	//Do this only once.
	var w = 0;

	for (var i = 0; i < formArg.elements.length;i++) {
		if (formArg.elements[i].name == "attributeValuesSelect") {
			arrayW[w++] = formArg.elements[i];
		}
		else if (formArg.elements[i].name == "attributeValuesCheck") {
			arrayW[w++] = formArg.elements[i];
		}
		else if(formArg.elements[i].name == "attributeValuesInput") {
			arrayW[w++] = formArg.elements[i];
		}
	}

	//run makeAttributesInvalid to make attributeval combinations invalid directly.
	//for (var i = 0; i < arrayW.length;i++) {
		//due to problems with the checkbox only make invalidate with Select.
	//	if (arrayW[i].name == "attributeValuesSelect")
	makeAttributesInvalid(0);
	loadItem(formArg);
	//}
}


function getSelectedValuesAsArray(pBeforeIndex) {
	var selectedValuesArray = new Array();
	var selectedValuesArrayCounter = 0;
	
	for (var k = 0; k < pBeforeIndex;k++) {
		tmpObj = getObj(arrayW[k].id+'alert');
		
		if (arrayW[k].name == "attributeValuesSelect") {
			selectedValuesArray[selectedValuesArrayCounter++] = arrayW[k].options[arrayW[k].options.selectedIndex].value;
		}	
		if (arrayW[k].name == "attributeValuesInput") {
			selectedValuesArray[selectedValuesArrayCounter++] = arrayW[k].value;
		}
		if (arrayW[k].name == "attributeValuesCheck") {
			if (arrayW[k].checked) {
				selectedValuesArray[selectedValuesArrayCounter++] = arrayW[k].value;
			}
			else {
				//it is not checked, we must add XXXXXX----<n/a> to the a array.
				var naValue = arrayW[k].value;
				selectedValuesArray[selectedValuesArrayCounter++]  = naValue.substring(0,naValue.indexOf("----") + 4) + "<n/a>";
			}		
		}		
			
	}		
	return selectedValuesArray;
}	

function getAttributeValueIndex(pId) {
	for (var k = 0; k < arrayW.length;k++) {
		if (arrayW[k].id==pId) return k;
	}	
}		

//------
// make attributes that are not valid greyed out and invalid, but they are chooseble anyway.
// depending on previous option boxes
//------
function makeAttributesInvalid(whichChanged) {

	//alert(whichChanged)
	

	// Loop over all elements in form
	// add selected to array
	var tmpObj;
	
	selectedValuesArray = getSelectedValuesAsArray(arrayW.length);
		
	// Loop over all, make invalid based on previous values
	var tmpArray;
	for (var k = 0; k < arrayW.length;k++) {
		tmpArray = new Array();
		for (var m=0;m<k;m++) {
			tmpArray[m] = selectedValuesArray[m];
		}
			
		if (arrayW[k].name == "attributeValuesSelect") {
			// loop over all the options
			// check which index is selected
			
			for (var l=0;l < arrayW[k].length; l++) {
				tmpArray[k] = arrayW[k][l].value;
				selectSelectedIndex = arrayW[k].options.selectedIndex;
				writeOut('Selected value ' + arrayW[k].options[arrayW[k].options.selectedIndex].value);
					
				// check if there is a item with attributes - this and previous	
				if (findItemsByAttributes(tmpArray).length>0) {
					writeOut('Item exists for ' +tmpArray);
					// item exists for options
					enableOption(arrayW[k][l]);		
				}
				else {
					writeOut('Item does not exist for ' + tmpArray);
					// no combination exists dim option
					//grey out
					disableOption(arrayW[k][l]);					
				}
			}
		}
		else	if (arrayW[k].name == "attributeValuesCheck") {
			if (arrayW[k].checked) {
				tmpArray[k] = arrayW[k].value;
			}
			else  {
				tmpArray[k]= arrayW[k].value.substring(0,arrayW[k].value.indexOf("----") + 4) + "<n/a>";
			}	
			if (findItemsByAttributes(tmpArray).length>0) {
				// item exists for options
			}
			else {
				// no combination exists dim option
				//grey out
				// check if both options exist otherwise disable
				arrayW[k].disabled = true;			
			}
		}	
	
	}
	makeAttributesValid(whichChanged);
}

function makeAttributesValid(whichChanged) {
		var found = false;
		var selectedValuesArray = new Array();
		//var vAlertText = getObj('alert');
		//vAlertText.style.display = 'none';
		var vAlert = false;
		var vTmpObj;
		// Loop over all options
		// add the selected to selectedArray if valid, if not find a valid and add mark as selected and add to selectedArray
		for (var i=0;i<arrayW.length;i++) {
			if (arrayW[i].name == "attributeValuesInput") {
				selectedValuesArray[i] = arrayW[i].value;
				selectedValidatedArray[i] = arrayW[i].value;
				selectedValidatedArrayIndexes[i] = 0;
			}	
			else if (arrayW[i].name == "attributeValuesSelect") {
				// First check selected option, add if valid
				//vTmpObj = getObj('no'+arrayW[i].id);
				//if (vTmpObj!=null) vTmpObj.style.display = 'none';
					
				if (arrayW[i].options[arrayW[i].options.selectedIndex].disabled==false) {
					selectedValuesArray[i] = arrayW[i].options[arrayW[i].options.selectedIndex].value;					
					selectedValidatedArray[i] = arrayW[i].options[arrayW[i].options.selectedIndex].value;					
					selectedValidatedArrayIndexes[i] = arrayW[i].options.selectedIndex;
				}
				else {
					// Check if previously selected option is valid..
					selectedValuesArray[i] = selectedValidatedArray[i];
					if (findItemsByAttributes(selectedValuesArray).length>0) {
								enableOption(arrayW[i][selectedValidatedArrayIndexes[i]]);
								arrayW[i].options.selectedIndex = selectedValidatedArrayIndexes[i];					
					}			
					else {
						// Find first selected that is valid based on previously selected options, mark as selected and add to selected array
						// update valid status on all
						//vTmpObj.style.display = 'block';
						vAlert = true;										
						found = false;
						var selectedValue;
						for (var j=0;j<arrayW[i].length;j++) {
							// check if this option is valid based on previously selected
							selectedValuesArray[i] = arrayW[i][j].value;
							if (findItemsByAttributes(selectedValuesArray).length>0) {
								enableOption(arrayW[i][j]);
								if (!found) {
									selectedValue = arrayW[i][j].value;
									arrayW[i].options.selectedIndex = j;
									found = true;
								}		
							}
							else {
								disableOption(arrayW[i][j]);
							}
						}
						selectedValuesArray[i] = selectedValue;	
						selectedValidatedArray[i] = selectedValue;	
					}
				}						
			}
			else if (arrayW[i].name == "attributeValuesCheck") {
				var selectedValue;
				if (arrayW[i].checked) {
					selectedValuesArray[i] = arrayW[i].value;
					selectedValue = arrayW[i].value;
				}
				else  {
					selectedValuesArray[i]= arrayW[i].value.substring(0,arrayW[i].value.indexOf("----") + 4) + "<n/a>";
					selectedValue = arrayW[i].value.substring(0,arrayW[i].value.indexOf("----") + 4) + "<n/a>";
				}	
				if (findItemsByAttributes(selectedValuesArray).length>0) {
					// item exists for options										
				}
				else {
					selectedValidatedArray[i] = selectedValue;
					// change check status
					if (arrayW[i].checked) arrayW[i].checked = false;
					else arrayW[i].checked = true;					
				}
				// check if both options are valid. Eg. should checkbox be checkable
				var count = 0;
				selectedValuesArray[i] = arrayW[i].value;
				if (findItemsByAttributes(selectedValuesArray).length>0) {
					count++;
				}	
				selectedValuesArray[i] = arrayW[i].value.substring(0,arrayW[i].value.indexOf("----") + 4) + "<n/a>";
				if (findItemsByAttributes(selectedValuesArray).length>0) {
					count++;
				}
				if (count!=2) {
					arrayW[i].disabled = true;
					getObj(arrayW[i].id+'area').style.display = 'none';			
				}	
				else {
					arrayW[i].disabled = false;		
					getObj(arrayW[i].id+'area').style.display = 'block';						
				}
				
			}
		}	
		if (vAlert) {
			//getObj('alerttext').innerHTML = getObj(arrayW[whichChanged].id+'label').innerHTML + ' ' + arrayW[whichChanged].options[arrayW[whichChanged].options.selectedIndex].text;
			//vAlertText.style.display = 'block';
		}
			
			
}		

function enableOption(theOption) {
	if (theOption.disabled == true) {
		theOption.text = theOption.text.substring(0,theOption.text.length - (notAvailable.length+1));
		theOption.style.color = "#000000";
		theOption.disabled = false;	
	}	
}

function disableOption(theOption) {
	if (theOption.disabled == false) {
		theOption.text += ' ' + notAvailable;
		theOption.style.color = "#828282";
		theOption.disabled = true;	
	}	
}

function writeOut(pStr) {
	//getObj("prompt").innerHTML += pStr + '<br>';	
}

//-------------------------------------------------------------------------------------------------------------------
// Check if a attributeValue combination are valid, e.g. does it exist a catentry for this item.
//-------------------------------------------------------------------------------------------------------------------
function checkValidCombination(formArg,whichChanged) {

	if (!allowSubmit) { return; } // check that page has been fully loaded.

	// FIX. validate choice -- disabled dropdown can be clicked in IE
	if ((typeof whichChanged != "undefined") && whichChanged != null && arrayW[whichChanged].name == "attributeValuesSelect") {
		if (arrayW[whichChanged].options[arrayW[whichChanged].options.selectedIndex].disabled == true) {
			// return value to previously selected if exists
			
			if (selectedValidatedArray.length>0) {
				for (var i=0;i<arrayW[whichChanged].options.length;i++) {
					if (arrayW[whichChanged][i].value == selectedValidatedArray[whichChanged])
					  arrayW[whichChanged].options.selectedIndex = i;
				}
			}	
			return;
		}	
	}
	//Call if not null. Only null when called the first time. This does initialiseArrayW take care off.
	if ((typeof whichChanged != "undefined") && whichChanged != null) { // && arrayW[whichChanged].name == "attributeValuesSelect") {
		makeAttributesInvalid(whichChanged);
	}
	
	loadItem(formArg);
	
}

function loadItem(formArg) {
	var a = new Array();
	var ai = 0;

	for (var i = 0; i < formArg.elements.length;i++) {

		if (formArg.elements[i].name == "attributeValuesSelect") {
			a[ai++] = formArg.elements[i].options[formArg.elements[i].options.selectedIndex].value;
		}
		else if (formArg.elements[i].name == "attributeValuesCheck") {
			// If there are only two values and one of them is <n/a> then a checkbox should be used instead of dropdown box.
			if (formArg.elements[i].checked) {
				//checked, add it to array a.
				a[ai++] = formArg.elements[i].value;
			}
			else {
				//it is not checked, we must add XXXXXX----<n/a> to the a array.
				var naValue = formArg.elements[i].value;
				a[ai++] = naValue.substring(0,naValue.indexOf("----") + 4) + "<n/a>";
			}
		}
		else if(formArg.elements[i].name == "attributeValuesInput") {
			a[ai++] = formArg.elements[i].value;
		}
	}

	a.sort(); //sort array to get the same order as itemAttrValue objects that is sorted.
				
	var itemObjFound = findCatentryIdForItem(a);
	var addButton = getObj('dispAddButton');
	var dispQty = getObj('dispQuantity');
		
	if (itemObjFound == null) {

		//if whichChanged then this might be running on old productdisplay (before selection criteria 16.4)
		if ((typeof whichChanged != "undefined") && whichChanged != null) {
			getObj('productImgDisable').style.visibility= 'visible';
			//getObj('checkAvailabilityLink').style.visibility= 'hidden';
		}
		
		if (addButton!=null) addButton.style.display = 'none';
		if (dispQty!=null) dispQty.style.display = 'none';		
	}
	else {

		//if whichChanged then this might be running on old productdisplay (before selection criteria 16.4)
		if ((typeof whichChanged != "undefined") && whichChanged != null) {
			getObj('productImgDisable').style.visibility= 'hidden';
			//getObj('checkAvailabilityLink').style.visibility= 'visible';
		}

		// make sure addbutton is visible
		if (addButton!=null) addButton.style.display = 'block';
		if (dispQty!=null) dispQty.style.display = 'block';
				
		initImgButBar(itemObjFound); // re-initialize Image button bar
		changeItem(itemObjFound); // change displayed item
		switchThumbsArea(itemObjFound);
		loadItemImgInBckgr(itemObjFound); // start loading variant images for displayed item in background
	}
}	

function getItem(catentryId) {
	for (var i=0;i<itemArray.length;i++) {
		if (itemArray[i].catEntryId==catentryId) {
			return itemArray[i];
		}
	}		
}

function getItemNbr(catentryId) {
	for (var i=0;i<itemArray.length;i++) {
		if (itemArray[i].catEntryId==catentryId) {
			return i;
		}
	}		
}

//-------------------------------------------------------------------------------------------------------------------
// Initializes buttons for changing images.
//-------------------------------------------------------------------------------------------------------------------
function initImgButBar(chosenItem) {        
	numOfDispImgBut = chosenItem.itemImg.length;

	if ($('buttonBar') != null) {
		//new thumbnail layout on PIP page

	  $('buttonBar').removeClassName('buttonBarVisible');
		var success = true;
		var i = 0;
		while (success) {
			try {
				$('imageThumb_' + i).remove();
				i++;
			} catch (err) {
				success = false;
			}
		}
	 	
		if (numOfDispImgBut > 1) {
			
			$('buttonBar').addClassName('buttonBarVisible');
					
			var imageTemplate = new Template("<div class=\"imageThumb\" id=\"imageThumb_#{id}\"><a href=\"javascript:void(0);\" id=\"imageThumbLink_#{id}\"><img src=\"#{src}\"></a></div>");
		
			for (var j = 0; j < NUMBEROFBUTTONS && j < numOfDispImgBut; j++) {
				
				var obj = new Object();
				obj.id = j;
				obj.src = chosenItem.itemImg[j];
			
				$('buttonBar').insert(imageTemplate.evaluate(obj));
						
				if (j == 0) {
					activeImgBut = $('imageThumbLink_0');
					activeImgBut.addClassName('active');
				}
						
				Event.observe($('imageThumbLink_' + j), 'click', function(e) {
									
					activeImgBut.removeClassName('active');
	        activeImgBut = this; 
					activeImgBut.addClassName('active');
	
					if(activeItemObject != null) {
						var imgNo = parseInt(this.id.substring(this.id.lastIndexOf('_') + 1));
						$('productImg').src = activeItemObject.itemImg[imgNo];  
						activeImgButNum = imgNo + 1;
					}
					        							
				});
			
			}
		}
		
	} else {
		//old layout on stocksearch page
		
		var counter = 1;        
		var thumb = 0;
		var imgObj;
		for (var j = 0; j < numOfDispImgBut ; j++) {
			imgObj = getObj('img'+ j +'thumb');
			imgObj.src = chosenItem.itemImg[j];
		}	
		
		for (var j = 0; j < NUMBEROFBUTTONS; j++) {
			
			if (document.getElementById || document.all) {
				// hide all buttons to the right that are not used
				if (numOfDispImgBut == 1 || j >= numOfDispImgBut) {
					getObj('tdNav' + j).style.visibility = 'hidden';
				}
				else {
					// style image buttons
					getObj('tdNav' + j).style.visibility = 'visible';
					getObj('tdNav' + j).className = 'thumbnail_normal';
					
					// activate the first visible button
					if (numOfDispImgBut != 1 && j == 0) {
						activeImgBut = getObj('tdNav' + j);
						activeImgBut.className = 'thumbnail_active';
					}
					
					
					getObj('tdNav' + j).style.visibility = 'visible';
				}
			}
			else {  
				alert (js_fn_NOT_VALID_BROWSER);
				return;
			}
		}
		
		
	}
	
}

function switchThumbsArea(chosenItem) {

	if ($('buttonBar') == null) {
		
		if (chosenItem.itemImg.length > 1) {
			
			//activeImgBut.className = 'thumbnail_active';
	        
	    
			if (document.getElementById || document.all) {
				getObj('nuberBoxDescription').className = 'showarea';	
				
				if (chosenItem.itemImg.length > 4) {
					getObj('nuberBoxDescription2').className = 'showarea';	
				}	
				else {
					getObj('nuberBoxDescription2').className = 'hidearea';	
				}	
				
				getObj('nuberBoxDescription').className = 'showarea';				
				
			}
			else {  
				alert (js_fn_NOT_VALID_BROWSER);
				return;
			}		
		}
		else {
			// hide image thumbnail area
			getObj('nuberBoxDescription').className = 'hidearea';	
		}	
		
	}
	
}

//-------------------------------------------------------------------------------------------------------------------
// Function to change the displayed item. Function not called directly in page but by checkValidCombination function.
//-------------------------------------------------------------------------------------------------------------------
function changeItem(itemObjToDisplay) {
					
	var stockSearchPageSet = !(window.stockSearchPage === undefined);
	if (document.getElementById || document.all){

		if (itemObjToDisplay == null) {
			// if null use active item object.
			itemObjToDisplay = activeItemObject;
		}
		
		for (var d = 0; d < displayedProperties.length; d++) {
			try {
				var value = eval("itemObjToDisplay." + displayedProperties[d]);
				//Commented for: SC4763060,SC4759895,SC4760348
				//if (value != "") { 
					$(displayedProperties[d]).update(value);
				//}
			} catch (err) {}
		}

		try {
			if (itemObjToDisplay.isBTI) {
				//make sure that the BTI wrapper has the BTI styles.
				$('productInfoWrapper1').up(0).className = 'productMain productMainBti';
				$('productInfoWrapper1').className = 'productBtiBack';
				$('productInfoWrapper2').className = 'productBtiFront';
			} else {
				//make sure that the BTI wrapper has no styles.
				$('productInfoWrapper1').up(0).className = 'productMain';
				$('productInfoWrapper1').className = '';
				$('productInfoWrapper2').className = '';
			}
		} catch (err) {
			//the new bti layout does not exist.
		}			
		
		// always go to first image when changing item object
		getObj('productImg').src = "http://www.ikea.com" + itemObjToDisplay.itemImg[0];
				
		if (itemObjToDisplay.isNew) {
			getObj('newicon').style.display = 'block';		
		}
		else {
			getObj('newicon').style.display = 'none';		
		}
		
		var catentryInForm = getObj('catentryInForm');
		if (catentryInForm!=null) catentryInForm.value = itemObjToDisplay.catEntryId;

		var partNumberInForm = getObj("thePartnumberInForm");
		if (partNumberInForm!=null) partNumberInForm.value = itemObjToDisplay.partNumber;
		
		var urlInForm = getObj('urlInForm');
		if (urlInForm!=null) urlInForm.value = itemObjToDisplay.url;

		var addButton = getObj('dispAddButton');
		var dispQty = getObj('dispQuantity');
		var dispNotShopableOnlineText = getObj('dispNotShopableOnlineText');
		if (itemObjToDisplay.addToShopCart) {
			if (addButton!=null) addButton.style.display = 'block';
			if (dispQty!=null) dispQty.style.display = 'block';
			if (dispNotShopableOnlineText!=null) dispNotShopableOnlineText.style.display = 'none';
						
		}
		else {
			if (addButton!=null) addButton.style.display = 'none';
			if (dispQty!=null) dispQty.style.display = 'none';			
			if (dispNotShopableOnlineText!=null) dispNotShopableOnlineText.style.display = 'block';
		}
		if (!stockSearchPageSet) {
			if(itemObjToDisplay.customerBenefitsText != '') {
				getObj('cbftssection').style.display = 'block';			
			}               
			else {
				getObj('cbftssection').style.display = 'none';			
			}
			
			if(itemObjToDisplay.designer != '') {
				getObj('dessection').style.display = 'block';			
			}               
			else {
				getObj('dessection').style.display = 'none';			
			}               
			if(itemObjToDisplay.careInstructions != '') {
				getObj('careInstructionsPart').style.display = 'block';			
			}
			else { getObj('careInstructionsPart').style.display = 'none'; }
			
			if(itemObjToDisplay.goodToKnow != '') {
				getObj('goodToKnowPart').style.display = 'block';
			}		
			else { getObj('goodToKnowPart').style.display = 'none'; }
	     
			if(itemObjToDisplay.environment != '') { getObj('environmentPart').style.display = 'block'; }
			else { getObj('environmentPart').style.display = 'none'; }
			
			if(itemObjToDisplay.productFacts != '' || itemObjToDisplay.productMeasure != '')
				getObj('pkgmeasPart').style.display = 'block';
			else
				getObj('pkgmeasPart').style.display = 'none';
	
			if (itemObjToDisplay.requiresAssembly)
				getObj('requiresAssembly').style.visibility = 'visible';
			else
				getObj('requiresAssembly').style.visibility = 'hidden';
	
			if(itemObjToDisplay.hasPkgMeas)
				getObj('package').style.visibility = 'visible';
			else
				getObj('package').style.visibility = 'hidden';          
		}
		if (itemObjToDisplay.dualCurrencies) {
			getObj('price2').style.visibility = 'visible';
		}
		else {
			getObj('price2').style.visibility = 'hidden';			
		}
		
		//Fixing dual currency on old price.
		if (itemObjToDisplay.price3 == '') {
			getObj('price3').style.visibility = 'hidden';
			getObj('price4').style.visibility = 'hidden';
		}

		//  Family prices
		if (itemObjToDisplay.price5 == '') {
			getObj('famsection').style.display = 'none';  // "block":"none"
			getObj('price5').style.visibility = 'hidden';
			getObj('price6').style.visibility = 'hidden';
			getObj('price7').style.visibility = 'hidden';
			getObj('price8').style.visibility = 'hidden';
		}
		else {
			getObj('famsection').style.display = 'block';  // "block":"none"
			getObj('price5').style.visibility = 'visible';
			if (itemObjToDisplay.dualCurrencies) {
				getObj('price6').style.visibility = 'visible';
			}
			else {
				getObj('price6').style.visibility = 'hidden';
			}

			if (itemObjToDisplay.price7 != '') {
				getObj('price7').style.visibility = 'visible';
				if (itemObjToDisplay.dualCurrencies) {
					getObj('price8').style.visibility = 'visible';
				}
				else {
					getObj('price8').style.visibility = 'hidden';
				}
			}
		}
    // check if this item has a prf charge
		if(itemObjToDisplay.hasPrfCharge == 'true'){
				getObj('prfCharge').style.display = 'block';
		}else if(getObj('prfCharge') != null ){
				getObj('prfCharge').style.display = 'none';
		}

		// change active item object
		setStoreCheckProductId(itemObjToDisplay);
		
		activeItemObject = itemObjToDisplay;            
	}
	else {
		alert (js_fn_NOT_VALID_BROWSER);
		return;
	}
	
}

//-------------------------------------------------------------------------------------------------------------------
// Function for finding the item object based on selected selection criterias.
//-------------------------------------------------------------------------------------------------------------------
function findCatentryIdForItem(attributeValues) {
				var joinedAttr = attributeValues.join("##").toLowerCase();
        for (var i = 0; i < itemAttrValueArray.length; i++) {
                if ( joinedAttr == itemAttrValueArray[i].join("##").toLowerCase()) {
                        return itemArray[i];
                }
        }
        return null;
}

//-------------------------------------------------------------------------------------------------------------------
// Micro API for objects.
//-------------------------------------------------------------------------------------------------------------------
function getObj(name)
{
        if (document.getElementById) {
                if (document.getElementById(name)) {
                        return document.getElementById(name);
                }
                else {
                        return document.getElementById('dummy');
                }       
        }
        else if (document.all) {
                if (document.all[name]) {
                        return document.all[name];
                } 
                else {
                        return document.all['dummy'];
                }
        }
        else {
                alert (js_fn_NOT_VALID_BROWSER);
                return;
        }
}

//-------------------------------------------------------------------------------------------------------------------
// Function for starting download of images in the background
//-------------------------------------------------------------------------------------------------------------------
function loadItemImgInBckgr(argItem) {  
	tmpImgObj = new Image();
	tmpArray = argItem.itemImgThumb;
	for (var i=0; i < tmpArray.length; i++) {
     	if(tmpArray[i] != '') {
				tmpImgObj.src = tmpArray[i];
		}
	}
	tmpArray = argItem.itemImg;
	for (var i=0; i < tmpArray.length; i++) {
     	if(tmpArray[i] != '') {
				tmpImgObj.src = tmpArray[i];
		}
	}    
	tmpArray = argItem.itemImgEnlarged;   
	for (var i=0; i < tmpArray.length; i++) {
     	if(tmpArray[i] != '') {
				tmpImgObj.src = tmpArray[i];
		}
	}    
}

//-------------------------------------------------------------------------------------------------------------------
// Opens Enlarged images popup
//-------------------------------------------------------------------------------------------------------------------
function openEnlargeImage(storeAndLang) {
        if (activeItemObject != null)
                openPopUp('/webapp/wcs/stores/servlet/ProductPopUpView?productId=' + activeItemObject.catEntryId + "&" + storeAndLang + "&variantNum=" + activeImgButNum, '500', '520', 'pop01b', 0);
}

//-------------------------------------------------------------------------------------------------------------------
// Opens Color sample popup
//-------------------------------------------------------------------------------------------------------------------
function openColorSample(args) {
        if (activeItemObject != null)
                openPopUp('/webapp/wcs/stores/servlet/SamplePopUpView?' + args, '296', '270', 'Pop09', 1);
                
}

//-------------------------------------------------------------------------------------------------------------------
// Opens Package and measurement popup
//-------------------------------------------------------------------------------------------------------------------
function openPackageAndMeasurement(args) {
        if (activeItemObject != null)
                openPopUp('/webapp/wcs/stores/servlet/PackagePopUpView?productId=' + activeItemObject.catEntryId + "&" + args, '296', '270', 'Pop10', 1);
}

//-------------------------------------------------------------------------------------------------------------------
// Opens check availability page
//-------------------------------------------------------------------------------------------------------------------
function openCheckAvailability(storeAndLang) {
        // alert("Not available in build cycle 1.");
        location.href="/webapp/wcs/stores/servlet/StockAvailSearchForm?productId=" + activeItemObject.catEntryId + "&" + storeAndLang + "";
}

//-------------------------------------------------------------------------------------------------------------------
// Changes the src for the product image
//-------------------------------------------------------------------------------------------------------------------
function changeImgSrc(argImage){
        //for ie5 >  and netscape 6
        if (document.getElementById){
                tmpImg = document.getElementById('productImg'); 
        }else if (document.all){ //Explorer 4
                tmpImg = document.all['productImg']; 
        }
        else{ 
                alert (js_fn_NOT_VALID_BROWSER);
                return;
        }       
        tmpImg.src = argImage;
} 
//-------------------------------------------------------------------------------------------------------------------
// Function that validates the quantity field
// 
// argFieldId, string   = the id to the field that will be validated
// optName, string              = Optional, description of field, e.g. Quantity (optional). If not provided no alert box is used.
//-------------------------------------------------------------------------------------------------------------------
function validateQuantity(argFieldId, optName){
  
	var sNumber = ""; //variable to store the value of the field
	//Netscape 6 and ie 5>
	if (document.getElementById){
		tmp = document.getElementById(argFieldId); 
		sNumber = tmp.value;
	}else if (document.all){ //Explorer 4
		tmp = document.all[argFieldId];
		sNumber = tmp.value;
	}else{ 
		alert (js_fn_NOT_VALID_BROWSER);
		return false;
	}
 
	//first check if the field is empty
	if( isEmpty(sNumber, false) ){
		if(optName){
			alert(optName + js_fn_NO_DIGIT);
		}
		return false;
	}
 
	//call function in the utility lib, 0 is not a valid number
	if( checkNum(sNumber, 0, 1, 0, 0, 99, optName) == false ){
   	tmp.select();
		tmp.focus();
		return false;
	}
 
	return true;
}


function findItemsByAttributes(attributeList) {
	var itemsFound = new Array();
	var itemsFoundIndex = 0;
	for (var i = 0; i < itemAttrValueArray.length;i++) {
		
		var itemAttrValue = itemAttrValueArray[i];
		var itemAttrValueJoined = itemAttrValue.join('##');
		
		var attrListJoined = attributeList.join('##');
		
		// check if workingAttrValue contains all attribute
		// Force complete match if same number of attributes checked SC#4782381
		if (attributeList.length == itemAttrValue.length) {
			if (itemAttrValueJoined == attrListJoined) {
				itemsFound[itemsFoundIndex++] = i;
			}
		} else {
			if (itemAttrValueJoined.search(attrListJoined) >= 0) {
				itemsFound[itemsFoundIndex++] = i;
			}
		}
		
	}
	return itemsFound;
}

/**************************************************************************
* NAVIGATION BAR FUNCTIONS, DYNAMIC ROLLOVER HANDLING
**************************************************************************/ 
function tdMouseOver(argID){
        if (!document.getElementById) {
                return;
        }       
        
   			tmp =  document.getElementById(argID);
   
   			if(tmp.className.indexOf('active') != -1) {
                return;
        }
        
        tmp.className = 'thumbnail_over';
}

function tdMouseOut(argID){
        if (!document.getElementById) {
                return;
        }       

        tmp =  document.getElementById(argID);
				if(tmp.className.indexOf('active') != -1) {
                return;
        }
   			tmp.className = 'thumbnail_normal';
}

function tdOnClick(argID){
        if (!document.getElementById) {
                return;
        }
        
                
        tmp =  document.getElementById(argID);
  
        if(tmp.className.indexOf('active') != -1) {
                return;
        }
  
  			activeImgBut.className = 'thumbnail_normal';
  			
        tmp.className = 'thumbnail_active';
        
        activeImgBut = tmp;     
}
/**************************************************************************
* END OF NAVIGATION BAR FUNCTIONS, DYNAMIC ROLLOVER HANDLING 
***************************************************************************/

function popLargeImageWindow(argLocale,argColorStr,argPriceStr,argSizeStr,argFamilyStr,argCloseStr)
{
	var x = (screen.availWidth - 520 ) / 2;
  var y = (screen.availHeight - 600 ) / 2;
  
  var width = 520;
  if(!is.mac){
    width = parseInt(width) + 26;
  }
	if(is.mac){
    width = parseInt(width) + 10;
  }
  
  var sFeatures = "width=" + width + "," + 
                  "height= 610 ," + 
									"toolbar=no," + 
                  "status=yes," + 
									"scrollbars= 1 ," + 
									"resizable=no," +                   
                  "left=" + x + ", top="+ y;
                  
  var generator=window.open('','enlarged',sFeatures);
  
	var htmlTemplate = new Template(
		
		'<!DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01 Transitional//EN">\n' + 
			'<html>\n' + 
				'<head>\n' +
			  	'<title>IKEA | #{title}</title>\n' +
					'<link rel="stylesheet" href="#{css}" type="text/css">\n' +
					'<script type="text/javascript" language="JavaScript">\n' +
						'#{javascript}\n' +
					'</script>\n' +
					'<script type="text/javascript" language="JavaScript" src="/ms/js/prototype.js"></script>\n' +
					'<script type="text/javascript" language="JavaScript" src="#{js}"></script>\n' +
				'</head>\n' +
			'<body>\n' +
				'<div class="top">\n' +
					'<div class="left">\n' +
						'<span class="productName">#{productName}</span>\n' +
						'<span class="productType">#{productType}</span>\n' +
					'</div>\n' +
					'<div class="right">\n' +
						'<span class="close"><a href="#" onclick="return false;" id="close">#{closeText}</a></span>\n' +
					'</div>\n' +
				'</div>\n' +		
				'<div class="main">\n' +
					'<img src="#{image}" id="fullImage" class="fullImage" border="0" />' +
					'#{newsarea}' +
					'#{thumbsarea}' +
				'</div>' +
				'<div class="bottom">\n' +
					'<div class="left">\n' +
						'<span class="productType">#{color}</span>\n' +
					'</div>\n' +
					'<div class="right">\n' +
						'<span class="instruction">#{instruction}</span>\n' +
						'<span class="smallPrice">#{smallPrice}</span>\n' +
						'#{ikeaFamilyPrice}' +							
					'</div>\n' +
				'</div>\n' + 
			'</body>\n' +						   
		'</html>\n'
		
	);
	
	var ikeaFamilyPriceTemplate = new Template('<span class="ikeaFamilyText">#{familyText}</span>\n<span class="ikeaFamilyPrice">#{familyPrice}</span>');
	
	var thumbsAreaTemplate = new Template(
		'<div id="thumbsArea" class="thumbsArea">\n' +
			'#{thumbs}' +
		'</div>'
	);
	
	var newsAreaTemplate = new Template(
		'<div id="newsArea" class="newsArea">\n' +
			'<img src="#{image}" />\n' +
		'</div>'
	);


	var thumbTemplate = new Template('<img id="#{thumbId}" src="#{thumbSrc}" />');
	var activeThumbTemplate = new Template('<img id="#{thumbId}" src="#{thumbSrc}" class="active" />');
	
	var javascriptTemplate = new Template(
		"var currentId = #{currentId};\n" +
		"var itemImgEnlarged = new Array(#{imgArray});\n"
	);
	
	var prod = new Object();
	
	prod.css = '/ms/css/ppc_popup_FW10_em.css';
	prod.js = '/ms/js/ppc_popup_FW10.js';
	prod.title = 'IKEA | ' + activeItemObject.productName + ' ' + activeItemObject.productType;		
	prod.image = activeItemObject.itemImgEnlarged[activeImgButNum-1];
	prod.productName = activeItemObject.productName;
	prod.productType = activeItemObject.productType;
	prod.closeText = argCloseStr;
	prod.instruction = argPriceStr;
	prod.smallPrice = activeItemObject.price1;
	prod.color = '';
	prod.familyText = argFamilyStr;
	prod.familyPrice = activeItemObject.price5;

	newsObject = new Object();
	newsObject.image = '/ms/' + argLocale + '/img/icons/new_large.gif';
	
	if (activeItemObject.isNew) {
		prod.newsarea = newsAreaTemplate.evaluate(newsObject);
	}
	
	jsObject = new Object();
	jsObject.currentId = activeImgButNum-1;
	jsObject.imgArray = '';

	//if color exists, display it
	if (activeItemObject.color != '') {
		prod.color = argColorStr + ' ' + activeItemObject.color;
	}
	
	//if family price exists, display it
	if (activeItemObject.price5 != '') {
		prod.ikeaFamilyPrice = ikeaFamilyPriceTemplate.evaluate(prod);
	}
	
	//if more than one image, display thumbs
	if (activeItemObject.itemImg.length > 1) {
		//create thumbs
		var thumbs = new Object();
		thumbs.thumbs = '';
		
		for (var i = 0; i < activeItemObject.itemImg.length; i++) {
			
			var thumb = new Object();
			thumb.thumbId = 'thumb_' + i;
			thumb.thumbSrc = activeItemObject.itemImg[i];
			
			jsObject.imgArray = jsObject.imgArray + '\'' + activeItemObject.itemImgEnlarged[i] + '\'';
			
			if (i < activeItemObject.itemImg.length - 1) {
				jsObject.imgArray = jsObject.imgArray + ',';
			}
			
			if (i == activeImgButNum - 1) {
				thumbs.thumbs = thumbs.thumbs + activeThumbTemplate.evaluate(thumb);
			} else {
				thumbs.thumbs = thumbs.thumbs + thumbTemplate.evaluate(thumb);
			}
			
		}
		
		//create thumbs area
		prod.thumbsarea = thumbsAreaTemplate.evaluate(thumbs);
	}

	prod.javascript = javascriptTemplate.evaluate(jsObject);
	
	generator.document.write(htmlTemplate.evaluate(prod));
	generator.document.close();  

  if (window.focus) {generator.focus();}
  
}

function popLargeImageWindow2(argLocale,argColorStr,argPriceStr,argSizeStr,argFamilyStr,argCloseStr,argOfferStr)
{
	var x = (screen.availWidth - 520 ) / 2;
	var y = (screen.availHeight - 600 ) / 2;
	var width = 520;
  if(!is.mac){
    width = parseInt(width) + 26;
  }
    if(is.mac){
    width = parseInt(width) + 10;
  }

  var sFeatures = "width=" + width + "," +
                  "height= 610 ," +
                                    "toolbar=no," +
                  "status=no," +
                                    "scrollbars= 1 ," +
                                    "resizable=no," +
                  "left=" + x + ", top="+ y;

  var generator=window.open('','enlarged',sFeatures);

    generator.document.write('<!DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01 Transitional//EN">');
  generator.document.write('<html><head><title>IKEA | ' + activeItemObject.productName + ' ' + activeItemObject.productType + '</title><link rel="stylesheet" href="/ms/css/ppc.css" type="text/css"><link rel="stylesheet" href="/ms/css/ikea_family.css" type="text/css">');

  var imgNbr = activeImgButNum-1;

  generator.document.write('<script> var currentId = \'nbr'+ imgNbr +'\';');
  generator.document.write('var itemImgEnlarged = new Array(');
  for (var i=0;i<activeItemObject.itemImgEnlarged.length;i++) {
      if (i==0) generator.document.write('\''+ activeItemObject.itemImgEnlarged[i] +'\'');
      else generator.document.write(',\''+ activeItemObject.itemImgEnlarged[i] +'\'');
  }
  generator.document.write(');');
  generator.document.write('function mouseOver(imageId) { if (currentId!=imageId)  document.getElementById(imageId).style.borderColor =  \'#FFCC00\'; }' );
  generator.document.write('function mouseOut(imageId) { if (currentId!=imageId)  document.getElementById(imageId).style.borderColor =  \'#CCCCCC\'; }' );
  generator.document.write('function changeImg(imageId,imageNbr) { document.getElementById(currentId).style.borderColor =  \'#CCCCCC\'; currentId = imageId; document.getElementById(\'fullimage\').src = itemImgEnlarged[imageNbr];document.getElementById(imageId).style.borderColor =  \'#FF9900\'; }');

  generator.document.write('</script>');



  generator.document.write('<style>#thumbsarea{position:absolute;top: 483px;left: 7px;z-index: 1;}');
  generator.document.write('#newsarea{position:absolute;top: 61px;left: 7px;z-index: 1;}');
  generator.document.write('.price_regular {font-family: Arial, Verdana, Sans-serif;font-weight: bold;font-size:16px;color: #333333;}');
  generator.document.write('.product_category {font-family: Arial, Verdana, Sans-serif;font-size:14px;color: #666666;}');
  generator.document.write('.defaultCopyGrey {font-familiy:Arial, Verdana, Sans-Serif;font-size:11px;line-height:13px;color:#999999;}');
  generator.document.write('.defaultCopy {font-familiy:Arial, Verdana, Sans-Serif;font-size:11px;line-height:13px;color:#666666;text-decoration: none;}');
  generator.document.write('A:link.defaultCopy {font-familiy:Arial, Verdana, Sans-Serif;font-size:11px;line-height:13px;color:#4D7EE5;text-decoration: none;}');
  generator.document.write('A:active.defaultCopy {font-familiy:Arial, Verdana, Sans-Serif;font-size:11px;line-height:13px;color:#4D7EE5;text-decoration: none;}');
  generator.document.write('A:visited.defaultCopy {font-familiy:Arial, Verdana, Sans-Serif;font-size:11px;line-height:13px;color:#4D7EE5;text-decoration: none;}');
  generator.document.write('a:hover.defaultCopy {font-familiy:Arial, Verdana, Sans-Serif;font-size:11px;line-height:13px;color:#4D7EE5;text-decoration: underline;}');
  generator.document.write('.ikeaFamilyPrice{font-family: Arial, Verdana, Sans-serif;font-size:11px;font-weight:bold;color: #E06023;}');
  generator.document.write('.instructional {color:#999999;font-size:11px;line-height:13px;font-familiy:Arial, Verdana, Sans-Serif;font-style:italic;}');
  generator.document.write('.smallPrice    {font-family: Arial, Verdana, Sans-serif;font-size:12px;font-weight:bold;color: #333333;}');
  generator.document.write('.greyBorderBottom {border-bottom:1px solid #CCCCCC;}');
  generator.document.write('//--></style></head>');


    generator.document.write('<body topmargin=0 leftmargin=0 rightmargin=0>');
    generator.document.write('<table width="530" cellspacing="0" cellpadding="0" border="0">');
    generator.document.write('<tr><td width="7">&nbsp;</td><td height="40" valign="top" class="greyBorderBottom" style="padding-top:14;padding-left:7;"><span class="price_regular">'+activeItemObject.productName+'</span>&nbsp;<span class="product_category">'+activeItemObject.productType+'</span></td>');
    generator.document.write('<td align="right" class="greyBorderBottom" style="padding-top:14;padding-right:7;"><a href="javascript:self.close()" class="defaultCopy">'+argCloseStr+'</a></td><td width="7">&nbsp;</td></tr></table>');
    generator.document.write('<table width="530" cellspacing="0" cellpadding="0" border="0"><tr><td width="7">&nbsp;</td><td class="greyBorderBottom" align="center" valign="top">');
    generator.document.write('<img id="fullimage" width="500" height="500" src="'+activeItemObject.itemImgEnlarged[activeImgButNum-1]+'" border="0"/>');
    if (activeItemObject.isNew) {
        generator.document.write('<div id="newsarea">');
        generator.document.write('<table border="0" cellspacing="0" cellpadding="0"><tr>');
        generator.document.write('<td><img src="/ms/'+ argLocale +'/img/icons/new_large.gif" border="0"></td></tr></table></div>');
    }
    generator.document.write('<div id="thumbsarea">');
    generator.document.write('<table cellspacing="7" cellpadding="0" border="0"><tr>');
    var borderColor;

    if (activeItemObject.itemImg.length>1) {
        for (var i=0;i<activeItemObject.itemImg.length;i++) {
            if (i==(activeImgButNum-1)) borderColor = '#FF9900';
            else borderColor = '#CCCCCC';
          generator.document.write('<td><img id="nbr'+i+'" onClick="changeImg(\'nbr'+i+'\',' + i + ')" onMouseOver="mouseOver(this.id)" onMouseOut="mouseOut(this.id)" src="'+activeItemObject.itemImg[i]+'" height="40" width="40" style="border-color:' + borderColor + ';border-width:1px;border-style:solid;"/></td>');
        }
    }
    generator.document.write('</tr></table></div></td><td width="7">&nbsp;</td></tr></table><table width="530" cellspacing="0" cellpadding="0" border="0"><tr>');
    generator.document.write('<td valign="top" align="left" style="padding-left:14;padding-top:7;" width="257" class="defaultCopyGrey">');
    if (activeItemObject.color!='') {
        generator.document.write(argColorStr+': '+ activeItemObject.color);
    }
    generator.document.write('</td>');
    generator.document.write('<td valign="top" align="right" style="padding-right:14;padding-top:7;" width="257">');
    generator.document.write('<table border="0" cellspacing="0" cellpadding="0">');
    generator.document.write('<tr><td class="instructional">'+argPriceStr+'</td></tr>');
    generator.document.write('<tr><td class="smallPrice">'+activeItemObject.price1+'</td></tr>');
    if (activeItemObject.price5!='') {
        generator.document.write('<tr><td class="ikeaFamilyPrice">'+argFamilyStr+'&nbsp;' + activeItemObject.price5 + '</td></tr>');
    }
    generator.document.write('<tr><td class="ikea-family-offer">'+argOfferStr+'</td></tr>');
    generator.document.write('</table></td></tr></table></body></html>');
    generator.document.close();
  if (window.focus) {generator.focus();}

}

function setStoreCookie() {
	var storeform = null;
	if (document.getElementById) {
  	if (document.getElementById('stocksearch')) {
    	storeform = document.getElementById('stocksearch');
    }
  }
  else if (document.all) {
  	if (document.all['stocksearch']) {
    	storeform = document.all['stocksearch'];
    } 
  }
  
  if (storeform.ikeaStoreNumber1.selectedIndex == 0) {
		return false;
	}
	setCookie('selected_store_num_' + localeJs, storeform.ikeaStoreNumber1.options[storeform.ikeaStoreNumber1.selectedIndex].value , null, '/' );
	return true;
}

function checkStockPressed(e) {
	if (setStoreCookie()) {
		$("stocksearch").submit();
	} 
}

function preSelectStore() {
	var storeNum = getCookie('selected_store_num_' + localeJs);
	if (storeNum != null) {
		var storeform = null;
		if (document.getElementById) {
	  	if (document.getElementById('stocksearch')) {
	    	storeform = document.getElementById('stocksearch');
	    }
	  }
	  else if (document.all) {
	  	if (document.all['stocksearch']) {
	    	storeform = document.all['stocksearch'];
	    } 
	  }
	  for (var i=0;i<storeform.ikeaStoreNumber1.options.length;i++) {
	  	if (storeform.ikeaStoreNumber1.options[i].value == storeNum) {
	  		storeform.ikeaStoreNumber1.options.selectedIndex = i;
	  	}
	 	}
	}
}

function initProductDisplayForFamily(chosenItem) {
	if(!chosenItem||chosenItem==null)
		chosenItem = item0;
	allowSubmit = true;
	activeImgButNum = 1; // initial active imgbut
	activeItemObject = chosenItem; 	
}

function setActiveImgButNum(num) {
	activeImgButNum = num;
}

function setStoreCheckProductId(chosenItem) {
    var storeform = null;
    if (document.getElementById) {
      if (document.getElementById('stocksearch')) {
        storeform = document.getElementById('stocksearch');
    }
  }
  else if (document.all) {
      if (document.all['stocksearch']) {
        storeform = document.all['stocksearch'];
    }
  }
  storeform.productId.value=chosenItem.catEntryId;
}
