
var cache;
var imageDir = 'images/';
var imageWidth = 400;
var imageHeight = 272;
var pics = new Array();

function Pic(number, image, width, height, caption, alt, explanation){
    this.caption = document.createTextNode(caption);
    this.alt = alt;
    this.explanation = document.createTextNode(explanation);
    this.img = new Image(width, height)
    this.img.src = imageDir + image;
    this.thumb = new Image(width/4, height/4)
    this.thumb.src = imageDir + image;
    this.img.onclick = clickHandler(number)
    this.thumb.onclick = clickHandler(number)
}


function clickHandler(n){
   function handler(){
     render(n)
   }
   return  handler
}

function addPicture(imageUrl, caption, alt, description){
    pics[pics.length] = 
            new Pic(pics.length, imageUrl, 
                    imageWidth, imageHeight, 
                    caption, alt, description)
}


function setup(){
    render(0);
}

/* Render all the images in places according to offset n */
function render(n){
    for (frameNo = 0; frameNo < pics.length; frameNo++){
       var picNo = (n + frameNo) % pics.length
       renderImage(frameNo, picNo)
    }
}

/* render one image in location pos */
function renderImage(frameNo, picNo){
    var pic = pics[picNo]
    /* all exceptthe first are thumbnails */
    var img = (frameNo == 0)? pic.img : pic.thumb;
    var element = document.getElementById('pic' + frameNo)
    /* element is now a <a> or <div> element */
    if (element.hasChildNodes()) {
       element.removeChild(element.firstChild)
    }
    element.insertBefore(img, element.firstChild)
    subDivs = element.parentNode.getElementsByTagName('div')
    subDivs[0].appendChild(pic.caption)
    subDivs[1].appendChild(pic.explanation)
}

function init(){
   setup();
}

window.onload = init;

