var imageCount = 0;
var scrollStep = 0;
var scrollContainer = null;
var updateContainer = null;
var ajaxRequestAllowed = true;

Event.observe(window, "load", function() {
    scrollContainer = $('scrollContainer');
    updateContainer = $('updateContainer');
    //we assume that all images have the same height
    imageCount = scrollContainer.immediateDescendants().length;
    var firstImageHeight = scrollContainer.immediateDescendants()[0].getHeight();
    var marginOffset = scrollContainer.scrollHeight - firstImageHeight*imageCount;
    scrollStep = firstImageHeight + marginOffset/imageCount;
    
    Event.observe('arrowUp','click', function(event){
   		smoothScroll(event, -scrollStep);
    });
    Event.observe('arrowDown','click', function(event){
   		smoothScroll(event, scrollStep);
    });
    
   	Event.observe(scrollContainer,'click', showContent);
   	ajaxCall("text/Tasks.txt"); //this is the initial content
});

function smoothScroll(ev, value){
    Event.stop(ev);
    var newTop = scrollContainer.scrollTop + value; 
    if (newTop + scrollContainer.getHeight() < scrollContainer.scrollHeight) {
        new Effect.Tween('scrollContainer', scrollContainer.scrollTop, newTop, {
              queue : { position: 'end', scope: 'scrollScope', limit: 1}
        },
        'scrollTop');
    }
    return false;
}

function showContent(ev) {
    if (!ajaxRequestAllowed) return false;
    Event.stop(ev);
	updateContainer.fade({queue: 'end', duration: 0, from: 1.0, to: 0.9});
   	var src = Event.element(ev).src;
    var textfile = "text/" + src.substring(src.lastIndexOf('/') + 1, src.lastIndexOf('_thumb') ) + ".txt";
    ajaxCall(textfile);
    return false;
}

function ajaxCall(datafile) {
   if (!ajaxRequestAllowed) return;
   ajaxRequestAllowed = false;
   new Ajax.Request(datafile, {
   		method: 'get',
        onSuccess: function(response) {
			updateContainer.update(response.responseText);
            updateContainer.fade({queue: 'end', duration: 0.2, from: 0.90, to: 1});
        },
        onComplete: function(transport){ajaxRequestAllowed = true;}
   });
}

