/**
 * Mediabox Plugin coded for LTB by H2G Internetagentur, 5000 Aarau
 *
 * jQuery Mediabox Plugin to control the headbanner elements inside
 * main layout. This version of the plugin is only able to handle
 * image elements but not any media streams. The use of the plugin is
 * divided up in the following script source files (to be included):
 *
 * - jquery.mediabox.js
 * - jquery.mediabox.controls.js
 * - jquery.mediabox.display.js
 *
 * Use of the plugin as provided inside HTML should be easy as plugin
 * only expects an absolute positioned div having the classname .tube.
 * Images contained inside will be parsed and processed by the plugin
 * accordingly.
 *
 * <div class="mediabox"><div class="tube"></div></div>
 *
 * @author michael.kuck@h2g.ch
 * @version v1.00 18-11-2010
 */
(function($) {
	
	var mediabox = {
		launcher: {
			label: false,
			init: function(box) {
				
				// globalize plugin defaults
				var o = $.fn.mediabox.defaults;
				
				// set reference to big cinema image
				var ref = $(box).find('.tube a').first().attr('href');
				
				// set label element with description
				this.label = $("<p></p>").html($(box).find('.tube a').first().attr('rel'));
				
				// create launcher element layer
				var div = $("<div></div>").addClass('launcher')
					.append($("<a></a>").attr({'href':ref})
					.append($("<img />").attr({
						'src': o.basepath+o.icons['launcher']['src'],
						'width': o.icons['launcher']['width'],
						'height': o.icons['launcher']['height'],
						'alt': ''
					}))).append(this.label);
					
				// adding onclick event to launch cinema display
				$(div).bind('click', function() {
					display.init($(this).find('a').attr('href'), box, o);
					return false;
				});
				
				// adding launcher to media container
				$(box).append(this.observe(box, div));
			},
			observe: function(box,launcher) {
				
				// observe mouseenter/mouseout events
				$(box).find('.observer').bind('mouseenter', function() {
					$(launcher).stop(true,true).animate({
						'top':'136px'
					}, 600, 'easeOutCubic', function() { });
				}).parent().bind('mouseleave', function() {
					$(launcher).stop(true,true).animate({
						'top':'200px'
					}, 600, 'easeInCubic', function() { });
				});
								
				// return launcher element
				return $(launcher);
			},
			update: function(label) {
				
				// referencing current slide
				var slide = $($.fn.mediabox.defaults.mediabox).find('.tube').find('.current');
				
				// update big image reference url
				$(this.label).parent().find('a').attr({
					'href':$(slide).attr('href')
				});
				
				// update label description text
				$(this.label).fadeOut('fast', function() {
					$(this).html(label); $(this).fadeIn('slow');
				});
				
			}
		},
		init: function(box,opts) {
			// show loader icon and init tube on callback
			loader.init(function() {
				
				// adding loader to mediabox container
				var loader = this; $(box).append(loader);
				
				// set first slide as current reference
				$(box).find('.tube a').first().addClass('current');
				
				// iterating anchor/image elements inside tube
				$(box).find('.tube a').each(function(i, e) {
					
					// disable on click event on anchor
					$(this).click(function() { return false; });
					
					// resize inner tube according to image size
					$(box).find('.tube').css({'width': function() {
						return ($(this).width() + $(e).find('img').width() + 10 + 'px');
					}});
					
					// try to preload images otherwise skip
					if ($.fn.mediabox.defaults.preload) {
						// preload image source and add to slide container
						$.fn.mediabox.preload($(e).find('img').attr('src'), function() {
							// remove loader icon if first image
							if (i == 0) { $(loader).remove(); }
							// fade in preloaded image now
							$(e).find('img').fadeIn('slow');
						});
					// skip preloading and display slides
					} else {
						$(box).find('.tube img').fadeIn('slow');
						$(loader).remove();
					}
				});
					
			});
			
			// return object
			return this;
		},
		position: function() {
			
			// setting position var to initial
			var position = 0;
			
			// set reference to mediabox carrier
			var box = $($.fn.mediabox.defaults.mediabox);
			
			$(box).find('.tube a').each(function() {
				if ($(this).hasClass('current')) { return false; }
				position += $(box).width();
			});
			
			return position;
		},
		next: function(callback) {
			if (this.hasNext()) {
				
				// requesting mediabox tube element
				var tube = $($.fn.mediabox.defaults.mediabox).find('.tube');
				
				// finding next slide element in tube
				var next = $(tube)
					.find('.current')
					.removeClass('current')
					.next('a')
					.addClass('current');
				
				// start animation sliding tube (negative direction)
				$(next).parent().animate({
					'left':'-'+this.position()+'px'
				}, 500, 'easeInOutQuint', function() {
					// updating launcher label and reference attribute
					mediabox.launcher.update($(next).attr('rel'));
					// execute callback function of controller
					if (typeof callback == "function")
						callback.call(this);
				});
				
			}
		},
		prev: function(callback) {
			if (this.hasPrev()) {
				
				// requesting mediabox tube element
				var tube = $($.fn.mediabox.defaults.mediabox).find('.tube');
				
				// finding previous slide element in tube
				var prev = $(tube)
					.find('.current')
					.removeClass('current')
					.prev('a')
					.addClass('current');
				
				// start animation sliding tube (positive direction)
				$(prev).parent().animate({
					'left':'-'+this.position()+'px'
				}, 500, 'easeInOutQuint', function() {
					// updating launcher label and reference attribute
					mediabox.launcher.update($(prev).attr('rel'));
					// execute callback function of controller
					if (typeof callback == "function")
						callback.call(this);
				});
				
			}
		},
		hasNext: function() {	return (!($($($.fn.mediabox.defaults.mediabox).find('.tube a').last()).hasClass('current')));	},
		hasPrev: function() {	return (!($($($.fn.mediabox.defaults.mediabox).find('.tube a').first()).hasClass('current'))); }
	}
	
	var loader = {
		init: function(callback) {
			var loader;
			// setting media box defaults
			var o = $.fn.mediabox.defaults;
			// preloading ajax loader icon graphic
			$.fn.mediabox.preload(o.basepath+o.icons['loader']['src'], function() {
				loader = $("<img />").attr({
					'src':o.basepath+o.icons['loader']['src'],
					'width':o.icons['loader']['width'],
					'height':o.icons['loader']['height'],
					'style':'position:absolute;top:50%;left:50%;'
				}).css({'display':'block'})
					.css({'margin-top':'-'+Math.round(parseInt(o.icons['loader']['height'])/2)+'px'})
					.css({'margin-left':'-'+Math.round(parseInt(o.icons['loader']['width'])/2)+'px'});
				$(loader).addClass('loader');
				if (typeof callback == "function")
					callback.call(loader);
			});
		}
	}
	
	// define cinemadisplay plugin
	$.fn.mediabox = function(options) {
		// build main options before initial procedure
		var opts = $.extend({}, $.fn.mediabox.defaults, options);
		// initialize cinemadisplay plugin
		return this.each(function() {
			var $this = $(this); var init = false;
			// build element specific options
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
			// setting class name reference to media box
			$.fn.mediabox.defaults.mediabox = '.'+$(this).attr('class');
			// randomly shuffle pictures inside mediabox
			$(this).find('.tube a').shuffle();
			// initialize mediabox object
			var m = mediabox.init(this,o);
			// setting up controller elements on media container
			controls.init(this,m);
			// initialize launcher element
			m.launcher.init(this);
			// enabling static cinema mode content launcher class
			$(document).find('a.cinemamode').each(function() {
				$(this).bind('click', function() {
					$($this).find('.launcher').trigger('click');
					return false;
				});
			});
		});
	};
	// callback function to preload image source
	$.fn.mediabox.preload = function(src, callback) {
		$("<img />").one('load', function() {
			if (typeof callback == "function")
				callback.call(this);
		}).attr({'src':src})
			.each(function() {
			// cache fix for browsers that don't trigger .load()
			if(this.complete) $(this).trigger('load');	
		});
	};
	$.fn.mediabox.next = function(callback) { mediabox.next(callback); }
	$.fn.mediabox.prev = function(callback) { mediabox.prev(callback); }
	$.fn.mediabox.hasNext = function() { return mediabox.hasNext(); }
	$.fn.mediabox.hasPrev = function() { return mediabox.hasPrev(); }
	$.fn.mediabox.controls = function() { controls.data = mediabox; }
	function debug($msg) {
		if (window.console && window.console.log)
			window.console.log('debug: '+$msg);
	}
	$.fn.mediabox.defaults = {
		mediabox: '',
		basepath: '/img/mediabox/',
		navigation: '/inc/navigation.php',
		preload: true,
		icons: {
			'loader': { 'src': 'ajax-loader.gif', 'width': '16', 'height': '16' },
			'cinemaloader': { 'src': 'cinema-loader.gif', 'width': '16', 'height': '16' },
			'launcher': { 'src': 'icon-launcher.png', 'width': '30', 'height': '30' },
			'closer': { 'src': 'icon-closer.png', 'width': '30', 'height': '30' },
			'prev': { 'src': 'icon-prev.png', 'width': '25', 'height': '45' },
			'next': { 'src': 'icon-next.png', 'width': '25', 'height': '45' },
			'empty': { 'src': 'empty.gif', 'width': '2', 'height': '2' }
		},
		overlay: {
			'cls': 'overlay',
			'opacity': '0.5',
			'speed': 500
		}
	}
})(jQuery);
