/**
* The main javascript file for Product Selector Tool
* @author Murat Arslan
* @author Fatih Incefidan
* @author Ozge Koylu
* 
* @author Deniz KALFA
*/

var INITIAL = "INITIAL";
var EMPTY = "empty";
var INTERSECTION_OPERATOR = "AND";
var EMPTY_INTERSECTION_ARRAY = new Array("NO-MATCH");

var QUESTION_VIEW_TYPE_SLIDER = "Slider";
var QUESTION_VIEW_TYPE_OTHER  = "Other";

var activeSliderLabelsMap = new  Object(); 
var sliderLabelsMap = new  Object(); 

var productSelector = {
	initialized : false,
	name : "",
	totalProductCount : 0,
	description : "",
	logger : null,
	questions : null,
	currentProducts : null,
	productGroups : null,
	allProducts : null,
	allProductsAsGrouped : null,
	//allProductsWithPrice : null,
	//allProductsWithoutPrice : null,
	allProductsBoxes : null,
	questionsHash : new Array(),
	processShowProducts: true,
	
    initialize: function(name, description) {
		this.name  = name;
		this.totalProductCount = 70;
		this.description = description;
		this.logger = document.getElementById('logger');
		this.questions = null;	//important hierarchy object
		this.currentProducts = new Array(); //Cant be null.
		this.productGroups = new Array();
		this.allProducts = null;
		this.allProductsAsGrouped = null;
		this.buildDataStructure(this);
		this.initialized = true;
		this.enablePreSelectedSku();
		this.adjustColourPalleteRowHeight();
		this.processShowProducts = true;
	},
	setSelectorType: function (selectorType){
		this.selectorType = selectorType;
	},
	getQuestion: function(qId){
		if(this.questionsHash!=null)
			return this.questionsHash[qId];
	},
	log: function(str){
		if(this.logger)
			this.logger.innerHTML += str;
	},
	logTime: function(startdate){
		if(this.logger){
			var endDate = new Date();
			this.logger.innerHTML += (endDate.getTime()-startdate.getTime())+'ms.';
		}
	},
	
	//updateAfterSortForPrice: function(allProductsWithPriceAfterSort){
		//this.allProductsWithPrice = allProductsWithPriceAfterSort;
	//},
	//pc : remove non price area
	//updateAfterSortForNonPrice: function(allProductsWithoutPriceAfterSort){
		//this.allProductsWithoutPrice = allProductsWithoutPriceAfterSort;
	//},
	
	updateAfterSortAsGrouped: function(allProductsAfterSort){
		this.allProductsAsGrouped = allProductsAfterSort;
	},
	
	// creates data structure from created page with jsp
	buildDataStructure: function() {
		
		this.allProducts = $('tvoe-all-products').value.split(';');
		this.allProductsAsGrouped = $('tvoe-all-products-as-grouped').value.split(';');
		this.currentProducts = this.allProducts;
		
		//this.allProductsWithPrice = new Array();
		//if($('tvoe-products-with-price').value != '') {
			//this.allProductsWithPrice = $('tvoe-products-with-price').value.split(';')
		//}
		
		//this.allProductsWithoutPrice = new Array();
		//if($('tvoe-products-without-price').value != '') {
			//this.allProductsWithoutPrice = $('tvoe-products-without-price').value.split(';');
		//}
		
		this.allProductsBoxes = new Array();
		for(var i=0; i < this.allProductsAsGrouped.length; i++)
		{
			var html1 =  $('grid-cell-product-'+this.allProductsAsGrouped[i]).innerHTML;
			var html2 =  $('grid-cell-controls-top-'+this.allProductsAsGrouped[i]).innerHTML;
			var html3 =  $('grid-cell-controls-middle-'+this.allProductsAsGrouped[i]).innerHTML;
			var html4 =  $('grid-cell-controls-bottom-'+this.allProductsAsGrouped[i]).innerHTML;
			
			this.allProductsBoxes[i] = new ProductBox(this.allProductsAsGrouped[i],html1, html2, html3, html4);
		}
		
		var questionsArray = $$('div.tvoe-question');
  		var questionsDataObject = new Array();
  		
  		for(var i=0; i < questionsArray.length; i++)
  		{
  			var question = questionsArray[i];
  			var criteriaQ = 'input.' + question.id + '-criteria';	
  			var title = $(question.id + '-title').innerHTML; // Use id identifier to get title.
  			var type = question.getAttribute('rel');
  			var checkedByDefault = question.getAttribute('alt');
  			var viewType = question.getAttribute('viewType');
  			var childs = $$(criteriaQ);
			var criterias = new Array();

			if(!viewType)
				viewType = QUESTION_VIEW_TYPE_OTHER;
			
			for(var j=0; j < childs.length; j++)
	  		{
				var child = childs[j];
				if(child.value!=null)
				{
					criterias[criterias.length] = new Criteria(
						child.id,
						question.id,
						child.alt, 
						child.value);
				}
  			}
  			
  			questionsDataObject[questionsDataObject.length] = new Question(
  				question.id,
  				title, 
  				type,
  				checkedByDefault,
  				criterias,
  				viewType
  			);
  			  			
  			this.questionsHash[question.id] = questionsDataObject[questionsDataObject.length-1];

		}//end-of-for
  		
  		this.questions = questionsDataObject;
  		sortSelectedModels();
  		sortAllProductSkus();
  		
  	},
  	reset: function() {
  		
  		var currentProducts = new Array();
  		//1-Firstly find ResultSet
  		for(var i=0; i < this.questions.length; i++)
  		{
  			var question = this.questions[i];
  			
  			var productsComesFromCurrentQuestion = question.getCurrentProducts();
  			
  			if(question.checkedByDefault == 'false' && productsComesFromCurrentQuestion.length == 0) {
  				productsComesFromCurrentQuestion = this.allProducts;
  			}
  			if(productsComesFromCurrentQuestion.length > 0) {
  				currentProducts = currentProducts.length==0 ? productsComesFromCurrentQuestion : currentProducts.intersection(productsComesFromCurrentQuestion);
  			}
  			
  		}//end-of-for
  		this.resetAllCheckBoxes();	// Reset checkboxes to their initial states.
  		this.currentProducts = currentProducts;
  		this.showProducts();
  		ProductCompare.Reset();
  	},

  	getCurrentProducts: function() {
  		
  		var currentProducts = new Array();
  		//1-Firstly find ResultSet
  		for(var i=0; i < this.questions.length; i++)
  		{
  			var question = this.questions[i];
  			
  			var productsComesFromCurrentQuestion = question.getCurrentProducts();
  			
  			if(productsComesFromCurrentQuestion.length > 0)
  			{
  				currentProducts = currentProducts.length==0 ? productsComesFromCurrentQuestion : currentProducts.intersection(productsComesFromCurrentQuestion);
  			}
  		}//end-of-for
  		
  		return currentProducts;
  	},
  	
  	getCurrentProductsWithRefresh: function(refreshThisQuestion, clickedCriteria) {
  		
  		var currentProducts = new Array();
  		var questionObj = this.getQuestion(refreshThisQuestion);
  		if(questionObj != null && questionObj != ''){
  			var criteriaObj = questionObj.getCriteria(refreshThisQuestion+'-'+clickedCriteria);
  		}
  		
  		//1-Firstly find ResultSet
  		for(var i=0; i < this.questions.length; i++)
  		{
  			var question = this.questions[i];
  			var productsComesFromCurrentQuestion = question.getCurrentProducts();
  			
  			if(criteriaObj && refreshThisQuestion != question.id){
  				var criterias = question.criterias;
  				for(var j=0; j < criterias.length; j++){
  					if(criterias[j].getHTMLObject().disabled && criterias[j].lastState){
		  				if(question.type != INTERSECTION_OPERATOR && criteriaObj.getHTMLObject().checked){	
		  					var productsOfCriteria = criterias[j].products;
		  					var intersectionProducts = productsOfCriteria.intersection(criteriaObj.products);
		  					productsComesFromCurrentQuestion = productsComesFromCurrentQuestion.union(intersectionProducts);
		  				}
			  			else if(questionObj.type == INTERSECTION_OPERATOR){
		  					var productsOfCriteria = criterias[j].products;
		  					productsComesFromCurrentQuestion = productsComesFromCurrentQuestion.union(productsOfCriteria);
			  			}
  					}
	  			}
  			}
  			
  			if(question.checkedByDefault == 'false' && productsComesFromCurrentQuestion.length == 0) {
  				productsComesFromCurrentQuestion = this.allProducts;
  			}
  			if(productsComesFromCurrentQuestion.length > 0) {
  				currentProducts = currentProducts.length==0 ? productsComesFromCurrentQuestion : currentProducts.intersection(productsComesFromCurrentQuestion);
  			}
  			
  			// If currentProducts' length becomes 0, it means empty intersection.
  			// Therefore, just return the empty array(currentProducts).
  			if(currentProducts.length == 0)
  			{
  				return currentProducts;
  			}
  		}//end-of-for
  		
  		return currentProducts;
  	},
   	
  	getCurrentProductsWithRefreshAsIfCheckboxClicked: function(refreshThisQuestion, clickedCriteriaId, checkboxObject) {
  		
  		// Store last chosen radio button, to restore it at the end.
  		var lastChosenRadioButtonHtmlObj;
  		if(checkboxObject.type == 'radio')
  		{
  			var question = this.getQuestion(refreshThisQuestion);
  			var criterias = question.criterias;
  			for(var i=0; i < criterias.length; i++){
  				var criteria = criterias[i];
  				if(criteria != null && criteria != "")
  				{
  					var criteriaHtmlObj = criteria.getHTMLObject();
  					// Check if it is checked and if its type is 'radio', since radio button type question might have hidden checkbox.
  					if(criteriaHtmlObj.checked && criteriaHtmlObj.type == 'radio')
  					{
						lastChosenRadioButtonHtmlObj = criteria.getHTMLObject();
  					}
  					
  				}
  			}
  		}
  		
  		if(checkboxObject != null && checkboxObject != '')
  		{
			checkboxObject.checked = true;
			var currentProducts = this.getCurrentProductsWithRefresh(refreshThisQuestion, clickedCriteriaId);
			checkboxObject.checked = false;
  		}
  		
  		// Restore last chosen radio button.
  		if(checkboxObject.type == 'radio' && lastChosenRadioButtonHtmlObj != null
  										  && lastChosenRadioButtonHtmlObj != "")
  		{
  			lastChosenRadioButtonHtmlObj.checked = true;
  		}
  		
  		return currentProducts;
  	}, 
  	
  	//Call with me with first selected criteria while calling from cookie-case.
  	click: function(checked, clickedQuestion, clickedCriteria) {
  		
  		//if(clickedQuestion)
  		//	this.preProcess(clickedQuestion, clickedQuestion+'-'+clickedCriteria, this.currentProducts);
  		
  		this.log('click:');
  		
  		var startdate = new Date();
  		this.currentProducts = this.getCurrentProductsWithRefresh(clickedQuestion, clickedCriteria);
  		this.log(this.currentProducts.length+'-');
  		this.logTime(startdate);
  		
  		if(clickedQuestion){
  			startdate = new Date();
  			this.postProcess(clickedQuestion, clickedQuestion+'-'+clickedCriteria, this.currentProducts);
  			this.logTime(startdate);
   		}
  		
  		var checkedQuestions = $("checkedCriteriaIds");
  		if(checked){
  			checkedQuestions.value = checkedQuestions.value + "&" + clickedQuestion + "-" + clickedCriteria;
  		}
  		else {
  			 var searchString = clickedQuestion + "-" + clickedCriteria;
  			 checkedQuestions.value = checkedQuestions.value.replace(searchString,"");
  		}
  		
  		// Refresh select all/none links with current states of checkboxes.
  		refreshSelectAllSelectNoneLinks();
  		
  		// Execute following lines, if last ticking action makes all the checkboxes
  		// at the same state(e.g. all checked or all unchecked).
  		if(this.isLastCheckedItem(clickedQuestion, clickedCriteria, checked)) {
  			this.currentProducts = this.getCurrentProductsWithRefresh(clickedQuestion, clickedCriteria);
  			this.postProcess(clickedQuestion, clickedQuestion+'-'+clickedCriteria, this.currentProducts);
  		}
  		
  		startdate = new Date();
  		if(this.processShowProducts) {
  			this.showProducts(); 
  		}
  		
  		// Reclick previously selected colours after each click.
  		if($('selectedColours') && $('selectedColours').value) {
  			var selectedColours = $('selectedColours').value.split(',');
  			reClickSelectedColoursFromPalette(selectedColours);
  		}
  		
  		this.logTime(startdate);
  		this.log('<br/>');
  	},
  	
  	// This method checks if all the checkboxes in the same group are at the same state
  	// with the last ticking action.
  	isLastCheckedItem: function(clickedQuestion, clickedCriteria, checkState) {
  				
  		if(clickedQuestion && clickedCriteria) {
  			
	  		var question = this.getQuestion(clickedQuestion);  		
	  		if(question != null && question != ''){
	  			var checkboxObject = question.getCriteria(clickedQuestion+'-'+clickedCriteria).htmlObject;
	  			
	  			if(checkboxObject && checkboxObject.checked == checkState) {
	  				
		  			var criterias = question.criterias;
		  			for(var i=0; i < criterias.length; i++) {
		  				var criteria = criterias[i];
		  				if(criteria && !criteria.htmlObject.disabled && criteria.htmlObject.checked == !checkState) {
		  					return false;
		  				}
		  			}
		  			
		  			// Meaning, clickedCriteria/checkbox was the only one selected and it was unselected recently. 
		  			return true;
	  			}
	  		}
	  		
  		}
  	},
  	
  	preProcess: function(clickedQuestion, clickedCriteria, currentProducts) {
  	
  	},
  	postProcess: function(clickedQuestion, clickedCriteria, currentProducts) {//Process trivial and useless criterias.
  		
  		for(var i=0; i < this.questions.length; i++)
  		{
  			var question = this.questions[i];
  			for(var j=0; j < question.criterias.length; j++)
  	  		{
  	  			var criteria = question.criterias[j];
	  	  		var checkboxObject = criteria.getHTMLObject();
	  	  		
	  	  		this.autoDisablePotentialEmptyResultCandidates(clickedQuestion, clickedCriteria, question, criteria, currentProducts, checkboxObject);
		  	  	if(clickedQuestion!=question.id)
				{	//Only Apply to other questions
		  	  		this.autoDisableUselessCriterias(clickedQuestion, clickedCriteria, question, criteria, currentProducts, checkboxObject);
		  	  		// Trivial Check : Only apply to other questions.
		  	  		//this.autoSelectTrivialCriterias(clickedQuestion, clickedCriteria, question, criteria, currentProducts, checkboxObject);
  	  			}
  	  		}
  		}//end-of-for
  		
  		loadSliders();
  	},
  	
  	resetAllCheckBoxes:function(){
  		for(var i=0; i < this.questions.length; i++)
  	  		{
  	  			var question = this.questions[i];
  	  			for(var j=0; j < question.criterias.length; j++)
  	  			{
  	  				var criteria = question.criterias[j];
  	  				
  	  				var checkByDefault = false;								// Set checkByDefault variable to false initially.
  	  				if(criteria.htmlObject.getAttribute('rel') == 'true'	// This one is for radiobutton or hidden no-price checkbox.
  	  					|| question.checkedByDefault == 'true') {			// This one is regular checkbox.
  	  					checkByDefault = true;
  	  				}
  	  				
	  	  			criteria.changeMode(false, checkByDefault, STATUS_INITIAL);
				}
  			}//end-of-for
  			
  			this.currentProducts = this.getCurrentProducts();
  	},
  	
  	autoDisablePotentialEmptyResultCandidates: function(clickedQuestion, clickedCriteria, question, criteria, currentProducts, checkboxObject) {
  	  	/*
  		 * Only checks clicked group, will it be empty after next click, if yes disable it to prevent from empty selection.
  		 */
  		if(criteria.getHTMLObject().type == 'checkbox')
  		{
			if(question.type == INTERSECTION_OPERATOR)
			{
				if(clickedQuestion == question.id && clickedCriteria != criteria.id)
				{
					var intersectionProducts = criteria.products.intersection(currentProducts);
					var uselessCandidate = criteria.isUselessCandidate(currentProducts);
					if(checkboxObject.checked == false)
					{
						if(uselessCandidate && criteria.status!=STATUS_CAUSE_EMPTY) {
							criteria.changeMode(true,false,STATUS_CAUSE_EMPTY);
						}
						else if((criteria.status==STATUS_CAUSE_EMPTY || criteria.status==STATUS_USELESS) && (!uselessCandidate)) 
						{	//It's not a potentialEmptyResult anymore, Then Revert it
							criteria.changeMode(false,false,STATUS_INITIAL);
						}
						else if(!uselessCandidate && intersectionProducts.length == currentProducts.length && criteria.status!=STATUS_TRIVIAL)
						{
							criteria.changeMode(true,true,STATUS_TRIVIAL);
						}
					}
					else	// Checked state
					{
						if(criteria.status==STATUS_TRIVIAL)
						{
						  	if(uselessCandidate)
							{
								criteria.changeMode(true,false,STATUS_USELESS);
							}
							else if(intersectionProducts.length != currentProducts.length)
							{
								criteria.changeMode(false,false,STATUS_INITIAL);
							}
						}
					}
	
					
				}
			}else{ // ! INTERSECTION_OPERATOR
				if(checkboxObject.checked==true)
				{
					if(criteria.status==STATUS_INITIAL)
					{
						// We don't auto-disable the last checkbox anymore. For detail: ADR7055.
						//
						// var potentialEmptyResultCandidates = question.getCurrentProductsWithExcluded(criteria.id);
						// var intersectionWithCurrentProducts= currentProducts.intersection(potentialEmptyResultCandidates);
						// if(criteria.id != clickedCriteria && intersectionWithCurrentProducts.length==0) {
						// 	criteria.changeMode(true,true,STATUS_CAUSE_EMPTY);
						// }
					}else{
						var potentialEmptyResultCandidates = question.getCurrentProductsWithExcluded(criteria.id);
						var intersectionWithCurrentProducts= currentProducts.intersection(potentialEmptyResultCandidates);
						if(intersectionWithCurrentProducts.length>0) 
						{	//It's not a potentialEmptyResult anymore, Then Revert it
							criteria.changeMode(false,true,STATUS_INITIAL);
						}
					}
				}
				
			}
  		}
  	},
  	
  	autoDisableUselessCriterias: function(clickedQuestion, clickedCriteria, question, criteria, currentProducts, checkboxObject) {
  	
  		if(question.type == INTERSECTION_OPERATOR)
		{
			var intersectionProducts = criteria.products.intersection(currentProducts);
  			if(criteria.status==STATUS_INITIAL)
			{
	  			if(checkboxObject.checked == false)
	  			{
	  				var uselessCandidate = criteria.isUselessCandidate(currentProducts);
	  				if(uselessCandidate)
					{
						criteria.changeMode(true,false,STATUS_USELESS);
					}
					else if(intersectionProducts.length == currentProducts.length)
					{
						criteria.changeMode(true,true,STATUS_TRIVIAL);
					}
	  			}
			}
			else if(criteria.status==STATUS_USELESS)
			{
				if(intersectionProducts.length>0)
				{
					criteria.changeMode(false,false,STATUS_INITIAL);
				}
				
			}
			else if(criteria.status==STATUS_TRIVIAL || criteria.status==STATUS_CAUSE_EMPTY){
				var uselessCandidate = criteria.isUselessCandidate(currentProducts);
  				if(uselessCandidate)
				{
					criteria.changeMode(true,false,STATUS_USELESS);
				}
				else if(intersectionProducts.length != currentProducts.length)
				{
					criteria.changeMode(false,false,STATUS_INITIAL);
				}
			}
		}else{	// !INTERSECTION_OPERATOR
			if(criteria.status==STATUS_INITIAL)
			{
				if(checkboxObject.checked == true)
				{	// Checked Criteria
					var uselessCandidate = criteria.isUselessCandidate(currentProducts);
					if(uselessCandidate && checkboxObject.type == 'checkbox')
					{
						criteria.changeMode(true,false,STATUS_USELESS);
						criteria.lastState = true;
					}
				}else{//!checked
					var criteriaId = criteria.id.substr(question.id.length+1, criteria.id.length);	// Extract questionId from criteriaId.
					var tmpCurrentProducts = this.getCurrentProductsWithRefreshAsIfCheckboxClicked(question.id, criteriaId, checkboxObject);
					var uselessCandidate = criteria.isUselessCandidate(tmpCurrentProducts);
					if(uselessCandidate)
					{
						criteria.changeMode(true,false,STATUS_USELESS);
						criteria.lastState = false;
					}
				}
			}else{	// Useless
				if(checkboxObject.checked == false)
				{					
					var criteriaId = criteria.id.substr(question.id.length+1, criteria.id.length);	// Extract questionId from criteriaId.
					var tmpCurrentProducts = this.getCurrentProductsWithRefreshAsIfCheckboxClicked(question.id, criteriaId, checkboxObject);
					var stillUselessCandidate = criteria.isUselessCandidate(tmpCurrentProducts);
					if( !stillUselessCandidate) 
					{	//Revert it
						criteria.changeMode(false,criteria.lastState,STATUS_INITIAL);
						
						//Also check STATUS_CAUSE_EMPTY to update question.
						for(var j=0; j < question.criterias.length; j++)
			  	  		{
			  	  			var criteriaInner = question.criterias[j];
				  	  		var checkboxObjectInner = criteriaInner.getHTMLObject();
				  	  		this.autoDisablePotentialEmptyResultCandidates(clickedQuestion, clickedCriteria, question, criteriaInner, currentProducts, checkboxObjectInner);
			  	  		}
					}
				}
			}
		}
  	},
  	
  	// change product related page view
  	showProducts: function() {
  				
  		var allProducts = new Array();
  		var target = $('productContainer');	
		//var targetNoPrice = $('productContainer-NoPrice');
		
		//if (this.allProductsWithPrice) {
			//allProducts = this.allProductsWithPrice;
		//}

		//if (this.allProductsWithoutPrice) {
			//allProducts = allProducts.concat(this.allProductsWithoutPrice);
		//}
  		
  		allProducts = this.allProductsAsGrouped;
		var len1 = this.rePaintGrid('productContainer', allProducts); 
		//var len2 = this.rePaintGrid('productContainer-NoPrice', this.allProductsWithoutPrice);
		
		//this.displayCurrentSelectionCount(len1 + len2); 
  		this.displayCurrentSelectionCount(len1); 
  		
  		//this.showAndHideNoPriceProductsBlock(len2);
  		//psCompareButton.showAndHideScroller(this);
  		
  		//this.disableLastProduct(len1 + len2);
  		this.disableLastProduct(len1);
  		this.displayNoProductText(len1, target);
  		
  		if(pstCookieManager)
  			pstCookieManager.resetSaveSettingLink();
  		
  		this.setImageGalleryOfProducts();
  		ProductCompare.init();
  	},
  	
  	setImageGalleryOfProducts: function(){
  		jQuery('.lightbox').lightbox({
            fitToScreen: true,
            disableNavbarLinks: true,
            imageClickClose:false,
			navbarOnTop: true,
            strings : {
                prevLinkTitle: translations.previous,
                nextLinkTitle: translations.next,
                prevLinkText:  '&laquo; Previous',
                nextLinkText:  'Next &raquo;',
                closeTitle: translations.close,
                image: translations.imageOf
            }
        });
  	},	 
  	
  	// display message when there is no product
	enablePreSelectedSku: function() {
		var name = $('preSelectedSku');
		if(name) { 
			if(name.value != null && name.value != '') {
				var obj = $(name.value);
				if(obj) {
					obj.checked = 'checked';
					//psCompareButton.showAndHideScroller(this,obj);
					name.value = null; // Reset value in order to avoid having it after history.back
									   // when the preselected product is unchecked.
				}
			}
		}
	},
    	
  	// disables the last products compare checkbox
  	disableLastProduct: function(len) {
  		if(len == 1) {
  			var prodName = this.currentProducts[0];
  			var obj = $(prodName);
  			if(obj) obj.disabled = true;
  		}
  	},
  	
  	// display message when there is no product
	displayNoProductText: function(len, target) {
		var object = $('noProductMessage');
		if(object && target != null) {
			(len == 0) ? object.style.display = 'block' : object.style.display = 'none';		
		}
	},
  	
  	// if there is no product without price, hide all No-Price-Block 
	// pc : remove non price area
	//showAndHideNoPriceProductsBlock: function(len) {
  		//var block = $('prodSelectorNoPriceBlock');
  		//if(block)
  			//(len == 0) ?	block.style.display = 'none' : block.style.display = 'block';
  	//},
  	
  	rePaintGrid: function(productContainerId, itemsToBeIterate){
  	
	  var productContainer = $(productContainerId);
      if (productContainer != null){
	      	productContainer.hide();
	  	
	      var tableHTML = '<table border="0" cellspacing="0" cellpadding="0" class="cntResultsTable">';
	      
	      var productBoxRowHTML = '';
	      var productControlsTopRowHTML = '';
	      var productControlsMiddleRowHTML = '';
	      var productControlsBottomRowHTML = '';
	  	   
	  	  var countOfVisibles = 0;
	      for(var i=0; i < itemsToBeIterate.length; i++)
	  		{
	        var productId = itemsToBeIterate[i];  //use id
	  			
	  			if(productId != null) {
		  			if(this.showProductBox(productId)) 
		  			{ //Visible
		  			  countOfVisibles++;
		  			  if(countOfVisibles%4==1) {
		  			    productBoxRowHTML = '<tr>';
		  			    productControlsTopRowHTML = '<tr>';
		  			    productControlsMiddleRowHTML = '<tr>';
		  			    productControlsBottomRowHTML = '<tr>';
		  			  }
		  			  
		  			  var currentProductBox = this.getProductBoxById(productId);
		  			  
		  			  productBoxRowHTML += '<td>' + currentProductBox.infoBoxHTML + '</td>';
		  			  productControlsTopRowHTML += '<td>' + currentProductBox.controlsBoxTopHTML + '</td>';
		  			  productControlsMiddleRowHTML += '<td>' + currentProductBox.controlsBoxMiddleHTML + '</td>';
		  			  productControlsBottomRowHTML += '<td>' + currentProductBox.controlsBoxBottomHTML + '</td>';
		  			  
		  			  if(countOfVisibles%4==0) { 
		  			    tableHTML += productBoxRowHTML + '</tr>'+ productControlsTopRowHTML + '</tr>' + productControlsMiddleRowHTML + '</tr>' + productControlsBottomRowHTML + '</tr>';
		  			    productBoxRowHTML = '';
		  			    productControlsTopRowHTML = '';
		  			    productControlsMiddleRowHTML = '';
		  			    productControlsBottomRowHTML = '';
		  			  }
		  			}
		  			
		  		}
	  		} // end of for
	  		
	  		if (countOfVisibles%4 != 0) {
	  			var emptyTDNumber = 4 - (countOfVisibles%4);
	  			for (var i=0; i<emptyTDNumber; i++){
	  				 productBoxRowHTML += '<td></td>';
	  				 productControlsTopRowHTML += '<td></td>';
	  				 productControlsMiddleRowHTML += '<td></td>';
	  				 productControlsBottomRowHTML += '<td></td>';
	  			}
	  			tableHTML += productBoxRowHTML + '</tr>'+ productControlsTopRowHTML + '</tr>' + productControlsMiddleRowHTML + '</tr>' + productControlsBottomRowHTML + '</tr>';
	  		}
	  		
	  		tableHTML += '</table>';
	  		
	  		productContainer.innerHTML = tableHTML;
	  		
	  		productContainer.show();

	  		this.adjustColourPalleteRowHeight();
	  
	  		return countOfVisibles;
      }
      
     
      return 0;
      
    },

    // Colour palette row can/should be double line, 
    // if there are more than 5 colour variations in the palette.
    adjustColourPalleteRowHeight: function() {
  		this.changeColourPaletteRowHeight('div#productContainer div.prod-color');
  		//this.changeColourPaletteRowHeight('div#productContainer-NoPrice div.prod-color');
    },
    
    changeColourPaletteRowHeight: function(selectorString) {
    	var colourPalettesOfPricedProducts = $$(selectorString);
    	
    	for(var i = 0; i < colourPalettesOfPricedProducts.length; i += 4) {
    		var colourPalettesPerRow = new Array();
    		// Take and put every 4 colour palette into the array.
    		for(var j = 0; j < 4; j++) {
    			if(colourPalettesOfPricedProducts[i + j]) {
    				colourPalettesPerRow[j] = colourPalettesOfPricedProducts[i + j];
    			}
    		}
    		
    		var defaultColourPaletteHeight = '0px';
    		var colourPaletteRowHeight = defaultColourPaletteHeight;
    		for(var j = 0; j < colourPalettesPerRow.length; j++) {
	    		var numberOfColourVariations = colourPalettesPerRow[j].select('a').length;
	    		// More than 5, it is 2rows
	    		if(numberOfColourVariations > 5) {
	    			colourPaletteRowHeight = '46px';
	    			j = colourPalettesPerRow.length;
	    		}
	    		// Up to 5 and more than 0, it is 1row
	    		else if(numberOfColourVariations > 0) {
	    			colourPaletteRowHeight = '23px';
	    		}
    		}
    		if(colourPaletteRowHeight != defaultColourPaletteHeight) {
	    		for(j = 0; j < colourPalettesPerRow.length; j++) {
	    			colourPalettesPerRow[j].setStyle({height: colourPaletteRowHeight});
	    		}
    		}
    	}
    },
    
    showProductBox: function(productId) {
    	if(this.currentProducts.exist(productId)) {
    		return true;
    	}
    	else if(productSelector.productGroups[productId]){
    		var groupedProductIds = productSelector.productGroups[productId].split(';');
    		
    		for(i=0, groupedProductIdsLength=groupedProductIds.length; i<groupedProductIdsLength; i++) {
    			if(this.currentProducts && this.currentProducts.exist(groupedProductIds[i])) {
    				return true;
    			}
    		}
    	}
    	
    	return false;
    },
    
    getProductBoxById: function(id){
      for(var i=0; i < this.allProductsBoxes.length; i++)
  		{
  		  if(this.allProductsBoxes[i].id == id)
  		    return this.allProductsBoxes[i];
  		}
    },
  	
	displayCurrentSelectionCount: function(len) {
		var object = $('currentSelectionCount');
		if(object != null)
			object.innerHTML = len;
	},
	
	
	// Deprecated, since we don't disable the last checkbox anymore.
	// Disables criteria of the questions that have only one criteria
	disableCriteriaForQuestionsWithSingleCriteria: function(){
	  	for(var i=0; i < this.questions.length; i++)
  		{
  			var question = this.questions[i];
	  			if(question.criterias.length == 1)
	  			{
	  				var criteria = question.criterias[0];
	  				if(question.type == INTERSECTION_OPERATOR)	// AND operator
	  				{
	  					if(criteria.products.length == this.currentProducts.length)
	  					{
	  						criteria.changeMode(true,true,STATUS_TRIVIAL);
	  					}
	  				}
	  				else if(question.type != INTERSECTION_OPERATOR)	// OR operator
	  				{
	  					criteria.changeMode(true,true,STATUS_CAUSE_EMPTY);
	  				}
	  			}
  		}
	}
	
};//End of ProductSelector Class


