// JavaScript Document
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


function ampliar(){
   var min = 10;
   var max = 16;
   var p = $("divTexto");
	if(p.style.fontSize) {
	 var s = parseInt(p.style.fontSize.replace("px",""));
	} else {
	 var s = 12;
	}
	if(s!=max) {
	 s += 1;
	}
	p.style.fontSize = s+"px"
	setCookie('cmsaja',s,365);
}

function reducir(){
   var min = 10;
   var max = 16;
   var p = $("divTexto");
	if(p.style.fontSize) {
	 var s = parseInt(p.style.fontSize.replace("px",""));
	} else {
	 var s = 12;
	}
	if(s!=min) {
	 s -= 1;
	}
	p.style.fontSize = s+"px";
	setCookie('cmsaja',s,365);
}

function setCookie(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name){
	if (document.cookie.length>0)
	  {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
	    { 
	    c_start=c_start + c_name.length+1; 
	    c_end=document.cookie.indexOf(";",c_start);
	    if (c_end==-1) c_end=document.cookie.length;
	    return unescape(document.cookie.substring(c_start,c_end));
	    } 
	  }
	return "";
}



function MM_openBrWindow(theURL,winName,features)
{ //v2.0
  window.open(theURL,winName,features);
}


/**
*devuelve las coordenada X
*/
  function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

/**
*devuelve las coordenada Y
*/
  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }
  
  
function submenu(obj,flat){
	if($(obj)){
		if(flat==1){
			w = findPosX($('mn23'));
			h = findPosY($('mn23'));
			var dimensions = $("mn23").getDimensions();
			$(obj).setStyle({ top: h+dimensions.height-1,left: w, position:'absolute'}); 
			$(obj).show();
		}else{
			$(obj).hide();
		}
	}
}


 /**
 * limpia los caracteres en blanco de los costados
 */
function trim(str){ 
    if(str != null){
        var i; 
        for(i=0; i<str.length; i++){
            if(str.charAt(i)!=" "){str=str.substring(i,str.length);break;} 
        } 
    
        for(i=str.length-1; i>=0; i--){
            if(str.charAt(i)!=" "){str=str.substring(0,i+1);break;} 
        } 
        
        if(str.charAt(0)==" "){return "";}else{ return str;}
    }
}

function ajatv(medio){
	if(medio){	new Ajax.Updater('ajatv','modulos/ajatv.php?txtMedi_id=' + medio,{method:'post',parameters: ''});	}
}

function scrollTop(tiempo){
	opa=$('gototop').getStyle('opacity');
	var top = f_scrollTop();
	if( top>= tiempo){
		if(opa==0){
			new Effect.Opacity('gototop',{duration:1.5, from:0, to:1});
		}
	}else{ 
		if(opa==1){
			new Effect.Opacity('gototop',{duration:1.0, from:1, to:0});
		}
	}
}

function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}

function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}

function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}

function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}

function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}


 var formato = 1;  

 function invFecha(nTipFormat,dFecIni){  
     var dFecIni = dFecIni.replace(/-/g,"/");                    /*?? reemplaza el - por ?  */ 
       
/*   primera division fecha*/  
     var nPosUno  = ponCero(dFecIni.substr(0,dFecIni.indexOf("/")));  
/*   2º divicion fecha  */
     var nPosDos  = ponCero(dFecIni.substr(parseInt(dFecIni.indexOf("/")) + 1,parseInt(dFecIni.lastIndexOf("/")) - parseInt(dFecIni.indexOf("/")) - 1));  
/*     ?? 3º divicion fecha  */
     var nPosTres = ponCero(dFecIni.substr(parseInt(dFecIni.lastIndexOf("/")) + 1));  
   
     switch(nTipFormat){  
         case 1 :    /*??  DD?MM?YYYY  */
             dReturnFecha = nPosTres + "" + nPosDos + "" + nPosUno;  
             break;  
   
         case 2 :   /* ??  MM?DD?YYYY  */
             dReturnFecha = nPosTres + "" + nPosUno + "" +nPosDos;  
             break;  
   
         case 3 :    /*??  YYYY?MM?DD  */
             dReturnFecha = nPosUno + "" + nPosDos + "" +nPosTres;  
             break;  
       
         case 4 :    /*??  YYYY?DD?MM  */
             dReturnFecha = nPosUno + "" + nPosTres + "" +nPosDos;  
             break;  
     }  
       
     return dReturnFecha;    /*?? retorna la fecha     */  
 }  
   
