String.prototype.capitalize = function(){
	return this.replace(/\S+/g, function(a){
		return a.charAt(0).toUpperCase() + a.slice(1).toLowerCase();
	});
};

function reloadCaptcha() {
	$('#captchaImage').attr('src', '/securimage/securimage_show.php?sid=' + Math.random() );
	$('#cfCaptchaField').val('');
}

function onComplaintFormSubmitSuccess(response){
	var $notice  = $('#complaint_form_notice').html('');
	var $form    = $('#complaint_form');
	var $message = $('#cfMessageField');
	if (response.success) {
		$notice.html(response.success);
		$('#cfFullnameField,#cfEmailField,#cfProjectidField,#cfPhoneField,#cfMessageField').each(function(){
			this.value = $.trim(this.value);
		});
		$message.val('Order ID: '+$('#cfProjectidField').val()+'\n'+'Phone #: '+$('#cfPhoneField').val()+'\n\n'+$message.val());
		$form.attr('action', response.redirect).submit();
	}else if(response.failure) {
		$notice.html(response.failure);
		reloadCaptcha();
		if (response.fields) {
			$('div.description', $form).removeClass('error');
			for(var i = 0; i < response.fields.length; i++) {
				$('#cf' + response.fields[i].capitalize() + 'Label').addClass('error');
			}
		}
	}
}

function onComplaintFormSubmitError(response){
	$('#complaint_form div.description').removeClass('error');
	$('#complaint_form_notice').html('Unknown error occurred while submitting the form. Please try later.');
}

function submitComplaintForm(form){
	$.ajax({
		type: 'POST',
		url: '/complaint-form/',
		data: $(form).serialize(),
		success: onComplaintFormSubmitSuccess,
		error: onComplaintFormSubmitError,
		dataType: "json"
	});
};