function Question (id, title, type, checkedByDefault, criterias, viewType) 
{
	this.id  = id;
    this.title = title;
    this.type = type;
    this.checkedByDefault = checkedByDefault;
    this.criterias = criterias;
    this.currentProducts = null;
    this.viewType = viewType;
    this.criteriasHash = new Array();
    
    for(var i=0; i < this.criterias.length; i++)
  	{
  		var criteria = this.criterias[i];
  		this.criteriasHash[criteria.id] = criteria;
  	}
  	
	
	this.getCriteria = function(criteriaId){
		if(this.criteriasHash != null){
			return this.criteriasHash[criteriaId];	
		}
	};
    this.getCurrentProducts = function() {
    	return this.getCurrentProductsWithExcludedOrIncluded(EMPTY, EMPTY);
    };
    this.getCurrentProductsWithIncluded = function(includedCriteria) {
		var arr = this.getCurrentProductsWithExcludedOrIncluded(includedCriteria, EMPTY);
		return arr;
	};
	this.getCurrentProductsWithExcluded = function(excludedCriteria) {
		var arr = this.getCurrentProductsWithExcludedOrIncluded(EMPTY, excludedCriteria);
		return arr;
	};
	this.getCurrentProductsWithExcludedOrIncluded = function(includedCriteria, excludedCriteria) {
		
		var productsComesFromCurrentQuestion = new Array();
		
		var noCheckedCriteria = true;
		
		for(var i=0; i < this.criterias.length; i++)
  		{
  			var criteria = this.criterias[i];
			if(excludedCriteria != criteria.id)
			{
				var checkboxObject = criteria.getHTMLObject();
				if(checkboxObject.checked == true || includedCriteria == criteria.id)
				{
					if(this.type == INTERSECTION_OPERATOR  && criteria.status != STATUS_TRIVIAL)
					{
						noCheckedCriteria = false;
						if(productsComesFromCurrentQuestion.length == 0)//check initial case
							productsComesFromCurrentQuestion = criteria.products;
						else
							productsComesFromCurrentQuestion = productsComesFromCurrentQuestion.intersection(criteria.products);
					}
					else if(this.type != INTERSECTION_OPERATOR)
					{
						noCheckedCriteria = false;
						productsComesFromCurrentQuestion = productsComesFromCurrentQuestion.union(criteria.products);
					}
				}
			}
		}//end-of-for
		
		if(this.type == INTERSECTION_OPERATOR && noCheckedCriteria)
			productsComesFromCurrentQuestion = new Array(); // Return Empty Array To ignore total calculate
		else if(this.type == INTERSECTION_OPERATOR && (!noCheckedCriteria) && productsComesFromCurrentQuestion.length==0)
			productsComesFromCurrentQuestion = EMPTY_INTERSECTION_ARRAY; //No-Matching

		return productsComesFromCurrentQuestion;
	};
};

