// START: variables used bellow in more than 2 places
var windowURL = window.location + "";
// END: variables used bellow in more than 2 places



// START: avoid cross domain restrictions
if(HTTP_PORT == null || HTTP_PORT == ''){
	HTTP_PORT = '8080';	
}
if(HTTPS_PORT == null || HTTP_PORT == ''){
	HTTPS_PORT = '8445';	
}
// END: avoid cross domain restrictions



// START: bookmark page
function addToFavorites() { 
	if (window.sidebar) { //Mozilla
		window.sidebar.addPanel(pageName, urlAddress,"");
	}else
		if (window.external){//IE
			window.external.AddFavorite(urlAddress,pageName);
		}
		else { //Opera
			alert(bookmarkPageKey); 
		}
}
// END: bookmark page



function AJAXPostConnection(name) {    
	this.className = 'AJAXPostConnection';
	{this.name = name;}
	this.xmlhttpPost = function (strURL, postParameters, callbackURL, functionObj, submitableForm) {
		var xmlHttpReq = false;
		var self = this;
	    // Mozilla/Safari
	    if (window.XMLHttpRequest) {
			self.xmlHttpReq = new XMLHttpRequest();
			if (self.xmlHttpReq.overrideMimeType) {
				self.xmlHttpReq.overrideMimeType('text/plain');
	            // See note below about this line
	        }
	       	// IE
		} else if (window.ActiveXObject) { // IE
			try {
				self.xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
			    	self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
			   	} catch (e) {}
			}
		}
		if (!self.xmlHttpReq) {
	    	//alert('ERROR AJAX:( Cannot create an XMLHTTP instance');
	        //return false;
	        submitableForm.submit();
	    }    
	    // this code was added to avoid cross domain restrictions 
	    if(windowURL.substring(0,5) == 'https'){
		  if(strURL.substring(0,5) != 'https'){
			  strURL = strURL.replace("http","https");
			  strURL = strURL.replace(HTTP_PORT,HTTPS_PORT);
		  }
	    }
	    // end code 
				
		self.xmlHttpReq.open('POST', strURL, true);
	    self.xmlHttpReq.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"); //add this line
  		self.xmlHttpReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded;');
  		self.xmlHttpReq.setRequestHeader("Content-length", postParameters.length);
		self.xmlHttpReq.setRequestHeader("Connection", "close");
		
		self.xmlHttpReq.onreadystatechange = function() { 
	    	_callBackFunction(self.xmlHttpReq, callbackURL, functionObj, submitableForm); 
		};
		
	    self.xmlHttpReq.send(postParameters);
    }
    _callBackFunction = function (http_request, callbackURL, functionObj, submitableForm) {
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {
				functionObj.callBackFunction(http_request.responseText, callbackURL, null, submitableForm);
			} else {
				//alert('ERROR: AJAX request status = ' + http_request.status);
			    submitableForm.submit();
	    	}
		}
	}
}

function addToCart(url, getstr, submitableForm) {
	var ajaxConnection = new AJAXPostConnection('ajaxConnection');
	var callBackFunction = new AddToCartCallback();
	//if something fails try to submit the form submitableForm
	ajaxConnection.xmlhttpPost(url, getstr, '', callBackFunction, submitableForm);
}

