// JavaScript Document
//defino tim para los objeto String
String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g,'') };

function addEvent(obj,evento,functionName){
	if(obj.attachEvent){
		obj.attachEvent(evento,functionName);
	}else{
		obj.addEventListener(evento.substring(2),functionName,true);
	}
}

function redir(url){
		document.location.replace(url);
	}
function obj(id){
		return (document.getElementById(id))?document.getElementById(id):undefined;
	}
function getVal(id){    
    return obj(id).value.trim();
}

function displayn(idObj){
    obj(idObj).style.display=(obj(idObj).style.display=='none')?'':'none';
}
function display(id,none){    
    obj(id).style.display=(none)?'':'none';
}

function setStatus(mensaje){
		div=document.getElementById('pgStatus');
		div.innerHTML=mensaje;
		div.style.visibility='visible';
	}
function hiddenStatus(){
		div=document.getElementById('pgStatus').style.visibility='hidden';
	}


function redEdit(url){
    this.url=url;
    this.method='POST';
    this.send=function(jsonInputValor){        
        f=document.createElement("form");
        f.action=this.url;
        f.method=this.method;
        for(var i in jsonInputValor){
            dc=document.createElement('input');
            dc.name=i;
            dc.value=jsonInputValor[i];
            f.appendChild(dc);
        }
        document.body.appendChild(f);
        f.submit();
        document.body.removeChild(f);
    }
}

function jsDeletePanel(){
    this.form;
    this.idChecks;//Id del checkbox, los check deven de tener un ID_n donde n es un cosecutivo de 0 a n segun el numero de opciones, esta variable solo contiene el "ID_"
    this.idCellNombre;//Id de la celda de nombre
    this.msjConfElimSin;//mensaje de confirmacion al eliminar solo un elemento
    this.msjConfElimPlu;//mensaje de confirmacion al eliminar mas de un elemento
    this.formAction;//direccion a la que se enviara el formulario
    this.selectedElements;
    this.msj;
    this.sinSeleccion;//Define el mensaje que se mostrara si no se selciona un elemento
    this.id_a_delS;//Define el id de las ligas para eliminar Solo
    this.id_a_delM;
    this.chekAllNone;
    this.initBtns=function(){    
        if(this.id_a_delS){
            for(var i=0;btn = obj(this.id_a_delS+i);i++){;
                var jsDeletePanel=this;
                btn.i=i;
                btn.onclick=function (){ 
                    jsDeletePanel.delS(this.i);
                    return false;
                }
              
            }
        }
        if(this.id_a_delM){
            var jsDeletePanel=this;
            obj(this.id_a_delM).onclick=function(){
                jsDeletePanel.eliminar();
                return false;
            }
        }
        if(this.chekAllNone){
            idChecks = this.idChecks;
            obj(this.chekAllNone).onclick=function(){
                    for(var i=0;ch=obj(idChecks+i);i++){                        
                        ch.checked=this.checked;
                    }
            }
        }
    }
    
    this.delS = function (numCheck){
       // checkeuncheckform(obj(this.form),0);
       for(var i=0;ch=obj(idChecks+i);i++){
                        ch.checked=false;
                    }

        obj(this.idChecks+numCheck).checked=true;
        if(!this.eliminar()){
            obj(this.idChecks+numCheck).checked=false;
        }
        return false;
    }
    this.onConfim=function(){
        obj(this.form).action=this.formAction;
        obj(this.form).method="POST";
        obj(this.form).submit();
    }
    this.eliminar = function(){  
        this.selectedElements=new Array();        
        for(var i=0; check=obj(this.idChecks+i); i++){            
            if(check.checked){
                var cel = obj(this.idCellNombre+i);                
                this.selectedElements[this.selectedElements.length]=cel.innerHTML;
           }
        }
        if(this.selectedElements.length==1){
            this.msj=this.msjConfElimSin + "\n" +this.selectedElements[0];
        }else if(this.selectedElements.length>1){
           this.msj = this.msjConfElimPlu + "\n" +this.selectedElements.toString().replace(/,/g,"\n");
        }else{
           if(this.sinSeleccion){
                alert(this.sinSeleccion);
                return;
           }
        }

        if(confirm(this.msj)){
            this.onConfim()
        }
        return false;
        
    }
    

}


