var searchText = "";
var lastMouseOverElement = null;
var numberOfSuggestions = 0;

function getLastMouseOverElement(){
	return lastMouseOverElement;
}

function setLastMouseOverElement(el){
	lastMouseOverElement = el;
}


function isLastMouseOverElement(el){
	if(el == null){
		return false;
	}
	if(lastMouseOverElement == null){
		return false;
	}
	return lastMouseOverElement === el;
}

var MyUtils = {onfocus: function(event){this.focused=true;},
		onblur: function(event){
					this.focused=false;
		},
		hasFocus: function(){
			        return this.focused;
		},
		focused: false 
};

Element.addMethods(MyUtils);

  
function encode(string) {
	  string = string.replace(/\r\n/g,"\n");
	  var utftext = "";
	 
	  for (var n = 0; n < string.length; n++) {
	 
	   var c = string.charCodeAt(n);
	 
	   if (c < 128) {
	    utftext += String.fromCharCode(c);
	   }
	   else if((c > 127) && (c < 2048)) {
	    utftext += String.fromCharCode((c >> 6) | 192);
	    utftext += String.fromCharCode((c & 63) | 128);
	   }
	   else {
	    utftext += String.fromCharCode((c >> 12) | 224);
	    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
	    utftext += String.fromCharCode((c & 63) | 128);
	   }
	 
	  }
	 
	  return utftext;
	 }
	 
	 function decode(utftext) {
	  var string = "";
	  var i = 0;
	  var c = c1 = c2 = 0;
	 
	  while ( i < utftext.length ) {
	 
	   c = utftext.charCodeAt(i);
	 
	   if (c < 128) {
	    string += String.fromCharCode(c);
	    i++;
	   }
	   else if((c > 191) && (c < 224)) {
	    c2 = utftext.charCodeAt(i+1);
	    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
	    i += 2;
	   }
	   else {
	    c2 = utftext.charCodeAt(i+1);
	    c3 = utftext.charCodeAt(i+2);
	    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
	    i += 3;
	   }
	 
	  }
	 
	  return string;
	 }
	 
	 
function hideSuggestionsBox(boxId, inputId, defaultText, debug){
	 if (boxId == null || boxId == ""){
		 if(debug){
			  alert("boxid is empty");
		  }
	  return;
	 }
	 var box = $(boxId);
	 
	 if (box == null){
		 if(debug){
			  alert("box is empty");
		  }
	  return;
	 }
	 Element.extend(box);
	 if (box.hasFocus()){
		 return;
	 }
	 
	 box.hide();
	 
	 if (inputId == null || inputId == ""){
		 if(debug){
			  alert("inputId is empty");
		  }
	  return;
	 }
	 var input = $(inputId);
	 
	 if (input == null){
		 if(debug){
			  alert("input is empty");
		  }
	  return;
	 }
	 
	 if (input.value == null || input.value == ""){
		 input.value = defaultText;
	 }
	 
	
}
	 
function buildEncodedURL (formId){
		 var form = $(formId);
		 var url = form.action;
		 var queryString = "";
		 var elements = form.getElements();
		 for (var i = 0 ; i < elements.length; i++){
		  var el = elements[i];
		  if (!el){
		   continue;
		  }
		  if (el.type == "select-one"){
		   queryString = queryString + el.name + "=" + encodeURI(el.options[el.selectedIndex].value) + "&";
		  }
		  else{
		   if (el.type == "hidden"){
		    queryString = queryString + el.name + "=" + encodeURI(el.value) + "&";
		   }
		   else if (el.type == "text"){
		    queryString = queryString + el.name + "=" + encodeURI(el.value) + "&";
		   }
		   else if (el.type == "password"){
		    queryString = queryString + el.name + "=" + encodeURI(el.value) + "&";
		   }
		  }
		 }
		 
		 if (!queryString.empty() && queryString.endsWith("&")){
			 	queryString = queryString.substring(0,queryString.length-1);
		 }
		 if (!queryString.empty()){
		  url = url + "?" + queryString;
		 }
		 alert(url);
		 return url;
		}

