function objetoAjax(){
	var xmlhttp=false;
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
		   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			xmlhttp = false;
  		}
	}

	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}

function PaginadorResultados(page)
{
	jQuery('#divLoading').show();
	jQuery('#divResults').hide();
	
	jQuery.post('cotizador-resultados-listado.php', { busc_prod: jQuery("#buscProd").val(), pag: page, prods: jQuery("#productos").val() }, function(data) {
		jQuery('#filaResultados').html(data);
		jQuery('#divLoading').hide();
		jQuery('#divResults').show();
	});
}

function Paginador(pagina, pag, div, nro, param){
 	param += "&prods="+$("productos").value;
	
	divContenido = document.getElementById(div);
  	ajax=objetoAjax();
	ajax.open("GET", pagina+"?"+pag+"="+nro+param);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			divContenido.innerHTML = ajax.responseText
		}
	}
	ajax.send(null)
}

function agregarProducto(id){
	cant 	= $("cant_"+id).value;	
	unid 	= $("unid_"+id).value;
	
	sacarProd(id, "productos");
	if( cant > 0){				
		if( cant != "" ){
			prod = "["+id+","+cant+","+unid+"]";
			
			if( $("productos").value == "" ){
				$("productos").value = prod;
			}else{
				$("productos").value += ";"+prod;
			}
		}
	}
}

function sacarProd(id, campo){
	
	var cadena = $(campo).value
	prods = cadena.split(";");
	campoNuevo = "";
	
	for(var i=0;i<prods.length;i++){
		datos = prods[i].substring(1, (prods[i].length)-1).split(",");
		
		if( datos[0] != id ){
			agrProd = prods[i];	
			if( campoNuevo != "" ){
				campoNuevo += ";";
			}
			campoNuevo += prods[i];
		}
	} 
	$(campo).value = campoNuevo;
}

function validarProductosBusq(){
	prods = $("productos").value;
	
	if( prods == "" ){
		alert("Debe seleccionar por lo menos un producto para agregar");
		return false;
	}else{
		inputs = jQuery('.validCant');
		flagValid = true;
		
		jQuery.each(inputs, function() {
			if( this.value == "false" ){ 
				flagValid = false;
			}
		});
		
		if( flagValid == false ){
			alert("La cantidad de los productos seleccionados debe ser menor que la cantidad del Pack 1, o  bien multiplo y/o combinatoria de los packs");
			return false;
		}else{
			return true;
		}
		return true;
	}
}

function validarProductos(f){
	flagSel = false;	
	flagErr	= false;
	flagValid = true;
	
   	for(i=0; i<f.elements.length; i++){
	    var alertText = ""	   		
		if(f.elements[i].type == "checkbox"){
			alertText += "Element Checked? " + f.elements[i].checked + "\n"
			nombre = f.elements[i].name;
			p1 = nombre.lastIndexOf('[')+1;
			p2 = nombre.lastIndexOf(']');
			id = nombre.substring(p1,p2);
			if( f.elements[i].checked){
				flagSel = true;	
				cant = document.getElementById("cant_"+id);
				if( cant.value < 1 ){ 
					flagErr = true;
				} 
				
				valid = document.getElementById("valid_"+id).value;
				if( valid == "false" ){ 
					flagValid = false;
				} 
			}
		}		
    }
	
	if( flagSel == false ){
		alert("Debe seleccionar por lo menos un producto para agregar");
		return false;
	}else if( flagErr == true ){
		alert("Debe ingresar la cantidad de todos los productos seleccionados");
		return false;
	}else if( flagValid == false ){
		alert("La cantidad de los productos seleccionados debe ser menor que la cantidad del Pack 1, o  bien multiplo y/o combinatoria de los packs");
		return false;		
	}else{
		return true;
	}		
}

function validarProductosEdit(){
	inputsPacks = jQuery('.validCant');
	flagValidPack = true;
	
	jQuery.each(inputsPacks, function() {
		if( this.value == "false" ){ 
			flagValidPack = false;
		}
   	});
	
	inputsCant = jQuery('.cantProd');
	flagValidCant = true;
	
	jQuery.each(inputsCant, function() {
		if( this.value == "" || this.value == "0" ){ 
			flagValidCant = false;
		}
   	});	
	
	if( flagValidCant == false ){
		alert("La cantidad de los productos debe ser mayor a 0");
		return false;
	}else if( flagValidPack == false ){
		alert("La cantidad de los productos debe ser menor que la cantidad del Pack 1, o  bien multiplo y/o combinatoria de los packs");
		return false;
	}else{
		return true;
	}
}