/*
if (document.captureEvents) 
	 document.captureEvents(Event.MOUSEMOVE)	

document.onmousemove = pMouse;

document.mouse=new Object();

function pMouse(e){
     if (!e) {		 
         e = window.event;
         e.layerX = e.clientX + document.body.scrollLeft;
         e.layerY = e.clientY + document.body.scrollTop;
     }    
	var X = e.layerX;
	var Y = e.layerY;

	document.mouse._x = X;
	document.mouse._y = Y;
	//obj('mesaje').style.top=Y+'px'
	//obj('mesaje').style.display='';
	//obj('logId').value=document.mouse._y;
}


/*var IE=(navigator.appName!='Netscape');
if (!IE) 
	 document.captureEvents(Event.MOUSEMOVE)	
document.onmousemove = getMouseXY;
var mX = 0;
var mY = 0;
function getMouseXY(e) 
	{
	if (IE) 
		{ //para IE
			mX = event.clientX + document.body.scrollLeft;
			mY = event.clientY + document.body.scrollTop;
		}
else 	
	{ //para netscape
		mX = e.pageX;
		mY = e.pageY;
	}
//	document.title=mX+"x"+mY;
}

*/

function checkeuncheckform(obj,checked){
	
		var i;
		for(i=0;i<obj.length;i++){
			if(obj[i].type=='checkbox'){
				obj[i].checked=checked;
			}
		}
	}


function ocultartbc(id){
		document.getElementById(id).innerHTML=null;
		document.getElementById(id).style.visibility='hidden';
		window.open("#top",'_self');
	}

function ran(){
		return Math.floor(Math.random() * (100000000000000));
	}

function tbc(idDiv,idTitulo,idContenido){
	this.idDiv=idDiv;
	this.idTitulo=idTitulo;
	this.idContenido=idContenido;
	this.width='';
	this.textTitulo="Cargado...";
	this.textContenido="Cargando...";
	this.ancla='tbl'+this.idDiv;
	this.html=function (){
		return '<a name="'+this.ancla+'" ></a><table border="0" cellpadding="0" cellspacing="0" width="'+this.width+'">'+
			  '<tr>'+
			   '<td height="10"><img src="imgs/bgTip_r1_c1.gif" width="9" height="10" /></td>'+
			   '<td background="imgs/bgTip_r1_c2.gif"></td>'+
			  '<td width="10"><img src="imgs/bgTip_r1_c3.gif" width="10" height="10"/></td>'+
			  '</tr>'+
			  '<tr>'+
			   '<td background="imgs/bgTip_r2_c1.gif"></td>'+
			   '<td bgcolor="#FFFFFF" width="100%" valign="top">'+
						'<a href="javaScript:ocultartbc(\''+this.idDiv+'\')"><img src="imgs/x.gif" width="11" height="12" align="right" border="0" /></a>'+
						'<div id="'+this.idTitulo+'" align="center" >'+this.textTitulo+'</div>'+
						'<hr style="margin:0 0 0 0px; height:1px; border-width:0px; background-color:#000000;"/>'+
						'<div id="'+this.idContenido+'">'+this.textContenido+'</div>'+
						'<div align="center"><a <a href="javaScript:ocultartbc(\''+this.idDiv+'\')" style=" font-family:Verdana, Arial; font-size:10px; color:#FF0000"><b>Cerrar</b></a></div>'+
			   '</td>'+
			   '<td background="imgs/bgTip_r2_c3.gif"></td>'+
			  '</tr>'+
			  '<tr>'+
			   '<td><img src="imgs/bgTip_r3_c1.gif" width="9" height="11"/></td>'+
			   '<td background="imgs/bgTip_r3_c2.gif">'+
			   '</td>'+
			   '<td><img src="imgs/bgTip_r3_c3.gif" width="10" height="11"/></td>'+
			  '</tr>'+
			'</table>';
		}
}

/********************************************************************************/
//getSelectedsIndex(objSelect)
//retorna un areglo de referencias a los indices selecionados de un select
function getSelectedsIndex(objSelect){
		var selected=new Array();
		for(var i=0;i<objSelect.options.length;i++){
				if(objSelect.options[i].selected){
					selected[selected.length]=objSelect.options[i];
				}
			}
		return selected;
	}
/********************************************************************************/
function input(tipo,nameId,value,otros){		
		 var control="";
		 this.type;
		 this.name=nameId;
		 this.id=nameId;
		 this.value=value;
		 this.otros=otros;
		if(tipo=='se'){			
		}else{
			if(tipo=='te'){				
			}else{
				this.type=(tipo=='b')?'button':
				(tipo=='s')?'submit':
				(tipo=='r')?'radio':
				(tipo=='c')?'checkbox':
				(tipo=='h')?'hidden':
				(tipo=='f')?'file':
				'text';
			}
		}
		this.html=function(){
			if(tipo=="se"){
				var textError=	"En caso de un control tipo select se requiere que el \n"+
								"parametro value sea un Arreglo de Object's con la \n"+

								"siguiente estructura:\n"+
								"new Array(\n"+
								"  {text:'texto3', value:'valor1' },\n"+
								"  {text:'texto3', value:'valor2' },\n"+
								");\n"+
								"Cada Elemento sera un Option del Ccampo\n"+
								"Pude agregar mas parametros al objeto ej: \n"+
								" {text:'texto3', value:'valor3', class:'clase', style:'estilo', selected:'selected'}";
				if(value.constructor!=Array)return textError;
				control='<select '+
						((nameId)?' name="'+nameId+'"':'')+
						((nameId)?' Id="'+nameId+'"':'');
						
				for(index in otros)
					control+=' '+index+'="'+otros[index]+'"';					
				control+='>\n';
				
				for(var index in value){
					if(value[index].constructor!=Object)return textError;
					control+='\t<option';					
					for(indexValue in value[index]){						
						if(indexValue!='text'){
							control+=' '+indexValue+'="'+value[index][indexValue]+'"';
							//{text:texto,value:valor;}
						}
					}
					control+='>'+value[index]['text']+'</option>\n';				
				}
				control+='</select>';
				return control;
			}
			
			if(tipo=='te'){
				control='<textarea></textarea>';
				return control;
			}
			
			control='<input type="'+this.type+'" value="'+this.value+'" name="'+this.name+'" '+
			' id="'+this.id+'"';
			for(index in otros){
					control+=' '+index+'="'+otros[index]+'"';	
				}
			control+='>';
			return control;	
		}
	}
	