var STATUS_INITIAL = 1;
var STATUS_USELESS = 2;
var STATUS_TRIVIAL = 3;
var STATUS_CAUSE_EMPTY = 4;

function Criteria (id, qid, title, products) 
{
	this.id  = id;
    this.questionId = qid;
    this.title = title;
	this.products = products.split(';');
	this.status = STATUS_INITIAL;
	this.lastState = false;	// Checked or not by user.
	this.htmlObject = $(id);
	
    this.getHTMLObject = function() {
    	return this.htmlObject;
    };
    this.isTrivialCandidate = function(currentProducts) {//All Criteria Products is a subset of currentProducts.
  		var intersection = this.products.intersection(currentProducts);
		if(intersection.length >0 && this.products.length == intersection.length)
			return true;
		
  		return false;
  	};
  	this.isUselessCandidate = function(currentProducts) {//Criteria does not have a subset of currentProducts.
  		var intersection = this.products.intersection(currentProducts);
		if( intersection.length == 0 )
			return true;
		return false;
  	};
  	this.setDisabled = function(disable) {
  		
  		//Disable Checkbox
  		this.getHTMLObject().disabled = disable; 
  		
  		//Disable Label
  		var labelObj = $(this.id + '-label');
  		if(labelObj!=null) {
  			labelObj.className = disable ? 'disabled' : '';
  		}
   	};

  	this.changeMode = function(disabled, checked, status) {
  		
  		this.setDisabled(disabled);
  		
  		this.status = status;
  		var htmlObj = this.getHTMLObject(); 
  		if(htmlObj.type == 'checkbox') {
  			
  			htmlObj.checked = checked;
  			
  			//Enable label if check box is disabled and checked
  			if (disabled == true && checked == true) {
	  			var labelObj = $(this.id + '-label');
	  	  		if(labelObj!=null) {
	  	  			labelObj.className = '';
	  	  		}
  			}
  			
  			appendToolTipPopup(this.id,disabled,checked);
  			
  	  		var fakeCheckBox = $(this.id+'-fakeCheckBox');
  			if(fakeCheckBox) {
  				fakeCheckBox.changeCheckedState(); 
  				fakeCheckBox.changeDisabledState();
  			}
  		}
  		else if(htmlObj.type == 'radio' && (checked == 'true' || checked == true) && checked != 'false') {
  			htmlObj.checked = checked;
  		}
  	};
};