function validarBusc(f){	
	if( f.busc_prod.value == "" ){ 
		alert("Debe ingresar parte del nombre o codigo a buscar");
		return false;
	}else{
		return true;
	}
}

function validarCant(campo){
	
	valor = campo.value.replace(/,/gi, ".");
	
	if( valor != "" ){ 
		if( isNaN(valor) ){
			campo.value = "";
			alert("Debe ingresar valores numericos");
		}else{
			/*
			if(campo.value == 0){
				campo.value = "";
				alert("La cantidad debe ser mayor a 0");	
			} else {
				campo.value = valor;
			}
			*/
			campo.value = valor;
		}
	}
}

function validarCantPacks(campo, id, pack1, pack2, pack3, showAlert){
	
	if( campo.value != "" ){ 
		if( isNaN(campo.value) ){
			campo.value = "";
			if(showAlert) alert("Debe ingresar valores numericos");
		}else{
			if( pack1==0 && pack2==0 && pack3==0 ){
				return true;
			}else{
				cantSolic = campo.value;
				//Si cantidad_solicitada es múltiplo de alguno de los packs ó cantidad_solicitada < pack1 --> ÉXITO.
				if( cantSolic < pack1 || (cantSolic%pack1)==0 || (cantSolic%pack2)==0 || (cantSolic%pack3)==0 )
				{
					$("valid_" + id).value = true;
					return true;	
				}
				//Sino
				cantAux = cantSolic;
	
				//Verifico las combinaciones para el pack3
				if(pack3 != 0)
				{
					while(cantAux > pack3)
					{
						cantAux = cantAux - pack3;
						if( (cantAux%pack1)==0 || (cantAux%pack2)==0 || (cantAux%pack3)==0 )
						{
							$("valid_" + id).value = true;
							return true;
						}
					}
				}
				
				//Sigo con la cantidad auxiliar que quedó del ciclo anterior.
				if(pack2 != 0)
				{
					while(cantAux > pack2)
					{
						cantAux = cantAux - pack2;
						if( (cantAux%pack1)==0 || (cantAux%pack2)==0 || (cantAux%pack3)==0 )
						{
							$("valid_" + id).value = true;
							return true;
						}
					}
				
					//Vuelvo a la cantidad solicitada original y verifico nuevamente con el pack2
					cantAux = cantSolic;
					
					while(cantAux > pack2)
					{
						cantAux = cantAux - pack2;
						if( (cantAux%pack1)==0 || (cantAux%pack2)==0 || (cantAux%pack3)==0 )
						{
							$("valid_" + id).value = true;
							return true;
						}
					}
				}
				
				//Si no hubo ÉXITO, el valor no es válido.
				if(showAlert) alert("La cantidad debe ser menor que la cantidad del Pack 1, o  bien multiplo y/o combinatoria de los packs.\nLos packs de este producto son de " + pack1 + ", " + pack2 + " y " + pack3 + " unidades.");
				$("valid_" + id).value = false;
				return false;
			}
		}
	}
}


//funcion para habilitar las cantidades
//recibe el id del producto y la cantidad de combos a hablitar
function habilitarCant(id, campo){
	
	check = "check["+id+"]";
	if( $(check).checked ){
		valorCmb = false;		
	}else{
		valorCmb = true;
	}
	
	$("cant_"+id).disabled = valorCmb;
	$("unid_"+id).disabled = valorCmb;
	
	if( valorCmb == true) $("cant_"+id).value = "";

	if( valorCmb == true){
		//sacarProd(id, campo);
	}
}

function habilitarCantBuscador(id, campo){
	
	check = "check["+id+"]";
	if( $(check).checked ){
		valorCmb = false;		
	}else{
		valorCmb = true;
	}
	
	$("cant_"+id).disabled = valorCmb;
	$("unid_"+id).disabled = valorCmb;
	
	if( valorCmb == true) $("cant_"+id).value = "";

	if( valorCmb == true){
		sacarProd(id, campo);
	}
}

