$(function(){
	
	$(".property_search").autocompleteLocation();
        $("#new_property, .edit_property, #street_address_search").autocompleteStreetAddress();
        
        $("#street_address_search").loadautocompleteStreetAddress();
        $(".edit_tenant, #edit_requirements").autocompleteIdealLocation();
	$('.requirements>ul>li').showRequirements();	
});

$.fn.autocompleteStreetAddress = function(){
  return this.each(function(){
    var street_address_input = $("#post_town", this);
    var loadData = function(){}
    street_address_input.initAutocomplete(loadData, "/admin/street_addresses/autocomplete", {clear:false});
  });
};

$.fn.loadautocompleteStreetAddress = function(){
  return this.each(function(){
    var street_address_input = $("#post_town", this);    
     var loadData = function(item){
      if(item){
        var street_address_id = item.value;
        if(street_address_id){
          window.location.href = "/admin/street_addresses/show/" + street_address_id
        }
      }
    }
    street_address_input.initAutocomplete(loadData, "/admin/street_addresses/autocomplete", {clear:false});
  });
};

// Property location search
$.fn.autocompleteLocation = function(){
  return this.each(function(){
    var locationInput = $(".location_autocomplete", this);
    var dataContainer = $('.data_container',this);
    var loadData = function(item){
      if(item){$.get("/location/find_or_create", {search_string:item.label, location_attributes:item.value, partial:"/admin/base/location"}, function(data){
        if(data){dataContainer.html(data);}
      });}
    }
    locationInput.initAutocomplete(loadData, "/location/autocomplete", {clear:false});
  });
};

// Autocomplete on Landlord names
// Load some data once selection is made
$.fn.initAutocomplete = function(callback, source, opts){
  return this.each(function(){
    opts = opts || {};
    var input = $(this);
    input.autocomplete({
      source: source,
      minLength: 2, //user must type at least 2 characters
      select: function(event, ui) {
        if(ui.item){ 
          input.val(ui.item.label); 
          callback(ui.item);
        }
        return false;
      },
      focus: function(event, ui) { // triggered by keyboard selection
        if(ui.item){input.val(ui.item.label);}
        return false;
      },
      change: function(event, ui) { // called after the menu closes
        if(callback && opts.clear != false){input.val("");}
      } 
    });
  });
}

// // Tenant ideal locations
$.fn.autocompleteIdealLocation = function(){
  return this.each(function(){
    var locationInput = $(".location_autocomplete", this);
    var template = $('#ideal_locations_fields_template');
    var regexp = new RegExp('new_ideal_locations', 'g');
    var container = $("#preferred_locations_container", this);
    
    var loadData = function(item){
      $.getJSON("/location/find_or_create", {search_string:item.label, location_attributes:item.value, json:"true"}, function(data){
        if(!$.isEmptyObject(data)){
          var newTemplate = template.clone();
          var new_id = data.location.id;
          newTemplate.find('[id]').each(function(){
            this.id = this.id.replace(regexp, new_id);
            this.name = this.name.replace(regexp, new_id);
          });
          newTemplate.find("label").each(function(){
            var label = $(this);
            label.attr('for',label.attr('for').replace(regexp, new_id));
          });          
          newTemplate.find("p.search_string").text(data.location.search_string);
          newTemplate.find("label.distance").text(data.location.search_string);
          newTemplate.find("input#tenant_ideal_locations_attributes_" + new_id + "_location_id").val(data.location.id);
          container.append(newTemplate);
          newTemplate.show();
        }
      });
    }
    
    locationInput.initAutocomplete(loadData, "/location/autocomplete");

		// handle remove gracefully
		$('.location>label>[type=checkbox]',container).live('click',function(){
			var remove = $(this);
			if (remove.is(':checked')) remove.closest('div').slideUp('fast');
		});
    
  });
};

$.fn.showRequirements = function(){
	return this.each(function(){
		var fields = $(this).children('ul'); // all the uls
		var options = fields.find('input'); // all the inputs in the uls
		var header = fields.prev(); // all the h3s
		var showAll = $('<label><input type="checkbox"> Select all</label>').appendTo(header); // add the select all to the h3s

		fields.each(function(){
			var field = $(this);
			if (field.find(':checked').length==0) {field.hide();} // if none of the inputs are checked hide them
		});
		header.children('a').click(function(){
			if (!fields.is(':animated')) {
				fields.is(':visible') ? fields.slideUp() : fields.slideDown(); // show hide toggle for the fields
			}
			return false;
		});
		showAll.click(function(){ // toggle for the select all
			$(this).children().is(':checked') ? options.attr('checked',true) : options.attr('checked',false);
		});
		options.change(function(){ // an input is changed
			if(options.not(":checked").length) { // there is an unchecked input
				showAll.children().attr("checked", false);  // ensure select all is not checked
			} else { // there are no unchecked inputs
				showAll.children().attr("checked", true); // ensure select all is checked
			}
		}).change();
	});
}


$(document).ready(function(){
    showFilters($("#property_search_property_category").val());
    

});
function showcheckBox(){
    if($("#property_search_dss_tenants_accepted").is(":checked")==true){
       $("#salebox").hide();
       $("#rentbox").hide();
       $("#salefilter").hide();
       $("#label_id").hide();
    }
    else if($("#property_search_property_category").val()!="rent"){
            $("#salebox").show();
       $("#rentbox").show();
       $("#salefilter").show();
       $("#label_id").show();
    }
    else{
       $("#rentbox").show();
       $("#label_id").show();
    }
}
function showFilters(category){
    if (category=="sale"){
        $("#rentfilter").hide();
        $("#salefilter").show();
        $("#furnshid").hide();
        $("#salebox").show();
        $("#rentbox").hide();
        $("#dss_tenant").hide();
        $(".checkboxes #rentbox #property_search_let_agreed").removeAttr("checked");
        $("#rentbox #property_search_let_agreed,#rentbox #property_search_dss_tenants_accepted").removeAttr("checked");
        $("#property_search_dss_tenants_accepted").removeAttr("checked");
        // Reseting range values.
        $("#property_search_minimum_rent").val('');
        $("#property_search_maximum_rent").val('');
    }
    else if (category=="rent"){
        $("#salefilter").hide();
        $("#rentfilter").show();
        
        $("#salebox").hide();
        if($("#property_search_dss_tenants_accepted").is(":checked")==false){
            $("#rentbox").show();
            $("#label_id").show();
        }
        else if($("#property_search_dss_tenants_accepted").is(":checked")==true){
            $("#rentbox").hide();
            $("#label_id").hide();
        }
        $("#dss_tenant").show();
        $("#furnshid").show();
        $(".checkboxes #salebox #property_search_under_offer").removeAttr("checked");
        $("#salebox #property_search_under_offer").removeAttr("checked");
        // Reseting range values.
        $("#property_search_minimum_sale").val('');
        $("#property_search_maximum_sale").val('');
    }
    else{
        $("#rentfilter").show();
        $("#furnshid").show();
        $("#dss_tenant").show();
        
        if($("#property_search_dss_tenants_accepted").is(":checked")==false){
            $("#salebox").show();
            $("#rentbox").show();
            $("#salefilter").show();
            $("#label_id").show();
        }
        else if($("#property_search_dss_tenants_accepted").is(":checked")==true){
            $("#salebox").hide();
            $("#rentbox").hide();
            $("#salefilter").hide();
            $("#label_id").hide();
        }
        // Reseting range values.
        $("#property_search_minimum_rent").val('');
        $("#property_search_maximum_rent").val('');
        $("#property_search_minimum_sale").val('');
        $("#property_search_maximum_sale").val('');
    }
}
