var imageIndex = -1;
//var images = null;

/*$(document).ready(function() {
	if (images) {
		imageIndex = Math.floor(Math.random()*images.length);
        console.log(imageIndex);
		nextImg();
	}
});*/

function nextImg() {
	imageIndex = (imageIndex + 1) % images.length;
	changeImage();
}

function prevImg() {
	imageIndex = (images.length + (imageIndex - 1)) % images.length;
	changeImage();
}

function changeImage() {

	$("#showcaseImage").attr({ 
          src: "image.php?w=216&h=250&keepAspect=y&img=" + images[imageIndex].source,
          title: images[imageIndex].title,
          alt: images[imageIndex].alt
        });

	$("#galleryLink").attr({ 
			href: "gallery-image.php?id=" + images[imageIndex].gallery.id + "&image="+ images[imageIndex].id
        });


	if (images[imageIndex].alt == "") {
		images[imageIndex].alt = "View This Image!";
	}

	var html = "<strong><a href='gallery-image.php?id=" + images[imageIndex].gallery.id + "&image="+ images[imageIndex].id +"'>" + images[imageIndex].alt + "</a></strong><br />" +
			   "Gallery: <a href='gallery-page.php?id=" + images[imageIndex].gallery.id + "'>" + images[imageIndex].gallery.attributes.publish_name + "</a><br />" ;

	var keyStageHTML = "";
	var keyStageFound = false;

	for (var i = 1; i <= 7; i++) {
		if (images[imageIndex].gallery.attributes['key_stage'+i] == '1') {
			keyStageHTML += "<a href='gallery-search.php?key_stage=" + i +"&college=" + gup("college") + "'>" + i + "</a> ";	
			keyStageFound = true;
		}
	}

	if (keyStageFound) {
		html += " Key Stage " + keyStageHTML + " | ";
	}

	var yearsFound = false;
	var yearsHTML = "";
	for (var i = 7; i <= 13; i++) {
		if (images[imageIndex].gallery.attributes['year'+i] == '1') {
			yearsHTML += "<a href='gallery-search.php?year=" + i +"&college=" + gup("college") + "'>" + i + "</a> ";	
			yearsFound = true;
		}
	}

	if (yearsFound)	{
		html += " Year " + yearsHTML + " | ";
	}
	
	var category = images[imageIndex].gallery.attributes.lookup_gallery_category.attributes;

	if (category != undefined)	{
		html += " <a href='gallery-search.php?category=" + category.publish_name + "&college=" + gup("college") + "'>" + category.publish_name + "</a>";
	}
	
	$("#showcaseText").html(html);
}

function setImage(id, src) {
	$("#"+id).attr({src: src});
}

/** source: http://www.netlobo.com/url_query_string_javascript.html */
function gup( name ) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}