;(function($) {
	/**
	 *
	 *		jBookBrowser v.1.0.2
	 *		jQuery Plugin for displaying page based publications e.g. booklets
	 *
	 *		Dependencies:		jQuery 1.5.1 or later
	 *		License:					GPL 3 
	 *
	 *		Created:					2011-03-14, Jack (tR)
	 *		Last modified:			2011-03-31, Jack (tR)
	 *
	 *
	 *		Project Website:		http://lnk.jtr.de/?id=jbookbrowser
	 *		Download:				http://dl.jtr.de/jbookbrowser-1.0.2.zip
	 *
	 *
	 *		Copyright (c) 2011, Andreas John aka Jack (tR)
	 *
	 *		This program is free software: you can redistribute it and/or modify
	 *		it under the terms of the GNU General Public License as published by
	 *		the Free Software Foundation, either version 3 of the License, or
	 *		(at your option) any later version.
	 *
	 *		This program 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 General Public License for more details.
	 *
	 *		You should have received a copy of the GNU General Public License
	 *		along with this program.  If not, see <http://www.gnu.org/licenses/>.
	 *
	 */


	var settings = null;
	
	/**
	 * The plugin constructor
	 * @param args
	 * @param callback
	 */
	$.fn.jbookbrowser = function( args, callback ) 
	{
		settings = $.extend( {}, $.fn.jbookbrowser.Settings, args, {callback:callback} );
		
		var HelpLink = "\r\n\r\nFor manual visit \r\nhttp://lnk.jtr.de/?id=jbookbrowser";
		
		if (settings.PageSetBaseDir == 'undefinedPageSetBaseDir' )
		{
			alert("Err#001 : Page Set Base directory not given"+HelpLink);
		}
		
		if (settings.PageSetFile == 'undefinedPageSetFile' )
		{
			alert("Err#002 : Page Set file not given"+HelpLink);
		}
		
		if (settings.CSSFile == 'undefinedCSSFile' )
		{
			alert("Err#003 : CSS file not given"+HelpLink);
		}
		
		return this.each( 
			function()
			{				
				PlugInLogic( settings,  $(this) );
			}
		);		
	};
	
	
	/**
	 * Removes all thumbnails (remove links and set to transparent picture)
	 */
	function clearThumbnails()
	{
		var Thumbnails = $("#nav #thumbnails a");
		
		Thumbnails.each( function() {
			$(this)
				.removeAttr('href')
				.children().first()
					.attr( 'src', settings.PageSetBaseDir+'/'+'00.png');
		} );
	}	
	
	/**
	 * Activates "previous page"-button and sets the link to previous page 
	 * @param PageNum
	 */
	function setNavLeft( PageNum )
	{
		if ( PageNum > 1 )
		{
			$("#bpage_nav_left")
				.css("opacity","0.5")
				.children().first()
					.attr('href','javascript:$.fn.jbookbrowser.Page("'+(PageNum-1)+'")');
		}
		else
		{
			$("#bpage_nav_left")
				.css("opacity","0.1")
				.children().first()
					.removeAttr('href');
		}
	}	
	
	/**
	 * Activates "next page"-navigation and sets the link to next page
	 * @param PageNum
	 */
	function setNavRight( PageNum )
	{
		if ( PageNum < NumPages )
		{
			$("#bpage_nav_right")
				.css("opacity","0.5")
				.children().first()
					.attr('href','javascript:$.fn.jbookbrowser.Page("'+(PageNum+1)+'")');
		}
		else
		{
			$("#bpage_nav_right")
				.css("opacity","0.1")
				.children().first()
					.removeAttr('href');
		}
	}	
	
	/**
	 * Loads the specified page and builds the preview buttons
	 * 
	 * @param SelPageNum
	 */
	function selectPage( SelPageNum )
	{
		var SelPageNum = parseInt( SelPageNum );	
		var Thumbnails = $("#nav #thumbnails a");
		var NumPagesInPreview = settings.Thumbnails_Number;
		var TNWidth = settings.Thumbnails_Width;
	
		var FirstThumbnailOfs = 0;
		
		setNavLeft( SelPageNum );
		setNavRight( SelPageNum );
		
		// calculate the limits for page preview (thumbnail pages)
		var PageNum_Start = (SelPageNum - NumPagesInPreview );
		if (PageNum_Start < 0) PageNum_Start = 0;
		
		var PageNum_End = (SelPageNum + NumPagesInPreview );
		if (PageNum_End > NumPages) PageNum_End = NumPages;
		
		if (SelPageNum <= NumPagesInPreview) 
		{ 
			FirstThumbnailOfs = 1 + NumPagesInPreview - SelPageNum; 
		}
	
		CurrentlySelectedPage = SelPageNum;
		
		clearThumbnails();
		
		var i = 0;
		
		// 1. load pages
		for( Page in Pages ) 
		{
			PPNum = parseInt(Page);
			PageSettings = Pages[Page];
			
			// for currently selected page..
			if (PPNum == SelPageNum) 
			{					
				// ..load image
				$("#jbookbrowser #bookpages #pages img")
					.hide()
					.attr('src',PageSettings.image_url)
					.fadeIn(settings.Page_FadeIn);
				
				// ..load page title
				if (settings.PageTitle_show)
				{
					$("#jbookbrowser #title")
						.hide()
						.text(PageSettings.title)
						.fadeIn(settings.PageTitle_FadeIn);
				}
				
				// ..load marginal notes for selected page
				if (settings.MarginalNotes_show) 
				{
					$("#jbookbrowser #margnotes")
						.hide()
						.html(PageSettings.additional_text)
						.fadeIn(settings.MarginalNotes_FadeIn);
				}
			}
			
			// if page is in preview range then show page thumbnail
			if ( settings.Thumbnails_show && ( PPNum >= PageNum_Start && PPNum <= PageNum_End) )
			{	
				// caculate opacity according to thumbnail position:
				// the thumbnail in the middle is the brightest
				var opct = 1.1 - ((1/NumPagesInPreview) * Math.abs(NumPagesInPreview-FirstThumbnailOfs-i));
					
				// set thumbnail image for current page to the appropiate thumbnail position
				$( Thumbnails.get( FirstThumbnailOfs+i ) ) 
					.attr('href',"javascript:$.fn.jbookbrowser.Page(\""+PPNum+"\");")
					.children().first()
					.hover(
						function() 
						{ 
							if (settings.Thumbnails_doHover)
							{
								$(this)
									.animate({ "width" : (settings.Thumbnails_Width*settings.Thumbnails_HoverSF)+"px", "height": (settings.Thumbnails_Height*settings.Thumbnails_HoverSF)+"px" }, 150 ); 
							}
						},
						function() 
						{ 
							if (settings.Thumbnails_doHover)
							{
								$(this)
									.animate({ "width" : settings.Thumbnails_Width+"px", "height": settings.Thumbnails_Height+"px" }, 150 ); 
							}
						}
					)
					.attr('src',PageSettings.image_url)								
					.css("opacity", opct );
				
				i++;
			}
		}
	}	
	
	/**
	 * Prepares the intial view
	 */
	function initBookViewer()
	{	
		// number of pages in page set
		NumPages          = 0;
	
		// number of thumbnails in page navigator
		NumPagesInPreview = settings.Thumbnails_Number;	
		
		// count pages
		for( Page in Pages ) { NumPages++; }
		
		// dim "previous page"-button
		$("#bpage_nav_left")
			.css("opacity","0.1");
			 
		// activate "next page"-button
		$("#bpage_nav_right a")
			.attr('href','javascript:$.fn.jbookbrowser.Page("'+(NumPagesInPreview+2)+'")');
		
		var main_img = $("#bookpages #pages img");
		
		var ImgMiddlePosX = (main_img.position().left)+(main_img.attr('width') / 2);
		
		main_img.click(function (e) {
			if (e.type=="click")
			{
				if (e.pageX <= ImgMiddlePosX && CurrentlySelectedPage > 1 )
				{
					selectPage( CurrentlySelectedPage-1 );
				}
				
				if (e.pageX > ImgMiddlePosX && CurrentlySelectedPage < NumPages )
				{
					selectPage( CurrentlySelectedPage+1 );
				}
			}
		});
			
		selectPage( 1 );	
	}	
	
	
	/**
	 * Reads PageSet from specified XML file
	 */
	function loadPages( PageSetUri )
	{
		var PageSet = new Array();
		
		var i = 1;
		
		$.get( PageSetUri,{},function(xml)
		{ 
	
			$('page',xml).each(function(xml) 
			{ 						
				di_page = $(this).find('title').text();
				di_iurl = $(this).find('image_url').text();
				di_text = $(this).find('additional_text').text();
				
				PageSet[i] = {
						'title'               : di_page,
						'image_url'        : di_iurl,
						'additional_text' : di_text
					};
				
				i++;
			});
			
		})
		.complete(function() 
		{ 
			Pages = PageSet; 
			initBookViewer(); 
		});
	 
	}	
	
	/**
	 * The main plugin logic
	 */
	function PlugInLogic( settings, obj)
	{
		var ThumbnailsHTML = "";
		
		var NumThumbnails = (settings.Thumbnails_Number*2)+1;
		for (var i=1; i<= (NumThumbnails);i++)
		{
			ThumbnailsHTML = ThumbnailsHTML +'<a><img src="'+settings.PageSetBaseDir+'/00.png" height="'+settings.Thumbnails_Height+'" width="'+settings.Thumbnails_Width+'" border="0" /></a>&nbsp;';
		}
				
		obj.html('<link href="'+settings.CSSFile+'" rel="stylesheet" type="text/css" /><div id="title">&nbsp;</div><div id="bookpages" align="center" ><div id="margnotes">&nbsp;</div><div id="pages"><img src="'+settings.PageSetBaseDir+'/00.png" /></div><div id="nav"><div class="left" id="bpage_nav_left"><a><img src="'+settings.PageSetBaseDir+'/prev.png" border="0" /></a></div><div class="right" id="bpage_nav_right"><a><img src="'+settings.PageSetBaseDir+'/next.png" border="0" /></a></div><div id="thumbnails">'+ThumbnailsHTML+'</div></div></div>');

		loadPages(settings.PageSetBaseDir+'/'+settings.PageSetFile);
	
		callFn( settings.callback );			
	};
		
	// callback helper
	function callFn( callback ) 
	{
		if ($.isFunction(callback)) {
			callback.call(this);
		}
	}
	
	$.fn.	jbookbrowser.Page = function( SelPageNum )
	{
		selectPage( SelPageNum );
	}
	
	// plugin default settings
	$.fn.jbookbrowser.Settings = 
	{
			// Obligatory Settings
			PageSetBaseDir        		: 'undefinedPageSetBaseDir',
			PageSetFile						: 'undefinedPageSetFile',
			CSSFile							: 'undefinedCSSFile',

			// Thumbnails Configuration
			Thumbnails_show 			: false,
			Thumbnails_Number		: 3,
			Thumbnails_Height			: 32,
			Thumbnails_Width			: 46,
			Thumbnails_doHover     : 1,
			Thumbnails_HoverSF		: 1.5, // Scaling Factor for hover effect
			
			// Page
			Page_FadeIn		 			: 500,			
			
			// Page Title
			PageTitle_show				: false,
			PageTitle_FadeIn			: 500,
			
			// Marginal Notes
			MarginalNotes_show		: false,
			MarginalNotes_FadeIn	: 1500,
	};

})(jQuery);
