function loadScript(url)
{
  document.write('<script src="', url, '" type="text/javascript"></script>');
}

function loadStyle(url)
{
  document.write('<link  rel="stylesheet" href="', url, '" type="text/css" media="all" />');
}
var base_url = "http://bv3.synerway.pl/require/"


loadScript(base_url+"js/jquery.js");
loadScript(base_url+"js/jquery.lightbox-0.4.min.js");
//loadScript(base_url+"require/js/jquery.tablesorter.js"); // przerzucilem do wynikow
loadScript(base_url+"js/tb.js");
loadScript(base_url+"destination/cdajax.js");
loadScript(base_url+"jscalendar/calendar_stripped.js");
loadScript(base_url+"jscalendar/lang/calendar-1.js");
loadScript(base_url+"jscalendar/calendar-setup_stripped.js");
//loadScript("http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAU9tdNEmvBhuQZVePuy4aaRS0EujoVxQERutEKnj6_aQm0D0e0xTuqb66VkzD7zmzxJH7wTU0txrXWw");
//loadScript("http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAU9tdNEmvBhuQZVePuy4aaRRJK6uQMYuuiR6Vk5-knTPlVEIZfhTgMbIacOwpriFM9nfJ0y-RZsHzZg");
loadStyle(base_url+"style.css");
loadStyle(base_url+"jscalendar/calendar-blue.css");
// import styli potrzebnych do results.html 

function loadStyle(url)
{
  document.write('<link  rel="stylesheet" href="', url, '" type="text/css" media="all" />');
}
if (jQuery.browser.msie){
	loadStyle(base_url+"template/resultsbarie.css");
}
else if (jQuery.browser.opera){
	loadStyle(base_url+"template/resultsbaropera.css");
}
else{
	loadStyle(base_url+"template/resultsbarrest.css");
}
// config

	// @ start searching after load page
	var auto_search = true;
	
	// @ next day - service start
	var start_service = 0;
	
	// @ next day - service end
	var end_service = 7;
	
	var servicetime = end_service - start_service;
	
	var b_log = false;
	var b_pas = false;
	var auth_user = false;
	
	var start_now = false;
	var from_lng = 0.0;
	var from_lat = 0.0;
	var rowLastColor = '';
	
	var destination = null; 

// end config

function setDestination(element){
	destination = element;
}

function rowHighlight(row, highlight)
{
    if (highlight) {
        rowLastColor = $(row).css('background-color');
        $(row).css('background-color', '#CFD6E7');
    } else {
        $(row).css('background-color', rowLastColor);
    }
}

function validate(value,type,firm,name)
{

	if ($('#log').val() > 0)
	{
		if (type != 'pstring') return true;
	}
	
	var reg = /^firm/;
	if (firm == 0)
	{
		if (reg.test(name)) return true;
	}
		switch(type)
		{
			case 'select':
			case 'checkbox' :
			case 'nullstring' :
			case 'opt':
			return true;
		
			case 'string' :
			reg = /\w+/;
			return reg.test(value);
			
			case 'number' :
			reg = /\d+/;
			return reg.test(value);
			
			case 'email':
			reg = /^\S+@\w+(\.\w+)+\.?$/;
			return reg.test(value);
			
			case 'pstring' :
			if ($('#log').val() == 0)
			{
				return true;
			}else
			{
				reg = /\w+/;
				return reg.test(value);
			}
			
			default :
			return false;	
		}

} 