function AddToCartCallback() {
	this.className = "AddToCartCallback";
	this.callBackFunction = function(responseText, callbackURL, functionObj, submitableForm) {
		if(responseText != null && responseText != ''){
			var responseStringTokens = responseText.split("@");
			//responseStringTokens[0] = "ERROR";
			//responseStringTokens[1] = "ERRORea";
			
			if(responseStringTokens.length == 2){
				if(responseStringTokens[0] != null && responseStringTokens[0] == "SUCCESS"){
					if(responseStringTokens[1] != null && responseStringTokens[1] == "RENDER"){
						if(document.getElementById(minicartContainerId)){
							renderMinicart(urlRenderMinicart, submitableForm);
						}else{
							renderMicrocart(urlRenderMicrocart, submitableForm);
						}
					}
					if(responseStringTokens[1] != null && responseStringTokens[1] == "SEND_TO_CART"){
						window.location = urlShowCart;
					}
					}else{
						if(responseStringTokens[0] != null && responseStringTokens[0] == "ERROR"){
							if(document.getElementById("ajax_errors_container")){
								var errStartHtml = "<div class=\"errorBox\">"+
														"<div class=\"errorBoxLeft\"></div>"+
														"<div class=\"errorBoxRight\"></div>"+
														"<div class=\"errorBoxMiddle\">";

								var errEndHtml = 		"</div>"+
														"<div class=\"errorBoxBottom\"></div>"+
													"</div>";
								document.getElementById("ajax_errors_container").innerHTML = errStartHtml + responseStringTokens[1] + errEndHtml;
							}
							var imageName = submitableForm.name + '_img';
							if(document[imageName]){
								StopAnimation(imageName);
							}
							// added by Razvan Tomescu - 11.01.2010
							addproductAvailabe = "true";
						}
					}
				}
		}
	}
}

function renderMinicart(url, submitableForm) {
	var ajaxConnection = new AJAXPostConnection('ajaxConnection');
	var callBackFunction = new RenderMinicartCallback();
	ajaxConnection.xmlhttpPost(url, '', '', callBackFunction, submitableForm);
}

function RenderMinicartCallback() {	
	this.className = "RenderMinicartCallback";
	this.callBackFunction = function(responseText, callbackURL, functionObj, submitableForm) {
		document.getElementById(minicartContainerId).innerHTML = responseText;
		renderMicrocart(urlRenderMicrocart,submitableForm); 	
	}    
}

function renderMicrocart(url, submitableForm) {
	var ajaxConnection = new AJAXPostConnection('ajaxConnection');
	var callBackFunction = new RenderMicrocartCallback();
	ajaxConnection.xmlhttpPost(url, '', '', callBackFunction, submitableForm);
}

function RenderMicrocartCallback() {
	this.className = "RenderMicrocartCallback";
	this.callBackFunction = function(responseText, callbackURL, functionObj, submitableForm) {
		if(document.getElementById("minicartTopSeller") && urlRenderCartTopSeller != null && urlRenderCartTopSeller != 'undefined' && urlRenderCartTopSeller != ''){
			if(document.getElementById(microcartContentId)){
				document.getElementById(microcartContentId).innerHTML = responseText;
			}
			renderCartTopSeller(urlRenderCartTopSeller, submitableForm); 	
		}else{
			addproductAvailabe = "true";
			try{
				document.getElementById(microcartContentId).innerHTML = responseText;
				if(executeScollerFunctionality){
					executeScollerFunctionality();
				}
				var imageName = submitableForm.name + '_img';
				if(document[imageName]){
					StopAnimation(imageName);
				}
			}catch(err){};
		}
	}    
}

function renderCartTopSeller(url, submitableForm) {
	var ajaxConnection = new AJAXPostConnection('ajaxConnection');
	var callBackFunction = new RenderCartTopSellerCallback();
	ajaxConnection.xmlhttpPost(url, '', '', callBackFunction, submitableForm);
}

function RenderCartTopSellerCallback() {
	this.className = "RenderCartTopSellerCallback";
	this.callBackFunction = function(responseText, callbackURL, functionObj, submitableForm) {
		addproductAvailabe = "true";
		document.getElementById("minicartTopSeller").innerHTML = responseText;
		try{
			if(executeScollerFunctionality){
				executeScollerFunctionality();
			}
			var imageName = submitableForm.name + '_img';
			if(document[imageName]){
				StopAnimation(imageName);
			}
		}catch(err){};
	}    
}

