/**
 * Galleria (http://monc.se/kitchen)
 *
 * Galleria is a javascript image gallery written in jQuery. 
 * It loads the images one by one from an unordered list and displays thumbnails when each image is loaded. 
 * It will create thumbnails for you if you choose so, scaled or unscaled, 
 * centered and cropped inside a fixed thumbnail box defined by CSS.
 * 
 * The core of Galleria lies in it's smart preloading behaviour, snappiness and the fresh absence 
 * of obtrusive design elements. Use it as a foundation for your custom styled image gallery.
 *
 * MAJOR CHANGES v.FROM 0.9
 * Galleria now features a useful history extension, enabling back button and bookmarking for each image.
 * The main image is no longer stored inside each list item, instead it is placed inside a container
 * onImage and onThumb functions lets you customize the behaviours of the images on the site
 *
 * Tested in Safari 3, Firefox 2, MSIE 6, MSIE 7, Opera 9
 * 
 * Version 1.0
 * Februari 21, 2008
 *
 * Copyright (c) 2008 David Hellsing (http://monc.se)
 * Licensed under the GPL licenses.
 * http://www.gnu.org/licenses/gpl.txt
 **/

(function($){

var $$;


/**
 * 
 * @desc Convert images from a simple html <ul> into a thumbnail gallery
 * @author David Hellsing
 * @version 1.0
 *
 * @name Galleria
 * @type jQuery
 *
 * @cat plugins/Media
 * 
 * @example $('ul.gallery').galleria({options});
 * @desc Create a a gallery from an unordered list of images with thumbnails
 * @options
 *   insert:   (selector string) by default, Galleria will create a container div before your ul that holds the image.
 *             You can, however, specify a selector where the image will be placed instead (f.ex '#main_img')
 *   history:  Boolean for setting the history object in action with enabled back button, bookmarking etc.
 *   onImage:  (function) a function that gets fired when the image is displayed and brings the jQuery image object.
 *             You can use it to add click functionality and effects.
 *             f.ex onImage(image) { image.css('display','none').fadeIn(); } will fadeIn each image that is displayed
 *   onThumb:  (function) a function that gets fired when the thumbnail is displayed and brings the jQuery thumb object.
 *             Works the same as onImage except it targets the thumbnail after it's loaded.
 *
**/

$$ = $.fn.galleria = function($options) {
	
	
	$.galleria.preload = {};
	// check for basic CSS support
	if (!$$.hasCSS()) { return false; }
	
	// init the modified history object
	
	// set default options
	var $defaults = {
		insert      : '.galleria_container',
		history     : true,
		clickNext   : true,
		onImage     : function(image,caption) {},
		onThumb     : function(thumb) {},
		startLoad   : function(e) {},
		endLoad     : function(e) {},
		_images      : {}
		
	};
	
	var $opts = $.extend($defaults, $options);
	
	
	
	for (var i in $opts) {
		if (i) {
			$.galleria[i]  = $opts[i];
		}
	}
	delete i;
	
	$.galleria.idx = [];
	
	for(var _img_id in $.galleria._images) {
		$.galleria.idx.push(_img_id);
	};
	$.galleria.selector = $('ul#ss-gal-ll');
	for(var i = 0; i < 4; i++) {
		var img_link = $('<li></li>').attr('id', 'ss-gal-p-' + $.galleria.idx[i]);
		var img = $('<img />').attr('src', $.galleria._images[$.galleria.idx[i]]['src_thumb']).addClass('ss-gal-p');
		$.galleria.selector.append(img_link.append(img));
		img_link.bind('click', $$.showImage);
	}
	
	$('#ss-gal-ln').click(function(e){
		$$.shiftSelector(4);
		return false;
	});
	$('#ss-gal-lp').click(function(){
		$$.shiftSelector(-4);
		return false;
	});
	
	
	// if no insert selector, create a new division and insert it before the ul
	var _insert = ( $($opts.insert).is($opts.insert) ) ? 
		$($opts.insert) : 
		jQuery(document.createElement('div')).insertBefore(this);
		
	// create a wrapping div for the image
	var _div = $(document.createElement('div')).addClass('galleria_wrapper');
	
	// create a caption span
	//var _span = $(document.createElement('span')).addClass('caption');
	
	// inject the wrapper in in the insert selector
	_insert.addClass('galleria_container').append(_div);
	$.historyInit($$.onPageLoad);
	
};

/**
 *
 * @name NextSelector
 *
 * @desc Returns the sibling sibling, or the first one
 *
**/

$$.nextSelector = function(selector) {
	
	return $(selector).is(':last-child') ?
		   $(selector).siblings(':first-child') :
    	   $(selector).next();
    	   
};

$$.nextImage = function() {
	return $.galleria.next_id;	   
};

$$.prevImage = function() {
	return $.galleria.prev_id;	   
};


$$.shiftSelector = function(increment) {
	var current = $.galleria.selector.children();
	if(increment > 0) {
		var step = 1;
		var start = 0;
	} else {
		var step = -1;
		var start = current.length - 1;
	}
	
	var i = start;
	var selector = (step == 1)?':last':':first';
	var for_remove = (step == -1)?':last':':first';
	for(var ii = 0; ii < Math.abs(increment); ii++) {
		var current = $.galleria.selector.children();
		try {
			var _id = parseInt(current.filter(selector).attr('id').replace('ss-gal-p-', ''));
			var new_link = $$.createNewImageLink(_id, step);
			if(new_link != null) {
				current.filter(for_remove).remove();
				(step == 1)?$.galleria.selector.append(new_link):$.galleria.selector.prepend(new_link);
			}
		} catch(e) {
			break;
		}
		
	}
};

$$.createNewImageLink = function(image_id, step) {
	var _idx = $.inArray(image_id.toString(), $.galleria.idx);
	if($.galleria.idx[_idx + step]) {
		var new_id = $.galleria.idx[_idx + step];
		var img_link = $('<li></li>').attr('id', 'ss-gal-p-' + new_id);
		var img = $('<img />').attr('src', $.galleria._images[new_id]['src_thumb']);
		img_link.bind('click', $$.showImage);
		return img_link.append(img);
	} else {
		return null;
	}
}

$$.showImage = function(e) {
	var _self = $(this);
	var id = parseInt(_self.attr('id').replace('ss-gal-p-', ''));
	if(_self.next().length <= 0) {
		$$.shiftSelector(1);
	}
	if(_self.prev().length <= 0) {
		$$.shiftSelector(-1);
	}
	return $.galleria.activate(id);
};

$$.preload = function(id) {
	if(!$.galleria.preload[id]) {
		$.galleria.preload[id] = {loaded : false};
		$.galleria.preload[id]['img'] = $(new Image()).bind('load', {id: id}, function(e) {
				$.galleria.preload[e.data.id]['loaded'] = true;
			}).attr('src', $.galleria._images[id]['src']);
	}
}

/**
 *
 * @name previousSelector
 *
 * @desc Returns the previous sibling, or the last one
 *
**/

$$.previousSelector = function(selector) {
	return $(selector).is(':first-child') ?
		   $(selector).siblings(':last-child') :
    	   $(selector).prev();
    	   
};

/**
 *
 * @name hasCSS
 *
 * @desc Checks for CSS support and returns a boolean value
 *
**/

$$.hasCSS = function()  {
	$('body').append(
		$(document.createElement('div')).attr('id','css_test').css({ width:'1px', height:'1px', display:'none' })
	);
	var _v = ($('#css_test').width() != 1) ? false : true;
	$('#css_test').remove();
	return _v;
};

/**
 *
 * @name onPageLoad
 *
 * @desc The function that displays the image and alters the active classes
 *
 * Note: This function gets called when:
 * 1. after calling $.historyInit();
 * 2. after calling $.historyLoad();
 * 3. after pushing "Go Back" button of a browser
 *
**/

$$.onPageLoad = function(_id) {	
	
	// get the wrapper
	var _wrapper = $('.galleria_wrapper');
	
	// get the thumb
	//var _thumb = $('.galleria img[@rel="'+_src+'"]');
	
	var first = false;
	if(!_id) {
		_id = $.galleria.idx[0];
		first = true;
	} 
	if (_id) {
		
		// new hash location
		if ($.galleria.history && !first) {
			window.location = window.location.href.replace(/\#.*/,'') + '#' + _id;
		}
		if($.galleria.preload[_id]) {
			var _img = $.galleria.preload[_id]['img'];
		} else {
			$$.preload(_id);
			var _img = $.galleria.preload[_id]['img'];
		}
		$(_img).css('display', 'none');
		_wrapper.empty().append(_img);
	
		if(!$.galleria.preload[_id]['loaded']) {
			$.galleria.startLoad(_img);
			$(_img).bind('load', function(e) {
					$.galleria.onImage(this, $.galleria._images[_id]);
				});
		} else {
			$.galleria.onImage(_img, $.galleria._images[_id]);
		}

		if($.galleria.clickNext) {
			//_img.css('cursor','pointer').click(function() { $.galleria.next(); });
		}
		
	} else {
		_wrapper.siblings().andSelf().empty();
	}

	// place the source in the galleria.current variable
	$.galleria.current = _id;
	var _idx = $.inArray(_id, $.galleria.idx);
	
	$.galleria.next_id = ((_idx + 1) < $.galleria.idx.length) ? ($.galleria.idx[_idx + 1]) : $.galleria.idx[0];
	$.galleria.prev_id = ((_idx - 1) > -1) ? ($.galleria.idx[_idx - 1]) : ($.galleria.idx[$.galleria.idx.length - 1]);
	
	$$.preload($.galleria.next_id);
	$$.preload($.galleria.prev_id);
	
};

/**
 *
 * @name jQuery.galleria
 *
 * @desc The global galleria object holds four constant variables and four public methods:
 *       $.galleria.history = a boolean for setting the history object in action with named URLs
 *       $.galleria.current = is the current source that's being viewed.
 *       $.galleria.clickNext = boolean helper for adding a clickable image that leads to the next one in line
 *       $.galleria.next() = displays the next image in line, returns to first image after the last.
 *       $.galleria.prev() = displays the previous image in line, returns to last image after the first.
 *       $.galleria.activate(_src) = displays an image from _src in the galleria container.
 *       $.galleria.onImage(image,caption) = gets fired when the image is displayed.
 *
**/

$.extend({galleria : {
	current : '',
	onImage : function(){},
	activate : function(_id) { 
		if ($.galleria.history) {
			$.historyLoad(_id);
		} else {
			$$.onPageLoad(_id);
		}
	},
	next : function() {
		var _next = $$.nextImage();
		$.galleria.activate(_next);
	},
	prev : function() {
		//var _prev = $($$.previousSelector($('.galleria img[@rel="'+$.galleria.current+'"]').parents('li'))).find('img').attr('rel');
		var _prev = $$.prevImage();
		$.galleria.activate(_prev);
	}
}
});

})(jQuery);


/**
 *
 * History extension for jQuery
 * Credits to http://www.mikage.to/
 *
**/


/*
 * jQuery history plugin
 *
 * Copyright (c) 2006 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
 * for msie when no initial hash supplied.
 */


jQuery.extend({
	historyCurrentHash: undefined,
	
	historyCallback: undefined,
	
	historyInit: function(callback){
		jQuery.historyCallback = callback;
		var current_hash = location.hash;
		
		jQuery.historyCurrentHash = current_hash;
		if(jQuery.browser.msie) {
			// To stop the callback firing twice during initilization if no hash present
			if (jQuery.historyCurrentHash === '') {
				jQuery.historyCurrentHash = '#';
			}
		
			// add hidden iframe for IE
			jQuery("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');
			var ihistory = jQuery("#jQuery_history")[0];
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = current_hash;
		}
		else if ($.browser.safari) {
			// etablish back/forward stacks
			jQuery.historyBackStack = [];
			jQuery.historyBackStack.length = history.length;
			jQuery.historyForwardStack = [];
			
			jQuery.isFirst = true;
		}
		jQuery.historyCallback(current_hash.replace(/^#/, ''));
		setInterval(jQuery.historyCheck, 100);
	},
	
	historyAddHistory: function(hash) {
		// This makes the looping function do something
		jQuery.historyBackStack.push(hash);
		
		jQuery.historyForwardStack.length = 0; // clear forwardStack (true click occured)
		this.isFirst = true;
	},
	
	historyCheck: function(){
		if(jQuery.browser.msie) {
			// On IE, check for location.hash of iframe
			var ihistory = jQuery("#jQuery_history")[0];
			var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
			var current_hash = iframe.location.hash;
			if(current_hash != jQuery.historyCurrentHash) {
			
				location.hash = current_hash;
				jQuery.historyCurrentHash = current_hash;
				jQuery.historyCallback(current_hash.replace(/^#/, ''));
				
			}
		} else if (jQuery.browser.safari) {
			if (!jQuery.dontCheck) {
				var historyDelta = history.length - jQuery.historyBackStack.length;
				
				if (historyDelta) { // back or forward button has been pushed
					jQuery.isFirst = false;
					var i;
					if (historyDelta < 0) { // back button has been pushed
						// move items to forward stack
						for (i = 0; i < Math.abs(historyDelta); i++) {
							jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop());
						}
					} else { // forward button has been pushed
						// move items to back stack
						for (i = 0; i < historyDelta; i++) {
							jQuery.historyBackStack.push(jQuery.historyForwardStack.shift());
						}
					}
					var cachedHash = jQuery.historyBackStack[jQuery.historyBackStack.length - 1];
					if (cachedHash !== undefined) {
						jQuery.historyCurrentHash = location.hash;
						jQuery.historyCallback(cachedHash);
					}
				} else if (jQuery.historyBackStack[jQuery.historyBackStack.length - 1] === undefined && !jQuery.isFirst) {
					// back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
					// document.URL doesn't change in Safari
					if (document.URL.indexOf('#') >= 0) {
						jQuery.historyCallback(document.URL.split('#')[1]);
					} else {
						current_hash = location.hash;
						jQuery.historyCallback('');
					}
					jQuery.isFirst = true;
				}
			}
		} else {
			// otherwise, check for location.hash
			current_hash = location.hash;
			if(current_hash != jQuery.historyCurrentHash) {
				jQuery.historyCurrentHash = current_hash;
				jQuery.historyCallback(current_hash.replace(/^#/, ''));
			}
		}
	},
	historyLoad: function(hash){
		var newhash;
		
		if (jQuery.browser.safari) {
			newhash = hash;
		}
		else {
			newhash = '#' + hash;
			location.hash = newhash;
		}
		jQuery.historyCurrentHash = newhash;
		
		if(jQuery.browser.msie) {
			var ihistory = jQuery("#jQuery_history")[0];
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = newhash;
			jQuery.historyCallback(hash);
		}
		else if (jQuery.browser.safari) {
			jQuery.dontCheck = true;
			// Manually keep track of the history values for Safari
			this.historyAddHistory(hash);
			
			// Wait a while before allowing checking so that Safari has time to update the "history" object
			// correctly (otherwise the check loop would detect a false change in hash).
			if(navigator.userAgent.indexOf('Chrome') == -1) {
				var fn = function() {jQuery.dontCheck = false;};
			}
			window.setTimeout(fn, 200);
			jQuery.historyCallback(hash);
			// N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
			//      By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
			//      URL in the browser and the "history" object are both updated correctly.
			location.hash = newhash;
		}
		else {
		  jQuery.historyCallback(hash);
		}
	}
});