var MediaFileOrganizer = new Class({
	
	Implements: [Options, Events],
	
	options: {
		wrapper: Document.body,
		collections: [],
		files: [],
		sortables: true
	},
	
	initialize: function(options){
		this.setOptions(options);
		this.wrapper = document.id(this.options.wrapper);
		delete this.options.wrapper;
		this.addEvent('onSelection', this.onSelection);
		this.onSelection();
		var files = this.wrapper.getElements(this.options.files);
		files.each(this._build, this);
		
		if (this.options.sortables) this._setupSortable();
	},
	
	_build: function(el){
		var me = this;
		var checkbox = el.getElement('input[type=checkbox]').hide();
		var isOnState = !checkbox.checked;
		var anchor = el.getElement('a').set('title', Vadingo.translationManager._('Double click to open', 'application'));
		var link = anchor.setStyle('cursor', 'default').addEvents({
			'dblclick': function(){
				el.removeClass('selected').addClass('active');
				return location.href = link;
			}
		}).get('href');
		
		if (!isOnState) el.addClass('selected');
		if (this.options.sortables) anchor.removeProperty('href'); // Prevent click with drag
		
		el.addEvent('mouseup', function(event){
			if (!me.dragging) {
				isOnState = !checkbox.checked;
				checkbox.set('checked', isOnState);
				this[(isOnState?'add':'remove') + 'Class']('selected');
				me.fireEvent('onSelection');
			}
		});
		// Bite me! IE...
		if (Browser.Engine.trident) document.ondragstart = function(){ return false; }
	},
	
	onSelection: function(){
		var nav, hasSelection = this.wrapper.getElements(this.options.files).some(function(el){
			if (el.hasClass('selected')) return true;
		});
		if (!hasSelection) {
			document.id('mediafile-browse-action').getElements('input').setProperty('disabled', 'disabled');
		} else {
			document.id('mediafile-browse-action').getElements('input').removeProperty('disabled');
		}
	},
	
	_setupSortable: function(){
		this._reOrder(true); // Initial order and setup
		
		this.dragging = false;
		
		new Sortables(this.wrapper, {
		    constrain: true,
		    clone: false,
		    revert: true,
			onStart: function(el){
				el.addClass('dragging');
				this.dragging = true;
				this.cancel();
			}.bind(this),
			onComplete: function(el){
				el.removeClass('dragging');
				if (this.dragging) this.save();
				this.dragging = false;
			}.bind(this),
			onSort: function(){
				this._reOrder();
			}.bind(this)
		}).removeItems(this.wrapper.getElements(this.options.collections));
		
		var uri = new URI(location.href);
		uri = uri.toRelative().replace(uri.get('query') ? '?'+uri.get('query') : '', '') + 'reorder';
		
		this.request = new Request.JSON.Advanced({
			method: 'post',
			url: uri
		}).addEvents({
			'complete': function(){
				this.fireEvent('reorderComplete');
			}.bind(this)
		});
	},
	
	_reOrder: function(start){
		var elements = this.wrapper.getElements(this.options.files + ' span.order');
		
		elements.each(function(el, index){
			index++;
			if (start) {
				new Element('strong').inject(el);
				new Element('input', {'type': 'hidden'}).inject(el);
			}
			el.getElement('input[type=hidden]').set({
				'name': 'reorder[]',
				'value': el.getElement('input[type=checkbox]').get('value')
			});
			el.getElement('strong').set('text', index + '/' + elements.length);
		});
	},
	
	save: function(){
		this.fireEvent('reorder');
		this.request.sendJSON({data: this.serialize()});
	},
	
	cancel: function(){
		this.request.cancel();
	},
	
	serialize: function(){
		var values = this.wrapper.getElements(this.options.files + ' span.order input[type=hidden]').map(function(input){
			return input.get('value');
		});
		
		return {'reorder': values};
	}
	
});