/** Agrega un cero delante del strPon cuando tenga solo un caracter  */
 function ponCero(strPon){  
     if(parseInt(strPon.length) < 2)  
         strPon = "0" + strPon;  
     return strPon;  
 }  
   
 function comparaFecha(dFormat,dFecMenor, dFecMayor){  
     dFecMenor = invFecha(dFormat,dFecMenor);  
     dFecMayor = invFecha(dFormat,dFecMayor);  
   
     if(dFecMenor > dFecMayor)  
         return false;  
     else  
         return true;  
 }  
   
 function validaFecha(){  
     var dFechaMenor = $('txtFecini').value;  
     var dFechaMayor = $('txtFecfin').value;  
   
     if(comparaFecha( formato,dFechaMenor,dFechaMayor) == false){
         alert("La fecha de Desde no debe ser menor a la fecha Hasta.");  
     }else{
	return true;
     }
 }  
   
 moveMe = function(n,t,a){ 
	var xpos   = parseInt($('pos'+t).value); 
	var maxpos = parseInt($('maxpos'+t).value)*Math.abs(n); 
	var nxpos  = xpos-n;
	/*alert('xpos='+xpos+'   '+'maxpos='+maxpos+'   n='+n+'   t='+t+'   nxpos='+nxpos)*/
	if(nxpos>0){ 
		$('pos'+t).value = -maxpos-n; 
		new Effect.Move($('table'+t), { y: 0, x: -maxpos-n, duration: 0.2 });
		if($('tabpag'+t)){$('tabpag'+t).update(parseInt($('maxpos'+t).value)+'/'+parseInt($('maxpos'+t).value));}
	}else if(maxpos==-nxpos){
		$('pos'+t).value = 0;
		new Effect.Move($('table'+t), { y: 0, x: maxpos-n, duration: 0.2 });
		if($('tabpag'+t)){$('tabpag'+t).update('1/'+parseInt($('maxpos'+t).value));}
	}else {
		$('pos'+t).value = parseInt($('pos'+t).value) - n;
		new Effect.Move($('table'+t), { y: 0, x: -n, duration: 0.2 });
		if($('tabpag'+t)){$('tabpag'+t).update( Math.abs(nxpos/n)+1+'/'+parseInt($('maxpos'+t).value));}
	}
}



function selectUbi(contenedor,url){
	
	if(contenedor){
		if(contenedor=='prov'){
			new Ajax.Updater('prov',url,{
				method:'post',
				parameters:'ubigeo=prov&txtUbi_id='+$('lstDpto').options[$('lstDpto').selectedIndex].value,
				onComplete: function(){
					$('lstDist').update('');
				}
			});
		}	
		if(contenedor=='dist'){
			new Ajax.Updater('dist',url,{
				method:'post',
				parameters:'ubigeo=dist&txtUbi_id='+$('lstProv').options[$('lstProv').selectedIndex].value
			});
		}	
	}
	
	if($('lstDpto').value){
		if($('lstProv').value){
			if($('lstDist').value){
				$('txtUbi_id').value = $('lstDist').options[$('lstDist').selectedIndex].value;
			}else{
				$('txtUbi_id').value = $('lstProv').options[$('lstProv').selectedIndex].value;
			}
		}else{
			$('txtUbi_id').value = $('lstDpto').options[$('lstDpto').selectedIndex].value;
		}
	}
	
}
	

participar = function(code,keywork){
	$('promo'+code).update(keywork+'&nbsp;<input type="text" name="keywork'+code+'" id="keywork'+code+'" onKeypress="valAlfa(this);" size=15><input type="button" value="Participar" onclick="enviarParticipacion('+code+',\''+keywork+'\')">')
}

enviarParticipacion = function(code,keywork){
	if(code){
		new Ajax.Request('modulos/promociones.php',{
			method:'post',
			parameters:'accion=participacion&txtComu_id=3&txtPromo_id='+code+'&txtPromo_keywork='+$("keywork"+code).value,
			onComplete:function(transport,json){
				if(json=='1'){//participaste
					alert('Gracias por participar');
				}else if(json=='2'){ // ya has participado
					alert('Ya participo de esta Promocion');
				}else if(json=='3'){ // vuelva a logearse
					alert('Vuelva a Logearse que se ah perdido su sesion');
					//location.href='indice.php';
				}else{ // no puedes participar
					
				}
			}
		})
		$('promo'+code).update("Para inscrib&iacute;rte s&oacute;lo tienes que hacer click, <a href=\"javascript:participar('"+code+"','"+keywork+"')\" class='txtrojo'>AQU&Iacute;</a>");
	}
}

ganadores = function(code){
	if(code){
		new Ajax.Updater('listaganador'+code,'modulos/promociones.php',{
			method:'post',
			parameters:'accion=ganadores&txtComu_id=1&txtPromo_id='+code
		});
	}
}

