

// error messages collected
var $ts_error_messages = [];

function ts_verifyDate($type, $postfix) {
	var $day = parseInt($('#' + $type + '_date_day' + $postfix).val());
	var $day_count = parseInt($ticket_search_params.month_day_count[ $('#' + $type + '_date_month' + $postfix).val() ]);

	// console.log('ts_verifyDate; type: ', $type, '; day_selected: ', $day, '; month_selected: ', $('#' + $type + '_date_month' + $postfix).val(), '; month_day_count: ', $day_count);

	// when given day doesn't exist in given month, then use last month day
	if ($day > $day_count) {
		$('#' + $type + '_date_day' + $postfix).val($day_count);
	}
}

function ts_syncronizeMonthDayCount($type, $date, $postfix) {
	var $day = $date.getDate();
	var $day_count = parseInt($ticket_search_params.month_day_count[ ($date.getMonth() + 1) + '/' + $date.getFullYear() ]);

	// console.log('ts_syncronizeMonthDayCount; type: ', $type, '; day_selected: ', $day, '; month_selected: ', ($date.getMonth() + 1) + '/' + $date.getFullYear(), '; month_day_count: ', $day_count);

	var $month_days = $('#' + $type + '_date_day' + $postfix);
	$month_days.empty();

	// when given day doesn't exist in given month, then use last month day
	if ($day > $day_count) {
		$day = $day_count;
		$date.setDate($day_count);
	}

	for (var $i = 1; $i <= $day_count; $i++) {
		var $selected = $i == $day ? ' selected="selected"' : '';
		$month_days.append('<option value="' +  $i + '"' + $selected + '>' + $i + '</option>');
	}

	return $date;
}

function ts_calculateBackwardFlightDate($mode, $postfix) {
	// calculate "TowardFlight date" based on "Nights" & "BackwardFlight date"
	// console.group('ts_calculateTowardFlightDate [', $mode, ']');

	var $backward_flight_date = ts_getDate('backward_flight', $postfix);
	var $toward_flight_date = ts_getDate('toward_flight', $postfix);

	if ($backward_flight_date !== false && $toward_flight_date !== false && $backward_flight_date < $toward_flight_date) {
		ts_setDate('backward_flight', $toward_flight_date, $postfix);
	}
}

function ts_calculateTowardFlightDate($mode, $postfix) {
	// calculate "TowardFlight date" based on "Nights" & "BackwardFlight date"
	// console.group('ts_calculateTowardFlightDate [', $mode, ']');

	var $backward_flight_date = ts_getDate('backward_flight', $postfix);
	var $toward_flight_date = ts_getDate('toward_flight', $postfix);

	if ($backward_flight_date !== false && $toward_flight_date !== false && $backward_flight_date < $toward_flight_date) {
		ts_setDate('toward_flight', $backward_flight_date, $postfix);
	}
}


function ts_getDate($type, $postfix) {
	// console.group('ts_getDate [', $type, ']');

	var $day = parseInt( $('#' + $type + '_date_day' + $postfix).val() );
	if (isNaN($day)) {
		// month day not entered
		// console.log('ts_getDate; type [', $type, '] -> Day Is Not A Number');
		// console.groupEnd();
		return false;
	}

	var $month = $('#' + $type + '_date_month' + $postfix).val().split('/');
	var $year = parseInt($month[1]);
	$month = parseInt($month[0]) - 1;

	var $date = new Date($year, $month, $day, 0, 0, 0);

	if ($date.getDate() == $day && $date.getMonth() == $month && $date.getFullYear() == $year) {
		// such month day was found in given month & year
		// console.log('ts_getDate; type [', $type, '] -> OK');

		/*if (($type == 'toward_flight') && ($date.getTime() / 1000 < $ticket_search_params.min_booking_date)) {
			// out of range
			// console.log('ts_getDate [', $type, '] - Out Of Range');
			// console.groupEnd();
			return false;
		}

		if (($type == 'backward_flight') && ($date.getTime() / 1000 > $ticket_search_params.max_booking_date)) {
			// out of range
			// console.log('ts_getDate [', $type, '] - Out Of Range');
			// console.groupEnd();
			return false;
		}*/

		// console.groupEnd();

		return $date;
	}

	// console.log('ts_getDate; type [', $type, '] -> Given Month Day Doesn\'t exist in given month');
	// console.groupEnd();
	return false;
}

