var Zendr = {};

/** ZENDR.INDEX **/

Zendr.Index = Class.create({
	swfu: null,

	elm: null,
	
	settings: null,

	queue: null,
	queued: 0,
	
	session: null,

	/* CONSTRUCTOR methods */

	initialize: function() {
		Class.methodize(this); // bind the methods

		// add error control
		content = $A($$('.contentcontainer')).first();
		if (this.error = content.down('.error')) {
			this.error = new Lib.Error(this.error); // use the already existing error div
		} else {
			this.error = new Lib.Error();
			content.insert({'top':this.error}); 
		}

		if (this.message = content.down('.important')) {
			this.message = new Lib.Important(this.error); // use the already existing message div
		} else {
			this.message = new Lib.Important();
			content.insert({'top':this.message}); 
		}

		this._init();
	},
	_init: function() {
		this.queue = new Hash();
		this.queued = 0;
		
		this.session = null;

		try {
			this.swfu = new SWFUpload(this.getSettings());
		} catch (Exception) {
			this.swfu = null;
		}
	},

	/* EVENT methods */
	
	event: {
		_click: function(event) {
			this.swfu.selectFiles();
		},
		_submit: function(event) {
			this.submit();
		},
		_validate: function(event) {
			if (!this.validate()) { 
				Event.stop(event); 
			} else {
				this.message.replace('<h2>Het verzenden is gestart</h2><p>Klik deze pagina niet weg tijdens het verzenden anders zal het verzenden mislukken.</p><p>De tijd die benodigd is om het bestand te versturen hangt af van de grootte van het bestand en de snelheid van je internetverbinding.</p>');

				if (!this.swfu) {
					loader = new Element('div', {'id':'loader'}).insert({'top': new Element('img', {'src': '/images/loader.gif'})}).insert(new Element('span').insert('Bezig met verzenden...'));
					$$('.contentcontainer').first().insert({'top': loader});
				}
			}
		},
		_reload: function(event) {
			window.location.reload();
		},
		noDefault: function(event) {
			event.preventDefault();
		}
	},
	
	/* PRIVATE methods */
	
	_swfuPrepare: function() {
		// setup the page for the use of SWFUpload
		field = new Element('input', {'id':'bestand', 'class':'text'});
		field.readOnly = true;
		
		button = new Element('button', {'id':'select', 'type':'button'}).update('laden...');
		
		this.elm = {};
		this.elm.input = new Element('div', {'id':'swf_input', 'class':'swfupload'}).insert(field).insert(button);
		this.elm.queue = new Element('div', {'id':'swf_queue', 'class':'swfupload'})

		$('bestand').up('div').insert(this.elm.queue);
		$('bestand').replace(this.elm.input);
		
		// no default action will be taken.
		$('send').observe('click', this.event.noDefault);
		
		// remove the noflash message
		$('noflash').remove();
		
		$$('label[for="bestand"]').first().update('Bestand: <span class="normal">(Max 100 Mb en 10 bestanden)</span>');
	},
	_swfuFailed: function() {
		$('send').observe('click', this.event._validate);
		
		// we dont need this anymore
		throw new Exception('No Flash');
	},
	_swfuLoaded: function() {
		//this.elm.input.select('input, button').invoke('observe', 'click', this.event._click)
		$('send').observe('click', this.event._submit);
	},
	_swfuUnLoad: function() {
		this.elm.input.select('input, button').invoke('stopObserving', 'click', this.event._click)
		$('send').stopObserving('click', this.event._submit);
		
		if (this.swfu) {
			// unload the queue
			this.queue.keys().each(this.removefile);
			
			// clear the finshed uploads
			this.elm.queue.select('button').each(function(button){
				button.stopObserving('click', button._handler);
			});

			this.elm.queue.update();
			
			// clear the swfupload flash object
			//this.swfu.destoy(); buggy
			this.swfu = null;
		}
	},

	_queueFile: function(file) {
		
		var maxSize = (105 * 1024 * 1024);
		if(this.swfu.calculateQueueSize() >= (maxSize))
		{
			this._queueError(file, SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT, '');
			return;
		}	
	
		
		field = new Element('input', {'class':'text'});
		field.disabled = true;
		field.value = file.name;
		
		button = new Element('button', {'type':'button'}).update('Verwijderen');
		button._handler = this.removefile.curry(file.id);
		button.observe('click', button._handler);
		
		container = new Element('div', {'id':file.id, 'class':'swfupload'}).insert(field).insert(button);
		
		this.elm.queue.insert(container);

		this.queue.set(file.id, file);
		this.queued++;
		
		if (this.queued >= this.getSettings().file_upload_limit)
		{
			//$('swf_input').hide();
			this.swfu.setButtonDisabled(true);
		}
	},
	_queueError: function(file, code, message) {
		switch (code) {
			case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
				/*Lib.Error.Popup.getInstance().add('Er mogen nog <b>maximaal #{max}</b> bestands worden toegoevoegd'.interpolate({
					'max': message
				}));
				*/
				Lib.Error.Popup.getInstance().add('Er kunnen maximaal 10 bestanden worden toegevoegd.');
				break;

			case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
				Lib.Error.Popup.getInstance().add('Het bestand [#{file}] is te groot. Je kunt maximaal 100 MB verzenden.'.interpolate({
					'file':file.name.truncate(40)
				}));
				
				break;

			case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
				Lib.Error.Popup.getInstance().add('Het bestand [#{file}] is leeg.'.interpolate({
					'file':file.name.truncate(40)
				}));
				
				break;

			case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE: break; // cant happen as we accept anything
		}
	},

	_uploadStart: function(file) {
		this.uploading = file;

		try { 
			input = $(file.id).down('input'); 
		} catch(ex) { return false; }

		if (this.queue.get(file.id)) {
			this.queue.unset(file.id);
			this.queued--;
		}

		input.setStyle({
			'backgroundRepeat':'no-repeat',
			'backgroundPosition':'-348px 0',
			'backgroundImage':'url(/images/form.upload.progress.gif)'
		});
	},
	_uploadProgress: function(file, complete, total) {
		input = $(this.uploading.id).down('input');
		input.setStyle({
			'backgroundPosition':'#{progress}px 0'.interpolate({'progress':Math.round(-348 + ((complete/total) * 348))})
		});
		input.value = '#{file} (#{progress}%)'.interpolate({'file':file.name, 'progress':Math.round(((complete/total) * 1000))/10})
	},
	_uploadError: function(file, code, message) {
		switch (code) {
			case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
				break; //ignore
		
			default:
				this.message.clear();
				this.error.replace('Er is een fout opgetreden tijdens het verzenden van het bestand. De upload kan daarom niet worden afgerond en moet opnieuw worden gestart. Klik op de knop of herlaad de pagina om opnieuw te beginnen');
				
				send = $('send').removeClassName('disabled').stopObserving('click', this.event._submit).observe('click', this.event._reload);
				send.disabled = false;
				send.value = 'Herladen';

				break;
		}
	}, 
	_uploadSuccess: function(file, server) {
		input = $(this.uploading.id).down('input');
		input.value = file.name;
		
		this.uploading = false;
	},
	_uploadComplete: function(file) {
		if (this.error.hasError()) {
			return; // stop on a error....
		} 
		
		if (this.queued) {
			this.swfu.startUpload();
		} else {
			// we are done so send the email
			post = new Hash();
			post.set('session', this.session)
			post.set('action', 'send');
			
			new Ajax.Request('/ajax/upload.php', {
				'parameters':post.toQueryString(),
				'onSuccess':function(transport, json) {
					if (json && json.error) {
						this.error.replace(json.error);
					} else {
						this.error.clear();
						this.message.clear();

						this._swfuUnLoad();
						$$('div.leftcontainer .content').first().replace(transport.responseText);
					}
				}.bind(this)
			});
		}
	},

	_disable: function() {
		$('send').addClassName('disabled').disabled = true;

		//$('swf_input').hide();
		this.swfu.setButtonDisabled(true);
		$('swf_queue').addClassName('uploading').select('button').invoke('hide');

		$('aan').disabled = true;
		$('van').disabled = true;
		$('onthoudmij').disabled = true;
		$('onderwerp').disabled = true;
		$('bestand').disabled = true;
	},
	_enable: function() {
		$('send').removeClassName('disabled').disabled = false;
		
		//$('swf_input').show();
		this.swfu.setButtonDisabled(false);
		$('swf_queue').removeClassName('uploading').select('button').invoke('show');
		
		$('aan').disabled = false;
		$('van').disabled = false;
		$('onthoudmij').disabled = false;
		$('onderwerp').disabled = false;
		$('bestand').disabled = false;
	},
	
	/* PUBLIC methods */
	
	getSettings: function() {
		if (!this.settings) {
			this.settings = Object.clone(Zendr.SWFUpload.settings);
			
			// loading handlers
			this.settings.swfupload_pre_load_handler = this._swfuPrepare;
			this.settings.swfupload_load_failed_handler = this._swfuFailed; // its still posible to validate the input data
			this.settings.swfupload_loaded_handler = this._swfuLoaded;
			
			// queue handlers
			this.settings.file_queued_handler = this._queueFile;
			this.settings.file_queue_error_handler = this._queueError;
			
			// upload handlers
			this.settings.upload_start_handler = this._uploadStart;
			this.settings.upload_progress_handler = this._uploadProgress;
			this.settings.upload_error_handler = this._uploadError;
			this.settings.upload_success_handler = this._uploadSuccess;
			this.settings.upload_complete_handler = this._uploadComplete;
		}
		
		return this.settings;
	},
	
	removefile: function(id) {
		if (this.queue.get(id)) {
			this.swfu.cancelUpload(id);

			try { 
				button = $(id).down('button');
				$(id).remove();
				button.stopObserving('click', button._handler);
			} catch (ex) {}
			
			this.queue.unset(id);
			this.queued--;
			
			if (this.queued < this.getSettings().file_upload_limit)
			{
				this.swfu.setButtonDisabled(false);
			}
		}
	},
	/*reset: function() {
		this.queue.each(function (input){
			this.removefile(input.key);
		}.bind(this));
		
		$('aan').clear();
		$('van').clear();
		$('onthoudmij').checked = false;
		$('onderwerp').clear();
	},*/
	submit: function() {
		if (this.validate()) {
			// prepare the UI
			this._disable();
			
			// send the from data to prepare a upload session
			post = new Hash();

			post.set('aan', $('aan').getValue());
			post.set('van', $('van').getValue());
			post.set('onthoudmij', $('onthoudmij').getValue());
			post.set('onderwerp', $('onderwerp').getValue());
			post.set('bericht', $('bericht').getValue());

			post.set('action', 'validate');
			
			new Ajax.Request('/ajax/upload.php', {
				'parameters':post.toQueryString(),
				'onSuccess':function(transport, json) {
					if (json.error) {
						this.error.replace(json.error);
						this._enable();
					} else if (json.session){
						// start upload.
						this.session = json.session;
						this.swfu.addPostParam('session', json.session);
						this.message.replace('<h2>Het verzenden is gestart</h2><p>Klik deze pagina niet weg tijdens het verzenden anders zal het verzenden mislukken.</p><p>De tijd die benodigd is om het bestand te versturen hangt af van de grootte van het bestand en de snelheid van je internetverbinding.</p>');
						this.swfu.startUpload();
					} else {
						this._enable();
						this.error.replace('Het verzenden kon niet gestart worden, probeer het laten nog een keer.');
					}
				}.bind(this),
				'onFailure':function(transport) {
					this._enable();
					this.error.replace('Het verzenden kon niet gestart worden, probeer het laten nog een keer.');
				}.bind(this),
				'onException':function(transport, ex) {
					this.error.replace('Er is een interne fout opgetreden waardoor de upload niet gestart kon worden, probeer het laten nog een keer.');
					this.error.replace(ex);
				}.bind(this)			
			});
		}
	},
	validate: function() {
		this.error.clear();
		
		if ($('aan').getValue().blank()) {
			this.error.add('Vul minimaal één ontvanger in.')
		} else {
			emails = $('aan').getValue().split(/[\s,;]/).uniq().without('');
			
			emails.each(function(email) {
				if (!Lib.Validate.isEmail(email)) {
					this.error.add('Eén of meerdere van de ontvangende e-mail adressen zijn ongeldig.');
					
					throw $break;
				}
			}.bind(this));
		}
		
		if ($('van').getValue().blank()) {
			this.error.add('Vul jouw emailadres in.')
		} else if ( !Lib.Validate.isEmail($('van').getValue()) ) {
			this.error.add('Je emailadres is ongeldig.')
		}

		// swfu loaded
		if (this.swfu) {
			if (this.queued < 1) {
				this.error.add('Selecteer minimaal één bestand.')
			}
		} else {
			if ($('bestand').getValue().blank()) {
				this.error.add('Selecteer een bestand om te uploaden.')
			}
		}
		
		if (this.error.hasError()) {
			return false;
		}
		
		return true;
	}
});

