// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

jQuery.noConflict();

var processing = new Array();

/* Helper function for use when showing similar documents */
generateHTML = function(data){
  html = "";
  html += "<div id='similar_documents" + "' class='similar_documents' style='display:none'>"

  html += "<a href='#' class='similar_documents_close_button'><img src='/images/cross.png'></a>"
  html += "The following articles are similar:"
  html += "<br>"
  html += "<br>"

  jQuery(data).each(function(n){
    s = data[n];
    html += "<div class='doc-box' id='similar_documents_" + s.topic_id + '_' + s.id + "'>"
    html += "<div class='voting'>"
    html += "<a href='/topics/" + s.topic_id + "/documents/" + s.id + "/toggle' class='up' id='sd_keep_" + topic_id + "_" + s.id + "'></a>"
    html += "<a href='/topics/" + s.topic_id + "/documents/" + s.id + "/toggle' class='down' id='sd_discard_" + topic_id + "_" + s.id + "'></a>"
    html += "</div>"
    html += "<div class='text-box'>"
    html += "  <a href='" + s.uri +"' title='" + s.title + "'>" + s.title + "</a>"
    html += "  <span class='letter'>" + s.date + "</span>"
    html += "  <p>"
    html += s.summary
    html += "  <span class='link-h'>(" + s.host + ")</span>"
    html += "  </p>"
    html += "</div>"
    html += "</div>"

  });
  html += "</div>"
  return html;
}

jQuery.fn.replaceClass = function(oldClass, newClass) {
  this.removeClass(oldClass);
  this.addClass(newClass);
}

