try{ 
if (typeof(Prototype) == "undefined" || typeof(domFunction) == "undefined" || typeof(Autocomplete) == "undefined") 
	throw("RegionalSearch : Required scripts are missing");
}catch(err){}

if(typeof(close_label)=="undefined")
{
	close_label = '';
}
// updated for Prototype 1.6.0 : http://www.prototypejs.org/learn/class-inheritance
var RegionalSearch = Class.create({

	initialize : function(name,options) {
		
		this.thO = Object.extend({
			debug : debug, // debug
			suffix : '',
			SearchForm : 'SearchForm', // default ID's
			selectString : 'selectString',
			SearchWhere : 'SearchWhere',
			widgetID : 'widgetID',
			cityID : 'cityID',
			longitude : 'longitude',
			latitude : 'latitude',
			basicRadius : 'basicRadius',
			parseChoiceSubmit : true,
			labels : this.initDefaultLabels(),
			ResultEvent : 'geoCoding.getGoogleResult',
			ResultQ : 's',
			ResultUrl : '/5/index.cfm',			
			showNoResultLightbox : true,
			AutoSuggest : { 
				callerscript : this,
				script: "/5/index.cfm?event=geoCoding.getAutoSuggest&astype=devbridge",
				serviceUrl: function() {
					var searchWhat = $F('SearchWhat');
					if(this.prevSearchWhat != $F('SearchWhat')) {
						this.cachedResponse = [];
						this.badQueries = [];
						this.prevSearchWhat = searchWhat;
					}
					return "/5/index.cfm?event=geoCoding.getAutoSuggest&astype=devbridge&w=" + searchWhat; 
				},
				varname: "s",
				minchars: 3,
				timeout: 100000,
				maxentries: 20, // shorter list for better user experience
				cache: true,
				shownoresults: false,
				json: true,
				callback: this.parseAfterSelect,
				onSelect: this.parseAfterSelect,
				suffix : '',
				closeLabel: close_label,
				useElipse: false
			}
		},options || {});
		
		var suffix = this.thO.suffix;
		window['ReSe'+suffix] = this;
		this.name = name;
		name = this;
		
		this.thD = this.thO.debug;
		this.thL = this.labels = this.thO.labels;
				
		if(typeof this.thO.AutoSuggest.callback == 'undefined'){
			this.thO.AutoSuggest.callback = this.parseAfterSelect;
		}	
		
		// Form and WhereField are looked up at load
		this.SF = this.SearchForm = $(this.thO.SearchForm + suffix);			
		this.SW = this.SearchWhere = $(this.thO.SearchWhere + suffix);
		try{ 
			if(this.SW == null) throw (this.name + " this.SW == null");
		}catch(err){}	
	
		// look up the wheresearch required fields
		this.sS = this.selectString = $(this.thO.selectString + suffix);
		this.wI = this.widgetID = $(this.thO.widgetID + suffix);
		this.cI = this.cityID = $(this.thO.cityID + suffix);
		this.lo = this.longitude = $(this.thO.longitude + suffix);
		this.la = this.latitude = $(this.thO.latitude + suffix);
		this.bR = this.basicRadius = $(this.thO.basicRadius + suffix);
		
		this.holdsubmit = false;
		
		if(typeof lbl_noResults == 'undefined') lbl_noResults = this.t("noResults");
		if(typeof lbl_notFound == 'undefined') lbl_notFound = this.t("notFound");
		if(typeof lbl_tryAgain == 'undefined') lbl_tryAgain = this.t("tryAgain");
		if(typeof lbl_multipleMatches == 'undefined') lbl_multipleMatches = this.t("multipleMatches");
		if(typeof lbl_pleaseSelect == 'undefined') lbl_pleaseSelect = this.t("pleaseSelect");

		if(this.SF != null){
			Event.observe(this.SF,'submit',this.doSubmit.bind(this));	
		}
		
		// start autosuggest
		if(this.SW != null){
			this.SW.removeClassName("loading"); 
			if(close_label!=''){
				this.bindBox(this.SW);
			}
		}
		
	},
	
	/*
	 * series of 5 label functions that maintain backward compatibility. We should not use those global 
	 * variables any more. The right way is to pass a hash of labels at the initialization. By default 
	 * labels are initialized to English. 
	*/ 
	getLabelNoResults: function(){
		if(typeof lbl_noResults == 'undefined'){
			return this.t("noResults");
		}
		return lbl_noResults;
	},
	
	getLabelNotFound: function(){
		if(typeof lbl_notFound == 'undefined'){
			return this.t("notFound");
		}
		return lbl_notFound;
	},
	
	getLabelTryAgain: function(){
		if(typeof lbl_tryAgain == 'undefined'){
			return this.t("tryAgain");
		}
		return lbl_tryAgain;
	},
	
	getLabeMultipleMatches: function(){
		if(typeof lbl_multipleMatches == 'undefined'){
			return this.t("multipleMatches");
		}
		return lbl_multipleMatches;
	},
	
	getLabelPleaseSelect: function(){
		if(typeof lbl_pleaseSelect == 'undefined'){
			return this.t("pleaseSelect");
		}
		return lbl_pleaseSelect;
	},
	
	doSubmit: function(event){
		
		try {
			
			//this.log("submit: " + ReSe.thO.ResultEvent);
			
			this.SW.addClassName("loading");
			
			// clear auto suggest
			if(typeof as != 'undefined'){
				this.log("as clearSuggestions");
				as.clearSuggestions();
			}
			
			// register externally called functions
			if (typeof confirmfunction == 'undefined') confirmfunction = this.tryAgain;
			if (typeof tryAgain == 'undefined') tryAgain = this.tryAgain;
			if (typeof parseChoice == 'undefined') parseChoice = this.parseChoice;
			
			this.checkWhereSearch();
			
			if (this.holdsubmit == true) {
				this.log("Stopping submit");
				// stop submit
				Event.stop(event);
			}
			else {
				this.log("Submitting...");
			}
			
		}catch(e){
			this.log("Error: checkWhereSearch: " + e.message);
		}
		
	},
	
	log: function(msg) {
		if (typeof this == 'object' && this.thD && typeof dump == 'function' && typeof msg != 'undefined'){
			dump(this.name + " : " + msg);
		}
	},
	
	initDefaultLabels : function(){
		thL = $H();		
		thL.set("noResults","No places found");
		thL.set("notFound", "StepStone was unable to find what you\'re looking for. Please adapt your search criteria.");
		thL.set("tryAgain", "Try Again");
		thL.set('multipleMatches', "Multiple matches have been found."); 
		thL.set('pleaseSelect', "Please select one of the following");
		return thL;
	},
	
	t : function (lbl){	if(typeof window['ReSe'+this.thO.suffix].thL == 'object') return window['ReSe'+this.thO.suffix].thL.get(lbl); },
	
	// ReSe = this
	parseChoice: function (sw,wi,ci,gx,gy,br,ReSe,forceSubmit){		
		
		//ReSe.log("parseChoice");
		ReSe.SW.value = decodeURI(sw.toString().stripTags());
		ReSe.sS.value = ReSe.SW.value;
		ReSe.wI.value = wi; ReSe.cI.value = ci; ReSe.lo.value = gx; ReSe.la.value = gy; ReSe.bR.value = br;		
		if(typeof TheLightbox != 'undefined') TheLightbox.closeit();
		//ReSe.log("Hidden form values: widgetID: " + ReSe.wI.value + "\n cityID: " + ReSe.cI.value + "\n longitude: " + ReSe.lo.value + "\n latitude: " + ReSe.la.value);
		if(typeof as != 'undefined') as.clearSuggestions();
		if((!ReSe.thD && ReSe.thO.parseChoiceSubmit) || (ReSe.thO.parseChoiceSubmit && forceSubmit)){
			ReSe.SF.submit();
		}
	},
	
	parseResult: function (json){	
		
		var self = this;
		var jso, lbC;		
		//ReSe.log("parseResult: " + json.MSG);
		var jso = json.OPTIONS;		
		if(typeof(json.LASTRESORTLUCENE) != 'undefined' && json.LASTRESORTLUCENE != null && json.LASTRESORTLUCENE){
			var lastResortLucene = true;
		}else{
			var lastResortLucene = false;
		}
		if(typeof(json.FORCECHOICESUBMISSION) != 'undefined' && json.FORCECHOICESUBMISSION != null && json.FORCECHOICESUBMISSION){
			var forceChoiceSubmission = true;
		}else{
			var forceChoiceSubmission = false;
		}
		switch(json.MSG){
			
			default: 
				
				//ReSe.log("Error: parseResult: not a valid option");
				window['ReSe'+this.thO.suffix].holdsubmit = false;
				break;
			
			case 'noResult':
				
				if(lastResortLucene){				
					//try Lucene, GeoCity and Google failed				
					window['ReSe'+this.thO.suffix].holdsubmit = false;
					this.selectString.value = $(this.thO.selectString + this.thO.suffix).value;
				}else{
					try{ 
						if(typeof(Lightbox) == "undefined")
		 				 throw "RegionalSearch requires Lightbox";			
					}catch(err){}
					//ReSe.log("parseResult: activating TheLightBox");					
					lbC = '<p class="regionalsearch-noresult" style="margin:0 0 10px 0;"><strong>' + self.getLabelNotFound() + ' "' + this.SW.value.stripTags().escapeHTML() + '"</strong></p>';
					
					if(this.thO.showNoResultLightbox){	
						TheLightbox = new Lightbox({identifier:"clickbox"+this.SF.id,type:"alert",onConfirm:"confirmfunction",height:'120',ok:self.getLabelTryAgain(),dialog:lbC});			
						TheLightbox.activate();
					}
					
					// don't submit yet, show the message
					window['ReSe'+this.thO.suffix].holdsubmit = true;					
				}				
				break;
				
			case 'oneResult':
			
				this.widgetID.value = jso[0].WIDGETID;
				this.cityID.value = jso[0].CITYID;
				this.longitude.value = jso[0].GEOX;
				this.latitude.value = jso[0].GEOY;
				this.basicRadius.value = jso[0].BASICRADIUS;
				
				// only one result, we show the result
				//ReSe.log("parseResult: submitting the form");
				window['ReSe'+this.thO.suffix].holdsubmit = false;
				
				break;
				
			case 'multiResult':
				try {
					if(typeof(Lightbox) == "undefined")
 				 		throw "RegionalSearch requires Lightbox";
				}catch(err){}
				/* TODO: create the list items "on the fly", so we can add in keyboard support to select the options */
								
				lbC = '<p class="regionalsearch-intro"><strong>' + self.getLabeMultipleMatches() + ' "' + this.SW.value.stripTags() + '"</strong></p>' +
					  '<p class="regionalsearch-pleaseselect" style="margin:10px 0 0 0;">' + self.getLabelPleaseSelect() + ':</p>';
				
				// Todo: removie inline styles	  
				lbC += '<ul class="bulletlist regionalsearch-multiple">';
					  
					for(var i = 0; i < jso.length; i++){
						lbC += '<li class="regionalsearch-result"><a href="#" onclick="javascript:parseChoice(\''+decodeURIComponent(jso[i].DS)+'\','+jso[i].WIDGETID+','+jso[i].CITYID+','+jso[i].GEOX+','+jso[i].GEOY+','+jso[i].BASICRADIUS+',ReSe'+this.thO.suffix+','+forceChoiceSubmission+');return false;"><span>'+decodeURIComponent(jso[i].DS)+'</span></a></li>';
					}				
				
				lbC += '</ul>';
				
				// moved tryagain outside the list
				lbC += '<div class="row buttons regionalsearch-tryagain"><div class="right"><a href="#" class="UIButton Button_Blue" onclick="javascript:tryAgain(ReSe);return false;"><span>'+self.getLabelTryAgain()+'</span></a></div></div>';
				
				//ReSe.log("parseResult: activating TheLightBox");
				TheLightbox = new Lightbox({identifier:"clickbox"+this.SF.id,type:"message",dialog:lbC});
				TheLightbox.activate();
				
				// don't submit the form yet
				window['ReSe'+this.thO.suffix].holdsubmit = true;
				
				break;
		
		}
		
			
	},
	
	checkWhereSearch: function(){
		var that = this;
		//ReSe.log("checkWhereSearch: field length: " + this.SW.value.length);
		if ((this.SW.value.length > 3 && this.lo.value == 0	&& this.wI.value == 0) || this.SW.value != this.sS.value && this.SW.value.length > 0) {			
				//if (this.sS != null) this.sS.value = '';
				//if (this.wI != null) this.wI.value = 0;
				//if (this.cI != null) this.cI.value = 0;
				//if (this.lo != null) this.lo.value = 0;
				//if (this.la != null) this.la.value = 0;
				//if (this.ba != null) this.bR.value = 0;
				
				//ReSe.log("checkWhereSearch: Ajax Request: " + this.thO.ResultEvent + " : " + encodeURI(this.SW.value));
				new Ajax.Request(this.thO.ResultUrl, {
					method: 'get',
					parameters: {event : this.thO.ResultEvent, s : encodeURI(this.SW.value)},
					asynchronous: false,
					onFailure: function(){
						//ReSe.log("checkWhereSearch: Ajax Failure");
						// Todo: replace with error handler
						window['ReSe'+that.thO.suffix].SW.removeClassName("loading");
					},
					onSuccess: function(transport, json){
						//ReSe.log("checkWhereSearch: Ajax Success");
						if (typeof json == 'object') {
							//ReSe.log("checkWhereSearch: JSON.MSG: " + json.MSG);
							window['ReSe'+that.thO.suffix].parseResult(json);
						}else{
							//ReSe.log("Error: checkWhereSearch: JSON is undefined!");
						}
						window['ReSe'+that.thO.suffix].SW.removeClassName("loading");
					}
				});					
		}else{
			
			// not a usable value, so continue submitting = regular submit
			this.holdsubmit = false;
			if(this.SW.value.length == 0){
				if (this.sS != null) this.sS.value = '';
				if (this.wI != null) this.wI.value = 0;
				if (this.cI != null) this.cI.value = 0;
				if (this.lo != null) this.lo.value = 0;
				if (this.la != null) this.la.value = 0;
				if (this.ba != null) this.bR.value = 0;
			}
			else{
				if (this.SW.value.length > 3){
					new Ajax.Request(this.thO.ResultUrl, {
						method: 'get',
						parameters: {event : 'geoCoding.updateHitCount', s : encodeURI(this.SW.value)},
						asynchronous: false,
						onFailure: function(){
						},
						onSuccess: function(transport, json){
						}
					});		
				}	
			}
		}	
	
	},

	parseAfterSelect: function (name,values){
		var name, values, info, suggestTemp; 
		var obj, cs;
		
		
		cs='';
		this.suffix = this.options.suffix;
		
		obj = new Object();
		obj.id = values;
		
		suggestTemp = name;
    	suggestTemp = suggestTemp.replace('<br>', ', ');
    	suggestTemp = suggestTemp.stripTags();
		
		var s = suggestTemp.split(',');
				
		obj.value 	= s[0];
		obj.info 	= s[1];
		
		//ReSe.log("parseAfterSelect: " + obj.id);
		if(typeof window['ReSe'+this.suffix] != 'undefined'){
			cs = window['ReSe'+this.suffix];
		}else{
			return false;
		}	
		
		var p = obj.id.split('|');
		
		if (typeof obj.info != 'undefined' && obj.info.length>0) {
			cs.SW.value = obj.value.trim() + ', ' + obj.info.trim();
		} else {
			cs.SW.value = obj.value.trim();
		}
		
		//ReSe.log("currentsearch.SW.value: " + obj.value);
		cs.sS.value = cs.SW.value;
		if(p[0] != 0 && p[1] == 0 && p[2] == 0 && p[5] == 0){
			//city ID, basic radius and widgetslistID2 is not available, but widgetslistID1 is		
			cs.wI.value = p[0];
		}else{
		cs.wI.value = p[1];
		}
		cs.cI.value = p[2];
		cs.lo.value = p[3];
		cs.la.value = p[4];
		cs.bR.value = p[5];
		if(typeof window['ReSeTL'] != 'undefined'){	
			cstl = window['ReSeTL'];
			if (typeof obj.info != 'undefined' && obj.info.length>0) {
				cstl.SW.value = obj.value.trim() + ', ' + obj.info.trim();
			} else {
				cstl.SW.value = obj.value.trim();
			}			
			if(p[0] != 0 && p[1] == 0 && p[2] == 0 && p[5] == 0){
				//city ID, basic radius and widgetslistID2 is not available, but widgetslistID1 is		
				cstl.wI.value = p[0];
			}else{
				cstl.wI.value = p[1];
			}	
			cstl.cI.value = p[2];	
			cstl.lo.value = p[3];
			cstl.la.value = p[4];
			cstl.bR.value = p[5];	
		}	
		
		obj = null;
		
	},
	
	// 
	tryAgain: function (){
		//ReSe.log("tryAgain");
		ReSe.SW.clear().focus();
		if(typeof as != 'undefined') as.clearSuggestions();
		if(typeof TheLightbox != 'undefined') TheLightbox.closeit();
	},
	
	// autosuggest binder
	bindBox: function (el){
		var o = this.thO.AutoSuggest; // el to activate autosuggest on
		//ReSe.log("bindBox active on " + el.id);
		if(typeof Autocomplete != 'undefined') {
			//ReSe.log("bindBox: starting bsn.AutoSuggest");
			try {
				// as will be used public
				as = new Autocomplete(el, o);
			} 
			catch (err) {
				//ReSe.log("Error: bsn.AutoSuggest: " + err.message);
			}
		} else{
			//ReSe.log("Error: bsn.AutoSuggest is undefined");
		}	
	}
});

if(document.observe){
	document.observe('dom:loaded', function() {		
		var startRegionalSearch = new domFunction(function(){
		     var DoRegionalSearch = new RegionalSearch('RegionalSearch');
		}, {
		    'SearchForm': 'id'
		});
	});
}
