$(document).ready(
	function() {
		jQuery.validator.addMethod('password', function (value, element, param) {
			return this.optional(element) || ((/([^\w])+/i.test(jQuery.trim(value))) && (this.getLength($.trim(value), element) >= param));
		}, $.format('Please enter alphanumeric password, minimum {0} characters long'));

		$('#form-flight').validate({
			submitHandler: function (form) {
				if (form.className == 'ajax') {
					$(form).ajaxSubmit({
						url: CONFIG.DOMAIN + 'FlightPicker/record?_content_type=json',
						dataType: 'json',
						success: formResponseAction
					});
						return false;
				}
					form.submit();
			},
			highlight: function (element, errorClass) {
				$(element).addClass(errorClass);
			},
			unhighlight: function (element, errorClass) {
				$(element).removeClass(errorClass);
			},
			rules: {
				departing: 'required',
				destination: 'required',
				flight: {
					required: true,
					digits: true
				},
				date: {
					required: true,
					date: true
				},
				name: {
					required: true,
					minlength: 2
				},
				email: {
					required: true,
					email: true
				},
				email_confirm: {
					equalTo: '#email'
				}/*,
				password: {
					required: '#account:checked',
					minlength: 7,
					password: 7
				},
				password_confirm: {
					required: '#account:checked',
					equalTo: '#password'
				}*/
			},
			messages: {
				airport: "{lang_error_airport}",
				destination: "{lang_error_destination}",
				flight: "{lang_error_flight}",
				date: "{lang_error_date}",
				name: "{lang_error_name}",
				email: "{lang_error_email}",
				email_confirm: "{lang_error_email_confirm}"/*,
				password: {
					required: "{lang_error_password}",
					password: "{lang_error_password}",
					minlength: "{lang_error_password_length}"
				},
				password_confirm: "{lang_error_password_confirm}"*/
			}
		});

		var airport = destination = ajaxLoadCounter = 0, removeSelectText = true;
		var airportElementSelect = $('#departing'), destinationElementSelect = $('#destination'), flightElementSelect = $('#flight'), dateElementSelect = $('#date');
		var passwordElementInput = $("#form-flight fieldset.register");

		var ajaxLoadStart = function () {
			ajaxLoadCounter++;
			var height = $('#form-flight').outerHeight();
			$('div.sub .loading').height(height).css('margin-bottom', '-' + height + 'px').show();
		};
		var ajaxLoadComplete = function () {
			if (ajaxLoadCounter === 1) {
				$('div.sub .loading').hide();
			}
			ajaxLoadCounter--;
		};
			
		var formResponseAction = function (response) {
			if (response.status == 'success') {
			//	$('#flight-picker').html(response.data).focus();
				location.reload();
			} else {
				$('#flight-picker p.loading-message').html(response.message).show().focus();
			}
		};

		var ajaxManagerFlight = $.manageAjax({manageType: 'sync'});
		var loadFlightInfo = function (url, callback) {
			ajaxLoadStart();
			var request = ajaxManagerFlight.add({
				url: url,
				success: callback,
				dataType: 'json'
			});
			var cancelAjaxFlightRequest = function () {
				ajaxManagerFlight.abort(request);
			};
		};
		$.fn.extend({
			buildSelect: function (option) {
				var element = this;
				$.each(option,
					function (key, value) {
						element.prepend($('<option>').attr('value', key).text(value));
					}
				);
				return this;
			}
		});

		$('#account').click(function () {
			if (this.checked) {
				passwordElementInput.show();
			} else {
				passwordElementInput.hide();
			}
		});
		airportElementSelect.change(
			function () {
				airport = airportElementSelect.val();
				loadFlightInfo(CONFIG.DOMAIN + 'FlightPicker/destination/' + airport + '?_content_type=json', 
					function (response) {
						if (response.status == 'success') {
							destinationElementSelect.empty().removeAttr('disabled').buildSelect(response.data).children(':first').attr('selected', 'selected');
							destinationElementSelect.change();

							if (removeSelectText) {
								airportElementSelect.children(':first').remove();
								removeSelectText = false;
							}
						} else {
							dateElementSelect.attr('disabled', 'disabled').empty().buildSelect(response.data);
							flightElementSelect.attr('disabled', 'disabled').empty().buildSelect(response.data);
							destinationElementSelect.attr('disabled', 'disabled').empty().buildSelect(response.data);
						}
						ajaxLoadComplete();
					}
				);
			}
		);
		destinationElementSelect.change(
			function () {
				airport = airportElementSelect.val();
				destination = destinationElementSelect.val();
				loadFlightInfo(CONFIG.DOMAIN + 'FlightPicker/flight/' + airport + '/' + destination + '?_content_type=json',
					function (response) {
						if (response.status == 'success') {
							flightElementSelect.empty().removeAttr('disabled').buildSelect(response.data).children(':first').attr('selected', 'selected');
							flightElementSelect.change();
						} else {
							dateElementSelect.attr('disabled', 'disabled').empty().buildSelect(response.data);
							flightElementSelect.attr('disabled', 'disabled').empty().buildSelect(response.data);
						}
						ajaxLoadComplete();
					}
				);
			}
		);
		flightElementSelect.change(
			function () {
				loadFlightInfo(CONFIG.DOMAIN + 'FlightPicker/schedule/' + flightElementSelect.val() + '?_content_type=json',
					function (response) {
						if (response.status == 'success') {
							dateElementSelect.empty().removeAttr('disabled').buildSelect(response.data).children(':first').attr('selected', 'selected');
						} else {
							dateElementSelect.attr('disabled', 'disabled').empty().buildSelect(response.data);
						}
						ajaxLoadComplete();
					}
				);
			}
		);
	}
);