function validateFormAgr(f){	
	codigo 	= f.agr_codigo.value;
	cant 	= f.agr_cant.value;
	//unid 	= f.agr_unid.value;
	error 	= "";
	
	if( codigo == "" ) 	error += "Debe ingresar el codigo\n";
	if( cant == "" ) 	error += "Debe ingresar la cantidad\n";
	//if( unid == "" ) 	error += "Debe seleccionar la unidad de medidad\n";
	
	if (error) {
		alert("AGREGAR PRODUCTOS POR CODIGO\n"+error);
		return false;
	}
	else{
		validateAgr(f);
		return false;
	}
}
function validateAgr(f){	
	codigo 	= f.agr_codigo.value;
	cant 	= f.agr_cant.value;
	//unid 	= f.agr_unid.options[f.agr_unid.selectedIndex].value;
	
	jQuery.post("cotizador-buscador-validate.php", { "codigo": codigo, "cant": cant },
   		function(data){
    		if(data.error){
				alert("AGREGAR PRODUCTOS POR CODIGO\n"+data.error);
				return false;
			}
			
			window.location = "cotizador-buscador-agregar.php?codigo="+codigo+"&cant="+cant;
			return true;
			
   		}, "json");
}

function validateFormLogin(f){	
	sap 	= f.log_sap.value;
	email 	= f.log_email.value;
	pass 	= f.log_pass.value;
	error 	= "";
	
	if( sap == "" ){
		error += "Debe completar el campo: Numero de cliente\n";
	}else if(isNaN(sap)){
		error += "El campo Numero de cliente debe ser numerico\n";
	}
	if( pass != "clientevip" && email == "" ) 	error += "Debe completar el campo: E-mail\n";
	if( pass == "" ) 	error += "Debe completar el campo: Contrase"+String.fromCharCode(241)+"a \n";
	
	if (error) {
		alert("INGRESAR A LA CUENTA\n"+error);
		return false;
	}
	else{
		//validateLogin(f);
		//return false;
		jQuery.post('cotizador-login-validate.php', { sap: sap, email: email, pass: pass }, function(data) {																								 	
			if( data == "0"){
				alert("Los datos ingresados son incorrectos.");
				//alert("En breve se podra operar con esta herramienta para sus solicitudes on line.");
				return false;					
			} else if( data == "2"){
				alert("El cliente ya está registrado.");
				return false;										
			}else{
				f.submit();
				//window.location = "cotizador-login-entrar.php?sap="+sap+"&email="+email+"&pass="+pass;
				return true;					
			}
		});
		return false;
	}
} 

function validateLogin(f){	
	sap 	= f.log_sap.value;
	email 	= f.log_email.value;
	pass 	= f.log_pass.value;	
	
	ajax=objetoAjax();
	ajax.open("GET", "cotizador-login-validate.php?sap="+sap+"&email="+email+"&pass="+pass);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			if( ajax.responseText == 0){
				alert("Los datos ingresados son incorrectos.");
				//alert("En breve se podra operar con esta herramienta para sus solicitudes on line.");
				return false;
			}else{
				window.location = "cotizador-login-entrar.php?sap="+sap+"&email="+email+"&pass="+pass;
				return true;
			}
		}
	}
	ajax.send(null);
}

function validateOlvidoPass(f){	
	email 	= f.email.value;
	
	ajax=objetoAjax();
	ajax.open("GET", "cotizador-olvido-contrasena-validar.php?email="+email);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			if( ajax.responseText == 0){
				alert("El e-mail ingresado no pertece a un usuario registrado.");
				return false;
			}else{
				f.submit();
				return true;
			}
		}
	}
	ajax.send(null);
}

function validarSelec(campo){	
	radioSel = jQuery("#formCotiz input:radio:checked").val();
	
	if( radioSel == "" || radioSel == undefined ){
		alert("Debe seleccionar una cotizacion");
	}else{
		location='cotizador-anterior.php?ped='+radioSel;
	}
}

function validarFormVisitante(f){
	valid = true;
	arrayError = new Array();

	if( jQuery('#formVisitante').find('#razon_social').val() == "" ){
		arrayError.push("Debe completar su razon social");
		valid = false;
	}
	if( jQuery('#formVisitante').find('#nombre').val() == "" ){
		arrayError.push("Debe completar su nombre");
		valid = false;
	}
	if( jQuery('#formVisitante').find('#apellido').val() == "" ){
		arrayError.push("Debe completar su apellido");
		valid = false;
	}	
	if( jQuery('#formVisitante').find('#email').val() == "" ){
		arrayError.push("Debe completar su email");
		valid = false;
	}else{
		if( jQuery('#formVisitante').find('#email').val() != jQuery('#formVisitante').find('#re_email').val() ){
			arrayError.push("El email y su confirmacion no coinciden");
			valid = false;	
		}
	}
	if( jQuery('#formVisitante').find('#telefono').val() == "" ){
		arrayError.push("Debe completar su telefono");
		valid = false;
	}	
	if( jQuery('#formVisitante').find('#recaptcha_response_field').val() == "" ){
		arrayError.push("Debe completar el captcha");
		valid = false;
	}
	
	if(!valid){
		alert(arrayError.join('\n'));
		return false;
	}
	return true;
}

