/**
 * @author jgt
 */
var app = new Object();

$(document).ready(function(){

    app = ({
        categoria: null,
        subcategoria: null,
        seccion: null
    });
    
	app.categoria = 1;
	app.seccion = "productos";
    mostrarCategorias();

    $("#empresas").click( function(){
		if (app.seccion != "empresas") {
			$("#txtNombre").val("");
			$("#lstSectores").val("");
			app.seccion = "empresas";
			mostrarSeccion();
		}
	} );
    $("#productos").click( function() { 
		if (app.seccion != "productos" ) {
			$("#txtNombre").val("");
			$("#lstSectores").val("");
			app.seccion = "productos";
			mostrarSeccion();
		}
	} );

	$("#btnBuscar").click( function() { 
		var longitud = $("#txtNombre").val().length;
		if ( longitud >= 2 ) {
			app.subcategoria = $("#lstSectores").val();
			if ( app.subcategoria == "" ) { app.subcategoria = null; }
	        mostrarSeccion();
		} else {
			strMsgError = "El campo de texto 'Nombre' requiere 2 carácteres como mínimo.\nPor favor, revise los criterios de búsqueda y vuelva a intentarlo. ";
			alert( strMsgError );
		}
	} );
	$("#btnLimpiar").click( function() { 
		$("#txtNombre").val(""); $("#lstSectores").val("");
	 } );
	 	
});


function mostrarNav(){
    var strNav = "<a href='#' onclick='javascript:mostrarCategorias();'>Inicio</a>";
    if (app.categoria) {
        strNav += " - <a href='#' onclick='javascript:mostrarSubcategorias(" + app.categoria + ");'>" + $("#c" + app.categoria).text() + "</a>";
    }
    if (app.subcategoria) {
        strNav += " - " + $("#s" + app.subcategoria).text();
    }
    
    $("#nav").empty();
    $("#nav").append(strNav);
}

function mostrarCategorias(){
    $("div.loading").show();
    $.ajax({
        type: "GET",
        url: "data.php",
        data: "q=categorias",
        error: function(data){
            alert(data);
        },
        success: function(data){
            $("div.loading").hide();
            var categorias = eval("(" + data + ")");
            var selected = false;
            $("#menu").empty();
            for (i in categorias) {
                $("#menu").append("<div id='c" + i + "' class='menu'>" + categorias[i] + "</div>");
	            if (app.categoria == null) {
	                app.categoria = i;
	            }
            }           

            $("#c" + app.categoria).addClass('selected');
			app.subcategoria = null;
			
            mostrarSubcategorias(app.categoria);
            
            $("#menu > div").click(function(){
                var idCategoria = $(this).attr("id").replace("c", "");                
                $("#c" + app.categoria).removeClass('selected');
                $("#c" + idCategoria).addClass('selected');
                app.categoria = idCategoria;                
                mostrarSubcategorias(app.categoria);
            });
        }
    });
}

function mostrarSubcategorias(idCategoria){
    $("div.loading").show();
    $.ajax({
        type: "GET",
        url: "data.php",
        data: "q=subcategorias&c=" + idCategoria,
        error: function(data){
            alert(data);
        },
        success: function(data){
            $("div.loading").hide();
            
            var subcategorias = eval("(" + data + ")");
            $("#lstSectores").empty();
            $("#lstSectores").append("<option value=''>Seleccionar</option>");
			$("#submenu").empty();
            $("#submenu").append("<ul>");
            for (i in subcategorias) {
                $("#submenu > ul").append("<li id='s" + i + "'>" + subcategorias[i] + "</li>");
                $("#lstSectores").append("<option value='" + i + "'>" + subcategorias[i] + "</option>");
            }
            
            app.subcategoria = null;
			$("#txtNombre").val("");
			$("#lstSectores").val("");
            mostrarSeccion();

            $("#submenu ul > li").click(function(){
                var idSubcategoria = $(this).attr("id").replace("s", "");
                app.subcategoria = idSubcategoria;
				$("#txtNombre").val("");
				$("#lstSectores").val("");
                mostrarSeccion();
            });            
        }
    });
}

function mostrarSeccion() {
	var strNombreBuscado = null;

	mostrarNav(); 
	$("#submenu ul > li").removeClass('sectorSelected');
    if ( app.subcategoria != null ) { $("#s"+app.subcategoria).addClass('sectorSelected') };
	$(".seccion").removeClass( "seccionSelected" );
	$("#"+app.seccion).addClass( "seccionSelected" );
	$("#buscador div.titulo").text( "Buscador de " + app.seccion );
	if ( $("#txtNombre").val() != "" ) strNombreBuscado = $("#txtNombre").val();
	switch ( app.seccion ) {
		case "empresas" : mostrarEmpresas(app.categoria, app.subcategoria, strNombreBuscado ); break;
		case "productos" : mostrarProductos(app.categoria, app.subcategoria, strNombreBuscado ); break;
		default:
			mostrarEmpresas(app.categoria, app.subcategoria, strNombreBuscado );
	}
}

