// -------------------------------------------------------------------------

if(typeof checkHash == 'undefined')
{
	var _window = $(window);
	var checkHash = function()
	{
		var hash = window.location.hash;

		if(hash != this.prevHash)
		{
			this.prevHash = hash;
			_window.trigger('hashChanged', hash.substring(1));
		}
	};

	if('onhashchange' in window)
	{
		_window.bind('hashchange', checkHash);
	}
	else if('onpopstate' in window)
	{
		_window.bind('popstate', checkHash);
	}
	else	
	{
		window.setInterval('checkHash()', 100);
	}
}

// -------------------------------------------------------------------------

var sdpsmViewBox = {
		author: 'SDPsM — http://sdpsm.com'
	// -------------------------
		,_window: $(window)
		,_body: $(document.body)
		,_box: $('<div/>').addClass('b-sdpsmViewBox')
		,_overlay: $('<div/>').addClass('b-sdpsmViewBox-overlay')
		,_isBoxReady: false
		,_arrows: {
			left: $('<a href="#" />').addClass('b-arrow b-arrow-left'),
			right: $('<a href="#" />').addClass('b-arrow b-arrow-right')
		}
		,_isArrowsReady: false
		,plugins: {}
		,pluginsActive: []
		,pliginsToGO: []
		,hashToGO: []
		,stepToGo: 0
		,prevHash: ''
		,prevPlugin: false
		,onCloseBefore: false
		,onCloseAfter: false
		,onCloseReset: function(){this.onCloseBefore = function(){return true};this.onCloseAfter = function(){}}
		,onOverlayClick: function(){window.location.hash = "!"}

	// -------------------------

	,init: function()
	{
		this._body = $(document.body);

		this.onCloseReset();

		this._window.bind('hashChanged', function(e, hash){sdpsmViewBox.go(hash)});
	}

	// --------------------------

	,_initBox: function()
	{
		this._box
			.append(this._overlay)
			.appendTo(this._body);
		this._isBoxReady = true;
	}

	// --------------------------

	,moveToCenter: function(obj, type)
	{
		type = type || '+';

		var css = {};

		if(type == '+' || type == '|')
		{
			css.top = '50%';
			css.marginTop = Math.round(Math.max(-$(window).height()/2, -obj.height()/2)) + 'px';
		}

		if(type == '+' || type == '—')
		{
			css.left = '50%';
			css.marginLeft = Math.round(Math.max(-$(window).width()/2, -obj.width()/2)) + 'px';
		}

		obj.css(css);

		return this;
	}

	// -------------------------

	,sizeTo: function(obj, width, height)
	{
		var animate = {};
		var isAnimated = false;

		if(typeof width != 'undefined')
		{
			width = Math.max(width, parseInt(obj.css('min-width')) || 0);
			animate.width = width + 'px';
			animate.marginLeft = Math.round(Math.max(-$(window).width()/2, -width/2)) + 'px';
			isAnimated = true;
		}

		if(typeof height != 'undefined')
		{
			height = Math.max(height, parseInt(obj.css('min-height')) || 0);
			animate.height = height + 'px';
			animate.marginTop = Math.round(Math.max(-$(window).height()/2, -height/2)) + 'px';
			isAnimated = true;
		}

		if(isAnimated)
		{
			obj.stop().animate(animate, function()
			{
				var me = $(this);
				me.css({overflow:'visible'});
			});
		}
	}

	// -------------------------

	,close: function()
	{
		if(this.onCloseBefore())
		{
			for(var i = 0, iLength = this.pluginsActive.length; i < iLength; i ++)
			{
				this.plugins[this.pluginsActive[i]].close();
			}
			this.pluginsActive = [];

			this._box.fadeOut(250);
			this._overlay.fadeOut(250);
			this.onCloseAfter();
			this.onCloseReset();
		}
	}

	// -------------------------

	,go: function(hash)
	{
		hash = hash || '';
		hash = hash == ' ' ? '' : hash;

		if(!hash.length)
		{
			this.close();
			return;
		}

		hash = hash.split('/');

		this.getOverlay()
			.unbind()
			.bind('click', sdpsmViewBox.onOverlayClick)
			.css({
				zIndex: 50
			});

		this.pliginsToGO = [];
		this.stepToGo = 0;
		this.hashToGO = hash;

		this.goNextStep();
	}

	// -------------------------

	,goNextStep: function()
	{
		this.stepToGo ++;

		if(this.stepToGo <= this.hashToGO.length)
		{
			var pluginHash = this.hashToGO[this.stepToGo -1].split(':', 2);
			pluginHash[0] = pluginHash[0] || '';
			pluginHash[1] = pluginHash[1] || '';

			if(	typeof this.plugins[pluginHash[0]] != 'undefined' &&
				typeof this.plugins[pluginHash[0]].go != 'undefined')
			{
				this.pluginsActive.push(pluginHash[0]);
				this.pliginsToGO.push(pluginHash[0]);
				if(this.plugins[pluginHash[0]].go(pluginHash[1], 50 + 5 * this.stepToGo))
				{
					this.goNextStep();
				}
			}
			else
			{
				this.goNextStep();
			}
		}
		else
		{
			this.goLastStep();
		}
	}

	// -------------------------

	,goLastStep: function()
	{
		for(var i = 0, iLength = this.pluginsActive.length; i < iLength; i ++)
		{
			if(-1 == this.pliginsToGO.indexOf(this.pluginsActive[i]))
			{
				this.plugins[this.pluginsActive[i]].close();
				this.pluginsActive.splice(i,1);
				i--;
				iLength --;
			}
		}

		if(!this.pluginsActive.length)
		{
			this.close();
		}
	}

	// -------------------------

	,getOverlay: function()
	{
		if(!this._isBoxReady)
		{
			this._initBox();
		}
		return this._overlay;
	}

	// -------------------------

	,getBox: function()
	{
		if(!this._isBoxReady)
		{
			this._initBox();
		}
		return this._box;
	}

	// -------------------------

	,getArrows: function()
	{
		if(!this._isArrowsReady)
		{
			this._arrows.left.appendTo(this._box);
			this._arrows.right.appendTo(this._box);
			this._isArrowsReady = true;
		}

		return this._arrows;
	}

	// -------------------------

	,getBody: function()
	{
		return this._body;
	}

	// -------------------------
};

