/* Class SearchEngine */
var SearchEngine = function() {
	// declare object variables
	this.sSearchParam 	= null;
	this.sParamsType 	= null;
	this.formParam		= { 'form' : {'id' : 'queryForm' , 'name' : 'queryForm'} , 'queryField' : 'query' , 'hiddenField' : ['nCode' , 'sFlag'] };
	this.nMinChar 		= (typeof(AUTOCOMPLETE_PARAMS['search']['minChar']) == "undefined") ? 2 : AUTOCOMPLETE_PARAMS['search']['minChar'];
	this.nCpLength 		= 5;
	this.nMinNumber  	= (typeof(AUTOCOMPLETE_PARAMS['search']['minNumeric']) == "undefined") ? 3 : AUTOCOMPLETE_PARAMS['search']['minNumeric'];
	this.aAjax 			= {'async' : true , 'method' : true , 'data' : true , 'dataType' : true};
	this.reEscape 		= new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', ' ' , '\\'].join('|\\') + ')', 'g');
	this.fieldsToUpdate = [];
	var _searchEngine	= this;
	
	// initialise la classe TestAjax : on passe des paramètres sous forme de string ou array ou object
	this.init = function (oParams) {

		// if debug, we check all Form and fields
		if (DEBUGJS) {
			// check params setted
			if(!_searchEngine.checkParamsObj(oParams , 'ajax')) {
				_searchEngine.showProblemFile('ajax_p');
				return false;
			}
			else if (!_searchEngine.checkFormFields()) {
				_searchEngine.showProblemFile('html_form');
				return false;
			}
		}
		// set fields to update in form
		if (typeof(oParams['fieldsToUpdate']) != 'undefined' && oParams['fieldsToUpdate'] != '') {
			this.fieldsToUpdate['query'] 		= oParams['fieldsToUpdate'][0];
			this.fieldsToUpdate['nCode'] 		= oParams['fieldsToUpdate'][1];
			this.fieldsToUpdate['sFlag'] 		= oParams['fieldsToUpdate'][2];
			this.fieldsToUpdate['mssg'] 		= oParams['fieldsToUpdate'][3];
			this.fieldsToUpdate['infos_bulle'] 	= oParams['fieldsToUpdate'][4];
		}
		else {
			this.fieldsToUpdate['query'] 		= 'query';
			this.fieldsToUpdate['nCode'] 		= 'nCode';
			this.fieldsToUpdate['sFlag'] 		= 'sFlag';
			this.fieldsToUpdate['mssg'] 		= 'mssg';
			this.fieldsToUpdate['infos_bulle'] 	= 'infos_bulle';	
		}
	};
	
	// define if is object
	this.defined = function (obj){
		return typeof obj == '"undefined"' || !obj ? false : true;
	};
	
	// define if is null
	this.isNull	= function (obj){
		return typeof valeur == 'object' && valeur == null ? true : false;
	};
	
	// verify type
	this.checkType = function (obj){
		if (!_searchEngine.defined(obj)) {
				return false;
		}
		if (obj.htmlElement) {
			return 'tagNode';
		}
		var type = typeof obj;
		if (type == 'object' && obj.nodeName) {
			switch (obj.nodeType) {
				case 1: return 'tagNode';break;
				case 3: return ('/\S/').test(obj.nodeValue) ? 'textNode' : 'whiteSpace';break;
			}
		};
		if (type == 'object' || type == 'function') {
			switch (obj.constructor) {
				case Array 		: return 'array';break;
				case RegExp 	: return 'regexp';break;
			};
			if (typeof(obj.length) == 'number') {
				if (obj.item)	{return 'collection';}
				if (obj.callee){return 'arguments';}
			}
		}
		return type;
	};
	
	// check all parameters
	this.checkParamsObj = function (oParams , sKey) {
		// test if object
		if (_searchEngine.checkType(oParams) == 'object') {
			// test a specific key of global array
			if (sKey != null && typeof(oParams[sKey]) != "undefined") {
				// loop on each key to test if exists
				for (var fx in _searchEngine.aAjax) {
					// if param to test
					if (_searchEngine.aAjax[fx]) {
						// if one key is ko, return false
						if (typeof(oParams[sKey][fx]) == "undefined") {
							return false;
						}
					}
				}
				return true;
			}
		}
		return false;
	};
	
	// check all fields in form
	this.checkFormFields = function () {
		// test if id or name are set
		if ( $('#'+_searchEngine.formParam['form']['id']) == "undefined" || $('#'+_searchEngine.formParam['form']['name']) == "undefined") {
			return false;
		}
		// test if query field is set
		if ($('#'+_searchEngine.formParam['queryField']) == "undefined") {
			return false;
		}
		// test if all hidden fields are set
		if (_searchEngine.checkType(_searchEngine.formParam['hiddenField']) == 'object') {
			for (var i =0 ; i < _searchEngine.formParam['hiddenField'].length;i++) {
				if ($('#'+_searchEngine.formParam['hiddenField'][i]) == "undefined") {
					return false;
				}
			}
		}
		else if ($('#'+_searchEngine.formParam['hiddenField']) == "undefined") {
			return false;
		}
		// return true if ok
		return true;
	};
	
	// test value entered 
	this.checkEnteredDatas = function(sValue) {
		// if numeric or string
		if (isNaN(sValue) == false) {
			var sEval = sValue.length+' == '+_searchEngine.nCpLength;
		}
		else {
			var sEval = sValue.length+' >= '+_searchEngine.nMinNumber;
		}
		// test value : numeric or string
		if (eval(sEval)) {
			return true;
		}
		else {
			return false;
		}	
	};
	
	// format les noms de lieu
	this.formatResult = function(value) {
		return value.replace(SearchEngine.reEscape, '');
	};

	// verifie le contenu saisi 
	this.processForm = function() {
			
		var bSubmit = false;
		var aSendData = [];		
		
		aSendData['query'] 	= $('#query').val();
		aSendData['nCode'] 	= $('#'+this.fieldsToUpdate['nCode']).val();
		aSendData['sFlag'] 	= $('#'+this.fieldsToUpdate['sFlag']).val();

		if (AUTOCOMPLETE_PARAMS['modeLight']) {
			if (aSendData['nCode'] != '' && isNaN(aSendData['nCode']) == false) {
//				_searchEngine.callAjaxMeteo(aSendData , AUTOCOMPLETE_PARAMS['listFile'][MODE] , AUTOCOMPLETE_PARAMS['ajax']);
				_searchEngine.callAjaxMeteo(aSendData , AUTOCOMPLETE_PARAMS['listFile'] , AUTOCOMPLETE_PARAMS['ajax']);
			}
			else if (isNaN(aSendData['query']) == false && aSendData['query'].length == 5) {
//				_searchEngine.callAjaxMeteo(aSendData , AUTOCOMPLETE_PARAMS['listFile'][MODE] , AUTOCOMPLETE_PARAMS['ajax']);
				_searchEngine.callAjaxMeteo(aSendData , AUTOCOMPLETE_PARAMS['listFile'] , AUTOCOMPLETE_PARAMS['ajax']);
			}
			else {
				_searchEngine.showProblemFile('html_field');
				return false;
			}
		}
		else if (aSendData['nCode'] != '' && isNaN(aSendData['nCode']) == false) {
//			_searchEngine.callAjaxMeteo(aSendData , AUTOCOMPLETE_PARAMS['listFile'][MODE] , AUTOCOMPLETE_PARAMS['ajax']);
			_searchEngine.callAjaxMeteo(aSendData , AUTOCOMPLETE_PARAMS['listFile'] , AUTOCOMPLETE_PARAMS['ajax']);
		}
		else if (_searchEngine.checkEnteredDatas(aSendData['query']) && isNaN(aSendData['query']) == false) {
//			_searchEngine.callAjaxMeteo(aSendData , AUTOCOMPLETE_PARAMS['listFile'][MODE] , AUTOCOMPLETE_PARAMS['ajax']);
			_searchEngine.callAjaxMeteo(aSendData , AUTOCOMPLETE_PARAMS['listFile'] , AUTOCOMPLETE_PARAMS['ajax']);
		}
		else if (_searchEngine.checkEnteredDatas(aSendData['query'])) {
//			_searchEngine.callAjaxMoteur(aSendData , AUTOCOMPLETE_PARAMS['searchFile'][MODE]);
			_searchEngine.callAjaxMoteur(aSendData , AUTOCOMPLETE_PARAMS['searchFile']);
		}
		else {
			_searchEngine.showProblemFile('html_field');
		}
	};
	
	/**
	* format les données du 3eme champ retournées en json (specially for meteo
	*/
	this.splitCode = function(sData) {
		var aSplit, aTmp, sSuffix;
		aTmp = [];
		sSuffix = '';
		aSplit = sData.split(new RegExp("(#)+", "g"));
		switch (aSplit[0]) {
			case 'plage' :	sSuffix = ' , <span style="color:#3399FF;"><b>littoral</b></span>';break;
			case 'montagne' :	sSuffix = ' , <span style="color:#3399FF;"><b>montagne</b></span>';break;
			case 'region' :	sSuffix = ' <span style="color:#3399FF;"><b>r&eacute;gion</b></span> ';break;
			case 'continent' :	sSuffix = ' <span style="color:#3399FF;"><b>continent</b></span> ';break;
			case 'dom-tom' :	sSuffix = ' , <span style="color:#3399FF;">Dom-Tom</span>';break;
			default  :	break;
		}
		if(!!(window.attachEvent && !window.opera)) {
			aTmp['flag']  	= (typeof(aSplit[0]) == "undefined") ? "" : aSplit[0];
			aTmp['code'] 	= (typeof(aSplit[1]) == "undefined") ? "" : aSplit[1];
			aTmp['place']  	= ((typeof(aSplit[2]) == "undefined") ? "" : aSplit[2]);
			aTmp['cont']  	= (typeof(aSplit[3]) == "undefined") ? "" : aSplit[3];	
		}
		else {
			aTmp['flag']  	= (typeof(aSplit[0]) == "undefined") ? "" : aSplit[0];
			aTmp['code'] 	= (typeof(aSplit[2]) == "undefined") ? "" : aSplit[2];
			aTmp['place']  	= ((typeof(aSplit[4]) == "undefined") ? "" : aSplit[4]);
			aTmp['cont']  	= (typeof(aSplit[6]) == "undefined") ? "" : aSplit[6];		
		}
		if (aSplit[0] == 'monde') {
			sSuffix += ' , <span style="color:#000;"><strong>'+aTmp['cont']+'</strong></span>';
		}
		aTmp['detail']  = '('+aTmp['place'] + sSuffix+')';
		return aTmp;
	},
	
	// get Ajax File
	this.callAjaxMoteur = function (aParam , sFile ) {
		if (typeof(sFile) != "undefined") {
			$.ajax({
			'type'		: 'GET',
			'url'		: sFile,
			'async'		: true, 
			'data'		: 'rtype=kw&dtd=2.0&id=1&cbf=SearchEngine.callBackAutcomplete&rdata='+aParam['query'],
			'dataType'	: 'jsonp',
			'jsonp'		: '',
			'success'	: function (oDatas , sTextStatus) {
							_searchEngine.callBackAutcomplete(oDatas);
						},
			'error'		: function(XMLHttpRequest, textStatus, errorThrown){_searchEngine.showProblemFile(textStatus);}
			});
		}
		else {
			_searchEngine.showProblemFile('ajax_file');
		}
	};
	
	// function called by DOP MOTEUR proxy 
	this.callBackAutcomplete = function(oDatas) {
		// test if we get data for search query		
		if (oDatas[3] != '') {
			var nLength = oDatas[1].length;
			if (nLength > 1) {
				var aTmp = [];
				var sInfoBulle = sFormatName = '';
				for (var i=0;i<nLength;i++) {
					aTmp = _searchEngine.splitCode(oDatas[3][i]);
					sFormatName = _searchEngine.formatResult(oDatas[1][i]);
					sFormatName = sFormatName.toLowerCase();
					sInfoBulle += '<a href="/previsions/' +aTmp['flag'] +'_'+aTmp['code']+'_'+sFormatName+'.html" >' + oDatas[1][i] + ' ' + aTmp['detail']+'</a><br/>';
				}
				sInfoBulle += '<a href="#" class="close" onclick="$(\'#infos_bulle\').hide()" title="fermer"></a>';
				$('#mssg').html(sInfoBulle);
				$('#infos_bulle').show();
			}
			else {
				var aSendData = aTmp = [];
				aTmp = _searchEngine.splitCode(oDatas[3][0]);
				aSendData['query'] = oDatas[1];
				aSendData['nCode'] = aTmp['code'];
				aSendData['sFlag'] = aTmp['flag'];
//				_searchEngine.callAjaxMeteo(aSendData , AUTOCOMPLETE_PARAMS['listFile'][MODE] , AUTOCOMPLETE_PARAMS['ajax']);
				_searchEngine.callAjaxMeteo(aSendData , AUTOCOMPLETE_PARAMS['listFile'] , AUTOCOMPLETE_PARAMS['ajax']);
			}
		}
		else {
			_searchEngine.showProblemFile('json_result' , oDatas[0]);
		}
	};
	
	// get Ajax File of Meteo in order to generate page
	this.callAjaxMeteo = function (aParam , sFile , aAjax) {
		if (typeof(sFile) != "undefined" && typeof(aAjax) != "undefined") {
			$.ajax({
			'type'		: aAjax.method,
			'url'		: sFile,
			'async'		: aAjax.async, 
			'data'		: 'query='+aParam['query']+'&nCode='+aParam['nCode']+'&sFlag='+aParam['sFlag'],
			'dataType'	: aAjax.dataType,
			'success'	: function (oDatas , sTextStatus) {
							if (typeof(oDatas.status) != undefined) {
								if (oDatas.status == 'MULTIPLE') {
									var sInfoBulle = '';	
									var nLength = oDatas.towns.length;
									if (nLength > 10) {
										nLength = 10;
									}
									for (var i=0;i<nLength;i++) {
										sInfoBulle += '<a href="/previsions/'+oDatas.towns[i].flag+'_'+oDatas.towns[i].code+'_'+oDatas.towns[i].nom+'.html" ><strong>' + oDatas.towns[i].nom + '</strong> (' + oDatas.towns[i].cp +')</a><br/>';
									}								
									sInfoBulle += '<a href="#" class="close" onclick="$(\'#infos_bulle\').hide()" title="fermer"></a>';
									$('#mssg').html(sInfoBulle);
									$('#infos_bulle').show();
								}
								// case of redirect on generated page
								else if (oDatas.status == 'REDIRECT') {
									window.location.href = oDatas.redirect;
								}
								// case of error
								else {
									_searchEngine.showProblemFile('json_result' , oDatas.msg);
								}
							}
						},
			'error'		: function(XMLHttpRequest, textStatus, errorThrown){_searchEngine.showProblemFile(textStatus);}
			});
		}
		else {
			_searchEngine.showProblemFile('ajax_file');
		}
	};
	
	// show error
	this.showProblemFile = function(sError , sSearch) {
		var sInfoBulle = '';
		if ( (typeof(sError) != "undefined" && sError != null) && typeof(MSG_CLASS[sError]) != "undefined" )  {
			sInfoBulle = MSG_CLASS[sError]+'<br/>';
		}
		else {
			sInfoBulle = sError+'<br/>';
		}
		if (typeof(sSearch) != 'undefined') { sInfoBulle = '<b>'+sSearch+'</b><br/>'+sInfoBulle; }
		// update div with info bulle
		//sInfoBulle += '<a href="#" class="close" onclick="document.getElementById(\''+_searchEngine.fieldsToUpdate['mssg']+'\').innerHTML = \'\';document.getElementById(\''+_searchEngine.fieldsToUpdate['infos_bulle']+'\').style.display = \'none\';" title="fermer"></a>';
		sInfoBulle += '<a href="#" class="close" onclick="document.getElementById(\''+_searchEngine.fieldsToUpdate['mssg']+'\').innerHTML = \'\';$(\'#'+_searchEngine.fieldsToUpdate['infos_bulle']+'\').hide();" title="fermer"></a>';
		$('#'+_searchEngine.fieldsToUpdate['mssg']).html(sInfoBulle);
		$('#'+_searchEngine.fieldsToUpdate['infos_bulle']).show();
	};
};
