/**
 * 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
 **/
/*------------------------------------------------------------------------------------*/
/*  Galleria(WP)                                                                      */
/*                                                                                    */
/*   CAUTION!!!    This is not a original version of Galleria V1.0.                   */
/*                                                                                    */
/*   Major modification : replaced all '$' global to 'jQuery'                         */
/*                        (to keep avoid global name conflicts)                       */
/*                                                                                    */
/*                        added the second caption line                               */
/*                                                                                    */
/*                                                     modified by Y2 May 11, 2008    */
/*                                                                                    */
/*  V1.2  5/30 2008                                                                   */
/*------------------------------------------------------------------------------------*/

(function($) {

var galleria;

var shrink = 1;
var tempClass = "";
var usejcarousel = false;
var numOfListItems = new Array();
/**
 * 
 * @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 jQuery('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.
 *
**/

/**************************************************************************************/
galleria = 
jQuery.fn.galleria = function( $options ) {

	// shrink mode
	if ( $options.shrink ) { 
		shrink = $options.shrink;
	}
	
	// temporary class
	if ( $options.tempClass) { 
		tempClass = $options.tempClass;
	}
	
	// jcarousel scroll
	if ( $options.jcarousel ) { 
		usejcarousel = $options.jcarousel ?  true: false;
	}

	// check for basic CSS support 
	//if (!galleria.hasCSS()) { return false; }	 // Opera returns false. why?

	// init the modified history object
	//jQuery.historyInit( galleria.onPageLoad ); // 

	// set default options
	var $defaults = {
		insert		: '.galleria_stage',
		history		: true,
		clickNext	: true,
		//onImage	  : function( image, caption, thumb ) {},
		onImage		: function( image, caption1, caption2, thumb ) {}, // modified by Y2
		onThumb		: function( thumb ) {}
	};

	// extend the options
	var $opts = jQuery.extend( $defaults, $options );

	// bring the options to the galleria object
	for (var i in $opts) {
		jQuery.galleria[i]	= $opts[i];
	}

	// if no insert selector, create a new division and insert it before the ul
	var _insert = ( jQuery($opts.insert).is($opts.insert) ) ? 
		jQuery($opts.insert) : 
		jQuery(document.createElement('div')).insertBefore(this);

	// create a new span for thumbnail caption and insert it after the ul
	var _thumbspan = 
	jQuery(document.createElement('span')).text($opts.thumbnail_caption).addClass(tempClass).addClass('thumb_caption').insertAfter(this);
	
	// create a wrapping div for the image
	var _div = jQuery(document.createElement('div')).addClass( 'galleria_wrapper' );

	// create a caption span
	var _span0 = jQuery(document.createElement('span')).addClass('caption0');
	var _span1 = jQuery(document.createElement('span')).addClass('caption1');
	var _span2 = jQuery(document.createElement('span')).addClass('caption2');

	// inject the wrapper in the insert selector
	//_insert.addClass('galleria_container').append(_div).append(_span)
	//
	_insert.addClass('galleria_container').append(_div).append(_span0).append(_span1).append(_span2);

	//-------------

	return this.each( function() {

		// add the Galleria class
		jQuery(this).addClass('galleria');

		numOfListItems[tempClass] = 0;
		
		// loop through list
		jQuery(this).children('li').each( function( i ) {

			(numOfListItems[tempClass])++;
			
			// bring the scope
			var _container = jQuery(this);

			// build element specific options
			var _o = jQuery.meta ? jQuery.extend({}, $opts, _container.data()) : $opts;

			// remove the clickNext if image is only child
			_o.clickNext = jQuery(this).is(':only-child') ? false : _o.clickNext;

			// try to fetch an anchor
			var _a = jQuery(this).find('a').is('a') ? jQuery(this).find('a') : false;

			// reference the original image as a variable and hide it
			var _img = jQuery(this).children('img').css('display','none');

			// extract the original source
			var _src = _a ? _a.attr('href') : _img.attr('src');

			// find a title
			var _title = _a ? _a.attr('title') : _img.attr('title');

			// create loader image
			var _loader = new Image();

			// check url and activate container if match
			//if (_o.history && (window.location.hash && window.location.hash.replace(/\#/,'') == _src)) {
			//	_container.siblings('.active').removeClass('active');
			//	_container.addClass('active');
			//}

			// begin loader
			jQuery(_loader).load( function () {

				// try to bring the alt
				jQuery(this).attr('alt',_img.attr('alt'));

				//-----------------------------------------------------------------
				// the image is loaded, let's create the thumbnail

				//** modified by Y2	 (force to scale thumbnail images) **//
				var _thumb = _a ? 
					//_a.find('img').addClass('thumb noscale').css('display','none') :
					_a.find('img').addClass('thumb').css('display','none') : 
					_img.clone(true).addClass('thumb').css('display','none');

				if ( $options.cropThumbnail ) { 
					_thumb.addClass('noscale');
				}

				if (_a) { _a.replaceWith(_thumb); }

				if (!_thumb.hasClass('noscale')) { // scaled tumbnails!

					//var w = Math.ceil( _img.attr('width') / _img.attr('height') * _container.height() );
					//var h = Math.ceil( _img.attr('height') / _img.attr('width') * _container.width() );

					// modified by Y2
					var w = Math.ceil( _thumb.width() / _thumb.height() * _container.height() );
					var h = Math.ceil( _thumb.height() / _thumb.width() * _container.width() );

					if ( w < h ) {
						_thumb.css({ height: 'auto', width: _container.width(), marginTop: -( h - _container.height())/2 });
					} else {
						_thumb.css({ width: 'auto', height: _container.height(), marginLeft: -(w - _container.width())/2 });
					}

				} else { // Center thumbnails.

					// a tiny timer fixed the width/height
					window.setTimeout( function() {
						_thumb.css({
							marginLeft: -( _thumb.width() - _container.width() )/2, 
							marginTop:	-( _thumb.height() - _container.height() )/2
						});
					}, 200 ); // incresed ticks ( 1ms => 200ms )
				}

				// add the rel attribute
				_thumb.attr('rel',_src);

				// add the title attribute
				_thumb.attr('title',_title);

				// add the click functionality to the _thumb
				_thumb.click( function() {
					//jQuery.galleria.activate( _src );
					// added 2nd argument : (stage ID)	 V1.1  5/11 2008
					//       3rd argument : V1.2 5/30 2008
					jQuery.galleria.activate( _src, _insert.attr('id'), $options.tempClass );
				});

				// hover classes for IE6
				_thumb.hover(
					function() { jQuery(this).addClass('hover'); },
					function() { jQuery(this).removeClass('hover'); }
				);
				_container.hover(
					function() { _container.addClass('hover'); },
					function() { _container.removeClass('hover'); }
				);

				// prepend the thumbnail in the container
				_container.prepend( _thumb );

				// show the thumbnail
				_thumb.css( 'display','block' );

				// call the onThumb function
				_o.onThumb( jQuery(_thumb) );

				// check active class and activate image if match
				if ( _container.hasClass('active') ) {
					//jQuery.galleria.activate( _src );
					// added 2nd argument : (stage ID)	 V1.1  5/11 2008
					jQuery.galleria.activate( _src, _insert.attr('id'), $options.tempClass );
					//_span.text(_title);
				}

				//-----------------------------------------------------------------

				// finally delete the original image
				_img.remove();

			}).error(function () {
				// Error handling
				_container.html('<span class="error" style="color:red">Error loading image: '+_src+'</span>');

			}).attr('src', _src);

		}); // end of [ jQuery(this).children('li').each( function( i ) {} ]

	}); // end of [ this.each( function(){} ]
};

/**************************************************************************************/

/**
 *
 * @name NextSelector
 *
 * @desc Returns the sibling sibling, or the first one
 *
**/

galleria.nextSelector = function(selector) {
	return jQuery(selector).is(':last-child') ?
		   jQuery(selector).siblings(':first-child') :
		   jQuery(selector).next();
		   
};

/**
 *
 * @name previousSelector
 *
 * @desc Returns the previous sibling, or the last one
 *
**/

galleria.previousSelector = function(selector) {
	return jQuery(selector).is(':first-child') ?
		   jQuery(selector).siblings(':last-child') :
		   jQuery(selector).prev();
		   
};

/**
 *
 * @name hasCSS
 *
 * @desc Checks for CSS support and returns a boolean value
 *
**/

galleria.hasCSS = function()  {
	jQuery('body').append(
		jQuery(document.createElement('div')).attr('id','css_test')
		.css({ width:'1px', height:'1px', display:'none' })
	);
	var _v = (jQuery('#css_test').width() != 1) ? false : true;
	jQuery('#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 jQuery.historyInit();
 * 2. after calling jQuery.historyLoad();
 * 3. after pushing "Go Back" button of a browser
 *
**/

//galleria.onPageLoad = function( _src ) {
galleria.onPageLoad = function( _src, _target_id, _temp_class ) {

	// get the thumbnail caption
	var _thumb_caption = jQuery('span.' + _temp_class );
	
	// get the wrapper
	//var _wrapper = jQuery( '.galleria_wrapper' );
	var _wrapper = jQuery('#' + _target_id + ' div.galleria_wrapper' ); 
	
	// get the thumb
	//var _thumb = jQuery('.galleria img[@rel="'+_src+'"]');
	var _thumb = jQuery('ul.' + _temp_class + '  img[@rel="'+_src+'"]');
	
	if ( _src ) {

		// new hash location
		//if (jQuery.galleria.history) {
		//	window.location = window.location.href.replace(/\#.*/,'') + '#' + _src;
		//}

		// alter the active classes
		_thumb.parents('li').siblings('.active').removeClass('active');
		_thumb.parents('li').addClass('active');

		// define a new image
		var _img   = jQuery( new Image() ).attr('src',_src).addClass('replaced ' + _temp_class );

		// copy thumbnail's alt attribute to main image
		_img.attr('alt', _thumb.attr('title') );

		// search "active" class item
		var image_number = 0;
		var image_number_text = "";

		_thumb.parents('li').parents('ul').children('li').each( function() {
			image_number++; 
			if ( jQuery(this).hasClass('active') ) {
				image_number_text = image_number + " / " + numOfListItems[ _temp_class];
			}
		});
		
		//var	 image_width  = _img.attr('width');  // <=== Opera returns illegal values why?
		//var	 image_height = _img.attr('height'); // <===  
		var	 image_width  = _img.attr('width');  // alternative method (6/03 2008 )
		var	 image_height = _img.attr('height'); //

		var	 wrapper_width = _wrapper.width();
		var	 wrapper_height = _wrapper.height();
		
		// empty the wrapper and insert the new image
		//_wrapper.empty().append( _img );
		_wrapper.empty().siblings('.caption0').text(image_number_text).append( _img );

		// shrink image (V1.0.3 May 09 2008)
		if ( shrink == 1 ) {
			// shrink mode
			if ( wrapper_width < image_width ) {
				image_height = Math.round( (wrapper_width / image_width) * image_height + 0.1 );
				image_width	 = wrapper_width;
				
				//alert( "New  image W : " + image_width + "  image H : " + image_height );
				_img.width(image_width);
				_img.height(image_height);
			}
		}

		// insert the caption
		//_wrapper.siblings('.caption').text(_thumb.attr('title'));

		// fire the onImage function to customize the loaded image's features
		//jQuery.galleria.onImage(_img,_wrapper.siblings('.caption'),_thumb);

		//*********************************************************************//
		//** divide title text into caption and EXIF meta datas		  by Y2	  *//
		//*********************************************************************//
		var captionText ="";
		
		if ( _thumb.attr('title') ) {
			captionText = _thumb.attr('title').split("::");
		}
		
		if ( captionText[0] != null ) {
			_wrapper.siblings('.caption1').text(captionText[0]);
		} else {
			_wrapper.siblings('.caption1').text('');
		}
		
		if ( captionText[2] != null ) {
			captionText[1] += captionText[2]; // 5/13 2008 
		}
		
		_wrapper.siblings('.caption2').text(captionText[1]);

		// fade out the thumbnail caption
		_thumb_caption.fadeTo(10000,0.0);

		// fire the onImage function to customize the loaded image's features
		jQuery.galleria.onImage( _img,
								 _wrapper.siblings('.caption1'),
								 _wrapper.siblings('.caption2'),
								 _thumb );

		// add clickable image helper
		if(jQuery.galleria.clickNext) {
			//_img.css('cursor','pointer').click( function() { jQuery.galleria.next(); })
			_img.css('cursor','pointer').click( function() {
				jQuery.galleria.next( _target_id, _temp_class );
			});
		}

	} else { // else of [ if ( _src ) ]

		// clean up the container if none are active
		_wrapper.siblings().andSelf().empty();

		// remove active classes
		//jQuery('.galleria li.active').removeClass('active');
		jQuery('ul.' + _temp_class + ' li.active').removeClass('active');

	}  // end of [ if ( _src ) ]

	// place the source in the galleria.current variable
	//jQuery.galleria.current = _src;
	jQuery.galleria.current[_target_id] = _src;

}

/**
 *
 * @name jQuery.galleria
 *
 * @desc The global galleria object holds four constant variables and four public methods:
 *		 jQuery.galleria.history = a boolean for setting the history object in action with named URLs
 *		 jQuery.galleria.current = is the current source that's being viewed.
 *		 jQuery.galleria.clickNext = boolean helper for adding a clickable image that leads to the next one in line
 *		 jQuery.galleria.next() = displays the next image in line, returns to first image after the last.
 *		 jQuery.galleria.prev() = displays the previous image in line, returns to last image after the first.
 *		 jQuery.galleria.activate(_src) = displays an image from _src in the galleria container.
 *		 jQuery.galleria.onImage(image,caption) = gets fired when the image is displayed.
 *
**/

jQuery.extend( { 

	galleria : {

		//current : '',
		current : new Array(),

		onImage : function(){
		},
		
		onThumb : function(){
		},

		//activate : function( _src ) {
		activate : function( _src, _target_id, _tmp_class ) {

			galleria.onPageLoad( _src, _target_id, _tmp_class );

			//=========================================================//
			//			for jCarousel thumbnail scroll
			//=========================================================//
			if ( usejcarousel ) {
				jcarousel_scroll_to_active_item( _tmp_class );
			}
			//=========================================================//
		},

		//next : function() {
		next : function( _target_id, _tmp_class ) {
		
			//var _next_src = jQuery(galleria.nextSelector(jQuery('.galleria' img[@rel="'+jQuery.galleria.current+'"]').parents('li'))).find('img').attr('rel');

			var _next_src = jQuery( galleria.nextSelector( jQuery( '.galleria img[@rel="'+jQuery.galleria.current[_target_id]+'"]').parents('li'))).find('img').attr('rel');

			//jQuery.galleria.activate( _next_src );
			jQuery.galleria.activate( _next_src, _target_id, _tmp_class );
		},

		//prev : function() {
		prev : function( _target_id, _tmp_class ) {

			//var _prev_src = jQuery(galleria.previousSelector(jQuery('.galleria	img[@rel="'+jQuery.galleria.current+'"]').parents('li'))).find('img').attr('rel');

			var _prev_src = jQuery( galleria.previousSelector( jQuery( '.galleria img[@rel="'+jQuery.galleria.current[_target_id]+'"]').parents('li'))).find('img').attr('rel');

			//jQuery.galleria.activate( _prev_src );
			jQuery.galleria.activate( _prev_src, _target_id, _tmp_class );
		}
	}

});

})(jQuery);
