/**
 * 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) {
	
	// check for basic CSS support
	if (!$$.hasCSS()) { return false; }
	
	// set default options
	var $defaults = {
		//insert      : '.galleria_container',
		clickNext   : true,
		onImage     : function(image,caption,thumb) {
				// fade in the image & caption
				if(! ($.browser.mozilla && navigator.appVersion.indexOf("Win")!=-1) ) { // FF/Win fades large images terribly slow
					image.css('display','none').fadeIn(1000);
				  caption.css('display','none').fadeIn(1000);
				}
				
				// fetch the thumbnail container
				var _image_div = thumb.parent();
				
				// fade out inactive thumbnail
				_image_div.siblings().children('img.selected').fadeTo(500,0.5);
				
				// fade in active thumbnail
				thumb.fadeTo('fast',1).addClass('selected');
				
				// add a title for the clickable image
				image.attr('title','Next image >>');
    },

		onThumb     : function(thumb) {
			var _image_div = thumb.parent();
			var _fadeTo = _image_div.is('.active') ? '1' : '0.5';
			thumb.css({display:'none',opacity:_fadeTo}).fadeIn(1500);
			thumb.hover(
				function() { thumb.fadeTo('fast',1); },
				function() {
					_image_div.not('.active').children('img').fadeTo('fast',0.5);
				}
			)
		}
	};
	

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

  // --------------------------------------------------------------------------
  //
  // Build the section that holds the thumbnails and thumbnail page navigation
  //
  //
  // --------------------------------------------------------------------------

  // create div to hold left and right arrows for page scrolling
	var _gal_scroll = $(document.createElement('div'));
  _gal_scroll.addClass('nav');

  var _back_arrow = $(document.createElement('img')).addClass('prev_arrow');
  _back_arrow.attr({
    src: '/graphics/icons/arrow-fast-reverse-rewind.gif',
    title: '<< Previous page'
  });
  _gal_scroll.append(_back_arrow);
	_back_arrow.css('cursor','pointer').click(function() { 
		$.galleria.prevPage();
	});

  var _pg_span = $(document.createElement('span')).addClass('pg_cnt');
  _gal_scroll.append(_pg_span);

  var _fwd_arrow = $(document.createElement('img')).addClass('next_arrow');
  _fwd_arrow.attr({
    src: '/graphics/icons/arrow-fast-forward.gif',
    title: 'Next page >>'
  });
  _gal_scroll.append(_fwd_arrow);
	_fwd_arrow.css('cursor','pointer').click(function() { 
    $.galleria.nextPage();
	});

  $(this).prepend(_gal_scroll);

  var _gallery_thumbs = $(document.createElement('div'));
  _gallery_thumbs.addClass('gallery_thumbs');
	$(this).children(".image").wrapAll(_gallery_thumbs);

  var _thumb_wrapper = $(document.createElement('div'));
  _thumb_wrapper.addClass('thumb_wrapper');
	$(this).children().wrapAll(_thumb_wrapper);


  // --------------------------------------------------------------------------
  //
  // Build the section that holds the enlarged image, caption, and individual
  // image navigation bar
  //
  // --------------------------------------------------------------------------

	var _image_div = $(document.createElement('div')).addClass('image');


  var _nav_div = $(document.createElement('div')).addClass('nav');

  var _prev_arrow = $(document.createElement('img'));
  _prev_arrow.attr({
    src: '/graphics/icons/arrow-left.gif',
		title: '<< Previous image'
  });
	_prev_arrow.css('cursor','pointer').click(function() { $.galleria.prev(); })

  var _img_span = $(document.createElement('span')).addClass('image_cnt');

  var _next_arrow = $(document.createElement('img'));
  _next_arrow.attr({
    src: '/graphics/icons/arrow-right.gif',
		title: 'Next image >>'
  });
	_next_arrow.css('cursor','pointer').click(function() { $.galleria.next(); });

  _nav_div.append(_prev_arrow).append(_img_span).append(_next_arrow);
	
	var _caption = $(document.createElement('div')).addClass('caption');

  var _gallery_image_big = $(document.createElement('div'));
  this.append(_gallery_image_big);
	_gallery_image_big.addClass('gallery_image_big').append(_nav_div).append(_image_div).append(_caption);
	
	//-------------

	return this.find(".gallery_thumbs").each(function(){
		// loop through list
		$(this).children('.image').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').is('a') ? $(this).find('a') : false;
			
			// reference the original image as a variable, save some attributes as 
			// variables, and then hide it
			var _img = $(this).children('img');
      var _img_height = _img.height();
      var _img_width = _img.width();
			_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();
			
      if (_container.prevAll().length == 0) {
				_container.siblings('.active').removeClass('active');
				_container.addClass('active');
			}
		
			// begin loader
			$(_loader).load(function () {
				
				// try to bring the alt
				$(this).attr('alt',_img.attr('alt'));
				
				//-----------------------------------------------------------------
				// the image is loaded, let's create the thumbnail
				
				var _thumb = _a ? 
					_a.find('img').addClass('thumb noscale').css('display','none') :
					_img.clone(true).addClass('thumb').css('display','none');
				
				if (_a) { _a.replaceWith(_thumb); }
				
				if (!_thumb.hasClass('noscale')) { // scaled thumbnails!
					if (_img_width < _img_height) {
            var _proportional_width = _container.height() / _img_height *
                                      _img_width;
						var _margin = (_container.width() - _proportional_width) / 2;
						_thumb.css({ 
            	marginLeft: _margin,
							height: _container.height(), 
							width: 'auto'
						});
					} else {
            var _proportional_height = _container.width() / _img_width *
                                      _img_height;
						var _margin = (_container.height() - _proportional_height) / 2;
						_thumb.css({ 
							marginTop:  _margin,
							width: _container.width(), 
							height: 'auto' 
						});
					}
				}
				
				// 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() {
					$.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'); }
				);

				// 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
				_img.remove();
				
			}).error(function () {
				
				// Error handling
			    _container.html('<span class="error" style="color:red">Error loading image: '+_src+'</span>');
			
			}).attr('src', _src);
		});
	});
};

/**
 *
 * @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();
    	   
};

$$.prevPageFirstThumb = function() {
  return ($$.pageFirstThumb() - $.galleria.pageSize);
}

$$.nextPageFirstThumb = function() {
  return ($$.pageFirstThumb() + $.galleria.pageSize);
}

$$.lastPageFirstThumb = function() {
  return (($$.pageCount() - 1) * $.galleria.pageSize);
}

$$.pageCount = function() {
  return ($(".thumb_wrapper").find(".gallery_thumbs").children().length() / $.galleria.pageSize);
}

$$.pageFirstThumb = function() {
  return $(".thumb_wrapper").find(".gallery_thumbs").children(".page_top").prevAll().length;
}

$$.currPage = function() {
  return (($$.pageFirstThumb() + $.galleria.pageSize) / $.galleria.pageSize);
}

$$.pageCount = function() {
  return Math.ceil($(".thumb_wrapper").find(".gallery_thumbs").children('.image').length / $.galleria.pageSize);
}

/**
 *
 * @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:
 * 3. after pushing "Go Back" button of a browser
 *
**/