function setInputValueAndSubmit(formId, inputId, divId, debug){
	 if (formId == null || formId == ""){
	  if(debug){
		  alert("formid is empty");
	  }
	  return;
	 }
	 if (inputId == null || inputId == ""){
		 if(debug){
			  alert("inputid is empty");
		  }
	  return;
	 }
	 
	 
	 var input = $(inputId);
	 var form = $(formId);
	 //input.value = value;
	 input.value = getCellValueByRow(getRowByIndex(divId, getSelectedSuggestionIndex(divId)));
	 
	 
	 form.submit();
	}

	function autoComplete(event, formId, inputId, boxId, url1, showProducts, debug){
	 if (formId == null || formId == ""){
		 if(debug){
			  alert("formid is empty");
		  }
	  return;
	 }
	 if (inputId == null || inputId == ""){
		 if(debug){
			  alert("inputid is empty");
		  }
	  return;
	 }

	 initSearchText(inputId);
	 
	 if (boxId == null || boxId == ""){
		 if(debug){
			  alert("boxid is empty");
		  }
	  return;
	 }
	 
	 $(boxId).hide();
	 
	 if (url1 == null || url1 == ""){
		 if(debug){
			  alert("url1 is empty");
		  }
	  return;
	 }
	 
	 var inputSearch = $(inputId);
	 
	 var handleAfterRequest = false;
	 
	 if(isArrowDown(event) && !isDivEmpty(boxId)){
		 if (isDivEmpty(boxId)){
			 handleAfterRequest = true;
		 }
		 else{
			 $(boxId).show();
			 handleArrowDown(boxId, inputId);
			 return;
		 }
	 }
	 
	 if(isArrowUp(event) && !isDivEmpty(boxId)){
		 if (isDivEmpty(boxId)){
			 handleAfterRequest = true;
		 }
		 else{
			 $(boxId).show();
			 handleArrowUp(boxId, inputId);
			 return;
		 }
	 }
	 
	 
	 var newURL1 = url1 + inputSearch.value;
	 var browserName = navigator.appName;
	
	 if(browserName == "Microsoft Internet Explorer"){
		 newURL1 = url1 + encode(inputSearch.value);
	 }
	 
	 new Ajax.Request(newURL1, {
		   	onSuccess: function (transport){
			   fillSuggestionBox(formId, inputId, boxId, transport.responseText.evalJSON(), true,  true);
		   	},
		   	onFailure: function (transport){
		   	 alert("failure");
		   	}
		   }); 
	 	
	 
	   
	 $(boxId).show();
	}
	
	function fillSuggestionBox(formId, inputId, divId, suggestions, showProducts, debug){
		numberOfSuggestions=0;
		if (formId == null || formId == ""){
			 if(debug){
				  alert("formid is empty");
			  }
		  return;
		 }
		 if (inputId == null || inputId == ""){
			 if(debug){
				  alert("inputid is empty");
			  }
		  return;
		 }
		 if (divId == null || divId == ""){
			 if(debug){
				  alert("divid is empty");
			  }
		  return;
		 }
		 
		 var input = $(inputId);
		
		 var template = new Template("<tr onmouseover=\" if (isLastMouseOverElement(this)){return false;} activateElement(\'\#{divId}\', this, \'\#{inputId}\', false); setLastMouseOverElement(this);\" onmouseout=\" deactivateElement(this,\'\#{inputId}\', false);setLastMouseOverElement(null);  \" onmousedown=\" setInputValueAndSubmit(\'\#{formId}\',\'\#{inputId}\','\#{divId}\',\#{debug});\"><td class=\"suggestionCol\" > #{suggestionText}</td></tr>");
		 var template2 = new Template("<tr style=\"background-color:white;\" onmouseover=\" if (isLastMouseOverElement(this)){return false;} activateElement(\'\#{divId}\', this, \'\#{inputId}\', false); setLastMouseOverElement(this);\" onmouseout=\" deactivateElement(this,\'\#{inputId}\', false);setLastMouseOverElement(null);  \" onmousedown=\"window.location='#{suggestionLink}'\"><td class=\"suggestionCol\" ><div style=\"float:left;\"><a href=\" #{suggestionLink}\"><img style=\"width:50px; height:54px;\" src=\" #{suggestionPicture}\"/></div></a><a href=\" #{suggestionLink}\"><div style=\"float:left;width:327px;color:#4F4F4F;\"><br/>#{suggestionText}</div></a></td></tr>");

		 var div = $(divId);
		 var html = "";
		 var i = 0;
		 if(showProducts){
		 if(suggestions.suggestedQueries.size() > 0 || suggestions.suggestedProducts.size() > 0){
			 html=html+"<table class=\"suggestionTable\">";
			 if(suggestions.suggestedQueries.size() > 0){
				 html=html + "<th class=\"header_static\"><br/>Häufige Suchanfragen</th>";
				 suggestions.suggestedQueries.each(function(suggestedQuery) {
					 var show = {formId: formId, divId: divId, inputId: inputId, debug: debug, suggestionText: suggestedQuery };
					 html = html + template.evaluate(show);
					 numberOfSuggestions++;
				 });
			 } 
			 if(suggestions.suggestedProducts.size() > 0){
				 html = html + "<tr><td class=\"header_static\"><br/>Passende Produkte zu Ihrer Suchanfrage</td></tr>";
				 suggestions.suggestedProducts.each(function(suggestedProduct){
					 var show2 = {formId: formId, divId: divId, inputId: inputId, debug: debug, suggestionPicture: suggestedProduct.pictureURL, suggestionText: suggestedProduct.name, suggestionLink: suggestedProduct.productURL };
					  html = html + template2.evaluate(show2); 
				 });
			 }
			 html=html+"</table>";
		 }
		 }
		 else{
			 if(suggestions.suggestedQueries.size() > 0){
				 html=html+"<table class=\"suggestionTable\">";
				 if(suggestedQueries.suggestedQueries.size() > 0){
					 
					 suggestions.suggestedQueries.each(function(suggestedQuery) {
						 var show = {formId: formId, divId: divId, inputId: inputId, debug: debug, suggestionText: suggestedQuery };
						 html = html + template.evaluate(show);
						 numberOfSuggestions++;
					 });
					 html=html+"</table>";
				 }
			 }
		 }
		 
		 div.update(html);
		 div.show();
	
	}
	function fillSuggestionBox_small(formId, inputId, divId, suggestedQueries, debug){
		if (formId == null || formId == ""){
			 if(debug){
				  alert("formid is empty");
			  }
		  return;
		 }
		 if (inputId == null || inputId == ""){
			 if(debug){
				  alert("inputid is empty");
			  }
		  return;
		 }
		 if (divId == null || divId == ""){
			 if(debug){
				  alert("divid is empty");
			  }
		  return;
		 }
		 
		 var input = $(inputId);
		 if (input.value == null || input.value == ""){
			 if(debug){
				  alert("value is empty fill");
			  }
		  return;
		 }
		 var template = new Template("<tr onmouseover=\" if (isLastMouseOverElement(this)){return false;} activateElement(\'\#{divId}\', this, \'\#{inputId}\', false); setLastMouseOverElement(this);\" onmouseout=\" deactivateElement(this,\'\#{inputId}\', false);setLastMouseOverElement(null);  \" onmousedown=\"setInputValueAndSubmit(\'\#{formId}\',\'\#{inputId}\',\'\#{suggestionText}\',\#{debug});\"><td class=\"suggestionCol\" > #{suggestionText}</td></tr>");
		 var div = $(divId);
		 var html = "";
		 var i = 0;
		 suggestedQueries.suggestedQueries.each(function(suggestedQuery) {
		  if (i == 0){
		   html = html + "<table class=\"suggestionTable2\">";
		  }
		  i++;
		  var show = {formId: formId, inputId: inputId, debug: debug, suggestionText: suggestedQuery };
		  html = html + template.evaluate(show);
		 });
		 if (i != 0){
		  html = html + "</table>";
		 }
		 div.update(html);
		 div.show();
	}
	
	
