// indexOf prototype is browser doesn't support it (IE)
if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        };
        return -1;
    };
};

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);
	},
	/**
	 * Trim - IE doesn't support .trim()
	 * @param {String} text Text to be trimmed
	 */
	trim: function(str) {
		return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
	}
};

/**
 * Give element hasLayout property in IE6 to fix bugs in rendering
 * @author lkieres
 */
$.fn.IEgiveLayout = function(){
	return this.each(function(){
		$(this).css('zoom',1);
	});
};

/**
 * Nice Hint plugin
 * @author lkieres
 * @param {Object} options
 */
$.fn.niceHint = function(options){
	var defaults = {
		animationDuration : 0,
		value: function(e) {
			return e.find('span').text();
		},
		beforeHintShow : function(){},
		afterHintHide : function(){}
	};
	var settings = $.extend({}, defaults, options);

	return this.each(function(){
		// help cursor
		$(this).css('cursor','hand');

		// bind onhover events
		$(this).hover(
			// onhover
			function() {
				settings.beforeHintShow.call(this);
				//remove old hint if exists
				if ($('#nice-hint').size()) {
					$('#nice-hint').remove();
				}

				if (typeof $(this).data('tip') == 'undefined') {
					$(this).data('tip', settings.value($(this))).removeAttr('title');
				}

				var content = $(this).data('tip');
				$(this).addClass('hover');


				var offset = $(this).offset();

				var $hint = $('<div></div>')
								.attr('id','nice-hint')
								.css({
										'left': -5000,
										'top': offset.top-24
								})
								.append($('<span></span>'))
								.find('span').text(content)
								.end()
								.prepend($('<em class="l"></em>'))
								.append($('<em class="r"></em>'))
								.append($('<ins></ins>'))
								.appendTo('body');

				$hint.hover(function() {$(this).addClass('hover');},function(){$(this).removeClass('hover');});
				$hint.css('left', offset.left-($hint.width()/2) + 4);
				if (settings.animationDuration == 0) {
					$hint.show();
				} else {
					$hint.animate({'opacity':'show',top: '+=6'},settings.animationDuration);
				}
			},
			// on hoverout
			function() {
				$(this).removeClass('hover');
				if (settings.animationDuration == 0) {
					$('#nice-hint').hide();
				} else {
					$('#nice-hint').animate({'opacity':'hide'},settings.animationDuration);
				}
				settings.afterHintHide.call(this);
			}
		);
	});
};

var Load = {
		Js : function(file){
			document.write(unescape('%3C')+'script type="text/javascript" src="'+file+'"'+unescape('%3E%3C')+'/script'+unescape('%3E'));
		}
	};

/* NEWSLETTER SUBSCRIPTION */
function newsletterSubscription() {
	var $form = $('#travelNewsletterBox'),
		$response = $form.find('#newsletter-response'),
		email = $form.find('#newsletterEmail').val();
	if (!(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})$/.test(email))) {
		$response.attr('class', 'error').text('Prosimy o podanie poprawnego adresu e-mail.').fadeIn('normal');
		return false;
	}
}

