function validarDireccion(f){
	if(f.Calle.value.length < 2){
		alert('Error su calle debe contener almenos 3 caracteres');
		f.Calle.focus();
		return false;
		
	}
	else{
		if(f.Numero.value.length < 2){
			alert('Error su numero esta incorrecto');
			f.Numero.focus();
			return false;
			
		}
		else{
			if(f.Region.selectedIndex==0){
				alert("Debe seleccionar una region.")
				f.Region.focus();
				return false;
    		}
    		else{
    			if(f.Comuna.selectedIndex==0){
					alert("Debe seleccionar una Comuna.")
					f.Region.focus();
					return false;
    			}
    			else{
    				f.action='misdatos.php';
    				//f.target="_parent"
    				return true;
    			}
    		} 	
			
		}
	}
}

function salida(tipo,termino){
	$.colorbox.close();
	window.location.reload();
}

function validarFinalCarro(f){
	if(validarEmail(f.Email.value) && validaSelect(f.comunaDespacho, "Debes seleccionar una direccion de despacho.") && validaSelect(f.fonodespacho, "Debes seleccionar un telefono de contacto.")){
		f.action="compra.php?pagar=1";
		f.submit();
	}	
}

function cerrarColorbox(){
	$.colorbox.close();
	//window.location.reload();
	//document.location="index.php";
	location.reload(true);
}

function cerrarColorboxError(error){
	$.colorbox.close();
	switch(error){
		case 1: 
			Sexy.error('Error de RUT y clave'); 
		break;
	}
}

function alertasCarro(alerta){
	Sexy.error(alerta);
}

function validaText(text, error){
	if(text.length <=1){
		alert(error);
		return false;
	}
	else {return true; }
	
}

function validaNum(num, error){
	
	if(!isNaN(num) && num < 1){
		alert(error);
		return false;
	}
	else {return true; }
	
}

function validaSelect(select, error){
	//alert(select.selectedIndex);
	if(select.selectedIndex==0){
		alertasCarro(error);
		return false;
	}
	else{
		return true;
	}
}

function claveValidator(pass, pass2){
	if(pass.length >= 4){
		if(pass==pass2){
			return true;
		}
		else{
			alert('sus claves no coinciden');
			return false;
		}
	}
	else{
		alert('La clave debe tener al menos 4 caracteres');
		return false;
	}
}

function Valida_Rut(Objeto, err){
	if(EsRut(Objeto)){
		return true;
	}
	else{
		alertasCarro(err);
		return false;
	}
}

function isRut(value){
	   
	   if(value == ''){
		   return false;
		   
	   }
	   var rexp = new RegExp(/^([0-9])+\-([kK0-9])+$/);
	   if(!value.match(rexp)){
		   return false;
	   }
	   var RUT  = value.split("-");
	   var elRut = RUT[0];
	   var factor = 2;
	   var suma = 0;
	   var dv;
	   
	   for(i=(elRut.length-1); i>=0; i--){
		   factor = factor > 7 ? 2 : factor;
		   suma += parseInt(elRut[i])*parseInt(factor++);
	   }
	   var ret = true;
	   dv = 11 -(suma % 11);
	   if(dv == 11){
		   dv = 0;
	   }else if (dv == 10){
		   dv = "k";
	   }
	   if(dv != RUT[1].toLowerCase()){
		   ret= false;
	   }
	   return ret
}
//
function EsRut(texto)
{   
   var tmpstr = "";   
   for ( i=0; i < texto.length ; i++ )      
      if ( texto.charAt(i) != ' ' && texto.charAt(i) != '.' && texto.charAt(i) != '-' )
         tmpstr = tmpstr + texto.charAt(i);   
   texto = tmpstr;   
   largo = texto.length;   

   if ( largo < 2 )   
   {      
      return false;   
   }   

   for (i=0; i < largo ; i++ )   
   {         
      if ( texto.charAt(i) !="0" && texto.charAt(i) != "1" && texto.charAt(i) !="2" && texto.charAt(i) != "3" && texto.charAt(i) != "4" && texto.charAt(i) !="5" && texto.charAt(i) != "6" && texto.charAt(i) != "7" && texto.charAt(i) !="8" && texto.charAt(i) != "9" && texto.charAt(i) !="k" && texto.charAt(i) != "K" )
      {         
         return false;      
      }   
   }   

   var invertido = "";   
   for ( i=(largo-1),j=0; i>=0; i--,j++ )      
      invertido = invertido + texto.charAt(i);   
   var dtexto = "";   
   dtexto = dtexto + invertido.charAt(0);   
   dtexto = dtexto + '-';   
   cnt = 0;   

   for ( i=1,j=2; i<largo; i++,j++ )   
   {      
      if ( cnt == 3 )      
      {         
         dtexto = dtexto + '.';         
         j++;         
         dtexto = dtexto + invertido.charAt(i);         
         cnt = 1;      
      }      
      else      
      {            
         dtexto = dtexto + invertido.charAt(i);         
         cnt++;      
      }   
   }   

   invertido = "";   
   for ( i=(dtexto.length-1),j=0; i>=0; i--,j++ )      
      invertido = invertido + dtexto.charAt(i);   

   if ( revisarDigito(texto) )      
      return true;   

   return false;
}