function activateElementIntern(el, inputId, changeInputValue){
		el.addClassName("active");
		if (changeInputValue && changeInputValue == true){
			var cellValue = getCellValueByRow(el);
			if (cellValue == null || cellValue == ""){
				cellValue = searchText;
			}
			$(inputId).value = cellValue;
		}
		$(inputId).focus();
		
		return el;
}

function deactivateElementIntern(el, inputId, changeInputValue){
	if (changeInputValue && changeInputValue == true){
			$(inputId).value = searchText;
	}
	el.removeClassName("active");
	return el;
}

function getSuggestionsCount(divId){
	var div = $(divId);
	var tables = div.select("table");
	if(tables == null || tables.length == 0){
		return 0;
	}
	var table = tables[0];
	var rows = table.select("tr");
	if(rows == null){
		return 0;
	}
	
	return rows.length;
}

function getSelectedSuggestionIndex(divId){
	var div = $(divId);
	if(div == null){
		return -1;
	}
	var tables = div.select("table");
	if(tables == null || tables.length == 0){
		return -1;
	}
	var table = tables[0];
	var rows = table.select("tr");
	if(rows == null || rows.length == 0){
		return -1;
	}
	for(var i=0;i<rows.length;i++){
		if(rows[i].hasClassName('active')){
			return i;
		}
	}
	return -1;	
}

