// JavaScript Document
var jsCart = new Array();
var jsAdd = new Array();
var ajaxCart = new Array();
var jsDel = new Array();
var modShop = new Array();
var clear = new Array();
var sendcart = new Array();
var calculateCart = new Array();

function ajaxShowCart(sesion, shop){
	//VARIABLE SHOP INDICA SI EL USUARIO ESTA EN EL SHOP O EN EL SITIO
	var ajaxIndex = jsCart.length;
	jsCart[ajaxIndex] = new sack();
	jsCart[ajaxIndex].requestFile = 'shopactions.php?action=show_cart&sesion=' + sesion;
	jsCart[ajaxIndex].onCompletion = function(){ showAjaxBasketContent(ajaxIndex, shop); };
	jsCart[ajaxIndex].runAJAX();		// Execute AJAX function
}

function showAjaxBasketContent(ajaxIndex, shop){
		var productItems = jsCart[ajaxIndex].response.split('|||');
		var total = document.getElementById('total');
		var cant_items = document.getElementById('cant_items');
		var num_items = document.getElementById('num_items');
		var compushopCart = document.getElementById('compushopCart');
		//alert ('la cantidad de articulos es: ' + productItems[0] + ' ctdad de prods ' + productItems[1] + ' y el total es: ' + productItems[2]);
		num_items.innerHTML = 'Ctdad de Artículos: ' + productItems[0]; //CAMBIA EL TOTAL DE LOS ARTICULOS
		cant_items.innerHTML = 'Ctdad de Productos: ' + productItems[1]; //CAMBIA EL TOTAL DE LOS PRODUCTOS
		total.innerHTML = 'Total: $' + productItems[2]; //CAMBIA EL TOTAL DEL PEDIDO
}


function agregaAlPedido()
{
	var estados = new Array();
	estados = document.getElementsByClassName('state_add');
	estados.each(function (el)
	{
		if (el.checked)
		{
			//console.log(el)
			var casiId = el.getAttribute('id');
			var aux = casiId.split('_');
			var codigoRel = aux[1];
			
			var cod_artic = el.value;
			var desc = $('desc_'+codigoRel).innerHTML;
			//alert($('precio_'+codigoRel).innerHTML);
			var precioX = $('precio_'+codigoRel).innerHTML.replace(',','.');
			var precio = parseFloat(precioX);
			//alert (desc + " " + precio);
			
			
			
			var url = 'shopactions.php';
			var pars = 'action=add_item&cod_artic=' + cod_artic  + '&desc=' + desc + '&precio=' + precio + '&cantidad=1&estado=true';
			
			new Ajax.Request(url, {
			method: 'get',
			asynchronous : false,
			parameters: pars
			});	
		}
	});
	
	ajax_loadContent('contentDivContainer','shop.php');
}

function addItem(productId, prodDesc, precio, cantidad, estado, multi){
	//agrego el item a la sesion
	sessvars.LastBuy = {id: productId}

	if ( multi === undefined ) {
    	multi = false;
	}
			
	var ajaxIndex = jsAdd.length;
	//console.log(ajaxIndex)
	jsAdd[ajaxIndex] = new sack();
	jsAdd[ajaxIndex].requestFile = 'shopactions.php?action=add_item&cod_artic=' + productId  + '&desc=' + prodDesc + '&precio=' + precio + '&cantidad=' + cantidad + '&estado=' + estado;
	//alert (jsAdd[ajaxIndex].requestFile);
	if(!multi)jsAdd[ajaxIndex].onCompletion = function(){	ajax_loadContent('contentDivContainer','shop.php?cod_artic=' + productId); };	// Specify function that will be executed after file has been found
	jsAdd[ajaxIndex].runAJAX();		// Execute AJAX function
}