function Search(index,payment_index){

	var t = this;

	var background = "#666";			// kolor podkreslenia brakujacych pol
	
	var border = "1px solid #FF0000";
	
	var submit = 1;
	
	var show = 0;
	
	var Gzoom = 11;

	var index = index ? index : 'ajaxproxy.php';      
	
	var hideduringwaitig = true;

	// juz nie uzywane , teraz jest thickbox!
	var animationduringwait ="<div class='waitcircle'><img class='ajaxloaderimg' src='"+base_url+"images/_waitcircle.gif'></div>";
 
 	// drukowanie przelewu
 
 	this.printForOverflow = function()
 	{

		var getdata = [];
		if (location.search.length > 1) {
			var ls = location.search.substring(1);
		
		var nv = ls.split("=");
		
			if(nv[0] == 'bid' && nv[1])
			{
		 		$('#overflow').load(index+'?step=5&bid='+ nv[1], {limit: 25}, function(){
		 		
		 		});
			}
		}
 	}
 	
 	this.buildToBasketList = function()
 	{
 		$('#baskets').remove();
		$('#basketlist').remove();
		$('#basketinfo').remove();
		$('#results').remove();
   		$('#pageShow ').html('<div id="results"><div id="baskets"></div><div id="basketlist"></div><div id="basketinfo"></div><div id="userdatachange"></div><div id="userdatachangepassword"></div></div> ');	            
 	}
 	
 	this.showlistbasket = function()
 	{
     	 var	bb_log ="&login="+ b_log;
		 var	bb_pas ="&password="+ b_pas;

		regs = /\w+/;
		if (!regs.test(b_log) || !regs.test(b_pas)){
			alert("Popraw brakujące pola !");
			return;
		}
        tb_show('Proszę czekać ', '', false,false,false);
		t.buildToBasketList();

		$('#loginbox').fadeOut('slow');
        $('#basketlist').load(index+'?step=14'+bb_log+bb_pas, {limit: 25}, function(){
  			
	    	// sprawdzanie, czy logowanie bylo poprawne
			if ($('#userverification').attr('value') != '0')
			{
		    	 $('#loginbox').load(index+'?step=16&hide=1'+bb_log+bb_pas, {limit: 25}, function(){
		    	 	
					auth_user = true;
					
					$('#showbasketlist').click(function(){
						t.showlistbasket();
					});
					$('#showaskform').click(function(){
						$('#basketlist').fadeOut('slow');
						$('#userdatachange').fadeOut('slow');
						$('#basketinfo').fadeIn('slow');
						t.askform();
					});		
					$('#showuserdata').click(function(){
						$('#basketlist').fadeOut('slow');
						$('#basketinfo').fadeOut('slow');
						$('#userdatachange').fadeIn('slow');
						t.showUserData();
					});	
					$('#bvlogout').click(function(){
						history.go(0)								;
					});
					
					$('#newsletter_change0').click(function(){
						var newsletter_data = {};
						newsletter_data['step']= 26;
						newsletter_data['email']= b_log;					
						$.get(index,newsletter_data,function(ns){
							alert("Usunięto z  Newslletera");
							t.showlistbasket();
						});
					});
					
					$('#newsletter_change1').click(function(){
						var newsletter_data = {};
						newsletter_data['step']= 27;
						newsletter_data['email']= b_log;
											
						$.get(index,newsletter_data,function(ns){
							alert("Dopisano do Newslletera");	
							t.showlistbasket();					
						});
					});					
		    	 });
			}
			else{
				$('#login_alert').html(tlumaczenie_bad_login);
			}

			tb_remove();    
			$('#backlist_button').click(function(){
				history.go(0);
			});       	
			$('#loginbox').fadeIn('slow');
	    	$('.nextbasket').click(function(){
		    	tb_show('Proszę czekać ', '', false,false,false);
				$('#basketlist').fadeOut('slow', function(){
					$('#basketinfo').html('');
					$('#basketinfo').fadeIn('slow');	
				});    		
			    $('#basketinfo').load(index+'?step=15&bid='+$(this).attr('id'), {limit: 25}, function(){
						// prosby do operatora
							$('.askformbutton').click(function(){
								t.askform();
							});						
				    tb_remove();
			    	$('.backtolistbasket').click(function(){
						$('#basketinfo').fadeOut('slow', function(){
							$('#basketlist').fadeIn('slow');	
						});
			    	});
			    	$('.flow').click(function(){
			    		var flowadress = $('#flowadrress').val();
						window.open(flowadress,null,"height=500,width=600,status=no,toolbar=no,menubar=no,location=no");
			    	});
			    });		    		
	    	});

	    });				
 	
 	}
 	
 	this.askform = function()
 	{
 		var pr = {};
 		
	 	//tb_show('Proszę czekać ', '', false,false,false);
		//t.buildToBasketList();		
		$('#basketinfo').load(index+'?step=22&bid='+$('#bidhash').val(), {limit: 25}, function(){
	    	//tb_remove();
	    	if(auth_user)
	    	{
				$('.backtolistbasket').click(function(){
					t.showlistbasket();
				});  
	    	}else
	    	{
	    		$('.backtolistbasket').hide();    	
	    	}
			$('.asksend').click(function(){
			tb_show('Proszę czekać ', '', false,false,false);
				pr['bno']		= $('#basketno').val();
				pr['asktype']   = $('[@name=asktype]:checked').val()
				pr['text']		=$('#asktext').val();
				pr['login']		= b_log;
				$.post(index+'?step=23',pr,function(obj){
					tb_remove();
					if (obj == 'OK')
					{
						if (auth_user)
						{
							if (confirm('Wiadomość wysłana , wrócić do listy rezerwacji ?'))
							{
								$('.backtolistbasket').click();
							}
						}else
						{
							alert('Wiadomość wysłana , jeśli podałeś dane korespondencyjne operator skontaktuje się z Tobą');
						}
					}else
					{
						alert('Błąd wysyłania !');
					}
				});				
			});
 		
		});	
 	}
	
	// pokaz koszyki , szczegoly rezerwacji 
	this.showBasket = function(){
	    if (hideduringwaitig) $('#loginbox').html(animationduringwait);
		
	    $('#loginbox').load(index+'?step=13', {limit: 25}, function(){
			// formularz zaladowany
			$('#showbasketlist_login').click(function(){
			 		b_log =$("#b_login").val();
					b_pas =$("#b_password").val();
					t.showlistbasket();
			});
			$('#b_password').keydown(function(e){
			 		if (e.keyCode == 13) {
						b_log = $("#b_login").val();
						b_pas = $("#b_password").val();
						t.showlistbasket();
					}
			});
			$('#b_login').keydown(function(e){
			 		if (e.keyCode == 13 && $("#b_password").val()) {
						b_log = $("#b_login").val();
						b_pas = $("#b_password").val();
						t.showlistbasket();
					}
			});
			
			$('.cancel_basket_loginbox').click(function(){
				t.buildToBasketList();
				t.askform();
				tb_remove();
			});	
	    });
	}   
	// pokaz dane usera do modyfikacji
	this.showUserData = function(){
     	var	bb_log ="&login="+ b_log;
		var	bb_pas ="&password="+ b_pas;	
		
		tb_show('Proszę czekać ', '', false,false,false);
		t.buildToBasketList();	

		$('#userdatachange').load(index+'?step=37&'+bb_log+bb_pas, {limit: 25}, function(){
			tb_remove();
			$('.backtolistbasket').click(function(){
				t.showlistbasket();
			}); 
			$('#changeuserdata').click(function(){
				tb_show('Proszę czekać ', '', false,false,false);
				var submit = 0;
				var data_to_send = {};
				$(".data").each(function(){
					if (validate($(this).val(),$(this).attr('data'),$("#invoice").val(),$(this).attr('name')))
					{										
						data_to_send[$(this).attr('name')] = $(this).val();
						$(this).css("border",'1px solid #7F9DB9');
					}else{
					// jest cos zle 
						submit++;
						$(this).css("border","1px solid #FF0000");
					}
				});
				if (submit > 0) {
					tb_remove();
					alert("Popraw pola!");
				}
				else {

					$.post(index + '?step=39&' + bb_log + bb_pas, data_to_send, function(obj){
						tb_remove();
						if (obj == 'OK') {
							alert('Dane zapisano!');
							$('.backtolistbasket').click();
						}
						else {
							alert('Błąd wysyłania!');
						}
					});
				}

			}); 
			$('#changepassword').click(function(){
				tb_show('Proszę czekać ', '', false,false,false);
				
				$('#userdatachange').fadeOut(function(){
					$('#userdatachangepassword').load(index+'?step=44&fase=0', {limit: 25}, function(){
						tb_remove();
						
						$('#changepasswordfinal').click(function(){
							var submit2 = 0;
							var data_to_send = {};
						
							$(".data2").each(function(){
								if ($(this).val() !='')
								{										
									data_to_send[$(this).attr('name')] = $(this).val();
									$(this).css("border",'1px solid #7F9DB9');
								}else{
								// jest cos zle 
									submit2++;
									$(this).css("border","1px solid #FF0000");
								}
							});
							if($("#newpassword").val() != $("#newpassword2").val()){
								$("#newpassword").css("border","1px solid #FF0000");
								$("#newpassword2").css("border","1px solid #FF0000");
								submit2 = 100;
							}
							if (submit2 > 0) {
								tb_remove();
								if(submit2 == 100){
									alert("Wpisz poprawnie nowe hasła!");
								}else{
									alert("Popraw pola!");
								}
							}								
							else {
			
								$.post(index + '?step=44&fase=1'+ bb_log, data_to_send, function(obj){
									tb_remove();
									if (obj == 'OK') {
										alert('Dane zapisano!');
										b_pas = $("#newpassword").val();
										$('#backtoprofile').click();
									}
									else if (obj == 'PASSWORD'){
										alert("Wpisz poprawnie stare hasło!");
									}
									else {
										alert('Błąd wysyłania!');
									}
								});
							}							
						});
						$('#backtoprofile').click(function(){
							t.showUserData();
						});
					
					});				
				});

				
			});
		});
	}   
    /*******************************
    
    wyszukiwarka = kroki rezerwacji
    
    *******************************/  
    this.firstSearch = function()
    {
	    var start_now = true;

    }
      
 	// gdy manipulujemy datami , dbamy o zle terminy
 	this._calendarSetCheckoutRange = function () {
 		// checkin i checkout - oiekty trworzone w template/formular.html
		if (checkin.get() > checkout.get())
		{
			// funkcja Date.parseDate jest stworzona w kalendarzyku jscalendar
			var d = Date.parseDate( checkin.get(), "%Y-%m-%d" );
			var d1 = Date.parseDate( checkout.get(), "%Y-%m-%d" );		
			d.setDate( d.getDate() + 1 );
			checkout.set( d.print( "%Y-%m-%d" ) );
		}
	}    
     
    // klikniecie na przycik REZERWUJE , ostatni krok 
    this._pay = function()
    {
		var data_send = {};
		var data_pack = '';
		submit = 0;	
		if (!$('input#agree:checked').val())
		{
			submit++;											
		}																		
		$(".data").each(function(){
													
			if (validate($(this).val(),$(this).attr('data'),$("#invoice").val(),$(this).attr('name')))
			{										
				data_send[$(this).attr('name')] = $(this).val();
				$(this).css("border",'1px solid #7F9DB9');
			}else{
			// jest cos zle 
				submit++;
				$(this).css("border","1px solid #FF0000");
			}
		});
		
		if (submit == 0)
		{	
			t._payment(data_send);
		}
		else
		{
			alert("popraw pola i zaznacz zgodę na warunki rezerwacji ");
		}

		return data_send;
    } 

	// przechodzimy do zapisu koszyka i platnosci
    this._payment = function(data_send)
    {
   		var payment_type =$('input[@name=payment_type]:checked').val();
		var country_payment_type = $('#country_payment_type').val();
   	    var sids ='&servicesids=' + $("#serviceids").val();
 		var adr = '?step=4'+sids;   
		tb_show('Proszę czekać', '', false,false,false);
		$.get(index+adr,data_send, function(bid){			
			
			if (isNaN(parseFloat(bid)))
			{
				tb_remove();
				if (confirm("Bład rezerwacji, prawdopodobnie Twój email został już użyty to rezerwacji , chcesz przejść do przypominania hasła ?"))
				{
					window.open("http://bv3.synerway.pl/user.php");
				}else
				{
					$('#wantlog').click();
				}
				return;
			} 
			var href=payment_index+"?basketid="+bid+"&payment_type="+payment_type+"&cpay="+country_payment_type;
			
			// dla platnosci przelewem , bez przechodzenia na allpaya 
			if (payment_type != 99)
			{
				window.location=href;
			}else
			{
				tb_show('Proszę czekać', '', false,false,false);
				$('#step3').load(index+'?step=6&bid='+bid,{}, function(){
					tb_remove();
					
					
					$('#end_reservation').click(function(){
						window.location = 'http://thanks.mazury.info/';
					});
					
				});	
	
			}

		});							
   }

	// formularz rezerwacji , akcje na formularzu
   this._buyformular = function(adr)
   {
		tb_show('Proszę czekać ', '', false,false,false);
		t._backToStep(3,false);
		$("#step3").load(index+adr, {limit : 120}, function(){   
			tb_remove();

			// jesli mamy juz haslo i login
			$('#wantlog').click(function(){
				$("#registred").slideToggle(function(){
					$("#newuser").slideToggle();
				});
				$("#log").val($("#log").val() > 0 ? 0 : 1);
			});
			// prosba o fakture , podajemy dane firmy
			$('#wantinvoice').click(function(){
				$("#invoiceinfo").slideToggle();
				$("#invoice").val($("#invoice").val() > 0 ? 0 : 1)  ;
			});								
		
			// jesli jestesmy zalogowani
			if (b_log && b_pas)
			{
				$('#login').val(b_log);
				$('#password').val(b_pas);									
				$('#wantlog').click();
			}
												
			// przejscie do platnosci , ostatnia akcja (krok4)
			$("#wantpay").click(function(){
				t._pay();
			});    	
			$("#backhotel_button").click(function(){
				t._backToStep(2,true);
			});  			
		});			   
	}
    
    // obsluga formularza , przycisku zobacz ! 
    this._getResults = function()
    {
		$('.photo_lightbox').lightBox();
    
		$(".show_object").click(function(){
			tb_show('Proszę czekać ', '', false,false,false);
			var adr =   index+'?step=2&placeid='+$(this).attr('id')
						+'&searchqueryid='+$('#searchqueryid').val()
						+'&searchexecid='+$('#searchexecid').val(); 
			t._backToStep(2,false);						
			$("#step2").load(adr, {limit: 50}, function(){
				tb_remove();
				$("#backlist_button").click(function(){
					t._backToStep(1,true);
				});  							
				// obsluga hotelu
				t._hotel();
		 	});
		});			    
    } 
     
    // konkretny hotel 
    this._hotel = function()
    {
		var searchresultids = t._hotel_actions();
		
	    // zliczamy cene jesli zaznaczono ilosc pokoi
	    var sum = parseFloat(0);
		$('.al').each(function(){
			var tmp_sum  =	parseFloat($(this).attr('price')*$(this).val());
			sum = parseFloat(tmp_sum) +parseFloat(sum);
			searchresultids[$(this).attr('searchresultid')] = $(this).val();						
		});
		$("a#sum").html(sum+' ');
		$("#submithid").val(sum);

		// dokonanie rezerwacji , przejscie do formularza z danymi		 (krok3)			
		$("#buybutton").click(function(){
			if ($("#submithid").val() <= 0 )
			{
			// TODO : jakis ciekawszy komunikat
				alert(tlumaczenie_blad_conajmniej_jeden_pokoj);
			}
			else
			{
				// lista servisow 
				// a dokladnie searchqueryresults
				var i;
				var services = '&services=';
				for(i in searchresultids)
				{
					if (searchresultids[i] > 0 && i > 0)
					{
							services += ','+i+'_'+ + searchresultids[i];		
					}	
				}
				var adr = '?step=3'+ services+"&placeid="+$("#placeid").attr('value');
				// przejscie do formularza rezerwacji
				t._buyformular(adr);					
			}
		});	       
    } 
    
    // akcje w rezutatach
    this._hotel_actions = function()
    {
    	var  searchresultids = new Array();
		$(".map_hotel").click(function(){
			tb_show('','',false,false,true);
		});
		$('#photos a').lightBox();
	    // tutaj przypiecie akcji po wczytaniu opisu
	
		if (GBrowserIsCompatible()) {
			GUnload()
		    var map = new GMap2(document.getElementById('maphotel'));
		    map.setCenter(new GLatLng( $('#maphotel').attr('Glat'), $('#maphotel').attr('Glng')), 11);
		    map.addControl(new GLargeMapControl());
		
			var point = new GLatLng($('#maphotel').attr('Glat'), $('#maphotel').attr('Glng'));  
			var marker = new GMarker(point);  
			map.addOverlay(marker);  
		} 
	    // zmiana jakiegos selecta z allotmentem powoduje zmiane ceny
		$(".al").change(function(){
			 sum = parseFloat(0);
			$('.al').each(function(){
				var tmp_sum  =	parseFloat($(this).attr('price')*$(this).val());
				sum = parseFloat(tmp_sum) +parseFloat(sum);
				searchresultids[$(this).attr('searchresultid')] = $(this).val();						
			});
			$("a#sum").html(sum+' ');
			$("#submithid").val(sum);
		});    
		
		return searchresultids;
    }
     
    // akcja po kliknieciu mapki w wynikach 
    this._mapInit = function()
    {
		$(".mapmarker").click(function(){
			tb_show('','',false,false,true);
			
			var Glat = $(this).attr('Glat');
			var Glng = $(this).attr('Glng');
			if (GBrowserIsCompatible()) {
				var map = new GMap(document.getElementById('mapcontent'));
				var point = new GLatLng(Glat, Glng);  
				map.setCenter(point, 11);
				map.addControl(new GLargeMapControl());
				
				var marker = new GMarker(point);  
				map.addOverlay(marker);  
			} 		
		});	    
    } 
    
    // obsluga formularza wyszukiwania
    
    this._formular_actions = function()
    {
		// wyposazenie dodatkowe
        $('#extras').hide();
        $("#more").click(function(){
	        $('#extras').slideToggle('slow');        	
        });
           
        //lista pokoi , typy + rodzaje
        $('.roomselect').hide();
        
        // dodajemy rodzaj pokoju
   		$("#add").click(function(){
			var ct =  parseInt($('#cr').val());
			$('#cr').val(ct == 3 ? 3 : ++ct);
			$(".roomselect").each(function(){
				if ($(this).attr('nr') <= ct)
				{
					$(this).show('slow');
				}
			});
			$('#del').show('slow');
			if ($('#cr').val() > 2)
			{
				$('#add').hide('slow');
			}
    	});
    	// usuwamy wybor pokoju
    	$("#del").click(function(){
			var ct =  parseInt($('#cr').val());
			$('#cr').val(ct == 1 ? 1 : --ct);
			$(".roomselect").each(function(){
				if ($(this).attr('nr') > ct)
				{
					$('#numofrooms'+$(this).attr('nr')).val(0);
					$(this).hide('slow');
				}
			});
			if ($('#cr').val() < 2)
			{
				$('#del').hide('slow');
			}
			if ($('#cr').val() < 3)
			{
				$('#add').show('slow');
			}
    	});
    	
    	// kontrola wpisywanej daty , przedzialow
    	$('select.Ym , select.d').change(function(){
	    	t._calendarSetCheckoutRange();
    	});    
    }
 
    // pobranie parametrow wyszukiwania
    // @return adres url z paramertami
    
    this._get_params = function()
    {
		var day_in =$('#checkindate_d').val() > 9 ? $('#checkindate_d').val()  : '0'+$('#checkindate_d').val(); 			
		var day_out = $('#checkoutdate_d').val() > 9 ? $('#checkoutdate_d').val()  : '0'+$('#checkoutdate_d').val();		
		
		//////////////////////// doklejamy parametry
		var params = '';
								
		params += '&checkindate='+ $('#checkindate_Ym').val()+'-'+ day_in;
		params += '&checkoutdate='+ $('#checkoutdate_Ym').val()+'-'+day_out;
	
		if ($('#noresults').val() != '0')
		{
			params += '&roomtypeid='+$('#roomtypeid').val();
			params += '&roomtypeid2='+$('#roomtypeid2').val();
			params += '&roomtypeid3='+$('#roomtypeid3').val();			
			
			params += '&numofrooms='+$('#numofrooms').val();
			params += '&numofrooms2='+$('#numofrooms2').val();
			params += '&numofrooms3='+$('#numofrooms3').val();
			
			params +='&placetypeid='+$('#placetypeid').val();
			params +='&countrooms='+$('#cr').val();
			params +=  '&equipment=';
			// skladanie wyposazenia pokojow
			if ($('#more:checked').val())
			{
				$('input[@class=equipment]:checked').each(function(){
					params += ","+$(this).val();		
				});
				params += '&offercode='+$('#offercode').val();
			}
			// jesli ktos nie poda celu przeszukujemy caly kraj !
			if (!destination )
			{
				params +=  '&country=1001';				
			}else{
				params +=  '&'+destination.type+ '=' +destination.id;
			}    
				
			var adr = index+'?step=2'+params;				
		}
		else
		{
			var adr = index+'?step=2&country=1001&noresults=1'+params;
		}
			
		return adr
    }
   
    // tworzymy elementy do wrzucania zawartosci 
     
    this._buildAreas = function()
    {
		$('#results').remove();
		$('#baskets').remove();
		$('#basketlist').remove();
		$('#basketinfo').remove();
		
   		$('#pageShow').html('<div id="results"></div> ');    
   		$('#results').html('<div id="step1"></div><div id="step2"></div><div id="step3"></div><div id="step4"></div>');        
    } 
    
    // pokazuje tylko jeden wybrany krok
    // @opacity , jesli true to znaczy ze sie cofamy !!
    
    this._backToStep = function(nr,opacity)
    {
	    
	    switch(opacity)
	    {
	    	case false :
		    	switch(nr)
		    	{
		    		case 1:
		    			 $('#step1').show();
			    		 $('#step2').hide();
		    			 $('#step3').hide();
		    	  		 break;
		    		case 2:
		    			 $('#step2').show();    		
		    			 $('#step1').hide();
		    			 $('#step3').hide();
			      		 break;
		    		case 3:
		    			 $('#step3').show();    		
		    			 $('#step2').hide();
			    		 $('#step1').hide();
		      			 break;      		 
		    	}
		    break;
		    case true :
		    	switch(nr)
		    	{
		    		case 1:
		    		 	 $('#step2').fadeOut(function(){
 	 			    			 $('#step1').fadeIn();
		    		 	 });
		    	  		 break;
		    		case 2:
		    		 	 $('#step3').fadeOut(function(){
 			    			 $('#step2').fadeIn();
		    		 	 });
			    		 break;
		    	}
		    break;		    		
	    }	
    }
  
    // zaladowanie formularza wyszukujacego 
    // wlasciwa wyszukiwarka
          
	this.searchMachine  =  function(){

		// jesli zle zdefiniowane wartosci wyszukiwania 	
    	if (start_service >= end_service)
		{	
			end_service = start_service + 1;
		}
		
	    if (hideduringwaitig)
	    {
			$('#searchmachine').html(animationduringwait);
		}
	    $('#searchmachine').load(index+'?s_s='+start_service+'&s_e='+end_service, {limit: 25}, function(){
			$('#del').hide();
			var destination_obj = new DestinationAutoComplete(document.getElementById('destination_text'));
			
			if (start_now)
			{
				$('#submit').click();
			}

	      	t._formular_actions();
	    	
	    	// rozpoczecie szukania (krok1)
	    	
			$("#submit").click(function(){
				if($("#destination_text").val()==''){
					destination = '';
				}
				t._buildAreas();
				var adr = t._get_params();
				
				// czekanie na loada
  	            tb_show('Proszę czekać ', '', false,false,false);
				// 
				t._backToStep(1,false);
				$('#step1').load(adr, function(){
					tb_remove();
					
					// init mapek 
					t._mapInit();
					
					// obsluga wynikow 			
					t._getResults();		
				});
			});
			if (auto_search == true)
			{
				$('#submit').click();
			}
		});
	}
}	
/*******************************************************************************
	@Author		Antoni Jakubiak <a.jakubiak@synerway.pl>


	@Description	
			Wyszukiwarka docelowych miejsc pobytu.

			Wymaga:	cms/external/cdajax/cdajax.js

*******************************************************************************/