function getCellValueByRow(row){
	if(row == null){
		return "";
	}
	var cells = row.select("td");
	if(cells == null || cells.length == 0){
		return "";
	}
	
	return cells[0].innerHTML;
}
	
function getRowByIndex(divId, index){
	var div = $(divId);
	var tables = div.select("table");
	if(tables == null || tables.length == 0){
		return null;
	}
	var table = tables[0];
	var rows = table.select("tr");
	if(rows == null || rows.length == 0){
		return null;
	}
	if(rows.length <= index){
		return null;
	}
	var currentRow = rows[index];
	return currentRow;
}


function isDivEmpty(divId){
	return getSuggestionsCount(divId) < 1;
}

function isInputValueEmpty(inputId){
	var input = $(inputId);
	return input.value == "" || input.value == null;
}

function isEnter(event){
	return event.keyCode == 13;
}

function isArrowUp(event){
	return event.keyCode == 38;
}

function isArrowDown(event){
	return event.keyCode == 40;
}

function handleArrowDown(divId, inputId){
	if(numberOfSuggestions > 0){
	var index = getSelectedSuggestionIndex(divId);
	if(index == -1){
		activateElement(divId,getRowByIndex(divId,1), inputId, true);
	}
	else{
		if(index == numberOfSuggestions){
			activateElement(divId, getRowByIndex(divId,1), inputId, true);
		}
		else{
			if(index>numberOfSuggestions){
				activateElement(divId,getRowByIndex(divId, 1), inputId, true);
			}
			else{
				activateElement(divId,getRowByIndex(divId,index + 1), inputId, true);
				
			}
			
		}
	}
}
}

function handleArrowUp(divId, inputId){
	if(numberOfSuggestions > 0){
	var index = getSelectedSuggestionIndex(divId);
	if(index == -1){
		activateElement(divId,getRowByIndex(divId,numberOfSuggestions), inputId, true);
	}
	else{
		if(index == 1){
			activateElement(divId,getRowByIndex(divId, numberOfSuggestions), inputId, true);
		}
		else{
			if(index > numberOfSuggestions){
				activateElement(divId,getRowByIndex(divId, numberOfSuggestions), inputId, true);
			}
			else{
				activateElement(divId,getRowByIndex(divId,index - 1), inputId, true);
			}
		}
	}
}
}
function activateElement(divId, el, inputId, changeInputValue){
	var index = getSelectedSuggestionIndex(divId);
	
	if (index == -1){
		// do nothing
	}
	else{
		
		var selectedEl = getRowByIndex(divId,index);
		selectedEl = deactivateElementIntern(selectedEl, inputId, changeInputValue);
	}
	return activateElementIntern(el, inputId, changeInputValue);
}


