/*
  Copyright (c) 2009 Open Lab, http://www.open-lab.com/
  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
   * options.tags an object array [{tag:"tag1",freq:1},{tag:"tag2",freq:2}, {tag:"tag3",freq:3},{tag:"tag4",freq:4} ].
   * options.jsonUrl an url returning a json object array in the same format of options.tag. The url will be called with
   *                              "search" parameter to be used server side to filter results
   * option.autoFilter true/false  default=true when active show only matching tags, "false" should be used for server-side filtering
   * option.autoStart true/false  default=false when active dropdown will appear entering field, otherwise when typing
   * options.sortBy "frequency"|"tag"|"none"  default="tag"
   * options.tagSeparator default="," any separator char as space, comma, semicolumn
   * options.boldify true/false default trrue boldify the matching part of tag in dropdown
   *
   * options.suggestedTags callback an object array like ["sugtag1","sugtag2","sugtag3"]
   * options.suggestedTagsPlaceHolder  jquery proxy for suggested tag placeholder. When placeholder is supplied (hence unique), tagField should be applied on a single input
   *                          (something like  jQuery("#myTagFiled").tagField(...) will works fine: jQuery(":text").tagField(...) probably not!)
   */

if (typeof(String.prototype.trim)  == "undefined"){
    String.prototype.trim = function () {
      return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
    };
}

