var urlBase;
YAHOO.namespace("principalK8");
var Y = YAHOO.principalK8;

var Dom = YAHOO.util.Dom;
var Event = YAHOO.util.Event;
var Sel = YAHOO.util.Selector;
var Element = YAHOO.util.Element;
var Dis = YAHOO.plugin.Dispatcher;

function evento(e, obj){
	eval(obj.code)
}

function initVentas() {
	YAHOO.plugin.Dispatcher.fetch('divItems', urlBase + 'www/store_item_lista_div.php', {
		onFailure: function() {cursor_clear();},
		onStart: function () { cursor_wait();},
		onLoad: function () { cursor_clear();}
	});
}

function initMetodos() {
	YAHOO.plugin.Dispatcher.fetch('divMetodos', urlBase + 'www/store_seleccionar_metodos_div.php', {
		onFailure: function() {cursor_clear();},
		onStart: function () { cursor_wait();},
		onLoad: function () { cursor_clear();}
	});
}


var swCerrarProductos;

function abrirProductos(id) {

	clearTimeout(swCerrarProductos)

	var hijo = MM_findObj('productos' + id);
	var padre = MM_findObj('topico' + id);

	if (hijo.style.display == 'none') {

		var nodesHijos = YAHOO.util.Selector.query('div[id^=productos]');
		var nodesPadres = YAHOO.util.Selector.query('div[id^=topico]');

		for (i = 0; i < nodesHijos.length; i++) {
			if (nodesHijos[i] != hijo) {
				nodesHijos[i].style.display = 'none'
				nodesPadres[i].style.backgroundColor = "#000"
			}
		}

		var subnodes = eval('botoneraProductos' + id);
		var hasta = subnodes * 20
		
		
		hijo.style.height = 0
		hijo.style.display = 'block'

		var myAnim = new YAHOO.util.Anim(hijo, {
			height: {
				to: hasta
			}
		}, 0.05 * subnodes, YAHOO.util.Easing.easeOut);
		
		myAnim.animate();

		padre.style.backgroundColor = "#444"

		var nodesHijos = YAHOO.util.Selector.query('div[id^=topico' + id + '] div div[id^=subproducto]');

		for (i = 0; i < nodesHijos.length; i++) {
			nodesHijos[i].style.display = 'block'
		}
	}
}


function verSiCerrarProductos(id) {
	var hijo = MM_findObj('productos' + id);
	var padre = MM_findObj('topico' + id);
	var anchorPadre = YAHOO.util.Selector.query('div[id^=topico' + id + '] span a');

	swHijo = Dom.hasClass(hijo, 'abierto');
	swpadre = Dom.hasClass(padre, 'abierto');
	swanchorPadre = Dom.hasClass(anchorPadre, 'abierto');

	if (swHijo | swpadre | swanchorPadre) {
		clearTimeout(swCerrarProductos)
	}
	else {
		swCerrarProductos = setTimeout("verSiCerrarProductos2(\"" + id + "\")", 200);
	}
}

function verSiCerrarProductos2(id) {
	var hijo = MM_findObj('productos' + id);
	var padre = MM_findObj('topico' + id);
	var anchorPadre = YAHOO.util.Selector.query('div[id^=topico' + id + '] span a');

	swHijo = Dom.hasClass(hijo, 'abierto');
	swpadre = Dom.hasClass(padre, 'abierto');
	swanchorPadre = Dom.hasClass(anchorPadre, 'abierto');

	if (swHijo | swpadre | swanchorPadre) {
		clearTimeout(swCerrarProductos)
	}
	else {
		cerrarProducto(id)
	}
}

function cerrarProducto(id) {
	clearTimeout(swCerrarProductos)


	var padre = YAHOO.util.Selector.query('div[id^=topico' + id + ']');
	var nodesHijos = YAHOO.util.Selector.query('div[id^=topico' + id + '] div div[id^=productos]');

	for (i = 0; i < nodesHijos.length; i++) {

		nodesHijos[i].style.display = 'none'
	}

	padre[0].style.backgroundColor = "#000"
}


function cerrarProductos() {

	clearTimeout(swCerrarProductos)

	var nodesHijos = YAHOO.util.Selector.query('div[id^=productos]');
	var nodesPadres = YAHOO.util.Selector.query('div[id^=topico]');

	for (i = 0; i < nodesHijos.length; i++) {

		nodesHijos[i].style.display = 'none'

	}
	for (i = 0; i < nodesPadres.length; i++) {

		nodesPadres[i].style.backgroundColor = "#000"

	}


}



