function dv(T){var M=0,S=1;for(;T;T=Math.floor(T/10))
S=(S+T%10*(9-M++%6))%11;return S?S-1:'k';}
function debug(txt){
	
	$("#debug").append(txt + "<br />")
}
function valrut(obj){
	
	tmpRut = $(obj).val();
	if(tmpRut.lastIndexOf("-") == -1){
		tmpRut = tmpRut.substring(0, tmpRut.length - 1) + "-" +  tmpRut.substring(tmpRut.length - 1, tmpRut.length)
	}
	var dg = tmpRut.substring(tmpRut.lastIndexOf("-") + 1, tmpRut.length);
	tmpRut = tmpRut.substring(0, tmpRut.lastIndexOf("-"));
	while(tmpRut.lastIndexOf(".") !== -1){
		tmpRut = tmpRut.replace(".", "")
	}
	if(tmpRut.length < 7 || tmpRut.length > 8 || isNaN(tmpRut)){
		return false;
	}
	var dig = dv(tmpRut);
	if(dg != dig){
		return false;
	}
	$(obj).val(formatRut(tmpRut)+ "-" + dg)
	return true;
}

function formatRut(rut){
	var l = rut.length;
	var out = "";
	for(var x=0; x<=l; x++){
		if(x==4 || x== 7){
			out = rut.charAt(l-x) + "." + out ;
		} else {
			out = rut.charAt(l-x) + out ;
		}
	}
	return out;
}

function validaForm(){
	
	var fields = $("input[type='text'].valida");
	
	for(var x = 0; x<fields.length; x++){
		
		if($(fields[x]).attr("title").indexOf("Rut") != -1){
			
			if(!valrut(fields[x])){
				$(fields[x]).select
				$(fields[x]).focus();
				messenger("Rut Inv&aacute;lido", "Verifique que el rut corresponda a un rut v&aacute;lido.", true);
				return false;
			}
		}
		if($.trim($(fields[x]).val()) == ""){
			$(fields[x]).val("")
			$(fields[x]).focus();
			
			messenger("Dato Requerido", "El campo <strong>" + $(fields[x]).attr("title") + "</strong> es requerido. <br />Complete los datos marcados con <span class='valida'>*</span> e intente enviar su solicitud nuevamente.", true)
			
			return false
		} 
	}
	
	return true;
}





function esInteger(e){
	var charCode
	if (navigator.appName == "Netscape"){
		charCode = e.which
	} else{
		charCode = e.keyCode
	} 
	if (charCode == 8){
		return true;
	}
	if (charCode < 48 || charCode > 57){
		messenger("Error", "Por favor teclee solo n&uacute;meros en este campo!", true); 
		return false;
	}else{
		return true;
	}
}



function showCartForm(){
	
	if  (lines.length <= 1 || lines.length == undefined){	
		messenger("Solicitar Cotizaci&oacute;n", "Debe ingresar productos a su solicitud para poder cotizar. <br />Use nuestro <strong><a href='#' id='msgCatLink'>cat&aacute;logo</a></strong> o utilice nuestro <strong><a href='#' id='msgSearchLink'>buscador</a></strong> para agregar productos.");
	$("#msgCatLink").click(function(e){
		e.preventDefault();
		showCatalog()
	});
	$("#msgSearchLink").click(function(e){
		e.preventDefault();
		$(".searchLink").click();
	})
	} else {
		$(".cartTable").hide("fast");
		$("#formDiv").show("fast");
	}
}


function attachEvents(){
	$(".cartTable input").change(function(e){
				var nc = this.name;
				for(var l=0; l<lines.length; l++){
					if(lines[l].codigo == nc){
						lines[l].qty = this.value;
						break;
					}
				}
				updateCart();
			})

	$(".cartTable td a").click(function(e){
		e.preventDefault();
		if(confirm("Para eliminar este producto haga click en Aceptar,\n para abortar haga click en Cancelar")){
			td = $(this).parent();
			tr = $(td).parent();
			
			var fldName= $(tr).find("input:first").attr("name");
		
			for(var l=0; l<lines.length; l++){
				if(lines[l].codigo == fldName){
					
					lines.splice(l, 1)
					
					updateCart()
					break;
				}
			}
		}
		
	})
}

function formatLines(){
	$(".cartTable tbody").html("");
	var l;
	for(var x=1; x< lines.length; x++){
		l = "<tr><td><a href='#'>&nbsp;&nbsp;&nbsp;</a></td><td>" + lines[x].producto + "</td><td>" + lines[x].codigo + "</td><td><input type='text' name='" + lines[x].codigo + "' value='" + lines[x].qty + "'  maxlength='4' size='4' /></td></tr>";
		$(".cartTable tbody").append(l)
	}
}


function valida_envia(){
    //valido el nombre
    if (document.fvalida.nombre.value.length==0){
       alert("Tiene que escribir su nombre")
       document.fvalida.nombre.focus()
       return 0;
    }

    //valido la edad. tiene que ser entero mayor que 18
    edad = document.fvalida.edad.value
    edad = validarEntero(edad)
    document.fvalida.edad.value=edad
    if (edad==""){
       alert("Tiene que introducir un número entero en su edad.")
       document.fvalida.edad.focus()
       return 0;
    }else{
       if (edad<18){
          alert("Debe ser mayor de 18 años.")
          document.fvalida.edad.focus()
          return 0;
       }
    }

    //valido el interés
    if (document.fvalida.interes.selectedIndex==0){
       alert("Debe seleccionar un motivo de su contacto.")
       document.fvalida.interes.focus()
       return 0;
    }

    //el formulario se envia
    alert("Muchas gracias por enviar el formulario");
    document.fvalida.submit();
} 
