/*-------------------------------------------------------------------------------------------------------------------
        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.15  2003/05/13 06:12:22  roym
        Cleand 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 = 7; //Maximum amount of variant image buttons

// variable declarations
var allowSubmit = false;
var activeItemObject = null;
var activeImgBut;
var activeImgButNum;
var numOfDispImgBut;

// selection critera variable
var arrayW = new Array();

//-------------------------------------------------------------------------------------------------------------------
// function for initializing page
//-------------------------------------------------------------------------------------------------------------------
function initProductDisplay(chosenItem) {
	if(!chosenItem||chosenItem==null)
		chosenItem = item0;
	allowSubmit = true;
	activeImgButNum = 1; // initial active imgbut
	initImgButBar(chosenItem.itemImg.length); // initiaize variantimage buttons
	changeItem(chosenItem); // activate first item
	loadItemImgInBckgr(chosenItem); // load variant images for item in background
}
/*function initProductDisplay() {
	allowSubmit = true;
	activeImgButNum = 1; // initial active imgbut
	initImgButBar(item0.itemImg.length); // initiaize variantimage buttons
	changeItem(item0); // activate first item
	loadItemImgInBckgr(item0); // 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. (Need to reverse numbering from right to left for number buttons)
	var calcNum = imgNo - (NUMBEROFBUTTONS - numOfDispImgBut);
	        
	if(activeItemObject != null) {
		changeImgSrc(activeItemObject.itemImg[calcNum]);  // swapImage
		activeImgButNum = calcNum + 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(i);
	}
}

//------
// make attributes that are not valid greyed out and invalid, but they are chooseble anyway.
//------
function makeAttributesInvalid(whichChanged) {

	//alert(whichChanged)
	var INVALID_OPTION = "";

	var whichChangedObj = null;


	//Selected value on changed attributeValue input.
	//här blir fel med checkbox.
	whichChangedObj = arrayW[whichChanged].options[arrayW[whichChanged].options.selectedIndex].value;
	
	var workingAvailAttrValues = new Array();
	var workingAvailCounter = 0;

	for (var i = 0; i < itemAttrValueArray.length;i++) {

		var workingAttrValue = itemAttrValueArray[i];

		//Is chosen one present in this workingAttrValue.
		var isValid = false;
		for (var m = 0; m < workingAttrValue.length; m++) {

			if (workingAttrValue[m] == whichChangedObj) {

				isValid = true;
				break;
			}
		}
		if (isValid) {
			//it is present, find those who are valid and set the invalid N/A.
			for (var j = 0; j < workingAttrValue.length;j++) {

				if (whichChangedObj != workingAttrValue[j]) {

					//build array with optionsvalues that are valid to chosen option.
					workingAvailAttrValues[workingAvailCounter++] = workingAttrValue[j];


				}
			}
		}
	}

	//Lets change dropdown text N/A options.

	//The one that is changed is whichChanged then loop through all dropdowns that are not equal to whichChanged.
	for (var k = 0; k < arrayW.length;k++) {
		if (k!=whichChanged) {
			//set N/A.
			for (var l = 0; l < arrayW[k].length;l++) {

				var isValid = false;
				for (var m = 0; m < workingAvailAttrValues.length; m++) {

					if (workingAvailAttrValues[m] == arrayW[k][l].value) {

						isValid = true;
						//alert("found it! wohoo. k = " + k + " l = " + l);
						break;
					}
				}
				if (isValid) {

					//availble, remove INVALID_OPTION.
					if (arrayW[k][l].text.indexOf(INVALID_OPTION) != -1) {
						//contains INVALID_OPTION string remove.
						arrayW[k][l].text = arrayW[k][l].text.substring(0,arrayW[k][l].text.length - INVALID_OPTION.length);
					}
					arrayW[k][l].style.color = "#000000";
				}
				else {
					//set N/A.
					//if it already contains INVALID_OPTION dont add.
					if (arrayW[k][l].text.indexOf(INVALID_OPTION) == -1) {
						arrayW[k][l].text = arrayW[k][l].text + " " + INVALID_OPTION;
					}

					//grey out
					arrayW[k][l].style.color = "#828282";
				}
			}
		}
	}
}


//-------------------------------------------------------------------------------------------------------------------
// 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.

	//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);
	
	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);
	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';
		}
		getObj('addtoshop').className = 'padt5';
		getObj('dispAddButton').style.display = 'none';
		getObj('dispQuantity').style.display = 'none';
		getObj('dispBuyInShop').style.display = 'block';
	}
	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
		getObj('dispAddButton').style.display = 'block';
		getObj('dispQuantity').style.display = 'block';
		getObj('dispBuyInShop').style.display = 'none';

		initImgButBar(itemObjFound.itemImg.length); // re-initialize Image button bar
		changeItem(itemObjFound); // change displayed item
		loadItemImgInBckgr(itemObjFound); // start loading variant images for displayed item in background
	}
}


//-------------------------------------------------------------------------------------------------------------------
// Initializes buttons for changing images.
//-------------------------------------------------------------------------------------------------------------------
function initImgButBar(nrButtons) {        
	numOfDispImgBut = nrButtons;
	var counter = 1;        

	for (var j = 0; j < NUMBEROFBUTTONS; j++) {
		
		if (document.getElementById || document.all) {
			// hide all buttons to the left that are not used
			if (nrButtons == 1 || j < (NUMBEROFBUTTONS - nrButtons)) {
				getObj('tdNav' + j).style.visibility = 'hidden';
			}
			else {

				// deactivate all buttons
				if (j<6) {
				        // all buttons except the last one should be set with left_out.
				        getObj('tdNav' + j).className = 'navbox_left_out';
				}
				else {
				        // last button is set with right_out
				        getObj('tdNav' + j).className = 'navbox_right_out';
				}

				// activate the first visible button
				if (nrButtons != 1 && counter == 1) {
				        getObj('tdNav' + j).className = 'navbox_left_active';
				        activeImgBut = getObj('tdNav' + j);
				}

				// re-number visible buttons starting with 1 at the leftmoste visible button
				getObj('nbr' + j).innerHTML = counter++;
				getObj('tdNav' + j).style.visibility = 'visible';
			}
		}
		else {  
			alert (js_fn_NOT_VALID_BROWSER);
			return;
		}
	}
}

//-------------------------------------------------------------------------------------------------------------------
// Function to change the displayed item. Function not called directly in page but by checkValidCombination function.
//-------------------------------------------------------------------------------------------------------------------
function changeItem(itemObjToDisplay) {
	if (document.getElementById || document.all){

		if (itemObjToDisplay == null) {
			// if null use active item object.
			itemObjToDisplay = activeItemObject;
		}
		
		for (var d = 0; d < displayedProperties.length; d++) {
			getObj(displayedProperties[d]).innerHTML = eval("itemObjToDisplay." + displayedProperties[d]);
		}
		
		// always go to first image when changing item object
		getObj('productImg').src = itemObjToDisplay.itemImg[0];
		
		getObj('catentryInForm').value = itemObjToDisplay.catEntryId;

		if (itemObjToDisplay.addToShopCart) {
			getObj('addtoshop').className = '';	
			getObj('dispAddButton').style.display = 'block';
			getObj('dispQuantity').style.display = 'block';
			getObj('dispBuyInShop').style.display = 'none';
		}
		else {
			getObj('addtoshop').className = 'padt5';
			getObj('dispAddButton').style.display = 'none';
			getObj('dispQuantity').style.display = 'none';
			getObj('dispBuyInShop').style.display = 'block';
		}
		
		if(itemObjToDisplay.customerBenefitsText != '') {
			getObj('cbftssection').style.display = 'block';
			getObj('lineCBFTS').style.display = 'block';
		}               
		else {
			getObj('cbftssection').style.display = 'none';
			getObj('lineCBFTS').style.display = 'none';
		}
		
		if(itemObjToDisplay.designer != '') {
			getObj('dessection').style.display = 'block';
			getObj('lineDes').style.display = 'block';
		}               
		else {
			getObj('dessection').style.display = 'none';
			getObj('lineDes').style.display = 'none';
		}               
		
		// Start: changed for line sep fix 29.04.03
		if(itemObjToDisplay.careInstructions != '') {
			getObj('careInstructionsPart').style.display = 'block';
			if(itemObjToDisplay.goodToKnow == '' && itemObjToDisplay.environment == '') {	getObj('sepCareInstructions').style.display = 'none'; }
			else { getObj('sepCareInstructions').style.display = 'block';}
		}
		else { getObj('careInstructionsPart').style.display = 'none'; }
		
		if(itemObjToDisplay.goodToKnow != '') {
			getObj('goodToKnowPart').style.display = 'block';
			if(itemObjToDisplay.environment == '') { getObj('sepGoodToKnow').style.display = 'none'; }
			else { getObj('sepGoodToKnow').style.display = 'block'; }	
		}		
		else { getObj('goodToKnowPart').style.display = 'none'; }
     
		if(itemObjToDisplay.environment != '') { getObj('environmentPart').style.display = 'block'; }
		else { getObj('environmentPart').style.display = 'none'; }
		// End: changed for line sep fix 29.04.03

		if(itemObjToDisplay.productFacts != '' || itemObjToDisplay.productMeasure != '')
			getObj('pkgmeasPart').style.display = 'block';
		else
			getObj('pkgmeasPart').style.display = 'none';

		if(itemObjToDisplay.productFacts != '' && itemObjToDisplay.productMeasure != '')
			getObj('pakmeasSplitLine').style.display = 'block';
		else
			getObj('pakmeasSplitLine').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';          

//----------------------------------------------------------
//  PRICES
//----------------------------------------------------------

		//Fixing dual currency on primary price.
		if (itemObjToDisplay.dualCurrencies) {
			getObj('price2').style.visibility = 'visible';
			getObj('separator1_2').style.visibility = 'visible';
		}
		else {
			getObj('price2').style.visibility = 'hidden';
			getObj('separator1_2').style.visibility = 'hidden';             
		}
		
//----------------------------------------------------------
//  Normal prices
//----------------------------------------------------------
		//Fixing dual currency on old price.
		if (itemObjToDisplay.price3 == '') {
			//No changed price.
			//Hide price3 and price4
			//Change style for price1 and price2
			//Black text.
			
			//change to real style!!
			// orange6Bold
			getObj('price1').className = 'black6Bold';
			getObj('pieces').className = 'black6Bold';
			getObj('separator1_2').className = 'black5Bold';
			getObj('price2').className = 'black5Bold';                      
			
			getObj('price3').style.visibility = 'hidden';
			getObj('price4').style.visibility = 'hidden';
			getObj('separator3_4').style.visibility = 'hidden';
		}
		else {
			//show them if there exists data.
			//Change style for price1 and price2.
			//Red text.                     
			getObj('price1').className = 'orange6Bold';
			getObj('pieces').className = 'orange6Bold';
			getObj('separator1_2').className = 'orange5Bold';
			getObj('price2').className = 'orange5Bold';
			
			getObj('price3').style.visibility = 'visible';
			// getObj('offerEndDate').style.visibility = 'visible';
			if (itemObjToDisplay.dualCurrencies) {
				getObj('price4').style.visibility = 'visible';
				getObj('separator3_4').style.visibility = 'visible';
			}                       
			else {
				getObj('price4').style.visibility = 'hidden';
				getObj('separator3_4').style.visibility = 'hidden';                     
			}       
		}
		
//----------------------------------------------------------
//  Family prices
//----------------------------------------------------------            
//Fixing family price dual currency and family text.
		if (itemObjToDisplay.price5 == '') {
			//no family price
			// hide complete familyprice section
			getObj('famsection').style.display = 'none';  // "block":"none"
			getObj('famsection_div').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';
			                        
			getObj('separator5_6').style.visibility = 'hidden';
			getObj('separator7_8').style.visibility = 'hidden';
			
			getObj('familyPrice').style.visibility = 'hidden';
			getObj('lowerDotLine').style.visibility = 'hidden';
		}
		else {
			getObj('famsection').style.display = 'block';  // "block":"none"
			getObj('famsection_div').style.display = 'block';

			getObj('familyPrice').style.visibility = 'visible';
			getObj('price5').style.visibility = 'visible';
			getObj('lowerDotLine').style.visibility = 'visible';

			if (itemObjToDisplay.dualCurrencies) {
				getObj('price6').style.visibility = 'visible';
				getObj('separator5_6').style.visibility = 'visible';
			}
			else {
				getObj('price6').style.visibility = 'hidden';
				getObj('separator5_6').style.visibility = 'hidden';     
			}

			if (itemObjToDisplay.price7 != '') {
				getObj('price7').style.visibility = 'visible';
				if (itemObjToDisplay.dualCurrencies) {
					getObj('price8').style.visibility = 'visible';
					getObj('separator7_8').style.visibility = 'visible';
				}
				else {
					getObj('price8').style.visibility = 'hidden';
					getObj('separator7_8').style.visibility = 'hidden';
				}
			}
		}
		// change active item object
		activeItemObject = itemObjToDisplay;            
	}
	else {
		alert (js_fn_NOT_VALID_BROWSER);
		return;
	}
}

//-------------------------------------------------------------------------------------------------------------------
// Function for finding the item object based on selected selection criterias.
//-------------------------------------------------------------------------------------------------------------------
function findCatentryIdForItem(attributeValues) {
        for (var i = 0; i < itemAttrValueArray.length; i++) {
                if (attributeValues.join("##").toLowerCase() == 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.itemImg;

	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('ProductPopUpView?productId=' + activeItemObject.catEntryId + "&" + storeAndLang + "&variantNum=" + activeImgButNum, '500', '520', 'pop01b', 0);
}

//-------------------------------------------------------------------------------------------------------------------
// Opens Color sample popup
//-------------------------------------------------------------------------------------------------------------------
function openColorSample(args) {
        if (activeItemObject != null)
                openPopUp('SamplePopUpView?' + args, '296', '270', 'Pop09', 1);
                
}

//-------------------------------------------------------------------------------------------------------------------
// Opens Package and measurement popup
//-------------------------------------------------------------------------------------------------------------------
function openPackageAndMeasurement(args) {
        if (activeItemObject != null)
                openPopUp('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="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;
}

/**************************************************************************
* NAVIGATION BAR FUNCTIONS, DYNAMIC ROLLOVER HANDLING
**************************************************************************/ 
function tdMouseOver(argID){
        if (!document.getElementById) {
                return;
        }       
        
   tmp =  document.getElementById(argID);
   
        if( tmp.className != 'navbox_left_active' && tmp.className == 'navbox_left_out' ){
                tmp.className = 'navbox_left_over';
        } 
        if( tmp.className != 'navbox_right_active' && tmp.className == 'navbox_right_out' ){
        tmp.className = 'navbox_right_over';
        }
}