function ts_setDate($type, $date, $postfix) {
	// console.group('ts_setDate [', $type, ', ', $date, ']');

	if ($date === false) {
		// console.log('ts_setDate [', $type, ']: -> Invalid Date Given');
		// console.groupEnd();
		return ;
	}

	$date = ts_syncronizeMonthDayCount($type, $date, $postfix);

	var $day = $date.getDate();
	var $month = ($date.getMonth() + 1) + "/" + $date.getFullYear();

	// console.log('ts_setDate [', $type, ']: ', $date.getDate(), '/', $date.getMonth() + 1, '/', $date.getFullYear() );

	$('#' + $type + '_date_day' + $postfix).val($day);
	$('#' + $type + '_date_month' + $postfix).val($month);

	// for date picker
	$('#' + $type + '_date_picker' + $postfix).val( $day + '/' + ($date.getMonth() + 1) + '/' + $date.getFullYear());
	// console.groupEnd();

	//if (ts_checkSetDateRecursion('setDate')) {
	//	$('#'+$type+'_date_picker' + $postfix).datepicker().setDate( new Date($date.getFullYear(), $date.getMonth(), $day) );
		$('#'+$type+'_date_picker' + $postfix).datepicker('setDate', $date);
	//}
}

function ts_setError($element) {
	$element.addClass('invalid-form-value').focus( function() { $element.removeClass('invalid-form-value'); } );
}

function ts_validateForm($postfix) {
	var $valid = true;
	var $required_fields = ['#departure_airport' + $postfix + '_hidden', '#destination_airport' + $postfix + '_hidden'];

	var $directions = $('#directions_0' + $postfix + ', #directions_1' + $postfix + ', #directions_2' + $postfix);
	if ($directions.filter(":checked").val() == '2') {
		$required_fields.push('#departure_airport2' + $postfix + '_hidden', '#destination_airport2' + $postfix + '_hidden');
	}

	if ($required_fields.length) {
		$( $required_fields.join(',') ).each(
			function() {
				var $value = $(this).val();
				switch ($(this).attr('id')) {
					case 'departure_airport_hidden':
						var $error_element = $('#departure_airport' + $postfix + '_input');
						break;
					case 'destination_airport_hidden':
						var $error_element = $('#destination_airport' + $postfix + '_input');
						break;
					case 'departure_airport2_hidden':
						var $error_element = $('#departure_airport2' + $postfix + '_input');
						break;
					case 'destination_airport2_hidden':
						var $error_element = $('#destination_airport2' + $postfix + '_input');
						break;
					default:
						var $error_element = $(this);
				}

				if (!$value) {
					ts_setError($error_element);
					$valid = false;
				}
				else {
					$error_element.removeClass('invalid-form-value');
				}
			}
		);
	}

	// check if date is greather or equals to today
	var $today = new Date();
	$today.setHours(0);
	$today.setMinutes(0);
	$today.setSeconds(0);

	if ($today.getTime() - ts_getDate('toward_flight', $postfix).getTime() > 1000) {
		$ts_error_messages.push($ticket_search_params.phrases['lu_error_TowardFlightDateInPast']);

		$('#toward_flight_date_day' + $postfix + ', #toward_flight_date_month' + $postfix)
		.addClass('invalid-form-value')
		.focus(
			function() {
				$('#toward_flight_date_day' + $postfix + ', #toward_flight_date_month' + $postfix).removeClass('invalid-form-value');
			}
		);

		$valid = false;
	}

	if ($today.getTime() - ts_getDate('backward_flight', $postfix).getTime() > 1000) {
		$ts_error_messages.push($ticket_search_params.phrases['lu_error_BackwardFlightDateInPast']);

		$('#backward_flight_date_day' + $postfix + ', #backward_flight_date_month' + $postfix)
		.addClass('invalid-form-value')
		.focus(
			function() {
				$('#backward_flight_date_day' + $postfix + ', #backward_flight_date_month' + $postfix).removeClass('invalid-form-value');
			}
		);

		$valid = false;
	}

	var $toward_flight_date = ts_getDate('toward_flight', $postfix);
	var $backward_flight_date = ts_getDate('backward_flight', $postfix);

	if (($toward_flight_date !== false) && ($backward_flight_date !== false) && ($backward_flight_date.getTime() < $toward_flight_date.getTime())) {
		if ($ts_error_messages.length && $ts_error_messages[$ts_error_messages.length - 1] == $ticket_search_params.phrases['lu_error_BackwardFlightDateInPast']) {
			// replace last error message for this field
			$ts_error_messages[$ts_error_messages.length - 1] = $ticket_search_params.phrases['lu_error_BackwardFlightDateBeforeTowardFlightDate'];
		}
		else {
			$ts_error_messages.push($ticket_search_params.phrases['lu_error_BackwardFlightDateBeforeTowardFlightDate']);
		}

		$('#backward_flight_date_day' + $postfix + ', #backward_flight_date_month' + $postfix)
		.addClass('invalid-form-value')
		.focus(
			function() {
				$('#backward_flight_date_day' + $postfix + ', #backward_flight_date_month' + $postfix).removeClass('invalid-form-value');
			}
		);

		$valid = false;
	}

	return $valid;
}

