/*
 * PDBox - javascript popup box for displaying images. Supports paging and multiple image groups.
 *  
 * Copyright (c) 2007 PeckaDesign (www.peckadesign.cz)
 *  
 * Parts of code based on Thickbox 2.0 by Cody Lindley (http://www.codylindley.com). Copyright (c) 2006 cody lindley 
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *   
 */
(function($){

jQuery.kfBox = 
{
	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: 540,
	activeGroup: null,
	groupNames: ['pripojene'],
	useHistory: false,
	oldhash: '',
	langcode: 'cs',
	langs: {
		cs: { close: "Zavřít", prev: "předchozí", next: "další" },
		en: { close: "Close", prev: "previous", next: "next" },
		de: { close: "Zumachen", prev: "vorige", next: "folgend" },
		es: { close: "Vaer", prev: "previo", next: "siguiente" },
		fr: { close: "Fermer", prev: "précédant", next: "suivant" },
		it: { close: "Chiudere", prev: "previo", next: " veniente" },
		ru: { close: "закрыть", prev: "предшествующий", next: "последующий" }
	},
	imgPreloader: null,
	o: {
		minWidth: 540
	},
	
	showImageByHash: function(hash)
	{
		var groupMatch = false;
		var gnlength = $.kfBox.groupNames.length;
		for(var i = 0; i < gnlength; i++)
		{
			if(hash.search($.kfBox.groupNames[i]) !== -1 )
			{
				groupMatch = true;
				break;
			}
		} 
		if(groupMatch) 
		{
			var group = hash.replace(/-.*$/, '');
			var imgIndex = parseInt(hash.replace(/^.*-/, ''));
			if($('#pdb-window').size() == 0)
			{
				$.kfBox.showBox();
			}
				
			var link = $("a[@rel=" + group + "]").get(imgIndex-1);
			$.kfBox.initGroup(link);
			return true;
		}
		else
		{
			$.kfBox.hideBox();
			return false;
		}
	},
	

	showBox: function()
	{
		//that.oldhash = window.location.hash;
		if(!document.getElementById("pdb-window")) 
		{
			this.showOverlay();
			$("body").append("<div id='pdb-window'></div>");
			var html =  "<div id='pdb-paging'><div id='prevnext'><a href='#' id='pdb-prev' rel=''>" + this.langs[this.langcode]["prev"] + "</a><a href='#' id='pdb-next' rel=''>" + this.langs[this.langcode]["next"] + "</a></div><div id='pdb-page-list'></div></div><div id='pdb-close'><a href='#' id='pdb-close-btn' title='" + this.langs[this.langcode]["close"] + "'>" + this.langs[this.langcode]["close"] + "</a></div><div class='break'></div><h2 id='pdb-caption'></h2> <p id='pdb-desc'></p> <a href='' id='pdb-image-anchor' title='" + this.langs[this.langcode]["close"] + "'></a><div id='pdb-content'></div>";		
			$("#pdb-window").append(html);
			$("#pdb-close-btn").bind('click', this.closeBox);
			this.positionBox();
		}			
	},
	
	closeBox: function()
	{
		if($.kfBox.useHistory) $.historyLoad($.kfBox.oldhash);
		return $.kfBox.hideBox();
	},
	
	hideBox: function()
	{
		$('#pdb-window, #pdb-overlay, #pdb-iframe').remove();		
		$(document).unbind('keyup');
		this.activeGroup = null;
		return false;
	},
	
	initGroup: function(elem)
	{
		var that = $.kfBox;
		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> ";					 
			});
			$("#pdb-page-list").empty().append(htmlPages); 
			this.numbers = $("#pdb-page-list a");
			$("#pdb-prev").unbind('click').bind('click', function(){ $('#pdb-page-list .active').prev().trigger('click'); return false; });
			$("#pdb-next").unbind('click').bind('click', function(){ $('#pdb-page-list .active').next().trigger('click'); return false; });
			$("#pdb-prev, #pdb-next, #pdb-page-list").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))
				{	
					$("#pdb-close-btn").trigger('click');
				} 
				else if(keycode == 37)
				{
					$("#pdb-prev:visible").trigger('click');
				} 
				else if(keycode == 39)
				{
					$("#pdb-next:visible").trigger('click');
				}
			});				
			
			if(this.numbers.size() == 1) $("#pdb-prev, #pdb-next, #pdb-page-list").addClass('hidden');
			
			$("#pdb-page-list a").bind('click', that.clickNumber).eq(that.groupLinks.index(elem)).each(function(){
			
				that = $.kfBox;
				
				that.numbers.removeClass('active');
				$(this).addClass('active');
				var index = that.numbers.index(this);
				if(index == 0) $("#pdb-prev").addClass("hidden");
				else $("#pdb-prev").removeClass("hidden");
				if(index == that.numbers.size() - 1) $("#pdb-next").addClass("hidden");
				else $("#pdb-next").removeClass("hidden");
				that.thisLink = that.groupLinks.eq(index);
				that.preloadContent(this.href);
				// that.preloadImage(this.href);
				return false;
			
			});
		}
		else 
		{
			this.groupLinks = $(elem);
			$("#pdb-prev, #pdb-next, #pdb-page-list").addClass('hidden');
			this.preloadImage(elem.href);
		}
	},

	clickNumber: function()
	{
		var that = $.kfBox;
		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)
		{
			// Open Image in kfBox:
			$('#pdb-caption, #pdb-desc, #pdb-image-anchor').removeClass('hidden');
			$("#pdb-content").addClass('hidden');
			$.kfBox.preloadImage(href);
		}
		else
		{
			// Open HTML using AJAX:
			$("#pdb-content").removeClass('hidden').addClass('loader');
			$('#pdb-caption, #pdb-desc, #pdb-image-anchor').addClass('hidden');			
			$.kfBox.preloadHtml(href);
		}
	},
			
	preloadImage: function(href)
	{			
		ioff = $('#pdb-image-anchor');
		if( ioff.size() == 1)
		{ 
			ioff.height( ioff[0].offsetHeight + "px");
		}
		$("img", ioff).remove();
		$('#pdb-content').empty();
		
		this.imgPreloader = document.createElement('img');
		$(this.imgPreloader).bind('load', this.showImage).attr('src', href);
	},

	preloadHtml: function(href)
	{			
		that = $.kfBox;
		
		ioff = $('#pdb-image-anchor');
		$("img", ioff).remove();
		$("#pdb-content").load(href, null, function(){ 
			$("#pdb-content").removeClass('loader');
			
			// reseni jak do texarey pridat aktualni url
			$("#formDoporucte #BDmessage").append(that.thisLink.attr('title')); 
			$("#formNapisteNam #BNmessage").append(that.thisLink.attr('title'));
		});
		 
		
	},
	
	showImage: function(e)
	{
		that = $.kfBox;
			
		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)	$("#pdb-caption").removeClass("hidden").html(caption);
		else $("#pdb-caption").addClass("hidden").empty();
		
		if(enhdesc) $("#pdb-desc").removeClass("hidden").html(enhdesc);
		else $("#pdb-desc").addClass("hidden").empty();				
		
		$('#pdb-image-anchor').removeClass('hidden');
		
		boxWidth = imageWidth + 2*15+10;
		if(boxWidth < that.o.minWidth) boxWidth = that.o.minWidth;
			
		that.positionBox();
		
		this.alt = caption;
		if(desc) this.title = desc;
		ioff.height("auto").empty().append(this).bind('click', that.hideBox);

		$("#pdb-window").css({display:"block"});			
				
	},
	
	positionBox: function() 
	{	
		var that = $.kfBox;
		var arrayPageScroll = that.getPageScrollTop();
		
		$("#pdb-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)
		{	// Explorer 6 Strict
			yScrolltop = document.documentElement.scrollTop;
		} 
		else if (document.body) 
		{	// all other Explorers
			yScrolltop = document.body.scrollTop;
		}
		arrayPageScroll = new Array('',yScrolltop); 
		return arrayPageScroll;
	},
	
	showOverlay: function()
	{
		if(!document.getElementById("pdb-iframe")) 
		{
			$("body").append("<iframe id='pdb-iframe'></iframe><div id='pdb-overlay'></div>");
			$("#pdb-overlay").bind('click', this.closeBox);
		  	var documentHeight = $(document).height();
		  	var windowHeight = $(window).height();
		  	var maxHeight = documentHeight > windowHeight ? documentHeight : windowHeight;		  	
			$("#pdb-overlay, #pdb-iframe").css("height", maxHeight);
		}
	}

};


jQuery.fn.kfBox = function(options)
{	
	var o = jQuery.extend({
		minWidth: 540
  	}, options);
  
	$.kfBox.allLinks = this;
	
	return this.each(function() 
	{	
		$(this).bind('click', function(e)
		{			 
			var group = this.rel;
			
			var hash = group + '-' + ($("a[rel=" + group + "]").index(this) + 1);
			
			if($.kfBox.useHistory)
			{ 
				$.kfBox.oldhash = window.location.hash.slice(1);
				$.historyLoad(hash);				
			}
			else $.kfBox.showImageByHash(hash);
			return false;	 
		});	
	});
};

})(jQuery)
