var LETTERS = "áéíóúÁÉÍÓÚabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var LETRAS = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ";
var LETRAS_AMADEUS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var DIGITS = "0123456789";
var ZIP_VALID = DIGITS;
var PHONE_VALID = DIGITS + "+- ()";
var PVP = DIGITS + ".,";
var MAIL_VALID = LETTERS + DIGITS + ";._@-";
var SELECTED = "Xx";
var INVALID_FOR_TEXT = "!·\\\"'$%&=?¿|@#`+*^[]{}´¨_<>;";
var INVALID_FOR_URL = "!·\\\"'$%()¿|@#`+*^[]{}´¨<>;";
var INVALID_FOR_MAIL = "!·\\\"'$%()¿|#`+*^[]{}´¨<>;";
var INVALID_NAME = "!·\\\"'$%()¿|#`+*^[]{}´¨<>:áéíóúÁÉÍÓÚäëïöüÄËÏÖÜâêîôûÂÊÎÔÛ";
var INVALID_DATE = LETRAS+"!·\\\"'$%()¿|#`+*^[]{}´¨<>:áéíóúÁÉÍÓÚäëïöüÄËÏÖÜâêîôûÂÊÎÔÛ";
var INVALID_TIME = "&/€!·\\\"'$%()¿|#`+*^[]{}´¨<>;áéíóúÁÉÍÓÚäëïöüÄËÏÖÜâêîôûÂÊÎÔÛ ";
var INVALID_AMADEUS = "áéíóúÁÉÍÓÚàèìòùÀÈÌÒÙäëïöüÄËÏÖÜâêîôûÂÊÎÔÛ`";
var INVALID_NONE="";
var INVALID_NUMBER = ":+-()" + LETRAS + INVALID_FOR_TEXT+"ºª€¬¡ç*/";
var DATE_VALID = DIGITS + "/";

function strtr(cadena, desde, hasta) {
	cadena = cadena.replace(/^\s*|\s*$/g,"");
	for (var i=cadena.length-1; i>=0; i--) {
		var index = desde.indexOf(cadena.charAt(i));
		if (index != -1) {
			var ch = "";
			if (hasta.length > index) {
				ch = hasta.charAt(index);
			}
			if (i==cadena.length-1) {
				cadena = cadena.substring(0,i)+ch;
			} else {
				cadena = cadena.substring(0,i)+ch+cadena.substring(i+1);
			}
		}
	}
	return(cadena);
}

function inputCHK(value,ctrStr){
	var ok = inputCTR(value,ctrStr);
	if(!ok){
		return(inputCLR(value,ctrStr));
	}else{
		return(value);
	}
}

function getControlStr(ctrStr){
	var str = "";
	switch(ctrStr){
		case 'nombre':
			str = INVALID_NAME;
			break;
		case 'fecha':
			str = INVALID_DATE;
			break;
		case 'hora':
			str = INVALID_TIME;
			break;
		case 'url':
			str = INVALID_FOR_URL;
			break;
		case 'email':
			str = INVALID_FOR_MAIL;
			break;
		case 'amacmd':
			str = INVALID_AMADEUS;
			break;
		case 'number':
			str = INVALID_NUMBER;
			break;
		case 'none':
			str = INVALID_NONE;
			break;
		default:
			str = INVALID_FOR_TEXT;
	}
	return str;
}

function inputCTR (str,ctrStr){
	var cadena = getControlStr(ctrStr);
	if(cadena!=""){
		if (str.length > 0){
			for (c = 0; c < str.length; c++){
  			if (cadena.indexOf (str.charAt (c)) != -1){
					return false;
  			}
 			}
		return true;
		}
	}
}

function inputCLR(str,ctrStr){
	var cadena = getControlStr(ctrStr);
	for (c = str.length-1; c >= 0; c--){
		for(i=0;i<cadena.length;i++){
			if(cadena.indexOf(str.charAt(c)) != -1){
				str = str.substring(0,c)+str.substring(c+1);
			}
		}
	}
 	return(str);
}