function revisarDigito(componente)
{   
   var crut =  componente
   largo = crut.length;   
   if ( largo < 2 )   
   {      
      return false;   
   }   
   if ( largo > 2 )      
      rut = crut.substring(0, largo - 1);   
   else      
   rut = crut.charAt(0);   
   dv = crut.charAt(largo-1);   
   
   if ( dv != '0' && dv != '1' && dv != '2' && dv != '3' && dv != '4' && dv != '5' && dv != '6' && dv != '7' && dv != '8' && dv != '9' && dv != 'k'  && dv != 'K')   
   {      
      return false;   
   }      

   if ( rut == null || dv == null )
      return 0   

   var dvr = '0'   
   suma = 0   
   mul  = 2   

   for (i= rut.length -1 ; i >= 0; i--)   
   {   
      suma = suma + rut.charAt(i) * mul      
      if (mul == 7)         
         mul = 2      
      else             
         mul++   
   }   
   res = suma % 11   
   if (res==1)      
      dvr = 'k'   
   else if (res==0)      
      dvr = '0'   
   else   
   {      
      dvi = 11-res      
      dvr = dvi + ""   
   }
   if ( dvr != dv)   
   {      
      return false   
   }

   return true
}
//
function rutXXvalidate(rut){
		 var rexp = new RegExp(/^([0-9])+\-([kK0-9])+$/);
		 if(rut.match(rexp)){
		     var RUT = rut.split("-");
		     var elRut = RUT[0];
		     var factor = 2;
		     var suma = 0;
		     var dv;
		     for(i=(elRut.length-1); i>=0; i--){
		         factor = factor > 7 ? 2 : factor;
		         suma += parseInt(elRut[i])*parseInt(factor++);
		     }
		     dv = 11 -(suma % 11);
		     if(dv == 11){
		         dv = 0;
		     }else if (dv == 10){
		         dv = "k";
		     }

		     if(dv == RUT[1].toLowerCase()){
		         //alert("El rut es válido!!");
		         return true;
		     }else{         
		         //alert("El rut es incorrecto");
		         return false;
		     }
		 }else{     
		     //alert("Formato incorrecto");
		     return false;
		}
}

function validarForm(f){
	if(Valida_Rut(f.rut.value+"-"+f.dv.value, 'Tu Rut esta incorrecto') && validaSelect(f.iano, 'Debes ingresar el a\u00f1o de ingreso.') && validaSelect(f.imes, 'Debes ingresar el mes de ingreso.') && validaSelect(f.idia, 'Debes ingresar el d\u00eda de ingreso.') && validaFecha(f) && validarEmail(f.mail.value) && validaRutOpt(f.rutC.value+'-'+f.dvC.value, 'El Rut(CONYUGE) esta incorrecto') && validaRutOpt(f.rutR.value+'-'+f.dvR.value, 'El Rut(EMPRESA) esta incorrecto') && validaSelect(f.placacentro,"Debes ingresar un Placacentro") && validaText(f.nombre.value, "Debes ingresar tu nombre") && validaText(f.apellidoP.value, "Debes ingresar tu apellido paterno") && validaText(f.apellidoM.value, "Debes ingresar tu apellido materno") && validaText(f.calle.value, "Debes ingresar tu calle") && validaNum(f.numero.value, "Debes ingresar el n\u00famero de tu direcci\u00f3n") && validaSelect(f.region,"Debes ingresar tu regi\u00f3n") && validaSelect(f.comuna,"Debes ingresar tu comuna") && claveValidator(f.clave.value, f.reClave.value)){
		f.action="index.php?option=com_content&view=article&id=10&Itemid=12&paseVerif=007";
		return true;
	}
	else{
		return false;
	}
	return false;
}