function ProductBox (id, infoBoxHTML, controlsBoxTopHTML, controlsBoxMiddleHTML, controlsBoxBottomHTML) 
{
    this.id  = id;
    this.infoBoxHTML = infoBoxHTML;
    this.controlsBoxTopHTML = controlsBoxTopHTML;
    this.controlsBoxMiddleHTML = controlsBoxMiddleHTML;
    this.controlsBoxBottomHTML = controlsBoxBottomHTML;
    
    this.sortSerie		= $(id+'-serie')!=null	? $(id+'-serie').readAttribute('rel') : null;
    this.sortSerieText	= $(id+'-serie')!=null	? $(id+'-serie').innerHTML : null;
    this.sortScreen		= $(id+'-screen')!=null ? $(id+'-screen').readAttribute('rel') : null;
    this.sortPrice		= $(id+'-price')!=null	? $(id+'-price').readAttribute('rel') : null;
    this.sortDate		= $(id+'-date')!=null	? $(id+'-date').readAttribute('rel') : null;
    this.sortCapacity	= $(id+'-capacity')!=null ? $(id+'-capacity').readAttribute('rel') : null;
    this.sortName 		= $(id+'-name')!=null	? $(id+'-name').readAttribute('rel') : null;
    this.sortMedia		= $(id+'-media')!=null	? $(id+'-media').readAttribute('rel') : null;
    this.sortMegapixel	= $(id+'-megapixel')!=null	? $(id+'-megapixel').readAttribute('rel') : null;
    this.sortWeight		= $(id+'-weight')!=null	? $(id+'-weight').readAttribute('rel') : null;
    this.sortAudience	= $(id+'-audience')!=null ? $(id+'-audience').readAttribute('rel') : null;
    this.sortMinFocalLength	= $(id+'-focalLength')!=null ? $(id+'-focalLength').readAttribute('relMin') : null;
    this.sortMaxFocalLength	= $(id+'-focalLength')!=null ? $(id+'-focalLength').readAttribute('relMax') : null;
};
	
