/**
 * BROWSBOX PHOTOBOOK
 * 
 * @projectDescription: browsbox default photobook
 * 
 * @Version:	0.5
 * @Date:		2011.02.21
 * @Author:		Jeroen Cornelissen
 * @Company:	KIXX www.kixx.be | BROWSBOX www.browsbox.be
 **/
 
(function($) {
	
	$.fn.bbphotobook = function(options) {
		
		// default settings
    	var settings = {
            overviewTxt		: albumOverviewLabel,
            diashowTxt		: albumSlideshowLabel,
            diashowTimeout	: 2500,
            prevTxt			: previousLabel,
            nextTxt			: nextLabel,
            keyBoardNav		: true,
            width			: 700,
            height			: 525,
            maxThumbs		: 8,
            ajaxfile		: '/'+installDir+'/ajax/photoalbum.php',
            maskColor		: '#000',
            maskOpacity		: 0.8,
            maskSpeed		: 200
        };
        
        if(options) { $.extend(settings, options); }
        
        // global vars
        maxThumbs = settings.maxThumbs;
        
        // html interface
        var ux = '<div id="bbph_overlay">' +
        			'<div id="btnbar">' +
        				'<a href="#" class="overview">' + settings.overviewTxt + '</a>' +
        				'<a href="#" class="diashow">' + settings.diashowTxt + '</a>' +
        				'<a href="#" class="nextImgBtn">' + settings.nextTxt + '</a>' +
        				'<a href="#" class="prevImgBtn">' + settings.prevTxt + '</a>' +
        			'</div>' +
        			'<a href="#" class="close">[X]</a>' +
        			'<div id="bigImg"></div>' +
        			'<div id="thumbbar">' +
        				'<a href="#" class="prevBtn"></a>' +
        				'<div id="thumbsmask"><div id="thumbs"></div></div>' +
        				'<a href="#" class="nextBtn"></a>' +
        			'</div>' +
        			'<div id="catsholder">' +
        				'<div id="catsheader">' + settings.overviewTxt + 
        					'<a href="#" class="prevCatBtn"></a>' +
        				'</div>' +
        				'<div id="catsmask"><div id="catscontent"></div></div>' +
        				'<div id="catsfooter">' +
        					'<a href="#" class="nextCatBtn"></a>' +
        				'</div>' +
        			'</div>' +
        		'</div>';
       		
        
        // add the overlay element to the body and add functions
        $('body').append(ux);
		
		// make a jquery tools overlay
        var overlay = $('#bbph_overlay').overlay({
			mask: {	color: settings.maskColor, loadSpeed: settings.maskSpeed, opacity: settings.maskOpacity },
			closeOnClick: false,
		 	load: false,
			fixed: false,
		 	onBeforeLoad: function() {
		 		// keyboard navigation
				if(settings.keyBoardNav) {
					$('html').keydown(function(e){
						// 37 = left arrow (prev) # 39 = right arrow (next)
						if(e.keyCode == 39) $('#bbph_overlay a.nextImgBtn').click();
						else if(e.keyCode == 37) $('#bbph_overlay a.prevImgBtn').click();
					});
				}
		 	},
		 	onBeforeClose: function(){ 
		 		// prevent timer from playing
		 		if(isPlaying) { isPlaying=false; clearTimeout(cycle); }
		 		// slide the catsholder up
		 		$('#bbph_overlay #catsholder').slideUp(5);
		 		// remove keyboard navigation
				if(settings.keyBoardNav) $('html').unbind('keydown');
		 	}
        }).data("overlay");
        
        // set the specified width & height and default functions
        $('#bbph_overlay').css({'width':settings.width+'px','height':settings.height+'px'});
		
		var barw = settings.width - $('#btnbar').css('padding-left').replace("px", "") - $('#btnbar').css('padding-right').replace("px", "");
		$('#bbph_overlay #btnbar').css({'width':barw+'px'});
        
        $('#bbph_overlay #bigImg').css({'width':settings.width+'px','height':settings.height+'px','background-image':'none','background-position':'center center','background-repeat':'no-repeat'});
        
        $('#bbph_overlay #catsholder').css({'width':settings.width+'px','height':settings.height+'px'});
        
        barw = settings.width - $('#bbph_overlay #catsheader').css('padding-left').replace("px", "") - $('#bbph_overlay #catsheader').css('padding-right').replace("px", "");
		$('#bbph_overlay #catsheader').css({'width':barw+'px'});
		$('#bbph_overlay #catsfooter').css({'width':barw+'px'});
		var cont = settings.height 
					- $('#bbph_overlay #catsheader').css('height').replace("px", "") 
					- $('#bbph_overlay #catsheader').css('padding-top').replace("px", "")
					- $('#bbph_overlay #catsheader').css('padding-bottom').replace("px", "") 
					- $('#bbph_overlay #catsheader').css('margin-top').replace("px", "")
					- $('#bbph_overlay #catsheader').css('margin-bottom').replace("px", "") 
					- $('#bbph_overlay #catsfooter').css('height').replace("px", "")
					- $('#bbph_overlay #catsfooter').css('padding-top').replace("px", "")
					- $('#bbph_overlay #catsfooter').css('padding-bottom').replace("px", "")
					- $('#bbph_overlay #catsfooter').css('margin-top').replace("px", "")
					- $('#bbph_overlay #catsfooter').css('margin-bottom').replace("px", "");
						
		barw = settings.width - $('#bbph_overlay #catscontent').css('padding-left').replace("px", "") - $('#bbph_overlay #catscontent').css('padding-right').replace("px", "");
		$('#bbph_overlay #catscontent').css({'width':barw+'px'});
		$('#bbph_overlay #catsmask').css({'width':settings.width+'px','height':cont+'px'});
		/*if( $.browser.msie && $.browser.version <= 6 )
			$('#bbph_overlay #catscontent').css({'height':cont+'px'});*/
		
		// btnbar > diashow
		var isPlaying = false;
		var cycle;
		$('#bbph_overlay a.diashow').click(function(e){
			if( !isPlaying )
			{
				// start cycle
				isPlaying = true;
				cycle = setTimeout(cycleImgs,settings.diashowTimeout);
			} else {
				// stop cycle
				isPlaying = false;
				clearTimeout(cycle);
			}
			e.preventDefault();
		});
		function cycleImgs() {
			// every x milliseconds - get the next img
			cycle = setTimeout(cycleImgs,settings.diashowTimeout);
			$('#bbph_overlay a.nextImgBtn').click();
		}
		function setDiashowText( pos ) {
			activeImg = pos;
			pos++;
			$('#bbph_overlay a.diashow').text( settings.diashowTxt + ' ['+pos+'/'+totalImgs+']');
		}
		
		var activeImg = 0;
		var totalImgs = 0;
		var activePanel = 0;
		// btnbar > prevImgBtn
		$('#bbph_overlay a.prevImgBtn').click(function(e){
			activeImg--;
			if(activeImg < 0) activeImg = totalImgs-1;
			$('#bbph_overlay img#img_'+activeImg).click();
			e.preventDefault();
		});
		// btnbar > nextImgBtn
		$('#bbph_overlay a.nextImgBtn').click(function(e){
			activeImg++;
			if(activeImg >= totalImgs) activeImg = 0;
			$('#bbph_overlay img#img_'+activeImg).click();
			e.preventDefault();
		});
		
		// thumbsbar position
		function checkPanel( pnl )
		{
			// slide to div#thumbs to the right position
			if( activePanel != pnl )
			{
				activePanel = pnl;
				
				// disable btns
				$('#bbph_overlay div#thumbbar a.prevBtn').addClass('disabled');
				$('#bbph_overlay div#thumbbar a.nextBtn').addClass('disabled');
								
				var img = $('#'+panelanchors[activePanel] );
				
				if($.browser.msie && $.browser.version < 8)
				{
					$('#bbph_overlay div#thumbs').scrollTo( img ,120 );
					setTimeout(
						function(){
							$('#bbph_overlay div#thumbbar a.prevBtn').removeClass('disabled'); 
							$('#bbph_overlay div#thumbbar a.nextBtn').removeClass('disabled');
					},120);
				} else {
					var pos = img.position();
					$('#bbph_overlay div#thumbs').animate(
						{left:-pos.left},
						120,
						function(){ 
							$('#bbph_overlay div#thumbbar a.prevBtn').removeClass('disabled')
							$('#bbph_overlay div#thumbbar a.nextBtn').removeClass('disabled') 
						}
					);
				}
			}
			// else -> nothing changed
		}
		
		// btnbar > overview
		var catanchors = new Array();
		var curranchor = 0;
		$('#bbph_overlay a.overview').click(function(e){
			
			if(isPlaying) { isPlaying=false; clearTimeout(cycle); }
			$('#bbph_overlay #catsholder').slideDown();
			
			// load all cats if necessary
			if( $('#bbph_overlay #catscontent').text() == "" ) {
				$.ajax({
						type: "POST",
						url: settings.ajaxfile,
						data: "function=listall",
						dataType: "json",
						statusCode: {404: function() {
							alert('404 ajaxfile not found\n' + settings.ajaxfile );
						}},
						success: function(result){
							var i = '';
							var l = result.length;
							var list = '';
							var addanchor = true;
							//for( i ; i < l ; ++i )
						//	{
								// push id's in achor-array for easy sliding the content with prev/next btns
								/*if( result[i].CATNAME != '' ) { 
									list += '<h4 id="bbph_anchor_'+i+'" class="'+result[i].CSSCLASS+'">'+result[i].CATNAME+'</h4>';
									catanchors.push("bbph_anchor_"+i);
									addanchor = false;
								} */
								var j = 0;
								var m = result[i].ALBUMS.length;
								for( j ; j < m ; ++ j)
								{
									if(result[i].ALBUMS[j].CSSCLASS != '')
									{ 
										//list += '<hr id="bbph_anchor_'+i+j+'"/>';
										// don't add the anchor for the h4 and this one
										if(addanchor) catanchors.push('bbph_anchor_'+i+j);
										addanchor = true;
									}
									
									list += '<div class="photocatbox '+result[i].ALBUMS[j].CSSCLASS+'" id="cat_'+ result[i].ALBUMS[j].ALBUMID+'" >' + 
												'<img src="' + result[i].ALBUMS[j].ALBUMIMAGE + '">' +
												'<p class="date">' + result[i].ALBUMS[j].ALBUMDATE + '</p>' +
												'<p class="title">'+ result[i].ALBUMS[j].ALBUMTITLE + '</p>' +
											'</div>';
								}
								//list += '<hr/>';
							//}
							$('#bbph_overlay #catscontent').html(list);
							// height nog eens instellen - ie shit
							if( $.browser.msie && $.browser.version < 8 )
							{
								var cont = settings.height 
										- $('#bbph_overlay #catsheader').css('height').replace("px", "") 
										- $('#bbph_overlay #catsheader').css('padding-top').replace("px", "")
										- $('#bbph_overlay #catsheader').css('padding-bottom').replace("px", "") 
										- $('#bbph_overlay #catsheader').css('margin-top').replace("px", "")
										- $('#bbph_overlay #catsheader').css('margin-bottom').replace("px", "") 
										- $('#bbph_overlay #catsfooter').css('height').replace("px", "")
										- $('#bbph_overlay #catsfooter').css('padding-top').replace("px", "")
										- $('#bbph_overlay #catsfooter').css('padding-bottom').replace("px", "")
										- $('#bbph_overlay #catsfooter').css('margin-top').replace("px", "")
										- $('#bbph_overlay #catsfooter').css('margin-bottom').replace("px", "");
								$('#bbph_overlay #catsmask').css({'height':cont+'px','overflow':'hidden'});
								$('#bbph_overlay #catscontent').css({'height':cont+'px','overflow':'hidden'});
							}
							//
							$('#bbph_overlay #catscontent div.photocatbox').click(function(e){
								$('#bbph_overlay #catsholder').slideUp();
								showPhotobook( $(this).attr('id').substr(4) );
								e.preventDefault();
							});
							
							if(catanchors.length > 2)
							{
								$('a.prevCatBtn').click(function(e){
									curranchor--;
									if(curranchor < 0) { curranchor = 0; return false; }
									
									if( $.browser.msie && $.browser.version < 8 ) {
										$('#bbph_overlay #catscontent').scrollTo( $('#'+catanchors[curranchor]), 350 );
									} else {
										var position = $('#'+catanchors[curranchor]).position();
										$('#bbph_overlay #catscontent').animate( {top:-position.top} );
									}
									e.preventDefault();
								});
								$('a.nextCatBtn').click(function(e){
									curranchor++;
									if(curranchor >= catanchors.length) { curranchor = catanchors.length-1; return false; }
									
									if( $.browser.msie && $.browser.version < 8 ) {
										$('#bbph_overlay #catscontent').scrollTo( $('#'+catanchors[curranchor]), 350 );
									} else {
										var position = $('#'+catanchors[curranchor]).position();
										$('#bbph_overlay #catscontent').animate( {top:-position.top} );
									}
									
									e.preventDefault();
								});
							}
							
						}
				});
				
				
				e.preventDefault();
			}	
		});
		
		var panelanchors = new Array();
		
		function showPhotobook( catID )
		{
			// a category box has been clicked - load all images from that cat
			$('#bbph_overlay #bigImg').css({'background-image':'none'}).hide();
							
			$.ajax({
				type: "POST",
				url: settings.ajaxfile,
				data: "function=detail&catID="+catID,
				dataType: "json",
				statusCode: {404: function() {
					alert('404 ajaxfile not found\n' + settings.ajaxfile );
				}},
				success: function(result){
					//set the first image
					$('#bbph_overlay #bigImg').css({'background-image':'url('+result[0].img+')'}).fadeIn('250');
					
					var i = 0; 
					var l = totalImgs = result.length;
					var img = '';
					var panel = -1;
					for(i;i<l;++i)
					{
						if (i%settings.maxThumbs == 0)
						{
							panel++;
							panelanchors.push("img_"+i);
						}
						img += '<img id="img_'+i+'" data="'+panel+'" class="thumb '; 
						img += i == 0 ? 'active' : '';
						img += '" src="'+result[i].img+'" />';
					}
					
					// set the thumbs & reset position
					$('#bbph_overlay div#thumbs').html(img).css('left',0);
					// activate first
					setDiashowText(0);
					
					// position thumbbar
					if(l < settings.maxThumbs) {
						// minder thumbs dan max - dus max gelijkstellen met het aantal - anders te lange balk
						maxThumbs = l;
						// prev & next btn weg halen
						$('#bbph_overlay div#thumbbar a.prevBtn').css('display','none');
						$('#bbph_overlay div#thumbbar a.nextBtn').css('display','none');
					} else {
						maxThumbs = settings.maxThumbs;
						// prev & next btn laten zien
						$('#bbph_overlay div#thumbbar a.prevBtn').css('display','');
						$('#bbph_overlay div#thumbbar a.nextBtn').css('display','');
					}
					var tbwidth = $('#bbph_overlay img.thumb:first').outerWidth(true) * l;
					var thumbswidth = tbwidth; //chrome bug - heb thumbswidth nodig, kan die later niet meer ophalen met .css (enkel viewport width)
					$('#bbph_overlay div#thumbs').css('width',tbwidth);
					
					tbwidth = $('#bbph_overlay img.thumb:first').outerWidth(true) * maxThumbs;
					$('#bbph_overlay div#thumbsmask').css('width',tbwidth);
					if( $.browser.msie && $.browser.version < 8 ) {
						$('#bbph_overlay div#thumbsmask').css({'overflow':'hidden'});
						$('#bbph_overlay div#thumbs').css({'width':tbwidth+'px','overflow':'hidden'});
					}
					if( $('#bbph_overlay div#thumbbar a.prevBtn').css('display') != 'none' )
						tbwidth = $('#bbph_overlay div#thumbbar a.prevBtn').outerWidth(true) + tbwidth + $('#bbph_overlay div#thumbbar a.nextBtn').outerWidth(true);
					var tbleft 	= (settings.width - tbwidth) / 2;
					
					$('#bbph_overlay div#thumbbar').css({'width':tbwidth,left:tbleft});
					
					// make the thumbs interactive 
					$('#bbph_overlay img.thumb').click(function(e){
						
						$('#bbph_overlay img.thumb').removeClass('active');
						$(this).addClass('active');
						
						setDiashowText( parseInt( $(this).attr('id').substr(4) ) );
						checkPanel( parseInt($(this).attr('data')) );
																				
						var img = $(this).attr('src');
						$('#bbph_overlay #bigImg').fadeOut('fast',function(){
							$(this).css({'background-image':'url('+img+')'}).fadeIn('fast');
						});
						e.preventDefault();
					});
					
					// prev / next thumb btns
					$('#bbph_overlay div#thumbbar a.prevBtn').click(function(e){
						//prevent doubleclick
						if( $(this).hasClass('disabled') ) return false;
						
						activePanel--;
						if( activePanel < 0 ) activePanel = 0;
						
						var img = $('#'+panelanchors[activePanel] );
						
						if($.browser.msie && $.browser.version < 8)
						{
							$('#bbph_overlay div#thumbs').scrollTo( img ,200 );
							setTimeout(function(){ $('#bbph_overlay div#thumbbar a.nextBtn').removeClass('disabled') },200);
						} else {
							var pos = img.position();
							$('#bbph_overlay div#thumbs').animate({left:-pos.left},200,function(){ $('#bbph_overlay div#thumbbar a.nextBtn').removeClass('disabled') } );
						}
						
						e.preventDefault();
					});
					$('#bbph_overlay div#thumbbar a.nextBtn').click(function(e){
						//prevent doubleclick
						if( $(this).hasClass('disabled') ) return false;
						
						activePanel++;
						if( activePanel < 0 ) activePanel = panelanchors.length-1;
						
						var img = $('#'+panelanchors[activePanel] );
						
						if($.browser.msie && $.browser.version < 8)
						{
							$('#bbph_overlay div#thumbs').scrollTo( img ,200 );
							setTimeout(function(){ $('#bbph_overlay div#thumbbar a.nextBtn').removeClass('disabled') },200);
						} else {
							var pos = img.position(); 
							$('#bbph_overlay div#thumbs').animate({left:-pos.left},200,function(){ $('#bbph_overlay div#thumbbar a.nextBtn').removeClass('disabled') } );
						}
						
						e.preventDefault();
					});
				}
			 });
		}
		
		// add behaviour to each cat box and return it
		return this.each(function() {
			
			var catID = $(this).attr('id').substr(9);
			$(this).click(function(e){
				showPhotobook( catID );
				overlay.load();
				e.preventDefault();
			});
			
		});
       
	}
})(jQuery);
