var xmlHttp;

function validate_contact(theForm){	
	if (!validRequired(theForm.nombre, "Name"))
		return false;
		
	if (!validEmail(theForm.email, "E-mail", true))
 		return false;

    if (!validRequired(theForm.pais, "Country"))
		return false;
	
	if (!validarImagenes(theForm.ciudad, "City"))
		return false;
	
	if (!validRequired(theForm.empresa, "Company"))
 		return false;		
		
    return true;
}

function validate_contacto(theForm){
	if (!validEmail(theForm.correo, "Correo", true))
 		return false;
		
	if (!validRequired(theForm.nombre, "Nombre"))
		return false;	
	
	return true;
}

function abrirgrande(imagen,ancho,alto){
	var anch=ancho;
	var alt=alto;
	var top = (screen.availHeight/2) - (alt/2);
	var left = (screen.availWidth/2) - (anch/2);
	abrir=window.open('','','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,menubar=no,left='+ left +',top='+ top +',width='+ anch +',height='+ alt);
	abrir.focus();
	abrir.document.writeln("<html>");
	abrir.document.writeln("<body leftmargin='0' topmargin='0' onblur='this.focus();'>");
	abrir.document.writeln("<div style='text-align:center; min-height: 10em; display: table-cell; vertical-align: middle'><img src='thumbgenerator.php?image="+ imagen +"&w="+ancho+"&h="+alto+"'></div></body></html>");	
	abrir.document.close();
	abrir.document.title = "Image Viewer";
}

function abrirFoto(imagen,ancho,alto){
	var anch=ancho;
	var alt=alto;
	var top = (screen.availHeight/2) - (alt/2);
	var left = (screen.availWidth/2) - (anch/2);
	abrir=window.open('','','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,menubar=no,left='+ left +',top='+ top +',width='+ anch +',height='+ alt);
	abrir.focus();
	abrir.document.writeln("<html>");
	abrir.document.writeln("<body leftmargin='0' topmargin='0' onblur='this.focus();'>");
	abrir.document.writeln("<div style='text-align:center; min-height: 10em; display: table-cell; vertical-align: middle'><img src='../admin/thumbgenerator.php?image="+ imagen +"&w="+ancho+"&h="+alto+"'></div></body></html>");	
	abrir.document.close();
	abrir.document.title = "Image Viewer";
}

function popnew(url,ancho,largo,status){
	x = (screen.width/2)-(ancho/2);
	y = (screen.height/2)-(largo/2);
	popup=window.open(url,"","width="+ancho+",height="+largo+",top="+y+",left="+x+",status="+status+",location=no,menu=no,scrollbars=no,toolbar=no");
	popup.focus();
}

function validRequired(formField,fieldLabel)
{
	var result = true;
	
	if (formField.value == "")
	{
		alert('"'+fieldLabel +'" este campo es requerido');
		formField.focus();
		result = false;
	}
	
	return result;
}

function isEmailAddr(email)
{
  var result = false;
  var theStr = new String(email);
  var index = theStr.indexOf("@");
  if (index > 0)
  {
    var pindex = theStr.indexOf(".",index);
    if ((pindex > index+1) && (theStr.length > pindex+1))
	result = true;
  }
  return result;
}

function validEmail(formField,fieldLabel,required)
{
	var result = true;
	
	if (required && !validRequired(formField,fieldLabel))
		result = false;

	if (result && ((formField.value.length < 2) || !isEmailAddr(formField.value)) )
	{
		alert("Formato de e-Mail incorrecto (verifique usuario@dominio.ext)");
		formField.focus();
		result = false;
	}
   
  return result;
}

function validarImagenes(campo, titu)
  {
	  var ext_arc = campo.value.substring(campo.value.lastIndexOf(".")+1);
	  
	  if (ext_arc == "jpg" || ext_arc == "JPG" || ext_arc == "gif" || ext_arc == "GIF")
	    {
			return true;
		}
	  else
	    {
			alert("Invalid image format on field \""+titu+"\", only \".jpg\" and \".gif\" are admited");
			return false;
		}
  }
  
function validExtension(archivo, extensiones) {
   var ext = getExt(archivo);
   if(!extensiones.in_array(ext)){
	  var valid_exts = "";
	  for(var i= 0; i < extensiones.length-1; i++){
		   valid_exts += extensiones[i];
		   if(i < extensiones.length-2){
			   valid_exts += ", ";
		   }
	  }
      alert("Estension invalida para el archivo, solo se permite: "+valid_exts);
	  return false;
   }
      
   return true;
}


function getExt(filename) {
   var dot_pos = filename.lastIndexOf(".");
   if(dot_pos == -1)
      return "";
   return filename.substr(dot_pos+1).toLowerCase();

}

