// VARIABLES GLOBALES

function showHelp(txt){
	var help_text = txt.getAttribute('help_text');
	if(isEmpty(txt.value) || txt.value == help_text){
		txt.className = 'inactive-search';
		txt.value = help_text;
	}
}

function hideHelp(txt){
	var help_text = txt.getAttribute('help_text');
	txt.className = '';
	if(txt.value == help_text){
		txt.value = '';
	}
}

function isValidURL(cadena){
	var v = new RegExp();
    v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
    return v.test(cadena);
}

function isValidYT(cadena){
	return startsWith(cadena, 'http://www.youtube.com');
}

function startsWith(str1, str2)
{return (str1.match("^"+str2)==str2)}

function endsWith(str1, str2)
{return (str1.match(str2+"$")==str2)}

function setFocus(id){
	_(id).focus();
	if(_(id).select){
		_(id).select();
	}
}

function activarLink(id, index){
	var as = _(id).getElementsByTagName('a');
	for(var i=0;i<as.length;i++){
		as[i].style.fontWeight = 'normal';	
	}
	if(as[index]){
		as[index].style.fontWeight = 'bold';	
	}
}

function marcarFilaEmp(index){
	_('cont_emp_' + index).className='fila_emp_on';
	_('desc_emp_' + index).className='fila_emp_on';
}

function desmarcarFilaEmp(index){
	_('cont_emp_' + index).className='';
	_('desc_emp_' + index).className='';
}

var filaSeleccionada = null;

function seleccionarFila(id){
	
	if(_(id).value){
		currentText = _(id).value;
	}
	if(filaSeleccionada!=null){
		filaSeleccionada.style.backgroundColor = 'white';
	}
	var fila = document.getElementById("fila_" + id);
	fila.style.backgroundColor = '#C9DBF5';
	filaSeleccionada = fila;
	
}

function loadSelect(id, list, _item, _key){
	var lst = _(id);
	lst.options.length = 0;
	if(_item){
		lst.options[0] = new Option(_item, '');
	}
	for(var i=0;i<list.length;i++){
		var _value = list[i].getPropertyValue('plazo', Encrypter.Types.DECRYPTED) + ' - ' + list[i].getPropertyValue('interes', Encrypter.Types.DECRYPTED) + '% (Anual)';
		lst.options[i+1] = new Option(_value, list[i].getPropertyValue(_key, Encrypter.Types.DECRYPTED));
	}
	lst.selectedIndex = 0;
}

function marcarError(campo, error, reqid){
	var label = _('label_' + campo.id);
	var req = _(reqid);
	if(error){
		label.style.color = 'Red';
		req.style.color = 'Red';
		erroresValidacion = true;
	}else{
		label.style.color = '#2C2829';
		req.style.color = '#2C2829';
	}
}

function deseleccionarFila(){
	if(filaSeleccionada!=null){
		filaSeleccionada.style.backgroundColor = 'white';
	}
}

function newXMLHttpRequest(){
		try {
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (E) {
				xhr = false;
			}
		}
		if (!xhr && typeof XMLHttpRequest != 'undefined') {
			xhr = new XMLHttpRequest();
		}
		return xhr;
}

function getPositionLeft(This){
	var el = This;var pL = 0;
	while(el){pL+=el.offsetLeft;el=el.offsetParent;}
	return pL
}
function getPositionTop(This){
	var el = This;var pT = 0;
	while(el){pT+=el.offsetTop;el=el.offsetParent;}
	return pT
}

function esFormatoSeguro(cadena){
	ExpresionRegular=/(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{5,10})$/;
	return ExpresionRegular.test(cadena);
}

function _(text, type){
	if(type == 'tag'){
		return document.getElementsByTagName(text);
	}else if(type == 'name'){
		return document.getElementsByName(text);
	}else{
		return document.getElementById(text);
	}
}

function procesarErrorAJAX(response){
	if(response == null){
		document.location.href = 'feedback.jsp';	
	}else{
		if(response.indexOf("redirect")){
			document.location.href = response.substring(response.lastIndexOf(":") + 1, response.length);				   
		}
	}
}