function valAlfa(campo){
	var validos = " abcdefghijklmnñopqrstuvwxyz0123456789.,";
	var letra;
	var bien = true;
	for(var i=0;i<campo.value.length;i++){
		letra=campo.value.charAt(i).toLowerCase();
		if(validos.indexOf(letra) == -1){bien=false;}
		if(!bien){
			campo.value = campo.value.substring(0,campo.value.length -1);
		}
	}
}


IsEmpty=function(obj){
	obj = obj.replace(/^\s+/,'');
	for(var i=obj.length;i>0;i--){
		if(/\S/.test(obj.charAt(i))){
			obj = obj.substring(0,i);
			break;
		}
	}
	return obj;
}

evaluar = function(tipo){
	var flat=1;
	if( IsEmpty($('txtSuscri_usuario').value) ){ 
		if( validaEmail($('txtSuscri_email')) ){ 
			if( IsEmpty($('txtSuscri_appat').value) ){ 
				if( IsEmpty($('txtSuscri_nom').value) ){ 
			    	if( IsEmpty($('txtSuscri_fecnac').value) ){ 			    		
			    		if( $F('lstEstci_id') ){ 
			    			if( $F('lstTipodoc_id')){ 
			    				if( IsEmpty($('txtSuscri_numdoc').value) ){ 
			    					if( IsEmpty($('txtSuscri_referencia').value) ){ 
			    						if( $F('lstNivelins_id')){ 			    												
											if( tipo ){
												new Ajax.Request(location.protocol+'//'+location.hostname+'/ojo/modulos/registrate.php?accion=validate',{
													method: 'post',
												    parameters: 'txtSuscri_email='+ $('txtSuscri_email').value  ,
													onComplete: function(transport,json){
														if(json=='true'){
															flat=0;
															alert('E-mail ya esta registrado');
															$('txtSuscri_email').focus();
															return false;
														}else{
															$('frm').submit();
														}
													}
												});
											}else{
												$('frm').submit();
											}																						
										}else{
											alert('Seleccione su nivel de instrucción');
											$('lstNivelins_id').focus();
											return false;
			    						}
					                }else{
										alert('Escriba su dirección');
										$('txtSuscri_referencia').focus();
										return false;
									}
								}else{
									alert('Escriba su Número de documento');
									$('txtSuscri_numdoc').focus();
									return false;
								}
							}else{
								alert('Seleccione su tipo de documento');
								$('lstTipodoc_id').focus();
								return false;
							}																						
			    		}else{
							alert('Seleccione su estado civil');
							$('lstEstci_id').focus();
							return false;
			    		}
					}else{
						alert('Escriba su Fecha de Nacimiento');
						$('txtSuscri_fecnac').focus();
						return false;
					}
				}else{
					alert('Escriba su Nombre');
					$('txtSuscri_nom').focus();
					return false;
				}
			}else{
				alert('Escriba su Apellido Paterno');
				$('txtSuscri_appat').focus();
				return false;
			}
		}else{
			alert('Escriba el E-mail');
			$('txtSuscri_email').focus();
			return false;
		}
	}else{
		alert('Escriba su Alias');
		$('txtSuscri_usuario').focus();
		return false;
	}
} 

selectPais = function(codigo){
	if(codigo!=$('lstPais_id').options[$('lstPais_id').selectedIndex].value){
		$('tablaUbigeo').hide()
	}else{
		$('tablaUbigeo').show()
	}
}

function validaEmail(txtEmail){
	caracteres =/^[A-Z, a-z, 0-9,_]+\.{0,1}[A-Z, a-z, 0-9,_]+\@[A-Z, a-z, 0-9,_]+\.[A-Z, a-z, 0-9,_]+/;	
	if (caracteres.test(txtEmail.value)){
		return true;
	}else{
	  	txtEmail.value = "";
	  	txtEmail.focus();
	    return false;
	}
}

function checkEmail(txtEmail) {
	//lista de caracteres que debemos comparar
	caracteres =/^[A-Z, a-z, 0-9,_]+\.{0,1}[A-Z, a-z, 0-9,_]+\@[A-Z, a-z, 0-9,_]+\.[A-Z, a-z, 0-9,_]+/;	
	if (caracteres.test(txtEmail.value)){
			
			new Ajax.Request('modulos/registrate.php',{
				method: 'post',
				parameters: 'txtSuscri_email='+ $('txtSuscri_email').value +'&accion=validate' ,
				onComplete: function(transport,json){
					if(json=='true'){													
						$('txtAvisoEmail').innerHTML="<font color='red'>&nbsp;&nbsp;Este e-mail ya est&aacute; registrado.</font>";
						txtEmail.focus();
						return false;
					}
					else{
						$('txtAvisoEmail').innerHTML="";																	
						return true;
					}
				}	
			});		 	
		
  	} else {
	  	$('txtAvisoEmail').innerHTML = "<font color='red'>&nbsp;&nbsp; Ingresar un e-mail v&aacute;lido</font>";
	  	txtEmail.value = "";
	  	txtEmail.focus();
	    return false;
  	}
}