Array.prototype.in_array = function(p_val) {
	for(var i = 0, l = this.length; i < l; i++) {
		if(this[i] == p_val) {
			return true;
		}
	}
	return false;
}  
//****************************************************************************************************************
function validate_login(theForm)
{
	if (!validRequired(theForm.login, "Login"))
		return false;
	
	if (!validRequired(theForm.password, "Password"))
		return false;
	
    return true;
}

function validate_userinfo(theForm)
{
	if (!validRequired(theForm.nombre, "Nombre Usuario"))
		return false;
		
	if (!validEmail(theForm.email, "E-mail", true))
		return false;
	
	if (!validRequired(theForm.login, "Login"))
		return false;
		
	if(!validRequired(theForm.contrasena, "Contraseña"))
		return false;
	
	if(!validRequired(theForm.contrasena2, "Confirmar Contraseña"))
		return false;
		
	if(theForm.contrasena.value != theForm.contrasena2.value){
		alert("Confirmar nueva contraseña");
		return false;
	}
	
	if (theForm.perfil.value == ''){ 
       alert("Debe seleccionar un perfil") 
       theForm.perfil.focus() 
       return false; 
	} 
	
    return true;
}

function validate_add_profile(theForm)
{
	if (!validRequired(theForm.nombre, "Nombre"))
		return false;
	
	return true;
}

function validate_update_userinfo(theForm)
{
	if (!validRequired(theForm.nombre, "Nombre Usuario"))
		return false;
		
	if (!validEmail(theForm.email, "E-mail", true))
		return false;
	
	if (!validRequired(theForm.login, "Login"))
		return false;
	
	if(theForm.antigua_contrasena.value != ''){
		if(!validRequired(theForm.nueva_contrasena, "Nueva Contraseña"))
			return false;
		
		if(!validRequired(theForm.nueva_contrasena2, "Confirmar Contraseña"))
			return false;
		
		if(theForm.nueva_contrasena.value != theForm.nueva_contrasena2.value){
			alert("Confirmar nueva contraseña");
			return false;
		}		
	}
	
	if (theForm.perfil.value == ''){ 
       alert("Debe seleccionar un perfil") 
       theForm.perfil.focus() 
       return false; 
	} 
	
    return true;
}

function validate_changepass(theForm)
{
	if (!validRequired(theForm.old_password, "Antigua Contraseña"))
		return false;
	
	if (!validRequired(theForm.new_password, "Nueva Contraseña"))
		return false;
		
	if (!validRequired(theForm.new_password2, "Confirmar Nueva Contraseña"))
		return false;
	
	if(theForm.new_password.value != theForm.new_password2.value){
		alert("Confirmar nueva contraseña");
		return false;
	}
	
    return true;
}

function validate_bloque(theForm)
{
	if (!validRequired(theForm.title, "Title"))
		return false;
	
	if(theForm.feat_image){
		if(theForm.feat_image.value != ""){
			if (!validarImagenes(theForm.feat_image, "Featured Image"))
			   return false;
		}
	}
	
    return true;
}

function validate_producto(theForm)
{
	if(theForm.tipovalor.value == "1"){
		if (!validRequired(theForm.valord, "Valor Dólares"))
			return false;
	}
	else if(theForm.tipovalor.value == "0"){
		if (!validRequired(theForm.valorp, "Valor Pesos"))
			return false;
	}
	
	if (!validRequired(theForm.nombre, "Nombre Producto"))
		return false;
	
	if(theForm.feat_image){
		if(theForm.feat_image.value != ""){
			if (!validarImagenes(theForm.feat_image, "Imagen"))
			   return false;
		}
	}
	
	return true;
}

function validate_link(theForm){
	if(theForm.seccion.value == 0){
		alert("Please select a section for this link first");
		return false;
	}
	
	if (!validRequired(theForm.title, "Title"))
		return false;

    if (!validRequired(theForm.link_url, "Link"))
		return false;
	
    return true;
}

function validate_archivo(theForm){
	if(theForm.seccion.value == 0){
		alert("Please select a section for this file first");
		return false;
	}
	
	if (!validRequired(theForm.title, "Title"))
		return false;

    if (!validRequired(theForm.archivo, "File"))
		return false;
	
    return true;
}

function validate_archivo_edit(theForm){
	if(theForm.seccion.value == 0){
		alert("Please select a section for this file first");
		return false;
	}
	
	if (!validRequired(theForm.title, "Title"))
		return false;
	
    return true;
}