function deactivateElement(el, inputId, changeInputValue){
	return deactivateElementIntern(el, inputId, changeInputValue);
}

function initSearchText(inputId){
	searchText = $(inputId).value;
}

function addMultipleProductsToCart(productsList){
	var requestURL="ajax_request/cartController/addToCartMultipleProductsAction.jsf?productList="+productsList;
	new Ajax.Request(requestURL,{
		onSuccess:function(transport){
			if(transport.responseText.isJSON()){
				processAdd2CartResponse(transport.responseText.evalJSON());
			}
		},
		onLoading:function(transport){
			$('add-to-cart-spinner').show();
		},
		onComplete:function(transport){
			$('add-to-cart-spinner').hide();
		}
	});
	
	return true;
}

function displayRatingError(canRate) {
	if(!canRate) {
		url = document.location.href;
		if(url.endsWith('#rezensionen')) {
			if(url.indexOf("allreviews=true") != -1) {
				url = (url.match(/.*\allreviews=true/));
			}
			else {
				url = (url.match(/.*\?/));	
			}
		}
		new Ajax.Request("ajax_request/productDetailsController/promptErrorMessage.jsf?", {
			onSuccess:function(transport) {
			}
		});
		window.location.href = url;
	}
}

function addCustomerFeedback(feedback,reviewPk, numberOfFeedbacks, canRate) {
	if(feedback == null || reviewPk == null || !canRate){
		return;
	}
	var requestUrl="ajax_request/productDetailsController/saveCustomerFeedback.jsf?feedback="
	if(feedback){
		requestUrl=requestUrl+"0";
	}	
	else{
		requestUrl=requestUrl+"1";
	}
	requestUrl=requestUrl+"&reviewPk="+reviewPk;
		
	new Ajax.Request(requestUrl,{
		onSuccess:function(transport){
			$("feedback_"+reviewPk).hide();
			if(feedback){
				$("feedbackmess_"+reviewPk).update(transport.responseText);
				$("feedbackmess_"+reviewPk).removeClassName("nonvisible");
			}
		},
		onComplete:function(transport){
			$("feedback_"+reviewPk).update("<br/><p>Vielen Dank für Ihr Feedback!</p>");
			$("feedback_"+reviewPk).show();
		}
	});
}

function initGenericIFramePopup(containerId, iframeId, width, height, marginTop) {
	if (document.getElementById(containerId) == null) {
		var div = document.createElement('div');
		div.id = containerId;
		div.style.display = 'none';
		div.style.backgroundColor = '#FFFFFF';
		div.style.border = 'solid 1px black';
		div.style.width = width + 'px';
		div.style.position = 'absolute';
		div.style.left = (document.documentElement.offsetWidth/2 - 250) + 'px';
		div.style.top = marginTop + 'px';
		div.style.zIndex = 9999;
		div.style.padding = '10px';
		
		var iframe = document.createElement('iframe');
		iframe.id = iframeId;
		iframe.frameBorder = 0;
		iframe.style.border = 0;
		iframe.style.width = div.style.width;
		iframe.style.height = height + 'px';
		iframe.style.overflowX = 'hidden';
		div.appendChild(iframe);
		
		var button = document.createElement('a');
		button.href = '#';
		button.innerHTML = 'Schlie&szlig;en';
		button.onclick = function() {
			document.getElementById(containerId).style.display = 'none';
			return false;
		};
		
		div.appendChild(button);
		document.body.insertBefore(div,null);
	}
};

function showGenericIFramePopup(containerId, url, width, height, marginTop) {
	var iframeId = containerId + '-iframe';
	
	initGenericIFramePopup(containerId, iframeId, width, height, marginTop);
	
	var scroll = self.pageYOffset||document.body.scrollTop||document.documentElement.scrollTop;
	var top = scroll + marginTop;

	var iframe = document.getElementById(iframeId);
	iframe.src = url;
	
	var container = document.getElementById(containerId);
	container.style.display = 'block';
	container.style.top = top + 'px';
};