//------------------------------------------------------------------------------------------------

function utf8_encode( argString ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
 
    var string = (argString+'').replace(/\r\n/g, "\n").replace(/\r/g, "\n");
 
    var utftext = "";
    var start, end;
    var stringl = 0;
 
    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;
 
        if (c1 < 128) {
            end++;
        } else if((c1 > 127) && (c1 < 2048)) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }
 
    if (end > start) {
        utftext += string.substring(start, string.length);
    }
 
    return utftext;
}

function acentos(x) {
// version 040623
	// Spanish - Español
	// Portuguese - Portugués - Português
	// Italian - Italiano
	// French - Francés - Français
	// Also accepts and converts single and double quotation marks, square and angle brackets
	// and miscelaneous symbols.
	// Also accepts and converts html entities for all the above.
//	if (navigator.appVersion.toLowerCase().indexOf("windows") != -1) {return x}
	x = x.replace(/¡/g,"\xA1");	x = x.replace(/&iexcl;/g,"\xA1");
	x = x.replace(/¿/g,"\xBF");	x = x.replace(/&iquest;/g,"\xBF");
	x = x.replace(/À/g,"\xC0");	x = x.replace(/&Agrave;/g,"\xC0");
	x = x.replace(/à/g,"\xE0");	x = x.replace(/&agrave;/g,"\xE0");
	x = x.replace(/Á/g,"\xC1");	x = x.replace(/&Aacute;/g,"\xC1");
	x = x.replace(/á/g,"\xE1");	x = x.replace(/&aacute;/g,"\xE1");
	x = x.replace(/Â/g,"\xC2");	x = x.replace(/&Acirc;/g,"\xC2");
	x = x.replace(/â/g,"\xE2");	x = x.replace(/&acirc;/g,"\xE2");
	x = x.replace(/Ã/g,"\xC3");	x = x.replace(/&Atilde;/g,"\xC3");
	x = x.replace(/ã/g,"\xE3");	x = x.replace(/&atilde;/g,"\xE3");
	x = x.replace(/Ä/g,"\xC4");	x = x.replace(/&Auml;/g,"\xC4");
	x = x.replace(/ä/g,"\xE4");	x = x.replace(/&auml;/g,"\xE4");
	x = x.replace(/Å/g,"\xC5");	x = x.replace(/&Aring;/g,"\xC5");
	x = x.replace(/å/g,"\xE5");	x = x.replace(/&aring;/g,"\xE5");
	x = x.replace(/Æ/g,"\xC6");	x = x.replace(/&AElig;/g,"\xC6");
	x = x.replace(/æ/g,"\xE6");	x = x.replace(/&aelig;/g,"\xE6");
	x = x.replace(/Ç/g,"\xC7");	x = x.replace(/&Ccedil;/g,"\xC7");
	x = x.replace(/ç/g,"\xE7");	x = x.replace(/&ccedil;/g,"\xE7");
	x = x.replace(/È/g,"\xC8");	x = x.replace(/&Egrave;/g,"\xC8");
	x = x.replace(/è/g,"\xE8");	x = x.replace(/&egrave;/g,"\xE8");
	x = x.replace(/É/g,"\xC9");	x = x.replace(/&Eacute;/g,"\xC9");
	x = x.replace(/é/g,"\xE9");	x = x.replace(/&eacute;/g,"\xE9");
	x = x.replace(/Ê/g,"\xCA");	x = x.replace(/&Ecirc;/g,"\xCA");
	x = x.replace(/ê/g,"\xEA");	x = x.replace(/&ecirc;/g,"\xEA");
	x = x.replace(/Ë/g,"\xCB");	x = x.replace(/&Euml;/g,"\xCB");
	x = x.replace(/ë/g,"\xEB");	x = x.replace(/&euml;/g,"\xEB");
	x = x.replace(/Ì/g,"\xCC");	x = x.replace(/&Igrave;/g,"\xCC");
	x = x.replace(/ì/g,"\xEC");	x = x.replace(/&igrave;/g,"\xEC");
	x = x.replace(/Í/g,"\xCD");	x = x.replace(/&Iacute;/g,"\xCD");
	x = x.replace(/í/g,"\xED");	x = x.replace(/&iacute;/g,"\xED");
	x = x.replace(/Î/g,"\xCE");	x = x.replace(/&Icirc;/g,"\xCE");
	x = x.replace(/î/g,"\xEE");	x = x.replace(/&icirc;/g,"\xEE");
	x = x.replace(/Ï/g,"\xCF");	x = x.replace(/&Iuml;/g,"\xCF");
	x = x.replace(/ï/g,"\xEF");	x = x.replace(/&iuml;/g,"\xEF");
	x = x.replace(/Ñ/g,"\xD1");	x = x.replace(/&Ntilde;/g,"\xD1");
	x = x.replace(/ñ/g,"\xF1");	x = x.replace(/&ntilde;/g,"\xF1");
	x = x.replace(/Ò/g,"\xD2");	x = x.replace(/&Ograve;/g,"\xD2");
	x = x.replace(/ò/g,"\xF2");	x = x.replace(/&ograve;/g,"\xF2");
	x = x.replace(/Ó/g,"\xD3");	x = x.replace(/&Oacute;/g,"\xD3");
	x = x.replace(/ó/g,"\xF3");	x = x.replace(/&oacute;/g,"\xF3");
	x = x.replace(/Ô/g,"\xD4");	x = x.replace(/&Ocirc;/g,"\xD4");
	x = x.replace(/ô/g,"\xF4");	x = x.replace(/&ocirc;/g,"\xF4");
	x = x.replace(/Õ/g,"\xD5");	x = x.replace(/&Otilde;/g,"\xD5");
	x = x.replace(/õ/g,"\xF5");	x = x.replace(/&otilde;/g,"\xF5");
	x = x.replace(/Ö/g,"\xD6");	x = x.replace(/&Ouml;/g,"\xD6");
	x = x.replace(/ö/g,"\xF6");	x = x.replace(/&ouml;/g,"\xF6");
	x = x.replace(/Ø/g,"\xD8");	x = x.replace(/&Oslash;/g,"\xD8");
	x = x.replace(/ø/g,"\xF8");	x = x.replace(/&oslash;/g,"\xF8");
	x = x.replace(/Ù/g,"\xD9");	x = x.replace(/&Ugrave;/g,"\xD9");
	x = x.replace(/ù/g,"\xF9");	x = x.replace(/&ugrave;/g,"\xF9");
	x = x.replace(/Ú/g,"\xDA");	x = x.replace(/&Uacute;/g,"\xDA");
	x = x.replace(/ú/g,"\xFA");	x = x.replace(/&uacute;/g,"\xFA");
	x = x.replace(/Û/g,"\xDB");	x = x.replace(/&Ucirc;/g,"\xDB");
	x = x.replace(/û/g,"\xFB");	x = x.replace(/&ucirc;/g,"\xFB");
	x = x.replace(/Ü/g,"\xDC");	x = x.replace(/&Uuml;/g,"\xDC");
	x = x.replace(/ü/g,"\xFC");	x = x.replace(/&uuml;/g,"\xFC");
	x = x.replace(/\"/g,"\x22");
	x = x.replace(/\'/g,"\x27");
	x = x.replace(/\</g,"\x3C");
	x = x.replace(/\>/g,"\x3E");
	x = x.replace(/\[/g,"\x5B");
	x = x.replace(/\]/g,"\x5D");
	x = x.replace(/¢/g,"\xA2");	x = x.replace(/&cent;/g,"\xA2");
	x = x.replace(/£/g,"\xA3");	x = x.replace(/&pound;/g,"\xA3");
	x = x.replace(/€/g,"\u20AC");	x = x.replace(/&euro;/g,"\u20AC");
	x = x.replace(/©/g,"\xA9");	x = x.replace(/&copy;/g,"\xA9");
	x = x.replace(/®/g,"\xAE");	x = x.replace(/&reg;/g,"\xAE");
	x = x.replace(/ª/g,"\xAA");	x = x.replace(/&ordf;/g,"\xAA");
	x = x.replace(/º/g,"\xBA");	x = x.replace(/&ordm;/g,"\xBA");
	x = x.replace(/°/g,"\xB0");	x = x.replace(/&deg;/g,"\xB0");
	x = x.replace(/±/g,"\xB1");	x = x.replace(/&plusmn;/g,"\xB1");
	x = x.replace(/×/g,"\xD7");	x = x.replace(/&times;/g,"\xD7");
	return x;
}

//-------------------------------------------------------------------------------------------------