function validarCampoRut(evt){
	
	var code = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
	//alert(code);
	if(code >= 48 && code <= 57 || code ==37 || code == 8 || code == 46 || code == 9){
		return true;
	}
	else{
		return false;
	}	
}

function validarCampoDv(evt){
	
	var code = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
	//alert(code);
	if(code >= 48 && code <= 57 || code == 75 || code == 107 || code ==37 || code == 8 ||  code == 46 || code == 9){
		return true;
	}
	else{
		return false;
	}	
}

function validaRutOpt(rut, err){
	
	if(rut=='-'){
		return true;
	}
	else{
		if(Valida_Rut(rut, err)){
			return true;
		}
		return false;
	}
}

function validarEmail(valor) { 
	if(valor!=''){
		if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)){
			return true;
		}
		else{
			alertasCarro('Tu Email est\u00e1 incorrecto.');
			return false;
		}
	}
	else{
		alertasCarro('Tu Email est\u00e1 incorrecto.');
		return false;
	}
}

function validarCampoText(evt){
	
	var code = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
	//alert(code);
	if(code >= 65 && code <= 90 || code >= 97 && code <= 122 || code ==37 || code == 8 || code == 46 || code == 9 || code == 32 || code == 241 || code == 209){
		
		return true;
	}
	else{
		return false;
	}	
}

function validarCampoTextNum(evt){
	
	var code = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
	//alert(code);
	if(code >= 65 && code <= 90 || code >= 97 && code <= 122 || code >= 48 && code <= 57 || code ==37 || code == 8 || code == 46 || code == 9 || code == 32 || code == 241 || code == 209){
		
		return true;
	}
	else{
		alert("S\u00f3lo debes ingresar letras y n\u00fameros, el caracter anterior no fue ingresado.");
		return false;
	}	
}

function validaFecha(f){
	fecha=new Date();
	if((f.mes.selectedIndex==1 && f.dia.selectedIndex>=28) || (f.mes.selectedIndex==3 && f.dia.selectedIndex>=30) || (f.mes.selectedIndex==5 && f.dia.selectedIndex>=30) || (f.mes.selectedIndex==8 && f.dia.selectedIndex>=30) || (f.mes.selectedIndex==10 && f.dia.selectedIndex>=30)){
		
		if((f.mes.selectedIndex==1 && f.dia.selectedIndex>=28) || (f.mes.selectedIndex==3 && f.dia.selectedIndex>=30) || (f.mes.selectedIndex==5 && f.dia.selectedIndex>=30) || (f.mes.selectedIndex==8 && f.dia.selectedIndex>=30) || (f.mes.selectedIndex==10 && f.dia.selectedIndex>=30)){
			alert('Ingresa un d\u00eda v\u00e1lido para el mes elegido');
		}
		return false;
	}
	else if(fecha.getFullYear() - f.ano.value <18){
		alert('Debe tener mas de 17 a\u00f1os para registrarse.');
		return false;
	}
	else{
		return true;
	}
}	

function validarAlfanumericos(campo) {
	    patron=/^[a-zA-Z áéíóúAÉÍÓÚÑñè0-9\s]+$/; 
	    if(!patron.test(campo.value) || campo.value.length < 3){ 
	    	Sexy.error('S\u00f3lo se permiten letras y n\u00fameros para comenzar la b\u00fasqueda y un m\u00ednimo de 3 caracteres');
			return false; 
		}else{
			return true;
		}			
}

