//Variable para determinar si se actualiza el menu o no
var reset = true;
var last_hash = -1;

$(function () {
    //Navegacion del menú
    $("#menu_items li a").live("click", function () {
        //Oculta el resto de niveles
        $("#menu_items li").removeClass("activo");
        $(this).parent().siblings("ul").addClass("display-no");
        $(this).parent().siblings("ul").find("ul").addClass("display-no");

        //Muestra mi nivel
        $(this).parent().next("ul").removeClass("display-no");

        $(this).parent().addClass("activo");
        $(this).parent().parents("ul").map(function () {
            $(this).prev("li").addClass("activo");
        });

        //Reset the height of the container
        $("#contentHtml").css("height", "auto");

        var h1 = $("#menu").height();
        var h2 = $("#contentHtml").height();

        if (h2 <= h1) {
            $("#contentHtml").css("height", h1);
        }
    });

    //Funciones de busqueda
    $("#search_input").click(function () {
        var tmp = $("#search_input").val() == "Búsqueda" ? $("#search_input").val("") : false;
    });

    $("#search_input").blur(function () {
        var tmp = $("#search_input").val() == "" ? $("#search_input").val("Búsqueda") : false;
    });

    $("#search_input").keypress(function (evt) {
        if ($("#search_input").val() != "Búsqueda" && $("#search_input").val() != "") {
           if (evt.which == 13) {
                $("#search_form").submit();
            }
        }
    });

    $("#search_button").click(function () {
        if ($("#search_input").val() != "Búsqueda" && $("#search_input").val() != "") {
            $("#search_form").submit();
        }
    });

    //Funciones para el idioma
    $("#eng_button").click(function () {
        var szLoc = window.location.toString().split("/").pop();
        window.location.href = "/en/" + szLoc;
    });

    $("#esp_button").click(function () {
        var szLoc = window.location.toString().split("/").pop();
        window.location.href = "/" + szLoc;
    });

    //Para el manejo del historial (funciona en IE8+, FF3+)
    /*$.history.init(function(url) {
        if (url != "") {
            loadContents(url);
            rebuildPath(url);
        } else if (sectionID != 0) {
            loadContents(sectionID);
            rebuildPath(sectionID);
        }
    });*/

    // Para que funcione en IE7 y el resto
    setInterval(checkHash, 200);

    // Verifica si tiene que cargar el menu
    if (reset) {
        loadMenu();
    }
});


function checkHash() {
    var hash = location.hash.replace(/^.*#/, '');

    if (last_hash != hash) {
        last_hash = hash;
        if (hash != "") {
            loadContents(hash);
            rebuildPath(hash);
        } else if (sectionID != 0) {
            loadContents(sectionID);
            rebuildPath(sectionID);
        }
    }
}


//Obtener las variables via GET
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf("?") + 1).split("&");
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split("=");
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}


function backContent() {
    history.back();
}


function loadContents(contID) {
    $.ajax({
        type: "POST",
        url: "services/services/contents.php",
        data: {
            ACTION: "CHILDREN",
            PARENT_UUID: contID
        },
        dataType: "json",
        beforeSend: function () {
            jQuery("#content").elapsor({
                color: "white",
                opacity: 60,
                image: "images/elapsor.gif",
                text: "Loading...",
                text_style: {
                    "color": "#005878",
                    "font-family": "Arial",
                    "font-size": 13
                }
            });
        },
        success: function(data) {
            jQuery("#content").hideElapsor();
            
            if (typeof data[0] == "object") {
                if (data[0].uuid == sectionID) {
                    $("#pag_title").html(data[0].spanish_title);
                    $("#pag_desc").html(data[0].spanish_text);

                    //Primer contenido para mostrar por defecto
                    $("#contentHtml").html(data[1].spanish_text);

                    //Se oculta el enlace de volver
                    $("#back_div").addClass("display-no");
                } else {
                    //Es solo el contenido.
                    if (data[0].spanish_text == null) {
                        //Primer contenido para mostrar por defecto
                        $("#contentHtml").html(data[1].spanish_text);
                    } else {
                        $("#contentHtml").html(data[0].spanish_text);
                    }
                    
                    if (data[0].uuid != sectionID) {
                        //Se coloca el enlace de volver
                        $("#back_div").removeClass("display-no");
                        $("#back_div").html('<a id="back_link" href="" onclick="backContent();return false;">< Volver</a>');
                    } else {
                        $("#back_div").addClass("display-no");
                    }
                }
            }

            //Reset the height of the container
            $("#contentHtml").css("height", "auto");
            
            var h1 = $("#menu").height();
            var h2 = $("#contentHtml").height();

            if (h2 <= h1) {
                $("#contentHtml").css("height", h1);
            }
        },
        error: function() {
            jQuery(document.body).hideElapsor();
            jAlert ("Error en la comunicación con el servidor.", "Premex");
        }
    });
}