var pstCookieManager = null;

Event.observe(window, 'load', function() {
	productSelector.initialize("TV Wizard", "TV Wizard Introduction");
	productSelector.productGroups = productGroups;		// productGroups variable comes from one of jsps.
	pstCookieManager = new PSTCookieManager(new PSTCookie("Product-Selector-"+productSelector.selectorType,"",30), $('saveSettingsAnchor'));
	
	//if (pstCookieManager.isNewVisitor()){
		//showPSTIntroductionMessage();
	//}
	//else{
		pstCookieManager.loadFilter("Product-Selector-"+productSelector.selectorType);
		if(!pstCookieManager.isFilterInInitialState()){
			loadSliders();
			productSelector.click();
			
			// Change the properties of previously selected and saved grouped products.			
			var SELECTED_COLOURS = 'selectedColours';
			if($(SELECTED_COLOURS) && $(SELECTED_COLOURS).value) {
				var selectedColours = $(SELECTED_COLOURS).value.split(',');
				
				reClickSelectedColoursFromPalette(selectedColours);
			}
		}
  		//psCompareButton.showAndHideScroller(this);
	//}
	

	
});

function restoreSelectedQuestionType(radioObj, searchKeyForHiding)
{
	
	var id_of_question = radioObj.getAttribute('rel');
	var sourceOfNewTitle = radioObj.getAttribute('radioButtonIndex');
	
	var question = productSelector.getQuestion(id_of_question);
	var criteriasOfQuestion = question.criterias;
	
	var counterForDivClearer = 0;
	for(var i=0; i < criteriasOfQuestion.length; i++)
	{
		var criteria = criteriasOfQuestion[i].htmlObject;
		var label = $(criteria.id+'-label');
		label.innerHTML = criteria.getAttribute(sourceOfNewTitle);
		
		// Hide the checkbox, if it is signed as hidden for this radioButton.
		var matchResult = criteria.getAttribute('hiddenForRadioButton').match(searchKeyForHiding);
		if(matchResult != '' && matchResult != null)
		{
			criteria.parentNode.style.display = 'none';
		}
		else
		{
			criteria.parentNode.style.display = 'block';
			counterForDivClearer++;
		}
		
		var divClearerHtmlObj = $(criteria.id+'-clearer'+i);
		if(counterForDivClearer > 0 && counterForDivClearer % 2 == 0)
		{
			divClearerHtmlObj.style.display = 'block';
			counterForDivClearer = 0;
		}
		else
		{
			divClearerHtmlObj.style.display = 'none';
		}
	}
}


