var popDiv = null;
var imgLoadCount = 0;
var imagesToLoad = 0;
var loadedImages;
var PADDING = 20;
var SCROLL_EL = "imgGal";
var loadingP;

var WIDTH = 800;
var HEIGHT = 550;

var timer = null;

function onPageCheck()
{
	for(var i = 0; i < loadedImages.length; i++)
	{
		if (!loadedImages[i].complete) 
		{
			return;
		}
	}

	window.clearInterval(timer);
	loadingComplete();
}


function showFullImage(index)
{
    var img = loadedImages[index];
    
	var body = document.getElementsByTagName('body')[0];
	
	if (popDiv == null)
	{
		popDiv = document.createElement('div');
		popDiv.setAttribute('id','imgPopup');
		popDiv.style.width = parseInt(WIDTH) + 'px';
		popDiv.style.height = parseInt(HEIGHT) + 'px';
	}

	popDiv.appendChild(loadingP);
	body.appendChild(popDiv);

	var left = (body.offsetWidth - WIDTH) / 2;
	var top = (body.offsetHeight - HEIGHT) / 2;
	popDiv.style.left = parseInt(left) + 'px';
	popDiv.style.top = parseInt(top) + 'px';

	var imgEl = new Image();
	imgEl.onload = function()
	{
	    popDiv.removeChild(loadingP);
	    popDiv.appendChild(imgEl);
	    popDiv.onclick = removePopup;
	}

	var fileName = img.src.substring(img.src.lastIndexOf('/'));
	imgEl.src = 'images' + fileName;
    
}

function removePopup()
{
	if (popDiv != null)
	{
	    var body = document.getElementsByTagName('body')[0];
	    body.removeChild(popDiv);
	    popDiv.removeChild(popDiv.getElementsByTagName('img')[0]);
	    popDiv.onclick = new Function();
	}
}

function createImageGallery(images) {

    imagesToLoad = images.length;

     loadedImages = new Array(imagesToLoad);

    for (var i = 0; i < imagesToLoad; i++) {
        var image = new Image();
        loadedImages[i] = image;
        image.alt = "Image preview";
        image.onclick = new Function("showFullImage(" + i +");");
        image.src = images[i];
    }

    createScrollingAreaStart(SCROLL_EL, 125, HORIZONTAL);
    var innerDiv = document.getElementById(SCROLL_EL).getElementsByTagName('div')[0];

    loadingP = document.createElement('p');
    loadingP.setAttribute('class', 'loadingMessage');
    loadingP.appendChild(document.createTextNode('Loading images please wait....'));
    innerDiv.appendChild(loadingP);

    createScrollingAreaEnd();

    timer = window.setInterval("onPageCheck()", 250);
}

function loadingComplete() {
    var width = 0;
    for (var i = 0; i < imagesToLoad; i++) {
        var image = loadedImages[i];
        width += image.width;
        width += PADDING;
    }

    var scrollEl = document.getElementById(SCROLL_EL);
    var div = scrollEl.getElementsByTagName('div')[0];
    div.removeChild(loadingP);
    div.style.width = div.style.width || '0px';
    div.style.width = parseInt(width) + 'px';

    for (var i = 0; i < imagesToLoad; i++) {
        div.appendChild(loadedImages[i]);
    }
   
}

