/**
 * jQuery Lightbox Plugin (balupton edition) - Lightboxes for jQuery
 * Copyright (C) 2008 Benjamin Arthur Lupton
 * http://jquery.com/plugins/project/jquerylightbox_bal
 *
 * This file is part of jQuery Lightbox (balupton edition).
 *
 * jQuery Lightbox (balupton edition) is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * jQuery Lightbox (balupton edition) is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with jQuery Lightbox (balupton edition).  If not, see <http://www.gnu.org/licenses/>.
 *
 * @name jquery_lightbox: jquery.lightbox.js
 * @package jQuery Lightbox Plugin (balupton edition)
 * @version 1.3.4-final
 * @date September 12, 2008
 * @category jQuery plugin
 * @author Benjamin "balupton" Lupton {@link http://www.balupton.com}
 * @copyright (c) 2008 Benjamin Arthur Lupton {@link http://www.balupton.com}
 * @license GNU Affero General Public License - {@link http://www.gnu.org/licenses/agpl.html}
 * @example Visit {@link http://jquery.com/plugins/project/jquerylightbox_bal} for more information.
 */
// Plugin kezdete
(function($) {

	// Debug
	$.log = $.log || function ( options )
	{
		var con = null;
		if ( typeof console !== 'undefined' && typeof $.log !== 'undefined' )
		{	con = console;	}
		else if ( typeof window.console !== 'undefined' && typeof window.$.log !== 'undefined')
		{	con = window.console;	}

		if ( con )
		{
			if ( typeof arguments !== 'undefined' && arguments.length > 1)
			{	con.log(arguments);	return arguments;	}
			else
			{	con.log(options);	return options;}
		}
	};

	// Declare our class
	$.cbsBoxClass = function (options )
	{	// This is the handler for our constructor
		this.construct(options);
	};
	//adott elemen bellüli képek inicializálása
	$.fn.cbsbox = function ( options )
	{
		// elem megszerzése
		var group = $(this);
		$.cbsBox = $.cbsBox || new $.cbsBoxClass(options);
		//nem inicializáljuk egyből, csak klikkelés esetén....
		$(group).unbind().click(function(){

			var obj = $(this);
			// inicislizálás
			
			if ( !$.cbsBox.init($(obj)[0], group) )
			{	return false;	}
			// renderelés
			if ( !$.cbsBox.start() )
			{	return false;	}

			return false;
		});
		// Add style
		$(group).addClass('cbsbox-enabled');

		// And chain
		return this;
	};

	// Define our class
	$.extend($.cbsBoxClass.prototype,
	{	// Our cbsbox definition

		// -----------------
		// Everyting to do with images

		images: {

			// -----------------
			// Variables

			// Our array of images
			list:[], /* [ {
				src: 'url to image',
				link: 'a link to a page',
				title: 'title of the image',
				name: 'name of the image',
				description: 'description of the image',
				type: 'imgae, html',
				open: 'div,iframe',
				width: '', //html width
				height: '' //html height
			} ], */

			// The current active image
			image: false,

			// -----------------
			// Functions

			prev: function ( image )
			{	// Get previous image

				// Get previous from current?
				if ( typeof image === 'undefined' )
				{	image = this.active();
					if ( !image ) { return image; }
				}

				// Is there a previous?
				if ( this.first(image) )
				{	return false;	}

				// Get the previous
				return this.get(image.index-1);
			},

			next: function ( image )
			{	// Get next image

				// Get next from current?
				if ( typeof image === 'undefined' )
				{	image = this.active();
					if ( !image ) { return image; }
				}

				// Is there a next?
				if ( this.last(image) )
				{	return false;	}

				// Get the next
				return this.get(image.index+1);
			},

			first: function ( image )
			{	//
				// Get the first image?
				if ( typeof image === 'undefined' )
				{	return this.get(0);	}

				// Are we the first?
				return image.index === 0;
			},

			last: function ( image )
			{	//
				// Get the last image?
				if ( typeof image === 'undefined' )
				{	return this.get(this.size()-1);	}

				// Are we the last?
				return image.index === this.size()-1;
			},

			single: function ( )
			{	// Are we only one
				return this.size() === 1;
			},

			size: function ( )
			{	// How many images do we have
				return this.list.length;
			},

			empty: function ( )
			{	// Are we empty
				return this.size() === 0;
			},

			clear: function ( )
			{	// Clear image arrray
				this.list = [];
				this.image = false;
			},

			active: function ( image )
			{	// Set or get the active image

				// Get the active image?
				if ( typeof image === 'undefined' )
				{	return this.image;	}

				// Set the ative image

				// Make sure image exists
				image = this.get(image);
				if ( !image ) { return image; }

				// Make it the active
				this.image = image;

				// Done
				return true;
			},

			add: function ( obj )
			{
				// Do we need to recurse?
				if ( obj[0] )
				{	// We have a lot of images
					for ( var i = 0; i < obj.length; i++ )
					{	this.add(obj[i]);	}
					return true;
				}

				// Default image

				// Try and create a image
				var image = this.create(obj);
				if ( !image ) { return image; }

				// Set image index
				image.index = this.size();

				// Push image
				this.list.push(image);

				// Success
				return true;
			},

			create: function ( obj )
			{	// Create image

				// Define
				var image = { // default
					src:	'',
					title:	null,
					description:	'',
					name:	'',
					index:	-1,
					image:	true,
					type: 'image',
					open: 'iframe',
					width: '',
					height: ''
				};
				// Create
				if ( obj.image )
				{	// Already a image, so copy over values
					image.src = obj.src || image.src;
					image.title = obj.title || image.title;
					image.description = obj.description || image.description;
					image.name = obj.name || image.name;
					image.index = obj.index || image.index;
					image.type = obj.type || image.type;
					image.open = obj.open || image.open;
					image.width = obj.width || image.width;
					image.height = obj.height || image.height;
				}
				else if ( obj.tagName )
				{	// We are an element
					obj = $(obj);
					if ( obj.attr('src') || obj.attr('href') )
					{
						image.src = obj.attr('src') || obj.attr('href');
						image.title = obj.attr('title') || obj.attr('alt') || image.title;
						image.name = obj.attr('name') || '';
						// Extract description from title
						if(image.title) {
						var s = image.title.indexOf(': ');
							if ( s > 0 )
							{	// Description exists
								image.description = image.title.substring(s+2) || image.description;
								image.title = image.title.substring(0,s) || image.title;
							}
						}

						image.type = 'image';
						if(obj.attr('rel')) {
							var rel = $(obj).attr('rel');
							var s = rel.indexOf('[');
							var s2 = rel.indexOf(']');
							//rellel átadott paraméterek levágása
							if ( s > 0 && s2 > 0) {
								rel = rel.substring((s+1),s2);
							}
							var rels = rel.split(',');
							for(i=0;i<rels.length;i++) {
								var s = rels[i].indexOf(':');
								if ( s > 0 ) {	// Description exists
									switch(rels[i].substring(0,s)) {
										case 'width':
											image.width = rels[i].substring(s+1);
											break;
										case 'height':
											image.height = rels[i].substring(s+1);
											break;
										case 'open':
											image.open = "iframe";
											if(rels[i].substring(s+1)=="div") {
												image.open = "div";
											}
											image.type = "html";
											break;
										case 'title':
											if($("#"+rels[i].substring(s+1))) {
												image.title = $("#"+rels[i].substring(s+1)).html();
											}
											break;
									}
								} else {
									switch(i) {
										case 1:
											image.width = rels[i];
											break;
										case 2:
											image.height = rels[i];
											break;
										case 3:
											if($("#"+rels[i])) {
												image.title = $("#"+rels[i]).html();
											}
											break;
										case 4:
											image.open = "iframe";
											if(rels[i]=="div") {
												image.open = "div";
											}
											image.type = "html";
											break;
									}
								}
							}
						}
					}
					else
					{	// Unsupported element
						image = false;
					}
				}
				else
				{	// Unknown
					image = false;
				}

				if ( !image )
				{	// Error
					$.log('ERROR', 'We dont know what we have:', obj);
					this.finish();
					return false;
				}
				// Success
				return image;
			},

			get: function ( image )
			{	// Get the active, or specified image

				// Establish image
				if ( typeof image === 'undefined' || image === null )
				{	// Get the active image
					return this.active();
				}
				else
				if ( typeof image === 'number' )
				{	// We have a index

					// Get image
					image = this.list[image] || false;
				}
				else
				{	// Create
					image = this.create(image);
					if ( !image ) { return false; }

					// Find
					var f = false;
					for ( var i = 0; i < this.size(); i++ )
					{
						var c = this.list[i];
						if ( c.src === image.src && c.title === image.title && c.description === image.description )
						{	f = c;	}
					}

					// Found?
					image = f;
				}

				// Determine image
				if ( !image )
				{	// Image doesn't exist
					$.log('ERROR', 'The desired image doesn\'t exist: ', image, this.list);
					this.finish();
					return false;
				}

				// Return image
				return image;
			},

			debug: function ( )
			{
				return $.cbsBox.debug(arguments);
			}

		},

		// -----------------
		// Options

		constructed:		false,
		autoShowInfoBox:	true,		 //autómatikusan egyből lenyílik az infoBox a kép megjelenésekor,  false esetén akkor jelenik meg, ha a kép fölé visszük az egeret
		autoShowInfoBoxTop:	false, //autómatikusan egyből lenyílik az infoBox a kép megjelenésekor,  false esetén akkor jelenik meg, ha a kép fölé visszük az egeret
		src:            null,      // the source location of our js file
		slideShow:			true,
		slideShowDuration:	3000,
		thumbnailNav:		true,
		slideShowOn:		false,
		imageBorder:		0,
		files: {
			// If you are doing a repack with packer (http://dean.edwards.name/packer/) then append ".packed" onto the js and css files before you pack it.
			js: {
				cbsbox:	'cbsbox2.0.js'
			},
			css: {
				cbsbox:	'../css/jquery.cbsBox.css'
			},
			images: {
				prev:			'../images/prev_uj.gif',
				next:			'../images/next_uj.gif',
				blank:			'../images/blank.gif',
				loading:		'../images/loading.gif',
				slideShowBar:	'../images/gray.gif',
        close:        '../images/close.gif'
			},
			pluginFiles: {}
		},
		plugins: {},

		text: {
			// For translating
			image:		'Kép',
			of:			'/',
			close:		'Bezár',
			closeInfo:	'A kép alatt vagy felett klikkelve bezár az ablak.',
			help: {
				close:		'Bezáráshoz kattints a kép fölé vagy alá<br/>Kép címére állva egyéb funkciók is elérhetők',
				interact:	' '
			},
			about: {
				text: 	' ',
				title:	' ',
				link:	'http://creamotiv.hu'
			},
			slideshow: {
				start: "<u>V</u>etítés indítása",
				stop: "<u>V</u>etítés vége"
			}
		},
		show_linkback:	true,

		keys: {
			close:	'b',
			prev:	'e',
			next:	'k',
			slideshow: 'v'
		},

		handlers: {
			// For custom actions
			show:	null
		},

		opacity:	0.9,
		padding:	null,	// if null - autodetect

		speed:		400,	// Duration of effect, milliseconds

		rel:		'cbsbox',	// What to look for in the rels

		auto_relify:	true,	// should we automaticly do the rels?

		scroll_with:	true,	// should the cbsbox scroll with the page?

		baseurl:			null,

		template: '\
<div id="cbsbox-overlay" style="display: none;"> \
	<div id="cbsbox-overlay-text"> \
		<p> \
			<span id="cbsbox-overlay-text-about"> \
				<a href="#" title="%about_title%">%about_text%</a> \
			</span> \
		</p> \
		<p>&nbsp;</p> \
		<p> \
			<span id="cbsbox-overlay-text-close">%help_close%</span> \
			<br/>&nbsp; \
			<span id="cbsbox-overlay-text-interact">%help_interact%</span> \
		</p> \
	</div> \
</div> \
<div id="cbsbox"  style="display: none;"> \
  <table id="cbsbox-over" cellspacing="0" cellpadding="0" border="0"> \
    <tr> \
      <td id="cbsbox-over-left"> \
      </td> \
      <td id="cbsbox-over-center"> \
      </td> \
      <td id="cbsbox-over-right"> \
      </td> \
    </tr> \
  </table> \
	<div id="cbsbox-infoBoxTop"> \
		<div id="cbsbox-slideShowBox"> \
      <div id="cbsbox-close"> \
        <a href="#" id="cbsbox-close-button" title="%closeInfo%">%close%</a> \
      </div> \
			<div id="cbsbox-slideShowContainer"> \
				<div id="cbsbox-startStop"> \
					<span id="cbsbox-startStop-start">%slideshow_start%</span> \
					<span id="cbsbox-startStop-stop">%slideshow_stop%</span> \
				</div> \
				<img id="cbsbox-slideShowBar" src="%images_slideShowBar%" /> \
				<div id="cbsbox-slideShowContainer-clear"></div> \
			</div> \
      <div id="cbsbox-clear"></div> \
		</div> \
	</div> \
	<div id="cbsbox-imageBox"> \
		<div id="cbsbox-imageContainer"> \
			<img id="cbsbox-image" /> \
			<span id="cbsbox-inline-content"></span> \
			<iframe id="cbsbox-iframe-content"></iframe> \
			<div id="cbsbox-nav"> \
				<a href="#" id="cbsbox-nav-btnPrev"></a> \
				<a href="#" id="cbsbox-nav-btnNext"></a> \
			</div> \
			<div id="cbsbox-loading"> \
				<a href="#" id="cbsbox-loading-link"><img src="%images_loading%" /></a> \
			</div> \
			<div id="cbsbox-thumbnailNavBox"></div> \
			<div id="cbsbox-thumbnailNavContainer"> \
				<div id="cbsbox-thumbnailNav-thumbnails"></div> \
			</div> \
		</div> \
	</div> \
	<div id="cbsbox-infoBox"> \
		<div id="cbsbox-infoContainer"> \
			<div id="cbsbox-infoHeader"> \
				<span id="cbsbox-caption"> \
					<span id="cbsbox-caption-title"></span> \
					<span id="cbsbox-caption-description"></span> \
				</span> \
			</div> \
    </div> \
		<div id="cbsbox-infoFooter"> \
			<span id="cbsbox-currentNumber"></span> \
		</div> \
		<div id="cbsbox-infoContainer-clear"></div> \
	</div> \
  <table id="cbsbox-bottom" cellspacing="0" cellpadding="0" border="0"> \
    <tr> \
      <td id="cbsbox-bottom-left">&nbsp;\
      </td> \
      <td id="cbsbox-bottom-center">&nbsp;\
      </td> \
      <td id="cbsbox-bottom-right">&nbsp;\
      </td> \
    </tr> \
  </table> \
</div>',
		// -----------------
		// Functions

		//cbsbox konstruktor
		construct: function ( options )
		{
			//már egyszer inicializáltunk?
			var initial = typeof this.constructed === 'undefined' || this.constructed === false;

			//konstruktorunk lefutott állapotba állítása
			this.constructed = true;

			//felépítettük a dom-ot már?
			var domReady = initial;

			// Prepare options
			options = $.extend({}, options);

			// -------------------
			// Handle files
			// Add baseurl
			if ( initial && (typeof options.files === 'undefined') )
			{	// Load the files like default

				// Get the src of the first script tag that includes our js file (with or without an appendix)
				this.src = $('script[src*='+this.files.js.cbsbox+']:first').attr('src');

				// Make sure we found ourselves
				if ( !this.src )
				{	// We didn't
					$.log('WARNING', 'cbsbox was not able to find it\'s javascript script tag necessary for auto-inclusion.');
					this.finish();
					// We don't work with files anymore, so don't care for domReady
					domReady = false;
				}
				else
				{	// We found ourself

					// automatikus baseurl detektalas, ha nincs megadva direktbe
					if(this.baseurl == null)
						this.baseurl = this.src.substring(0, this.src.indexOf(this.files.js.cbsbox));

					// Apply baseurl to files
					var me = this;
					$.each(this.files, function(group, val){
						$.each(this, function(file, val){
							me.files[group][file] = me.baseurl+val;
						});
					});
					delete me;
					domReady = false;
				}

			}
			else
			if ( typeof options.files === 'object' )
			{	// We have custom files
				var me = this;
				$.each(options.files, function(group, val){
					$.each(this, function(file, val){
						this.options[file] = me.baseurl+val;
					});
				});
				delete me;
			}
			else
			{	// Don't have any files, so no need to perform domReady
				domReady = false;
			}

			// -------------------
			// Apply options

			for ( i in this.options )
			{	// Cycle through the options
				var name = this.options[i];
				if ( (typeof options[name] === 'object') && (typeof this[name] === 'object') )
				{	// We have a group like text or files
					this.options[name] = $.extend(this.options[name], options[name]);
				}
				else if ( typeof options[name] !== 'undefined' )
				{	// We have that option, so apply it
					this.options[name] = options[name];
				}
			}

			// -------------------
			// Handle our DOM

			if ( !domReady)
			{	// We have reason to handle the dom
				$(function() {
					// DOM is ready, so fire our DOM handler
					$.cbsBox.domReady();
				});
			}

			// -------------------
			// Finish Up

			// All good
			return true;
		},

		replace: function(text, expr, val) {
			while(expr.test(text)) {
				text = text.replace(expr, val);
			}
			return text;
		},

		domReady: function ( )
		{
			// -------------------
			// Append display

			// Include stylesheet
			var stylesheets = this.files.css;
			var bodyEl = document.getElementsByTagName($.browser.safari ? 'head' : 'body')[0];
			for ( stylesheet in stylesheets )
			{
				var linkEl = document.createElement('link');
				linkEl.type = 'text/css';
				linkEl.rel = 'stylesheet';
				linkEl.media = 'screen';
				linkEl.href = stylesheets[stylesheet];
				linkEl.id = 'cbsbox-stylesheet-'+stylesheet;
				$('#'+linkEl.id).remove();
				bodyEl.appendChild(linkEl);
			}
			delete stylesheets;
			delete bodyEl;

			// template elokeszitese
			$('#cbsbox,#cbsbox-overlay').remove();
			var template = this.template;
			template = this.replace(template, /%about_title%/, this.text.about.title);
			template = this.replace(template, /%about_text%/, this.text.about.text);
			template = this.replace(template, /%help_close%/, this.text.help.close);
			template = this.replace(template, /%help_interact%/, this.text.help.interact);
			template = this.replace(template, /%images_loading%/, this.files.images.loading);
			template = this.replace(template, /%images_slideShowBar%/, this.files.images.slideShowBar);
			template = this.replace(template, /%closeInfo%/, this.text.closeInfo);
      if(this.files.images.close) {
        this.text.close+="&nbsp;<img class='cbsbox-close-image' src='"+this.files.images.close+"'>";
      }
			template = this.replace(template, /%close%/, this.text.close);
			template = this.replace(template, /%slideshow_start%/, this.text.slideshow.start);
			template = this.replace(template, /%slideshow_stop%/, this.text.slideshow.stop);

			$('body').append(template);

			// Update Boxes - for some crazy reason this has to be before the hide in safari and konqueror
			this.resizeBoxes();
			this.repositionBoxes();

			// Hide
			$('#cbsbox,#cbsbox-overlay,#cbsbox-overlay-text-interac,#cbsbox-startStop-stop,#cbsbox-thumbnailNavContainer').hide();

			//elotoltunk par kepet a templatehez...
			$.each(this.files.images, function()
			{	// Proload the image
				var preloader = new Image();
				preloader.onload = function() {
					preloader.onload = null;
					preloader = null;
				};	preloader.src = this;
			});

			// -------------------
			// Apply events

			// If the window resizes, act appropriatly
			$(window).unbind().resize(function ()
			{	// The window has been resized
				$.cbsBox.resizeBoxes();
				$.cbsBox.repositionBoxes();
			});

			// If the window scrolls, act appropriatly
			if ( $.cbsBox.scroll_with )
			{	// We want to
				$(window).scroll(function ()
				{	// The window has scrolled
					$.cbsBox.repositionBoxes();
				});
			}

			// Prev
			$('#cbsbox-nav-btnPrev').unbind().hover(function() { // over
				$(this).css({ 'background' : 'url(' + $.cbsBox.files.images.prev + ') left 45% no-repeat' });
			},function() { // out
				$(this).css({ 'background' : 'transparent url(' + $.cbsBox.files.images.blank + ') no-repeat' });
			}).click(function() {
				$.cbsBox.showImage($.cbsBox.images.prev());
				return false;
			});

			// Next
			$('#cbsbox-nav-btnNext').unbind().hover(function() { // over
				$(this).css({ 'background' : 'url(' + $.cbsBox.files.images.next + ') right 45% no-repeat' });
			},function() { // out
				$(this).css({ 'background' : 'transparent url(' + $.cbsBox.files.images.blank + ') no-repeat' });
			}).click(function() {
				$.cbsBox.showImage($.cbsBox.images.next());
				return false;
			});

			// Help
			if ( this.show_linkback )
			{	// Linkback exists so add handler
				$('#cbsbox-overlay-text-about a').click(function(){window.open($.cbsBox.text.about.link); return false;});
			}
			$('#cbsbox-overlay-text-close').unbind().hover(
				function(){
					$('#cbsbox-overlay-text-interact').fadeIn();
				},
				function(){
					$('#cbsbox-overlay-text-interact').fadeOut();
				}
			);

			// Assign close clicks
			$('#cbsbox-overlay, #cbsbox-loading-link, #cbsbox-btnClose, #cbsbox-close-button').unbind().click(function() {
				$.cbsBox.finish();
				return false;
			});

			// -------------------
			// Finish Up

			// Relify
			if ( $.cbsBox.auto_relify )
			{	// We want to relify, no the user
				$.cbsBox.relify();
			}

			// All good
			return true;
		},

		relify: function ( )
		{	// Create event

			//
			var groups = {};
			var groups_n = 0;
			var orig_rel = this.rel;
			// Create the groups
			$.each($('a[rel^="'+orig_rel+'"]'), function(index, obj){
				// Get the group
				var rel = $(obj).attr('rel');
				var s = rel.indexOf('[');
				var s2 = rel.indexOf(',');
				var s3 = rel.indexOf(']');
				//rellel átadott paraméterek levágása
				if ( s > 0 && s3 > 0) {
					if(s2 > 0) {
						rel = rel.substring((s+1),s2);
					} else {
						rel = rel.substring((s+1),s3);
					}
				} else {
					var rel = groups_n;
				}
				// Are we really a group
				if ( rel === orig_rel )
				{	// We aren't
					rel = groups_n; // we are individual
				}
				// Does the group exist
				if ( typeof groups[rel] === 'undefined' )
				{	// Make the group
					groups[rel] = [];
					groups_n++;
				}
				// Append the image
				groups[rel].push(obj);
			});
			// cbsbox groups
			$.each(groups, function(index, group){
				$(group).cbsbox();
			});
			// Done
			return true;
		},

		init: function ( image /*int*/, images /*[]*/ )
		{	// Init a batch of cbsboxes

			// Establish images
			if ( typeof images === 'undefined' )
			{
				images = image;
				image = 0;
			}
			// Clear
			this.images.clear();

			// Add images
			if ( !this.images.add(images) )
			{	return false;	}

			// Do we need to bother
			if ( this.images.empty() )
			{	// No images
				$.log('WARNING', 'cbsbox started, but no images: ', image, images);
				this.finish();
				return false;
			}

			// Set active
			if ( !this.images.active(image) )
			{	return false;	}

			// Done
			return true;
		},

		start: function ( )
		{	// Display the cbsbox

			// We are alive
			this.visible = true;

			// Adjust scrolling
			if ( this.scroll === 'disable' )
			{	//
				$(document.body).css('overflow', 'hidden');
			}

			// Fix attention seekers
			$('embed, object, select').css('visibility', 'hidden');//.hide(); - don't use this, give it a go, find out why!

			// Resize the boxes appropriatly
			this.resizeBoxes('general');

			// Reposition the Boxes
			this.repositionBoxes({'speed':0});

			// Hide things
			$('#cbsbox-infoFooter').hide(); // we hide this here because it makes the display smoother
			$('#cbsbox-image,#cbsbox-nav,#cbsbox-nav-btnPrev,#cbsbox-nav-btnNext,#cbsbox-infoBox,#cbsbox-infoFooter,#cbsbox-iframe-content,#cbsbox-inline-content').hide();
			// Display the boxes
			$('#cbsbox-overlay').css('opacity',this.opacity).fadeIn(400, function(){
				// Show the cbsbox
				$('#cbsbox').fadeIn(300);

				// Display first image
				if ( !$.cbsBox.showImage($.cbsBox.images.active()) )
				{	$.cbsBox.finish();	return false;	}
			});

			// All done
			return true;
		},

		finish: function ( )
		{	// Get rid of cbsbox
			$.cbsBox.slideShowStop();
			$('#cbsbox-slideShowBar').stop();
			$('#cbsbox').hide();
			$('#cbsbox-overlay').fadeOut(function() { $('#cbsbox-overlay').hide(); });
			// Fix attention seekers
			$('embed, object, select').css({ 'visibility' : 'visible' });//.show();
		},

		resizeBoxes: function ( )
		{
			// Style overlay and show it
			$('#cbsbox-overlay').css({
				width:		$(document).width(),
				height:		$(document).height()
			});
		},


		repositioning:			false,	// are we currently repositioning
		reposition_failsafe:	false,	// failsafe
		repositionBoxes: function ( options )
		{
			// Prepare
			if ( $.cbsBox.repositioning )
			{	// Already here
				$.cbsBox.reposition_failsafe = true;
				return null;
			}
			$.cbsBox.repositioning = true;

			// Options
			options = $.extend({}, options);
			options.callback = options.callback || null;
			options.speed = options.speed || 'slow';

			// Get page scroll
			var pageScroll = this.getPageScroll();

			// Figure it out
			var nHeight = options.nHeight+50 || parseInt($('#cbsbox').height(),10) || $(document).height()/3;

			// Display cbsbox in center
			var nTop = pageScroll.yScroll + ($(document.body).height() /*frame height*/ - nHeight) / 2.5;
			var nLeft = pageScroll.xScroll;

			// Animate
			var css = {
				left: nLeft,
				top: nTop
			};
			if (options.speed) {
				$('#cbsbox').animate(css, 'slow', function(){
					if ( $.cbsBox.reposition_failsafe )
					{	// Fire again
						$.cbsBox.repositioning = $.cbsBox.reposition_failsafe = false;
						$.cbsBox.repositionBoxes(options);
					}
					else
					{	// Done
						$.cbsBox.repositioning = false;
						if ( options.callback )
						{	// Call the user callback
							options.callback();
						}
					}
				});
			}
			else
			{
				$('#cbsbox').css(css);
				if ( $.cbsBox.reposition_failsafe )
				{	// Fire again
					$.cbsBox.repositioning = $.cbsBox.reposition_failsafe = false;
					$.cbsBox.repositionBoxes(options);
				}
				else
				{	// Done
					$.cbsBox.repositioning = false;
				}
			}

			// Done
			return true;
		},

		showImage: function ( image, options )
		{
			// Establish image
			image = this.images.get(image);
			if ( !image ) { return image; }

			// Establish options
			options = $.extend({step:1}, options);
			// Split up below for jsLint compliance
			if(image.type=="image") {
				var skipped_step_1 = options.step > 1 && this.images.active().src !== image.src;
				var skipped_step_2 = options.step > 2 && $('#cbsbox-image').attr('src') !== image.src;
				if ( skipped_step_1 || skipped_step_2 )
				{	// Force step 1
					$.log('We wanted to skip a few steps: ', options, image, skipped_step_1, skipped_step_2);
					options.step = 1;
				}
			}
			// What do we need to do
			switch ( options.step )
			{
				// ---------------------------------
				// We need to preload
				case 1:

					// Disable keyboard nav
					this.keyboardNavDisable();

					// Disable thumbnail nav
					this.thumbnailNavDisable();

					// Show the loading image
					$('#cbsbox-loading').show();

					// Hide things
					$('#cbsbox-image,#cbsbox-nav,#cbsbox-nav-btnPrev,#cbsbox-nav-btnNext,#cbsbox-infoBox,#cbsbox-infoBoxTop,#cbsbox-slideShowContainer,#cbsbox-inline-content ,#cbsbox-iframe-content').hide();

					// Remove show info events
					$('#cbsbox-imageBox').unbind();
					// ^ Why? Because otherwise when the image is changing, the info pops out, not good!

					// Make the image the active image
					if ( !this.images.active(image) ) { return false; }

					if(image.type=="image") {
						// Preload the image, and continue to step 2 once loaded
						var preloader = new Image();
						preloader.onload = function() {
							$.cbsBox.showImage(null, {step:2, width:preloader.width, height:preloader.height});
							preloader.onload = null;
							preloader = null;
						};
						preloader.src = image.src;
					} else {
						$.cbsBox.showImage(null, {step:2, width:image.width, height:image.height});
					}

					// Done
					break;


				// ---------------------------------
				// Resize the container
				case 2:
					if(image.type == "image")  {
						// Set image src
						$('#cbsbox-image').attr('src', image.src);
					}
					// Set container border (Moved here for Konqueror fix - Credits to Blueyed)
					if ( typeof this.padding === 'undefined' || this.padding === null || isNaN(this.padding) )
					{	// Autodetect
						this.padding = parseInt($('#cbsbox-imageContainer').css('padding-left'), 10) || parseInt($('#cbsbox-imageContainer').css('padding'), 10) || 15;
					}
					// Establish options
					options = $.extend({width:640, height:480}, options);

          options.width = parseInt(options.width)?parseInt(options.width):640;
          options.height = parseInt(options.height)?parseInt(options.height):480;

					// Resize image box
					// i:image, c:current, n:new, d:difference
					// Get image dimensions
					var iWidth  = parseInt(options.width);
					var iHeight = parseInt(options.height);

					// Get current width and height
					var cWidth = $('#cbsbox-imageBox').width();
					var cHeight = $('#cbsbox-imageBox').height();

					// Get the width and height of the selected image plus the padding
					var nWidth	= (iWidth  + (this.padding * 2)); // Plus the image's width and the left and right padding value
					var nHeight	= (iHeight + (this.padding * 2)); // Plus the image's height and the left and right padding value

					var docWidth = $(window).innerWidth();
					var docHeight = $(window).innerHeight();
					if(docWidth < nWidth) {
						nWidth = parseInt(docWidth-100);
						nHeight = parseInt(nWidth/iWidth*iHeight);
					}
					if(docHeight < nHeight) {
						nHeight = parseInt(docHeight-100);
						nWidth = parseInt(nHeight/iHeight*iWidth);
					}

					// Diferences
					var dWidth  = cWidth  - nWidth;
					var dHeight = cHeight - nHeight;

					// Lets do this here because we can - NO because we know the heights here
					$('#cbsbox-nav-btnPrev,#cbsbox-nav-btnNext').css({ height: nHeight });
					$('#cbsbox-infoBox').css({ width: nWidth });
					$('#cbsbox-infoBoxTop').css({ width: nWidth });
					$('#cbsbox-image').css({ width: nWidth, height: nHeight });

          if(!$.browser.msie) {
            var bWidth = nWidth + parseInt($('#cbsbox-imageBox').css("border-left-width"))+parseInt($('#cbsbox-imageBox').css("border-right-width"));
          } else {
            var bWidth = nWidth;
          }

          // Reposition the Boxes
					this.repositionBoxes({'nHeight':nHeight});

					if(image.type=="html"){
            $('#cbsbox-imageBox').animate({ width: nWidth, height: nHeight }, this.speed);
            $('#cbsbox-over').animate({ width: bWidth}, this.speed);
            $('#cbsbox-bottom').animate({ width: bWidth}, this.speed);
						if(image.open=="div") {
							$('#cbsbox-inline-content').load(image.src + "?ajax=" + (new Date().getTime()),function(evt){
								$.cbsBox.showImage(null, {step:5});
								$.cbsBox.relify();
							});
						} else {
							$('#cbsbox-iframe-content').attr("src",image.src + "?ajax=" + (new Date().getTime()));
							$.cbsBox.showImage(null, {step:5});
							$('#cbsbox-iframe-content').show();
						}
						return true;
					}
					// Do we need to wait? (just a nice effect to counter the other
					if ( dWidth === 0 && dHeight === 0 )
					{	// We are the same size
						this.pause(this.speed/3);
						$.cbsBox.showImage(null, {step:3});
					}
					else
					{	// We are not the same size
						// Animate
						$('#cbsbox-imageBox').animate({ width: nWidth, height: nHeight }, this.speed, function ( ) { $.cbsBox.showImage(null, {step:3}); } );
            $('#cbsbox-over').animate({ width: bWidth}, this.speed);
            $('#cbsbox-bottom').animate({ width: bWidth}, this.speed);
					}

					// Done
					break;


				// ---------------------------------
				// Display the image
				case 3:

					// Hide loading
					$('#cbsbox-loading').hide();

					// Animate image
					$('#cbsbox-image').fadeIn(500, function() {$.cbsBox.showImage(null, {step:4}); });

					// Start the proloading of other images
					this.preloadNeighbours();

					// Fire custom handler show
					if ( $.cbsBox.handlers.show !== null )
					{	// Fire it
						$.cbsBox.handlers.show(image);
					}

					if ($.cbsBox.images.size() > 1) {
            var thumbnails = '';
            var allThumbsWidth = 0;
            for (i = 0; i < $.cbsBox.images.size(); i++) {
                var preThumbs = new Image();
                var image = $.cbsBox.images.get(i);
                preThumbs.src = image.src;
                thumbnails += '<a href="javascript:void(0)" onclick="$.cbsBox.showImage($.cbsBox.images.get('+i+'))"><img style="border: 0; left: 50px;" " src="' + image.src + '" height="50" class="cbsbox-thumb-img" /></a>';
                allThumbsWidth += 67;
            }
            $('#cbsbox-thumbnailNav-thumbnails').html(thumbnails);
            var marginLeft = $('#cbsbox-thumbnailNav-thumbnails > a:first').css("margin-left");
            var marginRight = $('#cbsbox-thumbnailNav-thumbnails > a:first').css("margin-right");
            allThumbsWidth += ( $.cbsBox.images.size()-1) * parseInt(marginLeft)+parseInt(marginRight);
            $('#cbsbox-thumbnailNav-thumbnails').css("width",allThumbsWidth+"px");
						if($('#cbsbox-imageBox').width() < allThumbsWidth) {
							$('#cbsbox-thumbnailNav-thumbnails').unbind().mousemove(function(e){
								var tempX = 0;
								tempX = e.pageX;
								if (tempX < 0) {
										tempX = 0;
								}
								var imgWidth = $('#cbsbox-imageBox').width();
								$('#cbsbox-thumbnailNav-thumbnails').css("marginLeft",(($(document).width() - imgWidth) / 2 - tempX) / (imgWidth / (allThumbsWidth - imgWidth))+"px");
							});
						}
					} else {
						$('#cbsbox-thumbnailNav-thumbnails').html("");
					}
					// Done
					break;


				// ---------------------------------
				// Set image info / Set navigation
				case 4:

					// ---------------------------------
					// Set image info
					// Hide and set image info
          if(image.title && image.title!= '')
            $('#cbsbox-caption-title').html(image.title + (image.description ? ': ' : '') || 'Untitled');
					$('#cbsbox-caption-description').html(image.description || '&nbsp;');

					// If we have a set, display image position
					if ( this.images.size() > 1 )
					{	// Display
						$('#cbsbox-currentNumber').html(this.text.image + '&nbsp;<span class="cbsbox-image-numbers">' + ( image.index + 1 ) + '&nbsp;' + this.text.of + '&nbsp;' + this.images.size() + '</span>');
					} else
					{	// Empty
						$('#cbsbox-currentNumber').html('&nbsp;');
					}

					// ---------------------------------
					// Info events

					// Apply event
					if(this.autoShowInfoBox) {
						$('#cbsbox-infoBox').slideDown('fast');
					}
					if(this.autoShowInfoBoxTop) {
						$('#cbsbox-infoBoxTop').slideDown('fast');
					}
					$('#cbsbox-imageBox').unbind('mouseover').mouseover(function(){
						if(!$.cbsBox.autoShowInfoBox) {
							$('#cbsbox-infoBox').slideDown('fast');
						}
            if(!this.autoShowInfoBoxTop) {
              $('#cbsbox-infoBoxTop').slideDown('fast');
            }
						if($.cbsBox.slideShow && $.cbsBox.images.size() > 1) {
              $('#cbsbox-slideShowContainer').slideDown('fast');
							$('#cbsbox-startStop-start').unbind('click').click(function(){
								$.cbsBox.slideShow();
							});

							$('#cbsbox-startStop-stop').unbind('click').click(function(){
								$.cbsBox.slideShowStop();
							});
						}
					 });

					// Apply event
					$('#cbsbox-infoBox').unbind('mouseover').mouseover(function(){
             $('#cbsbox-infoBox').unbind('mouseover');
						 $('#cbsbox-infoFooter').slideDown('fast');
					 });

					if(this.slideShowOn) {
						this.slideShow();
						this.keyboardNavEnable();
					} else {

						// ---------------------------------
						// Set navigation

						// Instead to define this configuration in CSS file, we define here. And it's need to IE. Just.
						$('#cbsbox-nav-btnPrev, #cbsbox-nav-btnNext').css({ 'background' : 'transparent url(' + this.files.images.blank + ') no-repeat' });

						// If not first, show previous button
						if ( !this.images.first(image) ) {
							// Not first, show button
							$('#cbsbox-nav-btnPrev').show();
						}

						// If not last, show next button
						if ( !this.images.last(image) ) {
							// Not first, show button
							$('#cbsbox-nav-btnNext').show();
						}

						// Make navigation active / show it
						$('#cbsbox-nav').show();
						// Enable keyboard navigation
						this.keyboardNavEnable();
						// Enable thumbnail navigation
						if ( this.images.size() > 1 ) {
							this.thumbnailNavEnable();
						}

					}

					// Done
					break;

				// ---------------------------------
				// Display: content
				case 5:
					// Hide loading
					$('#cbsbox-loading').hide();

					if(image.open=="div") {
						$('#cbsbox-inline-content').show();
					}
					// ---------------------------------
					// Set image info
					// Hide and set image info
					$('#cbsbox-caption-title').html((image.title?image.title:'') + (image.description ? ': ' : '') || 'Untitled');
					$('#cbsbox-caption-description').html(image.description || '&nbsp;');

					// If we have a set, display image position
					/*if ( this.images.size() > 1 )
					{	// Display
						$('#cbsbox-currentNumber').html(this.text.image + '&nbsp;' + ( image.index + 1 ) + '&nbsp;' + this.text.of + '&nbsp;' + this.images.size());
					} else
					{	// Empty*/
						$('#cbsbox-currentNumber').html('&nbsp;');
					//}

					$('#cbsbox-infoBox').slideDown('fast');
					// Apply event
					$('#cbsbox-infoBox').unbind('mouseover').mouseover(function(){
             $('#cbsbox-infoBox').unbind('mouseover');
						 $('#cbsbox-infoFooter').slideDown('fast');
					 });

           // Apply event
					if(this.autoShowInfoBox) {
						$('#cbsbox-infoBox').slideDown('fast');
					}
					if(this.autoShowInfoBoxTop) {
						$('#cbsbox-infoBoxTop').slideDown('fast');
					}
					$('#cbsbox-imageBox').unbind('mouseover').mouseover(function(){
						if(!$.cbsBox.autoShowInfoBox) {
							$('#cbsbox-infoBox').slideDown('fast');
						}
            if(!this.autoShowInfoBoxTop) {
              $('#cbsbox-infoBoxTop').slideDown('fast');
            }
					 });

					 // Instead to define this configuration in CSS file, we define here. And it's need to IE. Just.
					$('#cbsbox-nav-btnPrev, #cbsbox-nav-btnNext').css({ 'background' : 'transparent url(' + this.files.images.blank + ') no-repeat' });

					/*
					// If not first, show previous button
					if ( !this.images.first(image) ) {
						// Not first, show button
						$('#cbsbox-nav-btnPrev').show();
					}

					// If not last, show next button
					if ( !this.images.last(image) ) {
						// Not first, show button
						$('#cbsbox-nav-btnNext').show();
					}

					// Make navigation active / show it
					$('#cbsbox-nav').show();
					*/
					// Enable keyboard navigation
					this.keyboardNavEnable();

					break;
				// ---------------------------------
				// Error handling
				default:
					$.log('ERROR', 'Don\'t know what to do: ',options);
					return this.showImage(image, {step:1});
					// break;

			}
			// All done
			return true;
		},

		slideShow: function ()
		{
			this.slideShowOn = true;
			$('#cbsbox-startStop-start').hide();
			$('#cbsbox-startStop-stop').show();
			$('#cbsbox-slideShowBar').css("width",0+"px");
			if(this.autoShowInfoBoxTop) {
				var width = $('#cbsbox-slideShowContainer').width();
			} else {
				var width = $('#cbsbox-imageBox').width();
			}
			$('#cbsbox-slideShowBar').stop();
			$('#cbsbox-slideShowBar').animate({"width":(width - 200)+"px"},{ duration: this.slideShowDuration, complete: function(){
					$('#cbsbox-slideShowBar').css("width",0+"px");
					if($.cbsBox.slideShowOn) {
						if (!$.cbsBox.images.last($.cbsBox.images.active())) {
							var next = $.cbsBox.images.next()
						}
						else {
							var next = $.cbsBox.images.first()
						}
						if(next) {
							$.cbsBox.showImage(next);
						}
					}
				}
			});
			return true;
		},

		slideShowStop: function (options)
		{
			this.slideShowOn = false;
			$('#cbsbox-slideShowBar').stop();
			$('#cbsbox-slideShowBar').css("width",0+"px");
			$('#cbsbox-startStop-start').show();
			$('#cbsbox-startStop-stop').hide();

			// If not first, show previous button
			var image = this.images.active();
			if ( !this.images.first(image) ) {
				// Not first, show button
				$('#cbsbox-nav-btnPrev').show();
			}

			// If not last, show next button
			if ( !this.images.last(image) ) {
				// Not first, show button
				$('#cbsbox-nav-btnNext').show();
			}

			// Make navigation active / show it
			$('#cbsbox-nav').show();
			// Enable thumbnail navigation
			if ( this.images.size() > 1 ) {
				this.thumbnailNavEnable();
			}

			return true;
		},

		preloadNeighbours: function ( )
		{	// Preload all neighbour images

			// Do we need to do this?
			if ( this.images.single() || this.images.empty() )
			{	return true;	}

			// Get active image
			var image = this.images.active();
			if ( !image ) { return image; }

			// Load previous
			var prev = this.images.prev(image);
			var objNext;
			if ( prev ) {
				objNext = new Image();
				objNext.src = prev.src;
			}

			// Load next
			var next = this.images.next(image);
			if ( next ) {
				objNext = new Image();
				objNext.src = next.src;
			}
		},

		thumbnailNavEnable: function ( ) {
			$('#cbsbox-imageContainer').css('width',parseInt($('#cbsbox-imageBox').css("width"))); //IE6 miatt
			$('#cbsbox-thumbnailNavBox').css('height',parseInt($('#cbsbox-thumbnailNavContainer').css('height')+40));
      $('#cbsbox-thumbnailNavBox').show();
			$('#cbsbox-thumbnailNavBox').unbind().mouseover(function(){$.cbsBox.thumbnailNavShow()});
		},
		thumbnailNavDisable: function ( ) {
			$('#cbsbox-imageContainer').css('width',"auto"); //IE6 miatt
			$('#cbsbox-thumbnailNavBox').unbind();
      $('#cbsbox-thumbnailNavBox').hide();
			$('#cbsbox-thumbnailNavContainer').fadeOut();
		},
		thumbnailNavShow: function ( ) {
			$('#cbsbox-thumbnailNavContainer').fadeOut(0);
			$('#cbsbox-thumbnailNavContainer').show();
			$('#cbsbox-thumbnailNavContainer').fadeTo('slow',0.85);
			$('#cbsbox-thumbnailNavBox').unbind().mouseover(function(){$.cbsBox.thumbnailNavHide()});
		},
		thumbnailNavHide: function ( ) {
			$('#cbsbox-thumbnailNavContainer').fadeOut();
			$('#cbsbox-thumbnailNavBox').unbind().mouseover(function(){$.cbsBox.thumbnailNavShow()});
		},


		// --------------------------------------------------
		// Things we don't really care about

		keyboardNavEnable: function ( ) {
			$(document).keydown(function(objEvent) {
				$.cbsBox.keyboardNavAction(objEvent);
			});
		},

		keyboardNavDisable: function ( ) {
			$(document).unbind();
		},

		keyboardNavAction: function ( objEvent ) {
			// Prepare
			objEvent = objEvent || window.event;

			// Get the keycode
			var keycode = objEvent.keyCode;
			var escapeKey = objEvent.DOM_VK_ESCAPE /* moz */ || 27;

			// Get key
			var key = String.fromCharCode(keycode).toLowerCase();

			// Close?
			if ( key === this.keys.close || keycode === escapeKey )
			{	return $.cbsBox.finish();		}

			// Prev?
			if ( key === this.keys.prev || keycode === 37 )
			{	// We want previous
				if(this.slideShowOn)
					$.cbsBox.slideShowStop();
				return $.cbsBox.showImage($.cbsBox.images.prev());
			}

			// Next?
			if ( key === this.keys.next || keycode === 39 )
			{	// We want next
				if(this.slideShowOn)
					$.cbsBox.slideShowStop();
				return $.cbsBox.showImage($.cbsBox.images.next());
			}

			if( key === this.keys.slideshow && this.images.size() > 1)
			{
				if(this.slideShowOn)
					return $.cbsBox.slideShowStop();
				else
					return $.cbsBox.slideShow();
			}

			// Unknown
			return true;
		},

		getPageScroll: function ( ) {
			var xScroll, yScroll;
			if (self.pageYOffset)
			{	// Some browser
				yScroll = self.pageYOffset;
				xScroll = self.pageXOffset;
			} else if (document.documentElement && document.documentElement.scrollTop)
			{	// Explorer 6 Strict
				yScroll = document.documentElement.scrollTop;
				xScroll = document.documentElement.scrollLeft;
			} else if (document.body)
			{	// All other browsers
				yScroll = document.body.scrollTop;
				xScroll = document.body.scrollLeft;
			}
			var arrayPageScroll = {'xScroll':xScroll,'yScroll':yScroll};
			return arrayPageScroll;
		},


		pause: function ( ms ) {
			var date = new Date();
			var curDate = null;
			do { curDate = new Date(); }
			while ( curDate - date < ms);
		}

	}); // We have finished extending/defining our cbsbox
		// Instantiate
	if ( typeof $.cbsBox === 'undefined' )
	{	//
		$.cbsBox = new $.cbsBoxClass();
	}

})(jQuery); // We are done with our plugin, so lets call it with jQuery as the argument