function validate_imagen(theForm){
	if(theForm.seccion.value == 0){
		alert("Please select a category for this image first");
		return false;
	}
	
	if (!validRequired(theForm.title, "Title"))
		return false;

    if (!validRequired(theForm.archivo, "Image"))
		return false;
	
	if (!validarImagenes(theForm.archivo, "Image"))
		return false;
	
    return true;
}

function validate_directorio_contactos(theForm){
	if(theForm.seccion.value == 0){
		alert("Please select a category for this image first");
		return false;
	}
	
	if (!validRequired(theForm.nombres, "Names"))
		return false;
		
	if (!validRequired(theForm.apellidos, "Last Names"))
		return false;

	if (!validEmail(theForm.email, "E-mail", true))
 		return false;

    if (!validRequired(theForm.archivo, "Image"))
		return false;
	
	if (!validarImagenes(theForm.archivo, "Image"))
		return false;
	
	if (!validRequired(theForm.telefono, "Telephono"))
 		return false;
	
	if (!validRequired(theForm.direccion, "Direccion"))
 		return false;
		
    return true;
}

function validate_catalogo(theForm){
	if(theForm.seccion.value == 0){
		alert("Por favor selecciona primero una seccion");
		return false;
	}
	if (!validRequired(theForm.nombre, "Nombre categoria"))
		return false;
	
	return true;
	
}

function validate_directorio_empresas(theForm){
	if(theForm.seccion.value == 0){
		alert("Please select a category for this image first");
		return false;
	}
	
	if (!validRequired(theForm.nombre, "Name"))
		return false;

	if (!validEmail(theForm.email, "E-mail", true))
 		return false;
	
	if (!validRequired(theForm.telefono, "Telephono"))
 		return false;
	
	if (!validRequired(theForm.direccion, "Direccion"))
 		return false;
		
    return true;
}

function validate_directorio_edit_contactos(theForm){
	if(theForm.seccion.value == 0){
		alert("Please select a section for this file first");
		return false;
	}
	
	if (!validRequired(theForm.nombres, "Names"))
		return false;
		
	if (!validRequired(theForm.apellidos, "Last Names"))
		return false;

	if (!validEmail(theForm.email, "E-mail", true))
 		return false;
	
	if (!validRequired(theForm.telefono, "Telephono"))
 		return false;
	
	if (!validRequired(theForm.direccion, "Direccion"))
 		return false;
		
    return true;
}

function validate_faq(theForm){
	if (!validRequired(theForm.question, "Question"))
		return false;
	
	if (!validRequired(theForm.answer, "Answer"))
		return false;
	
    return true;
}

function validate_user_AC(theForm)
{
	if (theForm.tipo_usuario.value == 'NO'){ 
       alert("Debe seleccionar un Tipo de Usuario") 
       theForm.tipo_usuario.focus() 
       return false; 
	} 
	
	if (theForm.tipo_usuario.value == 'PC'){ 
      if (!validRequired(theForm.dependencia, "Dependencia"))
		return false; 
	} 
	
	if (!validRequired(theForm.nombre, "Nombre"))
		return false;
	
	if (!validRequired(theForm.apellido, "Apellido"))
		return false;
		
	if (!validEmail(theForm.email, "E-mail", true))
		return false;
	
	if (!validRequired(theForm.login, "Login"))
		return false;
		
	if(!validRequired(theForm.contrasena, "Contraseña"))
		return false;
	
	if(!validRequired(theForm.contrasena2, "Confirmar Contraseña"))
		return false;
		
	if(theForm.contrasena.value != theForm.contrasena2.value){
		theForm.contrasena2.value = "";
		alert("Confirmar nueva contraseña");
		theForm.contrasena2.focus();
		return false;
	}
	
    return true;
}

function iniciar_ajax(){
var xmlHttp=null;
   var ua = navigator.userAgent.toLowerCase();
   if (!window.ActiveXObject){
     xmlHttp = new XMLHttpRequest();
   }
   else if (ua.indexOf('msie 5') == -1){
     xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
   }
   else{
     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
   }

   return xmlHttp;
}

function stateChangedVerificarLoginDuplicadoAC(theForm){ 
if (xmlHttp.readyState==4){ 
      if(xmlHttp.responseText.match("NO")){
		  theForm.submit();
		  return true;
	  }else{
		  alert("El login que ingreso ya se encuentra registrado, debe seleccionar uno nuevo");
		  return false;
	  }
   }
}

