
function showMunicipalityInfo(municipalityId) {
	$('form#buildingsearch, form#apartmentsearch #location, div.municipality-info').hide();
	$('div#m-' +municipalityId).show();
	$('div#m-' +municipalityId).css('z-index', '1');
	$('div#m-' +municipalityId).css('position', 'relative');
	if(municipalityId > 0) {
		getMunicipality(municipalityId);
	}
}

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results;
}

Array.prototype.remove = function(from, to) {
	  var rest = this.slice((to || from) + 1 || this.length);
	  this.length = from < 0 ? this.length + from : from;
	  return this.push.apply(this, rest);
	};

	
	
$(document).ready(function() {
    $.i18n.setDictionary(i18nDictionary);

	var frank_param = gup( 'county_id' );
	var pos =  location.href.indexOf("?");	

	if (pos >= 0) {
		getCities(frank_param[1]);
	} else {
		showMunicipalityInfo(0);
	}
	$('#cities input, form#apartmentsearch').change(function() {
		submitCountForm();
	});
	$("#cities").click(function(){
		submitCountForm();		
	});

	$('form#apartmentsearch, form#buildingsearch').submit(function() {
		if ($('fieldset#cities input:checked').get(0)) { // Now a simple "if" statement
			return true;
		} else {
			alert($.i18n._('please select district first'));
			return false;
		}
	});	
	//$('tbody tr:eq(0)').addClass('firstrow');
	checkBoxes();

});

function getCities(municipalityId) {
	
	$('div#m-' +municipalityId).hide();
	$("#apartmentsearch #cities").remove();
	
	$('#apartmentsearch #cities-select').append('<fieldset id="cities"></fieldset>');
	$('#apartmentsearch #location').removeClass('hidden');
	
	$('#cities').css('z-index', '1');
	$('#cities').css('position', 'relative');
	
	var box = $('#county_box_id');
	if (box.length > 0) {
		box.attr('value', municipalityId);
	} else {
		$('#apartmentsearch').prepend('<input type="hidden" id="county_box_id" value="' + municipalityId + '" name="county_id" id="county_box_id" />');
	}
		
	$.getJSON(baseUrl() + '/municipality/cities/id/' + municipalityId, function(data) {
		$("#cities").prepend('<input type="checkbox" id="all" name="city[id][]" value="0"><label for="all">' + $.i18n._('all districts') + '</label>');
		$.each(data, function(i,item){
			var apartmentText = ' asuntoa';
			if(item.apartmentText == 1) {
				var apartmentText = ' asunto';
			}
			$("#cities").append('<input type="checkbox" name="city[id][]" id="city-' +item.id +'" value="' +item.id +'" /><label for="city-' +item.id +'">' +item.name +' (' +item.apartmentCount +apartmentText +')'+'</label>');
		});
		getMunicipality(municipalityId);
		setCitySelect();
		setCitySelectEncoded();
		selectAllCities();
		

		$('#cities input:not(#all)').change(function(){
	        var value = $(this).attr('value');
	        if (value == 0) {
	        	$('#cities input').attr('checked', 'checked');
	        }
	        var allCboxCount = $("#cities input:checkbox:not(#all)").length;
	        var checkedCboxCount = $("#cities input:checkbox:checked:not(#all)").length;
	        if(allCboxCount == checkedCboxCount) {
	        	//alert('kaikki ois: bas.search.js');
	        	
	        	$('#cities input#all').attr('checked', 'checked');
	        } else {
	        	//alert('vajaa ois: bas.search.js');

	        	$('#cities input#all').attr('checked', '');	        	
	        
	        }
			submitCountForm();
		});
		
	});
}

function submitCountForm () {
	var formUrl = $('#buildingsearch, #apartmentsearch').attr('action');
	var queryString = $('#buildingsearch *, #apartmentsearch *').fieldSerialize();
	var formUrl = formUrl.replace("result", "count");
	var requestUrl = formUrl +"?" +queryString;
	var selectedCitiesCount = $("#cities input:checked").length;
	if(selectedCitiesCount > 0) {
		$.getJSON(requestUrl,
			function(data){
				if (data.resultCount !== null) {
					$('p.submit strong').show();
					$('body#request-search-buildingresult #result-count').text(data.resultCount);
					$('body#request-search-index #result-count').text(data.resultCount + ' kpl');
					$('div.info').show();
					checkBoxes();
				}
		});
	} else {
		$('p.submit strong').hide();
	}
}

function selectAllCities () {
    setTimeout(function() {
        var citiesCount = $("#cities input").length;  
        var selectedCitiesCount = $("#cities input:checked").length;
        if (selectedCitiesCount == 0 || selectedCitiesCount == (citiesCount - 1)) {
           $('#cities input').attr('checked', 'checked');
        }
        submitCountForm();
    }, 250);
}

function setCitySelect () {
	var cities = location.href.split('city[id][]=');
	cities.remove(0);
    jQuery.each(cities, function(i, val) {
    	if((val.indexOf("&") >= 0)) {
    		var tempval = val.split("&");
    		val = tempval[0];
    		if(val == 0) {
    			selectAllCities();
    			return;
    		}
    	}
        $('#cities input[value="' +val +'"]').attr('checked', 'checked');
     });
}

function setCitySelectEncoded () {
	var cities = location.href.split('city%5Bid%5D%5B%5D=');
	cities.remove(0);
    jQuery.each(cities, function(i, val) {
    	if(val.indexOf("&") >= 0) {
    		var tempval = val.split("&");
    		val = tempval[0];
    		if(val == 0) {
    			selectAllCities();
    			return;
    		}
    	}
        $('input[value="' +val +'"]').attr('checked', 'checked');
      });
}


function buildingResultInit() {
	/*
	$('#cities *').change(function(){
        var value = $(this).val();
		if (value == 0) {
        	$('#cities input').attr('checked', 'checked');
        }
		submitCountForm();
	});
	*/
	setCitySelect();
	setCitySelectEncoded();	
	
}

function getMunicipality(municipalityId) {
	var areaName = $('div#m-' +municipalityId +' h2:eq(0)').text(); 
	var buildingCount = $('div#m-' +municipalityId +' h2:eq(1)').text(); 
	$('#location .municipalities p').empty();
	$('#location .municipalities p').append(areaName +'<br />' +buildingCount);
}


function checkBoxes () {
	var allCboxCount = $("form#buildingsearch input:checkbox:not(#all)").length;
	var checkedCboxCount = $("form#buildingsearch input:checkbox:checked:not(#all)").length;
	if(allCboxCount > checkedCboxCount) {
		$('form#buildingsearch input#all').attr('checked', '');
	} else {
		$('form#buildingsearch input#all').attr('checked', 'checked');	        	
	}
	

}