jQuery(function(){

  jQuery('#query').smartFocus();

  //jQuery("div.overflow").textOverflow(true);
  //  jQuery("a.overflow").live('click'), function(event){
  //    puts("Shite");
  //  }

  jQuery('.focus').focus();

  jQuery.bt.options.closeWhenOthersOpen = true;

  jQuery('.refresh').live('click', function(event){
    event.preventDefault();
    location.reload(true);
  });

  jQuery('.help').bt({
    fill: '#F7F7F7', strokeStyle: '#B7B7B7', spikeLength: 20,
    spikeGirth: 10, padding: 8, cornerRadius: 5,trigger: 'click', positions: 'right',
    shadow: true, shadowOffsetX: 3, shadowOffsetY: 3, shadowBlur: 8, shadowColor: 'rgba(0,0,0,.9)',
    shadowOverlap: false, noShadowOpts: {strokeStyle: '#999', strokeWidth: 2},
    cssStyles: {
      fontFamily: '"lucida grande",tahoma,verdana,arial,sans-serif',
      fontSize: '11px'}
  });

  // Guard everything in this block.
  jQuery("div[id^=topic_stats]").each(function(){
      topic_id = this.id.replace(/topic_stats_/, '');
      jQuery.get('/topics/' + topic_id + '/topic_stats', {}, updateStats, 'json');
  })

  // Guard everything in this block.
  jQuery("div[id^=documents]").each(function(){

    page_number = jQuery('div.page_number').attr('id');

    jQuery("a[id^=keep],a[id^=sd_keep]").live('click', function(event){
      event.preventDefault();

      ids = this.id.replace(/(sd_)?keep_/, '').split("_");
      topic_id = ids[0];
      id =  ids[1];

      similar_documents = (voting_frame() == false && this.id.search(/^sd_keep/) != -1) ? true : false;

      jQuery(this).attr("disabled", "disabled");

      if(jQuery(this).hasClass('upactive')){
        if(similar_documents){
          callback = function(data){
            jQuery("a#keep_" + topic_id + "_" + id).replaceClass('upactive', 'up');
            jQuery("a#sd_keep_" + topic_id + "_" + id).replaceClass('upactive', 'up');
            window.processing[id] = false;
            updateStats(data.stats);
          }
        }
        else{
          callback = function(data){
            jQuery("a#keep_" + topic_id + "_" + id).replaceClass('upactive', 'up');
            jQuery("a#sd_keep_" + topic_id + "_" + id).replaceClass('upactive', 'up');
            jQuery("div#similar_documents").slideUp('normal', function(){ jQuery(this).remove()});
            window.processing[id] = false;
            updateStats(data.stats);
          }
        }
        jQuery.post(this.href, { category: 'undefined', sd: !similar_documents, id: this.id, authenticity_token: window.AUTH_TOKEN }, callback, 'json');
      }
      else{
        if(similar_documents){
          callback = function(data){
            jQuery('a#discard_' + topic_id + "_" + id).replaceClass('downactive', 'down');
            jQuery('a#sd_discard_' + topic_id + "_" + id).replaceClass('downactive', 'down');
            jQuery("a#keep_" + topic_id + "_" + id).replaceClass('up', 'upactive');
            jQuery('a#sd_keep_' + topic_id + "_" + id).replaceClass('up', 'upactive');
            window.processing[id] = false;
            updateStats(data.stats);
          }
        }
        else{
          jQuery('div[id^=similar_documents]').slideUp('normal', function(){ jQuery(this).remove()});
          callback = function(data){
            similar_documents = data.similar_documents;
            jQuery('#discard_' + topic_id + "_" + id).replaceClass('downactive', 'down');
            jQuery('#sd_discard_' + topic_id + "_" + id).replaceClass('downactive', 'down');
            jQuery('#keep_' + topic_id + "_" + id).replaceClass('up', 'upactive');
            if(similar_documents.length > 0){
              jQuery('#content_' + topic_id + "_" + id).append(generateHTML(similar_documents));
              jQuery('#similar_documents').slideDown('normal');
            }
            window.processing[id] = false;
            updateStats(data.stats);
          }
        }
        jQuery.post(this.href, { category: 'keep', sd: !similar_documents, id: this.id, authenticity_token: window.AUTH_TOKEN }, callback, 'json');
      }

      return false;
    });

    /* Downvote button */
    jQuery("a[id^=discard],a[id^=sd_discard]").live('click', function(event){
      event.preventDefault();

      ids = this.id.replace(/(sd_)?discard_/, '').split("_");
      topic_id = ids[0];
      id = ids[1];

      similar_documents = (voting_frame() == false && this.id.search(/^sd_discard/) != -1) ? true : false;

      if(voting_frame()){
          active = jQuery(this).hasClass('downactive');
          if(active){
            callback = function(data){
              jQuery("a#discard_" + topic_id + '_' + id).replaceClass('downactive', 'down');
              jQuery("a#keep_" + topic_id + '_' + id).replaceClass('upactive', 'up');
            }
            jQuery.post(this.href, { category: 'undefined', sd: false, id: this.id, authenticity_token: window.AUTH_TOKEN }, callback);
          }
          else{
            callback = function(data){
              jQuery('a#discard_' + topic_id + '_' + id).replaceClass('down', 'downactive');
              jQuery('a#keep_' + topic_id + '_' + id).replaceClass('upactive', 'up');
            }
            jQuery.post(this.href, { category: 'discard', sd: false, id: this.id, authenticity_token: window.AUTH_TOKEN }, callback);
          }
        } else {
          callback = function(data){
            updateStats(data.stats);
            if(similar_documents){
              /* Remove the document if the downbutton is clicked */
              jQuery('div#similar_documents_' + topic_id + "_" + id).slideUp('normal', function(){ jQuery(this).remove()});

              if(jQuery('div#similar_documents>div.doc-box').size() == 1){
                jQuery('div#similar_documents').slideUp('normal', function(){ jQuery(this).remove()});
              }
            } else {
              jQuery('div#document_' + topic_id + "_" + id).slideUp('normal', function(){ jQuery(this).remove()});
              jQuery.get('/topics/' + topic_id + '/next_document?page=' + page_number, {}, function(data){jQuery("div[id^=documents]").append(data)});
            }
          }
          jQuery.post(this.href, { category: 'discard', sd: false, id: this.id, authenticity_token: window.AUTH_TOKEN }, callback, 'json');
        }
    });

    // Close the similar documents div
    jQuery("a.similar_documents_close_button").live('click', function(event){
      jQuery(this).parent().slideUp('normal', function(){ jQuery(this).remove()});
      return false;
    });

    // Black list the document's domain
    jQuery("a.black-list-domain").live('click', function(event){
      event.preventDefault();
      callback = function(data){
        jQuery('.domain').each(function(){
          domain = jQuery(this);
          if(domain.html() == data.domain){
            domain.toggleClass('black-listed');
          }
        });
      };
      jQuery.post(this.href, {}, callback, 'json');
    });
  });
});

function puts(message){
  jQuery('#console').append('<div>' + message + '</div>');
}

function updateStat(element, value){
  jQuery(element).html("(" + value + ")");
}

function voting_frame() {
  return (jQuery("#voting_frame").size() == 1) ? true : false;
}

function updateStats(data){
  updateStat("span#topic-stats-new", data._new);
  updateStat("span#topic-stats-kept", data.kept);
  updateStat("span#topic-stats-discarded", data.discarded);
  updateStat("span#topic-stats-total", data.total);
}