//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('#esky-menu li, #esky-menu li a, #esky-menu .icon-home, .thumb span, .trip-character span, ul, .featured-destinations-column div span, .ui-datepicker-trigger, .wheater-ico em, .ui, .ui-star, em');
	};

	// przycisk "szukanie zaawansowane" submitujacy formularz do ASF
	// w celu przeniesienia danych
	$('#travel-advanced-search').click(function(){
		$('#travel-packages-qsf').attr('action', $(this).attr('href'));
		$('#travel-packages-qsf').submit();
		return false;
	});

	if ($('#qsf-container').length) {
		var qsfFormSpeed = 'fast',
	    showQsfForm = function(el) {
				$('#qsf-main-content form').css('display', 'none');
				$('#' + el.attr('id') + '-qsf')
					.css('display', 'block')
					.animate({
						"opacity": 1
					}, qsfFormSpeed, Insurances.Calculate);
		};

		$('.qsf-vertical-buttons').each(function() {
			var $button = $(this), $btnParent = $button.parents('li');
			if ($btnParent.hasClass('active')) {
				showQsfForm($button);
			}
			$button.click(function() {

				if(!$btnParent.hasClass('active') && (!$("#qsf-main-content").children("form:animated").length)) {
					$('#qsf-main-content form:visible').animate({
						  "opacity": 0
					}, qsfFormSpeed, function() {

						$('#qsf-nav ul li').removeClass('active');
						showQsfForm($button);
						$btnParent.addClass('active');
					});
					$(".error-tip").hide();
				}
			});
		});
	}

	// 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();*/

	// selecting number of children
	$('#Travellers-Child,#ToursTravellers-Child').change(function() {
		$age = $(this).closest('fieldset').find('.children-dob');

		var $closest_label = $(this).closest('#qsf-childs-container');

		// no children
		if ($(this).val() == '0') {
			$closest_label.removeClass('selected');
			$age.addClass('hidden');
		// some children
		} else {
			$closest_label.addClass('selected');
			$age.addClass('hidden');
			$(this).closest('fieldset').find('.children-dob li').addClass('hidden');
			$(this).closest('fieldset').find('.children-dob li:lt('+$(this).val()+')').removeClass('hidden');
			$age.find('small').text(($(this).val() == '1')?'Data urodzenia dziecka:':'Daty urodzenia dzieci:');
			$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');
		}
	});



	/*
	.one('focus',function(){
		if($(this).hasClass('virgin')){ // do it only if the object still has "virgin" class
			$(this).attr('rel', $(this).attr('value'));
			$(this).val('');

		}
	});
*/

	$('input[type=text]').focus(function(){
		$(this).get(0).select();
	});


	$.datepicker.setDefaults(datepickerDefaults);

	// calendar - departure date
	$('#DepartureDateFrom').datepicker({
		minDate: Travel.Datepicker.minDate,
		maxDate: Travel.Datepicker.maxDate
	});

	// 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');
			$(document).unbind('keypress');
		} else {
		// prepare list position, iframe, etc on init
			if (($('#esky-body > #destination-list').size() == 0) || ($('#body > #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();
				$("#esky-wrapper").find("div[id=destination-list]").remove();
			}
			// 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');
				$('#destination-list li a').unbind();
			});

			// 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();
				$(document).unbind('keypress');
				$('#destination-list li a').unbind();
				return false;
			});
		}

		return false;
	});

	$('#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');
		});

		var firstLetters = [];

		$('#countries-list li a').each(function() {
			var country = $(this).text();
			var firstLetter = country.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
			firstLetters.push(firstLetter.substring(0,1).toLowerCase());
		});

		// 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');
			});
			return false;
		});

		$(document).keypress(function(event){
			var letter_position = firstLetters.indexOf(String.fromCharCode(event.which));

			if ((typeof letter_position != 'undefined') && (letter_position > -1))  {
				var off_top = $('#countries-list li:eq(' + letter_position + ')').get(0).offsetTop;
				$('#destination-list').get(0).scrollTop = off_top;
			}
		});
		return false;
	});

	// 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'));
		}
	});

	$('#travel-packages-qsf').submit(function () {
		$(this).find('input.virgin').val('');
	});

	$("#trip-character-selector li a.trip-character").click(function(){

		if($(this).hasClass('trip-active')) {
			return false;
		} else {

			$tripActive = $("#trip-character-selector li a.trip-active");
			$active = $(this);

			//$tripActive.parent().slideDown('slow');

			//$active.parent().slideUp('slow');

			$tripActive.parent().animate({
				height: '31px'
			}, speed);

			$active.parent().animate({
				height: '297px'
			}, speed);


			$tripActive.removeClass('trip-active');
			$active.addClass('trip-active');

		};

	});


	//$("#holidays-best-offers-selector li a").parent().click(function(){

	//});


	$("#holidays-best-offers-selector li a.selector").click(function(){

		if($(this).parent().hasClass('active')) {
			return false;
		} else {
			$boActive = $("#holidays-best-offers-selector li.active");
			$this = $(this).parent();

			slidedDownHeight = $boActive.height();
			slidedUpHeight = $this.height();

			$this.data("originalHeight", slidedUpHeight);
			$boActive.data("originalHeight", slidedDownHeight);

			$this.css("height", $this.height()+"px");
			$boActive.css("height", $boActive.height()+"px");

			$this.addClass('active');
			$boActive.removeClass('active');

			$boActive.stop().animate({
				height: ['32px', 'swing']
			}, { queue:false, duration:speed,
				specialEasing: {
			      height: 'easeOutBounce'
			    }

			});

			$this.stop().animate({
				height: ['170px', 'swing']
			}, { queue:false, duration:speed,
				specialEasing: {
			      height: 'easeOutBounce'
			    }
			});


		}

		return false;
	});

	if($('#featured-destinations-carousel').length > 0) {
		jQuery('#featured-destinations-carousel').jcarousel({
	    	wrap: 'circular',
	    	scroll: 2,
	    	animation: 'slow',
	    	visible: 2,
	    	auto: 10,
	    	itemVisibleInCallback: {
				onAfterAnimation: function(instance, object, index, state) {

					$emActive = $('#featured-destinations-marker em.active');

					if((state == 'next') && (index % 2 == 0)) {

						if($emActive.next('em').length == 0) {
							$emActive.removeClass('active');
							$('#featured-destinations-marker em:first').addClass('active');
						} else {
							$emActive.removeClass('active').next('em').addClass('active');
						}

					}
					if((state == 'prev') && (index % 2 == 0)) {

						if($emActive.prev('em').length == 0) {
							$emActive.removeClass('active');
							$('#featured-destinations-marker em:last').addClass('active');
						} else {
							$emActive.removeClass('active').prev('em').addClass('active');
						}

					}
					if(state == 'init') {
						$('#featured-destinations-marker em:first').addClass('active');
					}
					return false;
	    		}
			}
	    });
		$('#featured-destinations-marker').appendTo('.jcarousel-container');
	}

	$('a.social-icons').niceHint();

	clearDestinationCode();

	/*
	 * Newsletter bind actions
	 */
	if($('form.newsletter').length > 0) {
		$('form.newsletter')
		.end()
		.find('#newsletter-subscribe').click(newsletterSubscription).end()
		.find('#newsletter-unsubscribe').click(newsletterSubscription);

		$('#newsletterEmail').click(function(){
			if($(this).attr('value') == "wpisz adres email...") {
				$(this).attr('value', '');
			}
		});
	}

	if($('.newsletter form #date_to').length > 0) {
		$('.newsletter form #date_to').click(function(){
			$('#unsubscribe-select').removeAttr('disabled');
		});

		$('.newsletter #permanent').click(function(){
			$('#unsubscribe-select').attr('disabled', 'disabled');
		});

		$('.newsletter form #other_reason').click(function(){
			if($(this).attr('checked')) {
				$('#other-reason-content').removeAttr('disabled');
			} else {
				$('#other-reason-content').attr('disabled', true);
			}
		});
	}

	if($('#newsletter-preferences-form').length > 0) {
		$('#newsletter-preferences-form').validate({
			event: "keyup",
			errorContainer: "#messages",
			errorLabelContainer: "#messages div ul",
			errorClass: "error",
			wrapper: "li",
			rules: {
				postalcode_1: {
					number: true,
					min: 2
				},
				postalcode_2: {
					number: true,
					min: 3
				}
			},
			messages: {
				postalcode_1: {
					number: 'Prosimy o wpisanie kodu pocztowego w prawidłowym formacie'
				},
				postalcode_2: {
					number: 'Prosimy o wpisanie kodu pocztowego w prawidłowym formacie'
				}
			},
			success: function(label) {
				label.remove();
			}
		});
	}

	$('body').find('img.load-image').each(function(){
		if($(this).attr('data-src') !== undefined) {
			$(this).attr('src', $(this).attr('data-src'));
			$(this).removeAttr('data-src');
		}
	});

	if($('#press-datepicker').length > 0) {

		var events = '';

		$.post(ibeConfig.pressCalendar, null, function(data){

			var events = data;
			var eventsArray = [];
			var maxDate;
			var minDate;
			$(events).each(function(i){
				var press_date = this['press_date'].split(',');
				var eventDate = new Date(press_date[0], press_date[1]-1, press_date[2]);
				if (!i)
					maxDate = eventDate;
				eventsArray[eventDate.getTime()] = this['press_date'];
				minDate = eventDate;
			});
			$('#press-datepicker').removeClass('loading');
			var temp = eventsArray;

			$('#press-datepicker').datepicker({
				beforeShowDay: function(date) {
					return {0: ((typeof eventsArray[date.getTime()] !== 'undefined') ? true : false), 1: ''};
				},
				onSelect: function(dateText, inst) {
					document.location = ibeConfig.pressFindByDate + '/' + dateText;
				},
				minDate: minDate,
				maxDate: maxDate
			});
			$(".ui-datepicker-days-cell-over").removeClass("ui-datepicker-days-cell-over");
			$(".ui-datepicker-current-day").removeClass("ui-datepicker-current-day");
			$(".ui-state-active").removeClass("ui-state-active");
			$(".ui-state-hover").removeClass("ui-state-hover");


			if(typeof setDatepickerCurrentDate === 'function') {
				setDatepickerCurrentDate();
			};
		});
	}

	if (jQuery.fn.fancybox && $(".fancybox").length) {

		$(".fancybox").fancybox();
	}

});

function clearDestinationCode() {
	if ($('#travel-packages-qsf').length) {
		var $input = $('#DestinationCode');
		var $inputVal = $input.val();
		$('#travel-packages-qsf').submit(function() {
			if ($input.val() == $inputVal) {
				$input.val('');
			}
		});
	}
}