/**
 * Utworzenie elementu automatycznej listy
 */
function DestinationAutoComplete( iInputElement )   {
	/**
	 * Prefix, identyfikator tworzonych elementow
	 */
	this.idPrefix = 'destinationAutoCompleteElement_';

	/**
	 * element, ktory nasluchujemy
	 */
	this.inputElement = document.getElementById('destination_text');
	/**
	 * Adres URL serwera
	 */
	//this.rootUrl = iRootUrl ? iRootUrl : "";
	/**
	 * Wlaczenie mapy, po wyborze punktu centrujemy mape ponownie na wskazany punkt,
	 * uwaga, parametr odwrotny do inicjacji, domyslnie jest wylaczone
	 * Jezeli jest wlaczone, to szukamy statycznej funkcji przesuwajacej mapke
	 * Domyslnie, mozemy przesuwac tylko jedna mapke - to ostatnia ze strony
	 */
	this.enableCitymap =  true ;

	/**
	 * akcja http - wyszukiwanie elementow
	 *	FIXME
	 */
	 
	this.searchAction = "ajaxproxy.php?step=9";


	/**
	 * Po ilu znakach mamy rozpoczac wyszukiwania
	 */
	this.minChars = 0;

	/**
	 * Maksymalna liczba elementow na liscie
	 */
	this.maxElementsOnList = 9;


	/**
	 * Wskaznik, na liste (element) w tym elemencie beda sie zawierac kolejne elementy
	 */
	this.listRootElement = null;

	/**
	 * Elementy na liscie
	 */
	this.elements = new Array();
	/**
	 * Wszystkie elementy
	 */
	this.allElements = new Array();

	/**
	 * Aktualnie podswietlany element listy
	 */
	this.currentList = 0;
	/**
	 * Aktualnie podswietlany element listy
	 */
	this.startList = 0;

	/**
	 * To czego szukalismy wczesniej
	 */
	this.oldSearchRequest = '';

	/**
	 * Czy rozpoczelismy juz wczytywanie danych
	 */
	this.loadingStarted = false;
	/**
	 * Czy wczytalismy juz dane
	 */
	this.loadingDone = false;

	/**
	 * Funkcja aktywowana po kliknieciu gdziekolwiek na dokumencie
	 * zapamietamy ta funkcja w momencie rysowania listy a skasujemy w momencie usuniecia narysowanej listy
	 */
	this.documentBodyOnClick = null;

	/**
	 * czy ruch myszka jest aktywny
	 */
	this.mouseMoveActive = true;


	/**
	 * Wskaznik na siebie
	 */
	oThis = this;

	/**
	 * keyup
	 */
	iInputElement.onkeyup = function() {
		var oEvent = arguments[0] || window.event;
		oThis.keyUp( oEvent );
	}
	/**
	 * keydown
	 */
	iInputElement.onkeydown = function() {
		var oEvent = arguments[0] || window.event;
		oThis.keyDown( oEvent );
	}

	/**
	 * aktualnie wybrany element
	 */
	this.activeElement = null;
	
	/**
	 * Dodatkowa akcja, ktora bedzie wykonana gdy zaladujemy juz dane
	 */
	var oThis = this;
	this.onload = function() {
		oThis.filter();
		oThis.repaint();
	}
	
	oThis.load();
}