Zendr.Index.instance = null
Zendr.Index.getInstance = function() {
	if (!Zendr.Index.instance) {
		Zendr.Index.instance = new Zendr.Index();
	}
	
	return Zendr.Index.instance;
}

Zendr.SWFUpload = {}; 
Zendr.SWFUpload.settings = {
	flash_url : "/scripts/swfupload/swfupload.swf",
	upload_url: "/ajax/upload.php",
	post_params : {"action":"upload"}, 

	file_size_limit : "105 MB",
	file_types : "*.*",
	file_types_description : "Alle bestanden",
	file_upload_limit : 10,
	
	/** Button info **/
	
	button_placeholder_id : "select",
	button_image_url: "/images/form.button.gif",
	button_width : 86,
	button_height : 20,
	button_text: '<span class="button">Bladeren</span>',
	button_text_style: ".button { color:#FFFFFF; text-align:center; font-family:verdana; }",
	//button_action: SWFUpload.BUTTON_ACTION.SELECT_FILES, 
	button_cursor: SWFUpload.CURSOR.HAND,
	
	/** SWFObject **/
	minimum_flash_version: "9.0.115",
	swfupload_pre_load_handler: Prototype.emptyFunction,
	swfupload_load_failed_handler: Prototype.emptyFunction
	
	//debug_handler: console.debug,
	//debug: true
}

/* 
 * Function to calculate the size of the queue
 */

SWFUpload.prototype.calculateQueueSize = function() {
	var index = 0;
	var file = this.getFile(index++);
	var queued_file_size = 0;
	
	while (file !== null) 
	{
		if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) {
			queued_file_size += file.size;
		}
		file = this.getFile(index++);
	}
	
	return queued_file_size;	
}

