function number_format (number, decimals, dec_point, thousands_sep) {
    // Strip all characters but numerical ones.
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');    }
    return s.join(dec);
}


$('.sico').live('click',function(){
  $('#is_section').click();  
});
 $(".iro").live('click',function(){
  var id = $(this).attr('id').slice(1);
  $('#'+id+' div').show('blind');
  $('#search_submit').hide();
  $('#mapsearch_box').hide();
 });
$(".msd button,.srb").live('click',function(){
  $('#search_submit').show();
  $('#mapsearch_box').show();
  if ($(this).hasClass('districtbutton')) {
    $('#groupRdiv').hide(); $('#groupLdiv').hide();
  }
  else $(this).parent().hide();   
  return false;  
});



$(".msd input").live('click',function(){
  if ($(this).hasClass('district')) {
    var classname = 'input:checkbox.'+$(this).attr('id');    
    if ($(this).next().hasClass('ui-checkbox-checked')) {      
      jQuery.each($(classname),function(){
        if (!$(this).next().hasClass('ui-checkbox-checked') && !$(this).hasClass('district')) $(this).next().click();    
      });      
    } else {      
      jQuery.each($(classname),function(){
        if ($(this).next().hasClass('ui-checkbox-checked') && !$(this).hasClass('district')) $(this).next().click();    
      });      
    }
  } else {
    var id = $(this).parent().parent().attr('id');  
    var txt = $('#i'+id);
    var values = [];
    var labs = '';
    $('#'+id+' input:checked').each(function(index) {
      labs = $(this).attr('id');
      labs = $('label[for='+labs+']').html();
      values.push(labs);     
    });
    txt.val(values.join());  
  }
});

function setSearch (section) {
  $('.s_one').each(function(index) {
    if ($(this).hasClass(section)) {
      $(this).show();      
      $("input:checkbox,input:radio").not('.searchcheck').checkBox();
      $("input:checkbox,input:radio").addClass('searchcheck');
    }
    else $(this).hide(); 
  });
} 
$('#Sale,#Rental').live('click',function(){
  setSearch($('#srb_section').val()+$(this).val());  
});
$('.srb').live('click',function(){
  $('.srbon').removeClass('srbon');
  $(this).addClass('srbon');
  $('#srb_section').val($(this).val());
  setSearch($(this).val()+$('#rs').val());  
});       
$('#advsearch_box').live('click',function () {
  if ( $('#advsearch_box span').hasClass('open') ) {
    $('#adv_search').hide('blind');         
    $('#advsearch_box span').removeClass('open');
    $('#adv').val(0);
  } else {
    $('#adv').val(1);
    $('#adv_search').show('blind',function(){
      $('#advsearch_box span').addClass('open');
    });
  }
});
$('#mapsearch_box').live('click',function () {
  if ( $('#mapsearch_box span').hasClass('open') ) {
    $('#mapsearch').hide('slide');         
    $('#mapsearch_box span').removeClass('open');
    usunMarkery();
  } else {
    $('#mapsearch').show('slide',function(){
      if (!$('#gmmap_load').hasClass('loaded')) mapaSearch();
      $('#mapsearch_box span').addClass('open');
    });
  }
});

$('#dorozwiniecia').live('click',function(){
  $(this).remove();
  $('.dorozwiniecia').removeClass('dorozwiniecia');
  $('.search_hide').removeClass('search_hide');
  start_options();
});
var keystrokes = 0;
$('#s_locations_name').live('keyup',function(){
  ++keystrokes;
  setTimeout(getlocation, 1000);
});

function show_search_submit() {
  $('#search_submit').show();
  $('#mapsearch_box').show();
  return false;
}

function getlocation() {  
  --keystrokes;
  if (keystrokes == 0) {
    if ($('#s_locations_name').val()) {
      $('#search_submit').hide();
      $('#mapsearch_box').hide();
      $('#locations_elems div').html('<img src="./upload/gfx/loader.gif" alt="" />');
      $('#locations_elems div').show();       
      $.ajax({
        url: 'ajax.php?locations='+$('#s_locations_name').val()
        ,success: function(locations) {
          var loco = '';
          var locodiv = '<input type="checkbox" id="locoindex" /><label for="locoindex" title="locotitle">loconame</label><br />';
          var ls = locations.split('##');
          if (ls[0]) {
            for (i=0;i<ls.length;i++) {
              var l = ls[i].split('#');
              var names = l[1].split('/');   
              var locotitle=names[1];
              names.splice(0,2);        
              loco = loco+locodiv.replace("locotitle", locotitle).replace("loconame", names.join(', ')).replace("locoindex", "loco"+l[0]).replace("locoindex", "loco"+l[0]);                    
            } 
          } else loco='Nie znaleziono miejscowości';
          loco = loco+"<button onclick='show_search_submit()'>"+close_values+"</button>";
          $('#locations_elems div').html(loco);
          $("#locations_elems div input:checkbox").checkBox();
          $("#locations_elems div button").button();  
          $("#locations_elems div").find('[title]').tooltip({track: true, showURL: false, showBody: "|", extraClass:'titleall'});
          
        }
        ,fail: function(locations) {
        } 
      });    
    }  
  }
}