//menu en jquery 
$(document).ready(function(){

	$("#nicemenu img.arrow").click(function(){ 
								
		$("span.head_menu").removeClass('active');
		
		submenu = $(this).parent().parent().find("div.sub_menu");
		
		if(submenu.css('display')=="block"){
			$(this).parent().removeClass("active"); 	
			submenu.hide(); 		
			$(this).attr('src','images/arrow_hover.png');									
		}else{
			$(this).parent().addClass("active"); 	
			submenu.fadeIn(); 		
			$(this).attr('src','images/arrow_select.png');	
		}
		
		$("div.sub_menu:visible").not(submenu).hide();
		$("#nicemenu img.arrow").not(this).attr('src','images/arrow.png');
						
	})
	.mouseover(function(){ $(this).attr('src','images/arrow_hover.png'); })
	.mouseout(function(){ 
		if($(this).parent().parent().find("div.sub_menu").css('display')!="block"){
			$(this).attr('src','images/arrow.png');
		}else{
			$(this).attr('src','images/arrow_select.png');
		}
	});

	$("#nicemenu span.head_menu").mouseover(function(){ $(this).addClass('over')})
								 .mouseout(function(){ $(this).removeClass('over') });
	
	$("#nicemenu div.sub_menu").mouseover(function(){ $(this).fadeIn(); })
							   .blur(function(){ 
							   		$(this).hide();
									$("span.head_menu").removeClass('active');
								});		
								
	$(document).click(function(event){ 		
			var target = $(event.target);
			if (target.parents("#nicemenu").length == 0) {				
				$("#nicemenu span.head_menu").removeClass('active');
				$("#nicemenu div.sub_menu").hide();
				$("#nicemenu img.arrow").attr('src','images/arrow.png');
			}
	});			   

	function gup( name ){
		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp ( regexS );
		var tmpURL = window.location.href;
		var results = regex.exec( tmpURL );
		if( results == null )
			return "";
		else
			return results[1];
	}

	if(gup('errTT')==1){
		//$.colorbox({href:"/images/alertaErrorregistro.jpg"});
		alertasCarro('Error con tu registro. Intenta nuevamente.');
	}
	else if(gup('status')==1){
		//$.colorbox({href:"/images/alertaRegistro.jpg"});
		Sexy.info('Has sido registrado satisfactoriamente.');
	}
	else if(gup('status')==3){
		//$.colorbox({href:"/images/alertaRUTrepetido.jpg"});
		alertasCarro('Este RUT ya est&aacute; registrado, si tienes problemas al loguearte haz click en "Recuperar clave".');
	}
	else if(gup('status')==2){
		//$.colorbox({href:"/images/alertaErrorregistro.jpg"});
		alertasCarro('Error con tu registro. Intenta nuevamente.');
	}
	
});

//validador de registro usuario
function validarRegistroUsuario(f){
	if(Valida_Rut(f.rut.value + '-' + f.dv.value, 'Su rut es incorrecto.')){
		if(f.nombres.value.length<3){
			alertasCarro('Su nombre debe tener mas de 2 caracteres');
			f.nombres.focus();
			return false;
		}
		else{
			if(f.apat.value.length<3){
				alertasCarro('Su apellido paterno debe tener mas de 2 caracteres');
				f.apat.focus();
				return false;
			}
			else{
				if(f.amat.value.length<3){
					alertasCarro('Su apellido materno debe tener mas de 2 caracteres');
					f.amat.focus();
					return false;
				}
				else{
					if(!validarEmail(f.email.value)){
						alertasCarro('Sus E-mail esta incorrecto');
						f.email.focus();
						return false;
					}
					else{
						if(f.pass.value.length <= 3){
							alertasCarro('Su claves debe contener mas de 3 caracteres');
							f.pass.focus();
							return false;
						}
						else{
							return true;
						}
					}
				}
			}
		}
	}
	else{
		return false;
	}
}
//fin de validador de registro de usuario.

$(document).ready(function(){
	
	$.getJSON('http://twitter.com/status/user_timeline/megustaelvinocl.json?count=3&callback=?', function(data){
		$.each(data, function(index, item){
			$('#twitter').append('<div class="tweet"><p>' + item.text.linkify() + '</p><p><strong>' + relative_time(item.created_at) + '</strong></p></div>');
		});
	
	});	
		
	function relative_time(time_value) {
	  var values = time_value.split(" ");
	  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	  var parsed_date = Date.parse(time_value);
	  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	  delta = delta + (relative_to.getTimezoneOffset() * 60);
	  
	  var r = '';
	  if (delta < 60) {
		r = 'a minute ago';
	  } else if(delta < 120) {
		r = 'couple of minutes ago';
	  } else if(delta < (45*60)) {
		r = (parseInt(delta / 60)).toString() + ' minutos';
	  } else if(delta < (90*60)) {
		r = 'an hour ago';
	  } else if(delta < (24*60*60)) {
		r = '' + (parseInt(delta / 3600)).toString() + ' horas';
	  } else if(delta < (48*60*60)) {
		r = '1 day ago';
	  } else {
		r = (parseInt(delta / 86400)).toString() + ' días';
	  }
	  
	  return r;
	}
	
	String.prototype.linkify = function() {
		return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
			return m.link(m);
		});
	};

});

