﻿/**
* LibrerÃ­a: jQuery
* @package PHPlus
* Document Load
*/ 

jQuery(function($){
    $.datepicker.regional['es'] = {
        closeText: 'Cerrar',
        prevText: '&#x3c;Ant',
        nextText: 'Sig&#x3e;',
        currentText: 'Hoy',
        monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio',
        'Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'],
        monthNamesShort: ['Ene','Feb','Mar','Abr','May','Jun',
        'Jul','Ago','Sep','Oct','Nov','Dic'],
        dayNames: ['Domingo','Lunes','Martes','Mi&eacute;rcoles','Jueves','Viernes','S&aacute;bado'],
        dayNamesShort: ['Dom','Lun','Mar','Mi&eacute;','Juv','Vie','S&aacute;b'],
        dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi','S&aacute;'],
        weekHeader: 'Sm',
        dateFormat: 'dd/mm/yy',
        firstDay: 1,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ''};
    $.datepicker.setDefaults($.datepicker.regional['es']);
});

/* US English initialisation for the jQuery UI date picker plugin. */
jQuery(function($){
	$.datepicker.regional['en-US'] = {
		closeText: 'Done',
		prevText: 'Prev',
		nextText: 'Next',
		currentText: 'Today',
		monthNames: ['January','February','March','April','May','June',
		'July','August','September','October','November','December'],
		monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
		'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
		dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
		dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
		dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'],
		weekHeader: 'Wk',
		dateFormat: 'mm/dd/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['en-US']);
});

//AutoComplete     

function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
} 

var focus_AutoComplete;
var click_hidden_AutoComplete;
jQuery.fn.AutoComplete = function(valores){ 
var valid = $("*[autocom]").size();

var d = $(document.createElement('div'));
$(d).css("position","absolute");
$(d).css("background","#ccc");
$(d).attr("autocom",valid); 
//$(d).css("overflow","hidden");
$(d).hide(); 

jQuery.each(valores, function() {
var label;
var keywords;
if(isArray(this)){
label = (this[0]+"");
keywords = (this[1]+"");
}else
label = this+""; 

var li = $(document.createElement('li'));    
 $(li).css("clear","both"); 
 $(li).css("list-style","none");
 $(li).attr("keywords",(label+","+keywords).toLowerCase());   
 //$(li).attr("elements",this);
 $(li).append(label);  
 
 $(li).click(function(){
      $(focus_AutoComplete).val($(this).html());
      $(click_hidden_AutoComplete).hide("fast");
      $(focus_AutoComplete).change();
 });
   
 $(li).appendTo(d); 
});

$(d).appendTo("body");
//$(d).css("height","100px");


$(this).attr("autocom_id",valid);

$(this).keyup(function(){
    if($(this).val() == ""){
     $("div[autocom='"+$(this).attr("autocom_id")+"']").hide("slow");
    return false;
    }
    
    
    $("div[autocom='"+$(this).attr("autocom_id")+"']").find("li").hide();
    focus_AutoComplete = $(this);
    click_hidden_AutoComplete = $("div[autocom='"+$(this).attr("autocom_id")+"']");
    $("div[autocom='"+$(this).attr("autocom_id")+"'] li[keywords ^= '"+$(this).val().toLowerCase()+"']").show();
    
    if($("div[autocom='"+$(this).attr("autocom_id")+"'] li[keywords ^= '"+$(this).val().toLowerCase()+"']").size() >8)
    $("div[autocom='"+$(this).attr("autocom_id")+"']").addClass("autocomplete");
    else
    $("div[autocom='"+$(this).attr("autocom_id")+"']").removeClass("autocomplete");
    
    if($("div[autocom='"+$(this).attr("autocom_id")+"'] li[keywords ^= '"+$(this).val().toLowerCase()+"']").size() == 1){
        if($("div[autocom='"+$(this).attr("autocom_id")+"'] li[keywords ^= '"+$(this).val().toLowerCase()+"']").html().toLowerCase() == $(this).val().toLowerCase()){
        $("div[autocom='"+$(this).attr("autocom_id")+"']").hide("slow");
        return false;
        }
    }
    
    
    $("div[autocom='"+$(this).attr("autocom_id")+"']").css("left",$(this).position().left+"px");
    $("div[autocom='"+$(this).attr("autocom_id")+"']").css("top",($(this).position().top+$(this).height()+5)+"px");
    $("div[autocom='"+$(this).attr("autocom_id")+"']").show("fast");  
});
}

