function ProviderSearch(){
  var _self = this;
  var tols = [];
  var deals = [];
  this.init = function(){
    $("#topLink").hide();
    $("#printLink").hide();
    $("#puitejarjestelyt").hide();
    $("#keyword").keyup(_self.nameSearch);
    $(".tol").click(_self.populateDeals);
    $("#deals").change(_self.search);
    $("#kortti").click(_self.search);
    $("#providerform").attr("action", "");
    $("#sendform").hide();
  }


  this.search = function(){

   // puitej�rjestelyt
    deals = [];
    $("#deals option:selected").each(
      function(i){
        deals.push(this.value);
      }
    );

    if(!_self.emptyCheck())
    {
      //$("#results").fadeOut();
      //$("#results").empty();
      $("#results").load("/fi/sopimustoimittajahaku/hae/text", {keyword: $("#keyword").val(), tols: tols.toString(), deals: deals.toString(), kortti:_self.getCardProperty()});
      $("#results").fadeIn('slow');
    }
  }

  this.emptyCheck = function()
  {
    if(_self.getCardProperty() == 0 && tols.length == 0 && deals.length == 0 && $("#keyword").val().length < 3)
    {
      $("#results").fadeOut('slow');
      //$("#results").empty();
      return true;
    }
    return false;
  }



  this.populateDeals = function()
  {
    // toimialat
    tols = [];
    $(".tol:checked").each(
      function(i){
        tols.push(this.value);
      }
    );

    if(tols.length > 0){
      // populate select
      $.post("/fi/sopimustoimittajahaku/hae/puitejarjestelyt/",{tols: tols.toString()}, function(j){
          // alert(j);
        var options = '<option value="">Valitse puitej&auml;rjestely</option>';
        for (var i = 0; i < j.length; i++) {
          options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
        }
        $("#deals").html(options);
        if(options != "")
	      {
	        $("#puitejarjestelyt").show();
	      }
      }, "json");
    }
    else
    {
      $("#deals").html("");
      $("#puitejarjestelyt").hide();
    }

    _self.search();
  }

  this.nameSearch = function()
  {
    if($("#keyword").val().length > 2)
    {
      _self.search();
    }
    else
    {
      _self.emptyCheck();
    }
  }

  this.getCardProperty = function()
  {
    if($("#kortti").is(":checked"))
    {
      return 1;
    }
    else
    {
      return 0;
    }
  }

}


$(function() {
  c = new ProviderSearch();
  c.init();
});
