/**
 * Helper Class for SmartFinder
 * 
 * @author OW
 * @since 05-2008
 */






/**
 * dom tree ids & references
 */

var FINDER_QUESTION_PRE = "question_";
var FINDER_QUESTION_ID = "questionInfotext";

var FINDER_INFO;
var QUESTION_INFO;



/**
 * settings
 * 
 * timer - information disappears after x milliseconds
 * info_display - ''|'mouseFollow'
 */
var timer = 200;
var compareLimit = 0;

//INFO_DISPLAY = "mouseFollow";

if(!INFO_DISPLAY){
	var INFO_DISPLAY = '';
}

var FinderManager = Class.create({
	
	initialize:function() {
		this.timer = 0; // reference to disappear timer
		this.currentNumber=0; // current shown information
		this.numberCompareProducts=0; // number of products in compare box
		this.currentQuestionId=0;
	
		// handles liveupdate events to reset finder
		if(!window['compareType'] || compareType!="continuous"){	
			document.observe("sis:updateQuestion", function() {
				FM.resetProductCompare();
			});
		}else{
			document.observe("sis:resultUpdate", function() {
				FM.updateProductsForCompare();
			}); 
		}
		
		document.observe("sis:resetAllQuestions", function() {
			FM.resetProductCompare();
		});
		
		

		
	},
	
	/* -------------------- mouse events --------------------------- */
	

	
	
	/**
	* Function to handle mouseOver-events on products in finder
	*
	* @param {Integer} number productNumber
	* @param {reference} t 
	* @param {event} ev 
	*/
	finderProductMouseOver2: function (number,t,ev, timeDelay){
		
		if(navigator.userAgent && $('intermediateresults_result')!= null)
			$('intermediateresults_result').style.opacity=1;
		
		//$("hiddeninfo"+number).style.display="block";
		$("product"+number).addClassName('hover'); // add hover class

		
		
		if(typeof timeDelay == 'undefined' || timeDelay <= 0){ // hide info immediately
			var timer = $("product-wrapper-"+number).retrieve("timer");
			if(timer){
				window.clearTimeout(timer);
			}
			$("hiddeninfo"+number).style.display="block";
			
		}else{
		
			var timer = $("product-wrapper-"+number).retrieve("timer");
			if(timer){
				window.clearTimeout(timer);
			}
			timer = window.setTimeout('$("hiddeninfo'+number+'").style.display="block";',timeDelay);	
			$("product-wrapper-"+number).store("timer",timer);
		}
		
		
	},	
	
	/**
	* Function to handle mouseOut-events on products in finder
	*
	* @param {Integer} number productNumber
	*/
	finderProductMouseOut2: function(number, timeDelay) {
		
		$("product"+number).removeClassName('hover'); // remove hover class
		
		if(typeof timeDelay == 'undefined' || timeDelay <= 0){ // hide info immediately
			var timer = $("product-wrapper-"+number).retrieve("timer");
			if(timer){
				window.clearTimeout(timer);
			}
			$("hiddeninfo"+number).style.display="none";
		}else{
			var timer = $("product-wrapper-"+number).retrieve("timer");
			if(timer){
				window.clearTimeout(timer);
			}
			timer = window.setTimeout('$("hiddeninfo'+number+'").style.display="none";',timeDelay);	
			$("product-wrapper-"+number).store("timer",timer);
		}
		
	},

	
	/**
	 * Source - DisplayQuestions
	 */
	finderQuestionMouseOver: function (qid) {

		var QUESTION_INFO_TEXT = $$("#questionInfotext")[0];
		
		this.currentQuestionId=qid; // save new question number
		
		$(FINDER_QUESTION_PRE+qid).addClassName('hover'); // add hover class
		
		if($$("div#" + FINDER_QUESTION_PRE+qid+" .infotext")[0]) {
			if(this.currentQuestionId == qid) {
				QUESTION_INFO.style.display="block";
			} else {
				QUESTION_INFO.style.display="none";
			}
			var d = $$("div#" + FINDER_QUESTION_PRE+qid+" .infotext")[0].innerHTML;
			$(FINDER_QUESTION_PRE+qid).addClassName('infotext_hover');
			this.questionInfoPosition(qid);
			QUESTION_INFO.style.display='block';
			
			var questionHeight = $(FINDER_QUESTION_PRE+qid).getHeight();
			
			$$("#questionInfotext")[0].innerHTML = "<div class='infoBorderOverlay'></div><div class='questionInfotextContent'>" + $$("#" + FINDER_QUESTION_PRE+qid+" .infotext")[0].innerHTML + "</div><div id='questionInfotextBottom'></div>";
			$$("#questionInfotext .questionInfotextContent")[0].style.minHeight=questionHeight + 'px'; // infobox should have at least the same height as the question 
			$$("#questionInfotext .infoBorderOverlay")[0].style.height=questionHeight-2 + 'px'; // box height for the border-overlay (shouldn�t overlay top and bottom border ==> -2px)
		}
	},
	
	/**
	* Function to handle mouseOut-events on questions in finder
	*
	* @param {Integer} number productNumber
	*/
	finderQuestionMouseOut: function(qid) {
		QUESTION_INFO.style.display="none";
		$(FINDER_QUESTION_PRE+qid).removeClassName('hover'); // remove hover class
		$(FINDER_QUESTION_PRE+qid).removeClassName('infotext_hover');
	},
		
	/*--------------------- helper methods --------------------------------------------------*/	
	
	// Finder 2.0 question info (hover)
	questionInfoPosition:function(qid){
		
		var pos = $(FINDER_QUESTION_PRE+qid).positionedOffset();
		//if (navigator.appName=="Microsoft Internet Explorer")

		
		var width = $(FINDER_QUESTION_PRE+qid).getWidth();
			
		var posX = pos[0]+width;
				
		var posY = pos[1];	
		QUESTION_INFO.style.top= posY+"px";
		QUESTION_INFO.style.left= posX+"px";
	}, 
	
	/*----------------------- finder product compare ------------------------------------------------*/
	
	
	/**
	* Add current product info product compare
	*/	
	addToCompare:function(){
	
		this.selectFinderProduct(this.currentNumber,$("prod_"+this.currentNumber).value,true);
		$('compareButton').toggleClassName('compareButtonChecked');	
	},
	
	/**
	* Add a product into product compare
	*
	* @param {Integer} number - productNumber
	* @param {Integer} productId - id of compare to add to compare - COMING SOON
	* @param {Boolean} toogle - toogle checkbox selection
	*/
	selectFinderProduct:function(number, productId, toggle) {
			var chb = $("prod_"+number);
			var prod = $("product-wrapper-"+number);

			if(toggle)
				chb.checked=(chb.checked==true)?false:true;

			// highlight product
			if(chb.checked) 
				prod.addClassName("marked");
			 else 
				prod.removeClassName("marked");
			

			// add/remove image to compare products
			
			if(chb.checked) { // add image
				
				// create compare product
				
				// TODO Philipp XXX: fix this, rename all "findimg" from FinderResult/process in "product-image" and test
				if($("product"+number).down(".product-image") != null) {
					var productImage = $("product"+number).down(".product-image");
				}
				else {
					var productImage = $("product"+number).down(".findimg");
				}
							
				var html = "<div onclick='FM.selectFinderProduct(\""+number+"\",\""+chb.value+"\",true);' id='productCompareImage_"+productId+"' class='productCompareImage'>" +
								"<div></div>" +
								"<img src='"+productImage.src+"' />";
								
					//if(window['compareType'] && compareType=="continuous"){			
								html += "<input name='compare' value='"+chb.value+"' type='hidden'/>";
					//}
					
					html +=	"</div>";



				$('compareProducts').innerHTML += html;

				if(this.numberCompareProducts==0)
					$('compareProductsEmptyText').style.display='none';
				
				this.numberCompareProducts++;	
			} else { // remove image
				
				var productCompareImage=$("productCompareImage_"+productId);
				if(productCompareImage != null){
					$('compareProducts').removeChild(productCompareImage);
					this.numberCompareProducts--;
				}
		
			
			
				if(this.numberCompareProducts==0)
					$('compareProductsEmptyText').style.display='block';
			
			}


			if($("startCompare").hasClassName("default-button")){		
				// change button design
				if($$("#intermediateresults_result input:checked").length > 0) {
					$("startCompare").removeClassName("inactive");
				} else {
					$("startCompare").addClassName("inactive");
				}
				
			}else{
				// fade in/out compare Button
				if($$("#intermediateresults_result input:checked").length > 0) {
					backgroundFade($("startCompare"),'startCompareActive');
				} else {
					backgroundFade($("startCompare"),'startCompareInactive');
				}
			}
			

			// if comparelimit is set in the jsp, checkboxes will be disabled 
			if(compareLimit != 0) {
				this.setChecks(compareLimit);
			}
			
			document.fire("sis:compareBoxUpdate");
		},
		
		/** 
		 * disables checkboxes when comparelimit is exceeded and enables again if there are less than the comparelimit
		 * @param {Integer} maxChecks - limit of products to compare
		 */		
		setChecks:function(maxChecks) {

			  var checkCount = 0;

			  
			  if(document.consresult){
				  // Determine the number of checked boxes
				  for (var i=0; i<document.consresult.compare.length; i++) {
				    if (document.consresult.compare[i].checked) {
				      checkCount++;
				    }
				  }
	
				  // Enable/disable unchecked boxes
				  for (var i=0; i<document.consresult.compare.length; i++) {
				    if (!document.consresult.compare[i].checked) {
				      document.consresult.compare[i].disabled = (checkCount==maxChecks);
				    }
				  }
			  }else{
				  
				 // debugger;
				  // Determine the number of checked boxes
				  $$("input[name=compare]").each(function(el){
					  if(el.checked) checkCount++;
				  });
				  
				  
				  // Enable/disable unchecked boxes
				  $$(":not(.productCompareImage) > input[name=compare]").each(function(el){
					  


					  if(!el.checked){ 
						  el.disabled = (checkCount==maxChecks);
					  }
				  });  
				  
			  }
		},
		
		
	/**
	* Reset product compare (delete all products)
	*/		
	resetProductCompare:function() {
		
		if(!$("compareProducts"))
			return;
		
		// reset compare product box, delete all product images
		$$('#compareProducts > div').each(function(el){
			$("compareProducts").removeChild(el);
		});
		
		// show empty-compare-text
		$('compareProductsEmptyText').style.display='block';
		
		
		
		if($("startCompare").hasClassName("default-button")){		
			// change button design
			$("startCompare").addClassName("inactive");
		}else{
			// compare Button reset - dirty
			$("startCompare").className="mir startCompareInactive";
			$("startCompare").innerHTML="";
		}
		
		
		
		
		
		
		
		
		
		
		
		// reset counter
		this.numberCompareProducts=0;
	},
	
	/**
	 * Enable compare checkbox for all products, which are selected in the compareBox.
	 */
	updateProductsForCompare:function(){

		var compareProductIDs = new Array();

		// get all productIDs of products in compareBox
		$$('#compareProducts input[name=compare]').each(function(el){
			compareProductIDs.push(el.value);
		});

		

		// loop all products in intermediate result
		for (var i=0; i<document.consresult.compare.length; i++) {
			
			if (compareProductIDs.indexOf(document.consresult.compare[i].value) != -1) {
				document.consresult.compare[i].checked = true;
				document.consresult.compare[i].up(".findproduct").addClassName("marked");
			}
		}
	}
});