function tdMouseOut(argID){
        if (!document.getElementById) {
                return;
        }       

        tmp =  document.getElementById(argID);

   if( tmp.className != 'navbox_left_active' && tmp.className == 'navbox_left_over' ){
                tmp.className = 'navbox_left_out';
   } 
   if( tmp.className != 'navbox_right_active' && tmp.className == 'navbox_right_over' ){
      tmp.className = 'navbox_right_out';
   }
}

function tdOnClick(argID){
        if (!document.getElementById) {
                return;
        }
                
        tmp =  document.getElementById(argID);
  
        if(tmp.className.indexOf('active') != -1) {
                return;
        }
  
        if( tmp.className == 'navbox_left_over' || tmp.className == 'navbox_left_active' || tmp.className == 'navbox_left_out') {
                tmp.className = 'navbox_left_active';
        } 
        else {
                tmp.className = 'navbox_right_active';
        } 
        
        if (activeImgBut.className == 'navbox_left_active') {
                activeImgBut.className = 'navbox_left_out';
        }
        else {
                activeImgBut.className = 'navbox_right_out';
        } 

        activeImgBut = tmp;     
}
/**************************************************************************
* END OF NAVIGATION BAR FUNCTIONS, DYNAMIC ROLLOVER HANDLING 
***************************************************************************/