$.flashVersion = function() {
	var version = [0, 0, 0];

   if (navigator.plugins && navigator.mimeTypes.length) {
		var plugin = navigator.plugins["Shockwave Flash"];

		if (plugin && plugin.description) {
			version = plugin.description.split(" ");
			version = version[2] + '.' + String(version[4]).slice(1);
			version = version.split(".");
		}
	}
	else {
		try {
			var plugin = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			for (var i = 3; plugin != null; i++) { plugin = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i); }
			i--;
		}
		catch(error) { }

		if (i == 6) {
      	version = new Array(6, 0, 0);
		}
      else if (i > 2) {
			try { var version = plugin.GetVariable("$version").split(" ")[1].split(","); }
			catch(error) { }
		}
	}

	return new Array(parseInt(version[0]), parseInt(version[1]), parseInt(version[2]));
}


$.userAgent = String(navigator.userAgent).toLowerCase();
$.browser.iphone = ($.userAgent.indexOf('iphone') !== -1);
$.browser.ipad = ($.userAgent.indexOf('ipad') !== -1);


$.extend({
	delegate: function(fn, thisObject) {
      var parameters = Array.prototype.slice.call(arguments).slice(2);
 
      return function() {
         return fn.apply(thisObject || this, parameters.concat(Array.prototype.slice.call(arguments)));
      };
	}
});


$.email = function($value) {
	return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test($value);						
}


$.popup = function(url, width, height, scrolling)
{
	if (scrolling == undefined) scrolling = 0;

	var x = (screen.width / 2) - (width / 2);
	var y = (screen.height / 2) - (height / 2);
	var properties = "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=" + scrolling + ",resizable=0,width=" + width + ",height=" + height + ",top=" + y + ",left=" + x;
	var popup;

	popup = window.open(url, 'default', properties);
	popup.focus();
}


$.widget('ui.video', {

	_init: function() {
		var value = this.options.value;
		
		if (!value) value = this.element.attr('rel');
		if (!value) return;

		var extension = String(value).split('.').pop().toLowerCase();
		var type;
		var info;
		var flash;
		var url;
		var html;

		if (value.indexOf('youtube.com') !== -1) type = 'youtube';
		else if (value.indexOf('vimeo.com') !== -1) type = 'vimeo';
		
		info = $.url.parse(value);

      if (type || $.inArray(extension, ['flv', 'f4v']) != -1) {
			if ($.flashVersion()[0] >= 7) {
				switch (type) {
					case 'youtube': url = 'http://www.youtube.com/v/' + info.params.v + '&hl=en_US&fs=1&'; break;
					case 'vimeo': url = "http://vimeo.com/moogaloop.swf?clip_id=" + info.directory.slice(1) +"&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=ffee00&amp;fullscreen=1"; break;
					default: url = this.options.player;
				}

				flash = new SWFObject(url, null, '100%', '100%', '8', '#d4d4d4');
				flash.addParam('allowScriptAccess', 'always');
				flash.addParam('allowFullScreen', 'true');
				flash.addParam('wmode', 'transparent');
				flash.addVariable('url', value);
				flash.write(this.element[0]);
			}
			else {
				switch (type) {
					case 'youtube': html = "<object width=\"100%\" height=\"100%\"><param name=\"movie\" value=\"" + value + "\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"" + value + "\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"100%\" height=\"100%\"></embed></object>"; break;
					case 'vimeo': html = "<video src=\"http://www.vimeo.com/play_redirect?clip_id=" + info.directory.slice(1) + ($.browser.iphone ? "&quality=" : "") + "\" controls=\"controls\" preload=\"preload\" width=\"000\" height=\"000\"></video>"; break;
				}
	
				this.element.html(html);
			}
		}
	}

});