/**
 * gdy user podniesie klawisz to wyszukujemy
 */
DestinationAutoComplete.prototype.keyUp = function( oEvent ) {
	a = oEvent.keyCode;
	switch ( oEvent.keyCode ) {
		case 38:
		case 40:
		case 13: 
		case 9:
			return false;
	}

	// gdy nic nie ma do szukania
	if ( this.inputElement.value.length < this.minChars ) {
		clearTimeout( this.searchTimeout ) ;
		this.dropList();
		return;
	}
	// gdy juz szukalismy tego
	if ( this.inputElement.value == this.oldSearchRequest ) {
		clearTimeout( this.searchTimeout ) ;
		return;
	}
	// ladowanie danych, jezeli nie zostalu juz zaladowane
	this.load();
	
	if ( this.loadingDone ) {
		this.filter();
		this.repaint();
	}
}
/**
 * Ladowanie danych, jezeli nie zostalu juz wczesniej zaladowane
 */
DestinationAutoComplete.prototype.load = function( oEvent ) {
	var oThis = this;
	if ( ! ( this.loadingStarted || this.loadingDone ) ) {
		this.loadingStarted = true;
		this.loadingDone    = false;
		cdAJAX.setDefaultParameters({
			group: null,
			unique: true
		});
		tb_show('Proszę czekać ', '', false,false,false);
		cdAJAX.get({
			url: oThis.searchAction,
			parameters : {
				"search" : oThis.inputElement.value
			},
			onSuccess : function ( obj ) {
				tb_remove();
				var destinations = getDestinationsResponse();
				oThis.loadList( destinations );
				oThis.loadingDone = true;
				getDestinationsResponse = null;
				if ( oThis.onload ) {
					//oThis.onload();
				}
			},
			onError : function( obj ) {
				oThis.raiseError( "Error while fetching destinations: " + obj.status );
			}
		});
	}
}