function changeSliderLabels(searchKeyForHiding,productSkuGroupId)
{
	activeSliderLabelsMap[productSkuGroupId] = sliderLabelsMap[productSkuGroupId][searchKeyForHiding];
	loadSliders();
}


function setAllCheckboxSelection(elementName, checked) {
	
	var checkBoxes = getCheckBoxesWithQuestionId(elementName);

	var baseCheckbox;
	for(var i=0; i<checkBoxes.length; i++) {
		var checkBox = checkBoxes[i];
		if(checkBox.type == 'checkbox' && checkBox.disabled == false) {
			checkBox.checked = checked;
			
			if (elementName == "Qcolor-criteria") {
				changeProductPropertiesByColor(checkBox);
			}
			
			var fakeCheckBox = $(checkBox.id+'-fakeCheckBox');
			if(fakeCheckBox) {
				fakeCheckBox.changeDisabledState();
				fakeCheckBox.changeCheckedState();
			}
			baseCheckbox = checkBox;
		}
	}

	if(baseCheckbox) {
		baseCheckbox.checked = !checked;
		baseCheckbox.click();
	}
	
	refreshSelectAllSelectNoneLinks();
}

function getCheckBoxesWithQuestionId(elementName){
	return document.getElementsByName(elementName);
}

function refreshSelectAllSelectNoneLinks() {
	disableSelectAllSelectNoneLinks('selectAll', false);
	disableSelectAllSelectNoneLinks('selectNone', true);	
}

