(function () {

// Pull widget options from data attribute
$.Widget.prototype._getCreateOptions = function () {
	return this.element.data(this.widgetName+'-options');
}

$.widget('ui.gallery', {
	_move_to: function (page) {
		if ( ! page.size() ) { return; }
		if ( page.is(this.current_page) ) { return; }

		var direction = this.pages.index(page) > this.pages.index(this.current_page) ? -1 : 1;
		var w = this.element.width();

		this.current_page.animate({
			marginLeft: w * direction,
			opacity : 0
		}, this.transitionSpeed);

		page.show()
			.css('margin-left', -w * direction)
			//.animate({ marginLeft: -w * direction }, 0)
			.animate({ opacity: 1, marginLeft: '0px' }, this.transitionSpeed);
		this.current_page = page;

		this.redraw();
	},
	_open: function (id) {
		var product = $('#'+id);
		if ( ! product.size() ) { return; }

		var page = product.closest('.gallery_page');
		this._move_to(page);

		$("#modal_container").modal({
			content: this.options.get_href(product)
		});
	},
	_create: function () {
		var _self = this;
		var pages = this.element.find('.gallery_page');
		var pagination = this.element.find('.gallery_pagination');
		var pagination_items = this.element.find('.gallery_pagination li');

		this.current_page = pages.eq(0);
		this.next = this.element.find('.gallery_next');
		this.pages = pages;
		this.pagination_items = pagination_items;
		this.prev = this.element.find('.gallery_prev');
		this.transitionSpeed = this.options.transitionSpeed || 800;

		this.pages.slice(1).hide();

		if ( pages.size() ) {
			//this.element.attr('tabIndex', 0).css('outline', 0);
			//this.element.bind('keydown', function (ev) {
			//	if ( $(ev.target).is(':input') ) { return; }
			//	if ( ev.keyCode === $.ui.keyCode.LEFT ) {
			//		_self.go_prev();
			//	} else if ( ev.keyCode === $.ui.keyCode.RIGHT ) {
			//		_self.go_next();
			//	}
			//});
			this.next.click(function (ev) {
				_self.go_next();
			});
			this.prev.click(function (ev) {
				_self.go_prev();
			});
			pagination.delegate('li', 'click', function (ev) {
				var index = pagination_items.index(ev.target);
				var page = pages.eq(index);
				_self._move_to(page);
			});
		} else {
			pagination.hide();
		}

		if ( this.options.deeplink ) {
			this._open(this.options.deeplink);
		}
	},
	_init: function () {
		//if ( this.pages.size() ) {
		//	this.element.focus();
		//}
		this.redraw();
	},
	redraw: function () {
		this.element.animate({ 'padding-top': this.current_page.height() });
		if ( this.current_page.prev('.gallery_page').size() ) {
			this.prev.show();
		} else {
			this.prev.hide();
		}
		if ( this.current_page.next('.gallery_page').size() ) {
			this.next.show();
		} else {
			this.next.hide();
		}
		var i = this.pages.index(this.current_page);
		this.pagination_items.removeClass('selected');
		this.pagination_items.eq(i).addClass('selected');
	},
	go_prev: function () {
		this._move_to( this.current_page.prev('.gallery_page') );
	},
	go_next: function () {
		this._move_to( this.current_page.next('.gallery_page') );
	}
});

function create_overlay(zIndex) {
	var overlay = $('<div class="fade"></div>').appendTo('body');
	if ( zIndex ) {
		overlay.css('zIndex', zIndex);
	}
	return overlay;
}

$.widget("ui.modal", {
	options: {
		hidden: true
	},
	_create: function() {
		var self = this;
		this.element.appendTo($('body'));
		this.element.attr('tabIndex', 0).css('outline', 0); // pour recevoir le focus
		this.element.bind('keydown', function (ev) {
			if ( ev.keyCode === $.ui.keyCode.ESCAPE ) {
				self.close();
			}
		});
	},
	_init: function () {
		var self = this;

		if ( ! this.options.content ) {
			throw 'Fuck off!';
		}

		if ( this.options.hidden ) {
			this.element.hide();
		}
		this.element.load(this.options.content, function () {
			// Initialisation des widgets inclus
			// L'élément doit être affiché (display !== none)
			self.element.css('visibility', 'hidden').show(); // cache et affiche (ce n'est pas contradictoire, et ouais !)
			cailles.init_widgets(self.element.children());
			self.element.hide().css('visibility', ''); // retour à l'état précédent

			self.open();
		});
	},
	open: function (callback) {
		var self = this;
		this.overlay = create_overlay().click(function () {
			self.close();
		})
		this.overlay.fadeIn();
		this.element.fadeIn();
		this.center(); // nécessite que l'élément soit affiché, c'est bon on est après le fadeIn
		this.element.focus();
	},
	center: function () {
		var left, top;

		if ( this.element.is(':hidden') ) { return; }

		var h = this.element.height();
		var w = this.element.width();
		var win_h = $(window).height();
		var win_w = $(window).width();

		if ( win_h <= h ) {
			top = $(window).scrollTop();
		} else {
			top = ( win_h-h ) / 2 + $(window).scrollTop();
		}
		if ( win_w <= w ) {
			left = $(window).scrollLeft();
		} else {
			left = ( win_w-w ) / 2 + $(window).scrollLeft();
		}

		this.element.css({ 'top': top, 'left': left });
	},
	close: function() {
		this.element.fadeOut().empty();
		this.overlay.remove();
	},
	destroy: function() {
		$.Widget.prototype.destroy.apply(this, arguments); // default destroy
	}
});

$.widget('ui.editable', {
	_create: function () {
		var self = this;

		this.editing = false;

		if ( ! this._get_text() ) {
			this.element.text('(texte à éditer)');
		}
		this.element.addClass('editable');
		this.element.click($.proxy(this, '_edit'));

		var element_edit = $('<textarea></textarea>').css({
			'width': '100%',
			'margin': '0',
			'padding': '0',
			'background': 'none',
			'border': 'none',
			'box-shadow': '0 0 6px #FF5E99',
			'color': 'inherit',
			'font-family': 'inherit',
			'font-size': 'inherit',
			'font-style': 'inherit',
			'font-weight': 'inherit',
			'outline': 'none',
			'overflow': 'hidden',
			'resize': 'none',
			'text-decoration': 'inherit'
		});
		element_edit.bind({
			blur: function (ev, cancel) {
				self._blur(ev, cancel);
			},
			keydown: function (ev) {
				if ( ev.keyCode === $.ui.keyCode.ESCAPE ) {
					$(this).trigger('blur', [ true ]);
				}
			}
		});
		element_edit.bind( 'change cut keydown paste', $.proxy(this, '_resize_delay') );
		this.element_edit = element_edit;
	},
	_get_text: function () {
		var res = [];

		var prev = null;
		this.element.contents().each(function () {
			if ( this.nodeType === 3 && prev === 3) { res.push(' '); }
			res.push( $.trim( $(this).text() ) );
			if ( this.nodeType !== 3 ) { res.push('\n'); }
			prev = this.nodeType;
		});

		return $.trim( res.join('') );
	},
	_edit: function () {
		if ( this.editing ) { return; }
		this.editing = true;
		this.__prev_html = this.element.html();

		this.element_edit.val( this._get_text() );
		this.element.removeClass('editable');
		this.element.empty().append(this.element_edit);
		this.element_edit.focus();
		this._resize_delay();
	},
	_resize_delay: function() {
		var self = this;
		setTimeout(function () {
			self.resize(); // detach call to have the updated value
		}, 0);
	},
	resize: function () {
		if ( ! this.editing ) { return; }
		var el = this.element_edit.get(0);
		// Inspiration : http://stackoverflow.com/questions/454202/creating-a-textarea-with-auto-resize/5346855#5346855
		el.style.height = '0';
		el.style.height = el.scrollHeight+'px';
	},
	_blur: function (event, cancel) {
		if ( ! this.editing ) { return; }
		this.editing = false;

		var text = $.trim( this.element_edit.val() );

		// Text to HTML
		var html;
		if ( cancel || ! text ) {
			html = this.__prev_html;
		} else {
			html = text.replace(/\n/g, '<br/>\n');
		}

		this.element_edit.detach(); // Chrome triggers "blur" again here
		this.element.html(html);
		this.element.addClass('editable');

		if ( this.element.html() === this.__prev_html ) {
			return;
		}

		// Store
		var data = {};
		data[ this.element.data('name') ] = text;
		$.get( this.element.data('url'), data );
	}
});

function __func_or_null(opt) {
	if ( typeof opt === 'string' ) {
		try {
			opt = eval(opt);
		} catch (e) {}
	}
	if ( $.isFunction(opt) ) {
		return opt;
	}
	return null;
}

$.widget('ui.form', {
	_create: function () {
		var form = this.element;
		var form_options = {};
		var self = this;

		form.find('.minus[data-name], .plus[data-name]')
			.disableSelection()
			.each(function () {
				var btn = $(this);
				self._qtt_mod(btn, true);
			})
			.click(function (ev) {
				var btn = $(this);
				self._qtt_mod(btn);
			});

		var success = __func_or_null(form.data('success'));
		if ( success ) {
			form_options.success = success;
		}

		form.ajaxForm(form_options);
	},
	_qtt_mod: function (btn, init) {
                        var name = btn.data('name');
                        var qtt = this.element.find('input[name="'+name+'"]');
                        var qtt_min = parseInt(qtt.data('min'), 10) || 0;
                        var qtt_max = parseInt(qtt.data('max'), 10) || Infinity;
                        var v = parseInt(qtt.val(), 10);

			if ( init ) {
							if ( v < qtt_min || v > qtt_max ) {
									throw 'Alors la, non !';
							}
				if ( qtt_min === qtt_max ) {
									btn.hide();
							}
				return;
			}

                        if ( btn.is('.minus') ) {
                                if ( v > qtt_min ) {
                                        v--;
                                        qtt.val(v);
                                }
                        } else {
                                if ( v < qtt_max ) {
                                        v++;
                                        qtt.val(v);
                                }
                        }
	},
	destroy: function () {
		$.Widget.prototype.destroy.apply(this, arguments);
		this.element.find('.minus, .plus').unbind('click');
	}
});

// http://weblog.bocoup.com/using-datatransfer-with-jquery-events
$.event.props.push('dataTransfer');

$(document).bind({
	dragover: function (ev) {
		if ( $(ev.target).is(':file') ) {
			return true;
		}
		return false;
	},
	drop: false
});

var imupload_tpl_floating_form = '<div class="imupload_floating_form">'+
'	<div class="inner">'+
'		<span class="button_file"><button class="button-file" data-button-options=\'{"icons":{"primary":"ui-icon-folder-open"}}\'>Charger...</button><input type="file" /></span>'+
'		<button title="Supprimer" class="button-del" data-button-options=\'{"icons":{"primary":"ui-icon-trash"}}\'>Suppr.</button>'+
'	</div>'+
'</div>';

var imupload_tpl_workspace = '<form class="imupload_form">'+
'	<input name="height" type="hidden" />'+
'	<input name="width" type="hidden" />'+
'	<input name="ratio" type="hidden" />'+
'	<input name="x" type="hidden" />'+
'	<input name="y" type="hidden" />'+
'	<div class="box_container">'+
'		<div class="box"><div class="helper">'+
'			<div class="ui-resizable-handle ui-resizable-nw ui-icon ui-icon-carat-1-nw"></div>'+
'			<div class="ui-resizable-handle ui-resizable-ne ui-icon ui-icon-carat-1-ne"></div>'+
'			<div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-carat-1-se"></div>'+
'			<div class="ui-resizable-handle ui-resizable-sw ui-icon ui-icon-carat-1-sw"></div>'+
'		</div></div>'+
'		<div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-grip-diagonal-se"></div>'+
'	</div>'+
'	<div class="action">'+
'		<span class="bloc">'+
'			<span class="button_file"><button class="button-file" data-button-options=\'{"icons":{"primary":"ui-icon-folder-open"}}\'>Charger...</button><input type="file" /></span>'+
'		</span>'+
'		<span class="bloc">'+
'			<button type="submit">OK</button>'+
'			<button type="reset">Annuler</button>'+
'		</span>'+
'	</div>'+
'</form>';

var imupload_focused_floating_form = null;

$.widget('ui.imupload', {
	_create: function () {
		var self = this;

		var upload_url = this.element.data('url');
		if ( !upload_url ) {
			throw 'Ça ne se passera pas comme ça !';
		}
		this.upload_url = upload_url;

		var __dragenter_el = null;
		this.element.addClass('imupload');
		this.element.bind({
			dragenter: function (ev) {
				if ( ! __dragenter_el ) {
					self.element.addClass('highlight');
				}
				__dragenter_el = ev.target;
			},
			dragover: false,
			dragleave: function (ev) {
				if ( __dragenter_el === ev.target ) {
					__dragenter_el = null;
					self.element.removeClass('highlight');
				}
			},
			drop: function (ev) {
				ev.preventDefault();
				ev.stopPropagation();
				__dragenter_el = null;
				self.element.removeClass('highlight');
				if ( ev.dataTransfer && ev.dataTransfer.files ) {
					self.read(ev.dataTransfer.files);
				}
			}
		});

		this.min_size = 64;

		this._create_floating_form();
		this._create_workspace();
	},
	_create_floating_form: function () {
		var del_timeout = null;
		var form = $(imupload_tpl_floating_form);
		var self = this;

		var buttons = form.find('button').button();
		var btn_del = buttons.filter('.button-del');
		var btn_file = buttons.filter('.button-file');
		form.css('z-index', this.element.zIndex()+1);

		this.element.add(form).hover(function (ev) {
			// OPEN
			__cancel_timer();
			if ( !form.parent().size() ) {
				form.hide().appendTo('body');
				btn_del.toggleClass('hidden', !self.has_image());
				form.show();
				self._focus_floating_form();
			}
			form.position({
				of: self.element,
				my: 'right bottom',
				at: 'right bottom',
				offset: '5 5'
			});

		}, function (ev) {
			// CLOSE
			if ( del_timeout ) {
				return;
			}
			del_timeout = setTimeout(function () {
				del_timeout = null;
				self._blur_floating_form();
			}, 200);
		});
		function __cancel_timer() {
			if ( del_timeout ) {
				clearTimeout(del_timeout);
				del_timeout = null;
			}
		}
		form.bind('close', function() {
			__cancel_timer();
			self._blur_floating_form();
		});

		btn_del.click(function (ev) {
			if ( !self.has_image() ) { return; }
			var choice = confirm('Marre de cette image ?');
			if ( !choice ) { return; }

			$.ajax({
				url: self.upload_url,
				data: { 'delete': 1 },
				dataType: 'json',
				error: function (xhr) {
					alert('Pas fonctionner. Toi devoir taper développeur.');
				},
				success: function (json) {
					for ( var image_class in json ) {
						var images = $('.'+image_class);
						self.set_image_url(null, images);
					}
				}
			});
		});

		this._init_load_file(btn_file);

		this.floating_form = form;
	},
	_focus_floating_form: function () {
		if ( imupload_focused_floating_form && imupload_focused_floating_form !== this.floating_form ) {
			imupload_focused_floating_form.triggerHandler('close');
		}
		imupload_focused_floating_form = this.floating_form;
	},
	_blur_floating_form: function (remove) {
		if ( this.floating_form === imupload_focused_floating_form ) {
			imupload_focused_floating_form = null;
		}
		if ( remove ) {
			this.floating_form.remove();
		} else {
			this.floating_form.detach();
		}
	},
	_init_load_file: function (btn_file) {
		var input_file = btn_file.parent().find('input[type="file"]');
		var self = this;
		input_file.hover(function () {
			btn_file.addClass('ui-state-hover');
		}, function () {
			btn_file.removeClass('ui-state-hover');
		});
		input_file.change(function () {
			self.read(this.files);
			this.value = null;
		});
	},
	_create_workspace: function () {
		var self = this;
		var workspace = $(imupload_tpl_workspace);

		var buttons = workspace.find('button').button();
		var btn_file = buttons.filter('.button-file');
		var btn_submit = buttons.filter('[type="submit"]');
		workspace.css('zIndex', this.element.zIndex()+5);

		workspace.submit(function (ev) {
			ev.preventDefault();

			if ( !self.file ) { return; }
			var form_data = new FormData(this);
			form_data.append('img', self.file);

			buttons.button('disable');
			btn_submit.addClass('waiting');
			$.ajax({
				url: self.upload_url,
				data: form_data,
				dataType: 'json',
				cache: false,
				contentType: false,
				processData: false,
				type: 'post',
				error: function () {
					alert('Pas fonctionner. Toi devoir taper développeur.');
				},
				success: function (json) {
					if ( self.is_image() ) {
						self.set_image_url(json.src);
					} else {
						for ( var image_class in json ) {
							var image_url = json[image_class];
							var images = $('.'+image_class);
							self.set_image_url(image_url, images);
						}
					}
					self.close();
				},
				complete: function () {
					buttons.button('enable');
					btn_submit.removeClass('waiting');
				}
			});
		});
		workspace.bind('reset', function (ev) {
			self.close();
		});

		// Box & helper
		var box_container = workspace.find('.box_container');
		var helper = workspace.find('.helper');

		if ( this.options.resize ) {
			box_container.resizable({
				//alsoResize: helper,
				handles: {
					se: '> .ui-resizable-se'
				},
				minHeight: this.min_size,
				minWidth: this.min_size,
				start: function () { self._start_edit(helper); },
				stop: function () { self._stop_edit(helper); }
			});
		} else {
			box_container.children('.ui-resizable-handle').remove();
		}

		helper.resizable({
			aspectRatio: true,
			handles: {
				nw: '> .ui-resizable-nw',
				ne: '> .ui-resizable-ne',
				se: '> .ui-resizable-se',
				sw: '> .ui-resizable-sw'
			},
			minHeight: this.min_size,
			minWidth: this.min_size,
			start: function () { self._start_edit(helper); },
			stop: function () { self._stop_edit(helper); }
		});
		helper.draggable({
			//snap: '.box',
			//snapMode: 'inner',
			//snapTolerance: 5,
			start: function () { self._start_edit(helper); },
			stop: function () { self._stop_edit(helper); }
		});

		this._init_load_file(btn_file);

		this.workspace = workspace;
	},
	is_image: function () {
		return this.element.is('img');
	},
	has_image: function () {
		if ( this.is_image() ) {
			return this.element.attr('src') !== this.element.data('src');
		} else {
			return !this.element.hasClass('noimage');
		}
	},
	set_image_url: function (url, target) {
		if ( url ) {
			if ( this.is_image() ) {
				this.element.attr('src', url);
			} else {
				target.removeClass('noimage');
				target.css('background-image', 'url('+url+')');
			}
		} else {
			if ( this.is_image() ) {
				this.element.attr( 'src', this.element.data('src') );
			} else {
				target.css('background-image', 'none');
				target.addClass('noimage');
			}
		}
	},
	read: function (files, callback) {
		var self = this;

		if ( ! files.length ) {
			return;
		}

		var file = files[0];
		if ( ! file.type.match(/^image\b/) ) {
			return;
		}
		this.file = file;

		// Loading...
		var reader = new FileReader();
		reader.onload = function (e) {
			var img = new Image();
			img.onload = function (e) {
				self.open(this, true);
			};
			img.src = e.target.result;
		};
		reader.readAsDataURL(file);

		if ( !this.overlay ) {
			var zIndex = parseInt( this.workspace.css('z-index'), 10 );
			this.overlay = create_overlay(zIndex-1).fadeIn();
		}
	},
	open: function (img) {
		var init_workspace = !this.workspace.parent().size(); // detached from the DOM
		var self = this;

		var box_container = this.workspace.find('.box_container');
		var helper = this.workspace.find('.helper');

		// Workspace
		if ( init_workspace ) {
			var offset = this.element.offset();
			this.workspace.appendTo('body');
			this.workspace.css({
				top: offset.top,
				left: offset.left
			});
		}


		var box_container_size;
		if ( this.options.resize ) {
			box_container_size = {
				height: Math.max(this.min_size, this.element.height()),
				width: Math.max(this.min_size, this.element.width())
			};
		} else {
			box_container_size = this._fit_out(
				{ height: this.element.height(), width: this.element.width() },
				{ height: this.min_size, width: this.min_size }
			);
		}
		box_container.css(box_container_size);

		// Helper
		var data_helper = {
			image_height: img.height,
			image_width: img.width
		};
		helper.data(data_helper);
		helper.css({
			width: '100%',
			height: Math.min(img.height, box_container.height()), // ratio will be fixed by __redraw_helper()
			top: 0,
			left: 0
		});
		helper.children('img').remove();
		helper.append(img);

		helper.find('.ui-resizable-handle').css({
			top: '', right: '', bottom: '', left: ''
		});

		// Display
		if ( init_workspace ) {
			this.workspace.fadeIn();
		}
		this._redraw_edit(helper);
	},
	_fit_out: function (src, dst) {
		if ( src.width >= dst.width && src.height >= dst.height ) {
			return src; // nothing to do;
		}
		var ratio_h = src.height / dst.height;
		var ratio_w = src.width / dst.width;
		var fit;
		if ( ratio_h < ratio_w ) {
			fit = {
				height: dst.height,
				width: src.width/ratio_h
			};
		} else {
			fit = {
				height: src.height/ratio_w,
				width: dst.width
			};
		}
		return fit;
	},
	_start_edit: function (helper) {
		helper.find('.ui-resizable-handle').hide();
	},
	_stop_edit: function (helper) {
		this._redraw_edit(helper);
	},
	_redraw_edit: function (helper) {
		var anim = {};
		var helper_height = helper.height();
		var helper_width;
		var parent_height = helper.parent().height();
		var parent_width = helper.parent().width();
		var position = helper.position();

		$('input[name="height"]', this.workspace).val(parent_height);
		$('input[name="width"]', this.workspace).val(parent_width);

		// Fix ratio
		var image_width = helper.data('image_width');
		var image_height = helper.data('image_height');
		helper_width = anim.width = helper_height * image_width / image_height;
		$('input[name="ratio"]', this.workspace).val( helper_height / image_height );

		// Stay inside the container
		if ( position.left < 64 - helper_width ) {
			position.left = anim.left = 64 - helper_width;
		} else if ( position.left > parent_width - 64 ) {
			position.left = anim.left = parent_width - 64;
		}
		if ( position.top < 64 - helper_height ) {
			position.top = anim.top = 64 - helper_height;
		} else if ( position.top > parent_height - 64 ) {
			position.top = anim.top = parent_height - 64;
		}
		$('input[name="x"]', this.workspace).val(position.left);
		$('input[name="y"]', this.workspace).val(position.top);


		helper.stop(true, true);
		helper.animate(anim, 500, 'easeOutExpo');

		// Place handles
		$('.ui-resizable-n, .ui-resizable-ne, .ui-resizable-nw', helper)
			.css('top', Math.max(16, -position.top+16));
		$('.ui-resizable-s, .ui-resizable-se, .ui-resizable-sw', helper)
			.css('bottom', Math.max(16, helper_height+position.top-parent_height+16));
		$('.ui-resizable-e, .ui-resizable-ne, .ui-resizable-se', helper)
			.css('right', Math.max(16, helper_width+position.left-parent_width+16));
		$('.ui-resizable-w, .ui-resizable-nw, .ui-resizable-sw', helper)
			.css('left', Math.max(16, -position.left+16));

		// Show handles
		$('.ui-resizable-handle', helper).show();
	},
	close: function () {
		this.file = null;
		this.workspace.fadeOut().detach().find('.helper > img').remove();
		this.overlay.remove();
		this.overlay = null;
	},
	destroy: function () {
		$.Widget.prototype.destroy.apply(this, arguments);
		this._blur_floating_form(true);
		this.workspace.remove();
	}
})

$.widget("ui.gmap", {
	options: {
		lat : 0,
		lng : 0,
		zoom : 1
	},
	_create: function() {

	},
	_init: function () {
		var self = this;
		var latlng = new google.maps.LatLng(this.options.lat, this.options.lng);
		var myOptions = {
		  zoom: this.options.zoom,
		  center: latlng,
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		var map = new google.maps.Map(this.element.get(0),myOptions);
		var marker = new google.maps.Marker({
		  position: latlng,
		  title:"Hello World!"
	  });

	  marker.setMap(map);
	},
	destroy: function() {
		$.Widget.prototype.destroy.apply(this, arguments); // default destroy
	}
});

$.widget('ui.zoom', {
	_create: function () {
		var self = this;

		this.element.addClass('zoom');

		var triggers = $(this.element.data('triggers'));
		triggers.bind('click.zoom', function (ev) {
			var i = triggers.index(ev.target);
			self.select(i);
		});

		this.images = this.element.children();
		this.triggers = triggers;
	},
	_init: function () {
		var i = 0;
		if ( this.element.is(':visible') ) {
			this.images.filter(':visible').index();
		}
		this.select(i);
	},
	select: function (i) {
		this.triggers.removeClass('selected');
		this.images.hide();
		this.images.eq(i).show();
		this.triggers.eq(i).addClass('selected');
	},
	destroy: function() {
		$.Widget.prototype.destroy.apply(this, arguments); // default destroy
		this.triggers.unbind('click.zoom');
	}
});

$.widget('ui.slideshow', {
	options: {
		speed: 4000,
		transition_speed: 800
	},
	_create: function () {
		var self = this;
		this.preload();

		this.w = this.element.width();
		this.current = this.element.children(':first');
		this.element.children(':not(:first)').css('opacity', 0);

		this.interval_id = setInterval(function () {
			self.update();
		}, this.options.speed);
	},
	preload: function () {
		var img = this.element.find('img[data-src]:first');
		if ( !img.size() ) { return; }
		var self = this;
		var img_load = $('<img/>');
		img_load.bind('load', function () {
			self.preload();
		});
		img_load.attr('src', img.data('src'));
		img.replaceWith(img_load);
	},
	update: function () {
		var next;
		next = this.current.nextAll(':has(img[src]):first');
		if ( !next.size() ) {
			next = this.current.siblings(':has(img[src]):first');
		}
		if ( !next.size() ) { return; }

		this.current.stop().animate({
			marginLeft: this.w,
			opacity: 0
		}, this.options.transition_speed);
		next.stop().css('margin-left', -this.w).animate({
			opacity: 1,
			marginLeft: 0
		}, this.options.transition_speed);

		this.current = next;
	},
	destroy: function () {
		$.Widget.prototype.destroy.apply(this, arguments); // default destroy
		clearInterval(this.interval_id);
	}
});

})();

