// JavaScript Document
var Productos;
var Compra = new Array();
var portes = false;
var bloqDespProd = false;

var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-16673126-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
  	
$().ready(function(){
	ajustaTamanno();
	
	$(".Menu2").show();
	$(".Menu3").hide();
	$(".dvCuerpo").html("");
	$(".MenuDesplegable1").click(function(){
		var level = 10;
		var clicked = $(this);
		var clase = "";
		$($("li"), $(".ulMenu")).each(function(){
		clase = $(this).attr('class').substr($(this).attr('class').length -1, $(this).attr('class').length);
		if( level < parseInt(clase)){
							if ($(this).css('display') == "none"&&clase!=3) {
		$(this).show(200);
		} else {
		$(this).hide(200);
		}
		} else {
		level = 10;
		}
		if ($(this).html() == $(clicked).html()) {
		level = parseInt(clase);
		}
		});
		});
			$(".MenuDesplegable2").click(function(){
		var level = 10;
		var clicked = $(this);
		var clase = "";
		$($("li"), $(".ulMenu")).each(function(){
		clase = $(this).attr('class').substr($(this).attr('class').length -1, $(this).attr('class').length);
		if( level < parseInt(clase)){
							if ($(this).css('display') == "none") {
		$(this).show(200);
		} else {
		$(this).hide(200);
		}
		} else {
		level = 10;
		}
		if ($(this).html() == $(clicked).html()) {
		level = parseInt(clase);
		}
		});
		});
	abrePage("quienes", $('li', '.ulMenu').get(0));
});

function ajustaTamanno(){
	$(".dvContenidoMenu").height(0);
	$(".dvContenido").height(0);
	if($(document).height()<= $(window).height()) {
		$(".dvContenidoMenu").height($(document).height()-$(".dvCabeceraMenu").height()-$(".dvMenuPie").outerHeight());	
	} else {
		$(".dvContenidoMenu").height($(document).height()-$(".dvCabeceraMenu").height());
	}
	$(".dvContenido").height($(".dvContenidoMenu").height());	
}
function abrePage(url, elem){
	$(".MenuClicked").removeClass("MenuClicked");
	if ($(elem).hasClass("Menu")){
		$(elem).attr("class", "MenuClicked "+ $(elem).attr("class"));
	}
	do_ajax_xml("/xml/"+url+".xml", "GET", "", "procesaPage(xml)");
}
function procesaPage(xml) {
	var html = $(xml).find("HTML").text();
	var script = $(xml).find("script").text();
	while (html.indexOf(String.fromCharCode(10)) != -1){
		html = html.replace(String.fromCharCode(10), "<br />");
	}
	$(".dvCuerpo").html(html);
	eval(script);
	ajustaTamanno();
}
function abrePageProductos(url, elem) {
	$(".MenuClicked").removeClass("MenuClicked");
	if ($(elem).hasClass("Menu")){
		$(elem).attr("class", "MenuClicked "+ $(elem).attr("class"));
	}
	do_ajax_xml("/xml/"+url+".xml", "GET", "", "procesaPageProductos(xml)");
}
function procesaPageProductos(xml){
	Productos = new Array();
	$(".dvCuerpo").html("<div class='btDesplazamiento'><table cellspacing=0 cellpadding=0 align='right'><tr><td class='boton btDesplazamientoAnterior'><img src='/sysimg/flechIzda.gif' alt='Anterior' /></td><td>&nbsp;</td><td class='boton btDesplazamientoSiguiente'><img src='/sysimg/flechDcha.gif' alt='Siguiente' /></td></tr></table></div>")
	.append("<div class='divTablaProductos'><table border=0 class='tablaProductos' cellpadding=0 cellspacing=0><tr id='tr0'></tr><tr id='tr1'></tr></table></div>");
	$("Producto", xml).each(function(index){
		tr = 1;
		Productos[index] = new Array();
		$($(this).children()).each(function(i2) {
			Productos[index][this.nodeName] = $(this).text();					
		});
		if (index%2 ==0 ){
			tr = 0;
		}
		var cantidad = 0;
		if (Compra[Productos[index]['ID']] != undefined) {
			cantidad = Compra[Productos[index]['ID']][1];	
		}
		var strAux = "";
		if (Productos[index]['Precio'] != 0) {
			strAux = "<div class='precioProducto'>"+Productos[index]['Precio']+"&nbsp;("+Productos[index]['Minimo']+"&nbsp;"+Productos[index]['Unidad']+")</div><span class='cantidadProducto'>Cantidad:&nbsp;</span><span class='dvCantidadProducto'>"+cantidad+"</span><span class='unidadProducto'>&nbsp;"+Productos[index]['Unidad']+"</span><div class='btCantidadProducto'><span class='btCantidad btCantidadMas'><img src='/sysimg/mas.gif' alt='' /></span><span class='btCantidad btCantidadMenos'><img src='/sysimg/menos.gif' alt='' /></span></div>";
	}
		$(".tablaProductos #tr"+tr).append("<td width='245px' id='tdProducto"+index+"'><img class='fotoProducto' src='"+Productos[index]['Foto']+"' alt='' /><div class='nombreProducto'>"+Productos[index]['Name']+"</div>"+strAux+"</td>");
	});
	var c = Productos.length
	if (c%2 != 0) {
		c++;	
	}
	c=c/2;
	$(".tablaProductos td").width(245);
	$(".tablaProductos").width(c*245);
	$(".btCantidad").hover(function(){
		$(this).css("backgorund-color", "#ADA06C");		   
	}, function(){
		$(this).css("backgorund-color", "#FFFFFF");								   
	}).click(function() {
		agregaProducto($(this));
	});
	$(".fotoProducto").click(function(){
		abreInformacion($(this));								  
	});
	ajustaTamanno();
	$(".btDesplazamientoAnterior").css("visibility", "hidden");
	if($(".tablaProductos").width() + $(".tablaProductos").position().left - $(".divTablaProductos").width() > 0){
		$(".btDesplazamientoSiguiente").css("visibility", "visible");
	} else {
		$(".btDesplazamientoSiguiente").css("visibility", "hidden");
	}
	$(".btDesplazamiento .boton").click(function(){
		if(!bloqDespProd) {
			bloqDespProd = true;
			var direc = 1;
			if ($(this).attr('class').indexOf('Anterior') == -1) {
				direc = -1;
			}
			var newpos = (parseInt($(".tablaProductos").position().left)+(490*direc));
			newpos = 490*Math.round(newpos/490); //IE7 hace lo que quiere y no sabe posicionar donde se le dice
			$(".tablaProductos").animate({left: newpos+"px"}, 1, function(){
				if($(".tablaProductos").position().left < 0) {
					$(".btDesplazamientoAnterior").css("visibility", "visible");
				} else {
					$(".btDesplazamientoAnterior").css("visibility", "hidden");
				}
				if($(".tablaProductos").width() + $(".tablaProductos").position().left - $(".divTablaProductos").width() > 0){
					$(".btDesplazamientoSiguiente").css("visibility", "visible");
				} else {
					$(".btDesplazamientoSiguiente").css("visibility", "hidden");
				}
				bloqDespProd= false;
			});
		}
	});
}