//Objeto utilizado para el manejo de selbox
function selectbox(code, field, options) {
	var urlAux = document.location.href;
	urlAux = urlAux.substring(0, urlAux.indexOf("/",8));
	if (urlAux.indexOf("barceloviajes") != -1 || urlAux.indexOf("barcelobusiness") != -1) {
		this.url = urlAux + this.url;
	} else {
		var index = urlAux.length + 1;
		urlAux = document.location.href;
		this.url = urlAux.substring(0, urlAux.indexOf("/", index)) + this.url;
	}
	this.inputcode = code;
	this.input = field;
	this.input.setAttribute('autocomplete', 'off');
	this.selBoxName = options.selBoxName;
	this.xmlUrl = options.xmlUrl;
	// Incrustamos la capa y el iframe
	if (!$("selBoxDIV")) {
		new Insertion.Before(this.input.id, '<div id="selBoxDIV" style="z-index:551;position:absolute;display:none;background-color:#fff;border:1px solid #000000;color:#000;"/>');
		if (document.all) {
			new Insertion.Before(this.input.id, '<IFRAME id="selBoxBG" style="position:absolute;visibility:visible;display:none;z-index:550;" />');
		}
		var pos = "absolute";
		if(detectBrowser() == "fx15" || detectBrowser() == "fx10" || detectBrowser()=="op"){
			pos = "fixed";
		}
		$("selBoxDIV").style.position = pos;
	}
	this.target = $("selBoxDIV");
	if (document.all) {
		this.targetBG = $("selBoxBG");
	}
	//this.timerImg('off');
	this.onComplete = this.response;
	this.onChange = options.onChange;
	field.onkeyup = this.keyup.bindAsEventListener(this);
	field.onfocus = this.focus.bindAsEventListener(this);
	field.onblur = this.exit.bindAsEventListener(this);
	// Traspasamos la cookie
	var ckval = getCookie("session_mem");
	delCookie("session_mem","/paginas/jspgen/");
	setCookie("session_mem", ckval, null,"/paginas/jspgen/");	
};

