function click_to_show(id, reveal) {
  $(id).click(function(e){$(e.target).hide(); $(reveal).show(); e.preventDefault(); return false; })
}

function apply_pagination(current_page) {
  $("#pagination").pagination(current_listings.length, {
    items_per_page: listings_per_page, 
    callback: pageselect_callback,
    link_to: '?page=__id__',
    current_page: current_page
  });
}

function reset_listings() {
  apply_pagination(0);
  pageselect_callback(0, $("#listings"));
  if (current_listings.length == 0) {
    $('#pagination').hide()
    $('#no_listings').show();
  } else {
    $('#pagination').show()
    $('#listings').show()
    $('#no_listings').hide();
  }
}

function filter_listings() {
  current_listings = [];
  for (var i = 0; i < listings.length; i++) {
    var matched = true;
    for(f in current_filters) {
      if (current_filters[f] && !current_filters[f](listings[i])) {
        matched = false;
        break;
      }
    }
    if (matched) current_listings.push(listings[i]);
  }
  sort_listings();
}

function sort_listings() {
  if (sorting_function != null) {
    current_listings = current_listings.sort(sorting_function);
  }
  reset_listings();
}

// Filtri del tipo key=value
function make_filter_function(key, value) {
  return function(e) { return e[key] == value; }
}

// Filtri di tipo range (min/max)
function make_range_filter_function(key) {
  return function(e) {
    var min = $('#'+key+"_min").val();
    var max = $('#'+key+"_max").val();
    var val = Number(e[key]);
    if (min == "" && max == "") {
      return true;
    } else if (val == "" || val == "-" || val == null) {
      return false;
    } else {
      if (min == "") { min = 0 } else { min = Number(min) }
      if (max == "") { max = 999999999 } else { max = Number(max) }
      // console.log("FILTER: "+key+" | " + min + " <= " + val + " <= " + max)
      return (val >= min && val <= max);
    }
  }
}

function apply_filter(name, value) {
  if (value == "") {
    delete(current_filters[name]);
  } else {
    current_filters[name] = make_filter_function(name, value);
  }
}

function apply_range_filter(name) {
  current_filters[name] = make_range_filter_function(name);
}

function pageselect_callback(page_index, jq) {
  var max_elem = Math.min((page_index+1) * listings_per_page, current_listings.length);
  $('#listings').html('');
  var row = ''
  for(var i = page_index * listings_per_page; i < max_elem; i++) {
    if (current_listings[i]['formatted_price'] == null) {
      if (current_listings[i]['price'] == null || current_listings[i]['price'] == '' || current_listings[i]['price'] == 0)
        current_listings[i]['formatted_price'] = '&nbsp;'
      else
        current_listings[i]['formatted_price'] = "&euro;&nbsp;" + formatPrice(current_listings[i]['price'])
      }
    if (current_listings[i]['surface'] == null)
      current_listings[i]['surface'] = '-'
    if (current_listings[i]['price'] == null)
      current_listings[i]['price'] = '-'
    if (current_listings[i]['box_type'] == 'non indicato') {
      current_listings[i]['show_box'] = '-'
    } 
    else if (current_listings[i]['box_type'] == 'doppio') {
      	current_listings[i]['show_box'] = '2'
  	}
	else if (current_listings[i]['box_type'] == 'nessuno') {
      	current_listings[i]['show_box'] = '-'
 	}
	else if (current_listings[i]['box_type'] == 'posto auto') {
      	current_listings[i]['show_box'] = '1'
    } else {
      current_listings[i]['show_box'] = '1'
    }
    if (current_listings[i]['bathrooms'] == '' || current_listings[i]['bathrooms'] == null) {
      current_listings[i]['show_bathrooms'] = '-'
    } else {
      current_listings[i]['show_bathrooms'] = current_listings[i]['bathrooms']
    }
    if (!current_listings[i]['show_address']) {
      current_listings[i]['street'] = ''
    }
    current_listings[i]['description_it'] = stripTags(current_listings[i]['description_it'])
    $('#listings').append(listing_template, current_listings[i])

  }
  // $('#listings').append('<br style="clear: left" />');
  return false
}

