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

var gcms_formUpload = Class.create({	
	
	vars: { field: '', format: 'admin' },
	
	/* ****************************************************************************************************************** */
	
	initialize: function(format) {
		
		this.vars.format = (format != null)? format: this.vars.format;
		
		document.observe('dom:loaded', function(e) {
			
			// Get all of the file upload fields
			$$('div.content form fieldset ol li input[type=text].gcms_formUpload').each(function(i) {
				
				// Change the type of this input ... BROWSER SNIFFING MADNESS!
				(Prototype.Browser.IE == true)? i.hide(): i.setAttribute('type', 'hidden');
				
				// update the file information
				this.drawFileInfo(i);
					
			}.bind(this));
												
		}.bindAsEventListener(this));
	},
	
	/* *********************************************************************************************************************
	
	DRAW
	
	********************************************************************************************************************* */
	
	drawFileInfo: function(i) {
		// Set the height of the containing LI
		i.up().style.minHeight = '8.1em';
		
		// Remove any file information boxes currently available for this input ...
		i.up().select('div.formUploadInfo').invoke('remove');
		
		// Construct an AJAX request to get the file information ...
   		new Ajax.Updater(i, site_url + this.vars.format + '/ajax/getFormUploadInfo', {
   			insertion: Insertion.Before,
			parameters: { format: this.vars.format, value: i.getAttribute('value') },
   			onComplete: function() {
					
				// Attach events - Select File
				i.up().select('div.formUploadInfo ul li.formUploadInfoSelect').each(function(li) {					
					li.observe('click', this.onClickFileSelect.bindAsEventListener(this));					
				}.bind(this));
				
				// Attach events - Remove File
				i.up().select('div.formUploadInfo ul li.formUploadInfoRemove').each(function(li) {					
					li.observe('click', this.onClickFileRemove.bindAsEventListener(this));					
				}.bind(this));	
				
			}.bind(this)
   		});
	},	
	
	/* ****************************************************************************************************************** */
	
	drawFileSelectClose: function(i) {
		// Define the field we are using everywhere ...
		this.vars.field = '';
				
		// Fade in the overlay, cos its pretty
		$('overlayFormUploadSelect').fade({
			duration: 0.2,
			afterFinish: function() {
				// Remove the overlay
				$('overlayFormUploadSelect').remove();
				
				// Add 'overlay' class to body
				$$('body').first().removeClassName('overlay');
			}
		});
	},
	
	/* ****************************************************************************************************************** */
	
	drawFileSelectOpen: function(i) {
		// Define the field we are using everywhere ...
		this.vars.field = i;
		
		// Construct an AJAX request to get the file information ...
   		new Ajax.Updater($$('body').first(), site_url + this.vars.format + '/ajax/getFormUploadSelect', {
			parameters: { 
				field: this.vars.field.getAttribute('name'), 
				format: this.vars.format, 
				rules: $$('input[name=uploadable_rules]').first().getAttribute('value'), 
				value: this.vars.field.getAttribute('value')
			},
   			insertion: Insertion.Top,
   			onComplete: function() {				
				// Add 'overlay' class to body
				$$('body').first().addClassName('overlay');
				
				// Attach events - Select Existing File
				$$('div#overlayFormUploadSelect ul.listOverlayOptions li').each(function(li) {					
					li.observe('click', this.onClickOverlayOptions.bindAsEventListener(this));					
				}.bind(this));
				
				// Retrieve files that match the bill ...
				if ($$('div#overlayFormUploadSelect div.moduleA').first()) {
					$$('div#overlayFormUploadSelect div.moduleA').first().insert({top: '<ul class="list"></ul>'}).observe('click', this.onClickChooseExisting.bindAsEventListener(this));					
					
					this.drawExisting();				
				}
				
				// Attach events - Submit Form
				if ($$('div#overlayFormUploadSelect div.moduleB form').first()) {
					$$('div#overlayFormUploadSelect div.moduleB form').first().observe('submit', this.onFormSubmit.bindAsEventListener(this));	
				}				
				
				// Fade in the overlay, cos its pretty
				$('overlayFormUploadSelect').appear({duration: 0.2});							
			}.bind(this)
   		});
	},
	
	/* ****************************************************************************************************************** */
	
	drawExisting: function(countA) {
		new Ajax.Updater($$('div#overlayFormUploadSelect div.moduleA ul.list').first(), site_url + this.vars.format + '/ajax/getFormUploadExisting', {
			parameters: {
				field: this.vars.field.getAttribute('name'),
				format: this.vars.format, 
				offset: countA,
				rules: $$('input[name=uploadable_rules]').first().getAttribute('value')
			},
   			insertion: Insertion.Bottom,
   			onComplete: function() {
				// Get the new size of the list
				var countB = $$('div#overlayFormUploadSelect div.moduleA ul.list li').size();
				
				// If they are different, (the list has updated ...) get the next batch
				if (countA != countB) { this.drawExisting(countB); }				
			}.bind(this)
   		});
	},
	
	/* ****************************************************************************************************************** */
		
	drawModuleSwap: function(i) {
		// Hide all of the modules ...
		$$('div#overlayFormUploadSelect div.module').invoke('hide');
		
		// Remove the classname on the link
		$$('div#overlayFormUploadSelect ul.listOverlayOptions li').invoke('removeClassName', 'on');
		
		// Show the selected module
		$$('div#overlayFormUploadSelect div.' + i + '').invoke('show');
		
		// Add the classname on the releavant link
		$$('div#overlayFormUploadSelect ul.listOverlayOptions li[rel=' + i + ']').invoke('addClassName', 'on');
	},	
	
	/* *********************************************************************************************************************
	
	ON CLICK
	
	********************************************************************************************************************* */
	
	onClickChooseExisting: function(e) {
		// If we haven't clicked an LI element
		if (!Event.findElement(e, 'li')) { return; }
		
		// Se the value of our current field to this ID
		this.vars.field.setAttribute('value', Event.findElement(e, 'li').getAttribute('rel'));
		
		// Redraw the fileinfo ...
		this.drawFileInfo(this.vars.field);
		
		// Draw the selection overlay closing ...
		this.drawFileSelectClose();
	},
	
	/* ****************************************************************************************************************** */
	
	onClickFileRemove: function(e) {
		// Find our form element
		var i = Event.findElement(e, 'li').up(2).down('input.gcms_formUpload');
		
		// Set the input value to nowt ...
		i.setAttribute('value', '');
		
		// Redraw the fileinfo ...
		this.drawFileInfo(i);
	},
	
	/* ****************************************************************************************************************** */
	
	onClickFileSelect: function(e) {
		// Find our form element
		var i = Event.findElement(e, 'li').up(2).down('input.gcms_formUpload');
		
		// Draw the selection overlay opening ...
		this.drawFileSelectOpen(i);
	},
	
	/* ****************************************************************************************************************** */
	
	onClickOverlayOptions: function(e) {
		// Find our list element
		var li = Event.findElement(e, 'li');
		
		// If this is the close element ... close the overlay
		if (li.getAttribute('id') == 'listOverlayOptionsC') {
			this.drawFileSelectClose();
		} else {
			this.drawModuleSwap(li.getAttribute('rel'));
		}
	},
	
	/* *********************************************************************************************************************
	
	ON FORM
	
	********************************************************************************************************************* */
	
	onFormSubmit: function() {
		
		// Remove any errors we are displaying ...
		$$('div#overlayFormUploadSelect div.moduleB form input[type=submit]').first().setAttribute('disabled', 'disabled');
		$$('div#overlayFormUploadSelect div.moduleB form input[type=submit]').first().setAttribute('value', 'Uploading File ...');

		var pu = new Ajax.PeriodicalUpdater('', site_url + this.vars.format + '/ajax/getFormUploadStatus', {
			method: 'post', 
			frequency: 1,
			onSuccess: function(response) {
				
				if (response.responseText.isJSON()) {
					
					var json = response.responseText.evalJSON();
					
					if ((json.file_id) || (json.file_error) || (json.title_error)) {
						
						// Stop the AJAX updater								
						pu.stop();

						// Call the form loaded function
						this.onFormLoad(json);
					}					
				}
			}.bind(this)
		});
	},
	
	/* ****************************************************************************************************************** */
	
	onFormLoad: function(json) {
		
		// If we have no errors, (a FILE json object ...)
		if (json.file_id) {

			// Se the value of our current field to this ID
			this.vars.field.setAttribute('value', json.file_id);

			// Redraw the fileinfo ...
			this.drawFileInfo(this.vars.field);

			// Draw the selection overlay closing ...
			this.drawFileSelectClose();
			
			// Stop here ...
			return;
			
		// If we have errors ...
		} else if((json.title_error) || (json.file_error)) {
			
			// Remove any errors we are displaying ...
			$$('div#overlayFormUploadSelect div.moduleB form fieldset ol li p.error').invoke('remove');
			
			// If we have a title error ...
			if (json.title_error != '') {
				$$('div#overlayFormUploadSelect div.moduleB form fieldset ol li input[name=title]').first().up().insert({bottom: '<p class="error">' + json.title_error + '</p>'})
			}
			
			// If we have a file error ...
			if (json.file_error != '') {
				$$('div#overlayFormUploadSelect div.moduleB form fieldset ol li input[name=file]').first().up().insert({bottom: '<p class="error">' + json.file_error + '</p>'})
			}
			
			// Remove any errors we are displaying ...
			$$('div#overlayFormUploadSelect div.moduleB form input[type=submit]').first().removeAttribute('disabled');
			$$('div#overlayFormUploadSelect div.moduleB form input[type=submit]').first().setAttribute('value', 'Upload File');
			
			// Stop here ...
			return;		
		}
	}
	
	/* ****************************************************************************************************************** */
});