function modEstado(codigo_prod, estado, sesion, fila){
	
	if(document.getElementById('estado' + fila).checked) {var state = 1; } else { var state = 0;}
	document.body.style.cursor = 'wait';
	document.getElementById('cargando').style.visibility = 'visible';
	if (estado != true){
		document.getElementById('id_' + fila).style.color = '#CCCCCC';
		document.getElementById('desc_' + fila).style.color = '#CCCCCC';
		document.getElementById('precio_' + fila).style.color = '#CCCCCC';		
	} else {
		document.getElementById('id_' + fila).style.color = '#000000';
		document.getElementById('desc_' + fila).style.color = '#000000';
		document.getElementById('precio_' + fila).style.color = '#000000';
	}
	ajaxCarts(codigo_prod, state, sesion, 'mod_estado', fila);
	ajaxShowCart(sesion, true);
}
function modCantidad(codigo_prod, cantidad, sesion, fila){
	document.body.style.cursor = 'wait';
	document.getElementById('cargando').style.visibility = 'visible';
	//alert('el codigo de producto es: ' + codigo_prod + ' y la cantidad a la que cambia es: ' + cantidad + ' y la sesion es: ' + sesion);
	ajaxCarts(codigo_prod, cantidad, sesion, 'mod_item', fila);
	ajaxShowCart(sesion , true);
}

function delItem(prodId, linea, sesion){
	var ajaxIndex = jsDel.length;
	jsDel[ajaxIndex] = new sack();
	jsDel[ajaxIndex].requestFile = 'shopactions.php?id=' + prodId  + '&action=del_item';
	//alert (jsDel[ajaxIndex].requestFile);
	document.getElementById(linea).style.display = 'none';
	jsDel[ajaxIndex].onCompletion = function(){ ajaxShowCart(sesion, true); };	// Specify function that will be executed after file has been found
	jsDel[ajaxIndex].runAJAX();		// Execute AJAX function
}

function ajaxMakeChanges(indice){
	var state = false;
	var codigo = document.getElementById('cod_artic_' + indice).value;
	var desc = document.getElementById('desc_' + indice).innerHTML;
	var precio = document.getElementById('precioOculto_' + indice).value;
	var cantidad = document.getElementById('quantity_' + indice).value;
	var incluir = document.getElementById('estado_' + indice).checked;
	if (incluir) {state = true; }
	var index = modShop.length;
	modShop[index] = new sack();
	modShop[index].requestFile = 'shopactions.php?action=mod_item&cod_artic=' + codigo + '&desc=' + desc + '&precio=' + precio + '&cantidad=' + cantidad + '&estado=' + state;
	modShop[index].onCompletion = function(){ compushopCartUpdate('shop.php');};
	modShop[index].runAJAX();
}

function ajaxClearCart(){
	var index = clear.length;
	clear[index] = new sack();
	clear[index].requestFile = 'shopactions.php?action=clear';
	clear[index].onCompletion = function(){ compushopCartUpdate('paginas.php?paginaId=10');};
	clear[index].runAJAX();
}
function compushopCartUpdate(url)
{
	ajax_loadContent('contentDivContainer',url);
	//ajax_loadContent('compushopCart','compushopCart.php');
}
function ajaxCarts(productId, numero, session, action)
{
	var ajaxIndex = ajaxCart.length;
	ajaxCart[ajaxIndex] = new sack();
	ajaxCart[ajaxIndex].requestFile = 'shopactions.php?cod_artic=' + productId + '&quantity=' + numero + '&action=' + action + '&sesion=' + session;
	//alert (ajaxCart[ajaxIndex].requestFile);
	//ajaxCart[ajaxIndex].onCompletion = function(){ showAjaxBasketContent(ajaxIndex); };	// Specify function that will be executed after file has been found
	ajaxCart[ajaxIndex].runAJAX();		// Execute AJAX function
}   

var enableCache = false;
var jsCache = new Array();
var realUrl = new Array();
var dynamicContent_ajaxObjects = new Array();