var verificar = function(){
	if($('txtFlat').value<1){
		if($('txtSuscri_numdoc').value!='' && $('txtSuscri_appat').value!='' && $('txtSuscri_apmat').value!='' && $('txtSuscri_nom').value!='' ){
			new Ajax.Request('modulos/registrate.php?accion=carnet',{
				method:'post',
				parameters:'txtComunidad_id=3&txtSuscri_numdoc='+$('txtSuscri_numdoc').value+'&txtSuscri_appat='+$('txtSuscri_appat').value+'&txtSuscri_apmat='+$('txtSuscri_apmat').value+'&txtSuscri_nom='+$('txtSuscri_nom').value,
				onSuccess: function(transport,json){
					if(json=='2'){
						new Ajax.Request('modulos/registrate.php?accion=datoscarnet',{
							method:'post',
							parameters:'txtComunidad_id=1&txtAfi_nrocarnet='+$('txtAfi_nrocarnet1').value,
							onComplete:function(){
								alert('Ya eres parte del Club de Suscriptores, se te ha enviado un correo con los datos de acceso')
							}
						});	
					}else if(json=='1'){
						return true;
					}else{
						alert('Por favor llene todos los datos que se encuentrar con (*) ');
					}
				}
			});	
		}
	}
}

function existe(){
	if($('txtSuscri_numdoc').value!='' && $('numdoc').value!='' && $('txtSuscri_email').value!=''){
		new Ajax.Request('modulos/registrate.php?accion=dni',{
			method:'post',
			parameters:'txtSuscri_numdoc='+$('txtSuscri_numdoc').value+'&txtSuscri_email='+$('txtSuscri_email').value,
			onComplete: function(transport,json){
				if(json='1'){
					alert('Ya se encuentra registrado');
					$('numdoc').value='';
					$('frm').reset();
					return false;
				}
			}
		});
	}
}

function upperCase(x){
	var y=document.getElementById(x).value;
	document.getElementById(x).value=y.toUpperCase();
}

function certifica(area){
	$('certificaframe').src='/ojo/certifica.php?area='+area;
}

function catpcha(flat){
	evaluar(flat)
}

desabilitar = function(){
	$('txtAfi_nrocarnet1').disabled=true;$('txtSuscri_appat').disabled=true;$('txtSuscri_apmat').disabled=true;$('txtSuscri_nom').disabled=true;$('txtSuscri_numdoc').disabled=true;$('lstTipodoc_id').disabled=true;$('txtFlat').value=1;
}
var regresar=function(path){
	new Ajax.Updater('contenidoclub',path+'/modulos/login.php',{method:'get'});
}


var loginComunidad = function(email,clave,path){
 	if(email!='' && clave!=''){
	 	new Ajax.Request(location.protocol+'//'+location.hostname+'/ojo/modulos/login.php',{
	 		method:'post',
	 		parameters:'accion=login&txtEmail='+email+'&txtClave='+clave,
			onComplete:function(transport,json){
				if(json==1){
					$('contenidoclub').innerHTML = transport.responseText 
				}else if(json=3){
					$('contenidoclub').innerHTML = transport.responseText 
				}else{
					$('txtEmail').value='';
					$('txtClave').value='';
					alert('Usuario y/o Clave incorrecta');
				}
			}
	 	});
 	}else{
 		alert('Ingrese su Correo y Clave correctamente');
 	}
 }
 
var logoutComunidad = function(path){
 	var flat=0;
 	new Ajax.Updater('contenidoclub',location.protocol+'//'+location.hostname+'/ojo/modulos/login.php',{
 		method:'post',
 		parameters:'accion=logout',
 		onComplete:function(){
			location.href='indice.php';
 		}
 	});
 	if(flat==1){
 		location.href=path+'/indice.php';
 	}
 }

var recuperarLogin = function(correo,fecnac,path){
	new Ajax.Request(path+'/modulos/login.php',{
		method:'post',
		parameters:'txtSuscri_email='+correo+'&txtSuscri_fecnac='+fecnac+'&accion=olvido',
		onComplete: function(transport,json){
			if(json==1){
				alert('Por favor revisa tu correo electronico!');
				$('txtSuscri_email').value='';
				$('txtSuscri_fecnac').value='';
				$('tabla05').hide();
			}else if(json==2){
				alert('No se ha podido enviar el mail.Vuelve a intentarlo mas tarde');
			}else{
				alert('No es una cuenta valida y/o no estás registrado');
			}
		}
	});
}

var registrate= function(path){
	new Ajax.Updater('contenidoclub',path+'/modulos/registrate.php',{	method:'post',evalScripts:true});
}