function getFromTable(obj,url,func) {
	var getstr = "?";
	for (i=0; i<obj.getElementsByTagName("input").length; i++) {
		if (obj.getElementsByTagName("input")[i].type == "hidden") {
			getstr += obj.getElementsByTagName("input")[i].name + "=" +
				encodeURI(obj.getElementsByTagName("input")[i].value) + "&";
		}
		if (obj.getElementsByTagName("input")[i].type == "text") {
			getstr += obj.getElementsByTagName("input")[i].name + "=" +
				encodeURI(obj.getElementsByTagName("input")[i].value) + "&";
		}
		if (obj.getElementsByTagName("input")[i].type == "checkbox") {
			if (obj.getElementsByTagName("input")[i].checked) {
				getstr += obj.getElementsByTagName("input")[i].name + "=" + 
					encodeURI(obj.getElementsByTagName("input")[i].value) + "&";
			} else {
				getstr += obj.getElementsByTagName("input")[i].name + "=&";
			}
		}
		if (obj.getElementsByTagName("input")[i].type == "radio") {
			if (obj.getElementsByTagName("input")[i].checked) {
				getstr += obj.getElementsByTagName("input")[i].name + "=" + 
					encodeURI(obj.getElementsByTagName("input")[i].value) + "&";
			}
		}  
		if (obj.getElementsByTagName("input")[i].tagName == "SELECT") {
			var sel = obj.getElementsByTagName("input")[i];
			getstr += sel.name + "=" + encodeURI(sel.options[sel.selectedIndex].value) + "&";
		}
	}

	if(addproductAvailabe == "true"){
		addproductAvailabe = "false";
		var imageName = obj.name + '_img';
		if(document[imageName]){
			StartAnimation(imageName);
		}
		if(getstr != null && getstr != ''){
			getstr += "isAJAX=true";
			try{
				if(additionalParameters){
					if(additionalParameters != 'undefined' && additionalParameters != '' && additionalParameters != 'null'){
						getstr += "&" + additionalParameters;
					}
				}
			}catch(err){addproductAvailabe = "true";};
		}
		addToCart(url, getstr, obj);
	}
}

function get(obj,url,func,additionalParameters) {
	var getstr = "";
	for (i=0; i<obj.childNodes.length; i++) {
		if (obj.childNodes[i].tagName == "INPUT") {
			if (obj.childNodes[i].type == "text") {
				getstr += obj.childNodes[i].name + "=" + encodeURI(obj.childNodes[i].value) + "&";
			}
			if (obj.childNodes[i].type == "checkbox") {
				if (obj.childNodes[i].checked) {
					getstr += obj.childNodes[i].name + "=" + encodeURI(obj.childNodes[i].value) + "&";
				}else{
					getstr += obj.childNodes[i].name + "=&";
				}
			}
			if (obj.childNodes[i].type == "radio") {
				if (obj.childNodes[i].checked) {
					getstr += obj.childNodes[i].name + "=" + encodeURI(obj.childNodes[i].value) + "&";
				}
			}
			if (obj.childNodes[i].type == "hidden") {
				getstr += obj.childNodes[i].name + "=" + encodeURI(obj.childNodes[i].value) + "&";
			}
		}   
		if (obj.childNodes[i].tagName == "SELECT") {
			var sel = obj.childNodes[i];
			getstr += sel.name + "=" + encodeURI(sel.options[sel.selectedIndex].value) + "&";
		}
	}
	
	if(addproductAvailabe == "true"){
		addproductAvailabe = "false";
		var imageName = obj.name + '_img';
		if(document[imageName]){
			StartAnimation(imageName);
		}
		if(getstr != null && getstr != ''){
			getstr += "isAJAX=true";
			try{
				if(additionalParameters){
					if(additionalParameters != 'undefined' && additionalParameters != '' && additionalParameters != 'null'){
						getstr += "&" + additionalParameters;
					}
				}
			}catch(err){};
		}
		addToCart(url, getstr, obj);
	}
}



// START: autocomplete avoid cross domain restrictions 
if(windowURL.substring(0,5) == 'https'){
	if(autocompleteURL.substring(0,5) != 'https'){
		autocompleteURL = autocompleteURL.replace("http","https");
		autocompleteURL = autocompleteURL.replace(HTTP_PORT,HTTPS_PORT);
	}
}
// END: autocomplete