function ajax_showContent(divId,ajaxIndex,url)
{
	realUrl = url.split('?');
	document.getElementById(divId).innerHTML = dynamicContent_ajaxObjects[ajaxIndex].response;
	if(enableCache && realUrl[0] != 'shop.php' && realUrl[0] != 'login.php'){
		jsCache[url] = 	dynamicContent_ajaxObjects[ajaxIndex].response;
	}
	
	if(realUrl[0] == 'suministros.php'){
		InitializeMainCategory('document.welcome');
		if(realUrl.length > 1)
		{
			var biblia = realUrl[1].split('=');
			AbrirBiblia(biblia[1]);
		}
	}
	
	if(realUrl[0] == 'shop.php' || realUrl[0] == 'shop_2.php' || realUrl[0] == 'fincompra.php')
	{
		document.getElementById('tableCont').style.backgroundColor = '#E7E2E2';
	}
	else
	{
		document.getElementById('tableCont').style.backgroundColor = color;
	}
	
	if(realUrl[0] == 'shop.php')
	{
		sessvars.LastBuy.id = '';
	}
	
	dynamicContent_ajaxObjects[ajaxIndex] = false;
}

function ir(url)
{
	ajax_loadContent('contentDivContainer',url);	
} 

function ajax_loadContent(divId,url)
{
	//console.log(divId + " " + url)

	//dejar en la sesion la ultima pagina visitada
	realUrl = url.split('?');
	
	if(divId == 'contentDivContainer' && realUrl[0] != 'shop.php')
	{
			sessvars.History = {lastPage: url}
	}
	else
	{
		//esta en el shop
		//console.log(sessvars.LastBuy);
	}
	//console.log(sessvars.History.lastPage)
	$('buscador').value = "";
	window.scrollBy(0,0);
	if(enableCache && jsCache[url]){
		document.getElementById(divId).innerHTML = jsCache[url];
		realUrl = url.split('?');
		if(realUrl[0] == 'suministros.php'){
			InitializeMainCategory('document.welcome');
		}
		return jsCache[url];
	}
	nd();
	//window.location='#';
	//alert (divId + "y el valor es:" + url);
	document.getElementById(divId).innerHTML = "<div align='center'><br><br><br><br><img src='img/cargando.gif'></div>"; 
	var ajaxIndex = dynamicContent_ajaxObjects.length;
	dynamicContent_ajaxObjects[ajaxIndex] = new sack();
	dynamicContent_ajaxObjects[ajaxIndex].requestFile = url;	// Specifying which file to get
	dynamicContent_ajaxObjects[ajaxIndex].onCompletion = function(){ ajax_showContent(divId,ajaxIndex,url); };	// Specify function that will be executed after file has been found
	dynamicContent_ajaxObjects[ajaxIndex].runAJAX();		// Execute AJAX function
}
/*
function ajax_loadContent(divId,url)
{
	if(enableCache && jsCache[url]){
		document.getElementById(divId).innerHTML = jsCache[url];
		realUrl = url.split('?');
		if(realUrl[0] == 'suministros.php'){
			InitializeMainCategory('document.welcome');
		}
		if(realUrl[0] == 'shop.php'){
			document.getElementById('compushopCart').style.display = 'none';
		} else {
			document.getElementById('compushopCart').style.display = 'block';
		}
		return jsCache[url];
	}
	//alert (divId + "y el valor es:" + url);
	document.getElementById(divId).innerHTML = "<div align='center'><br><br><br><br><img src='img/cargando.gif'></div>"; 
	var ajaxIndex = dynamicContent_ajaxObjects.length;
	dynamicContent_ajaxObjects[ajaxIndex] = new sack();
	dynamicContent_ajaxObjects[ajaxIndex].requestFile = url;	// Specifying which file to get
	dynamicContent_ajaxObjects[ajaxIndex].onCompletion = function(){ ajax_showContent(divId,ajaxIndex,url); };	// Specify function that will be executed after file has been found
	dynamicContent_ajaxObjects[ajaxIndex].runAJAX();		// Execute AJAX function	
	
	
}*/