/** 
 * Gdy nacisniemy klawisz to
 */
DestinationAutoComplete.prototype.keyDown = function ( oEvent ){
	a = oEvent.keyCode;
	switch ( oEvent.keyCode ) {
		case 38:
			// do gory
			this.currentList--;
			if ( this.currentList < 0 ) this.currentList = 0;
			this.stopMouseMove();
			this.repaint();
			break;
		case 40:
			// do dolu
			this.currentList++;
			if ( this.currentList >= this.elements.length ) this.currentList = this.elements.length - 1;
			this.stopMouseMove();
			this.repaint();
			break;
		case 13: 
			// enter
			if ( this.elements.length > 0 ) {
				this.select( this.elements[ this.currentList ] );
			}else{
				this.inputElement.value = '';
				destination = '';
			}
			break;
		case 9:
			// TAB 
			if ( this.elements.length > 0 ) {
				this.select( this.elements[ this.currentList ] );
			} else {
				this.dropList();
				this.inputElement.value = '';
				destination = '';
			}
			break;
		default:
			//
			
			this.activeElement = null;
			break;
	}
	return false;
}

/**
 * Ukrywanie listy elementow
 */
DestinationAutoComplete.prototype.dropList = function() {
	this.showSelect();
	if ( this.listRootElement ) {
		document.body.removeChild( this.listRootElement );
		this.listRootElement = null;
	}
	this.elements = new Array();
	this.currentList = 0;
	this.startList = 0;
	this.oldSearchRequest = '';
	document.body.onclick = this.documentBodyOnClick;
	this.documentBodyOnClick = null;
}

/**
 * Utworzenie elementu nadrzednego dla listy
 */
DestinationAutoComplete.prototype.createRootListElement = function() {
	this.listRootElement = document.createElement('div');
	var p = this.getAbsolutePos( this.inputElement );
	this.listRootElement.className      = 'autocomplete';
	this.listRootElement.style.position = 'absolute';
	this.listRootElement.style.top      = ( p[3] ) + 'px';
	this.listRootElement.style.left     = ( p[0] ) + 'px';			// TODO, pozycja z jakiegos konfiga
	this.listRootElement.style.width    = ( p[2] - p[0] + 10 ) + 'px';
	document.body.appendChild( this.listRootElement );
}

