<!--
//************Carrito de Compras V 1.0.2
//Desarrollado por : Jose Alberto Pérez Burgos <jeal83@hotmail.com>
//Este código puede ser utilizado en su propio sitio web, solo le pido que conserve 
//este comentario, gracias.
//Previamente se carga el catalogo desde el archivo catalogo.js
//Noviembre 2006

var grupo = 0;
var nresultados = 0;

//contendra las posiciones reales del catalogo 
//importado de catalogo.js para aparecer en resultados obtenidos
var apuntadores=new Array();

//contendras los apuntadores del producto comprado y la cantidad en la segunda posicion
var carrito =new Array();
//contendra el apuntador del producto actual que se puede agregar al carrito
var apactual;

var isIE = false;
//  Creamos una variable para el objeto XMLHttpRequest
var req, capaSalida;


function eliminarDeCarrito(ap,nombre){
	carrito.splice(ap,1);
	verCarrito(nombre);
}
function agregarAlCarrito(){
	//verificamos si existe el producto por agregar
	var DEFINED_ABC
	//alert("defined DEFINED_ABC? :" + isDefined('DEFINED_ABC'));
	//alert("defined DEFINED_DEF? :" + isDefined('DEFINED_DEF'));
	//alert("defined catalogo[ apactual ]? :" + isDefined('catalogo[ apactual ]') );

	if(catalogo[ apactual ]!=null){
		if( verifNb(document.getElementById('carrito_cantidad'),9) ){
			prodtemp=new Array();
			prodtemp[0]=apactual;
			prodtemp[1]=document.getElementById('carrito_cantidad').value;
			//si existe se agrega el apuntador del producto y la cantidad elegida
			carrito.push(prodtemp);
			alert('Se agrego '+catalogo[apactual][0]+' al carrito de compras');
			prodtemp=null;
		}else alert('Escriba una cantidad correcta');
	}
}
function nonVide(mt) {
    if (mt.value.length<1) {
       return false;
    }
    else {
       return true;
    }
 }

function verifNb(mt,dec) {
    if (!nonVide(mt)) {
      return false;
    }

    if (isNaN(mt.value)) {
       return false;
    }
    else {
      if (mt.value.indexOf('.') == -1) {
          return true;
      }
      else {
        dectext = mt.value.substring(mt.value.indexOf('.')+1, mt.value.length);
        if (dectext.length > dec)  {
           return false;
        }
        else {
           return true;
        }
	}
   }
 }
