var is_dirty=false;
function check_moneda(elemento){}
function check_regex(elemento){
	
	var reg = "";
	
	return reg.test($(elemento).val());
}
function check_igualque(elemento){
	
	var idelem = "";
	
	var valor2 = $("#" + idelem).val();
	var valor1 = $(elemento).val();
	return valor1==valor2;	
}
function check_javascript(elemento){
	
}
function check_email(elemento){
   	var reg = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z_\-])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
   	return reg.test($(elemento).val());
}
function check_dni(elemento){
	var params = $(elemento).attr('custom:requerido');
	params = params.replace("dni", "");
	params = params.replace(" ", "");
	params = params.replace("(", "");
	params = params.replace(")", "");
		
	var dni = $(elemento).val();
	var numero = "";
	var let = "";
	if (params==""){
		numero = dni.substr(0,dni.length-1);
		let = dni.substr(dni.length-1,1);
	}else{
		if($(elemento).attr('maxlength')==1){
			//esto es la letra	
			let = dni;
			numero = $("#" + params).val();
		}else{
			numero = dni;
			let = $("#" + params).val();
		}
	}
	let = let.toUpperCase();
	
	numero = numero % 23;
	letra='TRWAGMYFPDXBNJZSQVHLCKET';
	letra=letra.substring(numero,numero+1);
	if (letra==let){return true;}else{return false;}
}
function check_numero(elemento){
	var params = $(elemento).attr('custom:requerido');
	params = params.replace("numero", "");
	params = params.replace(" ", "");
	params = params.replace("(", "");
	params = params.replace(")", "");
	
	var reg = /^([0-9])*$/;
	if (params==""){
		return reg.test($(elemento).val());
	}else{
		if (reg.test($(elemento).val())){
			if($(elemento).val().length == params){
				return true;
			}else{
				return false;	
			}
		}else{
			return false;	
		}
	}
}
function check_texto(elemento){
	if ($(elemento).val()!=$(elemento).attr('custom:prevalue')){	
		return true; 
	} else{ 
		return false;
	}
}
function check_cp(elemento){
	var reg= /(0[1-9]|5[0-2]|[0-4][0-9])[0-9]{3}/;
	if (reg.test($(elemento).val())){
		if ($(elemento).val()>=1001){return true;
		}else{return false;}
	}else{return false;}
}
function check_fecha(elemento){
	var reg = /^([012][0-9]|[3][01])\/([0][0-9]|[1][012])\/([0-9]{4})$/;
	
	if (reg.test($(elemento).val())==false){return false;}
	
	var dtStr = $(elemento).val();
	var dtCh= "/";
	var minYear=1900;
	var maxYear=2100;
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strDay=dtStr.substring(0,pos1);
	var strMonth=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1){strDay=strDay.substring(1);}
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if (pos1==-1 || pos2==-1){
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return false;
	}
	//if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//return false
	//}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return false;
	}