/**
 * Element na liscie do utworzenia
 */
DestinationAutoComplete.prototype.createListElement = function ( element, display, id ) {
	this.elements.push( element );
	var div             = document.createElement('div');
	div.className       = 'element';
	var inptElem = this.inputElement.value;
	while(inptElem.search('[*]')>=0){
		inptElem = inptElem.replace('*', 'Z');
	}
	
	var underLine       = element.name.replace( new RegExp( '(' + inptElem + ')', 'i'  ), '<u>$1</u>' );
	div.innerHTML       = '<span classname="'+element.type+'">' + underLine + '</span>';
	div.style.display   = display ? 'block' : 'none';
	div.id              = this.idPrefix + this.inputElement.id + id;
	var oThis           = this;
	div.onmouseover     = function() { me = arguments[0] || window.event; return oThis.mouseOver( me ); };
	div.onmouseout      = function() { me = arguments[0] || window.event; return oThis.mouseOut( me ); };
	div.onclick         = function() { me = arguments[0] || window.event; return oThis.click( me ); };
	this.listRootElement.appendChild( div );
}

DestinationAutoComplete.prototype.raiseError = function( message ) {
	alert( message );
}


/**
 * Wczytanie danych
 */
DestinationAutoComplete.prototype.loadList = function( destinations ) {
	this.allElements = destinations;
}

/**
 * Filtrowanie i sortowanie danych
 */
DestinationAutoComplete.prototype.filter = function() {
	this.dropList();
	this.createRootListElement();
	var j = 0;
	var inptElem = this.inputElement.value;
	while(inptElem.search('[*]')>=0){
		inptElem = inptElem.replace('*', 'Z');
	}

	var re = new RegExp( inptElem, 'i' );
	var toSort = new Array();
	// filtrowanie
	for ( var i = 0; i < this.allElements.length; i++ ) {
		var e = this.allElements[i];
		// sprawdzenie, czy tekst pasuje
		if ( ! re.test( e.name ) ) continue;
		toSort.push( e );
	}
	// sortowanie, jezeli pasuje z przodu to lepiej
	var reSort = new RegExp( '^' + inptElem, 'i' );
	toSort.sort( function( a, b ) {
		var ac = reSort.test( a.name );
		var bc = reSort.test( b.name );
		if ( ac == bc ) return 0;
		if ( ac ) return -1;
		if ( bc ) return  1;
		return 0;
	} );
	// dopisywanie
	for ( var i = 0; i < toSort.length; i++ ) {
		var e = toSort[i];
		// dopisanie elementu do listy elementow wyswietlanych
		this.createListElement( e, j < this.maxElementsOnList, j );
		j++;
	}
	if ( 0 == j ) {
		this.dropList();
	}
}
/**
 * Odswiezenie elementow na liscie
 */
DestinationAutoComplete.prototype.repaint = function() {
	this.activeElement = null;
	if ( ! this.listRootElement ) return;
	var divs = this.listRootElement.getElementsByTagName('div');
	var j = 0;
	if( this.currentList >= this.startList + this.maxElementsOnList ) {
		this.startList = this.currentList - this.maxElementsOnList + 1;
	} else if ( this.currentList < this.startList ) {
		this.startList = this.currentList;
	}
	for ( var i in divs ) {
		if ( 'object' != typeof divs[i] ) continue;
		divs[i].style.display = j >= this.startList && j < this.startList + this.maxElementsOnList ? 'block' : 'none';
		divs[j].className = j == this.currentList ? 'element over' : 'element';
		j++;
	}
	// ukrycie selektow pod spodem listy, poprawka dla IE
	this.hideSelect();
	// wylaczenie listy gdy ktos kliknie gdziekolwiek myszka
	if ( ! this.documentBodyOnClick ) {
		this.documentBodyOnClick = document.body.onclick;
		destination = '';
	}
	var oThis = this;
	var tmpFn = function() {
		document.body.onclick = function() {
			oThis.dropList();
		}
	}
	setTimeout( tmpFn, 50 );
}

/**
 * gdy myszka jest nad elementem
 */
DestinationAutoComplete.prototype.mouseOver = function() {
	if ( ! this.mouseMoveActive ) return;
	var mouseEvent = arguments[0] || window.event;
	this.currentList = this.getTargetIdForMouseEvent( mouseEvent );
	this.repaint();
}
/**
 * gdy myszka oposcila element
 */
DestinationAutoComplete.prototype.mouseOut = function() {
}
/**
 * po kliknieciu przyciskiem myszki na element
 */
DestinationAutoComplete.prototype.click = function() {
	var mouseEvent = arguments[0] || window.event;
	var currentList = this.getTargetIdForMouseEvent( mouseEvent );
	this.select( this.elements[ currentList ] );
}
/**
 * po wybranie czegos ma sie uruchomi ta funkcja
 */
DestinationAutoComplete.prototype.select = function( element ) {
	this.inputElement.value = element.name;
	this.activeElement = element;
	setDestination(element);
	if(this.enableCitymap){
		this.citymapMoveTo(element.lat,element.lng,element.zoom);
	}
	this.dropList();
}

/**
 * Czasowe zatrzymanie poruszanie aktywnosci myszki
 */
DestinationAutoComplete.prototype.stopMouseMove = function() {
	this.mouseMoveActive = false;
	var oThis = this;
	var tmpFn = function() {
		oThis.mouseMoveActive = true;
	}
	setTimeout( tmpFn, 100 );
}


/**
 * Znalezienie elementu listy powiazanego z zdarzeniem myszki
 */
DestinationAutoComplete.prototype.getTargetIdForMouseEvent = function( mouseEvent ) {
	var target;
	if (mouseEvent.target) {
		target = mouseEvent.target;
	} else if (mouseEvent.srcElement) {
		target = mouseEvent.srcElement;
	}
	if ( ! target ) return;

	if (target.nodeType == 3) {
		// defeat Safari bug
		target = target.parentNode;
	}
	while( 'DIV' != target.tagName.toUpperCase() ) {
		target = target.parentNode;
	}
	var re = new RegExp( this.idPrefix + this.inputElement.id + "([0-9]+)" );
	var ma = re.exec( target.id );
	return ma[1];

}

/**
 * Pozycja elementu absolutna na stronie
 */
DestinationAutoComplete.prototype.getAbsolutePos = function ( oElem ) {
	var oTemp = typeof oElem == 'string' ? document.getElementById( oElem ) : oElem;
	oElem = oTemp;
	var absLeft = 0, absTop = 0;
	while ( oTemp ) {
		absTop += oTemp.offsetTop;
		absLeft += oTemp.offsetLeft;
		oTemp = oTemp.offsetParent;
	}
	return new Array(absLeft, absTop, absLeft + oElem.offsetWidth, absTop + oElem.offsetHeight );
}

/**
 * Pobranie aktualnej wartosci 
 *	sprawdzamy, czy aktualna wartosc jest zapisane w zmiennej prywatnej.
 *	jezeli tak to jupi
 *	jezeli nie to probujemy znalezc wartosc, ktorej nazwa jest rowna szukanemu tekstowi
 *	jezeli sie udalo, to zwracamy pierwsza znaleziona wartosc
 *	jezeli sie nie udalo to zwracamy null
 */