function disableSelectAllSelectNoneLinks(elementName, constraint) {
	
	if(document.getElementsByName) {
		var selectAllLinks = document.getElementsByName(elementName);
		
		for(var i=0; i<selectAllLinks.length; i++) {
			var link = selectAllLinks[i];
			var linkText = $(link.name + 'Text-' + link.rel);
			Element.extend(link);	// link should be prototype's Element, so that it can use its methods. 
			
			// Set link disabled initially.
			link.hide();
			linkText.show();
			
			var checkBoxes = getCheckBoxesWithQuestionId(link.rel);
			for(var j=0; j<checkBoxes.length; j++) {
				var checkBox = checkBoxes[j];
				if(checkBox.disabled == false && checkBox.checked == constraint) {
					// Set it enabled if any constraint exists.
					link.show();
					linkText.hide();
				}
			}
		}
	}
}

//This function changes basicly the thumbnail image, links,
//etc. of the selected products.
function changeProductPropertiesByColor(checkBox) {
	
	if($('selectedColours') != null){
		var selectedColours = new Array();
		if($('selectedColours').value) {
			selectedColours = $('selectedColours').value.split(',');
		}
		
		if(checkBox.checked) {
			selectedColours[selectedColours.length] = checkBox.id;
		}
		else {
			var newSelectedColours = new Array();
			for(i = 0; i < selectedColours.length; i++) {
				if(checkBox.id != selectedColours[i]) {
					newSelectedColours.push(selectedColours[i]);
				}
			}
			selectedColours = newSelectedColours;
		}
		
		reClickSelectedColoursFromPalette(selectedColours);
		$('selectedColours').value = selectedColours.toString();
	}
}

