var speed = 310;

var datepickerDefaults = {
		dateFormat : 'yy-mm-dd', //'ISO_8601'
		firstDay: 1,
		yearRange: '-0:+1',
		numberOfMonths: 1,
		closeText: 'Zamknij',
		prevText: '&#x3c;Poprzedni',
		nextText: 'Następny&#x3e;',
		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','Poniedziałek','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 Page = {
		Action : null,
		GetAction : function()
		{
			return String(this.Action).replace(/_action$/,'');
		},
		Init : function(){
			this.Action = String($('body').attr('class')).toLowerCase().match(/\w+_action/);
			//log(this.GetAction());
		}
	};

//Main Travel object
var Travel = {
Autocomplete : {
	delay: 10,
	minChars: 3,
	matchSubset: 0,
	matchContains: 0,
	cacheLength: 20,
	autoFill: false,
	maxItemsToShow: 20,
	autoFillOne: false,
	resultsClass: 'ac_results ac_travel',
	extraParams: {
		format: 'json',
		request: 'autocomplete',
		encoding: 'utf-8',
		language: 'pl',
		callback: '?'
	},
	formatItem: function(e){
		var elementname = (typeof e.elementhiglight !== 'undefined') ? e.elementhiglight : (e.parents != '' ? e.parents : e.elementname);
		return '<div class="ac_line">'+elementname+'<span class="arrow"></span></div>';
	},
	onChange: function(e){
		$(e).closest('form').find('[name=AutocompleteDestinationCode]').val('');
		$(e).closest('form').find('[name=DestinationType]').val('');
	},
	onItemSelect: function(e){
		$(e.related).closest('form').find('[name=AutocompleteDestinationCode]').val(e.data.elementcode);
		$(e.related).closest('form').find('[name=DestinationType]').val(e.data.type);
	}
},
	Datepicker : {
		minDate: '+0d',
		maxDate: '+365d'
	},
	Tabs : {
		tab_widths: [],
		max_tab_width: 180
	},
	// [jQ object] offer form pointer (searchresults) - needed by link in gallery popup
	currentOfferForm: undefined,
	// [jQ object] gallerrific object - needed for controlling gallery behavior later (next/prev/play/pause)
	gallery_object: undefined,
	// variant JSON cache
	cachedVariants: undefined,
	// count properties in objects (count for JSON)
	countJSON: function(obj) {
		var prop, propCount = 0;
		for (prop in obj) {
			if(obj.hasOwnProperty(prop)) {
				propCount++;
			}
		}
		return propCount;
	},

	/**
	 * Safe get value
	 * @author lkieres
	 * @param {String} text Value to be printed
	 * @param {String} replacementText Text which will replace original value in case of null or empty, default 'No data' text [optional]
	 */
	safeVal: function(text, replacementText) {
		return ((text!=null) && (text != '')) ? text : (typeof replacementText != 'undefined') ? replacementText : I18N_Travel_No_Data
	},

	/**
	 * Safe-length text
	 * @author lkieres
	 * @param {String} text Text to be shortened if its length exceedes given or default value
	 * @param {Number} cutlen Maximal length of text [optional]
	 */
	safeLength: function(text,cutlen) {
		var cutto = cutlen || 25;
		return (text.length<cutto) ? text : text.substr(0,cutto) + '...';
	},

	/**
	 * PHP's in_array implementation
	 */
	in_array: function(needle, haystack, strict) {
    var found = false, key, strict = !!strict;
    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }
    return found;
	},

	/**
	 * Test for IE6 and below
	 */
	isIE6: function(){
		return ((document.all && !window.opera && !window.XMLHttpRequest) ? true : false);
	}
};

/**
 * Give element hasLayout property in IE6 to fix bugs in rendering
 * @author lkieres
 */
$.fn.IEgiveLayout = function(){
	return this.each(function(){
		$(this).css('zoom',1);
	});
};

var Load = {
		Js : function(file){
			document.write(unescape('%3C')+'script type="text/javascript" src="'+file+'"'+unescape('%3E%3C')+'/script'+unescape('%3E'));
		}
	};

//load png fixer as soon as possible for IE6 only (fails in IE>6)
if (Travel.isIE6()) Load.Js(ibeConfig.host + '/common/scripts/plugins/dd_belatedpng.min.js');

