var position = 0;
var firstId = 0;
var secondId = 1;
var slideshow = false;
var loopId;
var moving = false;
var moveId;

function swapImage(incr, num) {
    var picture = eval("document.photo" + num);
    var id;
    if (num > 1) {
        id = secondId = (incr == '+') ? getValidId(eval(secondId + incr + 1)) : firstId;
    } else {
        id = firstId = (incr == '-') ? getValidId(eval(firstId + incr + 1)) : secondId;
    }
    var source = eval("pic[" + id + "]");
    picture.src = source.src;
    picture.width = source.width;
    picture.height = source.height;
    picture.alt = 'Photo #' + (firstId + 1) + (source.title ? (': ' + source.title) : '');
    picture.title = source.title ? source.title : '';
    
}

function rotateImages(mode, incr) {
    if (mode == 'off') {
        window.clearTimeout(loopId);
        if (moving) {
            window.clearTimeout(moveId);
        }
        slideshow = false;
    } else {
        slideshow = true;
        scrollImages(incr, true);
    }
}

function switchButtonStyle(mode, button) {
    button.style.borderStyle = (mode == 'off') ? 'outset' : 'inset';
    button.style.backgroundColor = (mode == 'off') ? '#FDCA67' : '#FFDFAD';
}

function scrollImages(incr, loop) {
    var frame = document.getElementById('presentation');
    width = width ? width : 0;
    if (incr == '-') {
        if (position != -width) {
            window.clearTimeout(loopId);
            position = -width;
            swapImage('-', 2);
            frame.style.left = position + 'px';
            setTimeout("swapImage('-', 1)", 10);
        }
    } else {
        if (position != 0) {
            window.clearTimeout(loopId);
            position = 0;
            swapImage('+', 1);
            frame.style.left = position + 'px';
            setTimeout("swapImage('+', 2)", 10);
        }
    }
    if (loop) {
        loopId = setTimeout("scrollImages('" + incr + "', true)", 10000);
    }
    moveImages(incr);
    moving = true;
}

function moveImages(incr) {
    var frame = document.getElementById('presentation');
    width = width ? width : 0;
    var step = width / 10;
    if (incr == "-") {
        if (position < 0) {
            position = position + step;
            moveId = setTimeout("moveImages('-')", 40);
        } else {
            position = -width;
            setTimeout("swapImage('-', 1)", 10);
            swapImage('-', 2);
            moving = false;
        }
    } else {
        if (position > -width) {
            position = position - step;
            moveId = setTimeout("moveImages('+')", 40);
        } else {
            position = 0;
            swapImage('+', 1);
            setTimeout("swapImage('+', 2)", 10);
            moving = false;
        }
    }
    frame.style.left = position + 'px';
}

function getValidId(id) {
    if (id >= pic.length) {
        return id % pic.length;
    } else if (id < 0) {
        return id + pic.length;
    } else {
        return id;
    }
}