function reClickSelectedColoursFromPalette(selectedColours) {
	
	if(selectedColours.length != 0) {
		for(var i = 0; i < selectedColours.length; i++) {
			var selectedColourCheckBox = $(selectedColours[i]);
			var productSkuIds = selectedColourCheckBox.value.split(';');
			productSkuIds = productSkuIds.intersection(productSelector.currentProducts);
			
			var productSkuLinkId;
			for(j = 0; j < productSkuIds.length; j++) {
				productSkuLinkId = 'colorPaletteLinkFor'+productSkuIds[j];
				if($(productSkuLinkId)) {
					$(productSkuLinkId).onclick();
				}
			}
		}
	}
	// Click the first colour in the palette, if there is no
	// selected colour from the filter.
	else {
		var colourPalettes = $$('div.prod-color');
		for(var i = 0; i < colourPalettes.length; i++) {
			var firstColour = colourPalettes[i].select('a')[0];
			if(firstColour) {
				firstColour.onclick();
			}
		}
	}
}

function appendToolTipPopup(id,disabled,checked) {
	
	//append or remove tooltip
	var divObj = jQuery('.' + id + '-div');
	var tooltipSpanObj = jQuery('.' + id + '-span');
	var tooltipSpanDoubleObj = jQuery('.' + id + '-span-double');
	var tooltipDivObj = jQuery('.' + id + '-div .cntSelectorFilterToolTip');
	
	var markup = "<div class=\"cntSelectorFilterToolTip\">" +
				"<div class=\"cntSelectorFilterToolTipContent\">" +
				"<div class=\"cntSelectorFilterToolTipInner\">" + translations.tooltipText + "</div> " +
				"</div><a class=\"cntSelectorFilterToolTipCloseBtn\" href=\"javascript:;\" onclick=\"jQuery('." + id + "-div .cntSelectorFilterToolTip').hide();\"></a> " +
				"</div>";
	
	if(divObj.length > 0 && disabled == true && checked == true) {
		divObj.append(markup);
		
		if (tooltipSpanObj.length > 0) {
			if (navigator.appVersion.indexOf('MSIE 6') > 0)
				tooltipSpanObj.css({'left':'-20px'});
			else
				tooltipSpanObj.css({'left':'0px'});
		}
		
		if (tooltipSpanDoubleObj.length > 0) {
			tooltipSpanDoubleObj.css({'left':'0px'});
		}
	
	}  	  		
	
	if(divObj.length > 0 && disabled == false && tooltipDivObj.length > 0) {
		tooltipDivObj.remove();
		  	  			
		if (tooltipSpanObj.length > 0) {
			if (navigator.appVersion.indexOf('MSIE 6') > 0)
				tooltipSpanObj.css({'left':'0px'});
			else
				tooltipSpanObj.css({'left':'20px'});
		}
		
		if (tooltipSpanDoubleObj.length > 0) {
			tooltipSpanDoubleObj.css({'left':'23px'});
		}
	}
}