function eliminarItem(id) {
	var sUrl = urlBase + 'www/store_item_lista_div_eliminar_proceso.php?ID=' + id;
	var postData = "";

	var callback = {
		success: function(o) {
			if (o.responseText !== undefined) {
				var root = o.responseXML;
				var ID = root.getElementsByTagName('ID')[0].firstChild.nodeValue
				var carritoTotal = root.getElementsByTagName('carritoTotal')[0].firstChild.nodeValue
				var carritoPesoTotal = root.getElementsByTagName('carritoPesoTotal')[0].firstChild.nodeValue

				if (document.location.href.match(/store_item_lista.php/gi) == null && document.location.href.match(/carrito/gi) == null ) {
					cursor_wait();
					document.location.href = urlBase + 'www/store_item_lista.php'
				} else {

					var divItem = MM_findObj('carritoItem' + ID);

					var nodesHijos = YAHOO.util.Selector.query('div[id^=carritoItem]');
					if (nodesHijos.length > 1) {
						divItem.parentNode.removeChild(divItem)


					} else {
						YAHOO.plugin.Dispatcher.fetch('divItems', urlBase + 'www/store_item_lista_div.php', {
							onFailure: function() {cursor_clear();},							
							onStart: function () { cursor_wait();},
							onLoad: function () { cursor_clear();}
						});
					}

					eval('precioCarritoTotal(' + carritoTotal + ')')
					eval('pesoCarritoTotal(' + carritoPesoTotal + ')')


				}



			}
			cursor_clear()
		},
		failure: function(o) {
			console.log(o.statusText)
			if(o.status==-1){
				if(confirm('Error Eliminando el Producto. ¿Intentar Nuevamente?')){
					YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
					return;
				}else{
					cursor_clear()
				}
			}else{
				cursor_clear()
			}
		},
		timeout: 10000,
		argument: {}
	};
	var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
	cursor_wait()
}

function modificarItemCantidad(id, selectCantidad) {

	var cantidad = selectCantidad.options[selectCantidad.selectedIndex].value

	var sUrl = urlBase + 'www/store_item_lista_div_modificar_proceso.php?ID=' + id + '&cantidad=' + cantidad + '';
	var postData = "";

	var callback = {
		success: function(o) {
			if (o.responseText !== undefined) {
				var root = o.responseXML;
				var ID = root.getElementsByTagName('ID')[0].firstChild.nodeValue
				var precioTotal = root.getElementsByTagName('precioTotal')[0].firstChild.nodeValue
				var carritoTotal = root.getElementsByTagName('carritoTotal')[0].firstChild.nodeValue
				var peso = root.getElementsByTagName('peso')[0].firstChild.nodeValue
				var pesoTotal = root.getElementsByTagName('pesoTotal')[0].firstChild.nodeValue
				var carritoPesoTotal = root.getElementsByTagName('carritoPesoTotal')[0].firstChild.nodeValue

				if (document.location.href.match(/store_item_lista.php/gi) == null && document.location.href.match(/carrito/gi) == null ) {
					cursor_wait();
					document.location.href = urlBase + 'www/store_item_lista.php'
				} else {

					eval('precio' + ID + '(' + precioTotal + ');precioCarritoTotal(' + carritoTotal + ')')
					eval('pesoTotal' + ID + '(' + peso + ',' + pesoTotal + ');pesoCarritoTotal(' + carritoPesoTotal + ')')

				}



			}
			cursor_clear()
		},
		failure: function(o) {
			console.log(o.statusText)
			if(o.status==-1){
				if(confirm('Error Modificando el Producto. ¿Intentar Nuevamente?')){
					YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
					return;
				}else{
					cursor_clear()
				}
			}else{
				cursor_clear()
					
				}
			},
			timeout: 10000,
		argument: {}
	};
	var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
	cursor_wait()
}

function validarModificarCaracteristicas() {
	//TODO deberia controlar solamente que no se dejen de elegir las que determinan peso.
	return true;

}

function modificarItemCaracteristica(producto_id, id, caracteristica_id, selectCaracteristica) {


	var caracteristica = selectCaracteristica.options[selectCaracteristica.selectedIndex].value

	var sUrl = urlBase + 'www/store_item_lista_div_modificar_proceso.php?ID=' + id + '&producto_id=' + producto_id + '&caracteristica_id=' + caracteristica_id + '&caracteristica=' + caracteristica + '';
	var postData = "";

	var callback = {
		success: function(o) {
			if (o.responseText !== undefined) {
				var root = o.responseXML;
				var ID = root.getElementsByTagName('ID')[0].firstChild.nodeValue
				var peso = root.getElementsByTagName('peso')[0].firstChild.nodeValue
				var pesoTotal = root.getElementsByTagName('pesoTotal')[0].firstChild.nodeValue
				var carritoPesoTotal = root.getElementsByTagName('carritoPesoTotal')[0].firstChild.nodeValue
				if (document.location.href.match(/store_item_lista.php/gi) == null && document.location.href.match(/carrito/gi) == null) {
					cursor_wait();
					document.location.href = urlBase + 'www/store_item_lista.php'
				} else {
					eval('pesoTotal' + ID + '(' + peso + ',' + pesoTotal + ');pesoCarritoTotal(' + carritoPesoTotal + ')')
				}
			}
			cursor_clear()
		},
		failure: function(o) {
			console.log(o.statusText)
			if(o.status==-1){
				if(confirm('Error Modificando el Producto. ¿Intentar Nuevamente?')){
					YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
					return;
				}else{
					cursor_clear()
				}
			}else{
				cursor_clear()
					
				}
			},
			timeout: 10000,
		argument: {}
	};
	var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
	cursor_wait()
}

