// globals
var path = "";
var URLs = new Array;
var captions = new Array;
var currentImageID = 0;
var active = false;
var orgWidth = 400;
var orgHeight = 300;

function initGallery(){

	// put all URLs in an array
	URLs = $("a.gallery").toArray();
	images = $("a.gallery").children([0]).toArray();
	
	// fill captions
	for(i=0; i<images.length; i++){
		// get image caption
		if(images[i].alt != images[i].title){
			captions[i] = images[i].alt;
		}else{
			captions[i] = "";
		}
	}
	
	// add click event to all hrefs with class="gallery"
	$("a.gallery").click(function(event){
		// stop default behaviour
		event.preventDefault();
		// remove click border
		this.blur();
		// get rel attribute for image groups
		var group = this.rel || false;
		// loop through URLs
		imageID = 0;
		for(i=0; i<URLs.length; i++){
			// check if same URL
			if(this.href == URLs[i]){
				imageID = i;
			}
		}
		// display the box for the elements href
		loadImage(this.href,imageID,captions[imageID]);
		
	});
	
	// Enable keyboard navigation
	_enable_keyboard_navigation();
	
	// remove everything inside gallery wrapper
	$("#gallery-wrapper").empty();
	// add overlay
	$("#gallery-wrapper").append('<div id="overlay"></div>');
	// image container
	$("#gallery-wrapper").append('<div id="image-container"></div>');
	// close button
	$("#gallery-wrapper").append('<div id="caption" class="markup"></div>');
	// close button
	$("#gallery-wrapper").append('<div id="close"><a href="javascript:void(0)" onclick="closeGallery();" title="close">&nbsp;x&nbsp;</a></div>');
	// prev + next button (just if more than one image)
	if(URLs.length > 1){
		$("#gallery-wrapper").append('<div class="prevNext" id="prev"><a href="javascript:void(0)" onclick="prev();" title="prev">&lsaquo; prev</a></div>');
		$("#gallery-wrapper").append('<div class="prevNext" id="next"><a href="javascript:void(0)" onclick="next();" title="next">next &rsaquo;</a></div>');
	}
	// interaction
	if(images.length>1){
		$("#image-container").click(function() {
			next();
		});
	}
	$("#overlay").click(function() {
		closeGallery();
	});
	
}

function loadImage(imageURL,ID,caption){
	
	// caption
	if(caption == ""){
		// hide
		$("#caption").css('display','none');
	}else {
		// show
		$("#caption").css('display','block');
		$("#caption").html(caption);
	}
	// upadte current image
	currentImageID = ID;
	// show
	//$("#gallery-wrapper").css('display','block');
	// bugfix
	if(active == false){
		$("#gallery-wrapper").fadeIn('slow');
		// hide scrollbars in body
		$("body").css('overflow','hidden');
		// disable zoom if iPhone
		/*if(is_iPhone()){
			disableZoom();
		}*/
	}
	
	// status active
	active = true;
	
	// resize gallery (bugfix)
	resizeGallery();
	
	// create new image
	var img = new Image();
	// remove everything inside image container
	$("#image-container").empty();
	// add loading class
	$("#image-container").addClass("loading");
	// write less, do more ;)
	$(img)
	// this is executed when image is loaded
	.load(function () {
		// remove loading class
		$("#image-container").removeClass("loading");
		// insert image
	    $("#image-container").append(this);
		// get original width + height
		orgWidth = $(this).width();
		orgHeight = $(this).height();
		// resize gallery
		resizeGallery();
    })
    // if there was an error loading the image, react accordingly
    .error(function () {
      	// remove loading class
		$("#image-container").removeClass("loading");
		// error message
		$("#caption").css('display','block');
		$("#caption").html('<div id="error">Image not found</div>');
    })
    // *finally*, set the src attribute of the new image to our image
    .attr('src', imageURL);

}