$.widget('ui.gallery', {

	_init: function() {
   	var data = this.options.data;
      var value;
      var extension;
		var index;
		var $button;

		this.flash = ($.flashVersion()[0] >= 7);
      this.viewer = this.element.find('.viewer ul');
      if (this.viewer.length == 0) this.viewer = this.element.find('.viewer');
		if (this.viewer.length == 0) this.viewer = this.element;

		this.viewer.show();
		this.duration = (this.options.duration ? this.options.duration : 3000);
		this.buttons = this.element.find('.pagination a');
		
		for (var i = 0; i < this.buttons.length; i++) {
			$button = this.buttons.eq(i);
			index = parseInt($button.attr('rel'), 10);
			if (index == 0) index = this.buttons.index($button) + 1;
			$button.attr('rel', index);
		}

		this.buttons.unbind().bind('click', this, function(event) {
      	event.data.change(parseInt($(this).attr('rel'), 10));
      });
		
		i = 0;

      if (data == null) {
      	data = [];

         if (this.viewer.filter('ul').length > 0) {
            this.element.find('li').each(function() {
            	data.push($('<div />').append(this).html());
            });
         }
         else {
            this.viewer.find('img').each(function() {
               data.push($(this).attr('rel'));
            });

            while (i < data.length) {
					extension = String(data[i]).split('.').pop().toLowerCase();
               
               if (!this.flash && $.inArray(extension, ['flv', 'f4v']) != -1) {
                  data.splice(i, 1);
               } 
               else {
                  i++;
               }
            }
			}
      }

		this.data = data;
		this.viewer.html('');
      this.enabled = true;
      
		if (this.data.length > 0) this.change(1);
	},
   
   
   play: function() {
   	this.pause();
   	this.interval = setInterval($.delegate(this.change, this, '1'), this.duration);
   },


   pause: function() {
   	if (this.interval == null) return;
   	clearInterval(this.interval);
      this.interval = null;
   },


	change: function(offset) {
		if (!this.enabled) return;

		var data = this.data;
		var index = Number(this.index);

		switch (offset) {
			case '-1': index = (index == 1 ? data.length : index - 1); break;
			case '1': index = (index == data.length ? 1 : index + 1); break;
			default: index = offset;	
		}

		if (index == this.index) return;
		if (this.container) {
			this.container.find('img').stop(true);
			this.containerOld = this.container;
			this.container = null;	
		}

		this.indexOld = this.index;
		this.index = index;
		this.buttons.removeClass('active').filter('[rel=' + index + ']').addClass('active');
      this.pause();
		this.load();
		
		if (this.options.change) this.options.change(this.index);
	},


	load: function() {
     	var value = this.data[this.index - 1];
		var extension = String(value).split('.').pop().toLowerCase();
      var html;
      var $items;
      var $item;
      var $image;
		var $video;

		if ($.inArray(extension, ['png', 'gif', 'jpg', 'jpeg']) != -1) {
			html = "<img src=\"" + escape(value) + "\" style=\"position: absolute; z-index: 1;\" />";
		}
		else if ($.inArray(extension, ['flv', 'f4v']) != -1) {
			html = "<div class=\"video\" rel=\"" + escape(value) + "\"></div>";
		}
		else {
			html = value;
		}

		this.viewer.append(html);
		$items = this.viewer.find('> *');
		$item = $items.filter(':last');

		if ($item.filter('img').length > 0) $image = $item;
		else $image = $item.find('img:first');
		
		this.type = null;

		if ($image.length > 0) {
			$item.fadeTo(0, 0);
			$image.fadeTo(0, 0);
			$image.load($.delegate(this.imageLoad, this, $items, $item, $image));
			
			if (this.options.click) {
				$image.click($.delegate(this.click, this));	
			}
			
			this.type = 'image';
			this.enabled = false;
		}

		if ($item.filter('.video').length > 0) $video = $item;
		else $video = $item.find('.video:first');

		if ($video.length > 0) {
			$video.video({ player: this.options.player });
			this.type = 'video';
			this.container = $item;
			this.complete();
		}
	},


	click: function() {
		this.options.click.apply(this.element[0]);
	},
	
	
	mode: function() { return this.type; },


   imageLoad: function($items, $item, $image) {
   	var callback = $.delegate(this.fadeComplete, this, $items, $item, $image);
		
		this.container = $item;

		$item.fadeTo(0, 1);

		switch (this.options.transition) {
			case 'slide':
			
				var direction = (this.indexOld > this.index ? 'left' : 'right');
			
				if (!this.indexOld) {
					$image.fadeTo(1000, 1, callback);
				}
				else {
					$image.fadeTo(0, 1);

					if (this.containerOld) {
						this.containerOld.animate({ marginLeft: ((direction == 'left' ? 1 : -1) * this.viewer.width()) + 'px' }, { duration: 1000 });
					}

					$item.css('margin-left', ((direction == 'left' ? -1 : 1) * this.viewer.width()) + 'px');
					$item.animate({ marginLeft: 0 }, { duration: 1000, complete: callback });
				}

				break;
				
			default:
			
				$image.fadeTo(1000, 1, callback);
			
				break;
		}

		this.animate(false);
		this.animate(true);
		
		if (!this.preload) {
			this.preload = true;
			this.backgroundLoad(1);
		}
		
		this.complete();
   },


	complete: function() {
		this.enabled = true;
		if (this.options.show) $.delegate(this.options.show, this, this.index)();
	},
	
	
	backgroundLoad: function(index) {
		var $image;

		if (index > this.data.length) {
			this.backgroundContainer.html('');	
			return;
		}

		if (!this.backgroundContainer) {
			$('body').prepend("<div class=\"background-container\" style=\"position: absolute; z-index: 10; left:-4000px;\"></div>");
			this.backgroundContainer = $('.background-container:first');
		}
		
		this.backgroundContainer.html(this.data[index - 1]);
		$image = this.backgroundContainer.find('img:first');

		if ($image.length == 0) {
			this.backgroundLoad(index + 1);
		}
		else {
			$image.load($.delegate(this.backgroundLoad, this, index + 1));
		}
	},

   
   fadeComplete: function($items, $item, $image) {
      $item.css('opacity', '').css('filter', '');
		$image.css('opacity', '').css('filter', '');
		
		if ($items.length > 1) {
			$items.not(':last').find('embed, object').remove();
			$items.not(':last').remove();
		}

		if (this.buttons.length == 0) this.play();

		this.complete();
   },


	animate: function(animate) {
		if (!this.options.animate) return;

		var $image = this.container.find('img');

		if ($image.length == 0 || $image.width() <= this.container.width()) return;

		$image.css('margin-top', -Math.round(($image.height() - this.container.height()) / 2) + 'px');
		$image.css('margin-left', -Math.round(($image.width() - this.container.width()) / 2) + 'px');

		if (!animate) return;

		$image.animate({ 'margin-left': 0 }, { duration: this.duration + 500, easing: 'easeInOutSine' });
	}

});

$.ui.gallery.getter = 'mode';