function isEmpty(cadena){ 		                                  
	var blanco = " \n\t" + String.fromCharCode(13); 		                                     
	var i;                         
	var es_vacio;                
	for(i = 0, es_vacio = true; (i < cadena.length) && es_vacio; i++) 
	  es_vacio = blanco.indexOf(cadena.charAt(i)) != - 1;
	return(es_vacio);
}

function isValidMail(cadena){
	ExpresionRegular=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return ExpresionRegular.test(cadena);
}

var textareas_stop = new Array();
function ismaxlength(obj, event, contador){
	var maxlength = parseInt(obj.getAttribute('lengthMax'));
	if(obj.value.length>maxlength){
		obj.value = obj.value.substring(0, maxlength);
	}
	if(contador){
		if(!textareas_stop[obj.id]){
			textareas_stop[obj.id] = true;
			window.setTimeout('doCount(\''+obj.id+'\',\''+contador+'\')', 1000);
		}
	}
}

function doCount(idobj, contador){
	var obj = _(idobj);
	var element = document.getElementById(contador);
	var num = parseInt(obj.getAttribute("length"));
	num = num - obj.value.length;
	if(element)
	element.innerHTML = num;
	textareas_stop[idobj] = false;
}

function isNumberKey(evt){
	 var charCode = (evt.which) ? evt.which : evt.keyCode
	 if (charCode > 31 && (charCode < 48 || charCode > 57)){
		return false;
	 }else{
	 	return true;
	 }
}

function isNumber(cadena){
	ExpresionRegular=/^\d+$/;
	return ExpresionRegular.test(cadena);
}

function isDecimal(cadena){
	if(isEmpty(cadena))return false;
	ExpresionRegular=/^\$?[0-9]*(\.[0-9]{0,2})?$/;
	return ExpresionRegular.test(cadena);
}

function isMoneyKey(evt, txt){	
	 var key = (evt.which) ? evt.which : evt.keyCode
	 keychar = String.fromCharCode(key);

	if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27)){
		return true;
	}else if ((("0123456789").indexOf(keychar) > -1)){
	   return true;
	}else if (keychar == "." && txt.value.indexOf('.') == -1){
	   return true;
	}else{
	   return false;
	}
}

function checkMoney(c){
	var text = new String(c.value);
	if(text.charAt(text.length-1) == '.'){
		c.value = text.replace('.','');	
	}else if(text.charAt(0) == '.'){
		c.value = text.replace('.','0.');
	}
}

function isNumeroCuentaKey(evt, txt){	
	 var charCode = (evt.which) ? evt.which : evt.keyCode
	 if (charCode > 41 && (charCode < 48 || charCode > 57) && charCode != 45 && charCode != 116){
		return false;
	 }else{
		return true;	
	 }
}

function isRestrictedValidInput(evt){
	var charCode = (evt.which) ? evt.which : evt.keyCode
	if (charCode > 31 && (charCode >= 65 || charCode <= 90 || charCode >= 97 || charCode <= 122 || charCode >= 48
						  || charCode <= 57 || charCode == 95)){
		return true;
	}else{
	 	return false;
	}
}

function checkInput(e, c){
	if(e.ctrlKey){
		var s = "'&$#<>*+^`~\\\"";
		for(var i=0;i<s.length;i++){
			if(c.value.indexOf(s.charAt(i)) != -1){
				c.value = currentText;
				alert("Hay caracteres inv\u00E1lidos en el texto que intenta introducir. Los siguientes caracteres no son permitidos: '&%$#<>*+^`~\\\"");
				return false;
			}
		}
		currentText = c.value;
	}
}

function _ALERT(idcampo, i, v, text){
	var campo = _(idcampo);
	if(!campo){
		campo = window.parent.document.getElementById(idcampo);	
	}
	if(text != null && text != 'undefined'){
		campo.innerHTML = text;	
	}else{
		campo.innerHTML = 'Hay errores en los datos introducidos';	
	}
	if(v){
		campo.style.visibility = 'visible';
	}else{
		campo.style.visibility = 'hidden';
	}
	if(i>0){
		window.setTimeout('_ALERT("'+idcampo+'", '+(i-1)+', '+!v+', "'+text+'")', 50);
	}
}

