$(function(){
	// check if we actually hav a placeholder
	if ( ! $('#spanButtonPlaceholder').length){
		return;
	}

	// hide no javascript message
	$('#story-nojscript').hide();
	
	// detecting flash
	if (!FlashDetect.installed){		
		$('#story-container').hide();
		$('#story-noflash').show();
		return;
	}

	var file_selected = false,
		progress_bar = $('#story-container #file-progress div');

	/** Constants **/
	var ON_BACKEND = (typeof backend !== "undefined");	

	var IMAGE_UPLOAD = (window.location.href.indexOf('type=image') !== -1);

	var FILE_TYPES = ON_BACKEND ? "*.gif;*.png;*.jpg;*.jpeg;*.mov;*.mpg;*.avi;*.wmv;" : (IMAGE_UPLOAD ? "*.gif;*.png;*.jpg;*.jpeg;" : "*.mov;*.mpg;*.avi;*.wmv;");

	/* resets the form, progress bar, errors */
	function clear_errors(){
		var container = $('#story-general-errors');
		$('ul', container).children().remove();
		container.hide();
	}

	function reset_progress(){
		progress_bar.width(1).html('');
		$('#file-progress').hide();		
	}

	// initializing swfupload
	var swfu = new SWFUpload({
		// Backend settings
		upload_url: ON_BACKEND ? baseurl + backend + "/story/handle_upload" : baseurl + 'stories/handle_upload',

		// Flash file settings
		file_size_limit : IMAGE_UPLOAD ? "3MB" : "10MB",
		file_types : FILE_TYPES,
		file_upload_limit : "0",
		file_queue_limit : "1",		

		button_width: 149,
		button_height: ON_BACKEND ? 22 : 23,
		button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,

		// Event handler settings
		file_dialog_start_handler: function(){
			$('#file-name').val('');
			this.cancelUpload();
		},

		file_queued_handler : function(file){
			$('#file-name').val(file.name);
			file_selected = true;
		},

		file_queue_error_handler : function(file, errorCode, message){

			// Handle this error separately because we don't want to create a FileProgress element for it.
			switch (errorCode) {
				case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
					alert("You have attempted to queue too many files.\n" + (message === 0 ? "You have reached the upload limit." : "You may select " + (message > 1 ? "up to " + message + " files." : "one file.")));
					return;
				case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
					alert("The file you selected is too big.");
					return;
				case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
					alert("The file you selected is empty.  Please select another file.");
					return;
				case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
					alert("The file you choose is not an allowed file type.");
					return;
				default:
					alert("An error occurred in the upload. Try again later.");
					return;
			}

		},

		upload_progress_handler : function(file, bytesLoaded, bytesTotal){
			var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
			progress_bar.html(percent + '%');
			progress_bar.css({ width: percent + '%' });
		},

		upload_error_handler : function(file, errorCode, message){
			$('#file-progress em').html(message);
		},

		upload_success_handler : function(file, data){			
			data = eval('('+data+')');

			reset_progress();

			if (data.success) {
				if (ON_BACKEND){
					window.location.reload();
				}
				
				$('body').prepend(data.script);
				
				$('#story-container').children().fadeOut(500, function(){
					$('#story-thanks').show();
				});
			} else {				
				 // this is not useful! @todo				
				window.location = '#story-container';
				$('#story-general-errors').show().append('<ul></ul>');
				var errors = $('#story-general-errors ul');
				$.each(data, function(i){
					errors.append('<li>'+data[i]+'</li>');
				});
			}
		},

		// Button Settings
		button_image_url : ON_BACKEND ? baseurl+'skin/frontend/images/uploader/XPButtonUploadText_61x22.png' : baseurl+'skin/frontend/images/uploader/choose-'+(IMAGE_UPLOAD ? 'photo' : 'video')+'.png',
		button_placeholder_id : "spanButtonPlaceholder",		

		// Flash Settings
		flash_url : baseurl+'skin/frontend/swf/uploader/swfupload.swf',

		// Debug settings
		debug: false
	});
	

	$('#story-submit').validate({
		rules:{
			'email': 'email',
			'postcode': {
				maxlength: 30
			},
			'description': {
				required: true,
				maxWords: 250
			},
			'telephone': {
				maxlength: 40,
				required: true
			},
			'agreed': {
				required: true
			},
			'tags': {
				maxlength: 500
			},
			'title': {
				maxlength: 30,
				required: true
			},
			'occupation': {
				maxlength: 255
			}
		},

		// actual form submit
		submitHandler: function(form){

			if ( ! file_selected){
				if (ON_BACKEND){
					form.submit();
				}else{
					alert('File must be specified!');
				}
			
				return;
			}

			// handling params
			$.each($(form).serializeArray(), function(i){
				swfu.addPostParam(this.name, this.value);
			});

			// add session id
			if (ON_BACKEND){
				swfu.addPostParam('kohanasession', backend_session);
			}

			clear_errors();
			
			// submit the form along with the file
			$('#file-progress').show();			
			
			swfu.startUpload();			
		},

		errorElement: 'small'
	});

	
});

