// *****************************************************
// ******************    searchNav.js    *************** 
//
/**
 * Diese JavaScript Datei definiert allgemeine Funktionalitäten bezüglich der
 * Hauptnavigation und das Umschalten der verschiedenen Suchemasken.
 *
 *
 * Bearbeiter: ych,md,lso
 *
 * Abhängigkeiten: vars.js, utilities.js
 *
 **/
// *****************************************************

var goNav = {
	init: function(){
		// Set object for navIds and layerIds
		goNav.setNavObject();
		
		// Set Examples-Text for textfields	
		goNav.examples.init();
		
		// Get and store initial search-Type
		var sSearchType = goNav.getInitialSearchType();
		// if searchType was set (if link is in subNav with class "on")
		if(sSearchType){
			goNav.setCurrentSearchType(sSearchType);
			
			// store current NavId and LayerId
			goNav.sCurrentNavId = goNav.oNav[sSearchType].sNavId;
			goNav.sCurrentNavId = goNav.oNav[sSearchType].sNavId;
			goNav.setCurrentLayerName(goNav.oNav[sSearchType].sLayerId);
	
			// Focus SubNav for Tabbing
			goNav.focusCurrentSubNavElement();
		}
		
		// Set SubNav-Var
		goNav.oSubNav = $('#subNav_search'); 
		
		// Set EventHandlers for subNav
		goNav.setSubNavHandlers();
	},
	setSubNavHandlers: function(){
		//alert("setSubNavHandlers() called");
		this.oSubNav.click(this.setSearchType);		
	},
	getInitialSearchType: function(){
		var oNavElement;
		// Iterate through oNav-Object, get the adNav-ID and check for the "on"-class
		// Afterwards return adView-Attribute, if class was found
		for(var o in this.oNav){
			oNavElement = $("#"+this.oNav[o].sNavId);
			if (oNavElement.hasClass("on")) {
				return oNavElement.attr("searchType");
				break;
			}
		}
		return false;
	},
	setSearchType: function(evt){
		evt.preventDefault();
		
		// Find id of clicked li-element
		var obj = evt.target;
		if(obj.nodeName.toLowerCase() == "ul") return;
		while(obj.nodeName.toLowerCase() != "li" && obj.nodeName.toLowerCase() != "body") obj = obj.parentNode;

		var sSearchType = obj.getAttribute("searchType");
		
		// Remove href of anchor because of preventDefault-failure in Safari
		obj.getElementsByTagName("a")[0].href = "#";
		
	  	//alert("id: " + obj.id + " | searchType: " + sSearchType);
		// Switch searchType
		var sSearchChannel = obj.getAttribute("channel");
		if(sSearchChannel == null || sSearchChannel == ''){
			sSearchChannel = '0';
		}
		goNav.switchSearchType(sSearchType, sSearchChannel);
		goNav.setCurrentSearchType(sSearchType);

	},
	setNavObject: function(){
		this.oNav = {
			schnellsuche:{
				sLayerId: "simpleSearch",
				sNavId: "subNav_simple",
				sNavTitle: "simSearch"
			},
			detailsuche:{
				sLayerId: "complexSearch",
				sNavId: "subNav_complex",
				sNavTitle: "comSearch"
			}, 
			inverssuche:{
				sLayerId: "telSearch",
				sNavId: "subNav_tel",
				sNavTitle: "telSearch"
			},
			websuche:{
				sLayerId: "webSearch",
				sNavId: "subNav_web",
				sNavTitle: "webSearch"
			},
			notdienste:{
				sLayerId: "emergencySearch",
				sNavId: "subNav_emergency",
				sNavTitle: "medSearch"
			},
			branchensuche:{
				sLayerId: "branchesSearch",
				sNavId: "subNav_branches",
				sNavTitle: "braSearch"				
			},
			redakeditor:{
				sLayerId: "redakSearch",
				sNavId: "subNav_redak",
				sNavTitle: "ediSearch"
			}
		}
	},
	highlightCurrentNav: function(){
		// highlight clicked li
		// Return if class already added
		if ($("#"+this.getCurrentNavId()).hasClass("on")) return;
		// otherwise add class
		$("#"+this.getCurrentNavId()).addClass("on");
		
		// set last li to default
		$("#"+this.getLastNavId()).removeClass("on");
		//alert(this.getLastNavId());
	},
	setCurrentNavId: function(sId){
		// Store last NavId
		this.setLastNavId(this.getCurrentNavId());
		// set current NavId
		this.sCurrentNavId = sId;
	},
	getCurrentNavId: function(){
		return (this.sCurrentNavId) ? this.sCurrentNavId : null;
	},
	setLastNavId: function(sId){
		this.sLastNavId = sId;
	},
	getLastNavId: function(){
		return (this.sLastNavId) ? this.sLastNavId : null;
	},
	setCurrentSearchType: function(sSearchType){
		this.sCurrentSearchType = sSearchType;
	},
	getCurrentSearchType: function(){
		return this.sCurrentSearchType;
	},
	switchSearchType: function(sType, sSearchChannel){
		var sLayer, sNavId;
		sType.toLowerCase();		
		if (sType == "branchensuche") {
			goUrl.loadURL("/branchenbuch");
			return;
		}
		else if (sType == "detailsuche" && this.getCurrentSearchType() == "schnellsuche"){
			this.splitLocalityData(document.simpleForm.LOC.value);
		}
		else if (sType == "schnellsuche" && this.getCurrentSearchType() == "detailsuche"){
			this.joinLocalityData(document.complexForm.plz_complex.value, document.complexForm.city_complex.value);
		}
		else if (sType == "redakeditor"){
			goUrl.loadURL("/GoYellowEditor/");
			return;
		}
		if (this.getCurrentSearchType() == sType) return;
		// Show Search layer and hide last layer
		$("#"+this.oNav[sType].sLayerId).css(goUtils.css.visible);
		this.setCurrentLayerName(this.oNav[sType].sLayerId);
		// Hide last inputfields if it was not the branches search
		if(this.getLastLayerName() && this.getLastLayerName() != "branchesSearch") $("#"+this.getLastLayerName()).css(goUtils.css.invisible);
		
		// Set Navigation-Properties
		// Store current navID
		this.setCurrentNavId(this.oNav[sType].sNavId);
		// Activate and highlight clicked Nav-Element
		this.highlightCurrentNav();
		
		//alert( 'c' + sSearchChannel + '_' + this.oNav[sType].sNavTitle );
		goUtils.emitMessage('c' + sSearchChannel + '_' + this.oNav[sType].sNavTitle );
		//goUtils.emitMessage(this.oNav[sType].sLayerId);
	},
	setCurrentLayerName: function(sLayer){
		// Store last layer
		this.setLastLayerName(this.sCurrentLayerName);
		// set current layer
		this.sCurrentLayerName = sLayer;		
	},
	getCurrentLayerName: function(){
		return (this.sCurrentLayerName) ? this.sCurrentLayerName : null;
	},
	setLastLayerName: function(sLayer){
		this.sLastLayerName = sLayer;
	},
	getLastLayerName: function(){
		return (this.sLastLayerName) ? this.sLastLayerName : null;
	},
	focusCurrentSubNavElement: function(){
		$("#"+this.sCurrentNavId).find("a").get(0).focus();
	},
	envSearch: {
		show: function(sType){			
			// Add Class "on" to show fields
			$("#"+this.getName(sType, "envSearchFields")).addClass("on");
			$("#"+this.getName(sType, "lnkEnvSearchHide")).css(goUtils.css.visible);
			$("#"+this.getName(sType, "lnkEnvSearchShow")).css(goUtils.css.invisible);
			$("#"+this.getName(sType, "searchFieldsHelp")).css(goUtils.css.invisible);			
			// Enable Elements
			goUtils.enableElement(this.getName(sType, "street"));
			goUtils.enableElement(this.getName(sType, "area_sel"));
		},
		hide: function(sType){
			// Remove Class "on"
			$("#"+this.getName(sType, "envSearchFields")).removeClass("on");
			$("#"+this.getName(sType, "lnkEnvSearchShow")).css(goUtils.css.visible);
			$("#"+this.getName(sType, "searchFieldsHelp")).css(goUtils.css.visible);
			$("#"+this.getName(sType, "lnkEnvSearchHide")).css(goUtils.css.invisible);
			// Disable Elements
			goUtils.disableElement(this.getName(sType, "street"));
			goUtils.disableElement(this.getName(sType, "area_sel"));
		},
		getName: function(sType, sBaseName){
			return sBaseName + ((sType) ? "_" + sType : "");
		},
		isVisible: function(){
			return $("#envSearchFields").hasClass("on");
		}
	},
	examples:{
		init: function(){

			this.inputWhat   = new InputDefault(".searchforms input[inputType='what']");
			this.inputWhere  = new InputDefault(".searchforms input[inputType='where']"); /* 2 fields set: where + emergency_where */
			this.inputStreet = new InputDefault(".searchforms input[inputType='street']");
			this.inputPhone  = new InputDefault(".searchforms input[inputType='phone']");
			
			// Check if textfield-focus has to be set
			this.checkForSettingFocus();
		},
		checkForSettingFocus: function(){
			// Only set focus on what-field if at startpage and history is not disabled (recurring user)
			(!User.searchHistory.isDisabled().histWhat && !User.searchHistory.isDisabled().histWhere && this.isStartpage()) ? $("#what").focus() : 0;
		},
		isStartpage: function(){
			// startpage if no subNav_search available
			return ($("#subNav_search").length > 0) ? false : true;
		},
		checkFormSubmit: function(oForm){
			// initialize and reset Filter-Cookie
			if(typeof goNavContext != "undefined") goNavContext.initFilterCookie();
			
			var arrFields = oForm.getElementsByTagName("input");
			
			var sSearchType, oField;
			var params = new Array();
			for(var c=0; c < arrFields.length; c++){
				oField = arrFields[c];
				sSearchType = oField.getAttribute("inputType");
				if (sSearchType != null && oField.value == goVars.txtFld[sSearchType]) oField.value = "";
				if (oField.id=='what') params["what"] = oField.value;
				if (oField.id=='where') params["where"] = oField.value;
				if (oField.id=='street') params["street"] = oField.value;
			}
			if (oForm.name=="simpleForm" || oForm.name=="inputForm"){
				if(!params["what"] && params["where"]){
					// Only where-field is filled - call map
					return goNav.checkMapSearch(params);
				} else if (params["what"] && !params["where"]){
					// Only what-field is filled - jump to where-field
					if(goNav.getCurrentInputElement() && goNav.getCurrentInputElement().id != "where"){
						$("#where").focus();
						return false;
					}
				}
			}      
			return true;
		}
	}, // end examples
	setCurrentInputElement: function(obj){
		this.oCurrentInputElement = obj;
	},
	getCurrentInputElement: function(){
		return this.oCurrentInputElement;
	},
	// start a web-search from a result page 
	doWebSearch: function(strFormName, strKeyword) {
  		var form = eval(document.forms[strFormName]);
  		form.keywords.value=unescape(strKeyword);
  		//form.PAGE.value="overtureSearch"; 
  		form.ACTION.value="initialWebSearch";
  		form.submit();
		return false;
	},
	
	checkMapSearch: function(params){
	  var loc = params["where"];
	  var street = params["street"];
	  
	  // Manually escape + and /
	  loc = loc.replace(/\//g," ");
	  street = street.replace(/\//g," ");
	  street = street.replace(/\+/g,"%2B");
	  
	  var urlSuffix = encodeURIComponent(loc);
  	  if (street != "") urlSuffix = urlSuffix + "/" + encodeURIComponent(street);
  	  urlSuffix = urlSuffix + "/";
  	  
   	  $.get("/ajaxPos/" + urlSuffix, function(xml) {
			  var responseUrl = xml.getElementsByTagName("url");
			      
			  if (responseUrl != undefined && responseUrl[0] != undefined && responseUrl[0].firstChild != undefined) {
			    urlSuffix = responseUrl[0].firstChild.nodeValue; 
			    urlSuffix = encodeURI(urlSuffix);   
			  }
			  
			  goUrl.loadURL("/map/" + urlSuffix);
		  
	  });
    
      return false;
	},
	joinLocalityData: function(plz, loc){
		var strLoc = (plz) ? plz+" "+loc : loc;
		var oField = document.simpleForm.LOC
		oField.value = strLoc;
		// if locality is not empty switch css otherwise get examples-text from goVars and reset to this value
		if(strLoc != "") {
			goNav.examples.inputWhere.setTxtToStandardMode();
		} else {
			goNav.examples.inputWhere.setTxtToExamplesMode();
		}
	},
	splitLocalityData: function(strLocBuf){
	  var results = this.splitLocalityDataFunc(strLocBuf);
	  var strCity = results[1], strPLZ = results[0];
	  if (strCity!=goVars.txtFld["where"]) {
	  	document.complexForm.plz_complex.value = strPLZ;
	  	document.complexForm.city_complex.value = strCity;
	  } else {
	  	document.complexForm.plz_complex.value = "";
	  	document.complexForm.city_complex.value = "";
	  }
	},
	splitLocalityDataFunc: function(strLocBuf){
	  var numCounter = 0;
	  var booZipCodeFound = false;
	  var strCity = "", strPLZ = "";
	  var strLoc = strLocBuf.toString();
	  var arrStringBuf = new Array();
	  arrStringBuf = this.getWordsFromString(strLoc);
	  var numArrayLength = arrStringBuf.length;
	  while(numCounter++ < numArrayLength){
		// Check if string is numeral
		if(this.checkForNumeralString(arrStringBuf[numCounter-1])){
		  // is numeral string
		  strPLZ += arrStringBuf[numCounter-1];
		} else {
		  // is NOT a numeral string
		  (strCity.length > 0) ? strCity += " " : 0;
		  strCity += arrStringBuf[numCounter-1];
		}
	  }
	  var results = new Array (2); results[0]= strPLZ; results[1] =strCity ;
	  return results;
	},
	checkForNumeralString: function(str){
	  var numStringLength = str.length;
	  var numCounter = 0;
	  while (numCounter < numStringLength){
		var strCurrChar = str.charAt(numCounter++)
		// Return false if not a number or a defined char
		if (isNaN(strCurrChar) && strCurrChar != "*" && strCurrChar != ".") return false;
	  }
	  return true;
	},

	getWordsFromString: function(str){
	  var arrString = str.split(" ");
	  return arrString;
	}
}

function topnavSwitcher() {
	var liWithOnClass = $('.navbar .topNav li').filter('.on');
	$('.topNav_more a.arrowDown').click (
		function () {
			$(liWithOnClass).removeClass('on');
			$('.topNav_more').addClass('on');
			$('.topNav_list').show();
			return false;
	});
	$('body').click (
		function () {
			$(liWithOnClass).addClass('on');
			$('.topNav_more').removeClass('on');
			$('.topNav_list').hide();			
	});	
}
$(function() {topnavSwitcher();});


function highlightSwitcher() {
	$(".topNav_list ul.gylist li").mouseover(function() {
		$(this).addClass('highlight');													  
	});
	$(".topNav_list ul.gylist li").mouseout(function() {
		$(this).removeClass('highlight');													  
	});	
}
$(function() {highlightSwitcher();});


function secondFooterSwitcher() {
	$(".secondFooter .sepwithDots li").click(function() {
		var index = $(".secondFooter .sepwithDots li").index(this);
		$(".secondFooter .moreLinks ul").hide();													  
		$(".secondFooter .moreLinks ul:eq("+index+")").show();
	});
}
$(function() {secondFooterSwitcher();});