function mostrarEmpresas(idCategoria, idSubcategoria, strNombreBuscado ) {
	if ( idSubcategoria != null ) {
		params = "q=empresas&s=" + idSubcategoria;
	} else {
		if ( idCategoria != null ) {
			params = "q=empresas&c=" + idCategoria;
		} else {
			return 1;
		}
	}
	if ( strNombreBuscado != null ) { params += "&n=" + encodeURI( strNombreBuscado ); }

    $("div.loading").show();
    $.ajax({
        type: "GET",
        url: "data.php",
        data: params,
        error: function(data){
            alert(data);
        },
        success: function(data){
            $("div.loading").hide();
            var empresas = eval("(" + data + ")");
			var e = 0;
            $("#resultado").empty();

			if (empresas.error) {
				mostrarError(empresas.error);
			} else {
	            for (i in empresas) {
					strHtml = "";
					if ( empresas[i].web ) {
						strHtml = "<br /><a href='http://"+empresas[i].web+"' target='_blank'>"+empresas[i].web+"</a>";
					}
					strHtml = "<div style='float: left; '><strong>" + empresas[i].nombre + "</strong>"+ strHtml +"</div>";
					strHtml = "<div style='float: left; '><img class='logo' src='verLogo.php?e=" + empresas[i].codigo + "' alt='logo " + empresas[i].nombre + "' height='60px' width='120px' /></div>" + strHtml;
					strHtml = "<div id='e" + empresas[i].codigo + "' class='empresa'>" + strHtml + "</div>";
	                $("#resultado").append(strHtml);
	            }				
			}
        }
    });
}

function mostrarProductos(idCategoria, idSubcategoria, strNombreBuscado) {
	if ( idSubcategoria != null ) {
		params = "q=productos&s=" + idSubcategoria;
	} else {
		if ( idCategoria != null ) {
			params = "q=productos&c=" + idCategoria;
		} else {
			return 1;
		}
	}
	if ( strNombreBuscado != null ) { params += "&n=" + encodeURI( strNombreBuscado ); }

    $("div.loading").show();
    $.ajax({
        type: "GET",
        url: "data.php",
        data: params,
        error: function(data){
            alert(data);
        },
        success: function(data){
            $("div.loading").hide();
            var productos = eval("(" + data + ")");
			var e = 0;
			var tituloProducto = null;
			
            $("#resultado").empty();
			if ( productos.error ) {
				mostrarError( productos.error );
			} else {
	            for (i in productos) {
					strHtml = "";
					if ( tituloProducto != productos[i].productoPuntex) {
						strHtml = "<h2 style='clear: both; '>"+productos[i].productoPuntex + "</h2>";
						if ( tituloProducto != null ) { strHtml = "<div style='clear: both; height: 15px; '></div>" + strHtml; }
						$("#resultado").append(strHtml);
						tituloProducto = productos[i].productoPuntex;
					}
					strHtml = "<p><strong>"+productos[i].producto + "</strong></p>";
					strHtml += "<div style='float: left; margin: 5px; '><img class='imagen' src='data.php?q=imagen&i=" + productos[i].imagenMin + "' alt='' height='120px' width='120px' style='cursor: pointer; ' onclick='mostrarImagen(" + productos[i].imagen + ", \"" + productos[i].producto + "\")' /></div>";
					strHtml += "<div style='float: left; width: 460px; margin-left: 5px; '><p><strong>Empresa: </strong>" + productos[i].empresa + "</p><p><strong>Descripci&oacute;n: </strong>" + productos[i].descripcion + "</p></div> ";
					strHtml = "<div class='producto'>" + strHtml + "</div>";
	                $("#resultado").append(strHtml);
	            }
			}
        }
    });
}

function mostrarImagen( idImagen, altTexto ) {
	var strFondoCSS = " position:absolute; left:0; top: 0; width: 100%; height: 100%; z-index:99999; filter: alpha(opacity=80); -moz-opacity: 0.8; opacity: 0.8; background-color:#000; ";
	var strMarcoCSS = " position:absolute; z-index:999999; -moz-opacity: 1; opacity: 1; background-color:#FFF; display:none; ";
	var strImagenCSS = " margin: auto; border: 1px solid #cccccc; width: 240px; font-size: 0.8em; color: #cccccc; ";

	$("body").append('<div id="fondo" style="'+strFondoCSS+'"></div>');
	strMarcoCSS += " width: 250px; height: 254px; top: 50%; left: 50%; margin-top:-150px; margin-left:-150px; "
	strMarcoCSS += " align: center; padding: 4px; ";
	$("body").append('<div id="marco" style="'+strMarcoCSS+'"></div>');

	// Insertar la imagen
	$("#marco").append('<img src="data.php?q=imagen&i=' + idImagen + '" alt="' + altTexto + '" title="' + altTexto + '" width="240" height="240" style="'+strImagenCSS+'"/><br /><a href="#" onclick="ocultarImagen();" style="font-size: 0.7em; ">cerrar</a> ');
	$("#marco").fadeIn( 2000 );
}

function ocultarImagen() {
	$("#marco").remove();
	$("#fondo").remove();
}

function mostrarError( msgError ) {
	strMsg = msgError + " para ";
    if (app.categoria) { strMsg += $("#c" + app.categoria).text(); }
    if (app.subcategoria) { strMsg += " - " + $("#s" + app.subcategoria).text(); }
	alert ( strMsg );
}
