(function($) {

	$.fn.shvalidate = function(options){

		var chekOnlyNumbers = function(evt){
			var charCode = evt.which;
			if (charCode > 31 && (charCode < 48 || charCode > 57)) {
				/*alert("Por favor digiet solo numeros.")*/
				return false;
			}
				return true;
		};

		var opts = $.extend({}, $.fn.shvalidate.defaults, options);
		opts._control=this;

		return this.each(function() {
		
			//Restricciones a los campos
			$("input, select, textarea", opts._control).each(function(){
				if($(this).attr("format")=="numeric"){
					$(this).bind("keypress",function(i, name){return chekOnlyNumbers(i)});
				}
				if($(this).attr("mask")){
					$(this).mask($(this).attr("mask"));
					//$(this).bind("keypress",function(i, name){return chekOnlyNumbers(i)});
				}
				if($(this).attr("format")=="autonumeric"){
					$(this).attr("readonly","true");
					$(this).attr("value","Autonumerico");
				}
			});
			
			
			
		
			//Validacion al enviar el formulario
			$(this).submit(function () { 
		
				var retorno=1;
				var iClave=0;
				var arrClave = new Array();
	
				$("div.validateError",opts._control).remove();
				
				$(":submit",opts._control).attr("disabled", "disabled");
				
				$("input, select, textarea", opts._control).each(function(){
					//alert($(this));
					//alert($(this).attr("name"));
					
					if($(this).val().length == 0){
						//alert($(this).attr("required"));
						if($(this).attr("required")=="yes" || $(this).attr("required")==true){
							$(this).parent().append("<div class='validateError'>Debe diligenciar este campo</div>");
							retorno=0;
						}
					}else{
						if($(this).attr("format")=="email"){
							
							var str=$(this).val();			
							var at="@"
							var dot="."
							var lat=str.indexOf(at)
							var lstr=str.length
							var ldot=str.indexOf(dot)
							if (str.indexOf(at)==-1){
								$(this).parent().append("<div class='validateError'>Debe diligenciar un email valido</div>");
								retorno=0;
							}else if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
								$(this).parent().append("<div class='validateError'>Debe diligenciar un email valido</div>");
								retorno=0;
							}else if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
								$(this).parent().append("<div class='validateError'>Debe diligenciar un email valido</div>");
								retorno=0;
							}else if (str.indexOf(at,(lat+1))!=-1){
								$(this).parent().append("<div class='validateError'>Debe diligenciar un email valido</div>");
								retorno=0;
							}else if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
								$(this).parent().append("<div class='validateError'>Debe diligenciar un email valido</div>");
								retorno=0;
							}else if (str.indexOf(dot,(lat+2))==-1){
								$(this).parent().append("<div class='validateError'>Debe diligenciar un email valido</div>");
								retorno=0;
							}else if (str.indexOf(" ")!=-1){
								$(this).parent().append("<div class='validateError'>Debe diligenciar un email valido</div>");
								retorno=0;
							}
								
						}
						if($(this).attr("format")=="password"){
							//alert("ppp");
							arrClave[iClave]=$(this).val();
							if(arrClave.length==2){
								if(arrClave[0]!=arrClave[1]){
									$(this).parent().append("<div class='validateError'>Las claves deben coincidir</div>");
									retorno=0;
								}
							}
							iClave++;
						}
						if($(this).attr("format")=="date"){
		
							//calculo la fecha de hoy
							fInicial=new Date();
							fInicial.setYear(fInicial.getYear()-14);
							fInicial.setHours(0);
							fInicial.setMinutes(0);
							fInicial.setSeconds(0);
							
							var array_fecha = $(this).val().split("-")
							//var ano = parseInt(array_fecha[0],10);
							//var mes = parseInt(array_fecha[1],10);
							//var dia = parseInt(array_fecha[2],10);
							var ano = parseInt(array_fecha[0],10);
							var mes = parseInt(array_fecha[1],10);
							var dia = parseInt(array_fecha[2],10);
							var mifecha = new Date(ano,mes-1,dia);
							//si el array no tiene tres partes, la fecha es incorrecta
							if (array_fecha.length!=3){
								$(this).parent().append("<div class='validateError'>Fecha no valida</div>");
								retorno=0;
							}else if(isNaN(ano)){
								$(this).parent().append("<div class='validateError'>Fecha no valida</div>");
								retorno=0;
							}else if(isNaN(mes) || (mes > 12)){
								$(this).parent().append("<div class='validateError'>Fecha no valida</div>");
								retorno=0;
							}else if(isNaN(dia)){
								$(this).parent().append("<div class='validateError'>Fecha no valida</div>");
								retorno=0;
							}
							
							/*else if(Math.floor(mifecha)>Math.floor(fInicial)){
								$(this).parent().append("<div class='validateError'>Edad m&iacute;nima para participar es de 14 a&ntilde;os</div>");
								retorno=0;
							}*/
							
						}
						
						if($(this).val().length<$(this).attr("minlength")){
							$(this).parent().append("<div class='validateError'>Este campo debe tener al menos "+$(this).attr("minlength")+" carateres</div>");
							retorno=0;
						}
						
						if($(this).attr("function")){
							eval($(this).attr("function")+"('#"+$(this).attr("id")+"')");
						}
						
					}
				
				});
				
				$(":submit",opts._control).removeAttr("disabled");
				$(opts._control).attr("valid",retorno);
				
				if(retorno=="0"){
					return false;
				}else{
					if(opts.sendviaAjax==true){
						$(":password", opts._control).each(function(){
							encrypt=hex_md5($(this).val());
							$(this).val(encrypt);
						});				
						
						var dataValues="";
						var dataForm=$(opts._control).serializeArray();
						opts.beforeSubmit();
						
						$.ajax({
							type: "POST",
							url: $(opts._control).attr("action"),
							data: jQuery.param(dataForm)+"&"+opts.data,
							dataType: opts.dataType,
							beforeSend: function(){
							},
							success: function(response){
								opts.onComplete(response);
							}
						});
						return false;
					}else{
						return true;
					}
					
				}
				
			});
		});	
		
	};

	$.fn.shvalidate.defaults = {
		sendviaAjax: false,
		data: "",
		dataType: "html",
		onComplete: function(){},
		beforeSubmit: function(){}
	}

})(jQuery);