/**
*	@package		Generic CMS, (GCMS)
*	@subpackage		Javascript
*	@author			Ben Sekulowicz-Barclay
*	@copyright		Copyright 2008, Outside Line.
*	@version		9.01
*
************************************************************************************************************************ **/

var gcms_tableSequence = Class.create({	
	
	vars: { format: 'admin' },
	
	/* ****************************************************************************************************************** */
	
	initialize: function(format) {
		
		this.vars.format = (format != null)? format: this.vars.format;
		
		document.observe('dom:loaded', function(e) {
			
			// if we have no table, don't do a thing ...
			if (!$('tableSequence')) { return; }
			
			// Insert a hidden field containing our value, after the table
			$('tableSequence').up().insert({ after: '<input type="hidden" id="tableSequenceOrder" value="' + this.getOrder() + '" />' });
			
			// Create our sortable
			Sortable.create($('tableSequence'), { tag: 'tr' });
			
			// Create our PE that checks the value ...
			new PeriodicalExecuter(function(p) {
				
				// If the current order doesn't match the cached value			
				if ((v = this.getOrder()) != $('tableSequenceOrder').getAttribute('value')) {
					
					// Store the new value
					$('tableSequenceOrder').setAttribute('value', v);
					
					// Update the order with the server
					this.setOrder();
				}
			}.bind(this), 0.75);
										
		}.bindAsEventListener(this));
	},
	
	/* ****************************************************************************************************************** */
	
	getOrder: function() {
		// Define our core value
		var v = '|';
		
		// loop through the table rows and update our value ...
		$$('table tbody#tableSequence tr').each(function(tr) {				
			v = v + tr.getAttribute('rel') + '|';
		});
		
		// Send back the string
		return v;
	},
	
	/* ****************************************************************************************************************** */
	
	setOrder: function() {				
		$('tableSequence').up().addClassName('tableSequenceLoading');
		
		new Ajax.Request(site_url + this.vars.format + '/ajax/setTableSequence', {
			method: 'post',
			parameters: { table: 'tableSequence', sequence:  $('tableSequenceOrder').getAttribute('value') },
			onSuccess: function(transport) {
				
				$('tableSequence').up().removeClassName('tableSequenceLoading');
				
				// If we get a JSON object back and there is no error
				if ((transport.responseText.isJSON()) && (transport.responseText.evalJSON().error != '')) {					
					Sortable.destroy($('tableSequence'));					
					alert(transport.responseText.evalJSON().error);
				} 			
			}.bind(this)
		});
	}	
	
	/* ****************************************************************************************************************** */
});
