/**
* jQuery fancyzoom plugin.
* This is an adaptation of the fancyzoom effect as a jQuery plugin
*
* Author: Mathieu Vilaplana <mvilaplana@df-e.com>
* Date: March 2008
* rev: 1.0
*/

//var scrollToSrc;

//  Minik, 09-05-04: nevalidni atribut REL nahrazen v elementu IMG validnim TITLE  


(function($) {
	var strImgDir = 'ressources/';
	var mainListHeight = undefined;
	
	$.fn.carouselInit = function(userOptions) {		
		var ret = this.each(function() {
			
			var $this 		= $(this);
			var optsId 		= userOptions.id;
			var defOpts 	= {photosPerPage:4,position:0,expandedGallery:false,thisIsExpandedGallery:false,carousel:'',carouselId:'',scrollBuffer:1,readyToScroll:true,maxHeight:0};
			    					
			// pokud je toto hlavni galerie, inicializujeme pole s nastavenim
			userOptions.carouselId=$this.attr('id');
			userOptions.parent=$this.parent();						
			if (!userOptions.thisIsExpandedGallery) {						
				$.fn.carouselInit.r[optsId] = {
					carouselMain:		$.extend({},defOpts,userOptions),
					carouselExpanded:	{}				
				};
				var opts = $.fn.carouselInit.r[optsId].carouselMain;
			} else {				
				$.fn.carouselInit.r[optsId].carouselExpanded = $.extend({},defOpts,userOptions);
				var opts = $.fn.carouselInit.r[optsId].carouselExpanded;						
			}		
			var carousels_opts = $.fn.carouselInit.r[optsId];
   			
   			var pages_count = Math.ceil($('li',$this).length/opts.photosPerPage);
   			
   			var opts_backup;   			
   			var loadedImagesCounter = 0;
   			
	    	$this.jcarousel({
	        	scroll: 3,
            initCallback: initCallbacks	,
	        	itemVisibleInCallback: {  					
  					onAfterAnimation: function(){
  						opts.readyToScroll = true;
  					}
				}      
	    	});    	
	    	
	    	$.fn.fancyzoom.defaultsOptions.imgDir='/js/jqueryfancyzoom/ressources/';
		    $.fn.fancyzoom.defaultsOptions.carousel=(opts.expandedGallery=="")?false:true;
		    $.fn.fancyzoom.defaultsOptions.carouselOptsId=optsId;
		    
		    // pokud je aktivovana galerie v fancyzoomu
		    if (opts.expandedGallery!=false && !opts.thisIsExpandedGallery) {
		    	var expandedId = opts.expandedGallery;		    			    			    	
		       	$('#'+opts.expandedGallery).carouselInit({
		    		expandedGallery:false,
		    		thisIsExpandedGallery:true,
		    		id:optsId    				    				    			    			  
		    	});		    		
		    	
		    	if(pages_count>1)
			    	$('#'+expandedId).mousewheel(function(event, delta) {	
			    			if ($.browser.opera) {delta = -delta}		    		
							if (delta > 0)
								$('a.carousel-prev',this).trigger('click');
							else if (delta < 0)
								$('a.carousel-next',this).trigger('click');
							return false; 
					});
		    	opts.expandedGallery = expandedId;
		    }
		    
		    // automaticky srovnat vysku popisku teprv az budou vsechny nactene
		    if (!opts.thisIsExpandedGallery) 
		    $('.jcarousel-item a span.jcarousel-item-image img',$this).bind('load',function(){
		    	var imagesCount = $('.jcarousel-item',$this).length+1;
				loadedImagesCounter++;				
				if (imagesCount == loadedImagesCounter && !opts.thisIsExpandedGallery) {
					var is_hidden = $('#tab-images').is(":not(:visible)");
					$('#tab-images').show();
					adjustHeights();
					if (is_hidden)	$('#tab-images').hide();
				}
			});
		    
	    
		    if (!opts.thisIsExpandedGallery) {
		    	// zjistime maximalni moznou vysku obrazku ktery je v galerii a posleme do fancyzoomu    	
		    	opts.maxHeight = getMaxHeight();
		    	$.fn.fancyzoom.defaultsOptions.maxHeight = opts.maxHeight;
				// inicializace fancyzoomu
				$('ul li a',$this).fancyzoom({carousel:(opts.expandedGallery=="")?false:true,maxHeight:opts.maxHeight});				
				if(pages_count>1)
					$('#'+opts.carouselId).mousewheel(function(event, delta) {	
							if ($.browser.opera) {delta = -delta}		    		
							if (delta > 0)
								$('a.carousel-prev',$this).trigger('click');
							else if (delta < 0)
								$('a.carousel-next',$this).trigger('click');
							return false; 
					});
			} else {
				
				scrollToSrc = function(src) {
					var pos = Math.ceil($('.jcarousel-list li a[href='+src+']',$this).parent().attr('jcarouselindex')/opts.photosPerPage);
					scroll(opts.carousel,pos);
				};				
				
				// inicializace akce po kliku na fotku v rozbalene galerii
				$('ul li a',$this).click(function(){
					var src = $(this).attr('href');
					manualHashChange = true;					
					actualHash = getHash($('img',this).attr('alt'),src);
					document.location.hash = getHash($('img',this).attr('alt'),src);
					
				
					var $context = this;
					actualHref = src;
					$('#imgZoom').load(function(){
					
						// prizpusobit vysky elementu podle velikosti obrazku
						$('#imgZoom').css({'height':'auto'});						
						var finalImgWrapHeight = $('#imgZoomWrap').height();
						var finalImgHeight = $('#imgZoom').height();						
						oImgZoom.css('height',((finalImgHeight/finalImgWrapHeight)*100)+'%');
						oImgZoom.css({'position':'relative','top':((finalImgWrapHeight-finalImgHeight)/finalImgWrapHeight)*50+'%'});
						
						// nastavit cil animace pri zavreni galerie
						var elLink = $('ul li a[href='+src+']','#'+opts.carouselId).parent();//.each(function(){console.log(this);	});
						var pos=$('img',elLink).offset();													
						$.fn.fancyzoom.defaultsOptions = $.extend($.fn.fancyzoom.defaultsOptions,{dimOri:{width:$('img',elLink).outerWidth(),height:$('img',elLink).outerHeight(),left:pos.left,top:pos.top,'opacity':0}});
						
						if (!$.browser.msie) {
							$('#imgZoom').fadeTo(100,1);
						}
					});				
					
					if (!$.browser.msie) {
						$('#imgZoom').fadeTo(100,0.01,function(){
							$('#imgZoom').attr('src',src);																									
						});
					} else {						
						$('#imgZoom').attr('src',src);						
					}
					return false;
				});				 				
				//opts.thisIsExpandedGallery = false;
				$this.hide();			
			}					
	    	
	    	function scroll(new_pos) {				
				if (opts.readyToScroll) {
				var scrollval = 0;
					if (opts.thisIsExpandedGallery) {
            scrollval = ((new_pos-1) * opts.photosPerPage) + 1 ; //+1				
						opts.carousel.scroll($.jcarousel.intval(scrollval));
						//carousels_opts.carouselMain.scrollBuffer = $.jcarousel.intval((new_pos-1)*opts.photosPerPage)+1;
					} else {
						carousels_opts.carouselExpanded.scrollBuffer = $.jcarousel.intval((new_pos-1)*opts.photosPerPage)+1;
						opts.carousel.scroll($.jcarousel.intval((new_pos-1)*opts.photosPerPage)+1);					
					}
								
					//carousels_opts.carouselMain.position 		= jQuery.jcarousel.intval((new_pos-1));
					carousels_opts.carouselExpanded.position 	= jQuery.jcarousel.intval((new_pos-1));
					
	    			// standard carousel
	    			var context = $('#'+carousels_opts.carouselMain.carouselId);
	    			$(' a.page-button-'+(opts.position+1),context).addClass('selected');
					$(' a:not(.page-button-'+(opts.position+1)+')',context).removeClass('selected');
					$('a.carousel-prev, a.carousel-next',context).removeClass('disabled');
					if (new_pos==1) {
						$('a.carousel-prev',context).addClass('disabled');
					}	
					if (pages_count==new_pos) {
						$('a.carousel-next',context).addClass('disabled');
					}
					
					// expanded carousel
					
					context = $('#'+carousels_opts.carouselExpanded.carouselId);
					$(' a.page-button-'+(opts.position+1),context).addClass('selected');
					$(' a:not(.page-button-'+(opts.position+1)+')',context).removeClass('selected');
					$('a.carousel-prev, a.carousel-next',context).removeClass('disabled');
					if (new_pos==1) {
						$('a.carousel-prev',context).addClass('disabled');
					}	
					if (pages_count==new_pos) {
						$('a.carousel-next',context).addClass('disabled');
					}	
				}
				opts.readyToScroll=false;
			}
	    	
	    	function getHash(alt, href) {
				alt = strtr(alt,"áäèïéìëíòóöø‘úùüýžÁÄÈÏÉÌËÍÒÓÖØŠÚÙÜÝŽáäèïéìëíòóöø¹»úùüý¾ÁÄÈÏÉÌËÍÒÓÖØ©«ÚÙÜÝ® '\\.:+&,/?","aacdeeeinoorstuuuyzAACDEEEINOORSTUUUYZaacdeeeinoorstuuuyzAACDEEEINOORSTUUUYZ-----------");
				if (alt!="") {
					alt = alt.concat("-");
				}
				var hash = alt+href.split('&')[0].split('=')[1];			
				return hash;
			}
	    	
	    	function getMaxHeight() {
	    	  //alert("zjistuju max vysku: ")
	    		var maxHeight = 0;	    		
	    		$('ul.jcarousel-list li img',$this).each(function(){	    		
	    			var height = $(this).attr('rel');
	    			if (height>maxHeight) maxHeight = height;
	    		});
          //alert("maxheight = " + maxHeight);	    		
	    		return maxHeight;
	    	}
	    	
	    	function adjustHeights() {	    	
				var max_img_height = 0;
				var max_title_height = 0;  			
				$('.jcarousel-item','#'+opts.carouselId).each(function(){
					var h = $('a span.jcarousel-item-image img',this).height();
					
					if (h>max_img_height) {
						max_img_height = h;
					}
				});								
				var max_pad = 0;
				$('.jcarousel-item','#'+opts.carouselId).each(function(){				
					var pad = max_img_height-$('a span.jcarousel-item-image img',this).height();					 
					$('a span.jcarousel-item-image',this).css({'padding-bottom':pad/2,'padding-top':pad/2});				
					$('.jcarousel-item[jcarouselindex='+$(this).attr('jcarouselindex')+'] a span.jcarousel-item-image','#'+opts.expandedGallery).css({'padding-bottom':pad/2,'padding-top':pad/2});					
				});	
				list_height = $('.jcarousel-list','#'+opts.carouselId).height();
				$('.jcarousel-item, .jcarousel-clip','#'+opts.carouselId).css('height',list_height);
				$('.jcarousel-item, .jcarousel-clip','#'+opts.expandedGallery).css('height',list_height);
				
				return list_height;		
	    	}
	    	
	    	function initCallbacks(carousel) {		
	    		opts.carousel = carousel;
	    		carousel.options.scroll = jQuery.jcarousel.intval(opts.photosPerPage);
	    		$('.jcarousel-controls .jcarousel-pages a',$this).click(function() {
        			scroll(jQuery(this).text());
        			return false;
    			});
    			$('a.carousel-next',$this).click(function() {  
    				 if (opts.position<pages_count-1) {    		
	    				scroll(opts.position+2);
	    			} 
	        		return false;
    			});    			
			    $('a.carousel-prev',$this).click(function() {			    	   
			    	if (opts.position>0) {
			    		scroll(opts.position);
			        }      
			        return false;
			    }); 		    
    		} 	   		    	
	 	});   
    };
   
    $.fn.carouselInit.r = [];
})(jQuery);