function ts_validateAirports($success_callback, $postfix, $is_full) {
	var preferredAirlineVisible = ($('#preferred_airline_input' + $postfix).length > 0);
	$.getJSON(
		'http://www.begonija.lv/inc/symphony/search_engine.js.html?env=symphony%5C-search---OnVerifyAirports-',
		{
			departure_airport_input: $('#departure_airport' + $postfix + '_input').val(),
			departure_airport_hidden: $('#departure_airport' + $postfix + '_hidden').val(),
			destination_airport_input: $('#destination_airport' + $postfix + '_input').val(),
			destination_airport_hidden: $('#destination_airport' + $postfix + '_hidden').val()		},

		function ($result) {
			// result is object with new value for hidden field or false, when failed
			if ($result.departure_airport_error || $result.destination_airport_error || $result.preferred_airline_error) {
				var error_message = false;
				if ($result.departure_airport_error) {
					ts_setError( $('#departure_airport' + $postfix + '_input') );
					$ts_error_messages.push($result.departure_airport_error);
				}
				if ($result.destination_airport_error) {
					ts_setError( $('#destination_airport' + $postfix + '_input') );
					$ts_error_messages.push($result.destination_airport_error);
				}

				if ($is_full) {
					if ($result.departure_airport2_error) {
						ts_setError( $('#departure_airport2' + $postfix + '_input') );
						$ts_error_messages.push($result.departure_airport2_error);
					}
					if ($result.destination_airport2_error) {
						ts_setError( $('#destination_airport2' + $postfix + '_input') );
						$ts_error_messages.push($result.destination_airport2_error);
					}
					if ($result.preferred_airline_error) {
						ts_setError( $('#preferred_airline' + $postfix + '_input') );
						$ts_error_messages.push($result.preferred_airline_error);
					}
				}

				var $res = false;
			}
			else {
				$('#departure_airport' + $postfix + '_input')
				//.val($result.departure_airport_name)
				.attr('hiddenValue', $result.departure_airport_id)
				.removeClass('invalid-form-value');

				$('#departure_airport' + $postfix + '_hidden').val($result.departure_airport_id);

				$('#destination_airport' + $postfix + '_input')
				//.val($result.destination_airport_name)
				.attr('hiddenValue', $result.destination_airport_id)
				.removeClass('invalid-form-value');

				$('#destination_airport' + $postfix + '_hidden').val($result.destination_airport_id);

				if ($is_full) {
					$('#departure_airport2' + $postfix + '_input')
					//.val($result.departure_airport2_name)
					.attr('hiddenValue', $result.departure_airport2_id)
					.removeClass('invalid-form-value');

					$('#departure_airport2' + $postfix + '_hidden').val($result.departure_airport2_id);

					$('#destination_airport2' + $postfix + '_input')
					//.val($result.destination_airport2_name)
					.attr('hiddenValue', $result.destination_airport2_id)
					.removeClass('invalid-form-value');

					$('#destination_airport2' + $postfix + '_hidden').val($result.destination_airport2_id);

					$('#preferred_airline' + $postfix + '_input')
					//.val($result.preferred_airline_name)
					.attr('hiddenValue', $result.preferred_airline_id)
					.removeClass('invalid-form-value');

					$('#preferred_airline' + $postfix + '_hidden').val($result.preferred_airline_id);
				}

				var $res = true;
			}

			$success_callback($res);
		}

	);
}

