(function($) {
	var isTouchDeviceVar = false;

	function isTouchDevice() {
	   var el = document.createElement('div');
	   el.setAttribute('ongesturestart', 'return;');
	   if(typeof el.ongesturestart == "function" || window.touch){
	      return true;
	   }else {
	      return false
	   }
	}
	
	$.fn.flashGallery = function( options ) {
		var objs = this;

		var defaults = {
			fadeTime: 1000,
			pauseTime : 6000,
			panZoom: false
		};

		options = $.fn.extend(defaults, options);

		// Setting behavior on mousemove
		var mouse = function(){
			this.left = 0;
			this.top = 0;
		}
		if (!document.all) document.captureEvents(Event.MOUSEMOVE);

		$(document).mousemove(function getMouseXY(e) {
		  if (document.all) {
			mouse.left = event.clientX + document.body.scrollLeft;
			mouse.top = event.clientY + document.body.scrollTop;
		  } else {  
			mouse.left = e.pageX;
			mouse.top = e.pageY;
		  }  
		  
		  if (mouse.left < 0){mouse.left = 0};
		  if (mouse.top < 0){mouse.top = 0};

		  $(window).trigger('hintmove');
		  
		  return true;
		});

		/*
			The function that kills everything
			@ level : a number representing the
					  timing of the error
		*/
		function gError( level, message ) {
			if( typeof(console) !== 'undefined' && console != null ) {
				var consoleMessage = "Flash Gallery Error on level " + level;
				if( typeof(message) != 'undefined' ) {
					consoleMessage += ": " + message;
				}
				console.log(consoleMessage);
			}
			return false;
		}

		/*
			Check if a XML document is provided
		*/
		if( typeof(options.xmlPath) == 'undefined' ) {
			if( typeof(console) ) {
				gError(1, "You must provide xml for the slider!");
				return this;
			}
		}

		/*
			Load the xml and do all the stuff 
			in the callback
		*/
		$.ajax({
			url:  options.xmlPath,
			error: function(jqXHR, textStatus, errorThrown) {
				gError(2, "AJAX Error, " + errorThrown)
			},
			success: function(data) {
				var $album = $(data).find("gallery > album");
				if( !$album.size() ) {
					return gError(3, 'There\'s no album element in the XML document!');
				}

				// Prepare items
				var items = new Array();
				$album.find("img").each(function() {
					items.push({
						src:   'http://mkeinsulationtrip.com/slideshowpro/p.php?a=' + $(this).attr("src"),
						thumb: 'http://mkeinsulationtrip.com/slideshowpro/p.php?a=' + $(this).attr("tn")
					});
				});

				if( !items.length ) {
					return gError(4, 'The XML document is fine, but it contains no images!');
				}

				objs.each(function() {
					var $obj = $(this);

					if( $(this).data("slideShowAdded") == 'yep' ) return this;

					$(this).data("slideShowAdded", 'yep');

					// Create thumbnails
					$(".thumbs-center").append("<ul />");
					var $thumbs = $(".thumbs ul", this);
					for(i=0; i<items.length; i++) {
						html = '<li><a href="#">';
						html += typeof(items[i].thumb) != 'undefined' ? '<img src="' + items[i].thumb + '" alt="" />' : '<em>' + (i+1) + '</em>';
						html += '</a>';
						if( typeof(items[i].thumb) != 'undefined' ) {
							html += '<span class="bubble"><span><img src="' + items[i].thumb + '" alt="" /></span></span>';
						}
						html += '</li>';

						$thumbs.append(html);
					}


					// Hover effect on buttons
					$obj.find(".ctrl").hover(function() {
						$(this).find("span").stop(true,true).animate({
							opacity: 1
						}, "fast");
					}, function() {
						$(this).find("span").stop(true,true).animate({
							opacity: 0
						}, "fast");
					});

					// Show/hide controls
					var ctrlsTimeout;
					$obj.hover(function() {
						clearTimeout(ctrlsTimeout);
						$(this).find(".controls").stop(true, true).animate({
							bottom: 0,
							avoidTransforms: true,
							opacity: 1
						}, {
							duration: 300
						});
					}, function() {
						ctrlsTimeout = setTimeout(function() {
							$obj.find(".controls").stop(true, true).animate({
								bottom: -30,
								opacity: 0.3,
								avoidTransforms: true
							})
						}, {
							duration: 300
						});
					});

					// Bubbles
					var bubbleTimeout;
					if( !isTouchDevice() ) {
						$thumbs.children("li").hover(function() {
							var $b = $('.bubble', this);
							clearTimeout(bubbleTimeout);
							bubbleTimeout = setTimeout(function() {
								$b.show();
								$("span", $b).stop(true,true).animate({
									width: 100,
									height: 60,
									left:  -44
								}, 500, function() {
									$("img", this).stop(true, true).animate({
										opacity: 1
									})
								});
							}, 200);
						}, function() {
							clearTimeout(bubbleTimeout);
							$(".bubble span", this).stop(true,true).css({
								width: 10,
								height: 0,
								left:   3
							});
							$(".bubble img", this).stop(true,true).css({
								opacity: 0
							});
							$(".bubble", this).hide();
						});
					}

					// Center thumbs
					$thumbs.css({
						width: $thumbs.width(),
						float: 'none'
					});
					
					// Apply hints
					var $hint = $(".hint", this);
					var movementEnabled = false;
					var hintTimeout;
					$(".hintable", $obj).each(function() {

						$(this).data("title", $(this).attr("title"));
						$(this).attr("title", "");

						$(this).hover(function() {
							if( isTouchDeviceVar ) return false;

							$hint.find(".text").text( $(this).data('title') );
							//$hint.appendTo(this);

							clearTimeout(hintTimeout);

							$hint.stop(true, true).animate({
								opacity: 1,
								avoidTransforms: true
							});

							movementEnabled = true;
						}, function() {
							clearTimeout(hintTimeout);
							hintTimeout = setTimeout(function() {
								$hint.stop(true).animate({
									opacity: 0,
									avoidTransforms: true
								})

								movementEnabled = false;
							}, 100);
						});
					});

					$hint.hover(function() {
						clearTimeout(hintTimeout);
					}, function() {
						hintTimeout = setTimeout(function() {
							$hint.stop(true).animate({
								opacity: 0
							});
						}, 100);
					});

					// Enable moving of the mouse
					$(window).bind('hintmove', function() {
						var newLeft, newTop;
						if( movementEnabled ) {
							newLeft = mouse.left - $hint.parent().offset().left - $hint.width()/2;
							newTop = mouse.top  - $hint.parent().offset().top - 30;

							if(newLeft < 0)
								newLeft = 0;
							else if (newLeft + $hint.width() > $hint.parent().width())
								newLeft = $hint.parent().width() - $hint.width();

							$hint.stop(true,true).animate({
								left: newLeft,
								top:  newTop,
								avoidTransforms: true
							})
						}						
					});

					// Create items
					var $holder = $(".holder", this);
					for(i=0; i<items.length; i++) {
						html = '<img src="' + items[i].src + '" class="s-item" alt="" style="image-rendering: optimizeSpeed" />'

						$holder.append(html);
					}

					// Changing function
					var autoTimeout, timeoutEnabled = true;

					function displaySlide( $new, first ) {
						first = typeof(first) != 'undefined' ? first: false;
						var $old = $activeSlide;

						var rand = Math.round( Math.random() * 100 ) % 2 == 0;
						var zoomed = { width: $obj.width() * 105 / 100 };
						var normal = { width: $obj.width() };

						$holder.find(".s-item").stop(true);
						clearTimeout(autoTimeout);

						$old.siblings(":not(:animated)").hide();

						$old.css({
							zIndex: 2
						}).siblings().css({
							zIndex: 1
						});

						$new.show();

						if(!first) {
							$new.css({
								'-webkit-transition' : 'all 0s linear',
								zIndex: 3,
								opacity: 0,
								'-webkit-transform': rand ? 'scale(1)' : 'scale(1.2)'
							});
						}

						if( options.panZoom ) {
							$new.css( rand ? zoomed: normal );
						}

						if( $.browser.webkit ) {
							$new.css({
								
							});
						} else {
							$new.animate({ opacity: 1 }, options.fadeTime);
						}

						if( options.panZoom ) {
							if( $.browser.webkit ) {
								newcss = rand ? normal : zoomed;

								$new.css("opacity");
								$new.css({
									opacity: 1,
									'-webkit-transform': rand ? 'scale(1.2)' : 'scale(1)',
									'-webkit-transition': 'opacity ' + (options.fadeTime/1000) + 's ease-in, -webkit-transform ' + (options.pauseTime/1000) + 's ease-in',
								});
							} else {
								$new.animate( 
									rand ? normal : zoomed,
									{
										queue: false,
										duration: options.pauseTime + options.fadeTime
									}
								);
							}
						}

						$activeSlide = $new;
						
						if( timeoutEnabled ) {
							autoTimeout = setTimeout(function() {
								$obj.trigger('nextSlide');
							}, options.fadeTime + options.pauseTime);
						}
					}

					var $activeSlide = $holder.find(".s-item:eq(0)");
					displaySlide( $activeSlide, true );

					// Actions
					$obj.bind('nextSlide', function() {
						var $nextSlide = $activeSlide.next().size() ? $activeSlide.next() : $holder.find(".s-item:eq(0)");
						displaySlide( $nextSlide );
					});

					$obj.bind('prevSlide', function() {
						var $nextSlide = $activeSlide.prev().size() ? $activeSlide.prev() : $holder.find(".s-item:last");
						displaySlide( $nextSlide );						
					});

					$obj.bind('toggleSlide', function() {
						if( timeoutEnabled ) {
							timeoutEnabled = false;
							clearTimeout(autoTimeout);
							$(".ctrl-play", $obj).removeClass("ctrl-pause");
							$activeSlide.css({
								'-webkit-animation-fill-mode': 'forwards'
							}).stop(true);
						} else {
							timeoutEnabled = true;
							$obj.trigger('nextSlide');
							$(".ctrl-play", $obj).addClass("ctrl-pause");
						}
					});

					$(".ctrl", $obj).click(function() {
						$(this).is(".ctrl-prev") && $obj.trigger('prevSlide');
						$(this).is(".ctrl-next") && $obj.trigger('nextSlide');
						$(this).is(".ctrl-play") && $obj.trigger('toggleSlide');

						return false;
					});

					$(".overlay", $obj).click(function() {
						$(this).is(".overlay-prev") ? $obj.trigger('prevSlide') : $obj.trigger('nextSlide');
						return false;
					});

					$thumbs.find("a").click(function() {
						var $nextSlide = $holder.find(".s-item").eq( $(this).parent().index() );
						displaySlide( $nextSlide );
						return false;
					});
				});

			}
		});

		function touchStart() {
			$(".thumbs .bubble").remove();
			isTouchDeviceVar = true;
		}
        document.getElementsByTagName('body')[0].addEventListener("touchstart", touchStart, false);


		return this;
	}
})(jQuery);