//Termina AutoComplete

function MM_openBrWindow(theURL,winName,w,h,scrollbars)
 {
 LeftPosition=(screen.width)?(screen.width-w)/2:100;
TopPosition=(screen.height)?(screen.height-h)/2:100;

settings='width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scrollbars+',location=no,directories=no,status=0,menubar=no,toolbar=no,resizable=no';
 URL = theURL;
 window.open(URL,winName,settings);
 }

$(document).ready(function(){
    $(function(){
        $(".date").each(function(i){
            $(this).attr("readonly","readonly");
            $(this).datepicker();
            format=$(this).attr('format');
            if(!format)
                format='yy-mm-dd';
            $(this).datepicker('option', {dateFormat: format}); 
        });
    });
    
    
    //Tooltip

jQuery.fn.jtoolTip = function(texto){
 //$("#tooltip_label").remove();
 var d = $(document.createElement('div')); 
 var name_tooltip = "tooltip"+$("*[tooltip_msg]").size();
 $(d).css("position","absolute");
 $(d).css("background","#F2F5A9");
 $(d).attr("tooltip_msg",name_tooltip);
  $(d).css("z-index","10000"); 
 $(d).hide();
 $(d).html(texto);
 $(this).mouseover(function(e){
 $(d).css("left",e.pageX-($(d).width()/2)+"px");
 $(d).css("top",(e.pageY+15)+"px");
 $(d).show("fast"); 
 });
 $(this).mouseout(function(){
 $(d).hide("fast"); 
 });
 $(d).appendTo("body");

 $(this).attr("numtooltip",name_tooltip);
}
    
 
    
    //buscador de listbox
    $(function(){
        $("*[searchlist]").keyup(function(){
        if($(this).val() == ""){
        $($(this).attr("searchlist")).show();
        return false;
        }
        
        
        $($(this).attr("searchlist")).hide();
        $($(this).attr("searchlist")).each(function(){
            $(this).attr("keywords", $(this).attr("keywords").toLowerCase());
        });
        
        $($(this).attr("searchlist")+"[keywords*='"+$(this).val().toLowerCase()+"']").show();
        }); 
    });
    
    // Fancylightbox
    $("a[rel='fancybox']").fancybox({
        'titleShow' : false
    }); 
    
    //video de fotter
    $("#video_footer").fancybox();

	//video de mamparas
    $("#video_mamparas").fancybox();
    
    //recorder contraseÃ±a modulo
    $("*[href='#recordar_password_mod']").fancybox();
    
    //Select value
    $("select").each(function(){
        if($(this).attr("valor")){
       $(this).val($(this).attr("valor")); 
       if($(this).val().toLowercase != $(this).attr("valor").toLowercase)
       $(this).val("otro");       
        }       
    });  
    
    
    //Limpiar formulario
    
      $.fn.clearForm = function() {
        return $(this).each(function() {
          // iterate the elements within the form
          $(':input', this).each(function() {
            var type = this.type, tag = this.tagName.toLowerCase();
            if (type == 'text' || type == 'password' || tag == 'textarea')
              this.value = '';
            else if (type == 'checkbox' || type == 'radio')
              this.checked = false;
            else if (tag == 'select')
              this.selectedIndex = 0;
          });
        });
      };
      
    //Evento formulario
    
      $.fn.JsendForm = function(url,backcall) {
          var vars = "";
         $(this).each(function() {
          // iterate the elements within the form
          $(':input', this).each(function() {
            var type = this.type, tag = this.tagName.toLowerCase();
            if($(this).attr("name")){
            if (type == 'text' || type == 'password' || tag == 'textarea' || type == 'hidden'){ 
              if(vars) vars = vars + "&";
              vars = vars + $(this).attr("name")+"="+this.value;
            }else if ((type == 'checkbox' || type == 'radio') && $(this).attr("checked")){
              if(vars) vars = vars + "&";
              vars = vars + $(this).attr("name")+"="+this.value;
            }else if (tag == 'select'){
              if(vars) vars = vars + "&";
              vars = vars + $(this).attr("name")+"="+this.value;
            }
            }
          });
        }); 
      $.ajax({
      url: url,
      type: "POST",
      data: vars,
      dataType: 'json',
      success: function(data){
         if(backcall)
         backcall(data);
      }
      });
        
      };
      
    //EMPIEZA Script de Validacion
    
        function ltrim(s) {
    return s.replace(/^\s+/, "");
    }

    function rtrim(s) {
        return s.replace(/\s+$/, "");
    }

    function trim(s) {
        return rtrim(ltrim(s));
    }
    
    function mascarafecha(str, num) {
  return str.replace(RegExp("(\\w{" + num + "})(\\w)", "g"), function(all,text,char){
    return text + "/" + char;
  });
}
                     
    
    
    
    jQuery.fn.jlimitacampo = function(){
    $(this).each(function(){
    var streq = $(this).attr("validar");
    if(!streq) streq = "";
     
            if(streq.indexOf("numeroentero") >= 0){
                $(this).numeric();
            }
            
            if(streq.indexOf("solonumeros") >= 0){
                $(this).numeric({allow:"."});
            }
            
            if(streq.indexOf("dinero") >= 0){
                $(this).numeric({allow:".,"});
            }
            
            if(streq.indexOf("lectura") >= 0){
                $(this).attr("readonly",true);
            }
            
            if(streq.indexOf("sololetras") >= 0){
                $(this).alpha({allow:" "});
            }
            if(streq.indexOf("date") >= 0){
                $(this).attr("readonly","readonly");
                $(this).datepicker();
                var format=$(this).attr('format');
                if(!format)
                format='yy-mm-dd';
                $(this).datepicker('option', {dateFormat: format}); 
            }
            if(streq.indexOf("fecha") >= 0){ 
                $(this).numeric({allow:"/"});     
                $(this).attr("maxlength","10");
                $(this).keyup(function(){
                if($(this).val().length < 7)
                $(this).val(mascarafecha($(this).val(),2));    
                });
            }
     });
    }
    
    
    jQuery.fn.jvalidarForm = function(){
    $(this).each(function(){
    
    var tform = $(this);    
    var elementos = $(this).find("input,select,textarea"); 
        
    $(elementos).jlimitacampo();
    
    
    $(this).submit(function(){
    
        var formnow = $(this);
        
        $(elementos).change(function(){
             
            var streq = $(this).attr("validar");
            var nombre = $(this).parent().find("label").html();
            var msgcam = "campo '"+nombre+"'";
            var msgend = "en la solicitud";
             
            hideError($(this));
            
            if(!streq) streq = "";
            
            //$(this).jlimitacampo(streq);
            
            
            if(streq.indexOf("norequerido") < 0){
                if($(this).val() == ""){
                displayError("El campo es requerido "+msgend,$(this));
                return false;
                }
                     
            }
            
            if(streq.indexOf("urlval") >= 0){
                if(!($(this).attr("aprobado") == $(this).val())){
                var url = $(this).attr("url");
                var valor = $(this).val();
                var telem = $(this);
                if(url){
                $.ajax({
                  url: url,
                  type:"POST",
                  dataType: 'json',
                  data: "texto="+valor,
                  success: function(data){
                  if(data['res']){
                  hideError($(telem));
                  $(telem).attr("aprobado",$(telem).val());
                  $(formnow).submit();    
                  }else{
                  hideError($(telem));
                  if(data['error'])
                  displayError(data['error'],$(telem));
                  else
                  displayError("Es incorrecto el dato del campo",$(telem));
                  }
                  }
                });
                }
                
                displayError("Revisando, esperando respuesta...",$(this));
                $(this).css("background","#F3F781");
                return false;
                }
            }
            
            if(streq.indexOf("email") >= 0){
                if(!/^[A-Za-z][A-Za-z0-9_\.]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/.test($(this).val())){
                displayError("Por favor introduce un e-mail válido",$(this));
                return false;
                }
            }
            
            if(streq.indexOf("fecha") >= 0){
                if(!/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/.test($(this).val())){
                displayError("Por favor introduce una fecha válida",$(this));
                return false;
                }
            }
            
            if(streq.indexOf("igual[") >= 0){
                var corte= streq.split("igual[");
                corte =corte[1].split("]");
                var telement = $(this);
                $("*[name='"+corte[0]+"']",tform).change(function(){$(telement).change()});
                if($("*[name='"+corte[0]+"']",tform).val() != $(this).val()){
                displayError("Es incorrecto el dato del campo",$(this));
                return false;    
                }
            }
            if(streq.indexOf("minimo[") >= 0){
               var corte= streq.split("minimo[");
                corte =corte[1].split("]");
                if($(this).val().length < parseInt(corte[0])){
                displayError("El campo debe contener minimo "+corte[0]+" caracteres",$(this));
                return false;    
                } 
            }
             
            
        });
        
        $(elementos).change();
        $(elementos).keyup(function(){
        var streq = $(this).attr("validar");
        if(streq.indexOf("urlval") < 0){
            $(this).change();
        }
        }); 
        
        if($("*[error_camp]",$(this)).size()){
           $("*[error_camp]:first",$(this)).focus(); 
        }
        return (!$("*[error_camp]",$(this)).size());              
    });
    });
    }

    
    
    //calificacion gestor
    var numstr = 0;

    jQuery.fn.upCalf = function(){
    var valn = parseInt($(this).attr("puntaje"));
    var self = $(this);
    $(this).find("li").each(function(){
    if($(this).attr("nstr") < valn)
    $(this).find("a").addClass("select");
    });
    };
    
    $("*[calificacion]").each(function(){
    var idart = $(this).attr("idart");
    var tipo = $(this).attr("calificacion"); 
    var url="/pagina.getCalf"; 
    var self = $(this);
    $.ajax({
              url: url,
              type:"POST",
              dataType: 'json',
              data: "idart="+idart+"&tipo="+tipo,
              success: function(data){
                  //alert(data['resp'])
              $(self).attr("puntaje",data['puntos']); 
              $(self).upCalf(); 
              }
    });   
    });
    
    $("*[calificacion]").each(function(){
        numstr = 0;
        $(this).find("li").each(function(){
        $(this).attr("nstr",numstr++);
        
        $(this).mouseover(function(){
            var self = $(this);
            $(this).attr("over","over");
            $(this).parent().find("li a").removeClass("select");  
            $(this).parent().find("li").each(function(){
                if($(this).attr("nstr") < $(self).attr("nstr"))
                $(this).find("a").addClass("select");
            });
        });
        $(this).mouseout(function(){
            $(this).attr("over","");
            if($(this).parent().find("li[over]").size()<1){
            
                $(this).parent().find("li a").removeClass("select");
                $($(this).parent().parent()).upCalf();
            
            } 
        });
        $(this).find("a").click(function(){
            var idart = $(this).parent().parent().parent().attr("idart");
            var tipo = $(this).parent().parent().parent().attr("calificacion");
            var calf =  parseInt($(this).parent().attr("nstr")) + 1;
            var self = $(this).parent().parent().parent();
            var url="/pagina.saveCalf";
            //alert("idart="+idart+"&calf="+calf+"&tipo="+tipo);
            $.ajax({
              url: url,
              type:"POST",
              dataType: 'json',
              data: "idart="+idart+"&calf="+calf+"&tipo="+tipo,
              success: function(data){
              //alert(data['resp']);
              if(data['resp']=="nolog")
              alert("Necesitas entrar a tu cuenta de usuario para poder continuar calificando.");
              if(data['resp']=="exists")
              alert("Unicamente puedes calificar una sola vez.");
              if(data['resp']=="ok"){
              $(self).attr("puntaje",data['puntos']); 
              $(self).upCalf();  
              }
              }
            });
            return false;
        })
        })
    });
    
    //TERMINA Script de Validacion 
    
    //addbutton
    
   jQuery.fn.plusButton = function(){  
    
    $(this).find(".plusval").click(function(){
       var valnow = parseInt($(this).parent().parent().find("*[inpval]").val()); 
       if(!valnow)
       $(this).parent().parent().find("*[inpval]").val("1");
       else
       $(this).parent().parent().find("*[inpval]").val(valnow+1);
    });
    
    $(this).find(".resval").click(function(){
       var valnow = parseInt($(this).parent().parent().find("*[inpval]").val()); 
       if(!valnow || valnow <= 1)
       $(this).parent().parent().find("*[inpval]").val("1");
       else
       $(this).parent().parent().find("*[inpval]").val(valnow-1);
    });
    
    $(this).find("*[inpval]").keyup(function(){
       var valnow = parseInt($(this).val()); 
       if(!valnow)
       $(this).val("1");
       else
        $(this).val(valnow);
    });
    
   }
    
    
    $(function(){
        $('*[resume]').each(function(){
        
        $(this).css("font-weight","normal");
        $(this).jTruncate({
        length: parseInt($(this).attr("resume")),
        minTrail: 0,
        ellipsisText: "..."
        });
        
        $("*[class='clearboth']").remove();
        $("*[class='truncate_more']").remove();  
        $("*[class='truncate_ellipsis']").attr("class","");
        });
    });
    
    $(function(){
        $("*[check]").each(function(i){
            var hiddentmp = $(document.createElement("input"));
                $(hiddentmp).attr("value","0");
                $(hiddentmp).attr("type","hidden");
                $(hiddentmp).attr("name",$(this).attr("name"));  
            var checktmp = $(document.createElement("input"));
                $(checktmp).attr("value",$(this).attr("default"));
                $(checktmp).attr("type","checkbox");
                $(checktmp).attr("name",$(this).attr("name"));
            if($(this).attr("value") == $(this).attr("default"))
                $(checktmp).attr("checked","checked");
                
            var contenedor = $(this).parent();
                $(contenedor).append($(hiddentmp));
                $(contenedor).append($(checktmp));
                $(this).remove();
        });
    });
    
    $(function(){
        jQuery.fn.jlistbox = function(){
        $("*[list='multiselect']",$(this)).each(function(){
         
        $("li",$(this)).click(function(){
        if($(this).attr("class") != "")
        $(this).attr("class","select_item");
        
        if($(this).attr("class") == "select_item"){
        $(this).attr("class","");
        $(this).find("input").attr("checked","");
        }else{
        $(this).attr("class","select_item");
        $(this).find("input").attr("checked","checked");
        }
        });
        
        var tli = $(this);
        var cortes;
        if($(this).attr("valor")){
        if($(this).attr("valor").indexOf(","))
        cortes = $(this).attr("valor").split(","); 
        else
        cortes = new Array($(this).attr("valor"));
        
        
        $.each(cortes,function(index,valor){
        var corteli = valor;
        $("li",tli).each(function(){   
        if(corteli == $(this).find("input").val()){ 
        $(this).attr("class","select_item");       
        $(this).find("input").attr("checked","checked");
        } 
        });    
        });
        }   
        });
        
        }
        $(this).jlistbox();
    });
    
    $(function(){
        $("*[tooltip]").each(function(){
            
            
         $(this).mouseover(function(){
         var currentTime_tem = new Date();
         if($(this).attr("id") == "") $(this).attr("id", "tmid_"+currentTime_tem.getTime());
         toolTip(document.getElementById($(this).attr("id")),$(this).attr('tooltip'));  
         });
         
         $(this).mouseout(function(){
         toolTip(document.getElementById($(this).attr("id")),"");    
         });
           
        });  
    });
    
    // Rich edit
    $(".full-edit").wysiwyg({
        controls: {
          strikeThrough : { visible : true },
          underline     : { visible : true },
          separator00 : { visible : true },
          justifyLeft   : { visible : true },
          justifyCenter : { visible : true },
          justifyRight  : { visible : true },
          justifyFull   : { visible : true },
          separator01 : { visible : true },
          indent  : { visible : true },
          outdent : { visible : true },
          separator02 : { visible : true },
          subscript   : { visible : true },
          superscript : { visible : true },
          separator03 : { visible : true },
          undo : { visible : true },
          redo : { visible : true },
          separator04 : { visible : true },
          insertOrderedList    : { visible : true },
          insertUnorderedList  : { visible : true },
          insertHorizontalRule : { visible : true },
          h4mozilla : { visible : true && $.browser.mozilla, className : 'h4', command : 'heading', arguments : ['h4'], tags : ['h4'], tooltip : "Header 4" },
          h5mozilla : { visible : true && $.browser.mozilla, className : 'h5', command : 'heading', arguments : ['h5'], tags : ['h5'], tooltip : "Header 5" },
          h6mozilla : { visible : true && $.browser.mozilla, className : 'h6', command : 'heading', arguments : ['h6'], tags : ['h6'], tooltip : "Header 6" },
          h4 : { visible : true && !( $.browser.mozilla ), className : 'h4', command : 'formatBlock', arguments : ['<H4>'], tags : ['h4'], tooltip : "Header 4" },
          h5 : { visible : true && !( $.browser.mozilla ), className : 'h5', command : 'formatBlock', arguments : ['<H5>'], tags : ['h5'], tooltip : "Header 5" },
          h6 : { visible : true && !( $.browser.mozilla ), className : 'h6', command : 'formatBlock', arguments : ['<H6>'], tags : ['h6'], tooltip : "Header 6" },
          separator07 : { visible : true },
          cut   : { visible : true },
          copy  : { visible : true },
          paste : { visible : true }
        }
    });
    $(".edit").wysiwyg();

    // Mensajes de error
    if($('.sys-msg').length!=0){
        $(this).oneTime(2000,function(){
            $('.sys-msg').fadeOut('slow');
        })
    }
    if($('.error-msg').length!=0){
        $(this).oneTime(5000,function(){
            $('.error-msg').fadeOut('slow');
        })
    }  
    
    // Checkall
    $(".checkall").click(function(){
        $(this).parents('form').find(':checkbox').attr('checked', this.checked);
    });
    
	/**
	 * FunciÃ³n para capturar los formularios por GET
	 * y procesar las variables para enviarlas en formato
	 * correcto.
     * TambiÃ©n verifica que el formato de cada input sea el correcto en caso 
     * de que tenga una regla de validaciÃ³n desde el HTML
	 */
	$("form").submit(function(){
		var uri="";
		var ret=true;
	 	$(this).find("input[type='text'],input[type='password'],textarea,input[type='hidden'],select").each(function(i){
			if(($(this).attr('validate')=="no-empty" || $(this).attr('validate')=="") && this.value==""){
				if($(this).attr('error')!="" && $(this).attr('error')!=null){
					displayError($(this).attr('error'),$(this));
				}else{
					displayError("Favor de llenar el campo: "+$(this).attr('name'),$(this));
				}
                this.focus();
				ret=false;
				return false;
			}else if($(this).attr('validate')=="email"){
				// Validamos que sea email
				var emailre=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
				if(!emailre.test($(this).attr('value'))){
					if($(this).attr('error')!='' && $(this).attr('error')!=null){
						displayError($(this).attr('error'),$(this));
					}else{
						displayError("Favor de introducir una dirección de correo válida",$(this));
					}
					this.focus();
					ret=false;
					return false;
				}
			}else if($(this).attr('validate')=="number"){
				// Validamos campo de tipo numerico
				if(isNaN($(this).attr('value')) || $(this).attr('value')==""){
					if($(this).attr('error')!='' && $(this).attr('error')!=null){
						displayError($(this).attr('error'),$(this));
					}else{
						displayError("Favor de introducir un valor numérico",$(this));
					}
					$(this).attr('value',"");
					this.focus();
					ret=false;
					return false;
				}
			}else if($(this).attr('validate')=="custom" || $(this).attr('validate')=="regex"){
				// Validamos la RegEx
				if($(this).attr('regex')!="" && $(this).attr('regex')!=null){
					var filter=eval("/"+$(this).attr('regex')+"/");
					if(!filter.test($(this).attr('value'))){
						if($(this).attr('error')!='' && $(this).attr('error')!=null){
							displayError($(this).attr('error'),$(this));
						}else{
							displayError("Favor de introducir un valor numérico",$(this));
						}
						this.focus();
						ret=false;
						return false;
					}
				}
			}
			uri+=this.name+','+this.value+"/";
		});
		if(ret==false)
			return false;
		if($(this).attr("method").toLowerCase()=="post")
			return true;
		if(ret)
			window.location.href=uri;
		return false;
	});
    
    // Alt
    $("input[alt!='']").each(function(){
        var caption=$(this).attr('alt');
        if(caption!='' && caption!=null){
            if($(this).attr('value')=='' || $(this).attr('value')==null){
                $(this).attr('value',caption);
                $(this).css('color','#cccccc');
            }
            $(this).focus(function(){
                if($(this).attr('value')==caption){
                    $(this).attr('value','');
                    $(this).css('color','black');
                }
            });
            $(this).blur(function(){
                if($(this).attr('value')==''){
                    $(this).css('color','#cccccc');
                    $(this).attr('value',caption);
                }    
            });
        }
    });
});

