var textoHMax = 80;

$(function() {
    window.loadedFoto = false;
    window.oldW = $(window).width();
    window.oldH = $(window).height()
    window.setInterval(function() {
        var wh = $(window).height();
        var ww = $(window).width();
        if (!window.loadedFoto || window.oldW != ww || window.oldH != wh) {
            resizeFoto();
            window.oldW = ww;
            window.oldH = wh;
        }
    }, 500);

    $("#the_foto").bind("load", resizeFoto);

    if (typeof myArea != "undefined") {
        $("#menu li a").each(function() {
            if (this.href.indexOf("/" + myArea + "/") >= 0) {
                $(this).closest("li").addClass("on");
            }
        });
    }
    if (!window.menuOn) {
        window.menuOn = false;
        $(document).bind("mousemove", function(event) {
            var y = event.pageY;
            if (y < 75) {
                if (!window.menuOn) {
                    window.menuOn = true;
                    $("#menu").fadeIn(100);
                }
            } else {
                if (window.menuOn) {
                    window.menuOn = false;
                    $("#menu").fadeOut(100);
                }
            }
        })

    } else {
        $("#menu").fadeIn(100);
    }

    var href = $("#foto a").attr("href");
    if (window.vimeo) {
        $("#the_foto").replaceWith(window.vimeo);
        if (href)
            $(".inTexto").prepend("<p><span class=\"area\"><a href=\"" + href + "\">&gt; Next</a></span></p>");
    }
    if (!href){
        $("#foto a").replaceWith($("#foto a").html());
    }
});

function resizeFoto() {
    var jfoto = $("#the_foto");
    if (jfoto.width() > 0)
        window.loadedFoto = true;
    else return;


    var mtop = $("#foto").offset().top;
    var mother = $("#foto").offset().left;

    var the_foto = $("#the_foto")[0];
    var wh = $(window).height();
    var ww = $(window).width();
    var maxh = wh - mtop - mother - Math.min($("#texto").height(), textoHMax);

    if ((jfoto.width() / jfoto.height()) > 6)
    {
        maxh = the_foto.realH ? the_foto.realH : jfoto.height();
        $("#texto").css("backgroundColor","black");
    }

    var iw = the_foto.realW = the_foto.realW ? the_foto.realW : jfoto.width();
    var ih = the_foto.realH = the_foto.realH ? the_foto.realH : jfoto.height();

    var w = ww - 2 * mother;
    var h = ih * w / iw;
    var padLeft = 0;
    if (maxh < h) {
        h = maxh;
        w = iw * h / ih;
        padLeft = ((ww - 2 * mother) - w) / 2;
    }

    the_foto.width = w;
    the_foto.height = h;
    $("#foto").css("paddingLeft", padLeft);
    jfoto.show();

    var jTexto = $("#texto");
    jTexto.css("top", mtop + mother + h);
    jTexto.css("left", mother + padLeft);
    jTexto.css("width", w);
    jTexto.show();
}