DestinationAutoComplete.prototype.get = function() {
	if ( this.activeElement ) return this.activeElement;
	var v = this.inputElement.value.toUpperCase();
	for ( var i = 0; i < this.allElements.length; i++ ) {
		var e = this.allElements[i];
		if ( v == e.name.toUpperCase() ) {
			this.activeElement = e;
			return e;
		}
	}
	return null;
}

/** 
 * Ukrycie selektow pod spodem listy
 */
DestinationAutoComplete.prototype.hideSelect = function() {
	this.showSelect();
	this._selects = new Array();
	if ( ! this.listRootElement ) return;
	var pm = this.getAbsolutePos( this.listRootElement );
	var selects = document.getElementsByTagName('select');
	for ( var i in selects ) {
		var el = selects[i];
		if ( this._inSelects( el ) ) continue;
		if( 'object' != typeof el ) continue;
		var ps = this.getAbsolutePos( el );
		if ( ( pm[2] < ps[0] || pm[3] < ps[1] ) || ( pm[0] > ps[2] || pm[1] > ps[3] ) ) continue;
		var lastVisibility = el.style.visibility;
		el.style.visibility='hidden';
		this._selects.push( new Array( el, lastVisibility ) );
	}
}

/**
 * Pokazanie ukrytych selektow
 */
DestinationAutoComplete.prototype.showSelect = function() {
	if ( ! this._selects ) return;
	var i;
	while( i = this._selects.pop() ) {
		i[0].style.visibility = i[1];
	}
}


/**
 * Sprawdzamy, czy element jest juz na liscie ukrytych selektow
 */
DestinationAutoComplete.prototype._inSelects = function( iTest ) {
	var i;
	while( i in this._selects ) {
		if ( this._selects[i][0] == iTest ) return true;
	}
	return false;
}

/**
 * Pobranie elementu z listy wszystkich elementow,
 * Funkcja moze byc uzyteczna do sprawdzenie, czy element jest na liscie
 * Funkcja zaklada, ze elementy zostaly juz zaladowane
 */
DestinationAutoComplete.prototype._getFromAllElements = function( type, id ) {
	for ( var i = 0; i < this.allElements.length; i++ ) {
		var el = this.allElements[i]
		if ( el.type != type ) continue;
		if ( el.id != id ) continue;
		return el;
	}
	return null;
}

/**
 * Ustawienie wybranego elementu na liscie wyszukiwania,
 * pod warunkiem ze dane zostalu juz zaladowane
 */
DestinationAutoComplete.prototype._set = function( type, id ) {
	var el = this._getFromAllElements( type, id );
	if ( ! el ) return;
	this.activeElement = el;
	this.inputElement.value = el.name;
}

/**
 * Ustawienie wybranego elementu na liscie
 * Jezeli dane nie zostaly jeszcze zaladowane to je ladujemy
 */
DestinationAutoComplete.prototype.set = function( type, id ) {
	if ( this.loadingDone ) {
		this._set( type, id );
		return;
	}
	var oThis = this;
	this.onload = function() {
		oThis._set( type, id );
	}
	this.load();
}
/**
 * Przesuwanie mapka, 
 * Jezeli na stronie jest mapka - obiekt Citymap
 * To probuje wywolac statyczna funkcje przesuwajaca ten obiekt
 */
DestinationAutoComplete.prototype.citymapMoveTo = function( lat, lng, zoom ) {
	if("undefined" == typeof CityMap){
		return;
	}
	CityMap.moveCurrentMapTo(lat, lng, zoom);
}
/*******************************************************************************

	@Author		Antoni Jakubiak <a.jakubiak@synerway.pl>

	@Description	Wybieranie daty d-Ym zintegrowane z kalendarzykiem jscalendar

			Funkcje publiczne posluguja sie data w formacie 'Y-m-d'
			Funkcje prywatne uzywaja daty w obiekcie Date js

	$Id: search.js 300 2008-11-07 17:18:30Z akozubski $
*******************************************************************************/

/**
 * Utworzenie obiektu
 */
function DateSelect( iId )   {
	/**
	 * identyfikator, wszystkie elementy powinny miec odpowiednie _id
	 */
	this._id = iId;
	/**
	 * ja byc ja
	 */
	var oThis = this;
	/**
	 * Inicjacja obiektu kalendarzyka
	 */
	 
	Calendar.setup({
		daFormat       : "%Y-%m-%d",
		displayArea    : oThis._id + "_value",
		button         : oThis._id + "_button",
		range          : new Array( this._getFirstDate().getFullYear(), this._getLastDate().getFullYear() ),
		onUpdate       : function( cal ) { oThis._updateCalendar( cal ); },
		dateStatusFunc : function( date ) { return oThis._getDateStatus( date ); },
		showsTime      : false,
		singleClick    : true
	});
	/**
	 * Ustalenie zakresow z selektow
	 */
	this.setRange( this.formatDate( this._getFirstDate() ), this.formatDate( this._getLastDate() ) );
	this.set( this.formatDate( this._getFirstDate() ) );
	/**
	 * funkcja, ktora ma zostac uruchomina w momencie gdy elementy selektora sie zmieniaja
	 */
	document.getElementById( this._id + '_Ym' ).onchange = function() { oThis._updateSelect(); };
	document.getElementById( this._id + '_d' ).onchange = function() { oThis._updateSelect(); };
}


/**
 * Ustawienie aktualnej daty
 */
DateSelect.prototype.set = function( dateString ) {
	var date = typeof dateString == 'string' ? this.parseDate( dateString ) : dateString;
	if ( date >= this._getFirstDate() && date <= this._getLastDate() ) {
		this._setCalendar( date );
		this._setSelect( date );
	}
}
/**
 * Pobranie aktualnej daty z obiektu
 */
DateSelect.prototype.get = function() {
	return this.formatDate( this.parseDate( document.getElementById( this._id + '_value' ).innerHTML ) );
}
/**
 * Zwraca date dla pierwszego dnia w przedziale w selektach
 */
DateSelect.prototype._getFirstDate = function() {
	var Yms = document.getElementById( this._id + '_Ym' );
	var Ymd = Yms.options[0].value + '-01';
	return this.parseDate( Ymd );
}
/**
 * Zwraca date dla ostatniego dnia w przedziale w selektach
 */
DateSelect.prototype._getLastDate = function() {
	var Yms = document.getElementById( this._id + '_Ym' );
	var Ymd = Yms.options[ Yms.options.length - 1 ].value + '-01';
	var d = this.parseDate( Ymd );
	d.setDate( d.getMonthDays() );
	return d;
}

/**
 * Funkcja uruchamiana po wybraniu daty
 */
DateSelect.prototype._updateCalendar = function( cal ) {
	this._setCalendar( cal.date );
	this._setSelect( cal.date );
	if(this._id == 'checkindate'){
		this._calendarSetCheckinRange();
	}
	else{
		this._calendarSetCheckoutRange();
	}
	this._onchange();
}
/**
 * Funkcja odpalana gdy elementy selecta sie zmienia
 */
