zenexity.tools.namespace('zenexity.glossary');

(function(){

  var zg = zenexity.glossary;

  zg.Glossary = function() {

    var initArgs = function() {
      return {
        id: 0,
        search: "",
        offset: 0,
        size: 12,
        order: "",
        desc: false,
        letter: "",
        selection: "",
        all: false,
        nostd: false
      }
    };

    var g_args = initArgs();
    var g_searchFlag = false;
    var g_total = 0;
    var g_initSearch = "Entrez votre recherche...";
    var g_searchTimeout = null;

    var resetSearch = function() {
      $("#searchInput").val(g_initSearch);
      g_args.search = "";
      g_searchFlag = false;
    };

    var resetLetter = function() {
      $("#alphabet li").removeClass("active");
      g_args.letter = "";
    };

    var onSubmitSearch = function() {
      resetLetter();
      g_args.id = 0;
      g_args.offset = 0;
      g_args.size = 12;
      g_args.search = $("#searchInput",this).val();
      getCompanies();
      return false;
    };

    var getCompanies = function(all) {
      g_args.all = !!all;
      $.get("/quifaitquoi/api/list",g_args,function(companiesHtml) {
        if(!all) $("#results").empty();
        $("#results")[0].innerHTML += companiesHtml;
        var companiesElems = $("#results .packet:last");
        if(!all) {
          $(".more",companiesElems).click(function() {
            $(".more",companiesElems).remove();
            getCompanies(true);
          });
        }
        else { 
          $(".more").remove(true);
        }
        g_total = parseInt($(".total",companiesElems).text());
        $("#searchInfos p").html("<strong>"+(isNaN(g_total)?0:g_total)+"</strong> société"+(g_total>1?"s":"")+" résultent de la recherche.");
        $(".standardLabels .standardLabel",companiesElems)
        .each(function(){
          var num = $(this).attr('rel');
          if ( $("#sider .standardLabelLabel[rel="+num+"]").parent().hasClass("disabled") )
            $(this).addClass('disabled');
        })
        .click(function() {
          var companyElems = $(this).parents().filter(".result");
          $(".standardLabels .standardLabel",companyElems).removeClass("activeLabel");
          $(this).addClass("activeLabel");
          $.get("/quifaitquoi/api/companies/"+companyElems.attr("rel")+"/standards/"+$(this).attr("rel")+"/contacts", function(contactsHtml) {
            $("div.infos",companyElems).replaceWith(contactsHtml);
            $(".option.close",companyElems).click(function() {
              $("div.infos",companyElems).empty().hide();
              $(".standardLabels .standardLabel.activeLabel",companyElems).removeClass("activeLabel");
            });
          });
        });
        $(".chief-contact",companiesElems).click(function() {
          var companyElems = $(this).parents().filter(".result");
          $.get("/quifaitquoi/api/contacts/"+$(this).attr("rel"), function(contactsHtml) {
            $("div.infos",companyElems).replaceWith(contactsHtml);
            $(".option.close",companyElems).click(function() {
              $("div.infos",companyElems).empty().hide();
              $(".standardLabels .standardLabel.activeLabel",companyElems).removeClass("activeLabel");
            });
          });
        });
      });
    };

    var onStandardLabelSelectionChange = function() {
      g_args.selection = "";
      $("#sider .standardLabelLabel").parent().not(".disabled").each(function() {
        if(g_args.selection != "") g_args.selection += " ";
        g_args.selection += $(".standardLabelLabel",this).attr("rel");
      });
      g_args.nostd = !!$("#noStandards").attr("checked");
      g_args.size = 12;
      getCompanies();
    };

    return {
      init: function() {
        g_args.categories = zenexity.context["selectedCategoryIds"];
        $("#search form").submit(function() {
          return false;
        });
        $("#results").empty();
        $("#searchInput").focus(function() {
          if(!g_searchFlag) {
            $("#searchInput").val("");
            g_searchFlag = true;
          }
        })
        .keyup(function() {
          if(g_searchTimeout!==null) {
            clearTimeout(g_searchTimeout);
          }
          g_searchTimeout = setTimeout(function() {
            onSubmitSearch.call($("#search form"));
            g_searchTimeout = null;
          },200);
        })
        .val(g_initSearch);
        $("#alphabet a").click(function() {
          resetSearch();
          $("#alphabet li").removeClass("active");
          if($.trim($(this).text())!=g_args.letter) {
            g_args.letter = $.trim($(this).text());
            $(this).parent().addClass("active");
          }
          else {
            g_args.letter = "";
          }
          g_args.id = 0;
          g_args.offset = 0;
          g_args.size = 12;
          getCompanies();
        });
        $(".sideBox .standardLabelLabel").click(function() {
          $(this).parent().toggleClass("disabled");
          $().trigger("zenexity.glossary.standardLabelSelection.change");
        });
        $(".sideBox .standardLabel .infos").click(function() {
          $(".displayInfos").hide();
          $(".displayInfos",$(this).parents().filter(".standardCategory")).html($(".standardInfos",$(this).parent()).html()).show();
        });
        $("#noStandards").click(function() {
          $().trigger("zenexity.glossary.standardLabelSelection.change");
        });
        $().bind("zenexity.glossary.standardLabelSelection.change",onStandardLabelSelectionChange);
        onStandardLabelSelectionChange();
        $(".allStandards .add-button").click(function() {
          $(".sideBox .standardLabel").removeClass("disabled");
          $("#noStandards").attr("checked","checked");
          $().trigger("zenexity.glossary.standardLabelSelection.change");
        });
        $(".allStandards .rem-button").click(function() {
          $(".sideBox .standardLabel").addClass("disabled");
          $("#noStandards").attr("checked","");
          $().trigger("zenexity.glossary.standardLabelSelection.change");
        });
        $(".standardCategory .add-button").click(function() {
          $(".standardLabels .standardLabel",$(this).parents().filter(".standardCategory")).removeClass("disabled");
          $().trigger("zenexity.glossary.standardLabelSelection.change");
        });
        $(".standardCategory .rem-button").click(function() {
          $(".standardLabels .standardLabel",$(this).parents().filter(".standardCategory")).addClass("disabled");
          $().trigger("zenexity.glossary.standardLabelSelection.change");
        });
      }
    };
  }();

  $().ready(zg.Glossary.init);

})();