function abreInformacion(elem, producto){
	var index = parseInt($(elem).parent().attr('id').replace("tdProducto",""));
	var producto = new Array();
	var titulo = "";
	producto = Productos[index];
	if ( producto['FotoG'] == undefined ) {
		return false;	
	}
	if (producto['TituloG'] == undefined){	
		titulo = producto['Name'];
	} else {
		titulo = producto['TituloG'];	
	}
	$("html").css("overflow", "hidden");
	$("body").append("<div class='fondoInfoProducto'></div><div class='divInfoProducto'><div class='divTituloProducto'></div><div class='divCuerpoProducto'></div></div>");
	$(".fondoInfoProducto").width($(document).width()).height($(document).height());
	$(".divInfoProducto").width(600).height(500).css("top", $(window).scrollTop()+50+"px").css("left", parseInt(($(window).width()-$(".divInfoProducto").width())/2)+"px");
	if(($(window).height()-50) < $(".divInfoProducto").height()){
		$(".divInfoProducto").height($(document).height()-50);
	}
	$(elem).effect("transfer", { to: ".divInfoProducto", className: 'ui-effects-transfer' }, 500, function(){
		$(".divInfoProducto").css("visibility", "visible");																									   
	});
	
	$(".divTituloProducto").append(titulo+"<img src='/sysimg/close.png' alt='cerrar' class='cerrarInfo' />");
	$(".cerrarInfo").click(function(){ closeInformacion(); });
	$(".divCuerpoProducto").height($(".divInfoProducto").height() - $(".divTituloProducto").outerHeight()-8)
	.append("<img src='"+producto['FotoG']+"' align='left' class='fotoInfoProducto' alt='' />");
	for (p in producto){
		if (p != "ID" && p!="Name" && p!="Foto" && p!="FotoG" && p!="Unidad" && p!="Minimo" && p!="Precio" && p!="TituloG"){
			$(".divCuerpoProducto").append("<div class='CategoriaTitulo'>"+p+"</div>")
			.append("<div class='contenidoCategoria'>"+producto[p]+"</div>");
		}
	}
}
function closeInformacion(){
	$(".divInfoProducto").remove();
	$(".fondoInfoProducto").remove();
	$("html").css("overflow", "");
}
function agregaProducto(elem){
	var direc = 1;
	if ($(elem).hasClass('btCantidadMenos')) {
		direc = -1;	
	}
	var parent = $(elem).parent().get(0);
	parent = $(parent).parent().get(0);
	var index = parseInt($(parent).attr('id').replace("tdProducto", ""));
	
	var cantidad = direc*Productos[index]['Minimo'];
	if (parseInt($("#"+$(parent).attr('id')+" .dvCantidadProducto").html())+cantidad >= 0) {
		$("#"+$(parent).attr('id')+" .dvCantidadProducto").html(parseInt($("#"+$(parent).attr('id')+" .dvCantidadProducto").html())+cantidad);
		$(".dvPresupuesto").html(formatDecimal(parseFloat($(".dvPresupuesto").html()) + (Productos[index]['Precio']*direc), true, 2));
		Compra[Productos[index]['ID']] = new Array(Productos[index]['Name'], parseInt($("#"+$(parent).attr('id')+" .dvCantidadProducto").html()), Productos[index]['Unidad'], (Productos[index]['Precio'] * parseInt($("#"+$(parent).attr('id')+" .dvCantidadProducto").html()))/ Productos[index]['Minimo'] );
	}
	
	
}
function formatDecimal(argvalue, addzero, decimaln) {
  var numOfDecimal = (decimaln == null) ? 2 : decimaln;
  var number = 1;

  number = Math.pow(10, numOfDecimal);

  argvalue = Math.round(parseFloat(argvalue) * number) / number;
  // If you're using IE3.x, you will get error with the following line.
  // argvalue = argvalue.toString();
  // It works fine in IE4.
  argvalue = "" + argvalue;

  if (argvalue.indexOf(".") == 0)
    argvalue = "0" + argvalue;

  if (addzero == true) {
    if (argvalue.indexOf(".") == -1)
      argvalue = argvalue + ".";

    while ((argvalue.indexOf(".") + 1) > (argvalue.length - numOfDecimal))
      argvalue = argvalue + "0";
  }

  return argvalue;
}
function imprimeCompra(){
	var inicio = true;
//	var impPortes = 0.00;
//	if (portes){
//		impPortes = 10.00;	
//	}
	$("#frmPedido #fldLista").val("");
	$(".formListaCompra").html("No has seleccionado ning&uacute;n producto");
	for(c in Compra) {
		if (Compra[c][1] != 0) {
			if (inicio) {
				$(".formListaCompra").html("<table class='tableListaCompra' width=100%></table>");	
			}
			inicio = false;
			$(".formListaCompra .tableListaCompra").append("<tr><td width='2'><img src='/sysimg/close.png' alt='cerrar' class='borrarCarrito' id='borrarCarrito_"+c+"' /></td><td>"+Compra[c][0]+"</td><td align='right'>"+Compra[c][1]+" "+Compra[c][2]+"</td></tr>");
			$("#frmPedido #fldLista").val($("#frmPedido #fldLista").val()+Compra[c][0]+"    "+Compra[c][1]+" "+Compra[c][2]+String.fromCharCode(10));
		}
	}
	if (!inicio){
//		impPortes = impPortes+parseFloat($(".dvPresupuesto").html());
//		$(".formListaCompra. .tableListaCompra").append("<tr><td colspan=3 align='right'>Total: "+formatDecimal(impPortes, true, 2)+" &euro;"+"</td></tr>");
		$(".formListaCompra. .tableListaCompra").append("<tr><td colspan=3 align='right'>Total: "+$(".dvPresupuesto").html()+" &euro;"+"</td></tr>");
	}
	$(".borrarCarrito").click(function(){
		var tr = $(this).parent().parent();
		var cid = $(this).attr('id').replace("borrarCarrito_", "");
		Compra[cid][1] = 0;
		$(".dvPresupuesto").html(formatDecimal($(".dvPresupuesto").html() - Compra[cid][3], true, 2))
		imprimeCompra();
	});
}
function preparaEnvio(){
	if (portes) {
		$("#fldPortes").attr("checked", "true");
	} else {
		$("#fldPortes").attr("checked", "");
	}
	$("#fldPortes").change(function(){
		portes = $("#fldPortes").attr("checked");
		if(portes) {
			$(".dvPresupuesto").html(formatDecimal(parseFloat($(".dvPresupuesto").html())+10, true, 2));
		} else {
			$(".dvPresupuesto").html(formatDecimal(parseFloat($(".dvPresupuesto").html())-10, true, 2));
		}
		imprimeCompra();
	});
	$("#frmPedido").submit(function(){
		$("#btEnviar").attr("value", "Enviando...").attr("disabled", "true");
		do_ajax_php_html("/enviarContacto.php", "POST", $(this).serialize() ,"#resultado",  "data");
		return false;
	});
}