function verCarrito(nombre){
	 ventana=window.open(' ','CarritodeCompras','scrollbars=no,status=yes,location=no,directories=no,menubar=no,toolbar=no,resizable=no,width=550,height=500,left=20px,top=20px');
	// ventana.opener=self;
 	 ventana.focus();
	 ventana.document.write("<HTML>");
	 ventana.document.write("<HEAD><TITLE>Carrito de Compras - "+nombre+"</TITLE>");
	 ventana.document.write("<link type='text/css' href='../estilos.css' rel='stylesheet'>");
	 ventana.document.write("</HEAD><BODY><CENTER>");
	 ventana.document.write("<span class='submed'>"+nombre+"</span><br><b>Carrito de Compras</b>");
	 ventana.document.write('<p><img src="../img/5.jpg" width="21" height="19"></p>');
	if(carrito.length>0){
		//imprimimos el carrito
		//bandera que nos indica si todos los productos tienen precio
		ban=true;
		ventana.document.write("<p style='margin:0px'><table border=0 width=520 class='bod'><tr bgcolor='#E2E2E2'><td width=140 align='left'>Nombre</td><td align='center' width=60>Cantidad</td><td width=90 align='center'>$ por Unidad</td><td width=150 align='center'>Total</td><td width=80></td></tr></table></p>");
		ventana.document.write("<p style='margin:0px'><pre style='margin:0px;width:520px;height:150px;overflow:scroll;'>");
		ventana.document.write("<table border=0 width=500 class='bod' align='center'><tr><td width=150 height=5></td><td width=60></td><td width=90></td><td width=150></td><td width=50></td></tr>");
			totalF=0.00;
//			pedido="Nombre \t Cantidad \t $ por Unidad \t Total ";
			pedido="Cantidad - Nombre [$ por Unidad] =  Total \n";
			for(i=0;i<carrito.length;i++){
				//si en nuestro catalogo el producto tiene precio se calcula el total
				if(catalogo[ carrito[i][0] ][2]!=""){
					total=0.00;
					total=(catalogo[ carrito[i][0] ][2])*(carrito[i][1]);
					totalF=totalF+total;
					total="$"+total;
				}
				else{ total="Por Cotizar"; ban=false; }
				//se imprime el nombre del produto comprado - la cantidad seleccionada y el total
//				pedido +="\n "+catalogo[ carrito[i][0] ][0]+" \t "+carrito[i][1]+" \t \t $"+catalogo[ carrito[i][0] ][2]+" \t "+total;
				pedido +="\n "+carrito[i][1]+" - "+catalogo[ carrito[i][0] ][0]+" [$"+catalogo[ carrito[i][0] ][2]+"] = "+total;
				ventana.document.write("<tr><td align='left'>"+catalogo[ carrito[i][0] ][0]+"</td><td align='center'>"+carrito[i][1]+"<td align='center'>$"+catalogo[ carrito[i][0] ][2]+"</td><td align='center'>"+total+"</td><td align='center'><input type='button' onClick='opener.eliminarDeCarrito("+i+",\""+nombre+"\");' value='Quitar' class='bod'></td></tr>");
			}
	 	ventana.document.write("</table></pre></p>");
		titulo="Cotizacion";
		boton = "Solicitar Cotizacion";
			if(totalF>0 && ban){
				totalF="$"+totalF;
				titulo="Compra";
				boton = "Realizar Compra";
			}
			else totalF="Por Cotizar";
		ventana.document.write("<p style='margin:0px' align='center'><form action='catalogo_enviar.php' method='post'>");
		ventana.document.write("<b>Información de "+titulo+"</b><br><table border=0 width=520 class='bod'>");
		ventana.document.write("<tr><td width=150 align='right' bgcolor='#E2E2E2'>* "+titulo+" a Nombre de: </td><td align='center' width=200><input type='text' name='nombre' class='bod' style='width:190px;'></td>");
		ventana.document.write("<td width=60 align='right' bgcolor='#E2E2E2'>** Email: </td><td align='center' width=110><input type='text' name='email' class='bod'></td></tr>");
		ventana.document.write("<tr><td align='right' bgcolor='#E2E2E2'>Dirección: </td><td align='center'><input type='text' name='direccion' class='bod' style='width:190px;'></td>");
		ventana.document.write("<td align='right' bgcolor='#E2E2E2'>Teléfono: </td><td align='center'><input type='text' name='telefono' class='bod'></td></tr>");
		ventana.document.write("<tr><td align='right' bgcolor='#E2E2E2'>Comentarios: </td><td rowspan=2 align='center'><textarea name='comentarios' style='width:190px;'></textarea></td>");
		ventana.document.write("<td align='center' valign='middle' colspan=2 rowspan=2>Total Final<br><b>"+totalF+"</b></td></tr>");
		ventana.document.write("<tr><td></td>");
		
		pedido = pedido+" \n \n \t TOTAL FINAL: "+totalF;
		
		ventana.document.write("<td><input type='hidden' name='pedido' value='"+pedido+"'></td></tr>");
		ventana.document.write("<tr><td colspan=4 align='center'><p style='margin:10px;'><input type='submit' name='boton' value='"+boton+"'  class='bod'></p><p align='left'>** Se enviara un correo a este email con informacion importante para completar su "+titulo+"</p></td></tr>");
		ventana.document.write("</table></form></p>");
	}
	else ventana.document.write("<br><b>Actualmente su carrito esta vacio</b><p class='bod'>Puede Agregar algunos productos o servicios</p>");
	ventana.document.write("</CENTER></BODY>");
	 ventana.document.write("</HTML>");
	 ventana.document.close();
}

function reiniciar(){
	grupo = 0;
	nresultados = 0;
	
	apuntadores=new Array();
	
	for(i=1; i<=20; i++)
		document.getElementById('producto'+i).value="";

}
function mostrar_todos(){
	req = AJAXCrearObjeto();
	reiniciar();
	for(i=0;i<catalogo.length;i++)
		apuntadores.push(i);
	mostrar();
}

