$(function($) {
	// Wyszukiwarka
	var defaultValues = {
		'searcher-target-region'	:	'Cel podróży', 
		'searcher-target-hotel'		:	'Nazwa hotelu',
		'searcher-date'				:	'Termin',
		'searcher-departure-place'	:	'Wylot',
		'searcher-price-from'		:	'Od',
		'searcher-price-to'			:	'Do'
	};
	
	$.each(defaultValues, function(id, value) {
		$('#' + id).focus(function(){
			if ($('#' + id).val() === value) $('#' + id).val('');
		});
		$('#' + id).blur(function(){
			if ($('#' + id).val() === '') $('#' + id).val(value);
		});
	});
    
    // Colorbox
    $("#how_use").colorbox({inline:true, width:"50%", top:"20%"});
    
    // Ikona z informacja w lewym menu
    $(".left-panel-information").hover(function(){
    	$(this).removeClass('icon-information-grey');
    	$(this).addClass('icon-information-orange');
    }, function(){
    	$(this).removeClass('icon-information-orange');
    	$(this).addClass('icon-information-grey');
    })
    
    // Slider na stronie glownej
	$('#slider').anythingSlider({
		width          		: 685,
		height 		        : 240,
		buildNavigation     : false
	});
	
	// Slider na stronie oferty
	$('.offer-slider').anythingSlider({
		width               : 680,
		height              : 50,
		startStopped        : true,
		resizeContents      : false,
		showMultiple    	: 9,
		buildNavigation     : false,
		animationTime       : 300,
	});
	
	// Zakładki
	var selectedAnchor = window.location.hash;
	var selectedElement = document.getElementById(selectedAnchor.replace('#', ''));
	if (selectedElement == null) { 
		var selectedIndex = 0;
	} else {
		var selectedIndex = $('.tabs div').index(selectedElement);
	}
	
	$( '.tabs' ).tabs({
		selected	: selectedIndex
	});
	
	$( '.ui-tabs-nav li' )
	.append('<span class="corners tabs-corner-blue-left"></span>' +
			'<span class="corners tabs-corner-blue-right"></span>' +
			'<span class="corners tabs-corner-silver-left"></span>' +
			'<span class="corners tabs-corner-silver-right"></span>'				
	);
	
	$('.tab-go-terms-prices').click(function(){
		$( '.tabs' ).tabs( "option", "selected", 1 );
	});
	
	// Img Tooltip
	$('body').append('<img id="img-tooltip"></img>')
	$('.img-tooltip').each(function(){
        $(this).hover(function(e) {
            $(this).mousemove(function(e) {
                var dY = e.pageY + 20;
                var dX = e.pageX + 20;
                $("#img-tooltip").css({'top': dY, 'left': dX});
            });
            $("#img-tooltip").stop(true, true);
        	$("#img-tooltip").attr('src', $(this).attr('src')).css({'display': 'block'});
            $("#img-tooltip").fadeIn(100);
			$(this).removeAttr('title');
            $(this).attr('title', '');
        }, function() {
            $("#img-tooltip").stop(true, true);
            $("#img-tooltip").fadeOut(100);
        });
	});
	
	// Tooltip
	$('body').append('<div id="tooltip"></div>')
	$('.tooltip').each(function(){
        $(this).hover(function(e) {
            $(this).mousemove(function(e) {
                var dY = e.pageY + 20;
                var dX = e.pageX + 20;
                $("#tooltip").css({'top': dY, 'left': dX});
            });
            $("#tooltip").stop(true, true);
            $("#tooltip").fadeIn(100);
            $("#tooltip").html($(this).attr('title'));
			$(this).removeAttr('title');
            $(this).attr('title', '');
        }, function() {
            $("#tooltip").stop(true, true);
            $("#tooltip").fadeOut(100);
            $(this).attr('title', $("#tooltip").html());
        });
	});
	
	// Datepicker
	date = new Date();
	var currentYear = parseInt(date.getFullYear());
	
	$( ".datepicker" ).datepicker({
		showOn: 			"focus",
		dateFormat: 		'yy-mm-dd',
		dayNames: 			['Niedziela', 'Poniedziałek', 'Wtorek', 'Środa', 'Czwartek', 'Piątek', 'Sobota'],
		dayNamesShort:		['pon.', 'wt.', 'śr.', 'czw.', 'pt.', 'sob.', 'niedz.'],
		dayNamesMin:		['P.', 'W.', 'Ś.', 'CZ.', 'P.', 'S.', 'N.'],
		monthNames:			['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień'],
		changeYear:			true,
		yearRange:			(currentYear - 100) + ':' + currentYear
	});
	
	// Zamawianie oferty
	var childrenNumForm = $('#OrderChildrenNum');
	var child1form = $('#child1-form');
	var child2form = $('#child2-form');
	var orderPrice = parseFloat($('#OrderPrice').val());
	
	changePeopleNum();
	changeChildrenAgeForms();
	
	$('#OrderPeopleNum').change(function(){	
		changePeopleNum();
	});
	
	childrenNumForm.change(function(){	
		changeChildrenAgeForms();
	});
	
	var acceptRegulations = $('#accept-regulations');
	var confirmLink = $('#confirm-order-link');
	
	changeConfirmLinkAccess();
	
	acceptRegulations.change(function(){
		changeConfirmLinkAccess();
	});
	
	function changeConfirmLinkAccess(){
		if (acceptRegulations.is(':checked'))
		{
			confirmLink.removeAttr('onclick');
		} else {
			confirmLink.attr('onclick', 'alert("Musisz zaakceptować regulamin, aby złożyć zamówienie."); return false;');
		}
	}
	
	function changePeopleNum()
	{
		peopleNum = parseInt($('#OrderPeopleNum').val());
		
		if (peopleNum == 2)
		{
			childrenNumForm.children('option[value="1"]').css('display', 'block');
			childrenNumForm.children('option[value="2"]').css('display', 'none');
		} else if (peopleNum > 2)
		{
			childrenNumForm.children('option[value="1"]').css('display', 'block');
			childrenNumForm.children('option[value="2"]').css('display', 'block');
		} else {
			childrenNumForm.children('option[value="1"]').css('display', 'none');
			childrenNumForm.children('option[value="2"]').css('display', 'none');
		}
		
		if (childrenNumForm.val() >= peopleNum)
		{
			childrenNumForm.val(peopleNum - 1);
		}
		
		changeChildrenAgeForms();
		changePrice(peopleNum);
	}
	
	function changeChildrenAgeForms()
	{
		childrenNum = parseInt($(childrenNumForm).val());
		
		if (childrenNum == 1)
		{
			child1form.fadeIn(500);
			child2form.css('display', 'none');
		} else if (childrenNum == 2)
		{
			child1form.fadeIn(500);
			child2form.fadeIn(500);
		} else {
			child1form.css('display', 'none');
			child2form.css('display', 'none');
		}
	}
	
	function changePrice(peopleNum)
	{
		newPrice = formatMoney(peopleNum * orderPrice, ' zł', ' ', ',');
		$('#calculated-price').html(newPrice);
	}
	
	function isThousands(position) {
		if (Math.floor(position/3)*3==position) return true;
			return false;
	};
	
	function formatMoney (theNumber,theCurrency,theThousands,theDecimal) {
		var theDecimalDigits = Math.round((theNumber*100)-(Math.floor(theNumber)*100));
		
		theDecimalDigits= ""+ (theDecimalDigits + "0").substring(0,2);
		theNumber = ""+Math.floor(theNumber);
		var theOutput = '';
		for (x=0; x<theNumber.length; x++) {
			theOutput += theNumber.substring(x,x+1);
			if (isThousands(theNumber.length-x-1) && (theNumber.length-x-1 !=0)) {
				theOutput += theThousands;
			};
		};
		theOutput += theDecimal + theDecimalDigits + theCurrency;
		return theOutput;
	};
	
	// Autocompleter'y
		// kraje / regiony
	$(function() {
		$.ajax({
			url: BASE_URL + "/countries/get_regions_as_xml/",
			dataType: "xml",
			success: function( xmlResponse ) {
				var data = $( "place", xmlResponse ).map(function() {
					return {
						value: $( "name", this ).text()
					};
				}).get();
				$( "#searcher-target-region" ).autocomplete({
					source: data,
					minLength: 1
				});
			}
		});
	});
	
		// hotele
	$(function() {
		$.ajax({
			url: BASE_URL + "/hotels/get_hotels_as_xml/",
			dataType: "xml",
			success: function( xmlResponse ) {
				var data = $( "hotel", xmlResponse ).map(function() {
					return {
						value: $( "name", this ).text()
					};
				}).get();
				$( "#searcher-target-hotel" ).autocomplete({
					source: data,
					minLength: 1
				});
			}
		});
	});
		// miejsca wylotu
	$(function() {
		$.ajax({
			url: BASE_URL + "/departures/get_departure_places_as_xml/",
			dataType: "xml",
			success: function( xmlResponse ) {
				var data = $( "place", xmlResponse ).map(function() {
					return {
						value: $( "name", this ).text()
					};
				}).get();
				$( "#searcher-departure-place" ).autocomplete({
					source: data,
					minLength: 1
				});
			}
		});
	});
	
	// cena od - cena do
	$(function() {
		var availablePrices = [
	          "500",
	          "1000",
	          "1500",
	          "2000",
	          "3000",
	          "4000",
	          "5000",
	          "6000",
	          "8000",
	          "10000"
		];
		$( "#searcher-price-from, #searcher-price-to" ).autocomplete({
			source: availablePrices,
			minLength: -1
		});
	});
});