// =======================================================================

sdpsmViewBox.plugins.w = {
	author: 'SDPsM — http://sdpsm.com'
	// -------------------------

	,_box: $('<div/>').addClass('b-sdpsmViewBox-box-page')
	,_page: $('<div/>').addClass('b-sdpsmViewBox-box-page-content')
	,_currentUrl: ''

	// -------------------------

	,go: function(hash, zIndex)
	{
		this._box.append(this._page).bind('click', sdpsmViewBox.plugins.w.onBoxClick);

		sdpsmViewBox.getOverlay().css({zIndex: zIndex});
		this._box.css({zIndex: zIndex + 1});

		sdpsmViewBox.getBody().css({
			overflow:'hidden'
		});

		if(this._currentUrl !== hash)
		{
			this._currentUrl = hash;
			this._page
				.addClass('b-sdpsmViewBox-box-page-content-loading')
				.load('/ajax/' + hash, function()
					{
						$(this).removeClass('b-sdpsmViewBox-box-page-content-loading');
						sdpsmViewBox.goNextStep();
					});
		}
		else
		{
			sdpsmViewBox.goNextStep();
		}

		sdpsmViewBox.getBox().append(this._box).show();
		sdpsmViewBox.getOverlay().fadeIn(250);

		return false;
	}

	// -------------------------

	,onBoxClick: function(e)
	{
		if($(e.target).hasClass('b-sdpsmViewBox-box-page'))
		{
			sdpsmViewBox.plugins.w._box.unbind('click', sdpsmViewBox.plugins.w.onBoxClick);
			sdpsmViewBox.getOverlay().click();
		}
	}

	// -------------------------

	,close: function()
	{
		this._page.empty();
		this._box.remove();
		sdpsmViewBox.getBody().css({
			overflow: 'auto'
		});
		this._currentUrl = '';
	}

	// -------------------------
};

// =======================================================================

