/**
 * --------------------------------------------------------------------
 * jQuery-Plugin "gallery"
 * by Rita Mantler, rita@wearetelescopic.co.uk
 * 	
 * --------------------------------------------------------------------
 */

(function($) { 
	$.widget('wat.gallery',{
		
		origWidth: 			null,
		newWidth: 			250,
		newBigWidth: 		250,
		overSpeed: 			100,
		navFadeSpeed: 		200,
		navFadeDelay: 		200,
		navFadeInTimeOut: 	null,
		navFadeOutTimeOut: 	null,
		bigActiveImage: 	null,
		showImageSpeed: 	300,
		scrollInterval: 	null,
		backColour:		 	'#B4B4B4',
		mouseOverIncrease: 	10,
		scrollDistance: 	400,
		maxHeight: 			0,
		scrollSpeed: 		300,
		objPositions: 		{},
		options: 			{
							},
		
		_create: function() {
			$.wat.gallery.instances.push(this.element);
			
			var self = this;
			self.gallery = this.element;
			
			self.gallery.append('<div class="zoom_holder">');
			self.gallery.css('overflow','hidden');
			self.gallery.live('mouseleave',function(){self._reset_all();});
			
			$('.image_holder').width(self.newBigWidth);
			$('.image_holder').find('img').width('100%');
			
			$('body').css('overflow','hidden');
			
			//add overlay navigation animation
			$('#big_image_holder').live('mouseleave',function(){
				if($.browser.msie)
				{
					$('.nav_big_image').hide();
					$('#close_big_image').hide();
				}
				else
				{
					clearTimeout(self.navFadeInTimeOut);
					self.navFadeOutTimeOut = setTimeout(function(){
						$('.nav_big_image').stop(true, true).fadeTo(self.navFadeSpeed,0);
						$('#close_big_image').stop(true, true).fadeTo(self.navFadeSpeed,0);
					}, self.navFadeDelay);
				}
			});
			$('#big_image_holder').live('mouseenter',function(){
				if($.browser.msie)
				{
					$('.nav_big_image').show();
					$('#close_big_image').show();
				}
				else
				{
					clearTimeout(self.navFadeOutTimeOut);
					self.navFadeInTimeOut = setTimeout(function(){
						$('.nav_big_image').stop(true, true).fadeTo(self.navFadeSpeed,1);
						$('#close_big_image').stop(true, true).fadeTo(self.navFadeSpeed,1);
					}, self.navFadeDelay);
				}
			});
			
			$('#close_big_image').live('click',function(){self._hide_image();});
			
			//create scrollbuttons
			$("<div>", {
	            "class": 'gallery_nav',
	            "id": 'gallery_up'
	        }).appendTo(self.gallery);
	        $('#gallery_up')
	        .live('click',function(){self._scroll_down();});
	        //.live('mouseout',function(){self._stop_scroll();});
	        
			$("<div>", {
				"class": 'gallery_nav',
				"id": 'gallery_down'
			}).appendTo(self.gallery);
			$('#gallery_down')
			.live('click',function(){self._scroll_up();});
			//.live('mouseout',function(){self._stop_scroll();});
			
			
		},
		
		_init: function(booInit)
		{
			var self = this;
			//set gallery height
			self._on_resize();
			$(window).resize(function(){
				self._on_resize();
			});
			
			//set listeners
			$('.zoom_holder').delegate('img','click',function(){self._show_image($(this));});
			//mouseover resize
			$('.image_holder li').live('mouseenter',function(){
				self._thumb_over($(this));
			});
		},
		
		_position_gallery_nav:function(){
			var totalWidth = 0;
			$('.image_holder').each(function(){
				totalWidth = totalWidth + $(this).outerWidth();
			});
			$('.gallery_nav').css('left',(totalWidth - $('.gallery_nav').width())/2);
		},
		
		_on_resize: function(){
			var self = this;
			$('.zoom_holder').children().remove();
			var whiteSpace = 60;
			var wrapperPos = $('#gallery').position();
			var navPos = $('#main_nav').position();
			var totalWidth = 0;
			$('.image_holder').each(function(){
				totalWidth = totalWidth + $(this).outerWidth();
			});
			var cross = wrapperPos.left + totalWidth + whiteSpace;
			this.newBigWidth = (navPos.left - whiteSpace - wrapperPos.left - 10)/3;
			
			if(this.newBigWidth > 250)
			{
				self.newBigWidth = 250;
			}
			self.newWidth = self.newBigWidth;
			$('.image_holder').width(this.newBigWidth);
			$('.image_holder').find('img').width(this.newBigWidth);
			self.origWidth = $('.image_holder').find('img').width();
			
			//set original image positions
			var imgCount = $('.image_holder').find('img').length;
			var checkCount = 0;
			
			//display up and down scroll
			$('.image_holder').each(function(){
				if(self.maxHeight < $(this).height())
				{
					self.maxHeight = $(this).height();
				}
			});
			if(self.maxHeight < self.gallery.height())
			{
				$('.gallery_nav').hide();
			}
			else
			{
				$('.gallery_nav').show();
			}
			$('.image_holder').find('img').load(function(){
				checkCount++;
				self.objPositions[$(this).attr('id')] = $(this).position();
				if(checkCount == imgCount){
					self.maxHeight = 0;
					$('.image_holder').find('img').each(function(){
						self.objPositions[$(this).attr('id')] = $(this).position();
					});
					//display up and down scroll
					$('.image_holder').each(function(){
						if(self.maxHeight < $(this).height())
						{
							self.maxHeight = $(this).height();
						}
					});
					if(self.maxHeight < self.gallery.height())
					{
						$('.gallery_nav').hide();
					}
					else
					{
						$('.gallery_nav').show();
					}
				}
			});
			
			
			var windowHeight = $(window).height() - $('#header').outerHeight() - 20;
			self.gallery.height(windowHeight);
			$('#big_image_holder').height(self.gallery.height());
			$('#big_image_holder').width(self.newBigWidth * 3 + 10);
			$('.nav_big_image').css('top',self.gallery.height()/2 - $('#next_big_image').height()/2);
			self._position_gallery_nav();
			$('.big_image_wrapper_inner').width($('#big_image_holder').width());
			$('#big_active_image').css('padding-top',(self.gallery.height() -$('#big_active_image').height())/2);
			
			//display up and down scroll
			/*self.maxHeight = 0;
			$('.image_holder').find('img').load(function(){
				$('.image_holder').each(function(){
					if(self.maxHeight < $(this).height())
					{
						self.maxHeight = $(this).height();
					}
				});
				if(self.maxHeight < self.gallery.height())
				{
					$('.gallery_nav').hide();
				}
				else
				{
					$('.gallery_nav').show();
				}
			});*/
		},
		
		
		_thumb_over: function(overItem){
			var self = this;
			self._reset_all();
			var origImg = overItem.find('img');
			self.bigActiveImage = origImg;
			var origPos = origImg.position();
			var newImg = origImg.clone();
			var oldWidth = origImg.width();
			self.newWidth = Math.round((oldWidth/100 * self.mouseOverIncrease) + oldWidth);
			self.newWidth = 280;
			newImg.bind('mouseleave',function(){
				self._reset_all();
			});
			if(overItem.parent().hasClass('left'))
			{
				var newLeft = origPos.left;
			}
			else if(overItem.parent().hasClass('right'))
			{
				var newLeft = origPos.left - (self.newWidth - self.origWidth);
			}
			else
			{
				var newLeft = origPos.left - (self.newWidth/2 - oldWidth/2);
			}
			
			if(overItem.is(':first-child'))
			{
				var newTop = origPos.top;
			}
			else
			{
				var oldHeight = origImg.height();
				var newHeight = oldHeight * self.newWidth / oldWidth;
				var newTop = origPos.top - (newHeight/2 - oldHeight/2);
			}
			
			newImg.css({position:'absolute',top:origPos.top,left:origPos.left});
			newImg.css('z-index',2);
			newImg.appendTo(self.gallery.find('.zoom_holder'));
			
			if ($.browser.msie  && parseInt($.browser.version) == 7 && newLeft > 0) {
				newLeft += 5;
			}
			newImg.animate({
				width:self.newWidth+"px",
				left:newLeft,
				top:newTop},self.overSpeed);
		},
		
		
		_scroll_down:function(){
			var self = this;
			$('.zoom_holder').children().remove();
			//this.scrollInterval = setInterval(function(){
				var newPos = parseInt($('#image_wrapper').css('margin-top').replace('px','')) + self.scrollDistance;
				//console.log(newPos);
				if(newPos > 0)
				{
					newPos = 0;
				}
				$('#image_wrapper').animate({'margin-top':newPos},self.scrollSpeed,'linear');
			//},500);
		},
		
		_scroll_up:function(){
			var self = this;
			$('.zoom_holder').children().remove();
			//this.scrollInterval = setInterval(function(){
				var newPos = parseInt($('#image_wrapper').css('margin-top').replace('px','')) - self.scrollDistance;
				//console.log(newPos,' ', parseInt($('#image_wrapper').css('margin-top').replace('px','')));
				if(newPos < self.maxHeight * -1 + self.gallery.height())
				{
					newPos = self.maxHeight * -1 + self.gallery.height();
				}
				$('#image_wrapper').animate({'margin-top':newPos},self.scrollSpeed,'linear');
			//},500);
		},
		
		_stop_scroll:function(){
			var self = this;
			$('#image_wrapper').stop();
			clearInterval(self.scrollInterval);
		},
		
		_reset_all:function(){
			var self = this;
			$('.zoom_holder').children().css('z-index',1);
			$('.zoom_holder').children().unbind('mouseleave');
			$('.zoom_holder').children().each(function(){
				var origPos = self.objPositions[$(this).attr('id')];
				if(!origPos)
				{
					$(this).remove();
				}
				else
				{
					var newTop = origPos.top + parseInt($('#image_wrapper').css('margin-top').replace('px',''));
					var newLeft = origPos.left;
					//ie7 hack
					if ($.browser.msie  && parseInt($.browser.version) == 7 && origPos.left > 0) {
						newLeft = origPos.left + 5;
					}
					$(this).stop().animate({
						width:self.origWidth,
						top:newTop,
						left:newLeft
						},
						self.overSpeed,
						function(){$(this).remove();});
				}
			});
		},
		
		
		_show_image: function(objImage){
			var self = this;
			self._hide_gallery();
			//close other big images
			self.gallery.find('#big_image_holder').remove();
			
			var curPos = objImage.position();
			
			//load big image and display full image
			//self.gallery.append('<img src="'+objImage.attr('src')+'"/>');
			$('<div>',{
				'id': 'big_image_holder'
			}).appendTo(self.gallery)
			.width(self.newBigWidth * 3 + 10)
			.height(self.gallery.height())
			.css({
                	left:curPos.left,
                	top:curPos.top,
                	background: self.backColour
                })
            .width(objImage.width())
            .height(objImage.height())
            .animate({
                    width: self.newBigWidth * 3 + 10, // width of large image
                    height:self.gallery.height(),
                    left:0,
                    top:0
                    },
                   {
                    duration:self.showImageSpeed,
                    step:function(){
                    	$('#big_active_image').css('padding-top',($(this).height() - $('#big_active_image').height())/2);
                    	},
                    complete:function(){
	                	$('#big_active_image').css('padding-top',($(this).height() - $('#big_active_image').height())/2);
	                	//add action buttons
	        			$('<div>',{
	        				'id': 'close_big_image'
	        			})
	        			.appendTo($('#big_image_holder'));
	        			
	        			$('<div>',{
	        				'id': 'next_big_image',
	        				'class': 'nav_big_image'
	        			}).appendTo($('#big_image_holder'))
	        			.css('top',self.gallery.height()/2 - $('#next_big_image').height()/2)
	        			.click(function(){self._scroll_image('next');});
	        			
	        			$('<div>',{
	        				'id': 'prev_big_image',
	        				'class': 'nav_big_image'
	        			}).appendTo($('#big_image_holder'))
	        			.css('top',self.gallery.height()/2 - $('#next_big_image').height()/2)
	        			.click(function(){self._scroll_image('prev');});
                    }
                   });
			
			//add image wrapper for scrolling
			$('<div>',{
				'id': 'big_image_wrapper'
			}).appendTo($('#big_image_holder'));
			
			$('<div>',{
				'class': 'big_image_wrapper_inner'
			}).appendTo($('#big_image_wrapper'))
			.width('100%');
			
			//load image
			$("<img />", {
	            "id": 'big_active_image',
	            "class": 'big_image',
	            "src": objImage.attr('src') + '?'+ Math.random()*99999
	        })
	        .load(function() {
	        	$(this).appendTo($('.big_image_wrapper_inner'));
	        	var ratio = $(this).width()/$(this).height();
	        	if($(this).width() > $(this).height())
	        	{
	        		//landscape
	        		$(this).width('100%');
	        		$(this).height('auto');
	        	}
	        	else
	        	{
	        		//portrait
	        		$(this).height('100%');
	        		$(this).width('auto');
	        	}
	        	$(this).css('padding-top',($('.big_image_wrapper_inner').height() - $(this).height())/2);
	        	
	        });
			
		},
		_hide_image: function()
		{
			var self = this;
			var activeImagePos = self.bigActiveImage.position();
			$('.nav_big_image').stop().fadeTo(self.navFadeSpeed,0);
			$('#close_big_image').stop().fadeTo(self.navFadeSpeed,0,function(){
				$('#big_image_wrapper').width('100%');
				$('.big_image_wrapper_inner').width('100%');
				$('#big_active_image').animate({
					paddingTop:0});
				$('#big_image_holder')
				.css('background','none')
				.animate({
					width: self.newBigWidth,
					height: self.bigActiveImage.height(),
					top:activeImagePos.top,
					left:activeImagePos.left
				},
				function(){
					$(this).remove();
				});
				self._show_gallery();
				
			});
			
		},
		_show_gallery:function(){
			$('.image_holder').animate({'opacity':1});
			if($.browser.msie)
			{
				$('.gallery_nav').show();
			}
			else
			{
				$('.gallery_nav').animate({'opacity':1});
			}
		},
		_hide_gallery:function(){
			$('.image_holder').animate({'opacity':0});
			if($.browser.msie)
			{
				$('.gallery_nav').hide();
			}
			else
			{
				$('.gallery_nav').animate({'opacity':0});
			}
		},
		_scroll_image: function(strDir){
			var self = this;
			var intActiveId = parseInt(self.bigActiveImage.attr('id').replace('thumb_',''));
			if(strDir == 'next')
			{
				var newId = intActiveId + 1;
				self.bigActiveImage = self.gallery.find('#thumb_' + newId);
				if(self.bigActiveImage.length == 0)
				{
					//get first
					self.bigActiveImage = self.gallery.find('#thumb_1');
				}
			}
			else
			{
				var newId = intActiveId - 1;
				if(newId == 0)
				{
					//get last
					var i = 1;
					while(self.gallery.find('#thumb_' + i).length > 0)
					{
						self.bigActiveImage = self.gallery.find('#thumb_' + i);
						i++;
					}
					
				}
				else
				{
					self.bigActiveImage = self.gallery.find('#thumb_' + newId);
				}
				
			}
			
			$("<img />", {
	            "id": 'big_'+strDir+'_image',
	            "class": 'big_image',
	            "src": self.bigActiveImage.attr('src') + '?'+ Math.random()*99999
	        }).load(function() {
	        	
	        	$('#big_image_wrapper').width($('#big_image_wrapper').width() * 2);
	        	
	        	if(strDir == 'next')
	        	{
		        	$('<div>',{
						'class': 'big_image_wrapper_inner'
					}).appendTo($('#big_image_wrapper'))
					.append($(this));
	        	}
	        	else
	        	{
	        		$('<div>',{
						'class': 'big_image_wrapper_inner'
					}).prependTo($('#big_image_wrapper'))
					.append($(this));
	        		
	        		$('#big_image_wrapper').css('margin-left','-' + $('#big_image_holder').width() + 'px');
	        	}
	        	if($(this).width() > $(this).height())
	        	{
	        		//landscape
	        		$(this).width('100%');
	        		$(this).height('auto');
	        	}
	        	else
	        	{
	        		//portrait
	        		$(this).height('100%');
	        		$(this).width('auto');
	        	}
	        	$('.big_image_wrapper_inner').width($('#big_image_holder').width());
	        	
	        	if($(this).width() > $(this).height())
	        	{
	        		//landscape
	        		$(this).css('padding-top',(self.gallery.height() - $(this).height())/2);
	        	}
	        	$('#big_image_wrapper')
	        		.animate({
	        			'margin-left' : strDir == 'next' ? '-' + $('#big_image_holder').width() + 'px' : 0
	        		},
	        		function(){
	        			$('#big_active_image').parent().remove();
	        			$(this).css('margin-left','0');
	        			$('#big_'+strDir+'_image').attr('id','big_active_image');
	        			$('#big_image_wrapper').width($('#big_image_holder').width());
	        		});
	        	
	        	
	        	
	        });
			
		}
		
		
	});
	
	
	$.extend($.wat.gallery, {
		instances: []
	});

})
(jQuery);

$(document).ready(function(){
	if($('#gallery').find('img').length > 0)
	{
	$('#gallery').gallery();
	}});

