Date.format = "yyyy-mm-dd";
var I18N_Language = 'pl';
var I18N_datepicker = {
	dateFormat : 'yy-mm-dd', //'ISO_8601'
	firstDay: 1,
	yearRange: '-0:+1',
	numberOfMonths: 1,
	closeText: 'Zamknij',
	prevText: '&laquo;',
	nextText: '&raquo;',
	currentText: 'Dziś',
	monthNames: ['Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec','Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień'],
	monthNamesShort: ['Sty','Lu','Mar','Kw','Maj','Cze','Lip','Sie','Wrz','Pa','Lis','Gru'],
	dayNames: ['Niedziela','Poniedzialek','Wtorek','Środa','Czwartek','Piątek','Sobota'],
	dayNamesShort: ['Nie','Pn','Wt','Śr','Czw','Pt','So'],
	dayNamesMin: ['N','Pn','Wt','Śr','Cz','Pt','So'],
	isRTL: false,
	showOn:'both',
	duration:'',
	buttonText: 'Wybierz datę'
};
var I18N_CalendarText = {
	'OutGreaterThenReturn' : 'Data powrotu musi być wyznaczona minimum na ten sam dzień co data wylotu.',
	'OutDateToClose' : 'Data wylotu musi być wyznaczona minimum na jedeń dzień w przód od dnia dzisiejszego.',
	'DateOutOfRange' : 'Wybrana data wykracza poza zakres dostępnych rezerwacji.',
	'OnlyCCPayment' : 'W przypadku podróży rozpoczynających się w ciągu najbliższych 2 dni udostępniamy jedynie płatność kartą płatniczą. W przypadku gdy nie posiadacie Państwo karty prosimy o kontakt z naszym Call Center.'
};

var I18N_ACSeparator = {
	'city' : 'Miasta',
	'airport' : 'Lotniska',
	'province' : 'Prowincje',
	'country' : 'Państwa',
	'region' : 'Regiony',
	'poi' : 'Punkty szczególne'
};


var today = function(){
	var today = new Date();
	today.setHours(0);
	today.setMinutes(0);
	today.setSeconds(0);
	today.setMilliseconds(0);
	return today;
};

var closeCalendar = function() {
	$('#esky_calendar').empty().remove();
};

var Flights = {
	Autocomplete : {
		url: 'http://www.eskyservices.pl/autocomplete/airport/v2/',
		delay: 300,
		minChars: 3,
		matchSubset: 1,
		matchContains: 1,
		cacheLength: 10,
		autoFill: false,
		maxItemsToShow: 15,
		autoFillOne: true,
		element: 'CityName',
		extraParams: {
			request: 'autocomplete',
			encoding: 'utf-8',
			language: I18N_Language,
			callback: '?'
		},
		formatItem: function(row) {
			if (row.CountryName=='') {
				return '<div class="ac_line"><strong>'+row.CityName+'</strong> ('+row.AirportCode+')</div>';
			} else {
				return '<div class="ac_line"><strong>'+row.CityName+'</strong>, '+row.CountryName+' - '+row.AirportName+' ('+row.AirportCode+')</div>';
			}
		},
		formatResult: function(row) {
			if (row.CountryName=='') {
				return row.CityName+" ("+row.AirportCode+")";
			} else {
				return row.CityName+", "+row.CountryName+" - "+row.AirportName+" ("+row.AirportCode+")";
			}
		},
		onItemSelect: function(e){
			$(this).watermark('option','clear');
		},
		watermark: {
			text: 'wpisz nazwę miejscowości lub lotniska...'
		}
	},
	Datepicker : {
		minDate: '+1d',
		maxDate: '+365d',
		/*
		 * beforeShowDay is used to render day in calendar before it is shown.
		 * We use it to add information about only CC payment when making reservation
		 * for the nearest two days (only-cc-payment class is added and additional title).
		 */
		beforeShowDay: function(date) {
			if (date <= new Date().setDate(new Date().getDate() + 2) && date > new Date()) {
				return [1, 'only-cc-payment', I18N_CalendarText.OnlyCCPayment];
			} else {
				return [1,'',''];
			}
		},
		/*
		 * beforeShow is used to setup calendar before it is shown.
		 * When index of the input is greater then 0 the we need to change minDate and maxDate
		 */
		beforeShow: function(){
			var _index = String(this.name).match(/^Fly\[(\d*)\]\[(DepartureDate|ArrivalDate)\]$/);
			if (_index[1] != '0') {
				var _previous_date = parseInt(_index[1]) > 1
							? $('[name$="['+(parseInt(_index[1],10)-1)+']['+_index[2]+']"][id$="multi"]').datepicker('getDate')
							: $('[name$="['+(parseInt(_index[1],10)-1)+']['+_index[2]+']"]').datepicker('getDate')
							;
				return (_previous_date instanceof Date) ? {
					minDate: new Date(Date.parse(_previous_date)),
					maxDate: new Date(Date.parse(_previous_date) + 365 * 24 * 60 * 60 * 1000) //Add 365 days to daparture date
				} : {};
			} else {
				return {};
			}
		},
		onSelect: function(dateText, inst){
			$(this).watermark('option','clear');
		},
		watermark: {
			text: 'RRRR-MM-DD'
		}
	}
};