$("#locations_elems div button").live('click',function(){
  
  var locations = $("#locations").html();
  var locoelems = '<div class="locoelem"><input type="hidden" name="search[locations][locoval]" value="loconame" />loconame</div>'; 
  jQuery.each($("#locations_elems div label.ui-checkbox-checked"),function(){
    locations = locations + locoelems.replace("locoval", $(this).attr('for').slice(4)).replace("loconame", $(this).html()).replace("loconame", $(this).html());
   // if ($(this).html() == 'Szczecin') $('#locations_district').show('fade');    
  });
  $("#locations_elems div").hide();
  $("#locations").html(locations);
  $("#s_locations_name").val('');
  
  return false;
});

$('.locoelem').live('click',function(){
  //if ($(this).find('input').val() == 'Szczecin') $('#locations_district').hide('fade');
  $(this).remove();  
});

function start_slider() {
  $('.slider').find('.minmaxstep').each(function(index) {
    var id = $(this).attr('id');
    var minmaxstep = $('#slider'+id).val().split('_');
    var rmin = new Number(minmaxstep[0]);
    var rmax = new Number(minmaxstep[1]);
    var rstep = new Number(minmaxstep[2]);
    var amount0 = $('#s_'+id+'_0');
    var amount1 = $('#s_'+id+'_1');
    var ramount0 = $('#r_'+id+'_0');
    var ramount1 = $('#r_'+id+'_1');
    var r0 = new Number(amount0.val()?amount0.val():rmin);
    var r1 = new Number(amount1.val()?amount1.val():rmax);
    $(this).slider({ 			
			min: rmin,
			max: rmax,
			values: [ r0, r1 ],
			step: rstep,
			range: true,
			slide: function( event, ui ) {        
        amount0.val(ui.values[0]==rmin?'':ui.values[0]);        
				amount1.val(ui.values[1]==rmax?'':ui.values[1]);
				ramount0.html(ui.values[0]==rmin?'':number_format(ui.values[0],0,',',' '));
				ramount1.html(ui.values[1]==rmax?'':number_format(ui.values[1],0,',',' '));
			}
		});     
  });
}
var smarkery = [];
var mapka;
var poly;
var polysearch = [];

function mapaSearch() { 
  var Lat = '53.429805';
  var Lng = '14.537883';
	var wspolrzedne = new google.maps.LatLng(Lat, Lng);
  var opcjeMapy = {
			zoom: 13,
			center: wspolrzedne,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			disableDefaultUI: true,
			navigationControl: true,
			navigationControlOptions:
      {
          style: google.maps.NavigationControlStyle.SMALL // w stylu SMALL  ZOOM_PAN
      }    
	};
	mapka = new google.maps.Map(document.getElementById("gmmap_load"), opcjeMapy);
	$('#gmmap_load').addClass('loaded');
  var polilinia = {
    strokeColor:    '#184583',
    strokeWeight:   2,
    strokeOpacity:  0.7
  }
  poly = new google.maps.Polyline(polilinia);
  poly.setMap(mapka);

  
	google.maps.event.addListener(mapka,'click',function(zdarzenie)
				{
					if(zdarzenie.latLng)	
					{
						dodajPunkt(zdarzenie.latLng);						
					}
				});
   		
}
function dodajPunkt(latlng)	{
	var path = poly.getPath();
  path.push(latlng);
  polysearch.push('{"lat":'+latlng.lat()+',"lng":'+latlng.lng()+'}');
  if (path.length > 2) $('#smap').val('[['+polysearch+']]');
  var marker = new google.maps.Marker({  
			position: latlng,
			map: mapka
	});  
  google.maps.event.addListener(marker,'click',function(zdarzenie)
				{
					if(zdarzenie.latLng)	
					{
						dodajPunkt(zdarzenie.latLng);						
					}
				}); 
	smarkery.push(marker);
}

function usunMarkery() {
  if (smarkery.length) mapaSearch();
	smarkery = [];
	polysearch = [];
	$('#smap').val('');
}