function loadMenu() {
    $.ajax({
        type: "POST",
        url: "services/services/contents.php",
        data: {
            ACTION: "MENU",
            PARENT_UUID: sectionID
        },
        dataType: "json",
        beforeSend: function () {
            $("#menu_load").css("display", "block");
        },
        success: function(data) {
            $("#menu_load").css("display", "none");

            $("#menu_items").html(data.menu);

            // Para IE7 para que muestre correctamente el menu
            $("#menu ul").css("padding-left", "10px");

            //Reset the height of the container
            $("#contentHtml").css("height", "auto");

            var h1 = $("#menu").height();
            var h2 = $("#contentHtml").height();

            if (h2 <= h1) {
                $("#contentHtml").css("height", h1);
            }
			
			// Para que cuando cargue el menu... sepa donde quedo
            var hsh = location.hash.replace(/^.*#/, '');
            rebuildPath(hsh);
        },
        error: function() {
            jQuery(document.body).hideElapsor();
            jAlert ("Error en la comunicación con el servidor.", "Premex");
        }
    });
}


function rebuildPath(contID) {
    $("#breadcrums").html('<a href="index.php">Inicio</a>');

    $.ajax({
        type: "POST",
        url: "services/services/contents.php",
        data: {
            ACTION: "PATH",
            UUID: contID
        },
        dataType: "json",
        success: function(data) {
            var first = true;
            var path = '<a href="index.php">Inicio</a>';

            //Recoge el menu
            $("#menu_items li").removeClass("activo");
            $("#menu_items ul").addClass("display-no");

            for (var ind in data) {
                //Coloca los contenidos del padre en los cajones de la seccion
                if (first) {
                    $("#pag_title").html(data[ind].spanish_title);
                    $("#pag_desc").html(data[ind].spanish_text);
                    first = false;
                }

                //Coloca las migas de pan
                var lcl = data[ind].spanish_title.split(".").pop();
                lcl = str_replace('<br />', ' ', lcl);
                path += '<span> > <a href="#' + data[ind].uuid + '">' + lcl + '</a></span>';

                // Se despliega el menu en cada nivel
                $("#menu_items li").each(function () {
                    var id = $(this).children("a").attr("href").replace(/^.*#/, '');

                    if (id == data[ind].uuid) {
                        $(this).next("ul").removeClass("display-no");
                        $(this).addClass("activo");
                    }
                });
            }
            $("#breadcrums").html(path);

            //Reset the height of the container
            $("#contentHtml").css("height", "auto");

            var h1 = $("#menu").height();
            var h2 = $("#contentHtml").height();

            if (h2 <= h1) {
                $("#contentHtml").css("height", h1);
            }
        },
        error: function(){
            jAlert ("Error en la comunicación con el servidor.", "Premex");
        }
    });
}


function str_replace(search, replace, subject){
    var s=subject;
    var ra=r instanceof Array,sa=s instanceof Array;
    var f=[].concat(search);
    var r=[].concat(replace);
    var i=(s=[].concat(s)).length;
    var j=0;
    while(j=0,i--){
        if(s[i]){
            while(s[i]=(s[i]+'').split(f[j]).join(ra?r[j]||"":r[0]),++j in f){};
        }
    }
    return sa?s:s[0];
}
