var Pref = {
	initPref: function(formname){
		//Pref.form = document.forms[formname];
		var cookie = Pref.getSuggestCookie();
		
		Pref.homeLocationPreferences = "";
		
		
		Pref.setElements();		
		Pref.initPrefAnchors();
		Pref.checkStatusPrefElements();
		Pref.setACField(cookie);
		Pref.updateHistoryStatus();
		Pref.initLocation();
	},

	initPositioningPref: function(formname){
		//Pref.form = document.forms[formname];
		Pref.homeLocationPreferences = "CALLBACK=locationPreferences";
		var cookie = Pref.getSuggestCookie();
		Pref.initLocation();
	},
	
	refreshParent: function(){
		// update for local feeds (hallo heimat)
		window.opener.location.reload();
  		//window.close();
	},	

	setElements: function(){
		// anchors
		this.oAnchorSuggest = $("#txtPrefSuggest");
		this.oAnchorAC = $("#txtPrefAC");
		this.oAnchorMap = $("#txtPrefMap");

		// anchortexts for active and inactive
		this.sTxtSuggestOn = "Vorschlagsfunktion aktivieren";
		this.sTxtSuggestOff = "Vorschlagsfunktion ausschalten";
		this.sTxtACOn = "Autovervollständigung aktivieren";
		this.sTxtACOff = "Autovervollständigung ausschalten";
		this.sTxtMapOn = "Treffer in Karte aktivieren";
		this.sTxtMapOff = "Treffer in Karte ausschalten";
	},
	
	initPrefAnchors: function(){
		var cookie = Pref.getSuggestCookie();
		this.setText(this.oAnchorSuggest, 1, this.sTxtSuggestOn, this.sTxtSuggestOff);
		this.setText(this.oAnchorAC, 2, this.sTxtACOn, this.sTxtACOff);
		this.setText(this.oAnchorMap, 4, this.sTxtMapOn, this.sTxtMapOff);
	},
	
	togglePref: function(sType, booCheckAC){
		var cookie = Pref.getSuggestCookie();
		// autocomplete is inactive if suggest is turned off (first bit of cookie for suggest is not set)
		if(sType == "autocomplete" && !(cookie&1)) return;
		Pref.setParam(sType);
		Pref.checkStatusPrefElements();
		if(booCheckAC) Pref.setACField();
		return false;
	},

	setParam: function(param) {
		var cookie = Pref.getSuggestCookie();
		if (!cookie) cookie = 0;
		if(opener && opener.Suggest) Suggest = opener.Suggest;
		switch(param){
			case "show":
				if (Suggest) {
					// Set flag to 1 if negation of first bit for suggest is true
					var flag = (!(cookie&1)) ? 1 : 0;
					for(var i = 0; i < Suggest.boxes.length; i++){
						Suggest.boxes[i].show = flag;
					}
				}
				nCookieValue = cookie^1;
				// Set cookie
				this.setSuggestCookie(Pref.cookieName + "=" + String(nCookieValue), 90);
				// set anchor text
				this.setText(this.oAnchorSuggest, 1, this.sTxtSuggestOn, this.sTxtSuggestOff);
				this.setText(this.oAnchorAC, 1, this.sTxtACOn, this.sTxtACOff);
				break;
			case "autocomplete":
				if (Suggest) {
					var flag = (!(cookie&2)) ? 1 : 0;
					for(var i = 0; i < Suggest.boxes.length; i++){
						Suggest.boxes[i].autocomplete = flag;
					}
				}
				nCookieValue = cookie^2;
				// Set cookie
				this.setSuggestCookie(Pref.cookieName + "=" + String(nCookieValue), 90);
				// Set anchor text. No Text if suggest is turned off (first bit of cookie for suggest is not set)
				this.setText(this.oAnchorAC, 2, this.sTxtACOn, this.sTxtACOff);
				break;
			case "showMap":
				nCookieValue = cookie^4;
				// Set cookie
				this.setSuggestCookie(Pref.cookieName + "=" + String(nCookieValue), 90);
				// Set anchor text
				this.setText(this.oAnchorMap, 4, this.sTxtMapOn, this.sTxtMapOff);
				break;
		}
		//goUtils.trace("cookieValue = " + nCookieValue + " | cookie%2 = " + (nCookieValue%2));
		return false;
	},
	
	setText: function(oAnchor, nBit, sTxtInactive, sTxtActive){
		var cookie = Pref.getSuggestCookie();
		if (!cookie) cookie = 0;
		var term = (cookie & nBit) ? sTxtActive : sTxtInactive;
		oAnchor.html(term);
	},
	
	checkStatusPrefElements: function(){
		var cookie = Pref.getSuggestCookie();
		if (!cookie) cookie = 0;
		
		// Switch on if first bit for suggest is set
		(cookie&1) ?  this.switchOnPrefElement("prefSimilarResults") :  this.switchOffPrefElement("prefSimilarResults");
		
		// Switch on if second bit for autocomplete is set. First bit for suggest also has to be enabled
		((cookie&2) && (cookie&1)) ? this.switchOnPrefElement("prefAutoComplete") :  this.switchOffPrefElement("prefAutoComplete");
				
		// Switch on if third bit for map was set
		(cookie&4) ? this.switchOnPrefElement("prefMap") : this.switchOffPrefElement("prefMap");
	},
	
	switchOnPrefElement: function(sObj){
		var obj = $("#"+sObj);
		if (obj) {
			obj.addClass("prefOn");
			obj.removeClass("prefOff");
		}
	},
	switchOffPrefElement: function(sObj){
		var obj = $("#"+sObj);
		if (obj) {
			obj.addClass("prefOff");
			obj.removeClass("prefOn");
		}
	},
	
	setACField: function(){
		var cookie = Pref.getSuggestCookie();
		if(cookie&1) $("#txtPrefAC").css(goUtils.css.visible); else $("#txtPrefAC").css(goUtils.css.invisible);;
		// Only switch on autocomplete if first bit for suggest was set (cookie%2 == 1)
		if (cookie%2) {
			// Only switch on if cookie for second bit is set
			if(cookie&2) {
				this.switchOnPrefElement("prefAutoComplete");				
			}
		} else {
			this.switchOffPrefElement("prefAutoComplete");
		}
	},

	setSuggestCookie: function(content, days) {
		var expires = new Date();
		var expTime = expires.getTime()+days*24*60*60*1000;
		expires.setTime(expTime);
		document.cookie = content+"; expires="+expires.toGMTString()+"; path=/;";
	},

	getSuggestCookie: function() {
		var defValue = 1;
		if (!document.cookie) return defValue;
		var start = document.cookie.indexOf(Pref.cookieName+"=");
		if (start>=0) {
			var substr = document.cookie.substring(start);
			var ende = substr.indexOf(';');
			var flag = (ende>=0) ? substr.substring(substr.indexOf('=')+1, ende) : substr.substring(substr.indexOf('=')+1);
			return flag;
		} else return defValue;
	},
	
	clearHistory: function(){
		// Reset HistoryList
		if (window.opener) {
			window.opener.User.searchHistory.resetList("what");
			window.opener.User.searchHistory.resetList("where");
		}
		this.updateHistoryStatus();		
		return false;
	},
	updateHistoryStatus: function(){		
		var historyLink = $("#lnkHistory");
		if(!historyLink) return;
		if (window.opener.User.searchHistory.isDisabled().histWhat && window.opener.User.searchHistory.isDisabled().histWhere) {
			historyLink.addClass("empty");
			// Change text
			historyLink.html("Suchhistorie wurde gelöscht");
			/* IDT-1561, doesn't work in FF3 whatever
			var tnHist = document.createTextNode("Suchhistorie wurde gelöscht");
			historyLink.replaceChild(tnHist, historyLink.firstChild);
			*/
		} else {
			historyLink.removeClass("empty");
		}
	},
	initLocation: function(){
		var mapOptions = { draggableCursor:'default' };
	    	Pref.getLocation ();	
	},
	getCoords4InputAddress: function(homeLocation){
		//alert('getCoords4InputAddress');
		var loc = null;
		var street = null;
		if (homeLocation){
			//alert(homeLocation);
			loc = homeLocation;
			street = ""
		}else{
  			loc = $("#where_home").attr('value');
  			street = $("#street_home").attr('value');
		}
		

  		$("#where_home").removeClass("notFound");
  		$("#street_home").removeClass("notFound");
  		
  if (!loc) loc=""; if (!street) street = "";
  
  // Default Texte aus den Feldern ignorieren
  if (loc == goVars.txtFld["cityMap"]) loc = "";
  if (street == goVars.txtFld["streetMap"]) street = "";

  // Sonderbehandlung: Wählt man als Standort "Redaktion", so erhält man einen EDS Link und interne Datensatz Informationen bei jedem Datensatz
  // Realisierung in "edsEditorTemplate.xsl" "adServerZonesTemplate.xsl" "seachAreaTemplate.xsl" "NDPDTelSearchMapper.java"
  if (loc == "Redaktion")
  {
  	Pref.setLocation (11.5803, 48.1395, "Redaktion");
  	return false;
  }
  
  // Auch ganz ohne Eingabe oder ohne Ort lassen wir die Suche zu, weil die Fehlermeldung dann im XSLT erzeugt wird.
  
  // Manually escape + and /
  loc = loc.replace(/\s*\/\s*/g," ");
  street = street.replace(/\s*\/\s*/g," ");
  street = street.replace(/\+/g,"%2B");

  var urlSuffix = encodeURIComponent(loc);
  if (street != "") urlSuffix = urlSuffix + "/" + encodeURIComponent(street);
  urlSuffix = urlSuffix + "/";
 
  var results = goNav.splitLocalityDataFunc(loc);
  var zcd = encodeURIComponent(results[0]);
  loc = encodeURIComponent(results[1]); 
  street = encodeURIComponent(street); // Street/hno wird in Mapper gesplittet 
  var action = ((street.length == 0)? "locSearch" : "streetSearch");
  
  // Statistik für Standort festlegen:
  // 1) Anzeige der Modalbox bei HalloHeimat + Angebote Seite
  //	==> PAGE=hallo_heimat bzw. PAGE=angebote + ACTION=modal
  //	siehe: tailor/statisticsStylesheets/baseTemplates.xsl
  // 2) Aktivierung "Standort ändern" durch Nutzer
  //	==> PAGE=homeLocation + ACTION=search
  //	Standard Verhalten bei Aufruf einer Seite (statisticsStylesheet=noSearchStat in businessLogicConfig.xml)
  // 3) Setzen eines Standortes durch Nutzer
  //	==> PREVIOUS=homeLocation
  //    wird durch REF=homeLocation in der unten stehenden URL erreicht
  
  return $.ajax({
  	async: false, // synchron, da das Folgeprocess auf die ermittelten Koordinaten basiert.
   	url: "/IDA2?MIME=xml&REF=homeLocation&PAGE=ajaxPos&ACTION="+action+ "&ZCD="+zcd+"&LOC="+loc+ "&STR="+street+ "&locField=" + "where_home" + "&strField=" + "street_home" + '&' + Pref.homeLocationPreferences,
   	success: function(xml){
		  var responseUrl = $(xml).find("url");
		  var relevantHomeLocation = xml.getElementsByTagName("homeLocation");

		  if (responseUrl != undefined && responseUrl[0] != undefined && responseUrl[0].firstChild != undefined) 
		  { // Position gefunden
		    	var responseCoordX = responseCoordY = CoordX = CoordY = 0;
			  	responseCoordX = xml.getElementsByTagName("coordinateX");
				if (responseCoordX != undefined && responseCoordX[0] != undefined && responseCoordX[0].firstChild != undefined) {
				    CoordX = responseCoordX[0].firstChild.nodeValue;
				}
			
			  	responseCoordY = xml.getElementsByTagName("coordinateY");
				if (responseCoordY != undefined && responseCoordY[0] != undefined && responseCoordY[0].firstChild != undefined) {
				    CoordY = responseCoordY[0].firstChild.nodeValue;
				} 
				homeLocation = relevantHomeLocation[0].firstChild.nodeValue;
				//alert(homeLocation);
				Pref.setLocation (CoordX, CoordY, homeLocation);			
			return true;
		  } 
		  else 
		  { // Position nicht gefunden
		  
		  	// Zeige Fehlerbox an
		    var error = xml.getElementsByTagName("error");
		  	var firstchild = error[0].firstChild;
		  	var content = firstchild.nodeValue;
		  	$('#geoPortalNav').empty();
		  	$('#geoPortalNav').addClass('layerBox');
		  	$('#geoPortalNav').html(content);
		  	$('#geoPortalNav').css('visibility', 'visible');
		  	$('#geoPortalNav').show();
		  	
		  	// färbe fehlerhaftes Eingabefeld rot
		  	var field = null;
		  	if ( (content.indexOf ("Ort nicht gefunden") != -1) || (content.indexOf ("Kein Ort eingegeben") != -1) )
		  	{
		  		field = "where_home";
		  	}
		  	if (content.indexOf ("Straße nicht gefunden") != -1)
		  	{
		  		field = "street_home";
		  	}
		  	if (field != null)
		  	{
		  		if (document.getElementById(field)) 
		  		{
		  			$("#"+field).addClass("notFound");
		  			$("#"+field).focus();
		  		}
		  	}	  	
		  	return false;
		  }
	  	} // End successsFunc
   }); // End ajax definition
	
	},
	getLocation: function(){
	    var homeInfo = $.cookie("GY_HOME");
	    if (! isUndefOrNull(homeInfo) && homeInfo.isNotEmpty())
	    {
	    	//Liest Koordinaten Zoomstufe und Maptype aus einem Cookie und ruft setCenter mit den Werten auf
	    	var homeHash = homeInfo.split("|");
			var lon = homeHash[0];
			var lat = homeHash[1];
			var zoom = parseInt(homeHash[2]);
			var loc = homeHash[4];
			var street = homeHash[5];
			if (!loc) loc=""; if (!street) street = "";
			
			if (street.length > 0) loc = loc + ", " + street;
			if (loc.length > 0)
			{ 
				$("#lastLocation").text(loc);
			}
			else
			{
				$("#lastLocationBox").hide ();
			}
		} 
		else
		{
			//Pref.map.setCenter(new GLatLng(51.70000,10.50000), 4);
			//$("#lastLocationBox").hide ();
		}		
	},
	setLocation: function(CoordX, CoordY, homeLocation){
   		//Speichert Koordinaten Zoomstufe und Maptype in einem Cookie
   		//alert(homeLocation);
		var curMT = "Satellit";
		var curLon = CoordX;
		var curLat = CoordY;
		var curZoom = "16";
		var loc = null
		if(! isUndefOrNull(homeLocation) && homeLocation.isNotEmpty()){
			loc = homeLocation;
		}else{
			loc = $("#where_home").attr('value');
		}	
  		var street = $("#street_home").attr('value');
   		if (!loc) loc=""; if (!street) street = "";
  
  		// Default Texte aus den Feldern ignorieren
  		if (loc == goVars.txtFld["cityMap"]) loc = "";
  		if (street == goVars.txtFld["streetMap"]) street = "";
  		
		var home = curLon + '|' + curLat + '|' + curZoom + '|' + curMT + '|' + loc + '|' + street;
		$.cookie("GY_HOME", home, {expires:365,path:"/"});
		
/*		if (street.length > 0) loc = loc + ", " + street;
		if (loc.length > 0)
		{ 
			$("#lastLocation").text(loc);
		}
		$("#lastLocationBox").show ();
*/		
		//alert(window.opener.document.body.className);
		if (document.forms['localityPreferences']) {
			if(window.opener.document.body.className == 'bodyMain brochure'){
				// Angebote					
				window.opener.location.pathname = '/angebote/' + encodeURIComponent(loc);
			}else if(window.opener.document.body.className == 'bodyFlex'){
				window.opener.location.pathname = '/map/' + encodeURIComponent(loc);			
			}else{
				
				window.opener.location.reload();
			}	
			self.close();
		}else{
			if(window.document.body.className == 'bodyMain brochure'){
				// Angebote
				window.location.pathname = '/angebote/' + encodeURIComponent(loc);
			}		
			window.location.reload();
		}
		
	},
	setLocationToNONE: function(){
		//console.log('setLocationToNONE');
   		//Speichert default Koordinaten Zoomstufe und Maptype in einem Cookie
		var curMT = "Satellit";
		var curLon = "8.6368";
		var curLat = "50.1211";
		var curZoom = "6";
		var rnd = Math.floor(Math.random()*99999999999);
	

  		
		var home = curLon + '|' + curLat + '|' + curZoom + '|' + curMT + '|' + "NONE" + '|' + "";
		$.cookie("GY_HOME", home, {expires:365,path:"/"});
		
		if (document.forms['localityPreferences']){
			if(window.opener.document.body.className == 'bodyMain brochure'){
				// Angebote	
				window.opener.location.pathname = '/angebote/';
				window.location.search = 'ACTION=search';
				
			}else if(window.opener.document.body.className == 'bodyFlex'){
				
				window.opener.location.pathname = '/map/';
			
			}else{
				window.opener.location.reload();
			}	
			self.close();
		}else{
			
			if(window.document.body.className == 'bodyMain brochure'){
				// Angebote	
				//window.location.pathname = '/angebote/';
				//window.location.search = 'ACTION=search&RND=' + rnd;
				window.location.href = '/angebote/?ACTION=search&RND=' + rnd;
				//window.location.reload();
				return false;
			}
			window.location.reload();
			return false;
		}
		
	},	
	deleteLocation: function(){
		$.cookie("GY_HOME", null, {path:"/"});
		Pref.getLocation ();
		if (Pref.circleOverlay != null)
		{
			Pref.map.removeOverlay (Pref.circleOverlay);
			Pref.circleOverlay = null;
		}
	},
	// for local feeds 'Hallo Heimat'
	getHomeLocation: function(){
	    var homeInfo = $.cookie("GY_HOME");
	    if (! isUndefOrNull(homeInfo) && homeInfo.isNotEmpty())
	    {
	    	//Liest Ort und Strasses aus dem Cookie aus 
	    	var homeHash = homeInfo.split("|");
			var loc = homeHash[4];
			var street = homeHash[5];
			if (!loc) loc=""; 
			if (!street) street = "";
			
			return new Array(loc,street)
	    }
	    else
	    {
			return null;
	    }	
	},

	getHistoryLocation: function(){
	    var homeInfo = $.cookie("GY_1HIST");	    
	    if (! isUndefOrNull(homeInfo) && homeInfo.isNotEmpty())
	    {
	    	homeInfo = homeInfo.split("||");
	    	
	    	//Liest Ort aus dem History-Cookie aus 
	    	var homeHash = homeInfo[0].split("#");
	    	var locHash = homeHash[0];
 	    		if (! isUndefOrNull(locHash) && locHash.isNotEmpty()){
 	    			var locHist = locHash.split("=");
 	    			if(! isUndefOrNull(locHist[0]) && locHist[0].isNotEmpty() &&  locHist[0] == "loc"){
 	    				var locHash = locHist[1].split(":");
 	    				if(! isUndefOrNull(locHash[0]) && locHash[0].isNotEmpty()){
 	
 	    					return locHash[0];
 	    				}	
 	    			
 	    			}
	    		
	    		
	    		}
			
	    }

	    return null;

	}	



}
Pref.cookieName = "GY_suggestMode";

