function associateMeGalleryRandomOrder()
{
	return (Math.round(Math.random())-0.5);
}

var tmpNumber=1;

(function($) 
{
	
	$.fn.AssociateMeGallery = function(galleryOptions) 
	{
		var defaults=
		{
//			["1.jpg", {title: "My Image", href: "http://www.utopia365.com"}]
			images: 		[
								{src: "http://www.bbc.co.uk/doctorwho/medialibrary/s1/images/1024/s1_01_wal_17.jpg"},
								{src: "http://www.bbc.co.uk/doctorwho/medialibrary/s1/images/1024/s1_01_wal_16.jpg"},
								{src: "http://www.bbc.co.uk/doctorwho/medialibrary/s1/images/1024/s1_01_wal_15.jpg"},
								{src: "http://www.bbc.co.uk/doctorwho/medialibrary/s1/images/1024/s1_01_wal_14.jpg"}
							],
			stamp: 			"associate_me_gallery_cf1_15022009",
			name: 			"test", 
			controlsalwaysvisible: false,
			cycleclicks: true,
			randomize: false,
			cycleslideshow: true,
			allowslideshow: true,
			resetslideshow: false,
			showloading: 	false,
			alwaysload: 	true,
			autoplay: 		true,
			appear: 		'random', 
			showcontrols: 	false,
			interval: 		3000
			
		};
		var options = $.extend(defaults, galleryOptions);
		options['showcontrols']=false;
		
		options['stamp']="gallery_30_06_2010_11_34";

		var lastRandomAppear='';
		
		if (options['randomize'])
		{
//		options['images'].sort(associateMeGalleryRandomOrder);
		}
		
		var imageOn=-1;
		var height=$(this).height();
		var width=$(this).width();
		var _this = this;
		var images=[];
		var frameOn=2;
		var isPlaying=false;
		var timer=null;
		
		_this.find(".previous").css("margin-left", "-50px");
		_this.find(".next").css("margin-right", "-50px");
		_this.find(".controls").hide();


		if (options['controlsalwaysvisible'])
		{
//			_this.find(".controls").show();
			_this.find(".previous").css("margin-left", "0px");
			_this.find(".next").css("margin-right", "0px");
		}
		if (!options['allowslideshow'])
		{
			_this.find(".play").hide();
			_this.find(".pause").hide();
		}
		
		$(this).hover(function(e)
		{
			if (options['showcontrols'])
			{
				if (options['allowslideshow'])
				{
//					_this.find(".associate_me_content_loading_container").animate({marginTop: "20px"}, 500);
				}
				if (!options['controlsalwaysvisible'])
				{
					_this.find(".next").animate({ 
					        marginRight: "0px"
					      }, 500 );
					_this.find(".previous").animate({ 
					        marginLeft: "0px"
					      }, 500 );
					_this.find(".controls").fadeIn(500);
				}
				_this.find(".associate_me_small_powered_by_icon").fadeIn(250);
			}
		},
		function(e) 
		{ 
			if (options['showcontrols'])
			{
				if (options['allowslideshow'])
				{
//					_this.find(".associate_me_content_loading_container").animate({marginTop: "-12px"}, 500);
				}
				if (!options['controlsalwaysvisible'])
				{
					_this.find(".next").animate({ 
					        marginRight: "-50px"
					      }, 500 );
					_this.find(".previous").animate({ 
					        marginLeft: "-50px"
					      }, 500 );
					_this.find(".controls").fadeOut(500);
				}
				_this.find(".associate_me_small_powered_by_icon").fadeOut(250);
			}
		});

		
		$(this).find(".controls > .next").click(function(e)
		{
			_this.next();
		});

		$(this).find(".controls > .previous").click(function(e)
		{
			_this.previous();
		});

		$(this).find(".controls > .play").click(function(e)
		{
			_this.start();
		});

		$(this).find(".controls > .pause").click(function(e)
		{
			_this.stop();
		});
		
		this.updateControlButtonsVisibility=function()
		{
			if (!isPlaying)
			{
				if (options['cycleclicks'])
				{
					_this.find(".next").show();
					_this.find(".previous").show();
					return;
				}
				if (imageOn==0)
				{
					_this.find(".previous").hide();
				}
				else
				{
					_this.find(".previous").show();
				}
				if (imageOn==(options['images'].length-1))
				{
					_this.find(".next").hide();
				}
				else
				{
					_this.find(".next").show();
				}
			}
			else
			{
				if (options['cycleslideshow'])
				{
					_this.find(".next").show();
					_this.find(".previous").show();
					return;
				}
				if (imageOn==0)
				{
					_this.find(".previous").hide();
				}
				else
				{
					_this.find(".previous").show();
				}
				if (imageOn==(options['images'].length-1))
				{
					_this.find(".next").hide();
				}
				else
				{
					_this.find(".next").show();
				}
			}
		},
		
		this.start=function()
		{
			if (options['resetslideshow'])
			{
				if (imageOn!=0)
				{
					imageOn=-1;
				}
			}
			isPlaying=true;
			_this.find(".play").hide();
			_this.find(".pause").show();
			timer=setTimeout(_this.onPlayTimeout, options['interval']);
			this.updateControlButtonsVisibility();
		},
		
		this.onPlayTimeout=function()
		{
			_this.next();
		}
		
		this.stop=function()
		{
			if (timer)
			{
				clearTimeout(timer);
				timer=null;
			}
			isPlaying=false;
			_this.find(".play").show();
			_this.find(".pause").hide();
			this.updateControlButtonsVisibility();
		},

		this.next=function()
		{
			imageOn++;
			if (imageOn==(options['images'].length))
			{
				if (!options['cycleslideshow'])
				{
					this.stop();
				}
				imageOn=0;
			}
			this.updateControlButtonsVisibility();
			this.update();
		},

		this.previous=function()
		{
			imageOn--;
			if (imageOn<0)
			{
				imageOn=(options['images'].length)-1;
			}
			this.updateControlButtonsVisibility();
			this.update();
		},
		
		this.showLoading=function()
		{
			if (options['showloading'])
			{
//				_this.find(".associate_me_content_loading_container").show();
			}
		},
		
		this.hideLoading=function()
		{
			if (options['showloading'])
			{
//				_this.find(".associate_me_content_loading_container").hide();
			}
		},
		
		this.appear=function(imageObject)
		{
			transitions=["fade","slideup","slidedown","slideleft","slideright","shrink","grow"];
			slideTransitions=["slideup","slidedown","slideleft","slideright"];
			scaleTransitions=["shrink","grow"];
			appear=options['appear']
			
			if (appear=='random')
			{
				appear=transitions[Math.floor(Math.random()*transitions.length)];
				while (lastRandomAppear==appear)
				{
					appear=transitions[Math.floor(Math.random()*transitions.length)];
				}
				lastRandomAppear=appear;
			}
			if (appear=='randomslide')
			{
				appear=slideTransitions[Math.floor(Math.random()*slideTransitions.length)];
				while (lastRandomAppear==appear)
				{
					appear=slideTransitions[Math.floor(Math.random()*slideTransitions.length)];
				}
				lastRandomAppear=appear;
			}
			if (appear=='randomscale')
			{
				appear=scaleTransitions[Math.floor(Math.random()*scaleTransitions.length)];
			}
			
			
			if (appear=='fade')
			{
				_this.find("#frame"+frameOn).fadeIn(1000);
			}
			if (appear=='slideup')
			{
				_this.find("#frame"+frameOn).css("top",height+"px");
				_this.find("#frame"+frameOn).show();
				_this.find("#frame"+frameOn).animate({ 
				        top: "0px"
				      }, 500 );
			}
			if (appear=='slidedown')
			{
				_this.find("#frame"+frameOn).css("top",0-height+"px");
				_this.find("#frame"+frameOn).show();
				_this.find("#frame"+frameOn).animate({ 
				        top: "0px"
				      }, 500 );
			}
			if (appear=='slideright')
			{
				_this.find("#frame"+frameOn).css("left",0-width+"px");
				_this.find("#frame"+frameOn).show();
				_this.find("#frame"+frameOn).animate({ 
				        left: "0px"
				      }, 500 );
			}
			if (appear=='slideleft')
			{
				_this.find("#frame"+frameOn).css("left",width+"px");
				_this.find("#frame"+frameOn).show();
				_this.find("#frame"+frameOn).animate({ 
				        left: "0px"
				      }, 500 );
			}
			if (appear=='grow')
			{
				imgWidth=parseInt(imageObject.width);
				imgHeight=parseInt(imageObject.height);

				imageObject=$(imageObject);
				
				startImgWidth=imgWidth*4;
				startImgHeight=imgHeight*4;
				imageObject.css("width",(startImgWidth)+"px");
				imageObject.css("height",(startImgHeight)+"px");

				imageObject.css("marginLeft",0-(startImgWidth/2) + "px");
				imageObject.css("marginTop",0-(startImgHeight/2) + "px");

				_this.find("#frame"+frameOn).show();


				imageObject.animate({ 
				        width: imgWidth+"px",
				        height: imgHeight+"px",
						marginLeft: 0-(imgWidth/2) + "px",
						marginTop: 0-(imgHeight/2) + "px"
				      }, 500 );
				
			}
			if (appear=='shrink')
			{
				imgWidth=parseInt(imageObject.width);
				imgHeight=parseInt(imageObject.height);

				imageObject=$(imageObject);
				
				startImgWidth=imgWidth/4;
				startImgHeight=imgHeight/4;
				imageObject.css("width",(startImgWidth)+"px");
				imageObject.css("height",(startImgHeight)+"px");

				imageObject.css("marginLeft",0-(startImgWidth/2) + "px");
				imageObject.css("marginTop",0-(startImgHeight/2) + "px");

				_this.find("#frame"+frameOn).show();


				imageObject.animate({ 
				        width: imgWidth+"px",
				        height: imgHeight+"px",
						marginLeft: 0-(imgWidth/2) + "px",
						marginTop: 0-(imgHeight/2) + "px"
				      }, 500 );
				
			}
		},
		
		this.applyImageAttrs=function(imageObject, image)
		{
			$(imageObject).attr('src', url + "?" + options['stamp'] + "_" + tmpNumber);
			tmpNumber++;
			$(imageObject).attr('title', image['title']);
			if (image['href'])
			{
				$(imageObject).css('cursor', 'pointer');
				$(imageObject).click(function(e)
				{
					window.open(image['href']);
				});
			}
		},
		
		this.update=function()
		{
			if (timer)
			{
				clearTimeout(timer);
				timer=null;
			}
			
			frameOn++;
			if (frameOn==3)
			{
				frameOn=1;
			}
			if (frameOn==1)
			{
				_this.find("#frame1").css("z-index",2);
				_this.find("#frame2").css("z-index",1);
			}
			if (frameOn==2)
			{
				_this.find("#frame2").css("z-index",2);
				_this.find("#frame1").css("z-index",1);
			}
			image=options['images'][imageOn];
			if (image['src'].substr(0,7)=="http://")
			{
				url=image['src'];
			}
			else
			{
				url="/galleries/" + options['name'] + "/" + image['src'];
			}
			_this.find("#frame"+frameOn).html("");
			if ((!images[imageOn]) || (options['alwaysload']))
			{
				images[imageOn]=null;
				this.showLoading();
				imageObject=new Image();
				_this.applyImageAttrs(imageObject, image);
				images[imageOn]=imageObject;
				_this.find("#frame"+frameOn).hide();
				
				
				
				$(imageObject).load(function()
				{
					setTimeout(_this.hideLoading, 750);
					if (this.width)
					{
						width=parseInt(this.width);
						height=parseInt(this.height);
						$(this).css("position","absolute");
						$(this).css("left","50%");
						$(this).css("top","50%");
						$(this).css("margin-left", 0-(width/2)+"px");
						$(this).css("margin-top", 0-(height/2)+"px");
					}
					_this.find("#frame"+frameOn).html(this);
					_this.appear(imageObject);
					if (isPlaying)
					{
						timer=setTimeout(_this.onPlayTimeout, options['interval']);
					}
				}),
				$(imageObject).error(function()
				{
					_this.hideLoading();
					_this.find("#frame"+frameOn).html("<div style='width:100%;height:100%;background-color:#202020;color:#ffffff;text-align:center;'><br />Image could not be loaded. " + imageObject.src + "</div>");
					_this.appear($(imageObject));
					if (isPlaying)
					{
						timer=setTimeout(_this.onPlayTimeout, options['interval']);
					}
					images[imageOn]=null;
				})
			}
			else
			{
				imageObject=images[imageOn];
				_this.applyImageAttrs(images[imageOn], image);
				_this.find("#frame"+frameOn).hide();
				_this.find("#frame" + frameOn).html(images[imageOn]);
//				_this.find("#frame"+frameOn).fadeIn(1000);
				_this.appear(imageObject);
				if (isPlaying)
				{
					timer=setTimeout(_this.onPlayTimeout, options['interval']);
				}
			}
			
		}
		
		this.next();
		if (options['autoplay'])
		{
			this.start();
		}
		this.updateControlButtonsVisibility();
	}
	
})(jQuery);
