var ImagePathList = new Array();
var ImageLoadedList = new Array();

var ImageLoadingPath = 'http://e-ejendom.dk/images/loading.gif';

var imgTmp = new Image();
imgTmp.src = ImageLoadingPath;

var ImageListPointer = 0;

var ImageLeft = null;
var ImageRight = null;

var ImageChangeTimer = null;

var ImageChangerInterval = 7000;
var ImageAppearDuration = 0.6;

var ImageLeftId = 'gallery_1';
var ImageRightId = 'gallery_2';

function imageAutoChanger(){
    if(ImagePathList.length < 3)
        return;

    ImageChangeTimer = setInterval("moveRight()", ImageChangerInterval);
}

function shiftImages(){
    if(ImagePathList.length == 0)
        return;

    setImages();

    var pointer_left = ImageListPointer;
    var pointer_right = null;
    if(ImageListPointer < ImagePathList.length - 1)
        pointer_right = ImageListPointer+1;
    else
        pointer_right = 0;

    if(ImageLoadedList[pointer_left])
        changeImageLeft(pointer_left);
    else
        loadImageLeft(pointer_left);

    if(ImageLoadedList[pointer_right])
        changeImageRight(pointer_right);
    else
        loadImageRight(pointer_right);
}

function changeImageLeft(aIndex){
    ImageLeft.hide();
    ImageLeft.src = ImagePathList[aIndex];
    ImageLeft.appear({ duration: ImageAppearDuration });
}

function changeImageRight(aIndex){
    ImageRight.hide();
    ImageRight.src = ImagePathList[aIndex];
    ImageRight.appear({ duration: ImageAppearDuration, queue: 'end' });
}

function loadImageLeft(aIndex){
    ImageLeft.src = ImageLoadingPath;
    image = new Image();
    image.onLoad = loadedLeft(aIndex);
    image.src = ImagePathList[aIndex];
}

function loadImageRight(aIndex){
    ImageRight.src = ImageLoadingPath;
    var image = new Image();
    image.onLoad = loadedRight(aIndex);
    image.src = ImagePathList[aIndex];
}

function loadedLeft(aIndex){
    ImageLoadedList[aIndex] = true;
    changeImageLeft(aIndex);
}

function loadedRight(aIndex){
    ImageLoadedList[aIndex] = true;
    changeImageRight(aIndex);
}

function moveToRight(){
    stopImageAutoChanger();
    moveRight();
}

function moveToLeft(){
    stopImageAutoChanger();
    moveLeft();
}

function stopImageAutoChanger(){
    clearInterval(ImageChangeTimer);
}

function moveRight(){
    ImageListPointer++;
    ImageListPointer %= ImagePathList.length;

    shiftImages();
}

function moveLeft(){
    if(ImageListPointer == 0)
        ImageListPointer = ImagePathList.length;
    ImageListPointer--;

    shiftImages();
}

function setImages(){
    ImageLeft = $(ImageLeftId);
    ImageRight = $(ImageRightId);
}
