﻿    String.prototype.trim = function() {
	    return this.replace(/^\s+|\s+$/g,"");
    }
    
    String.prototype.ltrim = function() {
	    return this.replace(/^\s+/,"");
    } 
    
    String.prototype.rtrim = function() {
	    return this.replace(/\s+$/,"");
    }
  
    function setDirectoryIndex(letter){      
      $(".filter-dropdown .index .alphabet").each(function() {
        $(this).click(function(){
          var letter = $(this).text();          
          if (letter == '') {return false;}
         
          var page = $(this).parent().parent().find("ul li[index="+letter+"]").eq(0);
          $(this).parent().parent().find("ul").scrollTo( page, 1500 );//specify an easing equation;
          return false;
        }); 
      });   
    }
        
    function setFilterSearchOperations() {
      var textBox = $(".filter-dropdown .search .text");
      
      //Keep copy of the original list to always repopulate any searched list
      var originalList = $(textBox).each(function() {$(this).parent().parent().find("ul").clone()});      
      //$(textBox).after("<ul class='original-list' style='display:none;'>"+$(originalList).html()+"</ul>");
      
      //Bind typing events
      $(textBox).each(function() {$(this).keyup(function(e){
        //each key press reduces the listing. user must press X next to search box to show all again
        if ((e.which == 32 || (65 <= e.which && e.which <= 65 + 25) || (97 <= e.which && e.which <= 97 + 25)) || (e.which == 8) || (e.which == 46)) {          
         var c = String.fromCharCode(e.which);
          var searchTerm         = '';
         //backspace
         if ((e.which == 8) || (e.which == 46)) {
            // backspace in IE only be on keydown  
            $(this).parent().find(".searchTerm").children(":last").remove();
         }            
         else {
          $(this).parent().find(".searchTerm").append($("<span/>"))
                      .children(":last")
                      .append(c); 
         }
         searchTerm = $(this).parent().find(".searchTerm").text().toLowerCase().trim();
         //Do the search
         if (searchTerm == '') {
          $(this).parent().parent().find("ul li").each(function(){$(this).show(); });
         }
         else {
           //Find any li's that start with these letters
           $(this).parent().parent().find("ul li").each(function(){
              var contents = $("a", this).text();
              if ((contents != '') || (contents != 'undefined')) {
                if (contents.substring(0, searchTerm.length).toLowerCase() != searchTerm) {
                  $(this).fadeOut("fast");
                } 
                else {
                  $(this).css("display") == 'none' ? $(this).fadeIn("fast") : $(this).css({display:'block'});
                }
              }
           });
         }
         
        } //end keyup
      }).after("<span style='display:none;' class='searchTerm'></span>");
      });
    }
    
    function splitListIntoColumns(listContainer, numColumns){
      $(listContainer).each(function() {
        if ((numColumns==null) || (numColumns=='undefined')) {numColumns = 2;}
        var items = $("li", this);      
        var newList = "";
        var listItems = "";
        var counter = 1;
        var numItemsPerCol = Math.round(items.length/numColumns);          
        if ($(items).length > 0) {
          $(items).each(function(){        
            listItems += "<li rel='"+$(this).attr("rel")+"' class='"+$(this).attr("class")+"'>" + $(this).html() + "</li>";
            if (counter >= numItemsPerCol) {
              newList += "<ul>" + listItems + "</ul>";
              counter = 0;
              listItems = "";
            } 
            counter += 1;        
          });        
          $("ul", this).replaceWith(newList + "<ul>" + listItems + "</ul>");
          $("ul:last", this).addClass("last");
          $("li:last-child", this).addClass("last");
        }
      });
    }  

    
    function getArgs() { 
      var args = new Object(); 
      var query = document.location.search.substring(1); 
      var pairs = query.split("&"); 
      for(var i = 0; i < pairs.length; i++) { 
        var pos = pairs[i].indexOf('='); 
        if (pos == -1) continue; 
        var argname = pairs[i].substring(0,pos); 
        var value = pairs[i].substring(pos+1); 
        args[argname] = unescape(value); 
      } 
      return args; 
    }
    
    //global querystring parameters
    var g_QueryStringParameters = getArgs();

    function request(parameter) {      
      if (g_QueryStringParameters[parameter] != null && g_QueryStringParameters[parameter] != 'undefined') {
        return g_QueryStringParameters[parameter];
      }
      return "";      
    }
    
    function setFilterValue(filter, value) {
      if (filter.length <= 0 || value == "") { return false; }     
      var className = "selected";
      var link = $(filter).find("a:eq(0)");
      if ($(filter).hasClass("last")) {
        className = "selected-last";
      } 
      $(link).addClass(className);
      $(link).attr("rel", value);
      $(filter).closest(".filter-dropdown").find("input").val(value); 
      
      //Set the filter label accordingly
      //TODO: Assume only 1 value in the query string rather than a CSV
      var label = $(filter).find("li[rel="+value+"]").text();
      
      setFilterLabel(filter, label);
    }
    
    /*TODO: MAKE NICE!! This is rubbish*/
    function setFilters() {
      $(".filter-group li.filter").each(function() {
        setFilterValue($(this), request($(this).attr("rel")));  
      });
    }    
    
    /* Set the filter label with selected item, shorten if required */
    function setFilterLabel(filter, label){            
      var link = $(filter).find("a:eq(0)");
      $(link).attr("title", "Filter network by " + label);
      var strlen = $(link).attr("strlen");
      if (label.length > strlen) {
        label = label.substring(0, strlen-3) + "...";
      }        
      $("span", link).text(label);
    }    
        
    function setFilterStatus(filter, label) {
      var link = $(filter).find("a:eq(0)");
      $(link).removeClass("current").attr("rel", label);
      if ($(link).parent().hasClass("last")) {
        $(link).addClass("selected-last");
      } 
      else {
        $(link).addClass("selected");
      }    
    }
    
    /* Set hidden variable with ID or alias     */
    function setFilterFormValue(filter, value) {
      value = ((value == 'undefined') || value == null) ? "" : value;
      $(".filter-dropdown input", filter).val(value);     
    }
   
   
  function updatePage(jqueryDomObj) {
    /**
     * When the user clicks on the update button need to:
     * 1 - For each selected filter build the GET request.
     * 2 - Conacetanate to URL
     * 3 - Submit the request
     */
    
      var filterGroup = $(jqueryDomObj).closest(".filter-group");

      var queryString = "?";
      $(".filter", filterGroup).each(function(){
        var param = $(this).attr("rel");
        var value = $("a:eq(0)", this).attr("rel");
        
        if (value != 'undefined' || value != null || param != 'undefined' || param != null) {
          queryString += param + "=" + escape(value) + "&";
        }
      });
      
      window.document.location.href = window.location.pathname + queryString;
      
      
      
  }   
    
  
  
  function initFilters() {
      
      //Dropdown filter lists need to be listed a-z top to bottom not left to right
      //which is what happens with css float:left. Ugly, but necessary if compiled
      //code is to be left untouched.
      
      splitListIntoColumns( $(".sector-list"), 2.9); //I want 3 columns but putting in 3 will make 4 columns for this set!!
      splitListIntoColumns( $(".subject-list"), 2);
                        
      
      //Filter behaviour
      $(".filter")
      .each(function(){
        //Save the filter label within the anchor and also the str length
        var link = $(this).find("a:eq(0)");
        var label = $("span", link).text();
        $(link).attr("label", label).attr("strlen", label.length)           
      })
      .mouseover(function(){
        var link = $(this).find("a:eq(0)");
        link.removeClass("selected").removeClass("selected-last").addClass("current");        
        $(".filter-dropdown", this).show();
      })
      .mouseleave(function(){
        var link = $(this).find("a:eq(0)");
        var className = "";
        
        currentSelection = $(link).attr("rel");
        //Reset back to selected state
        if (currentSelection != null && currentSelection != 'undefined' && currentSelection != "") {          
          className = "selected"
          if ($(this).hasClass("last")) {
            className = "selected-last";
          }             
        }
        link.removeClass("current").addClass(className);        
        $(".filter-dropdown", this).hide();        
      });
      
      //Filter operation for events, groups, questions, businesses and profiles
      $(".filter-dropdown li").click(function() {       
        var link = $(this).closest(".filter").find("a:eq(0)");

        //Special case if this is the clear option        
        if ($(this).hasClass("clear")) {          
          $(this).closest(".filter-dropdown").hide();          
          $("span", link).text($(link).attr("label"));           
          $(link).removeClass("selected").removeClass("selected-last").removeClass("current").attr("rel", "");
          return false;         
        }
       
        var label = $("a", this).text(); 
        var filter = $(this).closest(".filter");
        
        setFilterFormValue(filter, $(this).attr("rel"));
        setFilterLabel(filter, label);        
        setFilterStatus(filter, $(this).attr("rel"));

        $(this).closest(".filter-dropdown").hide();
        
        updatePage(this);        
        
        return false;
      });      
      
      //If this page was refreshed with selections then update filters accordingly
      setFilters();      
            
      $(".button-update").hide();
      
      //Only show clear button if we need to
      $("#filter-clear-button").click(function(){
        window.document.location.href = window.location.pathname;  
      });     
  
  }