function ajaxEnviarcompushopCart(){
	if (validarCompleto()){
	$('msg').style.display = 'block';
	$('msg').innerHTML = 'ENVIANDO PEDIDO';
	var url = 'carritoactionsphp.php';
	var pars = 'nombre=' + $F('nombre') + '&email=' + $F('email') + '&telefono=' + $F('telefono') + '&vendedor=' + $F('vendedor') + '&comentario=' + $F('comentario');
	var myAjax = new Ajax.Request(
		url, 
		{
			method: 'get', 
			parameters: pars,
			onComplete: showResponse
		});
	} 
}

function validarCompleto(){
	todoOk = true;
	if ($F('nombre') == ""){
		$('msg').innerHTML = 'DEBE COMPLETAR EL NOMBRE EN EL FORMULARIO';
		$('msg').style.display = 'block';
		todoOk = false;		
	}
	if ($F('email') == "" && $F('telefono') == ""){
		$('msg').innerHTML = 'DEBE COMPLETAR SU TELEFONO O SU EMAIL';
		$('msg').style.display = 'block';
		todoOk = false;		
	}
	return todoOk;
}

function showResponse()
{
	//$('msg').style.display = 'block';
	//ajax_loadContent('compushopCart','compushopCart.php');
	ajax_loadContent('contentDivContainer','fincompra.php');
}

function Get_Cookie(name) { 
	var start = document.cookie.indexOf(name+"="); 
	var len = start+name.length+1; 
	if ((!start) && (name != document.cookie.substring(0,name.length))) return null; 
	if (start == -1) return null; 
	var end = document.cookie.indexOf(";",len); 
	if (end == -1) end = document.cookie.length; 
	return unescape(document.cookie.substring(len,end)); 
} 

function ajaxCalcularPedido(noIrAlShop){
	if ( noIrAlShop === undefined ) {
      noIrAlShop = false;
   	}


	var cookieProds = Get_Cookie('compushopCart');
	if (cookieProds){ //VALIDA QUE EXISTA LA COOKIE
		var cookieValues = new Array();
		cookieValues = cookieProds.split('|||');
		var totalProds = cookieValues.length / 5; //TOTAL DE PRODUCTOS
		//alert (totalProds);
		var codigos = new Array;
		var cantidades = new Array;
		var incluidos = new Array;
		var codeMulti = 5;
		var cantMulti = 3;
		var inclMulti = 4;
		var url = 'shopactions.php';
		var pars = 'action=mod_carrito';
		var state = 'true';
		for(i = 0; i < totalProds; i++){
			codigos[i] = cookieValues[i*codeMulti];
			pars += '&codigo' + i + '=' + codigos[i];
			var cant = 'quantity_' + i;
			cantidades[i] = $F(cant);
			pars += '&cantidad' + i + '=' +  cantidades[i];	
			var estado = 'estado_' + i;
			//alert ($F(estado));
			if ($F(estado) != '1'){ state = 'false';} else {state = 'true';}
			incluidos[i] = state;
			pars += '&incluido' + i + '=' +  incluidos[i];
		}
		pars += '&qty=' + i;
		
		
	}
	var myAjax = new Ajax.Request(
		url, 
		{
			method: 'get', 
			parameters: pars, 
			onComplete: function(){
				if(!noIrAlShop)
				{
					ajax_loadContent('contentDivContainer','shop.php');
				}
				else
				{
					ajax_loadContent('contentDivContainer',sessvars.History.lastPage);
				}
				//ajax_loadContent('compushopCart','compushopCart.php');
				/*var precioTxt = 'precio_' + linea;
				var precioNumero = formatCurrency(((precio / 1.105) / cantidadvieja) * cantidad);
				var precioFinalTxt = 'precio_final_' + linea;
				var precioFinalNumero = formatCurrency((precio / cantidadvieja) * cantidad);
				//alert(precioNumero);
				$(precioTxt).innerHTML = precioNumero;
				$(precioFinalTxt).innerHTML = precioFinalNumero;	*/			
			}
		});
}
