/**
 * Version 1.0
 * Februari 21, 2008
 *
 * Copyright (c) 2008 David Hellsing (http://monc.se)
 * 
 * Version 2.1
 * October 27, 2008
 *
 * Modified by Arshinov Maxim (LaCoNix)
 * Licensed under the GPL licenses.
 * http://www.gnu.org/licenses/gpl.txt
 **/

;(function($){

var $$;


/**
 * 
 * @desc Convert images from a simple html tag 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) {
	
	// check for basic CSS support
	if (!$$.hasCSS()) { return false; }
	
	// set default options
	var $defaults = {
		insert      : '.galleria_container',
		clickNext   : true,
		onImage     : function(image,caption,thumb) {},
		onThumb     : function(thumb) {},
		childTag    : 'li'
	};
	
	var _mainWraper = $options.mainWrapper;		
	var _captionWrapper = $options.captionWrapper;	
	var _descriptionWrapper = $options.descriptionWrapper;	
	
	// extend the options
	var $opts = $.extend($defaults, $options);
	
	// bring the options to the galleria object
	for (var i in $opts) {
		$.galleria[i]  = $opts[i];
	}
	
	//alert('#' + $opts.insert );
	// if no insert selector, create a new division and insert it before the ul
	var _insert = $opts.insert ? 
		$('#' + $opts.insert) : 
		jQuery(document.createElement('div')).insertBefore(this);
		
	var _caption;
	var _wrapper = $(document.createElement('div'));
	var _replaced = $(document.createElement('div')).addClass('galleria_image');
	_wrapper.html(_replaced);
	
	if(_captionWrapper)
	{
		_caption = $('#' + _captionWrapper);
		$.fn.captionWrapper = _caption ;
	}
	else
	{
		_caption = $(document.createElement('div'));
		_replaced .html(_caption);
	}
	
	if(_descriptionWrapper)
	{
		$.fn.descriptionWrapper = $('#' + _descriptionWrapper);
	}
	
	_wrapper.addClass('galleria_wrapper')
	_caption.addClass('caption');
	_insert.addClass('galleria_container').append(_wrapper);
	$$.opts = $opts;
	//-------------
	var _result = this.each(function(){
		
		// add the Galleria class
		$(this).addClass('galleria');
		
		// loop through list
		$(this).children($$.opts.childTag).each(function(i) {
			
			// bring the scope
			var _container = $(this);
			                
			// build element specific options
			var _o = $.meta ? $.extend({}, $$.opts, _container.data()) : $$.opts;
			
			// remove the clickNext if image is only child
			_o.clickNext = $(this).is(':only-child') ? false : _o.clickNext;
			
			// try to fetch an anchor
			var _a = $(this).find('a');
			if( !_a.is('a') ){ return; }
			
			var _img = $(_a).find('img').attr('id', $(_a).attr('href'));
			var _src = _img.attr('id');
			 
			// 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');
			}
			*/
			// try to bring the alt
			$(this).attr('alt',_img.attr('alt'));
				
			var _thumb = _img.addClass('thumb noscale').css('display','');
			_thumb.attr('title',_a.find('img').attr('title'));
			_thumb.click(function() {
				$.galleria.activate(_src);
			});
				
			// hover classes for IE6
			_thumb.hover(
				function() { $(this).addClass('hover'); },
				function() { $(this).removeClass('hover'); }
			);
			_container.hover(
				function() { _container.addClass('hover'); },
				function() { _container.removeClass('hover'); }
			);
			
			_a.replaceWith(_thumb);
						// 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')) {
				$.galleria.activate(_src);
					//_span.text(_title);
			}
				
			//-----------------------------------------------------------------
				
			// finally delete the original image
		});
	});

	if (_result) {
		var _cHref =  window.location.href.match(/(.*)#/) ? window.location.href.replace(/(.*)#/, '') : '';
		_cHref = _cHref ? 'http://' + _cHref : $(this).find($$.opts.childTag).find('img').attr('id');
		//alert(_cHref);
		$.galleria.activate( _cHref);
	};
	return _result;
};

