/*
 *  Add Tags Dialog Box
 
   to use this, make sure these dependencies are included
   (some are already in the master template):
  -jquery.ui css and javascript
  -tags.css and tag.js
  -util.js
  -util_format.js
  
  Then add this somewhere in your HTML:
  
  <div id="other-tags-dialog"></div>
  
  Add this to your document.ready:
  
  loadAddTagDialogBox();
  
  You'll also probably want to bind an event like this:
  
  $j(someElem).bind('click', function() { $j('div#other-tags-dialog').dialog('open'); });
 
 */

function loadAddTagDialogBox()
{
  /**
   * updates the empty div for the add tags dialog box to be a dialog box
   * then populates it with its contents
   * population is done after build so it won't take up space on the page
   * DEPENDENCIES: needs jquery.ui javascript, util.js, util_format.js, jquery ui.css.all
   */
  
    var clear_input_and_status_func = function() {
        $j("input#otd-text")[0].value = "";
        updateAddTagsStatus("", "");
    }
    
    $j.ui.dialog.defaults.bgiframe = true;
    $j('div#other-tags-dialog').dialog(
    { 
        autoOpen:false,
        beforeclose:clear_input_and_status_func,
        bgiframe:true,
        dialogClass:"other-tags-dialog-frame",
        draggable:false,
        modal:true,
        height:190,
        resizable:false,
        width:475,
        zIndex:"10000"
    });
    
    // the dialog frame and surrounding form
    var dc = $j('div#other-tags-dialog');
    var form = $j('<form name="otd-form" id="otd-form"></form>');
    dc.append(form);
    
    // add messaging above the text input to the dialog box
    form.append($j("<h2>").html(ellipsify(site_name, 35)));
    form.append($j("<h3>Add a public tag:</h3>"));
    var valid_input_msg = $j("<p>").attr("class","otd-valid-input");
    valid_input_msg.html('Valid characters are: <span>A-Z, 0-9, and "-" for multi-word tags</span>');
    form.append(valid_input_msg);
    
    // add text input, add button, and status elem to the dialog box
    var text_input = $j("<input>").attr("type","text").attr("maxlength","50");
    text_input.attr("name","otd-text").attr("id","otd-text");
    form.append(text_input);
    form.append($j("<input>").attr("type","submit").attr("id","otd-add").attr("value","").attr("class","linky"));
    form.append($j("<p>").attr("id","otd-status"));
    
    // add autocomplete
    _make_autocomplete(text_input)
    // bind event to do the add tag ajax call
    $j("form#otd-form").bind("submit", function() { addTag($j("input#otd-text")[0].value);return false; });
    
    // bind event to convert dashes to spaces on the fly, observe_form_element is from util.js
    var spaces_to_dashes_func = function() {
        var text_input = $j("input#otd-text")[0];
        text_input.value = text_input.value.replace(" ", "-");
        text_input.value = text_input.value.replace("_", "-");
    }
    observe_form_element("otd-text", .5, spaces_to_dashes_func);
}

function updateAddTagsStatus(cssClass, message)
{
  /**
   * Updates the status of the add tags dialog box
   * with either errors or success messages
   * @param {String} cssClass - class to set for the status message or ""
   * @param {String} message - message to set
   */
    $j("p#otd-status").attr("class",cssClass).html(message);
}

function addTag(tagName)
{
  /**
   * Does the validation and adds the tag for the current site.
   * Called from the add tags dialog box
   * @param {string} tagName - tag entered by the user or voted up
   */
    var entered_tag = $j('input#otd-text')[0].value;
    if (entered_tag.length)
    {
        var tag_format_regex = /[^a-zA-Z0-9-]/; // anything not alphanumeric or dash "-"
        if (tag_format_regex.test(entered_tag))
        {
            updateAddTagsStatus("status-error", 'Invalid character: use only A-Z, 0-9, and "-" for multi-word tags');
        }
        else
        {
            updateAddTagsStatus("", "");
            $j.getJSON('/s/add_tag/' + tagName + '/' + site_name + '/', addTagSuccess);
        }
    }
}

function addTagSuccess(jsonObject)
{
    if (jsonObject.error_message)
    {
        updateAddTagsStatus("status-error", jsonObject.error_message);
    }
    else
    {
        updateAddTagsStatus("status-success", '"'+jsonObject.tag_name+'" successfully added.');
        var text_input = $j("input#otd-text")[0];
        text_input.value = "";
        text_input.focus();
        
        // Some pages don't have this but still include the code for it
        try { loadTagsForSite(); } catch(err) { }
    }
}

function _make_autocomplete(input_box) {
  /* Attaches autocomplete functionality to a given input box
  */
  input_box.autocomplete('/s/async/autocomplete_tags/', 
    {'minChars': 3, 
     'delay': 200,
     'cacheLength': 0, 
     'matchSubset': false,
     'selectFirst': true,
     'width': 346, 
   	 'formatItem': function(json_str, i, max, search_term) {
   		  json = eval("(" + json_str + ")")
   		  if (json.is_tagged == 1) {
   		    return '<div class="has_tag"></div>' + ellipsify(json.tag_name, 20).html() + ' (From My Tags)'
   		  }
   		  else {
   		    return '<div class="no_tag"></div>' + ellipsify(json.tag_name, 30).html()
   		  }
   		},
   	 'formatResult': function(json_str, i, max, search_term) {
   		  json = eval("(" + json_str + ")")
   		  return json.tag_name 
   		}
    }
  )
}