function validate_user_AC_AJAX(theForm){
	if(validate_user_AC(theForm)){
		xmlHttp = iniciar_ajax();
		if (xmlHttp == null){
		  alert ("Su navegador no soporta AJAX por consiguiente no puede realizar esta operación");
		  return false;
		}
		
		var post_data = "option=verificarLoginDuplicadoAC&login="+theForm.login.value;
		
		var url="../clases/imagine_ajax.php";
		url=url+"?uid="+Math.random();
		xmlHttp.onreadystatechange = function(){
			stateChangedVerificarLoginDuplicadoAC(theForm);
		}
		xmlHttp.open("POST",url,true);
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("Content-length", post_data.length);
		xmlHttp.setRequestHeader("Connection", "close");
		
		xmlHttp.send(post_data);
	}else{
		return false;
	}
}

function stateChangedVerificarLoginDuplicadoACEdit(theForm){ 
if (xmlHttp.readyState==4){ 
      if(xmlHttp.responseText.match("NO")){
		  theForm.submit();
		  return true;
	  }else{
		  alert("El login que ingreso ya se encuentra registrado, debe seleccionar uno nuevo");
		  return false;
	  }
   }
}

function validate_edituser_AC_AJAX(theForm){
	if(validate_user_AC(theForm)){
		xmlHttp = iniciar_ajax();
		if (xmlHttp == null){
		  alert ("Su navegador no soporta AJAX por consiguiente no puede realizar esta operación");
		  return false;
		}
		
		var post_data = "option=verificarLoginDuplicadoACEdit&login="+theForm.login.value+"&codigo="+theForm.usuario_id.value;
		
		var url="../clases/imagine_ajax.php";
		url=url+"?uid="+Math.random();
		xmlHttp.onreadystatechange = function(){
			stateChangedVerificarLoginDuplicadoACEdit(theForm);
		}
		xmlHttp.open("POST",url,true);
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("Content-length", post_data.length);
		xmlHttp.setRequestHeader("Connection", "close");
		
		xmlHttp.send(post_data);
	}else{
		return false;
	}
}

function validar_tarea_AC(theForm, tipoUsr){
	if (theForm.responsable.value == '0'){ 
       alert("Debe seleccionar un Punto de Contacto al cual dirigir su comentario") 
       theForm.responsable.focus() 
       return false; 
	}
		
	if(tipoUsr == 0){
		if (!validRequired(theForm.nombre, "Nombre"))
		return false;
	
		if (!validRequired(theForm.apellido, "Apellido"))
			return false;
			
		if (!validEmail(theForm.email, "E-mail", true))
		   return false;
	}
	
	if (!validRequired(theForm.descripcion, "Detalles de su comentario"))
		return false;
	
	if(theForm.adjunto.value != ""){
		var validExts = new Array("pdf","doc", "xls", "txt", "zip", "rar");
		if (!validExtension(theForm.adjunto.value, validExts))
		   return false;
	}
	
	return true;
}

function validar_login_AC(theForm){
	if (!validRequired(theForm.login, "Nombre de Usuario"))
		return false;
	
	if (!validRequired(theForm.password, "Contraseña"))
		return false;
	
	return true;
}

function validarLoginAC(theForm){
	if(validar_login_AC(theForm)){
		xmlHttp = iniciar_ajax();
		if (xmlHttp == null){
		  alert ("Su navegador no soporta AJAX por consiguiente no puede realizar esta operación");
		  return false;
		}
		
		var post_data = "option=validarLoginUserAC&login="+theForm.login.value+"&password="+theForm.password.value+"&seccion="+theForm.seccion.value;
		
		var url="../admin/clases/imagine_ajax.php";
		url=url+"?uid="+Math.random();
		xmlHttp.onreadystatechange = function(){
			stateChangedValidarLoginAC(theForm);
		}
		xmlHttp.open("POST",url,true);
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=iso-8859-1");
		xmlHttp.setRequestHeader("Content-length", post_data.length);
		xmlHttp.setRequestHeader("Connection", "close");
		
		xmlHttp.send(post_data);
	}else{
		return false;
	}
}

function stateChangedValidarLoginAC(theForm){ 
if (xmlHttp.readyState==4){ 
      if(xmlHttp.responseText.match("VALIDO")){
		  theForm.action = "ac_login.php";
		  theForm.submit();
		  return true;
	  }else{
		  alert("Error: "+xmlHttp.responseText);
		  return false;
	  }
   }
}

function validarNuevoRegistroAC(theForm){
	if (!validRequired(theForm.descripcion_interna, "Descripcion"))
		return false;
	
	var contenedor1 = document.getElementById("variableForm");
	
	if(contenedor1.style.display == "block"){
		if (!validRequired(theForm.descripcion_UF, "Descripcion para Usuario Final"))
		   return false;
	}
    
	return true;
}


function detectar_enter(){
	//ojo solo IE
	if(document.all){
		var e = window.event;
		if(e.keyCode == 13){
			validarLoginAC(document.form_login);
		}
	}
}

