/* globals
-------------------------------------------------------------- */
var ImageURLs = new Array;
var captionsGallery = new Array;
var currentGalleryImageID = 0;
var galleryActive = false;
var opacityGalleryOverlay = 1.0;
var orgImageWidth = 400;
var orgImageHeight = 300;
var speedFadeGalleryImage = 800;
var speedFadeGalleryOverlay = 800;

/* Functions
-------------------------------------------------------------- */

function initGallery(){

	// put all ImageURLs in an array
	ImageURLs = $("a[rel^='lightbox']").toArray();
	images = $("a[rel^='lightbox']").children([0]).toArray();
	
	// fill captionsGallery
	for(i=0; i<images.length; i++){
		// get image caption
		if(images[i].alt != images[i].title){
			captionsGallery[i] = images[i].alt;
		}else{
			captionsGallery[i] = "";
		}
	}
	
	// loop through image links
	$("a[rel^='lightbox']").each(function(index) {
		
		// click event
		$(this).click(function(event){

			// stop default behaviour
			event.preventDefault();
			// remove click border
			this.blur();
			// index
			imageID = index;
			// display the box for the elements href
			loadImage(this.href,imageID,captionsGallery[imageID]);

		});
		
	});
	
	// Enable keyboard navigation
	_enable_keyboard_navigation();
	
	
	// add gallery wrapper
	$("body").append('<div id="gallery-wrapper"></div>');
	// 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" onclick="closeGallery();">x</div>');
	// prev + next button (just if more than one image)
	if(ImageURLs.length > 1){
		$("#gallery-wrapper").append('<div class="prevNext" id="prev" onclick="prevImage();">&lsaquo;</div>');
		$("#gallery-wrapper").append('<div class="prevNext" id="next" onclick="nextImage();">&rsaquo;</div>');
	}
	// interaction
	if(images.length>1){
		$("#image-container").click(function() {
			//nextImage();
		});
	}
	$("#overlay").click(function() {
		closeGallery();
	});
	
	// opacity overlay
	$("#overlay").css({'opacity':opacityGalleryOverlay});
}

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
	currentGalleryImageID = ID;
	// bugfix
	if(galleryActive == false){
		// check if there is a movie (bugfix chrome)
		if($('.project-movie').length!=0){
			$('.project-movie').hide();
		}
		// fade in wrapper
		$("#gallery-wrapper").fadeIn(speedFadeGalleryOverlay);
		// hide scrollbars in body
		$("body").css('overflow','hidden');
	}
	
	// status galleryActive
	galleryActive = 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);
		// hide
		$("#image-container img").hide();
		// fade in
		$("#image-container img").fadeIn(speedFadeGalleryImage);
		// get original width + height
		orgImageWidth = $(this).width();
		orgImageHeight = $(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 prevImage(){
	currentGalleryImageID--;
	if(currentGalleryImageID < 0){
		currentGalleryImageID = ImageURLs.length-1;
	}
	loadImage(ImageURLs[currentGalleryImageID],currentGalleryImageID,captionsGallery[currentGalleryImageID]);
}
function nextImage(){
	currentGalleryImageID++;
	if(currentGalleryImageID > ImageURLs.length-1){
		currentGalleryImageID = 0;
	}
	loadImage(ImageURLs[currentGalleryImageID],currentGalleryImageID,captionsGallery[currentGalleryImageID]);
}

function closeGallery(){
	// status
	galleryActive = false;
	// hide
	$("#gallery-wrapper").fadeOut(speedFadeGalleryOverlay, function() {
		// check if there is a movie (bugfix chrome)
		if($('.project-movie').length!=0){
			$('.project-movie').show();
		}
		// hide wrapper
		$("#gallery-wrapper").css('display','none');
		// show scrollbars in body
		$("body").css('overflow','auto');
	});
}

function resizeGallery(){
	// just if active
	if(galleryActive == true){
		
		// calc everything
		var w = window.innerWidth ? window.innerWidth : $(window).width();
	    var h = window.innerHeight ? window.innerHeight : $(window).height();
	
		var mh = h - offsetXGallery;
	
	    var iw = orgImageWidth;
	    var ih = orgImageHeight;
	    var rw = iw / ih;
	    var sc = mh * rw;
	    nh = mh;
	    nw = sc;
	
		// check if image is smaller than screen
		if(ih <= mh){
			nh = ih;
			nw = iw;
		}
		
		// position
		positionY = $(document).scrollTop()+'px';
		positionX = w/2 - nw/2;

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

		// resize overlay
		$('#gallery-wrapper').css({'height': h, 'width': w, 'top':positionY});
		// size overlay
		$('#overlay').css({'width': w, 'height': h});
	
		// resize image
		$('#image-container img').css({'height': nh, 'width': nw});
		// position+resize image container
		if(ih <= mh){
			positionY = h/2 - orgImageHeight/2;
		}else{
			positionY = offsetXGallery/2;
		}
		$('#image-container').css({'left': positionX, 'top': positionY, 'width': nw, 'height': nh});
	
		// position prev next
		positionY = h/2 - $('#prev').height()/2;
		$('.prevNext').css({'top': positionY, 'display': 'block'});
	
	}
	
}

/**
 * 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 galleryActive
	if(galleryActive == true){
		// To ie
		if ( objEvent == null ) {
			keycode = event.keyCode;
		// To Mozilla
		} else {
			keycode = objEvent.keyCode;
		}
		// Get the key in lower case form
		key = String.fromCharCode(keycode).toLowerCase();
		// Verify the keys to close the ligthBox
		if ( ( key == 'x' ) || ( keycode == 27 ) ) {
			closeGallery();
		}
		// Verify the key to show the previous image
		if ( keycode == 37 ) {
			prevImage();
		}
		// Verify the key to show the next image
		if ( keycode == 39 ) {
			nextImage();
		}
	}
}