$(document).ready(function(){

	Page.Init();

	// fixes for IE6
	if (Travel.isIE6()) {
		// fix layout
		//$('.thumb span').IEgiveLayout();
		//$('#variant-form').IEgiveLayout();
		//$('*').IEgiveLayout();
		// fix PNG problem
		DD_belatedPNG.fix('.thumb span, .trip-character span, ul, .featured-destinations-column div span, .ui-datepicker-trigger, .wheater-ico em, .ui, .ui-star, em');
	};

	$('.qsf-vertical-buttons').click(function(){

		tempo = "fast";

		$button = $(this);

		if(!$button.parents('li').hasClass('active')) {
			$('#qsf-main-content form').animate({
				  "opacity": 0
			}, tempo, function() {

				$('#qsf-nav ul li').removeClass('active');

				$('#qsf-main-content form').css('display', 'none');
				$form = $('#' + $button.attr('id') + '-qsf');
				$form.css('display', 'block');
				$form.animate({
					"opacity": 1
				}, tempo);
				$button.parents('li').addClass('active');

			});
		}
	});

	// selecting number of children
	$('#Travellers-Child,#ToursTravellers-Child').change(function() {
		$age = $(this).closest('fieldset').find('.children-age');
		// no children
		if ($(this).val() == '0') {
			$(this).closest('#qsf-childs-container').removeClass('selected');
			$age.addClass('hidden');
		// some children
		} else {
			$(this).closest('#qsf-childs-container').addClass('selected');
			$age.addClass('hidden');
			$(this).closest('fieldset').find('.children-age select').addClass('hidden');
			$(this).closest('fieldset').find('.children-age select:lt('+$(this).val()+')').removeClass('hidden');
			$age.removeClass('hidden');
		}
	}).change();

	//travel autocomplete
	$('#DestinationCode,').autocomplete(ibeConfig.travelAutocomplete,Travel.Autocomplete);

	//travel autocomplete
	$('#ToursDestinationCode').autocomplete(ibeConfig.travelAutocomplete,Travel.Autocomplete);

	$('input.virgin').bind('focus', function(){
		if($(this).hasClass('virgin')){ // do it only if the object still has "virgin" class
			$(this).attr('rel', $(this).attr('value'));
			$(this).val('');
			$(this).removeClass('virgin');
		}
	});

	$('input.virgin').bind('focusout', function(){
		if($(this).attr('value') == '') {
			$(this).attr('value', $(this).attr('rel')).addClass('virgin');
		} else {
			$(this).removeClass('virgin');
		}
	});

	$('input.virgin').bind('change', function(){
		if($(this).attr('value') == '') {
			$(this).attr('value', $(this).attr('rel'));
			$(this).addClass('virgin')
		} else {
			$(this).removeClass('virgin');
		}
	});

	$('input[type=text]').focus(function(){
		$(this).get(0).select();
	});


	$.datepicker.setDefaults(datepickerDefaults);

	$('[name=DepartureDateFrom]').datepicker({
		minDate: '+0d',
		maxDate: '+365d'
	});

	$('[name=DepartureDateTo]').datepicker({
		minDate: '+0d',
		maxDate: '+365d',
		beforeShow: function(){
			var checkin = $('[name=DepartureDateFrom]',$(this).closest('form')).datepicker('getDate');
			return (this.name == 'DepartureDateTo') ? {
				minDate: new Date(Date.parse(checkin) + 1*24*60*60*1000),	//Add one day to departure date
				maxDate: new Date(Date.parse(checkin) + 365*24*60*60*1000)	//Add 365 days to departure date
			} : {};
		}
	});

	// NEW QSF
	// destination list in ASF
	$('#destination-list-button').click(function() {
		// if list is visible hide it, unbind click-outside-to-close event
		if ($('#destination-list:visible').length) {
			$('#destination-list').hide();
			$('body').unbind('click');
		} else {
		// prepare list position, iframe, etc on init
			if (($('#esky-body > #destination-list').size()==0) || ($('#esky > #destination-list').size()==0)) {
				var offset = $(this).prev('input').offset();
				$('#destination-list').css({left: offset.left, top: offset.top+$(this).prev().height()+2}).appendTo('body').bgIframe();

				// bind destination selection event
				$('#destination-list li a').click(function() {
					if (typeof $('#DestinationCode').data('hint') === 'undefined') {
						$('#DestinationCode').data('hint',$('#DestinationCode').val());
					}
					$('#AnyDestination').attr('checked',false);
					$('#DestinationCode').removeClass('virgin').val($(this).text());
					// set destination type (country/region/province/city)
					$('#DestinationType').val($(this).attr('rev'));
					// set destination code
					$('#AutocompleteDestinationCode').val($(this).attr('rel'));
					// hide list and unbind close event
					$('#destination-list').hide();
					$('body').unbind('click');
				});
			}

			// on initial show only 5 countries
			$('#countries-list li:gt(4)').addClass('hidden');
			// and all headers
			$('#destination-list h4:first,#destination-list h4:last, #destination-list ul:first').show();
			// country list not yet scrollable
			$('#destination-list').removeClass('scrollable').show();

			// bind click-outside-to-close event
			$('body').one("click",function() {
				$('#destination-list').hide();
				return false;
			});
			// allow to click inside list
			$('#destination-list').click(function(event){
				event.stopPropagation();
			});
		}
		return false;
	});

	// handle showing all countries on list
	$('#show-all-countries').click(function() {
		$('#destination-list').get(0).scrollTop = 0;
		$('#countries-list li').removeClass('hidden');
		$('#destination-list h4:first, #destination-list h4:last, #destination-list ul:first').slideUp(500, function() {
			$('#destination-list').addClass('scrollable');
		});
	});

	// if destination field in ASF is focused - uncheck anydestination checkbox
	$('#DestinationCode').focusin(function() {
		$('#AnyDestination').attr('checked',false);
	});

	// handle any destination field
	$('#AnyDestination').click(function(){
		if ($(this).is(':checked')) {
			if (typeof $('#DestinationCode').data('hint') == 'undefined') {
				$('#DestinationCode').data('hint',$('#DestinationCode').val());
			}
			$('#DestinationCode').addClass('virgin').val('Dowolny kierunek');
			$('#DestinationType').val('');
			$('#AutocompleteDestinationCode').val('');
		} else {
			$('#DestinationCode').addClass('virgin').val($('#DestinationCode').data('hint'));
		}
	});

});

