// Created Image Gallery using Javascript

function addLoadEvent(func) {
	var oldonload = window.onload;
	if(typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

// Current => to keep track of current index. The pictures array contains links to pictures
var current = 0;
var pictures = new Array("images/butiken_1.jpg", "images/butiken_2.jpg", "images/butiken_3.jpg", "images/teddybjorn.jpg", "images/exterior.jpg", "images/knappingborg_stor.jpg", "images/marina.jpg", "images/viggo.jpg");

function prepareGallery() {
	if(!document.getElementsByTagName) return false;
	if(!document.getElementById) return false;
	
	// Get the prev and next element
	var prev = document.getElementById("prev");
	var next = document.getElementById("next");
	
	// Since they're hidden by default set their display to inline
	prev.style.display = "inline";
	next.style.display = "inline";
	
	// Attach showPic to onclick events
	prev.onclick = function() {
		return showPic(current-1);		
	}
	next.onclick = function() {
		return showPic(current+1);
	}
	prev.onkeypress = prev.onclick;
	next.onkeypress = next.onclick;
}

function showPic(currentNew) {
	if(!document.getElementById("placeholder")) return true;
	
	// If currentNew is negative you'll get an undefined value so set it to index of last element 
	if (currentNew < 0) {
		currentNew = pictures.length - 1;
	}
	
	// Uses modulo so counter can -> INF
	currentNew = currentNew % pictures.length;
	
	// Set the global variable to the new value
	current = currentNew;
	
	// Draw the new picture
	var source = pictures[current];
	var placeholder = document.getElementById("placeholder");
	placeholder.setAttribute("src", source);
	return false;
}

addLoadEvent(prepareGallery);