// START: editperson.ftl
function submitUpdatePersonForm(){
	var monthSelectedIndex = document.editpersonform.CUSTOMER_MONTH.selectedIndex;
	var yearSelectedIndex = document.editpersonform.CUSTOMER_YEAR.selectedIndex;
	var daySelectedIndex = document.editpersonform.CUSTOMER_DAY.selectedIndex;
	var daysArray = new Array("31", "", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31");
	var isLeapYear = checkLeapYear(document.editpersonform.CUSTOMER_YEAR.options[yearSelectedIndex].value);
	
	if(monthSelectedIndex == 1){ //if the February month is selected
		if(isLeapYear){
			daysArray[1] = "29";
		}else{
			daysArray[1] = "28";
		}
	}
	
	var numberOfDays = daysArray[monthSelectedIndex];
	day = document.editpersonform.CUSTOMER_DAY.options[daySelectedIndex].value;
	dayInt = parseInt(day,10);
	if(numberOfDays < dayInt){
		document.getElementById("userBirthdayIncorrect").style.display = "";
	}else{
		document.getElementById("userBirthdayIncorrect").style.display = "none";
		document.editpersonform.submit();
	}
}

function checkLeapYear(year){
	var year = parseInt(year);
	if(year%4 == 0){
		if((year%100 != 0) || (year%400 == 0)){
			return true;
		}else{
			return false;
		}
	}
	return false;
}
// END: editperson.ftl



// START: quickAddProducts.ftl
function addDefaultQuntity(nr){
	var quantity = document.getElementById("quantity_"+nr).value;
	if(document.getElementById("pzn_"+nr).value == "" ){
		document.getElementById("quantity_"+nr).value = "";
	}else{
		if(quantity == "" ){
			document.getElementById("quantity_"+nr).value = "1";
		}
	}
	if(quantity!=""){
		var qty = parseInt(quantity);
		if( qty == "NaN"){
			document.getElementById("quantity_"+nr).value = "1";
			alert(qty);
		}
	}
}

function setQuantity(nr){
	var pzn = document.getElementById("pzn_"+nr).value;
	var quantity = document.getElementById("quantity_"+nr).value;
	if( pzn != "" && parseInt(quantity) < 1 ){
		document.getElementById("quantity_"+nr).value = "1";
	}
	addDefaultQuntity(nr);
}
// END: quickAddProducts.ftl



// START editcontactmech.ftl
// Method will be called IF birthDate for addresses should be ignored => no use to check it 
function submitForm(){
	// In case  the permission is not activated do NOT check birthDate, just submit the form 
	document.editcontactmechform.submit();
}

// JavaScript enable: function will be called
// JavaScript disabled: check also has to be done in code 
function checkDays(){
	var monthSelectedIndex = document.editcontactmechform.CUSTOMER_MONTH.selectedIndex;
	var yearSelectedIndex = document.editcontactmechform.CUSTOMER_YEAR.selectedIndex;
	var daySelectedIndex = document.editcontactmechform.CUSTOMER_DAY.selectedIndex;
	
	//the dropDowns contain also the Tag, Monat, Yahre => the 
	if(daySelectedIndex==0 || monthSelectedIndex==0 || yearSelectedIndex==0){
		document.getElementById("userBirthdayMissing").style.display = "";
		document.getElementById("userBirthdayIncorrect").style.display = "none";
	}else{
		var daysArray = new Array("31", "", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31");
		var isLeapYear = checkLeapYear(document.editcontactmechform.CUSTOMER_YEAR.options[yearSelectedIndex].value);
		
		//alert('monthIndex = '+monthSelectedIndex);	
		if(monthSelectedIndex == 2){ //if the February month is selected
			if(isLeapYear){
				daysArray[1] = "29";
			}else{
				daysArray[1] = "28";
			}
		}
		var numberOfDays = daysArray[monthSelectedIndex-1];
		day = document.editcontactmechform.CUSTOMER_DAY.options[daySelectedIndex].value;
		if(day.charAt(0) == "0"){
			day = day.substring(1); 
		}		
		dayInt = parseInt(day,10);
		if(numberOfDays < dayInt){
			document.getElementById("userBirthdayIncorrect").style.display = "";
			document.getElementById("userBirthdayMissing").style.display = "none";
		}else{
			document.getElementById("userBirthdayIncorrect").style.display = "none";
			document.getElementById("userBirthdayMissing").style.display = "none";
			
			yearSelected = document.editcontactmechform.CUSTOMER_YEAR.options[yearSelectedIndex].value;
			monthSelected = document.editcontactmechform.CUSTOMER_MONTH.options[monthSelectedIndex].value;
			birth = yearSelected + "-" + monthSelected + "-" + day;
			document.getElementById("birthDate").value = birth;  
			document.editcontactmechform.submit();
		}
	}
}
	
function checkLeapYear(year){
	var year = parseInt(year);
	if(year%4 == 0){
		if((year%100 != 0) || (year%400 == 0)){
			return true;
		}else{
			return false;
		}
	}
	return false;
}
// END: editcontactmech.ftl



// START: Packstation Popup (newcustomer.ftl, editcontactmech.ftl, quickAnonCustSettings.ftl)
function packstationPopup() {
	newwindow2 = window.open(packstationPopupURL,packstationNameLabel,'height=600,width=550');
}
// END: Packstation Popup (newcustomer.ftl, editcontactmech.ftl, quickAnonCustSettings.ftl)



// START: Avoid the code modification on every page where the add to cart functionality is used
function alertContents(){}
// END: Avoid the code modification on every page where the add to cart functionality is used

var currentActive = -1;
var currentSubActive = -1;
function activateDiv(idPrefix,numberOfDivs,curentDiv){
	if(currentActive == curentDiv){
		if(document.getElementById(idPrefix + curentDiv)){
			if(document.getElementById(idPrefix + curentDiv).style.display == 'none'){
				document.getElementById(idPrefix + curentDiv).style.display = 'block';
				currentActive = curentDiv;
			}else{
				document.getElementById(idPrefix + curentDiv).style.display = 'none';
				currentActive = -1;
			}
		}
	}else{
		for(i=0;i<(numberOfDivs+1);i++){
			if(document.getElementById(idPrefix + i)){
				if(i == curentDiv){
					document.getElementById(idPrefix + i).style.display = 'block';
					currentActive = i;
				}else{
					document.getElementById(idPrefix + i).style.display = 'none';
				}
			}
		}
	}
}

function activateSubDiv(idPrefix,numberOfDivs,curentDiv){
	if(currentSubActive == curentDiv){
		if(document.getElementById(idPrefix + curentDiv)){
			if(document.getElementById(idPrefix + curentDiv).style.display == 'none'){
				document.getElementById(idPrefix + curentDiv).style.display = 'block';
				currentSubActive = curentDiv;
			}else{
				document.getElementById(idPrefix + curentDiv).style.display = 'none';
				currentSubActive = -1;
			}
		}
	}else{
		for(i=0;i<(numberOfDivs+1);i++){
			if(document.getElementById(idPrefix + i)){
				if(i == curentDiv){
					document.getElementById(idPrefix + i).style.display = 'block';
					currentSubActive = i;
				}else{
					document.getElementById(idPrefix + i).style.display = 'none';
				}
			}
		}
	}
}

function expandAllDivs(idPrefix,numberOfDivs){
	for(i=0;i<(numberOfDivs+1);i++){
		if(document.getElementById(idPrefix + i)){
			document.getElementById(idPrefix + i).style.display = 'block';
		}
	}
}

function prepareForPrint(idPrefix,numberOfDivs,idPrefixS,numberOfDivsS,curentDiv){
	if(idPrefix != null && idPrefix != ''){
		expandAllDivs(idPrefix,numberOfDivs);
	}
	if(idPrefixS != null && idPrefixS != ''){
		expandAllDivs(idPrefixS,numberOfDivsS);
	}
	window.print();
}

// updated by Razvan Tomescu - 29.06.2010
function updateShopppingListAndAddToCart(obj){
	obj.elements["onlyUpdate"].value = "false";
	if(obj.elements["reservStartStr"]){
		if (obj.elements["reservStartStr"].value.length == 10){
			obj.elements["reservStart"].value = obj.elements["reservStartStr"].value + " 00:00:00.000000000";
		}else{
			obj.elements["reservStart"].value = obj.elements["reservStartStr"].value;
		}
	}
	obj.submit();
}

function updatedShoppingList(size, url ){
	var newUrl = url + "&";
	for ( i = 1 ; i <= size ; i++){
		if( i < 10 ){
			newUrl = newUrl + "0000"+i + "=" + document.getElementById("qty_0000"+i).value + "&";
		}else{
			newUrl = newUrl + "000"+i + "=" + document.getElementById("qty_000"+i).value + "&";
		}	
	}
	window.location = newUrl;
}

// START: editShoppingList.ftl
// Function to add extra info for timestamp format
// updated by Razvan Tomescu - 29.06.2010
function TimestampSubmit(obj){
	if(obj.elements["reservStartStr"]){
		if (obj.elements["reservStartStr"].value.length == 10){
			obj.elements["reservStart"].value = obj.elements["reservStartStr"].value + " 00:00:00.000000000";
		}else{
			obj.elements["reservStart"].value = obj.elements["reservStartStr"].value;
		}
	}
	obj.submit();
}

function removeShoppingList(){
	document.removeShoppingListItemsForm.submit();
}

function checkToggleShoppingElement(e){
	for(i = 0; i<document.getElementsByTagName("input").length; i++){
		if(document.getElementsByTagName("input")[i].type== "checkbox"){
			if(document.getElementsByTagName("input")[i].name == "selectedItem"){
				if(document.getElementsByTagName("input")[i].value != "0"){
					if(document.getElementsByTagName("input")[i] == e ){
						if(e.checked){
							document.getElementById("selectedShoppingItems").value += e.value+"#";
						}else{
							var str = document.getElementById("selectedShoppingItems").value;
							str = str.replace(""+e.value+"#","");
							document.getElementById("selectedShoppingItems").value = str;
						}
					}
				}
			}
		}
	}
}

function addAll(){
	document.getElementById("test_all").value="true";
	//document.searchformMultipleParty.submit();
	setSelectedValuesForGeos();
}

function clearInputField(){
	document.getElementById("selectedShoppingItems").value = "";
}

function getSelectedShoppingValues(){
	for(i = 0; i<document.getElementsByTagName("input").length; i++){
		if(document.getElementsByTagName("input")[i].type== "checkbox"){
			if(document.getElementsByTagName("input")[i].name == "selectedItem"){
				if(document.getElementsByTagName("input")[i].value != "0"){
					//document.removeShoppingListItemsForm.getElementById("selectedShoppingItems").value = document.getElementsByTagName("input")[i].value +" #";
				}
			}
		}
	}
	alert("ok");
}
// END: editShoppingList.ftl



// SMALLBOX javascript actions (START)
// #smallBoxRecommend
function emptyTextField(){
	document.getElementById("sendTo").value = "";
}
// #smallBoxOnlineHelp
function emptyTextFieldOnlineHelp(){
	document.getElementById("onlineHelpSendTo").value = "";
}
// #smallBoxContactMe
function emptyTextFieldPleaseContactMe(){
	document.getElementById("pleaseContactMeSendTo").value = "";
}
// SMALLBOX javascript actions (END)


// SEARCH box text (START)
function searchOnBlurDefault(obj) {
	if(obj.value == '' || obj.value == ' '){obj.value = inputSearchText}
}
function searchOnUse(obj) {
	if(obj.value == inputSearchText){obj.value = '';}
}
// SEARCH box text (END)

// SEARCH box text (START)
function searchOnBlurDefaultShopping(obj) {
	if(obj.value == '' || obj.value == ' '){obj.value = inputSearchTextShopping}
}
function searchOnUseShopping(obj) {
	if(obj.value == inputSearchTextShopping){obj.value = '';}
}
// SEARCH box text (END)

// Gutschine input text (START)
function gutschineOnBlurDefault(obj) {
	if(obj.value == '' || obj.value == ' ')
		{obj.value = gutschineInputText;}
}

function gutschineOnUse(obj) {
	if(obj.value == gutschineInputText)
		{obj.value = '';}
}
// Gutschine input text (END)

// TRIM CODE (START)
function trimCode(form) {
	stringToTrim = document.getElementById("optInVerifyCodeId").value
	document.getElementById("optInVerifyCodeId").value = stringToTrim.replace(/^\s+|\s+$/g,"");
	fromName = "clistAcceptForm"+form;
	//document.fromName.submit();
}
// TRIM CODE (END)