/**
  QuickComments UI
  requires jQuery, ui.stars, ui.autocomplete, tablesorter (all MIT)
**/
QC = {
  currentTagList: 0, // counter
  defaultCommentText: 'Add a comment (optional)',
  defaultAddTagText: '15 letters max.',
  maxTagLength: 15,
  
  // initialize the widget
  init: function () {
    $('#tag_cloud li a').click(QC.toggleTag);
    $('#ratings_and_comments_form').submit(QC.submitFeedback);
    $('#custom_tag_form').submit(QC.submitNewTag);
    $('#footer a, #view_opinions a').click(QC.toggleWidgetState);
    $('#report_section').hide();
    $("#tag_text").autocomplete(QC.AUTOCOMPLETE_TAGS);
    $('#tag_text').keydown(QC.limitTagLength)
    QC.initTagLists();
    QC.initDefaultText();
    QC.initReportScreen();
  },

  // These will need to be updated again when the partial is reloaded
  initReportScreen: function () {
    $('#report_wrapper table').tablesorter({ sortList: [[1,1]], widgets: ['zebra'] });
    $('#report_wrapper a').click(QC.showTagDetailReport);
  },
  
  initDefaultText: function () {
    // tag textfield
    var tagField = $("#tag_text");
    var tagText = QC.defaultAddTagText;
    if (tagField.val().length == 0) { tagField.val(tagText); }
    tagField.focus(function (evt) {
      if (tagField.val() == tagText) { tagField.val(''); }
    });
    tagField.blur(function (evt) {
      if (tagField.val().length == 0) { tagField.val(tagText); }
    });    
    
    // comments textarea
    var commentDiv = $("#comment");
    var commentExample = QC.defaultCommentText;
    if (commentDiv.val().length == 0) { commentDiv.val(commentExample); }
    commentDiv.focus(function (evt) {
      if (commentDiv.val() == commentExample) { commentDiv.val(''); }
    });
    commentDiv.blur(function (evt) {
      if (commentDiv.val().length == 0) { commentDiv.val(commentExample); }
    });
  },

  initTagLists: function () {
    //QC.TAGS_TO_SHOW
    var numLists = $('#tag_cloud ul').length;
    var wrapper = $('#tag_scroll_wrapper');
    // wrapper.css('width', '10000px');
    if (numLists <= 2) {
      $('#tag_nav').hide();
    } else {
      $('#prev_tags').addClass('disabled');
      $('#prev_tags').click(function (evt) {
        evt.preventDefault();
        $('#next_tags').removeClass('disabled');
        var wrapper = $('#tag_scroll_wrapper'), offset = parseInt(wrapper.css('marginLeft'));
        wrapper.animate( { marginLeft:(offset+205)+'px' }, { duration:500 })
        QC.currentTagList -= 2;
        if (QC.currentTagList <= 0) {
          $('#prev_tags').addClass('disabled');
        }
      });
      $('#next_tags').click(function (evt) {
        evt.preventDefault();
        $('#prev_tags').removeClass('disabled');
        var offset = parseInt(wrapper.css('marginLeft'));
        wrapper.animate( { marginLeft:(offset-205)+'px' }, { duration:500 })
        QC.currentTagList += 2;
        if (QC.currentTagList * 2 >= numLists) {
          $('#next_tags').addClass('disabled');
        }
      });
    }
  },
  
  /**
    Handler for user click in the tag cloud
  */
  toggleTag: function (evt) {
    var link = $(evt.target);
    var tagId = link.attr('href').match(/[0-9]+$/)[0];
    evt.preventDefault();
    if (link.hasClass('selected')) {
      QC.removeStars(link, tagId);
    } else {
      QC.createStars(link, tagId);
    }
  },
  
  /**
    Note: this prevents using keyboard shortcut to select all if max is reached.
  */
  limitTagLength: function (evt) {
    var aCharaterWasTyped = (evt.keyCode >= 48 && evt.keyCode <= 90) || (evt.keyCode >= 96 && evt.keyCode <= 111);
    return !($("#tag_text").val().length >= QC.maxTagLength && aCharaterWasTyped);
  },
  
  /**
    Create a star rating
    fromLink {jQuery object} - link for the tag
    text {string} - optional; use instead of fromLink to specify a custom tag (user-added)
  */
  createStars: function (fromLink, tagId, text) {
    text = text || fromLink.html();
    if (fromLink) { 
      fromLink.addClass('selected'); 
    } else if ($('#tag_select_'+tagId).length > 0) { // user typed a tag that was already shown in the list
      $('#tag_select_'+tagId).addClass('selected');
    }
    var starsWrapperId = 'stars_wrapper_' + tagId;
    if ($('#'+starsWrapperId).length > 0) { // this tag has already been added
      return;
    }
    $('#rating_instructions').hide();
    $('#rating_header, #ratings, #rating_legend').show();
    $('#ratings').append([
      '<div class="rating_line" id="rating_line_', tagId, '">',
        '<label for="rating_', tagId, '">', 
          '<a href="#delete" id="del_', tagId, '"><img src="/images/icon_rating_list.gif" alt="delete" class="delete"></a>', text, 
        '</label>',
        '<div id="', starsWrapperId, '">',
          '<input type="radio" name="ratings[', tagId, ']" value="1" title="', QC.SCALE_LABELS[0], '">',
          '<input type="radio" name="ratings[', tagId, ']" value="2">',
          '<input type="radio" name="ratings[', tagId, ']" value="3">',
          '<input type="radio" name="ratings[', tagId, ']" value="4">',
          '<input type="radio" name="ratings[', tagId, ']" value="5" title="', QC.SCALE_LABELS[1], '">',
        '</div>',
      '</div>'
    ].join(''));
    $('#del_'+tagId).click(function (evt) {
      evt.preventDefault();
      QC.removeStars(tagId);
    });
    $("#" + starsWrapperId).stars({
     captionEl: $('#rating_scale') 
    });
  },
  
  removeStars: function (tagId) {
    $("#rating_line_"+tagId).remove();
    $("#tag_select_"+tagId).removeClass('selected');
  },
  
  /**
    abstracted submit form
    params - query string style
  */
  submit: function (url, params, callback, type) {
    type = type || 'json';
    params = params || "";
    params += (params ? "&" : "") + "&authenticity_token=" + encodeURIComponent(QC.AUTH_TOKEN);
    $.post(url, params, callback, type);
  },
  
  /**
    Handler for submit event on main ratings/comment form
  */
  submitFeedback: function (evt) {
    evt.preventDefault();
    if ($("#comment").val() == QC.defaultCommentText) {
      $("#comment").val('');
    }
    var params = $(evt.target).serialize();
    QC.submit('/widgets/feedback', params, QC.receivedFeedback, 'html');
  },
  
  /**
    Handler for submit event on add tag form
  */
  submitNewTag: function (evt) {
    evt.preventDefault();
    var params = $(evt.target).serialize();
    QC.submit('/tags', params, QC.addedTag);
  },
  
  receivedFeedback: function (data, textStatus) {
    $('#report_section').html(data);
    QC.initReportScreen();      
    QC.toggleWidgetState(null, true);
  },
  
  addedTag: function (data) {
    if (data.id) {
      $('#tag_text').val('');
      QC.AUTOCOMPLETE_TAGS.push(data.text);
      // TODO: reset the autocompleter
      QC.createStars(null, data.id, data.text);
    } else {
      alert('Sorry there was a problem adding your tag.')
    }
  },
  
  /**
    Switch between feedback & report states
    showOpinions {Bool} - programmatically show either "opinion" or forms, 
                          instead of relying on event handler (defaults to false)
  */
  toggleWidgetState: function (evt, showOpinions) {
    if (evt) { 
      evt.preventDefault(); 
      showOpinions = evt.target.href.indexOf('opinions') >= 0;
    }
    if (showOpinions) { // show the 'report'
      $('#tags_section, #ratings_and_comments_section, #view_opinions').hide();
      $('#report_section, #view_forms').show();
    } else { // show the forms
      QC.resetWidgetForm();
      $('#tags_section, #ratings_and_comments_section, #view_opinions').show();
      $('#report_section, #view_forms').hide();
    }
  },
  
  resetWidgetForm: function () {
    $("#tag_cloud a").removeClass('selected');
    $('#rating_legend, #rating_header, #ratings').hide();
    $('#comment').val(QC.defaultCommentText);
    $('#rating_instructions').show();
    $('#ratings').html('');
  },
  
  showTagDetailReport: function (evt) {
    QC.popup = window.open(evt.target.href, "quickcomments", "height=300, width=300, menubar=0, location=0, toolbar=0, status=0");
    return false;
  }
};

$(QC.init);