var SORTING_FUNCTIONS = {
  "id_DESC": function(a, b){ return a.id - b.id; },
  "city_ASC": function(a, b){ return (a.city < b.city) ? -1 : ((a.city > b.city) ? 1 : 0); },
  "city_DESC": function(a, b){ return (a.city > b.city) ? -1 : ((a.city < b.city) ? 1 : 0); },
  "id_ASC": function(a, b){ return a.id - b.id; },
  "id_DESC": function(a, b){ return b.id - a.id; },
  "surface_ASC": function(a, b){ return a.surface - b.surface; },
  "surface_DESC": function(a, b){ return b.surface - a.surface; },
  "price_ASC": function(a, b){ return a.price - b.price; },
  "price_DESC": function(a, b){ return b.price - a.price; }
}

function setup_building_type_filter() {
  var v = $('#building_type_filter').val();
  if (v == "") {
    $("#type_com").hide(); 
    $("#type_vac").hide(); 
    $("#type_res").hide(); 
    $("#type_all").show(); 
    $("#type_all").val("");
  } else if (v == "1") {
    $("#type_all").hide(); 
    $("#type_com").hide(); 
    $("#type_vac").hide(); 
    $("#type_res").show(); 
    $("#type_res").val("");
  } else if (v == "2") {
    $("#type_all").hide(); 
    $("#type_com").hide(); 
    $("#type_res").hide(); 
    $("#type_vac").show(); 
    $("#type_vac").val("");
  } else if (v == "4") {
    $("#type_all").hide(); 
    $("#type_res").hide(); 
    $("#type_vac").hide(); 
    $("#type_com").show(); 
    $("#type_com").val("");
  }
}

function init_listings() {
  var qs = new Querystring();

  var current_page = qs.get('page');

  var building_type = qs.get('building_type');
  if (building_type == undefined) {
    building_type = '';
  }
  apply_filter('building_type', building_type);
  $('#building_type_filter').val(building_type);

  setup_building_type_filter();
  
  var house_typology = qs.get('house_typology');
  if (house_typology == undefined || house_typology == '') {
    house_typology = '';
  }
  apply_filter('house_typology', house_typology);
  if (building_type == '1') {
    $('#type_res').val(house_typology);
  } else {
    $('#type_com').val(house_typology);
  }

  $('#surface_min').val(qs.get('surface_min'));
  $('#surface_max').val(qs.get('surface_max'));
  apply_range_filter('surface');
  
  $('#price_min').val(qs.get('price_min'));
  $('#price_max').val(qs.get('price_max'));
  apply_range_filter('price');
  
  filter_listings();
  if (current_page == undefined || current_page == '') {
    current_page = 1;
  }
  apply_pagination(current_page-1);
  pageselect_callback(current_page == "" ? 0 : Number(current_page-1), $("#listings"));
}

function do_search() {
  $('select.filter').each(function(n, e){
    if (e.style.display != 'none')
      apply_filter($(e).attr("rel"), $(e).val());
  });
  filter_listings();
}

function build_search_url(contract_type, page) {
  var url = "/" + contract_type + '?building_type=' + $('#building_type_filter').val()
  url += '&price_min=' + $('#price_min').val()
  url += '&price_max=' + $('#price_max').val()
  if ($('#type_res').val() != '') {
    url += '&house_typology=' + $('#type_res').val()
  } else if ($('#type_com').val() != '') {
    url += '&house_typology=' + $('#type_com').val()
  }
  url += '&surface_min=' + $('#surface_min').val()
  url += '&surface_max=' + $('#surface_max').val()
  if (page) url += "&page=" + page
  return url
}



function stripTags(s) {
  return s.replace(/<\/?[^>]+>/gi, '')
}

function formatPrice(p)
{
	p += ''
	x = p.split(',')
	x1 = x[0]
	x2 = x.length > 1 ? ',' + x[1] : ''
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + '.' + '$2');
	}
	return x1 + x2;
}