function seleccionarMetodoEnvio(nombre, costo) {

	var sUrl = urlBase + 'www/store_seleccionar_metodos_div_envio_proceso.php?destino=' + nombre + '&destino_precio=' + costo + '';
	var postData = "";

	var callback = {
		success: function(o) {
			if (o.responseText !== undefined) {
				var root = o.responseXML;
				var ID = root.getElementsByTagName('ID')[0].firstChild.nodeValue

				var carritoTotal = root.getElementsByTagName('carritoTotal')[0].firstChild.nodeValue
				var carritoPesoTotal = root.getElementsByTagName('carritoPesoTotal')[0].firstChild.nodeValue

				eval('precioCarritoTotal(' + carritoTotal + ')')
				eval('pesoCarritoTotal(' + carritoPesoTotal + ')')

				initMetodos()
			}
			cursor_clear()
		},
		failure: function(o) {
console.log(o.statusText)
if(o.status==-1){
			if(confirm('Error Seleccionando el Tipo de Envio. ¿Intentar Nuevamente?')){
				YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
				return;
			}else{
				cursor_clear()
			}
		}else{
				cursor_clear()
					
				}
			},
			timeout: 10000,
		argument: {}
	};
	var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
	cursor_wait()
}

function seleccionarMetodoPago(nombre, costo) {

	var sUrl = urlBase + 'www/store_seleccionar_metodos_div_pago_proceso.php?pago=' + nombre + '&pago_precio=' + costo + '';
	var postData = "";

	var callback = {
		success: function(o) {
			if (o.responseText !== undefined) {
				var root = o.responseXML;
				var ID = root.getElementsByTagName('ID')[0].firstChild.nodeValue

				var carritoTotal = root.getElementsByTagName('carritoTotal')[0].firstChild.nodeValue
				var carritoPesoTotal = root.getElementsByTagName('carritoPesoTotal')[0].firstChild.nodeValue

				eval('precioCarritoTotal(' + carritoTotal + ')')
				eval('pesoCarritoTotal(' + carritoPesoTotal + ')')

				initMetodos()
			}
			cursor_clear()
		},
		failure: function(o) {
			console.log(o.statusText)
			if(o.status==-1){
				if(confirm('Error Seleccionando el Tipo de Pago. ¿Intentar Nuevamente?')){
					YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
					return;
				}else{
					cursor_clear()
				}
			}else{
				cursor_clear()
			}
		},
		timeout: 10000,
		argument: {}
	};
	var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
	cursor_wait()
}


function initListaProductos(){
}

function listaProductosAgregarCarrito(form){
	if(confirm('¿Desea agregar este Producto a su carrito de Compras?')){
		form=MM_findObj(form);
		form.submit();
	}
}

function confirmarCompraYProcesarPago() {

	form = MM_findObj('confirmarForm');
	form.submit();
	setTimeout('MM_jumpMenu(\'self\',\'store_compra_proceso.php\')', 500);
}


function getFormularioCampos(formularioNombreDeClaseDeControles) {


	var iputForm = Dom.getElementsByClassName(formularioNombreDeClaseDeControles, 'input');
	var textareaForm = Dom.getElementsByClassName(formularioNombreDeClaseDeControles, 'textarea');
	var selectForm = Dom.getElementsByClassName(formularioNombreDeClaseDeControles, 'select');
	var auxParam = "",
		sep = "";

	for (i = 0; i < iputForm.length; i++) {
		
			if(iputForm[i].type == "text" || iputForm[i].type == "password" || iputForm[i].type == "hidden"  ){
				auxParam = auxParam + sep + iputForm[i].id + "=" + escape(iputForm[i].value)
			
			}else if(iputForm[i].type == "checkbox"){
				if(iputForm[i].checked){
					auxParam = auxParam + sep + iputForm[i].id + "=" + escape(iputForm[i].value)
				}else{
					auxParam = auxParam + sep + iputForm[i].id + "=" 
				}
				
			}
			sep = "&"
		}
		

	
	
	for (i = 0; i < selectForm.length; i++) {
			auxParam = auxParam + sep + selectForm[i].id + "=" + escape(selectForm[i].options[selectForm[i].selectedIndex].value)
			sep = "&"
		}


	for (i = 0; i < textareaForm.length; i++) {
			auxParam = auxParam + sep + textareaForm[i].id + "=" + escape(textareaForm[i].value)
			sep = "&"
		}

	return auxParam;
}

function isNumeric(value) {
	if (value == null || !value.toString().match(/^[-]?\d*\.?\d*$/)) return false;
	return true;
}



var cursor_cantidad_wait = 0

function cursor_wait() {
	cursor_cantidad_wait++
	document.body.style.cursor = 'wait';
}

function cursor_clear() {
	cursor_cantidad_wait--
	if (cursor_cantidad_wait <= 0) {
		document.body.style.cursor = 'default';
		cursor_cantidad_wait = 0
	}
}