/**
 * LibrerÃ­a: MooTools
 * Document Load
 * Descomentar la funciÃ³n si se tiene
 * habiliada la librerÃ­a mootools (comentar la funciÃ³n de arriba)
 */
/*
window.addEvent('domready',function(){
	$(document.body).getElements("form").addEvent('submit',function(){
		var uri='';
		var ret=true;
		$each(this.getElements("input[type=text],input[type=password],textarea,input[type=hidden]"),function(item,index){
			if((item.get('validate')=="no-empty" || item.get('validate')=="empty") && item.get('value')==""){
				// Validamos campo vacÃ­o
				if(item.get('error')!='' && item.get('error')!=null){
					displayError(item.get('error'));
				}else{
					displayError("Favor de llenar el campo: "+item.get('name'));
				}
				item.focus();
				ret=false;
				return false;
			}else if(item.get('validate')=="email"){
				// Validamos campo de tipo email
				var emailre=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
				if(!emailre.test(item.get('value'))){
					if(item.get('error')!='' && item.get('error')!=null){
						displayError(item.get('error'));
					}else{
						displayError("Favor de introducir una direcciÃ³n de correo vÃ¡lida");
					}
					item.focus();
					ret=false;
					return false;
				}
			}else if(item.get('validate')=="number"){
				// Validamos campo de tipo numerico
				if(isNaN(item.get('value')) || item.get('value')==""){
					if(item.get('error')!='' && item.get('error')!=null){
						displayError(item.get('error'));
					}else{
						displayError("Favor de introducir un valor numÃ©rico");
					}
					item.set('value',"");
					item.focus();
					ret=false;
					return false;
				}
			}else if(item.get('validate')=="custom" || item.get('validate')=="regex"){
				// Validamos la RegEx
				if(item.get('regex')!="" && item.get('regex')!=null){
					var filter=eval("/"+item.get('regex')+"/");
					if(!filter.test(item.get('value'))){
						if(item.get('error')!='' && item.get('error')!=null){
							displayError(item.get('error'));
						}else{
							displayError("Favor de introducir un valor numÃ©rico");
						}
						item.focus();
						ret=false;
						return false;
					}
				}
			}
			uri+=item.get('name')+','+item.get('value')+"/";
		});
		if(this.get('method').toLowerCase()=="post" && ret!=false)
			return true;
		if(ret!=false){
			window.location.href=uri;
		}
		return false;
	});
    
    // Alt
    $$('input[alt!=""]').each(function(el){
        var caption=el.get('alt');
        if(caption!='' && caption!=null){
            el.set('value',caption);
            el.setStyle('color','#cccccc');
            el.addEvent('focus',function(){
                if(this.get('value')==caption){
                    this.set('value','');
                    this.setStyle('color','black');
                }
            });
            el.addEvent('blur',function(){
                if(this.get('value')==''){
                    this.setStyle('color','#cccccc');
                    this.set('value',caption);
                }    
            });
        }
    });	
});
*/

/**
* Esta funcion se ejecutara cada ves que el campo
* de tipo input tenga una regla de validacion y la regla
* no se haya cumplido
* - Esta funcion puede personalizarse para desplegar otro tipo de error -
*/

function displayError($msg,element){
    if(element){
    $(element).css("background","#FA5858");
    $(element).attr("error_camp","1");
    $(element).jtoolTip($msg);
    }else
    alert($msg);
    return true;
}
function hideError(element){
    $(element).each(function(){
    $("*[tooltip_msg='"+$(this).attr("numtooltip")+"']").remove();
    });                        
    $(element).removeAttr("error_camp");
    $(element).css("background","");
} 

function number_format( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://crestidg.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57     
 
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