return true;
}
function check_movil(elemento){
	var reg = /^[76][0-9]{8}$/;
	return reg.test($(elemento).val());
}
function check_fijo(elemento){
	var reg = /^[98][0-9]{8}$/;
	return reg.test($(elemento).val());
}
function check_telefono(elemento){
	if (check_fijo(elemento) || check_movil(elemento)){
		return true;
	}
	return false;
}
function check_rango(elemento){
	var params = $(elemento).attr('custom:requerido');
	params = params.replace("!", "");
	params = params.replace("rango", "");
	params = params.replace(" ", "");
	params = params.replace("(", "");
	params = params.replace(")", "");
	params = params.split(",",2);
	//es un numero
	var reg = /^([0-9])*$/;
	if ( reg.test($(elemento).val()) && reg.test(params[0]) && reg.test(params[1]) ){
		if ( $(elemento).val() >= params[0] && $(elemento).val() <= params[1] ){ return true; }
		else{ return false;	}
	}else{ return false; }
}
function check_cuenta(elemento){
  	var params = $(elemento).attr('custom:requerido');
	params = params.replace("cuenta", "");
	params = params.replace(" ", "");
	params = params.replace("(", "");
	params = params.replace(")", "");
	params = params.split(",",4);
  
  
  
  	var banco = "";
  	var entidad = "";
	var control = "";
	var cuenta = "";
  
	  if (params[0] == ""){
		  
		  
		  
	  }else{
		  banco = $("#" + params[0]).val();
		  entidad = $("#" + params[1]).val();
		  control = $("#" + params[2]).val();
		  cuenta = $("#" + params[3]).val();
	  }
  
	  if (banco == ""  || entidad == "" || control == "" || cuenta == "")
		return false;
	  else {
			if (banco.length != 4 || entidad.length != 4 || control.length != 2 || cuenta.length != 10)
			  	return false;
			else {
			  if (!numerico(banco) || !numerico(entidad) || !numerico(control) || !numerico(cuenta))
				return false;
			  else {
				  
				if (!(obtenerDigito("00" + banco + entidad) ==
					  parseInt(control.charAt(0))) || 
					!(obtenerDigito(cuenta) ==
					  parseInt(control.charAt(1))))
				  return false;
				else
				  return true;
			  }
			}
	  }
}
function ValidaForm() {
	var elementos = $(':input');
	var campo_ok = false;
	var requerido_text = "";
	var mensaje_mostrar = "";
	var mostrar_alert = false;
	$.each(elementos, function(i, elemento){
		if ($(elemento).attr('custom:requerido')!=undefined){
			campo_ok = false;
			if($(elemento).attr('type')=="checkbox"){
				if ( $(elemento).attr('checked') ){campo_ok = true;	}		
			}else{
				if($(elemento).attr('type')=="radio"){
					if ($('[name="' + $(elemento).attr('name') + '"]:checked').val()) {campo_ok = true;}
				}else{
					requerido_text = $(elemento).attr('custom:requerido');
					if(requerido_text.match("^"+"!")=="!"){
						requerido_text = requerido_text.replace("!","");
						valor_elemento = $(elemento).val();
						preval = $(elemento).attr('custom:prevalue');
						if (preval!="") {valor_elemento = valor_elemento.replace(preval,""); }
						if (valor_elemento==""){campo_ok=true;}
					}
					if($(elemento).val()!="" && campo_ok==false){
						if (requerido_text.match("^"+"email")=="email"){campo_ok=check_email(elemento);}
						if (requerido_text.match("^"+"moneda")=="moneda"){campo_ok=check_moneda(elemento);}
						if (requerido_text.match("^"+"dni")=="dni"){campo_ok=check_dni(elemento);}
						if (requerido_text.match("^"+"numero")=="numero"){campo_ok=check_numero(elemento);}
						if (requerido_text.match("^"+"regex")=="regex"){campo_ok=check_regex(elemento);}
						if (requerido_text.match("^"+"igualque")=="igualque"){campo_ok=check_igualque(elemento);}
						if (requerido_text.match("^"+"rango")=="rango"){campo_ok=check_rango(elemento);}
						if (requerido_text.match("^"+"javascript:")=="javascript:"){campo_ok=check_javascript(elemento);}
						if (requerido_text.match("^"+"texto")=="texto"){campo_ok=check_texto(elemento);}
						if (requerido_text.match("^"+"fecha")=="fecha"){campo_ok=check_fecha(elemento);}
						if (requerido_text.match("^"+"cp")=="cp"){campo_ok=check_cp(elemento);}
						if (requerido_text.match("^"+"movil")=="movil"){campo_ok=check_movil(elemento);}
						if (requerido_text.match("^"+"fijo")=="fijo"){campo_ok=check_fijo(elemento);}
						if (requerido_text.match("^"+"telefono")=="telefono"){campo_ok=check_telefono(elemento);}
						if (requerido_text.match("^"+"cuenta")=="cuenta"){campo_ok=check_cuenta(elemento);}
						if (requerido_text==""){campo_ok=check_texto(elemento);}
					}
				}
			}
			if (campo_ok!=true){
				var mensaje = "";
				var estavacio = true;
				
				if($(elemento).attr('type')=="checkbox"){
					if ($(elemento).attr('checked')){estavacio = false;}else{estavacio = true;}
				}else{	
					if($(elemento).attr('type')=="radio"){
						if ($('[name="' + $(elemento).attr('name') + '"]:checked').val()) {estavacio = false;}else{estavacio = true;}
					}else{
						if ($(elemento).val()==""){ estavacio = true;}else{estavacio = false;}
					}
				}	
							
				if (estavacio){
					mensaje = $(elemento).attr('custom:empty');
				}else{
					if($(elemento).attr('type')=='text'){
						mensaje = $(elemento).attr('custom:validate');
						if (mensaje==undefined){
							mensaje = $(elemento).attr('custom:empty');
						}
					}
				}
				if (mensaje==undefined){
					mensaje = $(elemento).attr('custom:nombre');
					if (mensaje==undefined){
						mensaje = $(elemento).attr('name');
					}
					mensaje = "El elemento " + mensaje + " no tiene el formato adecuado o esta vacio";
				}
				var imagen = "";				
				if ( $('#span-' + $(elemento).attr('name')).length!=0){
					$('#span-' + $(elemento).attr('name')).remove();
				}
				var clase="";
				var margen = 0;
				if($(elemento).attr('type')=="checkbox"){
					clase = "requeridocheckbox";
					margen = ($(elemento).width()+ 4)
					imagen = "/imagenes/formularios/error3.gif";
				}else{	
					if($(elemento).attr('type')=="radio"){
						clase = "requeridoradio";
						margen = 20;
						imagen = "/imagenes/formularios/error2.gif";
					}else{
						if ($(elemento).is("select")){
							clase = "requeridoselect";
							margen = $(elemento).width() + 1;
							imagen = "/imagenes/formularios/error.gif";
						}else{
							clase = "requerido";
							margen = $(elemento).width() + 1;
							imagen = "/imagenes/formularios/error.gif";
						}
					}
				}	
				//arreglo navegadores antiguos
				if ($.browser.msie && $.browser.version <= 7) {margen=-3;}
				
				if($(elemento).attr('type')=="checkbox"){
					//arreglo navegadores antiguos
					if ($.browser.msie && $.browser.version <= 7) {
						$(elemento).after('<div id="span-' + $(elemento).attr('name') + '" class="' + clase + '" style="margin-left:-40px;"></div>');
					}else{
						$(elemento).after('<div id="span-' + $(elemento).attr('name') + '" class="' + clase + '" style="margin-left:-17px;"></div>');
					}
				}else{
					$(elemento).after('<div id="span-' + $(elemento).attr('name') + '" class="' + clase + '" style="margin-left:' + margen + 'px;"></div>');
				}
				
				$('#span-' + $(elemento).attr('name')).html('<img src="' + imagen + '" title="' + mensaje + '"/>');				
				
				$('#span-' + $(elemento).attr('name') + " img[title]").tooltip({tip: '.tooltip', effect: 'bouncy'});
								
				mensaje_mostrar = mensaje_mostrar + mensaje + "\n";
			}else{
				$('#span-' + $(elemento).attr('name')).remove();
			}
		}

	});
	if (mensaje_mostrar!=""){
		if (mostrar_alert){
			alert (mensaje_mostrar);
		}
		return false;
	}else{
		return true;
	}
}
//utilizadas para calcular las fechas validas
function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}
function obtenerDigito(valor){
  valores = new Array(1, 2, 4, 8, 5, 10, 9, 7, 3, 6);
  control = 0;
  for (i=0; i<=9; i++)
    control += parseInt(valor.charAt(i)) * valores[i];
  control = 11 - (control % 11);
  if (control == 11) control = 0;
  else if (control == 10) control = 1;
  return control;
}
function numerico (valor){
	var reg = /^([0-9])*$/;
	return reg.test(valor);	
}



