/*
 * Thickbox Bonus Edition - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/

(function($){

jQuery.ThickBox = 
{
	allLinks: null,	// all matched elements (links) type: jQuery
	groupLinks: null,	// filtered links by group (rel attribute) type: jQuery
	thisLink: null,	// original link for currently displayed image type: jQuery
	numbers: null,		// links for numbers type: jQuery
	boxWidth: '480',
	activeGroup: null,
	groupNames: ['box'],
	useHistory: false,
	oldhash: '',
	langcode: 'cs',
	langs: {
		cs: { prev: "předchozí", next: "další", close: "Zavřít" },
		sk: { prev: "predchádzajúca", next: "ďalšie", close: "Zatvoriť" },
		en: { prev: "previous", next: "next", close: "Close" }
	},
	imgPreloader: null,
	o: {
		minWidth: 480
	},

	showImageByHash: function(hash)
	{
		var groupMatch = false;
		var gnlength = $.ThickBox.groupNames.length;
		for(var i = 0; i < gnlength; i++)
		{
			if(hash.search($.ThickBox.groupNames[i]) !== -1 )
			{
				groupMatch = true;
				break;
			}
		} 
		if(groupMatch) 
		{
			var group = hash.replace(/-.*$/, '');
			var imgIndex = parseInt(hash.replace(/^.*-/, ''));
			if($('#TB-window').size() == 0)
			{
				$.ThickBox.showBox();
			}

			var link = $("a[@rel=" + group + "]").get(imgIndex-1);
			$.ThickBox.initGroup(link);
			return true;
		}
		else
		{
			$.ThickBox.hideBox();
			return false;
		}
	},

	showBox: function()
	{
		//that.oldhash = window.location.hash;
		if(!document.getElementById("TB-window")) 
		{
			this.showOverlay();
			$("body").append("<div id='TB-window'></div>");
			var html =  "<div id='TB-paging'><div id='prevnext'><a href='#' id='TB-prev' rel=''>" + this.langs[this.langcode]["prev"] + "</a><a href='#' id='TB-next' rel=''>" + this.langs[this.langcode]["next"] + "</a></div><div id='TB-page'></div></div><div id='TB-close'><a href='#' id='TB-close-btn' title='" + this.langs[this.langcode]["close"] + "'>" + this.langs[this.langcode]["close"] + "</a></div><div class='break'></div><a href='#' id='TB-image' title='" + this.langs[this.langcode]["close"] + "'></a><div id='TB-content'></div><h3 id='TB-caption'></h3><p id='TB-desc'></p>";
			$("#TB-window").append(html);
			$("#TB-close-btn").bind('click', this.closeBox);
			this.positionBox();
		}			
	},

	closeBox: function()
	{
		if($.ThickBox.useHistory) $.historyLoad($.ThickBox.oldhash);
		return $.ThickBox.hideBox();
	},

	hideBox: function()
	{
		$('#TB-window, #TB-overlay, #TB-iframe').remove();		
		$(document).unbind('keyup');
		this.activeGroup = null;
		return false;
	},

	initGroup: function(elem)
	{
		var that = $.ThickBox;
		var group = $(elem).attr('rel');
		var title = $(elem).attr('title');
		if(group)
		{				
			that.groupLinks = that.allLinks.filter("a[@rel=" + group + "]");

			if (group == "refer" || group == "question" || group == "sklad") that.groupLinks = $(elem);

			var htmlPages = '';
			that.groupLinks.each(function(i)
			{ 
				htmlPages += " <a href='" + this.href + "'>" + (i + 1) + "</a> ";					 
			});
			$("#TB-page").empty().append(htmlPages); 
			this.numbers = $("#TB-page a");
			$("#TB-prev").unbind('click').bind('click', function(){ $('#TB-page .active').prev().trigger('click'); return false; });
			$("#TB-next").unbind('click').bind('click', function(){ $('#TB-page .active').next().trigger('click'); return false; });
			$("#TB-prev, #TB-next, #TB-page").removeClass('hidden');
			this.activeGroup = group;

			$(document).bind('keyup', function(e)
			{ 
				var keycode;
				if (!e) var e = window.event;
				if (e.keyCode) keycode = e.keyCode;
				else if (e.which) keycode = e.which;

				var key = String.fromCharCode(keycode).toLowerCase();

				if((keycode == 27))
				{	
					$("#TB-close-btn").trigger('click');
				} 
				else if(keycode == 37)
				{
					$("#TB-prev:visible").trigger('click');
				} 
				else if(keycode == 39)
				{
					$("#TB-next:visible").trigger('click');
				}
			});				

			if(this.numbers.size() == 1) $("#TB-prev, #TB-next, #TB-page").addClass('hidden');

			$("#TB-page a").bind('click', that.clickNumber).eq(that.groupLinks.index(elem)).each(function(){

				that = $.ThickBox;

				that.numbers.removeClass('active');
				$(this).addClass('active');
				var index = that.numbers.index(this);
				if(index == 0) $("#TB-prev").addClass("hidden");
				else $("#TB-prev").removeClass("hidden");
				if(index == that.numbers.size() - 1) $("#TB-next").addClass("hidden");
				else $("#TB-next").removeClass("hidden");
				that.thisLink = that.groupLinks.eq(index);
				that.preloadContent(this.href);
				// that.preloadImage(this.href);
				return false;

			});
		}
		else 
		{
			this.groupLinks = $(elem);
			$("#TB-prev, #TB-next, #TB-page").addClass('hidden');
			this.preloadImage(elem.href);
		}
	},

	clickNumber: function()
	{
		var that = $.ThickBox;
		var hash = that.activeGroup + '-' + ($(this).text());	
		if(that.useHistory) $.historyLoad(hash);
		else that.showImageByHash(hash);
		return false;		
	},

	preloadContent: function(href)
	{	
		var regexp = /\.jpg|\.png|\.gif$/;
		if(href.search(regexp) !== -1)
		{
			// IMG
			$('#TB-caption, #TB-desc, #TB-image').removeClass('hidden');
			$("#TB-content").addClass('hidden');
			$.ThickBox.preloadImage(href);
		}
		else
		{
			// HTML
			$("#TB-content").removeClass('hidden').addClass('loader');
			$('#TB-image, #TB-caption, #TB-desc').addClass('hidden');			
			$.ThickBox.preloadHtml(href);
		}
	},

	preloadImage: function(href)
	{			
		ioff = $('#TB-image');
		if( ioff.size() == 1)
		{ 
			ioff.height( ioff[0].offsetHeight + "px");
		}
		$("img", ioff).remove();
		$('#TB-content').empty();

		this.imgPreloader = document.createElement('img');
		$(this.imgPreloader).bind('load', this.showImage).attr('src', href);
	},

	preloadHtml: function(href)
	{			
		that = $.ThickBox;

		ioff = $('#TB-image');

		var s = '?'
		var re1=/\?/;
		if (href.search(re1)!=-1) s = '&';

		$("img", ioff).remove();
		$("#TB-content").load(href + s +"ajax=true", null, function(){ 
			$("#TB-content").removeClass('loader');
		});
	},

	showImage: function(e)
	{
		var that = $.ThickBox;

		this.onload = null;

		var imageWidth = this.width;
		var imageHeight = this.height;

		var jqimg = $('img', that.thisLink);		

		var caption = jqimg.attr('alt') || that.thisLink.attr('title'); 
		var desc = jqimg.attr('title');
		var longdesc = jqimg.attr('longdesc');

		var enhdesc = desc ? desc + ', ' : '';

		if(longdesc) enhdesc += '<a href="' + longdesc + '">' + longdesc + '</a>'; 

		if(caption)	$("#TB-caption").removeClass("hidden").html(caption);
		else $("#TB-caption").addClass("hidden").empty();

		if(enhdesc) $("#TB-desc").removeClass("hidden").html(enhdesc);
		else $("#TB-desc").addClass("hidden").empty();				

		$('#TB-image').removeClass('hidden');

		that.boxWidth = imageWidth + 2*15+10;

		if(that.boxWidth < that.o.minWidth) that.boxWidth = that.o.minWidth;

		that.positionBox();

		this.alt = caption;
		if(desc) this.title = desc;
		ioff.height("auto").empty().append(this).bind('click', that.hideBox);

		$("#TB-window").css({display:"block"});			
	},

	positionBox: function() 
	{	
		var that = $.ThickBox;
		var arrayPageScroll = that.getPageScrollTop();

		$("#TB-window").css({marginLeft: '-' + parseInt(that.boxWidth / 2) + 'px', width: that.boxWidth + 'px', top: (arrayPageScroll[1] + 40)+"px"});			
	},

	getPageScrollTop: function()
	{
		var yScrolltop;
		if (self.pageYOffset) 
		{
			yScrolltop = self.pageYOffset;
		} 
		else if (document.documentElement && document.documentElement.scrollTop)
		{
			yScrolltop = document.documentElement.scrollTop;
		} 
		else if (document.body) 
		{
			yScrolltop = document.body.scrollTop;
		}
		arrayPageScroll = new Array('',yScrolltop); 
		return arrayPageScroll;
	},

	showOverlay: function()
	{
		if(!document.getElementById("TB-iframe")) 
		{
			$("body").append("<iframe id='TB-iframe'></iframe><div id='TB-overlay'></div>");
			$("#TB-overlay").bind('click', this.closeBox);
		  	var documentHeight = $(document).height();
		  	var windowHeight = $(window).height();
		  	var maxHeight = documentHeight > windowHeight ? documentHeight : windowHeight;		  	
			$("#TB-overlay, #TB-iframe").css("height", maxHeight);
		}
	}
};

jQuery.fn.ThickBox = function(options)
{	
	var o = jQuery.extend({
		minWidth: 480
  	}, options);

	$.ThickBox.allLinks = this;

	return this.each(function() 
	{	
		$(this).bind('click', function(e)
		{			 
			var group = this.rel;

			if($.ThickBox.useHistory) $.ThickBox.oldhash = window.location.hash.slice(1);

			var hash = this.rel + '-' + ($("a[rel=" + group + "]").index(this) + 1);
			if($.ThickBox.useHistory) $.historyLoad(hash);
			else $.ThickBox.showImageByHash(hash);
			return false;	 
		});	
	});
};
})(jQuery)

