/**
 * 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) {

	if (!$$.hasCSS()) { return false; }
//	$.historyInit($$.onPageLoad);
	var $defaults = {
		insert      : '.galleria_container',
		history     : true,
		clickNext   : true,
		onImage     : function(image,caption,thumb) {},
		onThumb     : function(thumb) {},
	};
	
	var $opts = $.extend($defaults, $options);
	for (var i in $opts) {
		if (i) $.galleria[i]  = $opts[i];
	}


	
	// 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');

	
	// inject the wrapper in in the insert selector
	_insert.addClass('galleria_container').prepend(_div);
	
	//-------------
	
	return this.each(function(){
		$(this).addClass('galleria');
		$(this).children('li').each(function(i) {
			var _container = $(this);
			var _o = $.meta ? $.extend({}, $opts, _container.data()) : $opts;
			_o.clickNext = $(this).is(':only-child') ? false : _o.clickNext;
		//	var _atem = $(this).hasClass('malleria');
			var _a = $(this).find('a').is('a') ? $(this).find('a').hasClass('malleria') : false;
		//	var _a =  _atemp.hasClass('malleria');
			var _img = $(this).children('img').css('display','none');
			var _src = _a ? _a.attr('href') : _img.attr('src');
			var _title = _a ? _a.attr('title') : _img.attr('title');
      
			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
			$(_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 tumbnails!
					var w = Math.ceil( _img.width() / _img.height() * _container.height() );
					var h = Math.ceil( _img.height() / _img.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
						});
					}, 1);
				}
				
				// add the rel attribute
				_thumb.attr('rel',_src);
				_thumb.attr('title',_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'); }
				);

				_container.prepend(_thumb);
				_thumb.css('display','block');
				_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();
    	   
};

/**
 *
 * @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) {	
	var _wrapper = $('.galleria_wrapper');
	var _thumb = $('.galleria img[rel="'+_src+'"]');
	
	if (_src) {
		// new hash location
		if ($.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   = $(new Image()).attr('src',_src).addClass('replaced');
		
		// empty the wrapper and insert the new image
		_wrapper.empty().append(_img);
		_wrapper.siblings('.caption').text(_thumb.attr('title'));

		// screen pull content for each image (maybe the issue as not wrapped?
		var title = _thumb.attr('alt');
		var wpcontent = _thumb.parents('li').children('div.wpcontent').html();
		var exif = _thumb.parents('li').children('div.exif').html();
		var comments = _thumb.parents('li').children('div.wpcomments').html();
		var infoInject;
		
		if (title) infoInject = "<div id='maTitle'><h1>"+title+"<h1></div>";
		if (exif)  infoInject = infoInject+"<div id='maExif'>"+exif+"</div>";
		if (wpcontent) infoInject = infoInject+"<div id='maCaption'>"+wpcontent+"</div>";
		if (comments) infoInject =  infoInject+"<div id='maComments'>"+comments+"</div>";
		
		//inject information into output box
		$('#maInfoOut').html(infoInject);
		
		//define ajax comment submition
		$('form.wpCommentForm').submit(function() {
			var wpauthor = $('#author').attr('value');
			var wpemail = $('#email').attr('value'); 
			var wpwebsite = $('#url').attr('value');
			var wpcomment = $('#comment').attr('value');
			var wppost_id = $(this).find('#comment_post_ID').attr('value');
			var wpcomment_parent = $(this).find('#comment_parent').attr('value');
			var html_comment = $(this).find('#_wp_unfiltered_html_comment').attr('value');

			var submited = "author="+ wpauthor +"&email="+ wpemail+"&website="+ wpwebsite +"&comment="+wpcomment+"&comment_post_ID="+wppost_id+"&comment_parent="+wpcomment_parent+"&_wp_unfiltered_html_comment="+html_comment;
			
			$.ajax({
				type: "POST",
				url: "wp-comments-post.php",
				data: submited,
				success: function(){$('#maComments').load('wp-content/themes/slideblog/ajaxcomments.php',"ID="+wppost_id)},
//				success: function(comment) {$('#maComments').html(comment)},
				complete: function(){$('#respond').slideUp(50)},
			});
			return false;
		});
		
		if (!showComments) 	$('#commentSlide').hide();
		$('div#maComments h3#comments').click(function(){
			$('#commentSlide').slideToggle(20); 
			showComments = showComments ? false : true; 		
			clearInterval(slideShow); 
			$('.maPlay').find('a').removeClass('active');});
		$('textarea#comment').focus(function() { clearInterval(slideShow); $('.maPlay').find('a').removeClass('active'); });
		
		// 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
		$('.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) { 
		if ($.galleria.history) {
			$.historyLoad(_src);
		} else {
			$$.onPageLoad(_src);
		}
	},
	next : function() {
		var _next = $($$.nextSelector($('.galleria img[rel="'+$.galleria.current+'"]').parents('li'))).find('img').attr('rel');
		$.galleria.activate(_next);
	},
	prev : function() {
		var _prev = $($$.previousSelector($('.galleria img[rel="'+$.galleria.current+'"]').parents('li'))).find('img').attr('rel');
		$.galleria.activate(_prev);
	}
}
});

})(jQuery);

	