// only, when document is loaded
$(document).ready(
	function() {
		// code to execute, when document is ready
		$('#departure_airport').flexbox(
			'http://www.begonija.lv/inc/symphony/search_engine.js.html?env=symphony%5C-search---OnSuggestAirport-',
			{
				width: $airport_input_width,
				contentClass: 'flexbox-content',
				watermark: 'Izlidošanas pilsēta',
				noResultsText: 'Ja nekas netiek atrasts ievadot nosaukumu latviski, mēģiniet ievadīt galamērķa nosaukumu angļu valodā',
				initialHiddenValue: $ticket_search_params.departure_airport.initialHiddenValue,
				initialValue: $ticket_search_params.departure_airport.initialValue,
				paging: false,
				// maxVisibleRows: 8,
				showArrow: false,
				autoCompleteFirstMatch: false,
				arrowQuery: '#popular#',
			//	resultTemplate: '{name} {meta_info}',
				minChars: 3,
				onSelect: function () {}
			}
		);

		$('#destination_airport').flexbox(
			'http://www.begonija.lv/inc/symphony/search_engine.js.html?env=symphony%5C-search---OnSuggestAirport-',
			{
				width: $airport_input_width,
				contentClass: 'flexbox-content',
				watermark: 'Lidojuma galamērķis',
				noResultsText: 'Ja nekas netiek atrasts ievadot nosaukumu latviski, mēģiniet ievadīt galamērķa nosaukumu angļu valodā',
				initialHiddenValue: $ticket_search_params.destination_airport.initialHiddenValue,
				initialValue: $ticket_search_params.destination_airport.initialValue,
				paging: false,
				// maxVisibleRows: 8,
				showArrow: false,
				autoCompleteFirstMatch: false,
				arrowQuery: '#popular#',
			//	resultTemplate: '{name} {meta_info}',
				minChars: 3,
				onSelect: function () {}
			}
		);

		var departureAirport2 = $('#departure_airport2');
		if (departureAirport2.length > 0) {
			departureAirport2.flexbox(
				'http://www.begonija.lv/inc/symphony/search_engine.js.html?env=symphony%5C-search---OnSuggestAirport-',
				{
					width: $airport_input_width,
					contentClass: 'flexbox-content',
					watermark: 'Izlidošanas pilsēta 2',
					initialHiddenValue: '',
					initialValue: '',
					paging: false,
					// maxVisibleRows: 8,
					showArrow: false,
					autoCompleteFirstMatch: false,
					arrowQuery: '#popular#',
				//	resultTemplate: '{name} {meta_info}',
					minChars: 3,
					onSelect: function () {}
				}
			);
		}

		var destinationAirport2 = $('#destination_airport2');
		if (destinationAirport2.length > 0) {
			destinationAirport2.flexbox(
				'http://www.begonija.lv/inc/symphony/search_engine.js.html?env=symphony%5C-search---OnSuggestAirport-',
				{
					width: $airport_input_width,
					contentClass: 'flexbox-content',
					watermark: 'Ielidošanas pilsēta 2',
					initialHiddenValue: '',
					initialValue: '',
					paging: false,
					// maxVisibleRows: 8,
					showArrow: false,
					autoCompleteFirstMatch: false,
					arrowQuery: '#popular#',
				//	resultTemplate: '{name} {meta_info}',
					minChars: 3,
					onSelect: function () {}
				}
			);
		}

		
					$('#departure_airport_input, #destination_airport_input').css('height', '20px');
		
		// Flight day
		$('#toward_flight_date_day')
			.click( function ($e) { ts_calculateBackwardFlightDate('blur', ''); } )
			.change( function ($e) { ts_calculateBackwardFlightDate('blur', ''); } );

		// Toward Flight month
		$('#toward_flight_date_month')
			.click( function() { ts_verifyDate('toward_flight', ''); ts_calculateBackwardFlightDate('blur', ''); } )
			.change( function() { ts_verifyDate('toward_flight', ''); ts_calculateBackwardFlightDate('blur', ''); } );

		// Date pickers
		$("#toward_flight_date_picker, #backward_flight_date_picker").datepicker(
			$.extend(
				{},
				$.datepicker.regional['Latvian (Latvia) /lv-LV/'],
				{
					numberOfMonths: 2,
				    showOn: 'button',
				    buttonImage: 'img/calendar.gif',
				    buttonImageOnly: true,
				    minDate: new Date ($ticket_search_params.min_booking_date * 1000),
				    maxDate: new Date ($ticket_search_params.max_booking_date * 1000),
				    dateFormat: 'd/m/yy',
				    firstDay: 1,
				    onSelect: function(dateText) {
				    	var $mode = $(this).attr('mode');

						if (dateText) {
							// date was selected
							var $date_parts = dateText.split('/');
							var $date = new Date (parseInt($date_parts[2]), parseInt($date_parts[1]) - 1, parseInt($date_parts[0]), 0, 0, 0);
							ts_setDate($mode, $date, '');

							if ($mode == 'toward_flight') {
								ts_calculateBackwardFlightDate('blur', '');
							}
							else {
								ts_calculateTowardFlightDate('blur', '');
							}
						}
						else {
							// "Clear" link used
							var $date = ts_getDate($mode, '');
							$(this).val( $date.getDate() + '/' + ($date.getMonth() + 1) + '/' + $date.getFullYear() );
						}
					}
				}
			)
		);

		$('#toward_flight_date_picker').datepicker('setDate', ts_getDate('toward_flight', ''));
		$('#backward_flight_date_picker').datepicker('setDate', ts_getDate('backward_flight', ''));

		// -3 months
		var lastTowardDate = new Date ($ticket_search_params.max_booking_date * 1000);
		lastTowardDate.setDate(1);
		lastTowardDate.setMonth(lastTowardDate.getMonth() - 2);
		lastTowardDate.setDate(0);
		$('#toward_flight_date_picker').datepicker('option', 'maxDate', lastTowardDate);

		$('#toward_flight_date_day, #toward_flight_date_month, #backward_flight_date_day, #backward_flight_date_month').change(
			function ($e) {
				ts_setDate('toward_flight', ts_getDate('toward_flight', ''), '');
				ts_setDate('backward_flight', ts_getDate('backward_flight', ''), '');
			}
		);

		// Backward Flight Month
		$('#backward_flight_date_month')
			.click( function() { ts_verifyDate('backward_flight', ''); } )
			.change( function() { ts_verifyDate('backward_flight', ''); } )

		// on form submit
		$('#airline_ticket_search_form').submit (
			function ($e, $verify_airports) {
				// remove postfix from fields
				$('input[name=departure_airport]').attr('name', 'departure_airport');
				$('input[name=destination_airport]').attr('name', 'destination_airport');
				$('input[name=preferred_airline]').attr('name', 'preferred_airline');

				// make sure, that all entered values are saved to hidden fields
				if ($verify_airports === undefined || $verify_airports === true) {
					// don't submit, do ajax query to validate airportsin input boxes
					$e.preventDefault();

					ts_validateAirports(
						function($result) {
							if (!ts_validateForm('') || !$result) {
								var $error_msg = $form_error_msg;
								if ($ts_error_messages.length) {
									$error_msg += "\n" + $ts_error_messages.join("\n");
								}

								$ts_error_messages = []; // reset error messages
								alert($error_msg);

								return ;
							}

							// don't perform ajax query again
							$('#airline_ticket_search_form').trigger('submit', false);
						},
						'', false					);
				} else {
					if (!ts_validateForm('')) {
						var $error_msg = $form_error_msg;
						if ($ts_error_messages.length) {
							$error_msg += "\n" + $ts_error_messages.join("\n");
						}

						$ts_error_messages = []; // reset error messages
						alert($error_msg);

						$e.preventDefault();
					}
				}
			}
		);

		var $directions = $('#directions_0, #directions_1, #directions_2');
		$directions.click(
			function () {
				var $checked_direction = $directions.filter(':checked');
				if ($checked_direction.val() == '1') {
					$('#backward_flight_date_title_tr, #backward_flight_date_input_tr, #backward_flight_date, #backward_flight_date_picker_tr, #backward_flight_date_select_td, #backward_flight_date_picker_td, #backward_flight_date_label_td').hide();
					$('#toward_flight_airport2_tr, #backward_flight_airport2_tr').hide();
				}
				else if ($checked_direction.val() == '0') {
					$('#backward_flight_date_title_tr, #backward_flight_date_input_tr, #backward_flight_date, #backward_flight_date_picker_tr, #backward_flight_date_select_td, #backward_flight_date_picker_td, #backward_flight_date_label_td').show();
					$('#toward_flight_airport2_tr, #backward_flight_airport2_tr').hide();
				}
				else if ($checked_direction.val() == '2') {
					$('#backward_flight_date_title_tr, #backward_flight_date_input_tr, #backward_flight_date, #backward_flight_date_picker_tr, #backward_flight_date_select_td, #backward_flight_date_picker_td, #backward_flight_date_label_td').show();
					$('#toward_flight_airport2_tr, #backward_flight_airport2_tr').show();

					if ($('#price_choice').val() != 'MSP' && $('#price_choice').val() != 'AVB') {
						$('#price_choice').val('MSP');
					}
				}

				if (typeof(resizeBlocks) == 'function') {
					$('.first-row-div').css({height: 'auto'});
					resizeBlocks();
				}
			}
		);

		$directions.filter(':checked').click();

		$('#price_choice').change(
			function () {
				if ($(this).val() != 'MSP' && $(this).val() != 'AVB') {
					$('#directions_0').attr('checked', true);
					$('#directions_0').click();
				}
			}
		);

			}
);