jQuery.fn.tagInput = function(options) {
  // --------------------------  start default option values --------------------------
  if (!options.tags && !options.jsonUrl) {
    options.tags = [ { tag:"tag1", freq:1 }, { tag:"tag2", freq:2 }, { tag:"tag3", freq:3 }, { tag:"tag4", freq:4 } ];
  }

  if (typeof(options.tagSeparator) == "undefined")
    options.tagSeparator = ",";

  if (typeof(options.autoFilter) == "undefined")
    options.autoFilter = true;

  if (typeof(options.autoStart) == "undefined")
    options.autoStart = false;

  if (typeof(options.boldify) == "undefined")
    options.boldify = true;

  if (typeof(options.sortBy) == "undefined")
    options.sortBy = "tag";

  // --------------------------  end default option values --------------------------


  this.each(function() {

    var theInput = jQuery(this);
    var theDiv;

    theInput.tagOptions=options;

    var suggestedTagsPlaceHolder=options.suggestedTagsPlaceHolder;
    //create suggested tags place if the case
    if (options.suggestedTags){
      if (!suggestedTagsPlaceHolder){
        //create a placeholder
        var stl=jQuery("<p class='form-text text-muted'>"+jquery_tagInput_js_suggested_tags_text+"<span class='tagInputSuggestedTagList'></span></p>");
        suggestedTagsPlaceHolder=stl.find(".tagInputSuggestedTagList");
        theInput.parent().after(stl);
      }

      //fill with suggestions
      for (var i = 0; i < options.suggestedTags.length; i++) {
        suggestedTagsPlaceHolder.append(jQuery("<span class='tag'></span>").text(options.suggestedTags[i]));
        if (i != options.suggestedTags.length - 1)
          suggestedTagsPlaceHolder.append(options.tagSeparator);
      }
      jQuery(this).oneTime(400, "suggTagRefresh", function() { selectSuggTagFromInput(); });

      // bind click on suggestion tags
      suggestedTagsPlaceHolder.find(".tag").click(function() {
        var element = jQuery(this);
        var val = theInput.val();
        var tag = element.text();

        //check if already present
        if (containsTag(val, tag)) {
          val = removeTag(val, tag);
          element.removeClass("tagUsed");
        } else {
          val = val + options.tagSeparator + tag;
          element.addClass("tagUsed");
        }
        theInput.val(refurbishTags(val));
      theInput.change();
      });

    }


    // --------------------------  INPUT FOCUS --------------------------
    var tagInputFocus = function () {
      theDiv = jQuery("#__tagInputDiv");
      // check if the result box exists
      if (theDiv.size() <= 0) {
        //create the div
        theDiv = jQuery("<div id='__tagInputDiv' class='tagInputDiv' style='width:" + theInput.get(0).clientWidth + ";display:none; '></div>");
        theInput.after(theDiv);
        theDiv.css({left:theInput.position().left});
      }
      if (options.autoStart)
        tagInputRefreshDiv(theInput, theDiv);
    };


    // --------------------------  INPUT BLUR --------------------------
    var tagInputBlur = function () {
      // reformat string
      theDiv = jQuery("#__tagInputDiv");
      theInput.val(refurbishTags(theInput.val()));

      theDiv.fadeOut(200, function() {
        theDiv.remove();
      });
    };


    // --------------------------  INPUT KEYBOARD --------------------------
    var tagInputKey = function (e) {
      var rows = theDiv.find("div.tagInputLine");
      var rowNum = rows.index(theDiv.find("div.tagInputSel"));

      var ret = true;
      switch (e.which) {
        case 38: //up arrow
          rowNum = (rowNum < 1 ? 0 : rowNum - 1 );
          tagInputHLSCR(rows.eq(rowNum), true);
          break;

        case 40: //down arrow
          rowNum = (rowNum < rows.size() - 1 ? rowNum + 1 : rows.size() - 1 );
          tagInputHLSCR(rows.eq(rowNum), false);
          break;

        case 9: //tab
        case 13: //enter
          if (theDiv.is(":visible")){
            var theRow = rows.eq(rowNum);
            tagInputClickRow(theRow);
            ret = false;
          }
          break;

        case 27: //esc
          theDiv.fadeOut(200);
          break;

        default:
          jQuery(document).stopTime("tagInputRefresh");
          jQuery(document).oneTime(400, "tagInputRefresh", function() {
            tagInputRefreshDiv();
          });
          break;
      }
      return ret;
    };


    // --------------------------  TAG DIV HIGHLIGHT AND SCROLL --------------------------
    var tagInputHLSCR = function(theRowJQ, isUp) {
      if (theRowJQ.size() > 0) {
        var div = theDiv.get(0);
        var theRow = theRowJQ.get(0);
        if (isUp) {
          if (theDiv.scrollTop() > theRow.offsetTop) {
            theDiv.scrollTop(theRow.offsetTop);
          }
        } else {
          if ((theRow.offsetTop + theRow.offsetHeight) > (div.scrollTop + div.offsetHeight)) {
            div.scrollTop = theRow.offsetTop + theRow.offsetHeight - div.offsetHeight;
          }
        }
        theDiv.find("div.tagInputSel").removeClass("tagInputSel");
        theRowJQ.addClass("tagInputSel");
      }
    };


    // --------------------------  TAG LINE CLICK --------------------------
    var tagInputClickRow = function(theRow) {
      var lastComma = theInput.val().lastIndexOf(options.tagSeparator);
      var sep= lastComma<=0? (""):(options.tagSeparator+ (options.tagSeparator==" "?"":" "));
      var newVal = (theInput.val().substr(0, lastComma) + sep + theRow.find(".tagInputLineTag").text()).trim();
      theInput.val(newVal);
      theInput.change();
      theDiv.hide();
      jQuery(document).oneTime(200, function() {
        theInput.focus();
      });
	  selectSuggTagFromInput();
    };


    // --------------------------  REFILL TAG BOX --------------------------
    var tagInputRefreshDiv = function () {

      var lastComma = theInput.val().lastIndexOf(options.tagSeparator);
      var search = theInput.val().substr(lastComma + 1).trim();


      // --------------------------  FILLING THE DIV --------------------------
      var fillingCallbak = function(tags) {
        /*if (options.sortBy == "frequency") {
          tags = tags.sort(function (a, b) {
            if (a.freq < b.freq)
              return 1;
            if (a.freq > b.freq)
              return -1;
            return 0;
          });

        } else if (options.sortBy == "tag") {
          tags = tags.sort(function (a, b) {
            if (a.tag < b.tag)
              return -1;
            if (a.tag > b.tag)
              return 1;
            return 0;
          });
        }*/

        jQuery.ajax('/intranet/rest/core/tags/', {
            method: 'get',
            data: { filter: search + '*' },
            dataType: 'json',
            success: function (data) {
                var tags = data.data;
                for (var i=0; i<tags.length; i++) {
                    var el = tags[i];

                    var line = jQuery("<div class='tagInputLine'></div>");
                    var tag = el.tag;

                    lineTag = jQuery("<div class='tagInputLineTag'></div>");

                    if (options.boldify) {
                        lineTag.append(jQuery("<b></b>").text(tag.substring(0, search.length)));
                        lineTag.append(jQuery("<span></span>").text(tag.substring(search.length)));
                    } else {
                        lineTag.text(tag);
                    }

                    line.append(lineTag);
                    if (el.freq)
                        line.append("<div class='tagInputLineFreq'>" + el.freq + "</div>");
                    theDiv.append(line);
                }
                if (theDiv.html() !== ""){
                    theDiv.fadeIn();
                }

                theDiv.find("div:first").addClass("tagInputSel");
                theDiv.find("div.tagInputLine").bind("click", function() {
                    tagInputClickRow(jQuery(this));
                });
            }
        });
      };


      if (search !== "" || options.autoStart) {
        theDiv.html("");

        if (options.tags)
          fillingCallbak(options.tags);
        else{
          var data = {search:search};
          jQuery.getJSON(options.jsonUrl, data, fillingCallbak );
        }
      } else {
        theDiv.fadeOut(200);
      }
    };

    // --------------------------  CLEAN THE TAG LIST FROM EXTRA SPACES, DOUBLE COMMAS ETC. --------------------------
    var refurbishTags = function (tagString) {
      var splitted = tagString.split(options.tagSeparator);
      var res = "";
      var first = true;
      for (var i = 0; i < splitted.length; i++) {
        if (splitted[i].trim() != "") {
          if (first) {
            first = false;
            res = res + splitted[i].trim();
          } else {
            res = res + options.tagSeparator+ (options.tagSeparator==" "?"":" ") + splitted[i].trim();
          }
        }
      }
      return( res);
    };

    // --------------------------  REMOVE TAG FROM THE LIST. --------------------------
    var removeTag = function (tagString, tagToRemove) {
      var splitted = tagString.split(options.tagSeparator);
      var res = "";
      var first = true;
      for (var i = 0; i < splitted.length; i++) {
		var cleanTag = splitted[i].trim();
        if (cleanTag != "" && cleanTag != tagToRemove) {
          if (first) {
            first = false;
            res = res + cleanTag;
          } else {
            res = res + options.tagSeparator+ (options.tagSeparator==" "?"":" ") + cleanTag;
          }
        }
      }
      return( res);
    };

    // --------------------------  TEST IF TAG IS PRESENT --------------------------
    var containsTag=function (tagString,tag){
      var splitted = tagString.split(options.tagSeparator);
      var res="";
      var found=false;
      tag=tag.trim();
      for(i = 0; i < splitted.length; i++){
        var testTag=splitted[i].trim();
        if (testTag==tag){
          found=true;
          break;
        }
      }
      return found;
    };


    // --------------------------  SELECT TAGS BASING ON USER INPUT --------------------------
    var delayedSelectTagFromInput= function(){
      var element = jQuery(this);
      element.stopTime("suggTagRefresh");
      element.oneTime(300, "suggTagRefresh", function() {
        selectSuggTagFromInput();
      });

    };

    var selectSuggTagFromInput = function () {
      var val = theInput.val();
      suggestedTagsPlaceHolder.find(".tag").each(function(){
        var el = jQuery(this);
        var tag=el.text();

        //check if already present
        if (containsTag(val,tag)) {
          el.addClass("tagUsed");
        } else {
          el.removeClass("tagUsed");
        }
      });

    };

    // --------------------------  INPUT BINDINGS --------------------------
    jQuery(this).bind("focus", tagInputFocus).bind("blur", tagInputBlur).bind("keydown", tagInputKey);
    if (options.suggestedTags)
      jQuery(this).bind("keyup",delayedSelectTagFromInput) ;
  });
  return this;
};


