$(document).ready(function() {

    //update title
    document.title += $("h1").text();

    //IE min-height
    if ($.browser.msie) {
        if ($("#pageBody").height() <= 500)
            $("#pageBody").css({height: 500});
    }

    //left onn
    var lcl = $("#left").attr("className");
    $("#" + lcl).addClass("on");


    initBodyNavH2();
    initSelectConcelho();

    $(".nInL").bind("mouseover",function(){
       $(".title",this).addClass("titleOn");
    });
    $(".nInL").bind("mouseout",function(){
        $(".title",this).removeClass("titleOn");
    });
    $(".nInL").bind("click",function(){
        document.location.href=$(".title a",this).attr("href");
    });

    $(document).trigger("mainInitDone");
});

function initBodyNavH2() {
    var hh2 = $("#pageBody h2");
    if (hh2.length) {
        var n = $("<ul class=\"bodyNav\">");

        var ihh2 = 0;
        $.each(hh2, function() {
            var content = $(this).attr("title");
            if (content == null || $.trim(content).length == 0)
                content = $(this).html();

            var atohh2 = $("<a>").attr("href", "#hh2" + ihh2).append("&bull; " + content + "&nbsp;&nbsp;");
            n.append(atohh2);

            var newA = $("<a>");
            //newA[0].name="hh2" + ihh2;
            newA[0].id = "hh2" + ihh2;

            $(this).prepend(newA);
            ihh2++;
        });

        if ($("#pageBody ul.bodyNav").length) {
            $("#pageBody ul.bodyNav:last").after(n);
        } else
            $("#pageBody").prepend(n);
    }
    $.localScroll();
}


var nutsOptions = new Object();

function initSelectConcelho() {
    nutsOptions.all = new Array();

    $.each($("#nutsiii option"), function() {
        if (this.disabled) return;
        var n = this.value;
        nutsOptions["" + n] = new Array();
    });
    nutsOptions.all = new Array();
    nutsOptions.first = $("#concelho option:first")[0];

    $.each($("#concelho option"), function() {
        if (this.disabled) return;
        var n = this.className;
        nutsOptions.all[nutsOptions.all.length] = this;
        nutsOptions["" + n][nutsOptions["" + n].length] = this;
    });

    $("#municipios").bind("click", function(e) {
        if ($("#selectConcelho").css("display") != "block")
            $("#selectConcelho").slideDown("fast");
        else {
            $("#concelho option").remove();
            $("#concelho").append(nutsOptions.first);
            $("#concelho").append(nutsOptions.all);
            $("#nutsiii").val("-1");
            $("#concelho").val("-1");
            $("#mapa").attr("src", "/maps");
            e.stopPropagation();
        }

        return false;
    });

    $("#nutsiii").bind("change", changedNut);

    $("#concelho").change(function() {
        document.location.href = "/np4/municipios/?c=" + $(this).val();
    });

    $("#mapa").bind("click", mapaClick);
    $("#mapa").css("cursor", "pointer");

    var timei;
    $("#mapa").bind("mouseover", function() {
        $(document).bind("mousemove", mapaTrackMove);
        timei = window.setInterval(mapaTrackPosition, 250);
    });
    $("#mapa").bind("mouseout", function() {
        $(document).unbind("mousemove", mapaTrackMove);
        window.clearInterval(timei);
        $("#mapaTip").html("&nbsp;");
    });

}

function mapaTrackMove(e) {
    var mapa = $("#mapa");
    mapa[0].lastX = e.pageX;
    mapa[0].lastY = e.pageY;
}

function mapaTrackPosition() {

    var mapa = $("#mapa");

    var x = mapa[0].lastX;
    var y = mapa[0].lastY;

    if (!mapa[0].lastXX || Math.abs(mapa[0].lastX - mapa[0].lastXX) > 3 || Math.abs(mapa[0].lastY - mapa[0].lastYY) > 3) {
        mapa[0].lastXX = x;
        mapa[0].lastYY = y;
        y -= mapa.offset().top;
        x -= mapa.offset().left;

        var inMapa = y > 0 && x > 0 && y < mapa.height() && x < mapa.width();
        if (inMapa)
        {
            var curSrc = mapa.attr("src");
            var uri = "/maps?json&x=" + x + "&y=" + y;
            if (curSrc.indexOf("?") >= 0)
                uri += "&" + curSrc.substr(curSrc.indexOf("?") + 1);
            $.ajax({
                url: uri,
                global: false,
                type: "GET",
                dataType: "json",
                success: function(d) {
                    if (d["name"])
                        $("#mapaTip").html(d["name"]);
                    else
                        $("#mapaTip").html("&nbsp;");
                }
            });
        }
    }
}


function mapaClick(e) {
    var x = e.pageX;
    var y = e.pageY;
    y -= $("#mapa").offset().top;
    x -= $("#mapa").offset().left;
    var curSrc = $("#mapa").attr("src");
    var uri = "/maps?json&x=" + x + "&y=" + y;
    if (curSrc.indexOf("?") >= 0)
        uri += "&" + curSrc.substr(curSrc.indexOf("?") + 1);

    $.ajax({
        url: uri,
        global: false,
        type: "GET",
        dataType: "json",
        success: function(d) {
            if (d["cconc"] > 0) {
                document.location.href = "/np4/municipios/?c=" + d["cconc"];
            } else if (d["nutsiii"] > 0) {
                $("#nutsiii").val(d["nutsiii"]);
                changedNut();
            }
        }
    });
}

function changedNut() {
    $("#concelho option").remove();
    $("#concelho").append(nutsOptions.first);
    $("#concelho").append(nutsOptions[$("#nutsiii").val()]);
    $("#concelho").val("-1");

    var mapUri = "/maps?iii=" + $("#nutsiii").val();
    if (typeof onConcelho != "undefined") {
        mapUri += "&c=" + onConcelho;
    }
    $("#mapa").attr("src", mapUri);
}