var lastY = -100;
var timeout = false;
$(document).ready(function(){
    if($("#header img").length > 1){
        timeout = window.setTimeout('switchImage(0)', 5000);
    }
    $("#gallery img").hover(function(){
        $(this).animate({opacity:1}, "fast");
    }, function(){
        $(this).animate({opacity:0.4}, "fast");
    });
    $("#gallery").mousemove(function(e){
        var y = e.pageX;
        if(y >= 280 && y <= 960){
             $("#gallery ul").stop();
             lastY = y;
             return;
        }
        var mTop = $("#gallery ul").css("left");
        var top = parseInt(mTop.substr(0, mTop.length - 2), 10);
        if((y > 960 && lastY <= 960) || lastY == -100){
            $("#gallery ul").stop();
            galleryMove(top, true);
        }
        else if((y < 280 && lastY >= 280) || lastY == -100){
            $("#gallery ul").stop();
            galleryMove(top, false);
        }
        lastY = y;
    });
    $("#gallery img").click(function(){
        var ix = $.inArray(this, $("#gallery img"));
        if(timeout){
            window.clearTimeout(timeout);
        }
        timeout = window.setTimeout('switchImage(' + ix + ')', 10000);
        $("#header img").fadeOut();
        $($("#header img")[ix]).fadeIn();
    });
});
function switchImage(ix) {
    var imgs = $("#header img");
    var current = ix;
    if(++ix >= imgs.length) { ix = 0; }
    $(imgs[current]).fadeOut("slow");
    $(imgs[ix]).fadeIn("slow");
    timeout = window.setTimeout('switchImage(' + ix + ')', 5000);
}
function galleryMove(top, up){
    if(up){
        newTop = top - 4;
        if(newTop < 890 - $("#gallery ul").width()){
            $("#gallery ul").stop();
            return;
        }
    }
    else{
        newTop = top + 4;
        if(newTop > 0){
            $("#gallery ul").stop();
            return;
        }
    }
    $("#gallery ul").animate({left:newTop}, {duration:10, complete:function(){
        galleryMove(newTop, up);
    }});
}
function debugWrite(s){
    if(!$("#debug").length){
        $("<div></div>")
            .attr("id", "debug")
            .appendTo("body");
    }
    $("#debug").html(s + "<br />" + $("#debug").html());
}