////////////////////////////////////////////////////////////////////////////////////

var FM;

document.observe("dom:loaded",function() {
	QUESTION_INFO = $(FINDER_QUESTION_ID);
	FM = new FinderManager();

});


document.observe("dom:loaded",function() {

	$$("input").each(function(input){ // loop all inputs
		Event.observe(input, 'click', function() { // add onchange handler
			
			if(input.checked) {
				input.addClassName("checked");
			}
			else {
				input.removeClassName("checked");
			}
			
		});
	});
});






/**
 * Source - finderresult.jsp 
 * Close after click on X
 */
function hideProductInfo(id){
	$(id).style.display='none';
}


// ########### IE6 handling ####################


document.observe("sis:resultUpdate", function() {
	if(document.recalc) {document.recalc(); }
});
document.observe("sis:compareBoxUpdate", function() {
	if(document.recalc) {document.recalc(); }
});

///////////// call from liveUpdate.js ///////////////////////////////////

/**
 * TODO  Check this!!
 * Source - liveUpdate.js
 */
function showInfo(id,t){

	if(!$('info_'+id))
		return;

	if($('question_'+id).hasClassName('hiddenContent'))
		return;
	
	var pos = Element.cumulativeOffset(t);
	$('info_'+id).style.height=(($this(t)).getHeight()-2)+"px";

	$('info_'+id).style.top= pos[1]+"px";
	$('info_'+id).style.left= (pos[0] + 292)+"px";

	
	var height = $$('#question_'+id+' .title_text')[0].getHeight();
	//console.debug(height);
	$$('#question_'+id+' .finderInfo .inner')[0].style.borderTopWidth=height+"px";
	
	$('info_'+id).style.display='block';
}

/**
 * TODO  Check this!!
 * Source - liveUpdate.js
 */
function hideInfo(id){

	if(!$('info_'+id))
		return;
		
	$('info_'+id).style.display='none';			
}