/************/
function cleanSelect(selectObj){
	while(selectObj.options.length>0)selectObj.options[0]=null;
}
/**********************/

function trimgroup(){
    this.arr=new Array();
    this.add=function(IdObj,propiedad){        
        this.arr[this.arr.length]={
            obj:obj(IdObj),
            propiedad:propiedad
        }   
    }

    this.trim=function(){
        for(var i=0;i<this.arr.length;i++){
             o=this.arr[i]['obj']
             o[this.arr[i]['propiedad']]=o[this.arr[i]['propiedad']].trim();
        }
    }
}
//elimina los espacios en blaco de los campos text y textarea de un formulario
function trimForm(form){
    for(i=0;i<form.length;i++){
        if(form[i].type=='text'||form[i].type=='textarea'){
            form[i].value=form[i].value.trim();
        }
    }
}

//var f=/.{1}/;
//var a=" ";
//alert(f.test(a.trim()));

/*
 * psudoclase para validar formulario atravez de expreciones
 * regulares
 *
 **/

function validator(){
    this.objetos=new Array();
    this.add = function(IdObj,strPropiedad,strMensajeError,filtro){
        if(obj(IdObj)==undefined){
            alert(IdObj+" No Existe");
        }
        this.objetos[this.objetos.length]={
            'obj':obj(IdObj),
            'propiedad':strPropiedad,
            'mensaje':strMensajeError,
            'filtro':filtro
        }
    }
    this.test = function(){
        for(var i in this.objetos){
            var otem=this.objetos[i]            
            if(!otem.filtro.test(otem.obj[otem.propiedad])){
                alert(otem.mensaje);
                try{
                    otem.obj.focus();
                }catch(e){}
                return false;
            }
        }
        return true;
    }
}


//Valida un campo email con este formato: idDelUsuario@servidor.com
function validaEmail(theElement)
{
var s = obj(theElement);
var filter=/^[A-Za-z][A-Za-z0-9_]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;

if (filter.test(s.value)){
return true;
}
else{
alert("Ingrese una dirección de correo válida");
s.focus();
return false;
}
}

// funcion que trunca las letras y solo permite escrivir numeros
function soloNums(evt){	
var nav4 = window.Event ? true : false;
// NOTE: Backspace = 8, Enter = 13, '0' = 48, '9' = 57	
var key = nav4 ? evt.which : evt.keyCode;	
return (key <= 13 || (key >= 48 && key <= 57));
}

function js2vURL(json,inicia){
	url='';
	if(!inicia){
		url='?'; 
	}
	for(var i in json){		
		url+= escape(i)+'='+escape(json[i])+'&';
	}
	return url.substr(0,url.length-1);
}
//-->




// JavaScript Document

function validaCajas(ArrCajasId,ArrTextError,funcion){
		var i;
		for(i=0;i<ArrCajasId.length;i++){
				if(document.getElementById(ArrCajasId[i]).value==''){
						alert(ArrTextError[i]);
						return false;
					}
			}
			if(funcion)
				return funcion();
			else
				return true;
	}

function valueNoContiene(id,caracter,mensaje){
	obj=obj(id);
	if(obj.value.indexOf(caracter)<0){
		alert(mensaje);
		return true;
	}
	else return false;
}

function valueVacio(id,mensaje){
	obj=obj(id);
	if(obj.value)
		return false;
	else{
		alert(mensaje);
		return true;
	}
}

function valuesNoIguales(id1,id2,mensaje){
	obj1=obj(id1);
	obj2=obj(id2);
	if(obj1.value!=obj2.value){
		alert(mensaje);
		return true;
    }else
		return false;
}

function jsredir(url,ventana,opciones){
	if(ventana)
		window.open(url,ventana,opciones);
	else
		document.location.replace(url);

}