selectbox.prototype = {
	selBoxName : null,					//Nombre del objeto
	target : null,						//div que pintamos
	targetBG : null,					//iframe background para pasar por encima de los selects
	input : null,						//Campo de texto
	inputcode : null,					//Codigo, oculto
	values : null,						//Array de objetos con la parte de la petición filtrada
	callValues : new Array(),			//Array de objetos con la respuesta de la petición
	url : "/jspgen/ajax/selectbox.jsp", //Url de petición xml
	xmlUrl : null,						//Url del xml de información
	cursel : 0,							//Indice para controlar en que elemento (dentro del div) seleccionado cuando vamos por las teclas
	prevsel : 0,						//Elemento (div) previo selecionado (para cambiar el class)
	sboxminwidth : -1, 					//Indica si iframe bacground tiene límite (-1 sin limite width)
	stop : true,						//Controla cuando podemos pulsar sobre el input
	lastkey : null,						//Indica el código de la última tecla pulsada
	adapt : true,						//Indica si el div debe adaptarse al tamaño del document que lo contiene
	filtro: null, 						//Indica código de filtro adicional
	nofColor: "#000000",				//Color de error
	onComplete: null,					//Ajax onComplete call
	onChange: null,						//Función a llamar en el onChange del código
	
	timerImg: function(action) {
		switch(action){
			case 'on' :
				this.input.style.backgroundImage = 'url(/jsgen/imgs/selectbox/loader_ajax_on.gif)';
				break;
			case 'off' :
				this.input.style.backgroundImage = 'url(/jsgen/imgs/selectbox/loader_ajax_off.gif)';
				break;
			case 'out' :
				this.input.style.backgroundImage = 'url()';
				break;
		}
		var tam = this.input.offsetWidth - 20;//(tamaño de la imagen +2px para que no quede pegado al input)
		this.input.style.backgroundRepeat = "no-repeat";
		this.input.style.backgroundPosition = tam+"px 1px";		
	},
	
	clear: function() {
		if (this.target!=null){this.target.style.display = 'none';this.target.innerHTML = "";}
		if (this.targetBG){this.targetBG.style.display = 'none';}
		this.callValues = new Array();
		this.values = null;
		//this.timerImg('off');
		this.timerImg('out');
	},
	
	focus: function() {
		selBoxAct = this.selBoxName;
	},
	
	change: function() {		
		if (this.onChange) {
			eval(this.onChange+"();");
		}
	},
	
	exit: function() {
		if (this.cursel != -1) {
			if ((this.values != null) && (this.values.length > 0)) {
				this.putValue(this.cursel);
			}
			if (this.target!=null){this.target.style.display = 'none';this.target.innerHTML = "";}
			if (this.targetBG){this.targetBG.style.display = 'none';}
		}
		if (this.inputcode.value != '') {
			this.timerImg('out');
		}
	},
	
	comprobar: function() {
		// Si tenemos código (han seleccionado un elemento) empezamos de nuevo
		if (this.inputcode.value != "") {
			this.inputcode.value = "";
			if ((this.lastkey == 9) ||(this.lastkey > 46)) {
				this.input.value = String.fromCharCode(this.lastkey).toLowerCase();
			} else {
				this.input.value = "";
				this.clear();
			}
			this.change();
		}
		if (this.input.value.length < 3) {
			this.clear();
			return;
		}
		if ((this.input.value.length == 3) && (this.input.value.indexOf(" ") == -1)) {
			this.runCall();
		} else if (this.input.value.length > 3) {
			var index = this.input.value.lastIndexOf(" ");
			if ((this.input.value.length - index - 1) == 3) {
				this.runCall();
			} else {
				this.filtra();
			}
		}
	},
	
	putValue: function(index) {	
		if (index == null) index = this.cursel;
		if ((index == -1) || (this.values == null)) return;
		this.input.value = this.values[index].str;
		this.inputcode.value = this.values[index].code;
		this.change();
	},

	chgRow: function(index) {
		//alert("chgRow: "+index);
		if (this.target.childNodes.length > 0) {
			if (this.prevsel >= 0) {
				var prev = this.target.childNodes[this.prevsel];
				prev.style.backgroundColor = "";
			}
			if (index >= 0){
				if(this.target.childNodes.length > 0) {
					var cur = this.target.childNodes[index];
					cur.style.backgroundColor = "#ffff99";
//					alert(findPosY(cur));
//					this.target.moveTo(findPosX(cur),findPosY(cur));
				}
				this.prevsel = index;
			}
		}
	},
	
	runCall: function(texto) {
		window.status = "buscando...";
		//Activar busqueda
		this.timerImg('on');
		var timestamp = new Date();
		var _url = this.url+"?xml="+this.xmlUrl+"&text="+((texto==null)?this.input.value:texto);
		if (this.filtro != null) {
			_url += "&filtro="+this.filtro;
		}
		_url += "&selBoxName="+this.selBoxName;
		_url += "&time="+timestamp.getTime();
		//alert(_url);
		ajax(_url, {onComplete: this.onComplete}); 
	},
	
	response: function(request) {
		window.status = "";
		var cont = 0;
		this.values = new Array();
		this.callValues = new Array();
		//alert(request.responseText);
		var xmldoc = request.responseXML;
		var selBoxName = request.getResponseHeader("selBoxName");
		var results = xmldoc.getElementsByTagName('data')[0];
		//Creamos el objeto JS
		if (results.hasChildNodes) {
			for(var i=0;i<results.childNodes.length;i++){
				var elem = results.childNodes[i];
				if(elem.attributes){
					var data = new Object();
					var str = _getAttribute(elem,"nom");
					data.str = str;
					var codigo = _getAttribute(elem,"cod")
					data.code = codigo;
					data.sch = eval(selBoxName+".normaliza(codigo+' '+str);");
					eval(selBoxName+".callValues[cont] = data;");
					//data.sch = this.normaliza(codigo+' '+str);
					//this.callValues[cont] = data;
					cont ++;
				}
			}
		}
		eval(selBoxName+".filtra();");
		eval(selBoxName+".timerImg('out');");
		//this.filtra(selBoxName);
		//desactivar busqueda
		//this.timerImg('off');
	},

	normaliza: function(texto) {
		texto = texto.toLowerCase();
		texto = strtr(texto, "àáäçèëéìïíñòóöùúü -',_`¨´\"()","aaaceeeiiinooouuu| ");
		return('|'+texto+'|');
	},

	filtra: function() {
		var cont = 0;
		this.values = new Array();
		if (this.callValues.length > 0) {
			var palabras = new Array();
			var texto = this.normaliza(this.input.value);
			var index = texto.indexOf("|",1);
			var i = 0;
			while (texto != "|") {
				var palabra = texto.substring(0, index);
				palabras[i] = palabra;
				i++;
				texto = texto.substring(index);
				index = texto.indexOf("|",1);
			}		
			for (var i=0;i<this.callValues.length;i++) {
				var ok = true;
				for (var j=0; j<palabras.length; j++) {
					if (this.callValues[i].sch.indexOf(palabras[j]) == -1) {
						ok = false;
						break;
					}
				}
				if (ok) {
					this.values[cont] = this.callValues[i];
					cont++;
				}
			}
			window.status = "Listo. regs "+this.callValues.length+"-"+this.values.length;
			if (this.values.length == 0) {
				this.values = null;
				this.clear();				
				this.input.style.color = this.nofColor;
			} else {
				this.input.style.color = "#000000";
				this.cursel = 0;
				this.prevsel = 0;
				if ((this.input.name != null) && ((selBoxAct == null) || (selBoxAct != this.selBoxName))) {
					this.putValue();
				} else {
					this.show();
					this.chgRow(0);
				}
			}
		} else {
			this.values = null;
			this.clear();				
			this.input.style.color = this.nofColor;
		}
	},

	show: function(){
		html = "";
		for (var i=0;i<this.values.length;i++) {
			html += '<div style="width:100%;" onmousedown="'+this.selBoxName+'.msDown(\''+i+'\');" ';
			html += 'onmouseover="'+this.selBoxName+'.msOver(\''+i+'\')"';
			html += 'onmouseout="'+this.selBoxName+'.msOut()">';
			html += '<span="color:#000;font-size: 11px;"><nobr>&nbsp;&nbsp;'+this.values[i].str+'&nbsp;</nobr></span>';
			html +=  '</div>';
		}
		//alert(html);
		var direction = "right";
		this.target.style.width = 'auto';
		this.target.style.height = 'auto';
		this.target.innerHTML = html;
		var x = findPosX(this.input);
		var y = findPosY(this.input) + this.input.offsetHeight + 1;
		this.target.style.top= y + 'px';
		this.target.style.left= x + 'px';
		this.target.style.display = 'block';
		// Si estamos en la 2a mitad del documento y el tamaño del div es mayor que el campo lo habrimos al reves
		if ((this.target.clientWidth > this.input.offsetWidth) && (x > (document.body.clientWidth / 2))) {
			x = x + this.input.offsetWidth - this.target.clientWidth;
			this.target.style.left = x + 'px';
			direction = "left";
		}
		if (this.adapt) {
			if (((x + this.target.clientWidth) > document.body.clientWidth) ||
				((y + this.target.clientHeight) > document.body.clientHeight)) {
				this.target.style.overflow = 'auto';
			} else {
				if (this.target.style.overflow) {		
					this.target.style.overflow = 'visible';
				}
			}
			if ((x + this.target.clientWidth) > document.body.clientWidth) {
				this.target.style.width = document.body.clientWidth - x;
			}
			if ((y + this.target.clientHeight) > document.body.clientHeight) {
				this.target.style.height = document.body.clientHeight - y;
				if (direction = "left") {
					this.target.style.left = (x-17) + 'px';
				}
			}
		}
		//Pintamos background iframe
		if (this.targetBG) {this.targetBG.style.display = 'inline';}
		if (this.sboxminwidth > this.target.offsetWidth) {
			if (this.targetBG) {this.targetBG.style.width = this.sboxminwidth;}
			this.target.style.width = this.sboxminwidth;
		} else {
			if (this.targetBG) {this.targetBG.style.width = this.target.offsetWidth;}
		}
		if (this.targetBG) {
			this.targetBG.style.height = this.target.offsetHeight;
			this.targetBG.style.top = this.target.style.top;
			this.targetBG.style.left = this.target.style.left;
			this.targetBG.style.zIndex = this.target.style.zIndex -1;
		}
	},

	msDown: function(index) {
		this.cursel = index;
		this.putValue(index);
		this.clear();
		this.input.focus();
	},

	msOut: function() {
		this.cursel = -1;
		this.chgRow(-1)
	},

	msOver: function (index) {
		this.cursel = index;
		this.chgRow(this.cursel);
	},

	keyup: function(e) {
		var pK = document.all? window.event.keyCode:e.which;
		this.keypressed(pK);
	},

	keypressed: function(keycode) {
		this.lastkey = keycode;
		//Movemos el cursor
		switch (keycode){
			case LEFT:
			case UP:
				if (this.values) {this.cursel--;if (this.cursel<0){this.cursel=0;}this.chgRow(this.cursel)};
				break;
			case RIGHT:
			case DOWN:
				if (this.values) {this.cursel++;if (this.cursel>=this.values.length){this.cursel=this.values.length-1;}this.chgRow(this.cursel)};
				break;
			case ESC:
				this.inputcode.value = "";
				this.input.value = "";
				this.clear();
				this.change();
				break;
			case ENTER:
				if ((this.values) && (this.values.length>0)){this.putValue(this.cursel);this.clear();}
				break;
//Falta ver diferencia entre ENTER y TAB				
			case TAB:
//				if (this.values && this.cursel>=0 && this.cursel<this.values.length){this.putValue(this.cursel);this.clear();}
			case ALT:
			case SHIFT:
				break;
			default:
				this.putValue(-1);
				this.comprobar();
		}
	}
}