$$.onPageLoad = function(_src) {	
	
	// get the wrapper
	var _wrapper = $('.gallery_image_big .image');
	
	// get the thumb
	var _thumb = $('.gallery_thumbs img[@rel="'+_src+'"]');

  // get the image count span
  var _cnt_span = $('.image_cnt');
	
	if (_src) {

    // Build image count string
    var _curr_index = _thumb.parent().prevAll().length + 1;
    var _img_cnt = _thumb.parent().siblings().length + 1;
    _cnt_span.text('Image ' + _curr_index + ' of ' + _img_cnt);
		
		// alter the active classes
		_thumb.parents('.image').siblings('.active').removeClass('active');
		_thumb.parents('.image').addClass('active');
	
		// define a new image
		var _img   = $(new Image()).attr('src',_src).addClass('replaced');

		// empty the wrapper and insert the new image
		_wrapper.empty().append(_img);

		// insert the caption text
    var _text = _thumb.attr('title') ? _thumb.attr('title') : '';
		_wrapper.siblings('.caption').text(_text);
		
		// fire the onImage function to customize the loaded image's features
		$.galleria.onImage(_img,_wrapper.siblings('.caption'),_thumb);
		
		// add clickable image helper
		if($.galleria.clickNext) {
			_img.css('cursor','pointer').click(function() { $.galleria.next(); })
		}
		
	} else {
		
		// clean up the container if none are active
		_wrapper.siblings().andSelf().empty();
		
		// remove active classes
		$('.gallery_thumbs div.active').removeClass('active');
	}

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

  //
  // Get index of first image currently being displayed in gallery, pass to
  // function that displays the gallery
  //
  var firstVisible = ($(".gallery_thumbs").children().is(".page_top"))
                   ? $$.pageFirstThumb()
                   : 0;
  if ( _curr_index == 1) {
    firstVisible = 0;
  } else if ( _curr_index == _img_cnt) {
    firstVisible = $$.lastPageFirstThumb();
  } else if ( _curr_index > firstVisible + $.galleria.pageSize) {
    firstVisible = $$.nextPageFirstThumb();
  } else if ( _curr_index <= firstVisible) {
    firstVisible = $$.prevPageFirstThumb();
  }
  $$.loadGallery(firstVisible);	
}

$$.loadGallery = function(firstVisible) {	
  var lastVisible = firstVisible + $.galleria.pageSize;

  var cnt = 0;
	$(".gallery_thumbs").children('.image').each(function() {
    if (cnt == firstVisible)  {
			$(this).addClass('page_top');
    } else if ($(this).hasClass('page_top')) {
			$(this).removeClass('page_top');
		}
		if (cnt < firstVisible || cnt >= lastVisible) {
			$(this).css('display','none');
    } else {
			$(this).css('display','block');
    }
    cnt++;
	});

  var currPage = $$.currPage();
  var pageCount = $$.pageCount();
  var _pg_span = $('.pg_cnt');
  _pg_span.text(currPage + "/" + pageCount);

  var prevArrow = $(".prev_arrow");
  if (currPage == 1) {
    prevArrow.hide();
  } else {
    prevArrow.show();
  }

  var nextArrow = $(".next_arrow");
  if (currPage == pageCount) {
    nextArrow.hide();
  } else {
    nextArrow.show();
  }
}


/**
 *
 * @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) { 
	  $$.onPageLoad(_src);
	},
	next : function() {
		var _next = $($$.nextSelector($('.gallery_thumbs img[@rel="'+$.galleria.current+'"]').parents('.image'))).find('img').attr('rel');
		$.galleria.activate(_next);
	},
	prev : function() {
		var _prev = $($$.previousSelector($('.gallery_thumbs img[@rel="'+$.galleria.current+'"]').parents('.image'))).find('img').attr('rel');
		$.galleria.activate(_prev);
	},
  nextPage : function() {
    $$.loadGallery($$.nextPageFirstThumb());
  },
  prevPage : function() {
    $$.loadGallery($$.prevPageFirstThumb());
  },
  pageSize : 7
}
});

})(jQuery);