$(document).ready(function(){
	// create custom animation algorithm for jQuery called "bouncy"
	$.easing.bouncy = function (x, t, b, c, d) {
		var s = 1.70158;
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	}
	// create custom tooltip effect for jQuery Tooltip
	$.tools.tooltip.addEffect("bouncy",
		// opening animation
		function(done) {
			this.getTip().slideDown(300);
			this.getTip().animate({top: '+=15'}, 500, 'bouncy');
		},
		// closing animation
		function(done) {
			this.getTip().animate({top: '-=15'}, 500, 'bouncy');
			this.getTip().slideUp(300);
		}
	);
	
	var elementos = $(':input');
	$.each(elementos, function(i, elemento){
		if ($(elemento).attr('custom:prevalue')!=undefined){
			if($(elemento).attr('type')=="text"){
				if ($(elemento).val()==""){
					$(elemento).val($(elemento).attr('custom:prevalue'));
				}
				$(elemento).focus(function(){
					if ($(this).val()==$(this).attr('custom:prevalue')) {$(this).val("");}
				});
				$(elemento).blur(function(){
					if ($(this).val()=="") {$(this).val($(this).attr('custom:prevalue'));}
				});
			}
			
			if($(elemento).attr('type')=="password"){
				if ($(elemento).val()==""){
					$(elemento).attr('type', 'text');
					$(elemento).val($(elemento).attr('custom:prevalue'));
				}
				$(elemento).focus(function(){
					if ($(this).val()==$(this).attr('custom:prevalue')) {$(this).val(""); $(elemento).attr('type', 'password');}
					
				});
				$(elemento).blur(function(){
					if ($(this).val()=="") {$(this).val($(this).attr('custom:prevalue')); $(elemento).attr('type', 'text');}
				});				
			}
		}
	});

});