function findPosX(obj){
	var curleft = 0;
	if (obj.offsetParent){
		while (obj.offsetParent){
			curleft += obj.offsetLeft
      obj = obj.offsetParent;
		}
	}else if (obj.x)
		curleft += obj.x;
		return curleft;
}

function findPosY(obj){
	var curtop = 0;
  if (obj.offsetParent){
		while (obj.offsetParent){
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}else if (obj.y)
  	curtop += obj.y;
		return curtop;
}

var ESC=27;var DEL=8;var TAB=9;var ALT=18;var UP=38;var DOWN=40;var LEFT=37;var RIGHT=39;var ENTER=13;var SHIFT=16;
var selBoxAct = null;

/*function extrAction(cadena, action) {
	var resp = "";
	if(cadena){
		var index = cadena.toLowerCase().indexOf(action);
		if (index != -1) {
			var index2 = cadena.indexOf("=", index)+1;
			while (cadena.charAt(index2) == " ") index2++;
			var comilla = cadena.charAt(index2);
			var index3 = cadena.indexOf(comilla, index2+1);
			resp = cadena.substring(index2+1, index3);
		}
		resp = strtr(resp, "\"","'");
	}
	return(resp);
}
function rmvAction(cadena, action) {
	if(cadena){
		var index = cadena.toLowerCase().indexOf(action);
		if (index != -1) {
			var index2 = cadena.indexOf("=", index)+1;
			while (cadena.charAt(index2) == " ") index2++;
			var comilla = cadena.charAt(index2);
			var index3 = cadena.indexOf(comilla, index2+1);
			cadena = cadena.substring(0,index)+cadena.substring(index3+1);
		}
	}
	return(cadena);
}*/
/*
	Function selectbox:
		Funcion que crea un input con toda la funcionalidad AJAX para que simule un select, cargado
		desde un xml.
		-Parámetros:
		 id, identificador del input (id)
		 url, url de xml de transformación
		 name, name de input (name) 
		 ctrStr, cadena de control (none,nombre,email)
		 size, size del input (size)
		 maxlength, maxlength del input (maxlength)
		 clase, estilo del input (class)
		 codigo, si queremos menter código adicional (eventos:onclick...)
		 tab, indice de tabulación (tabindex)
*/
/*function selectbox(field, options) {
	var output = "<script>var selBox"+id+" = new selBox();</script>";
	//alert(output);
	document.write(output);
	output = '';
	// Si no tenemos ya el div lo creamos
	if (document.getElementById("selBoxDIV") == null) {
	  var position = "absolute";
		if(detectBrowser() == "fx15" || detectBrowser() == "fx10" || detectBrowser()=="op"){
			position = "fixed";
		}
		output += '<div id="selBoxDIV" style="z-index:551;position:'+position+';display:none;background-color:#fff;border:1px solid #000000;color:#000;"></div>';
		if (detectBrowser!="op") {
			output += '<iframe id="selBoxBG" src="" scrolling="no" frameborder="0" style="position:absolute;display:none;"></iframe>';
			selBox.targetBG = "selBoxBG";
		}
	}
	//Render Object (input)
	output += '<input ';
	output += ' type="text"';
	output += ' id="'+id+'txt"';
	output += ' name="'+id+'txt"';
	if(size!=null)output += ' size="'+size+'"';
	if(maxlength!=null)output += ' maxlength="'+maxlength+'"';
	if(tab!=null)output += ' tabindex="'+tab+'"';
	if(clase!=null)output += ' class="'+clase+'"';
	// Extraemos el código perteneciente a onfocus, onblur y onkeyup y
	// eliminamos el código de onkeydown y onkeypressed
	var onblur = extrAction(codigo, "onblur");
	codigo = rmvAction(codigo, "onblur");
	var onfocus = extrAction(codigo, "onfocus");
	codigo = rmvAction(codigo, "onfocus");
	var onkeyup = extrAction(codigo, "onkeyup");
	codigo = rmvAction(codigo, "onkeyup");
	codigo = rmvAction(codigo, "onkeydown");
	codigo = rmvAction(codigo, "onkeypressed");
	if(codigo!=null)output += ' '+codigo;
	if(ctrStr==null)ctrStr = 'none';
	// Events
	output += ' AUTOCOMPLETE="off"';
	output += ' onfocus="selBoxAct=\'selBox'+id+'\';"';
	output += ' onblur="selBoxAct=null;selBox'+id+'.exit();selBox'+id+'.timerImg(\'out\');'+onblur+'"';
	output += ' onkeyup="var newval=inputCHK(value,\''+ctrStr+'\');if(value != newval){value = newval;}else{selBox'+id+'.keyUp(event)}'+onkeyup+'"';
	output += '/>';
	output += '<span style="display:none;"><input type="Hidden" id="'+id+'" name="'+id+'"/></span>';
	//alert(output);
	document.write(output);
	//eval("document.getElementById('"+id+"txt').captureEvents(Event.KEYPRESS);");
	eval("selBox"+id+".init('"+id+"','"+url+"');");	
	eval("selBox"+id+".timerImg('off');");
}*/


/*function detectBrowser() {
    var ie = document.all != undefined;
    var opera = window.opera != undefined;
		if (opera) return "op";
    if (ie) return "ie";
    if ((window)&&(window.netscape)&&(window.netscape.security)) {
    	if (window.XML) {
        return "fx15";
      }
      else return "fx10";
    }
    return "ie";      // Si no sabemos que navegador es, devolvemos ie.
  }*/

//function selBoxIni(name, "destinoViaje", "destinoViajetxt", {xmlUrl: '/datagen/CAP/ofertas/destinos.xml', selBoxName: 'selBoxDestino'});

function _getAttribute(_node,_attr){
	var _value = "";
	if(_node!=null){
		if(_node.attributes){
			for( var x = 0; x < _node.attributes.length; x++ ) {
				if(_node.attributes[x].nodeName==_attr){
					_value = _node.attributes[x].nodeValue;
				}
			}
		}
		if(_value!=""){
			return _value;
		}else{
			return "";
		}
	}else{
		return "";
	}
}