$$.loadedImages = new Array();
/**
 *
 * @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();
    	   
};

/**
 *
 * @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(_src) {	
	// get the wrapper
	var _wrapper = $('.galleria_wrapper');
	// get the thumb
	var _thumb = $('.galleria img[@id="'+_src+'"]');
	var imageLoadedFlag = false;

	if (_src) {
		// alter the active classes
		_thumb.parents($$.opts.childTag).siblings('.active').removeClass('active');
		_thumb.parents($$.opts.childTag).addClass('active');
		
		var i;
		var _img;
		
		if ( $$.loadedImages.length > 0) {
			for (i = 0; i < $$.loadedImages.length; i++) {
				if (_src == $$.loadedImages[i].src) {
					imageLoadedFlag = $$.loadedImages[i];
					break;
				}
			}
		}
		
		var imageLoaded = function(){
			var _replaced = _wrapper.find('.galleria_image');
			_replaced.animate(
				{ height: _img.attr('height') + 10 },
				500,
				'linear',
				function(){
					var _text = _thumb.attr('alt');
					if ($.fn.captionWrapper) {
						$.fn.captionWrapper.text(_text);
					}
					
					if(_thumb.attr('title')){
						if($.fn.descriptionWrapper){
							$.fn.descriptionWrapper.text(_thumb.attr('title'));
						}
						_text = _text ? _text + ' | ' + _thumb.attr('title') : _thumb.attr('title');
						
					}
					
					_replaced.empty().append(_img);
					
					if (!$.fn.captionWrapper && !$.fn.descriptionWrapper) {
						var _caption = $(document.createElement('div')).addClass('caption').text(_text);
						_replaced.append(_caption);
					}
					
					$.galleria.onImage(_img, _replaced.find('.caption'),_thumb);
						
					// add clickable image helper
					if ($.galleria.clickNext) {
						_img.css('cursor', 'pointer').click(function(){
							$.galleria.next();
						});
					}
					
					window.location.href = window.location.href.replace(/#(.*)/, '') + '#' + _src.replace('http://', '');
				});
		};

	
		// define a new image
		if(!imageLoadedFlag){
			var _div = _wrapper.find('.galleria_image');
			if(_div.find('img').is('img')){
				var _innerDiv = $(document.createElement('div')).
					css('height', _div.find('img').attr('height')).
					html('Подождите, идет загрузка...');
					
				_div.html(_innerDiv);
			}
			
			var img = new Image();
			_img = $(img).addClass('replaced');
			
			img.src = _src;
			img.onload = function(){imageLoaded(); $$.loadedImages.push(img);}
			
		}else{
			img = imageLoadedFlag;
			_img   = $(img).addClass('replaced');
			imageLoaded();
		}
		
		
		//_img = $(document.createElement('img')).attr('src', _src).addClass('replaced');
	} else {
		
		// clean up the container if none are active
		_wrapper.siblings().andSelf().empty();
		
		// remove active classes
		$('.galleria li.active').removeClass('active');
	}

	// place the source in the galleria.current variable
	$.galleria.current = _src;
	
}

/**
 *
 * @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(_src) {
		//alert(_src); 
		$$.onPageLoad(_src);
	},
	next : function() {
		var _next = $($$.nextSelector($('.galleria img[@id="'+$.galleria.current+'"]').parents($$.opts.childTag))).find('img').attr('id');
		if(_next)
			$.galleria.activate(_next);
	},
	prev : function() {
		var _prev = $($$.previousSelector($('.galleria img[@id="'+$.galleria.current+'"]').parents($$.opts.childTag))).find('img').attr('id');
		if(_prev)
			$.galleria.activate(_prev);
	}
}
});

})(jQuery);