ban1=true;
ban2=true;
function ordenar(op){
	temp = new Array();
	temp2 = new Array();
	for(i=0;i<apuntadores.length;i++){
		temp[i]=catalogo[ apuntadores[i] ];
		temp2[i]=catalogo[ apuntadores[i] ];
	}
	
	switch(op){
		case 1:
				temp.sort();
				if(ban1){
					ban1=false;
					document.getElementById('ordenar1').value='Por Nombre Z-A';
				}else {
					ban1=true;
					document.getElementById('ordenar1').value='Por Nombre A-Z';
				}
		break;
		case 2:
				if(ban2){
					alert("menor a mayor");
					temp.sort(
						function(a,b){
							if( isNaN(a[2]) )return -1;
							if( isNaN(b[2]) )return 1;
							if(a[2]>b[2])return 1;
							else return -1;
						}
					);
					ban2=false;
					document.getElementById('ordenar2').value='Por Precio Mayor-Menor';
				}else {
					alert("mayor a menor");
					temp.sort(
						function(a,b){
							if( isNaN(a[2]) )return -1;
							if( isNaN(b[2]) )return 1;
							if(a[2]>b[2])return -1;
							else return 1;
						}
					);
					ban2=true;
					document.getElementById('ordenar2').value='Por Precio Menor-Mayor';
				}
		break;
		default:
		break;
	}
	for(i=0;i<temp.length;i++)
		alert('temp '+i+': '+temp[i][0]);
		
	for(i=0;i<apuntadores.length;i++){
		ban=false;
		j=0;
		while(j<apuntadores.length && !ban){
			alert('temp '+i+': '+temp[i][0]+' == '+temp2[j][0]);
			if(temp[i]==temp2[j]){
				alert('se carga apuntadores['+i+'] = '+j);
				apuntadores[i]=j;
				ban=true;
			}
			j++;
		}
	}
	mostrar();
}
function buscar(){
	reiniciar();
	palabras = document.getElementById('buscar').value.toLowerCase();
	for(i=0;i<catalogo.length;i++){
		if( (catalogo[i][0].toLowerCase().search(palabras)>-1) || (catalogo[i][1].toLowerCase().search(palabras)>-1) )
			//se guarda la posicion del producto encontrado
			apuntadores.push(i);
	}
	mostrar();
}
function detalles(cual){
	apuntador=(grupo*20)+cual-1;
	if(catalogo[ apuntadores[apuntador] ]!=null){
		//se actualiza el apuntador del producto actual que se puede agregar al carrito
		apactual = apuntadores[apuntador];
		document.getElementById('muestra_nombre').value=catalogo[ apuntadores[apuntador] ][0];
		document.getElementById('muestra_descripcion').value=catalogo[ apuntadores[apuntador] ][1];
		if(catalogo[ apuntadores[apuntador] ][2]!="")
			document.getElementById('muestra_precio').value="$"+catalogo[ apuntadores[apuntador] ][2];
		else document.getElementById('muestra_precio').value="Por Cotizar";
		document.images['muestra_imagen'].src=catalogo[ apuntadores[apuntador] ][3];
		AJAXCargar("capa_detalles");
	}
}
function AJAXCrearObjeto(){
var obj;
if(window.XMLHttpRequest) { // no es IE
obj = new XMLHttpRequest();
} else { // Es IE o no tiene el objeto
try {
obj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert('El navegador utilizado no está soportado\n Algunas acciones pueden no funcionar correctamente');
}
}
return obj;
} 

function AJAXCargar(capa){
	var url;
	//url = "cat/"+apuntador+".html"
	url = "cat/"+apactual+".html"
	capaSalida = capa;
	document.getElementById(capaSalida).innerHTML = "<b>"+catalogo[ apuntadores[apactual] ][0]+"</b><br /><br /><img src='../img/load.gif'> <b>Cargando...</b>";
	variables="";
	req.open("GET", url, true);
	req.onreadystatechange = mostrarDatos;
    req.send( variables);
}
/*
getAllResponseHeaders() 	Devuelve el conjunto de cabeceras HTTP como una cadena.
getResponseHeader( nombreCabecera ) 	Devuelve el valor de la cabecera HTTP especificada.
*/
function mostrarDatos(){
    if(req.readyState == 4){
		if(req.statusText=="OK")
		document.getElementById(capaSalida).innerHTML = "<b>"+catalogo[ apuntadores[apactual] ][0]+"</b><br /><br />"+req.responseText;
		else document.getElementById(capaSalida).innerHTML = "<b>"+catalogo[ apuntadores[apactual] ][0]+"<br /><br /><img src='../img/alert_icon.gif'> <b>Descripcion no Localizada </b> ";
	}
    else {
        //    ...en caso contrario, le diremos al usuario que los estamos cargando:
      //  detalles.innerHTML = '<img src="loading.gif" align="absmiddle" /> Cargando...';
	//  document.getElementById(capaSalida).innerHTML ="Procesando: <marquee>0110101010</marquee>"
    }
}

function mostrar(){
	nresultados = apuntadores.length;
	grupos = 0;

	if(nresultados%20 == 0) grupos = (nresultados / 20)-1;
	else grupos = Math.floor(nresultados / 20);

	if( grupo<0 )grupo=grupos;
	else if(grupo>grupos) grupo=0;
	
	inicio=grupo*20;
	fin = inicio+20;

	if(nresultados < fin ) fin = nresultados;
	
	document.getElementById('resultados').value=fin+" de "+nresultados;
	x=0;
	for(i=inicio; i<fin; i++){
		x++;
		document.getElementById('producto'+x).value=catalogo[ apuntadores[i] ][0];
	}
	detalles(1);
}
function siguiente(){
	for(i=1; i<=20; i++)
		document.getElementById('producto'+i).value="";
	grupo++;
	mostrar();
}
function anterior(){
	for(i=1; i<=20; i++)
		document.getElementById('producto'+i).value="";
	grupo--;
	mostrar();
}