// JavaScript Document
//alert('ldkskdls');
function correcto(field) {
	//var help = document.getElementById("help_" + field.name);
	//help.innerHTML = '';
	field.style.backgroundColor = '#fff';
}

function incorrecto(field) {
	//var help = document.getElementById("help_" + field.name);
	//help.innerHTML = '*';
	field.style.backgroundColor = '#ffeacf';
}

function validate_form_solicit(the_form) {
	var element = document.getElementById("spanErrorSolInfo");
	if(element) {
		element.style.display="none";
	}
	isAllOk=true;
	if (!validate_field(the_form['nombre'], 255)){
		isAllOk=false;
	}
	if (!validate_field(the_form['apellido'], 255)){
		isAllOk=false;
	}
	if (!validate_field(the_form['empresa'], 255)){
		isAllOk=false;
	}
	if (!emailCheck(the_form['email'])){
		isAllOk=false;
	}
	if (!validate_field(the_form['telefono'], 255)){
		isAllOk=false;
	}
	if (!validate_field(the_form['comentario'], 255)){
		isAllOk=false;
	}
	if (!validate_field(the_form['sol_codigo_imagen'], 255)){
		isAllOk=false;
	}
	if (isAllOk){
		the_form.submit();
	} else {
		var element = document.getElementById("spanErrorSolInfo");
		if(element) {
			element.style.display="block";
		}
		return false;
	}
}

function validate_form_contacto(the_form,valcaptcha) {
	var element = document.getElementById("spanErrorContacto");
	if(element) {
		element.style.display="none";
	}
	isAllOk=true;
	if (!validate_field(the_form['nombre'], 255)){
		isAllOk=false;
	}
	if (!validate_field(the_form['apellido'], 255)){
		isAllOk=false;
	}
	if (!validate_field(the_form['empresa'], 255)){
		isAllOk=false;
	}
	if (!validate_field(the_form['cargo'], 255)){
		isAllOk=false;
	}
	if (!emailCheck(the_form['email'])){
		isAllOk=false;
	}
	if (!validate_field(the_form['telefono'], 255)){
		isAllOk=false;
	}
	if (!validate_field(the_form['comentario'], 255)){
		isAllOk=false;
	}
	if (!validate_field(the_form['con_codigo_imagen'], 255)){
		isAllOk=false;
	}
	if (isAllOk){
		the_form.submit();
	} else {
		var element = document.getElementById("spanErrorContacto");
		if(element) {
			element.style.display="block";
		}
		return false;
	}
}

function validate_form_nuevo_producto1(the_form) {
	if (
		   validate_field(the_form['nombre'], 255)
		   
		&& validate_file(the_form['imagen'])   
		&& validate_file(the_form['imagen_titulo'])   
		&& validate_file(the_form['img_logo']) 
		&& validate_file(the_form['img_asociado'])
		   
		&& validate_field(the_form['frase1'], 255)
		//&& validate_field(the_form['frase2'], 255)
		
		) {
			//botUpdate.value="ok";
			the_form.submit();
			//alert("OK");
	} else {
			alert("Hay datos incompletos o erróneos. Por favor verifique los campos resaltados.");
			return false;
	}
}

function validate_form_editar_producto1(the_form) {
	if (
		   validate_field(the_form['nombre'], 255)
		&& validate_field(the_form['frase1'], 255)
		//&& validate_field(the_form['frase2'], 255)
		
		) {
			//botUpdate.value="ok";
			the_form.submit();
			//alert("OK");
	} else {
			alert("Hay datos incompletos o erróneos. Por favor verifique los campos resaltados.");
			return false;
	}
}

function validate_file(file) {
	var extensions = new Array("jpg","jpeg","gif","png","bmp");
	var image_file = file.value;
	var image_length = image_file.length;
	var pos = image_file.lastIndexOf('.') + 1;
	var ext = image_file.substring(pos, image_length);
	var final_ext = ext.toLowerCase();
	for (i = 0; i < extensions.length; i++) {
    	if(extensions[i] == final_ext) {
    		return true;
    	}
	}
	return false;
}