$.watermark = {
	marker: 'hasWatermark',
	eclass: 'watermark',
	text: '',
	emptyOnSumbit: true
};
$.fn.watermark = function(options, action)
{
	if (options == 'option' && $(this).hasClass($.watermark.marker))
	{
		var settings = $(this).data('settings');

		switch (action)
		{
			case 'clear':
				$(this).removeClass(settings.eclass);
				break;
			case 'reset':
				$(this).addClass(settings.eclass).val(settings.text);
				break;
			case 'empty':
				$(this).val('');
				break;
		}
	}
	if (typeof options == 'object')
	{
		var settings = $.extend({}, $.watermark, options);

		$(this)
			.filter('input:text')
			.data('settings', settings)
			.addClass(settings.marker)
			.blur(function(){
				if ($(this).val() == '')
				{
					$(this).addClass(settings.eclass).val(settings.text);
				}
			})
			.click(function(){
				if ($(this).hasClass(settings.eclass))
				{
					$(this).removeClass(settings.eclass);

					if($(this).val() == settings.text)
					{
						$(this).val('');
					}
				}
			})
			.filter(function(){
				return $(this).val() == '' || $(this).val() == settings.text;
			})
			.addClass(settings.eclass)
			.val(settings.text);

		if(settings.emptyOnSumbit)
		{
			var $element = $(this);
			$element.closest('form').submit(function(){
				if ($element.hasClass(settings.eclass) && $element.val() == settings.text) {
					$element.watermark('option', 'empty');
				};
			});
		}
	}
	return $(this);
};
jQuery.fn.DeactivateFormFields = function() {
	$(this)
		.addClass('deactivated-form').hide()
		.find('input,select').attr('disabled','disabled');
};
jQuery.fn.ActivateFormFields = function() {
	$(this)
		.removeClass('deactivated-form').show()
		.find('input,select').removeAttr('disabled');
};
jQuery.fn.FlightSearchForm = function(settings) {

	var Config = (typeof settings === 'object') ? settings : Flights;

	$this = $(this);

	var date_options = $('#Fly-1-DepartureDate:first',$this).parent();

	$('[name=TripType]',$this).click(function(){
		switch(this.value){
			default:
			case 'roundtrip':
				date_options.ActivateFormFields();
				break;
			case 'oneway':
				date_options.DeactivateFormFields();
				break;
		}
	}).find(':checked').click();

	$('[name$=[DepartureDate]]',$this)
		.datepicker(Config.Datepicker)
		.watermark(Config.Datepicker.watermark);

	$('[name$=[DepartureCity]],[name$=[ArrivalCity]]',$this)
		.autocomplete(Config.Autocomplete.url,Config.Autocomplete)
		.watermark(Config.Autocomplete.watermark);

	return $this;
};

