jQuery.fn.mousehold = function(timeout, f){
    if (timeout && typeof timeout == 'function') {
        f = timeout;
        timeout = 100;
    }
    if (f && typeof f == 'function') {
        var timer = 0;
        var fireStep = 0;
        return this.each(function(){
            jQuery(this).mousedown(function(){
                fireStep = 1;
                var ctr = 0;
                var t = this;
                timer = setInterval(function(){
                    ctr++;
                    f.call(t, ctr);
                    fireStep = 2;
                }, timeout);
            })
            
            clearMousehold = function(){
                clearInterval(timer);
                //if (fireStep == 1) 
                //    f.call(this, 1);
                fireStep = 0;
            }
            
            jQuery(this).mouseout(clearMousehold);
            jQuery(this).mouseup(clearMousehold);
            jQuery(this).error(clearMousehold);
        })
    }
}

LEFT_ARROW = 37;
UP_ARROW = 38;
RIGHT_ARROW = 39;
DOWN_ARROW = 40;


var cache = new Object();
var state = new Object();
state.slices = new Object();
state.currentPhotoIndex = 0;
state.imageReady = false;
state.loadingSlice = false;
state.currentDir = 1;

var tooMuch = 0;
var maxTooMuch = 10000000;

function getJsonUrl(){
	return "listPhotos.php?page=" + extractPage()+"&t="+new Date().getTime(); 
}

function extractPage(){
	arr=window.location.href.split("/")
	return arr[arr.length-1].split('.')[0]
}

function currentPhotoList(){
    return state.slices[state.currentSlice];
}

function showPictures(){
    jQuery.getJSON(getJsonUrl(), null, function(json){
        state.currentSlice = json.slice;
        state.slices[json.slice] = json.files;
		state.currentDir = json.dir;
        showPhoto();
        jQuery.each(json.files, function(i, item){
            cache[item] = new Image();
            cache[item].src = "photos/" + json.dir + "/" + item;
        });
    });
}

function loadPreviousSlice(){
    if (state.loadingSlice) 
        return;
    previousSlice = state.currentSlice - 1;
    if (null != state.slices[previousSlice]) 
        return;
    state.loadingSlice = true;
    jQuery.getJSON(getJsonUrl() + "&slice=" + previousSlice, null, function(json){
        state.slices[json.slice] = json.files;
        state.loadingSlice = false;
        setButtonStates();
        jQuery.each(json.files, function(i, item){
            cache[item] = new Image();
            cache[item].src = "photos/" + json.dir + "/" + item;
        });
    });
}

function showPhoto(){
    tooMuch++;
    if (tooMuch > maxTooMuch) {
        console.debug("limit maxTooMuch");
        return;
    }
    if (0 > state.currentPhotoIndex) {
        if (null != state.slices[state.currentSlice + 1]) {
            state.currentSlice = state.currentSlice + 1;
            state.currentPhotoIndex = state.slices[state.currentSlice].length - 1
        }
        else 
            state.currentPhotoIndex = 0;
    }
    else 
        if (currentPhotoList().length - 1 < state.currentPhotoIndex) {
            if (state.currentSlice > 0) {
                if (null != state.slices[state.currentSlice - 1]) {
                    state.currentPhotoIndex = 0;
                    state.currentSlice = state.currentSlice - 1;
                }
                else {
                    loadPreviousSlice();
                    return;
                }
            }
            else 
                state.currentPhotoIndex = currentPhotoList().length - 1;
        }
    if (currentPhotoList().length > 0) {
    	state.imageReady = false;
        jQuery("#image").attr("src", "photos/"+state.currentDir+"/" + currentPhotoList()[state.currentPhotoIndex]);
    }
    setButtonStates();
    if (state.currentSlice > 0 && state.currentPhotoIndex > currentPhotoList().length * 1 / 2) {
        loadPreviousSlice();
    }
}

function setButtonStates(){
    if (0 >= state.currentPhotoIndex && null == state.slices[state.currentSlice + 1]) {
        jQuery('#rewindImageButton').error();
        jQuery('#rewindImageButton').attr("disabled", "disabled");
    }
    else {
        jQuery('#rewindImageButton').removeAttr("disabled");
    }
    if (currentPhotoList().length - 1 <= state.currentPhotoIndex && null == state.slices[state.currentSlice - 1]) {
        jQuery('#forwardImageButton').error();
        jQuery('#forwardImageButton').attr("disabled", "disabled");
    }
    else 
        jQuery('#forwardImageButton').removeAttr("disabled");
}

function forwardImage(){
    if (state.imageReady) {
        state.currentPhotoIndex += 1;
        showPhoto();
    }
}

function rewindImage(){
    if (state.imageReady) {
        state.currentPhotoIndex -= 1;
        showPhoto();
    }
}

jQuery(document).ready(function(){
    showPictures();
    jQuery('#image').click(function(){
        forwardImage();
    });
    jQuery('#image').load(function(){
        state.imageReady = true;
    });
    jQuery('#image').error(function(){
        state.imageReady = true;
    });
    jQuery('#rewindImageButton').mousehold(function(){
        rewindImage();
    });
    jQuery('#forwardImageButton').mousehold(function(){
        forwardImage();
    });
    jQuery('').keydown(function(event){
        switch (event.keyCode) {
            // see here for details: http://unixpapa.com/js/key.html    
            case LEFT_ARROW:
                forwardImage();
                break;
            case RIGHT_ARROW:
                rewindImage();
                break;
            case UP_ARROW:
                break;
            case DOWN_ARROW:
                break;
        }
    });
});