function validate_empty(field) {
	if(field.value.length < 1) {
		incorrecto(field);
		return false;
	} else {
		correcto(field);
		return true;
	}
}

function validate_field(field, max_length) {
    if (field.value.length == 0 || field.value.length > max_length || field.value.length < 1) {
        incorrecto(field);
        return false;
    }  else {
		correcto(field);
        return true;
    }
}

function emailCheck(emailStr_ori) {
    
    var emailStr = emailStr_ori.value;

    var checkTLD=1;
    var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
    var emailPat=/^(.+)@(.+)$/;

    var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

    var validChars="\[^\\s" + specialChars + "\]";

    var quotedUser="(\"[^\"]*\")";

    var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

    var atom=validChars + '+';

    var word="(" + atom + "|" + quotedUser + ")";

    var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

    var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

    var matchArray=emailStr.match(emailPat);

    if (matchArray==null) {
		incorrecto(emailStr_ori);
        return false;
    }
    
    var user=matchArray[1];
    var domain=matchArray[2];

    for (i=0; i<user.length; i++) {
        if (user.charCodeAt(i)>127) {
            //alert("The username contains invalid characters.");
            incorrecto(emailStr_ori);
            return false;
       }
    }
    
    for (i=0; i<domain.length; i++) {
        if (domain.charCodeAt(i)>127) {
            //alert("The domain name contains invalid characters.");
            incorrecto(emailStr_ori);
            return false;
        }
    }

    // See if "user" is valid 

    if (user.match(userPat)==null) {
        // user is not valid
        //alert("The username doesn't seem to be valid.");
        incorrecto(emailStr_ori);
        return false;
    }

    /* if the e-mail address is at an IP address (as opposed to a symbolic
    host name) make sure the IP address is valid. */

    var IPArray=domain.match(ipDomainPat);
    if (IPArray!=null) {
        // this is an IP address
        for (var i=1;i<=4;i++) {
            if (IPArray[i]>255) {
                //alert("Destination IP address is invalid!");
                incorrecto(emailStr_ori);
                return false;
           }
        }
        return true;
    }

    // Domain is symbolic name.  Check if it's valid.
 
    var atomPat=new RegExp("^" + atom + "$");
    var domArr=domain.split(".");
    var len=domArr.length;
    
    for (i=0;i<len;i++) {
        if (domArr[i].search(atomPat)==-1) {
            //alert("The domain name does not seem to be valid.");
            incorrecto(emailStr_ori);
            return false;
       }
    }
    
    /* domain name seems valid, but now make sure that it ends in a
    known top-level domain (like com, edu, gov) or a two-letter word,
    representing country (uk, nl), and that there's a hostname preceding 
    the domain or country. */
    
    if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) {
        //alert("The address must end in a well-known domain or two letter " + "country.");
        incorrecto(emailStr_ori);
        return false;
    }
    
    // Make sure there's a host name preceding the domain.
    
    if (len<2) {
        //alert("This address is missing a hostname!");
        incorrecto(emailStr_ori);
        return false;
    }
    
    // If we've gotten this far, everything's valid!
    correcto(emailStr_ori);
    return true;
}

function check_captcha(id, uservalue, where) {
	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
	else {
		// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			//element.innerHTML = xmlhttp.responseText;
			//alert(xmlhttp.responseText);
			if(where=='contacto'){
				validate_form_contacto(document.forms.contacto,xmlhttp.responseText);
			}else{
				validate_form_solicit(document.forms.solicit_info,xmlhttp.responseText);
			}
		}
	}
	
	var dateVar = new Date();
	strNC = dateVar.getYear().toString() + dateVar.getMonth().toString() + dateVar.getDay().toString() + dateVar.getHours().toString() + dateVar.getMinutes().toString() + dateVar.getSeconds().toString() + aleatorio(1,100).toString();
	xmlhttp.open("POST","_ajax/check_captcha.php?funcion=pt"+strNC,true);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xmlhttp.send("id=" + id + "&uservalue=" + uservalue);
}