function _ALERTBOX(idbox, i, v, color){
	var box = _(idbox);
	if(v){
		box.style.borderColor = '#FFFFFF';
	}else{
		box.style.borderColor = color;
	}
	if(i>0){
		window.setTimeout('_ALERTBOX("'+idbox+'", '+(i-1)+', '+!v+', \''+color+'\')', 50);
	}
}

function isSecure(cadena){
	ExpresionRegular=/(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{0,15})$/;
	return ExpresionRegular.test(cadena);
}

function isEnterKey(evt){
	 var charCode = (evt.which) ? evt.which : evt.keyCode;
	 return charCode == 13;
}


function showBlock(h){	
	var div = document.createElement('div');
	div.className = 'divblock';
	div.id = 'divblock';
	var e = _('fieldset', 'tag')[0];
	div.innerHTML = '<img src="../img/cargando.gif" />';
	var left = getPositionLeft(e);
	var top = getPositionTop(e);
	div.style.left = (left + 10) + 'px';
	div.style.top = (top + 20) + 'px';
	div.style.width = '650px';
	div.style.height = h + 'px';	
	_('body', 'tag')[0].appendChild(div);
	var lsts = _('select', 'tag');
	for(var i=0;i<lsts.length;i++){
		lsts[i].style.visibility = 'hidden';	
	}
}

function hideBlock(method){
	var lsts = _('select', 'tag');
	for(var i=0;i<lsts.length;i++){
		lsts[i].style.visibility = 'visible';	
	}
	_('body', 'tag')[0].removeChild(_('divblock'));
	if(method){
		method();
	}
}




//************** AJAX 
//*************************************************************************

var error_url = 'feedback.jsp';

function AQUAX(){
	this.xhr = null;
	this.method;
	this.url;
	this.params = new Array();
	this.callback_method;
	this.addParam = function(key,value){
		this.params[this.params.length] = new Param(key,value);
	}
	this.send = function(){
		var _url = '?ajax=true';
		for(var i=0;i<this.params.length;i++){
			_url += this.params[i];	
		}
		this.xhr = newXMLHttpRequest();
		var oncallback = this.oncallback;
		var callback_method = this.callback_method;
		var _xhr = this.xhr;
		if(this.method == AQUAX.GET){
			this.xhr.open(this.method, this.url + _url, true);
			this.xhr.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
			this.xhr.onreadystatechange = function(){oncallback(callback_method, _xhr);}
			this.xhr.send(null);
		}else if(this.method == AQUAX.POST){
			this.xhr.open(this.method, this.url, true);
			this.xhr.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"); 
			this.xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			this.xhr.setRequestHeader("Content-length", _url.length);
			this.xhr.setRequestHeader("Connection", "close");	
			this.xhr.onreadystatechange = function(){oncallback(callback_method, _xhr);}
			this.xhr.send(_url.replace('?',''));
		}else{
			throw "Invalid Ajax method";	
		}
	}
	this.oncallback = function(callback_method, _xhr){
		if (_xhr.readyState == 4) {
			var text = _xhr.responseText;
			if(text.indexOf("TIMEOUT") != -1){
				document.location.href = 'feedback.jsp';
				return;
			}
			if(text.indexOf("ERROR") == -1){
				callback_method(text);
			}else{
				procesarErrorAJAX(text);
			}
		}	
	}
}

AQUAX.GET = "GET";
AQUAX.POST = "POST";
AQUAX.parseObject = function(r){
	return Transport.parseObject(eval('('+r+')'));	
}
AQUAX.parseList = function(r){
	return Transport.parseList(eval('('+r+')'));	
}

function Param(_key, _value){
	this.key = _key;
	this.value = _value;
	this.toString = function(){
		if(!this.value.serialize){
			return "&" + this.key + "=" + this.value;
		}else{
			return "&" + this.key + "=" + this.value.serialize();
		}
	}
}


function isValidAttach(file, extArray) {
	allowSubmit = false;
	if (!file) return false;
	while (file.indexOf("\\") != -1){
		file = file.slice(file.indexOf("\\") + 1);
		}
		ext = file.slice(file.lastIndexOf(".")).toLowerCase();
		for (var i = 0; i < extArray.length; i++) {
			if (extArray[i] == ext) { allowSubmit = true; break; }
		}
	
	return allowSubmit;
}