sdpsmViewBox.plugins.p = {
	author: 'SDPsM — http://sdpsm.com'
	// -------------------------

	,_box: $('<div/>').addClass('b-sdpsmViewBox-box-gallery')
	,prevImageBox: false

	// -------------------------

	,go: function(hash, zIndex)
	{
		var xHash = 'p:' + hash;
		var galleries = {};
		var galleryPosition = 0;
		var galleryName = '';
		var links = $('a.x-hash');
		var xLink = false;
		for(var i = 0, iLength = links.length; i < iLength; i ++)
		{
			var link = links.get(i);
			var galName = link.getAttribute('xgallery');
			galleries[galName] = galleries[galName] || [];
			if(galName)
			{
				galleries[galName].push(link);
			}

			if(link.getAttribute('xhash') == xHash)
			{
				galleryPosition = galleries[galName].length -1;
				galleryName = galName;
				xLink = link;
			}
		}

		if(xLink)
		{
			var photoPlugin = this;

			sdpsmViewBox.getOverlay()
				.unbind()
				.bind('click', function()
				{
					var hash = window.location.hash.split('/');
					var result = [];
					for(var i = 0, iLength = hash.length; i < iLength; i ++)
					{
						var x = hash[i].split(':');
						if(x[0] != 'p')
						{
							result.push(hash[i]);
						}
					}
					window.location.hash = result.join('/');
					return false;
				});

			this._box
				.unbind()
				.bind('click', function()
				{
					sdpsmViewBox.getOverlay().click();
				});

			sdpsmViewBox.getOverlay().css({zIndex: zIndex});
			this._box.css({zIndex: zIndex + 1});

//			sdpsmViewBox.getOverlay().fadeIn(250);

			sdpsmViewBox.getBox().append(this._box).show();
			sdpsmViewBox.moveToCenter(this._box);
/*
			sdpsmViewBox.getArrows().left.show();

			var gallery = galleries[galleryName];
			if(galleryPosition < gallery.length -1)
			{
				sdpsmViewBox.getArrows().right.attr({
					href: '#' + gallery[galleryPosition+1].getAttribute('xhash')
				}).show();
			}
			else
			{
				sdpsmViewBox.getArrows().right.hide();
			}

			if(galleryPosition > 0)
			{
				sdpsmViewBox.getArrows().left.attr({
					href: '#' + gallery[galleryPosition-1].getAttribute('xhash')
				}).show();
			}
			else
			{
				sdpsmViewBox.getArrows().left.hide();
			}
*/
			var image = new Image();
			image.onload = function()
			{
				var w_width = sdpsmViewBox._window.width();
				var w_height = sdpsmViewBox._window.height();

				w_width = Math.round(w_width * .9);
				w_height = Math.round(w_height * .9);

				var width = this.width;
				var height = this.height;

				if(width > w_width)
				{
					height = height * (w_width / width);
					width = w_width;
					if (height > w_height)
					{
						width = width * (w_height / height);
						height = w_height;
					}
				}
				else if (height > w_height)
				{
					width = width * (w_height / height);
					height = w_height;
					if (width > w_width)
					{
						height = height * (w_width / width);
						width = w_width;
					}
				}

				var imageBox = $('<img/>', {class: 'p-photo', src: this.src}).hide();
				sdpsmViewBox.sizeTo(photoPlugin._box.append(imageBox), width, height);
				imageBox.fadeIn(250);
				if(photoPlugin.prevImageBox)
				{
					photoPlugin.prevImageBox.fadeOut(250, function(){$(this).remove()});
				}
				photoPlugin.prevImageBox = imageBox;
			};
			image.src = xLink.href;
		}

		return true;
	}

	// -------------------------

	,close: function()
	{
		this._box
			.empty()
			.remove();

		sdpsmViewBox.sizeTo(this._box, 0,0);

//		sdpsmViewBox.getBox().sizeTo(0,0).removeClass('b-sdpsmViewBox-box-gallery');
//		if(this.prevImageBox)
//		{
//			this.prevImageBox.fadeOut(250, function(){$(this).remove();sdpsmViewBox.getBox().empty()});
//		}
	}

	// -------------------------
};

// =======================================================================

if(typeof jQuery != 'undefined')
(function($){
	// -------------------------------------------------------------------------

	$(function()
	{
		sdpsmViewBox .init();
		checkHash();
	});

	// -------------------------------------------------------------------------
})(jQuery);
