$(function() {
	setupFormCSS();
	setupWYSIWYGEditors();
	setupFormValidation();
});

function _log(data) {
	if (typeof(console) != 'undefined') {
		console.log(data);
	}
}

function applicationComplete(response) {
	_log(['applicationComplete',response]);
	$("#application-submit").dialog('close');
	if ((typeof(response.stmt) != 'undefined')
	&& (typeof(response.stmt.rows) != 'undefined')
	&& (typeof(response.stmt.rows[0].id) != 'undefined')) {
		setTimeout(showUploadCompleteDialog,500);
	}
}

function setupFormCSS() {
	$('.required').parent('.form-field').addClass('required').each(function() {
		if ($(this).attr('title') != '') {
			$(this).attr('title', $(this).attr('title') + ' - ');
		}
		$(this).attr('title', $(this).attr('title') + 'This field is required.');
	});
	$('.form-field').append('<div class="clear" />');
}

function setupWYSIWYGEditors() {
	CKEDITOR.replace('short_descr', {
		height: '5em',
		toolbar: 'Basic'
	});
	CKEDITOR.replace('long_descr', {
		height: '10em',
		toolbar: 'Basic'
	});
	CKEDITOR.replace('message_to_producers', {
		height: '5em',
		toolbar: 'Basic'
	});
}

/*
function setupAjaxFileUpload(fileElementId) {
	preparing ajax file upload
	url: the url of script file handling the uploaded files
	fileElementId: the file type of input element id and it will be the index of  $_FILES Array()
	dataType: it support json, xml
	secureuri:use secure protocol
	success: call back function when the ajax complete
	error: callback function when the ajax failed
	$.ajaxFileUpload({
		url:'services/application_handler.php',
		secureuri:false,
		fileElementId: fileElementId,
		dataType: 'json',
		success: function (data, status) {
			_log(['success','data',data]);
			_log(['success','status',status]);
			if(typeof(data.error) != 'undefined') {
				if(data.error != '') {
					_log(data.error);
				} else {
					_log(data.msg);
				}
			}
		},
		error: function (data, status, e) {
			_log(['error','data',data]);
			_log(['error','status',status]);
			_log(['error','e',e]);
		}
	});
	return false;
}
*/

function setupFormValidation() {
	/*
	$('#application').submit(function(){
		showProcessingDialog();
		$.ajax({
			type: 'POST',
			url: 'services/application_handler.php',
			dataType: 'json',
			data: $('form#application').serialize(),
			success: function(response, status, xhr) {
				_log(['success','response',response]);
				_log(['success','status',status]);
				_log(['success','xhr',xhr]);
				applicationComplete(response);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				_log(['error','XMLHttpRequest',XMLHttpRequest]);
				_log(['error','textStatus',textStatus]);
				_log(['error','errorThrown',errorThrown]);
			}
		});
		return false;
	});

	$('#application').ajaxForm({
		beforeSubmit: showProcessingDialog,
		dataType: 'json',
		success: function(response, status, xhr, $form) {
			_log(['success','response',response]);
			_log(['success','status',status]);
			_log(['success','xhr',xhr]);
			_log(['success','$form',$form]);
			applicationComplete(response);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			_log(['error','XMLHttpRequest',XMLHttpRequest]);
			_log(['error','textStatus',textStatus]);
			_log(['error','errorThrown',errorThrown]);
		}
	});
	*/

	jQuery.validator.addMethod("isUnique", function(value, element) { 
		  return this.optional(element) || (!$(element).hasClass('notUnique')); 
		}, "It appears that that handle is already in use.");
	$("#application").validate({
		submitHandler: function (form) {
			showProcessingDialog();
			$(form).ajaxSubmit({
				dataType: 'json',
				success: function(response, status, xhr, $form) {
					_log(['success','response',response]);
					_log(['success','status',status]);
					_log(['success','xhr',xhr]);
					_log(['success','$form',$form]);
					if (typeof response.errors == 'object' ) {
						alert(response.errors.join('<br />'));
					} else {
						applicationComplete(response);
					}
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					_log(['error','XMLHttpRequest',XMLHttpRequest]);
					_log(['error','textStatus',textStatus]);
					_log(['error','errorThrown',errorThrown]);
				}
			});
		}
	});
	$('#handle').focus().keyup(function(evt) {
		_log(['keyup',$('#handle').val()]);
		$('#handle').val($('#handle').val().replace(/[^a-zA-Z0-9]/g,''));
	}).keypress(function(evt) {
		if (typeof(keyTimer) != 'undefined') {
			clearTimeout(keyTimer);
		}
		keyTimer = setTimeout(checkForUniqueHandle,500);
	});
}

function showProcessingDialog() {
	$("#application-submit").dialog({
		bgiframe: true,
		resizable: false,
		height: 250,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			'Close': function() {
				$(this).dialog('close');
			}
		}
	});
	$("#application-submit").dialog('open');
}

function showUploadCompleteDialog() {
	$("#application-complete").dialog({
		bgiframe: true,
		resizable: false,
		height: 250,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			'Close': function() {
				$(this).dialog('close');
				setTimeout("window.location = '/'",2000);
			}
		}
	});
	$("#application-complete").dialog('open');
}

function checkForUniqueHandle() {
	$('#handle').removeClass('notUnique').removeClass('unique').removeClass('error');
	var handle = $('#handle').val();
	if (handle.length >= 3) {
		_log($('#handle').val());
		$.ajax({
			url: '/services/application_handler.php',
			data: {
				function_name: 'is_handle_available',
				is_ajax: true,
				handle: $('#handle').val()
			},
			success: checkForUniqueHandleResponse,
			dataType: 'json'
		});
	}
}

function checkForUniqueHandleResponse(data, textStatus, XMLHttpRequest) {
	if (data.is_available == 'TRUE') {
		_log(['result','TRUE']);
		$('#handle').addClass('unique');
	} else {
		_log(['result','FALSE']);
		$('#handle').addClass('notUnique');
	}
	$("#application").validate().element('#handle');
	_log(['data',data]);
	_log(['textStatus',textStatus]);
	_log(['XMLHttpRequest',XMLHttpRequest]);
}