function prev(){
	currentImageID--;
	if(currentImageID < 0){
		currentImageID = URLs.length-1;
	}
	loadImage(URLs[currentImageID],currentImageID,captions[currentImageID]);
}
function next(){
	currentImageID++;
	if(currentImageID > URLs.length-1){
		currentImageID = 0;
	}
	loadImage(URLs[currentImageID],currentImageID,captions[currentImageID]);
}

function closeGallery(){
	// status active
	active = false;
	// hide
	$("#gallery-wrapper").fadeOut('slow', function() {
		$("#gallery-wrapper").css('display','none');
		// show scrollbars in body
		$("body").css('overflow','auto');
		// enable zoom again if iPhone
		/*if(is_iPhone()){
			allowZoom();
		}*/
	});
}

function resizeGallery(){
	// just if active
	if(active == true){
		
		// calc everything
		var w = window.innerWidth ? window.innerWidth : $(window).width();
	    var h = window.innerHeight ? window.innerHeight : $(window).height();
	    var iw = $('#image-container img').attr('width');
	    var ih = $('#image-container img').attr('height');
	    var rw = iw / ih;
	    var sc = h * rw;
	    nh = h;
	    nw = sc;

		// bugfix first time
		if(iw==null){
			iw=400;
		}
		if(ih==null){
			ih=300;
		}

		positionY = $(document).scrollTop()+'px';
		positionX = w/2 - nw/2;

		// resize overlay
		$('#gallery-wrapper').css({'height': h, 'width': w, 'top':positionY});
		// size overlay
		$('#overlay').css({'width': w, 'height': h});
	
		// resize image (just if not bigger than original size)
		if(nw <= orgWidth){
			$('#image-container img').css({'height': nh, 'width': nw});
			// position+resize image container
			$('#image-container').css({'left': positionX, 'top': 0, 'width': nw, 'height': nh});
		}else{
			$('#image-container img').css({'height': orgHeight, 'width': orgWidth});
			// position+resize image container
			positionX = w/2 - orgWidth/2;
			positionY = h/2 - orgHeight/2;
			$('#image-container').css({'left': positionX, 'top': positionY, 'width': orgWidth, 'height': orgHeight});
		}
	
		// position prev next
		positionY = h/2 - $('#prev').height()/2;
		$('.prevNext').css({'top': positionY, 'display': 'block'});
	
	}
	
}

/**
 * iPhone hacks
 *
 */
// Return boolean TRUE/FALSE
function is_iPhone(){
    return (
        (navigator.platform.indexOf("iPhone") != -1) ||
        (navigator.platform.indexOf("iPod") != -1) ||
		(navigator.platform.indexOf("iPad") != -1)
    );
}
// prevent zooming
function allowZoom(){
	document.getElementById("viewport").setAttribute('content','width=device-width, initial-scale=1.0, maximum-scale=10.0');
}
function disableZoom(){
	document.getElementById("viewport").setAttribute('content','width=device-width, minimum-scale = 1, maximum-scale = 1');
}

/**
 * Enable a support to keyboard navigation
 *
 */
function _enable_keyboard_navigation() {
	$(document).keydown(function(objEvent) {
		_keyboard_action(objEvent);
	});
}
/**
 * Disable the support to keyboard navigation
 *
 */
function _disable_keyboard_navigation() {
	$(document).unbind();
}
/**
 * Perform the keyboard actions
 *
 */
function _keyboard_action(objEvent) {
	// just if active
	if(active == true){
		// To ie
		if ( objEvent == null ) {
			keycode = event.keyCode;
			escapeKey = 27;
		// To Mozilla
		} else {
			keycode = objEvent.keyCode;
			escapeKey = objEvent.DOM_VK_ESCAPE;
		}
		// Get the key in lower case form
		key = String.fromCharCode(keycode).toLowerCase();
		// Verify the keys to close the ligthBox
		if ( ( key == 'x' ) || ( keycode == escapeKey ) ) {
			closeGallery();
		}
		// Verify the key to show the previous image
		if ( keycode == 37 ) {
			prev();
		}
		// Verify the key to show the next image
		if ( keycode == 39 ) {
			next();
		}
	}
}