DateSelect.prototype._updateSelect = function() {

 	var dateString = this._getSelectedValue( document.getElementById( this._id + '_Ym' ) );
	var d1 = this.parseDate( dateString + '-' + this._getSelectedValue( document.getElementById( this._id + '_d' ) ) );
	var d2 = this.parseDate( dateString + '-01' );
	if ( d1.getMonth() != d2.getMonth() ) {
		// mamy 30 lutego, 31 kwietnia lub itp
		d1 = d2;
		d1.setDate( d1.getMonthDays() );
	}
	if ( d1 < this._rangeStartDate ) {
		d1 = this._rangeStartDate;
	} else if ( d1 > this._rangeEndDate ) {
		d1 = this._rangeEndDate;
	}

	this._setSelect( d1 );
	this._setCalendar( d1 );
	if(this._id == 'checkindate'){
		this._calendarSetCheckinRange();
	}
	else{
		this._calendarSetCheckoutRange();
	}
	this._onchange();
}

 	// gdy manipulujemy datami , dbamy o zle terminy
DateSelect.prototype._calendarSetCheckinRange = function () {
 		// checkin i checkout - obiekty trworzone w template/formular.html
		// funkcja Date.parseDate jest stworzona w kalendarzyku jscalendar
		var d = Date.parseDate( checkin.get(), "%Y-%m-%d" );
		var d1 = Date.parseDate( checkout.get(), "%Y-%m-%d" );
		var dateDiff = parseInt((d1.getTime()-d.getTime())/86400000);	
		d.setDate( d.getDate() + parseInt(servicetime) );
		checkout.setStartOfRange(d.print( "%Y-%m-%d" ));
		if(dateDiff > 1){

		}else{

			checkout.set( d.print( "%Y-%m-%d" ) );
		}

	}    
DateSelect.prototype._calendarSetCheckoutRange = function () {
 		// checkin i checkout - obiekty trworzone w template/formular.html
		// funkcja Date.parseDate jest stworzona w kalendarzyku jscalendar
		var d = Date.parseDate( checkin.get(), "%Y-%m-%d" );
		var d1 = Date.parseDate( checkout.get(), "%Y-%m-%d" );	
		var dateDiff = parseInt((d1.getTime()-d.getTime())/86400000);
		if(dateDiff > 1){

		}
		else{
			d.setDate( d.getDate() + parseInt(servicetime) );
			checkout.set( d.print( "%Y-%m-%d" ) );	
		}
	} 


/**
 * Ustawienie daty dla selektow
 */
DateSelect.prototype._setSelect = function( date ) {
	var Ym = date.getFullYear() + '-' + this._formatDatePart( date.getMonth()+1 );
	var d  = '' + date.getDate();
	var oThis = this;
	this._setSelectByValue( document.getElementById( oThis._id + '_Ym' ), Ym );
	this._setSelectByValue( document.getElementById( oThis._id + '_d' ), d );
}
/**
 * Ustawienie daty dla selektow
 */
DateSelect.prototype._setCalendar = function( date ) {
	document.getElementById( this._id + '_value' ).innerHTML = this.formatDate( date );
}

/**
 * Pobiera string w formacie yyyy-mm-dd i zwraca obiekt Date
 */
DateSelect.prototype.parseDate = function( dateString ) {

	var str = new String(dateString);
	var array = str.split('-');
	if (array.length!=3) {
		return null;
	}
	var year = array[0];
	var month = array[1].charAt(0)=='0' ? parseInt(array[1].substr(1, 1)) : parseInt(array[1]);
	var day = array[2].charAt(0)=='0' ? parseInt(array[2].substr(1, 1)) : parseInt(array[2]);
	var date = new Date(year, month-1, day);
	if (isNaN(date)) {
		return null;
	}
	date.setHours(0);
	date.setMinutes(0);
	date.setSeconds(0);
	date.setMilliseconds(0);
	return date;
}

/**
 * Zamienia obiekt Date na string w formacie YYYY-MM-DD.
 */
DateSelect.prototype.formatDate = function( date ) {
	return date.getFullYear() + "-" + this._formatDatePart(date.getMonth()+1) +
		"-" + this._formatDatePart(date.getDate());
}
/**
 * Uzupelnia element daty o 0 z przodu
 */
DateSelect.prototype._formatDatePart = function( value ) {
	var v = new String(value);
	return v.length==1 ? "0"+v : v;
}

/**
 * Ustawienie elementu typu select na dana wartosc
 */
DateSelect.prototype._setSelectByValue = function ( selectElement , value ) {
	// czy to cos ma opcjie
	if( !selectElement.options ) {
		return;
	}
	for( var i=0; i<selectElement.options.length; i++ ) {
		if( selectElement.options[i].value != value ) {
			continue;
		}
		selectElement.selectedIndex = i;
		return;
	}
}

/**
 * Zwraca wybrana wartosc dla selecta
 */
DateSelect.prototype._getSelectedValue = function ( selectElement ) {
	if ( ! selectElement ) return;
	return selectElement.options[ selectElement.selectedIndex ].value;
}

/**
 * Pobiera status dla danej daty.
 * 	Zwraca true, gdy element ma nie byc pokazywany.
 *	w przeciwynym wypadku zwraca false
 */
DateSelect.prototype._getDateStatus = function ( date ) {
	if ( date < this._rangeStartDate || date > this._rangeEndDate ) {
		return true;
	}
	return false;
	// return this._rangeStartDate > date || this._rangeEndDate < date;
}
/**
 * Pobierania nazwy dla miesiaca
 */
DateSelect.prototype._getMonthString = function ( month ) {
	return 'aaa' + month;
}
/**
 * Ustalenie zakresow
 */
DateSelect.prototype.setRange = function( iRangeStartDateString, iRangeEndDateString ) {
	var rs = iRangeStartDateString ? this.parseDate( iRangeStartDateString ) : this._rangeStartDate;
	var re = iRangeEndDateString   ? this.parseDate( iRangeEndDateString )   : this._rangeEndDate;
	if ( rs >= this._getFirstDate() ) {
		this._rangeStartDate = rs;
	} else {
		this._rangeStartDate = this._getFirstDate();
	}
	if (re <= this._getLastDate() ) {
		this._rangeEndDate   = re;
	} else {
		this._rangeEndDate   = this._getLastDate();
	}
}

/**
 * Ustalenie poczatku zakresu
 */
DateSelect.prototype.setStartOfRange = function(iRangeStartDateString) {
	var rs = iRangeStartDateString ? this.parseDate( iRangeStartDateString ) : this._rangeStartDate;
	if ( rs >= this._getFirstDate() ) {
		this._rangeStartDate = rs;
	} else {
		this._rangeStartDate = this._getFirstDate();
	}
}

/**
 * Funkcja odpalana po zmianie daty obojetnie czy z kalendarza, czy z selektow.
 * Jezeli mamy jakis callback to go uruchamiamy
 */
DateSelect.prototype._onchange = function() {
	if ( this._onchangeCallback ) {
		this._onchangeCallback( this );
	}
}
/**
 * ustawienie funkcji zwrotne uruchamianej podczas modyfikacji
 */
DateSelect.prototype.setOnchangeCallback = function ( iCallback ) {
	this._onchangeCallback = iCallback;
}

