/**
 * jQuery Fotoviewer plugin written for michaelorlik.ch.
 *
 * @author michael.kuck@h2g.ch
 * @version v1.00 28-05-2010
 *
 */
(function($) {
	// set global options default var
	var o = false;
	// set reference to glider object
	var g = false;
	// set up glider object reference
	var Glider = function(g) {
		// setting up glider member
		this.obj = g,
		this.posx = 0,
		this.width = 0,
		this.offset = 0,
		this.active = '',
		this.imgs = new Object(),
		this.resetPos = function() {
			this.posx = 0;
			this.offset = 0;
		},
		this.add = function(i) {
			var $this = this;
			// calculating image width size
			this.width += parseInt($(i).attr('width'));
			// adding image reference to container
			this.imgs[$(i).attr('id')] = i;
		},
		this.get = function(id) {
			if (this.imgs[id]) {
				return this.imgs[id];
			} else { throw false; }
		},
		this.animate = function() {
			var $this = this;
			$(this.obj).animate({'left':(0-(this.posx-this.offset))+'px'},
				o.speed, o.easing, function() {
					try {
						// resize controls and highlight current image
						var w = $($this.get($this.active)).width();
						$.fn.fotoviewer.resizecontrols(w, function() {
							$($this.get($this.active)).fadeTo('fast',
								o.opacity['active'], function() {});
						});
					} catch (e) {	}
				}
			);
		}
	}
	// define the fotoviewer plugin
	$.fn.fotoviewer = function(options) {
		// build main options before initial procedure
		var opts = $.extend({}, $.fn.fotoviewer.defaults, options);
		// initialize image glider
		return this.each(function() {
			var $this = $(this);
			// build element specific options
			o = $.meta ? $.extend({}, opts, $this.data()) : opts;
			// initialize control button list
			var controls = $('<ul></ul>')
				.addClass(o.classes['controls']);
			$(o.controlBox).append(controls);
			// initialize glider instance
			g = new Glider($(this).find('.glider'));
			g.size = $(g.obj).find('img').size();
			// iterating image located in glider container
			$(this).find('.glider img').each(function() {
				// fade down opacity of current image
				$(this).fadeTo('fast', o.opacity['passive'], function() {});
				// building control button field
				var c = $.fn.fotoviewer.getcontrol($(this).attr('id'));
				// applying control button to control frame
				$(controls).append(c);
				// register image reference to glider object
				g.add(this);
				// set preselected control object to glider
				if ($(this).hasClass(o.imgDefault))
					$(c).find('a').trigger('click');
				// center controls at start to default image
				if ($(this).hasClass(o.imgDefault))
					$.fn.fotoviewer.resizecontrols($(this).width(), null, true);
			});
			// set glider box width to fit layout
			$(this).find('.glider').css({'width':((g.width+100)+'px')});
			// bind window resize event
			$(window).resize(function() {
				$.fn.fotoviewer.centercontrols($(o.controlBox).width());
				// repositioning glider
				g.offset = $.fn.fotoviewer.getoffset($(o.controlBox).width());
				$($this).find('.glider').css({
					'left':(0-(g.posx-g.offset))+'px'
				});
			});
		});
	};
	$.fn.fotoviewer.slideTo = function(id) {
		// fade out current active image
		try {
			$(g.get(g.active)).fadeTo('fast', o.opacity['passive'], function() {});
		} catch (e) { }
		// reset glider and prepare animation
		var pos = 0; g.resetPos(); g.active = id;
		// iterating each img in glider and calculate position
		$(g.obj).find('img').each(function(i,obj) {
			if ($(obj).attr('id') == id) {
				// getting image offset width from left window border
				g.offset = $.fn.fotoviewer.getoffset($(this).width());
				// set position and animate glider
				g.posx = (pos); g.animate();
			} else {
				// adding current image width to pos
				pos += parseInt($(obj).attr('width'));
			}
		});
	};
	$.fn.fotoviewer.getoffset = function(w) {
		return Math.round(($(document).width()-w)/2);
	};
	$.fn.fotoviewer.centercontrols = function(w) {
		var offset = $.fn.fotoviewer.getoffset(w);
		// set control box to width given
		$(o.controlBox).css({'width':w+'px'});
		$(o.controlBox).css({'left':offset+'px'});
		$(o.shortcutBox).find('ul').css({'padding-left':offset+'px'});
	};
	$.fn.fotoviewer.resizecontrols = function(w,c,force) {
		if ($(o.controlBox).width() != w || force == true) {
			// applying control box min width limits
			w = (w >= this.getminwidth() ? w : this.getminwidth());
			// engage animation effects to control frame
			$(o.controlBox).animate({width:w},
			{
				duration: 500,
				step: function() {
					// centering control frame on each step
					$.fn.fotoviewer.centercontrols(
						$(o.controlBox).width());
				},
				complete: function() {
					// execute callback after animation stop
					if (typeof c == 'function')
						c.call(this);
				}
			});
		} else {
			// ececute callback immediately
			if (typeof c == 'function')
				c.call(this);
		}
	}
    $.fn.fotoviewer.getminwidth = function(){
        var minwidth =  g.size * o.control.width;
        minwidth += o.control['padding'] * (g.size - 1);
        minwidth += o.control['logo-width'] * 1;
        return minwidth;
    }
	$.fn.fotoviewer.getcontrol = function(id) {
		// create control anchor
		var c = $('<a></a>').attr({'href':id}).append(
			$('<img />').attr({
				'src': o.control['src-off'],
				'width': o.control['width'],
				'height': o.control['height'],
				'alt': ''
			})
		);
		// adding mouseover effects
		$(c).find('img').mouseover(function() {
			if (!$(this).hasClass(o.classes['active']))
				$(this).attr({'src':o.control['src-on']});
		});
		$(c).find('img').mouseout(function() {
			if (!$(this).hasClass(o.classes['active']))
				$(this).attr({'src':o.control['src-off']});
		});
		// adding click event to control glider
		$(c).click(function() {
			// disabling all controls
			$('ul.'+o.classes['controls']).find('img')
				.attr({'src':o.control['src-off']});
			$('ul.'+o.classes['controls']).find('img')
				.removeClass(o.classes['active']);
			// activating current control
			$(this).find('img').attr({'src':o.control['src-on']});
			$(this).find('img').addClass(o.classes['active']);
			// enabling slide animation
			$.fn.fotoviewer.slideTo($(this).attr('href'));
			return false;
		});
		// return control listelement
		return $('<li></li>').append(c);
	};
	function debug($msg) {
		if (window.console && window.console.log)
			window.console.log('debug: ' + $msg);
	}
	$.fn.fotoviewer.defaults = {
		imgDefault: 'preselected',
		easing: 'easeInOutQuint',
		speed: 1440,
		shortcutBox: '#shortcut',
		preloaderBox: '#viewer .loader',
		controlBox: '#control .frame',
		control: {
			'src-off': 'img/button_off.png',
			'src-on': 'img/button_on.png',
			'width': '26',
            'height': '26',
            'padding': '4',
			'logo-width': '265'
		},
		classes: {
			'controls': 'controls',
			'active': 'active'
		},
		opacity: {
			'active': 1,
			'passive': 0.2
		}
	}
})(jQuery);
