// Configuration parameters

var crVoteURL = 'http://commentisfree.guardian.co.uk/mt/rate.pl';
var crRecommendedThreshold = 3;

function add_script(url, params) {
  var e = document.createElement("script");
  var now = (new Date()).getTime();
  
  params = $H(params);
  params.set('nocache', now);
  // obvious FIXME: this doesn't escape
  var query = params.keys().map(function(k) { return k + '=' + params.get(k) }).join('&');
  e.setAttribute("type", "text/javascript");
  e.setAttribute("src", url + '?' + query);
  e.setAttribute("id", 'id-' + now);
  
  document.getElementsByTagName("head").item(0).appendChild(e);
};

var crCommentSelector = 'div[class=individualcomment]';
var crCommentHeadSelector = 'div[id=individualcommentheader]'

// Add in a commentID method...

Element.extend({ commentid: function () {
      //<a name="comment-717588">
      var abox = this.getElement('a[name^=comment-]');
      if(abox) {
	var propID = abox.getProperty( 'name' );
	propID = propID.replace(/comment\-/,'');
	return propID;
      } else {
	return 0;
      }
    }});

function crBuildVoteBox ( commentid ) {
  var voteBox = new Element( 'div', { 'class': 'crVoteBox', 'id': 'cr-commentvotebox-' + commentid } );
  voteBox.setHTML('<a href="javascript:crRegisterVote(\'' + commentid + '\')">Recommend?</a>');
  return voteBox;
}

function crRegisterVote ( commentid ) {
  // Update the state of the vote box
  var voteBox = $( 'cr-commentvotebox-' + commentid );
  voteBox.setHTML("Please wait...");
//   var voteCall = new Ajax( crVoteURL, {
//       'method': 'post',
// 	'data': { 'e': '21501', 'c': commentid },
// 	'onSuccess': crVoteResponse.bind( commentid )
// 	  }).request();
  // FIXME: remove hardwired constant
  add_script(crVoteURL, { 'e': entryid, 'c': commentid, 'f': 'crVoteResponse' });
}

function crVoteResponse (_, commentid, response) {
  var voteBox = $( 'cr-commentvotebox-' + commentid );
  if(response == "ok") {
    voteBox.setHTML('Recommendation received');
  } else if(response == 'login') {
    voteBox.setHTML('Please log in to make a recommendation');
  } else {
    voteBox.setHTML('Sorry, there was a fault. Please try again later.');
  }
  voteBox.setStyle('background', '#fff');
}

var crRecommendedView = 1; // We call a toggle first, so start this as one

function crToggleRecommendedView () {
var recommendedheader = $('recommendedheader');
  if ( crRecommendedView == 0 ) {   // Turn it on if it was off
    // Switch the flag
    crRecommendedView = 1;
    // Update the tab box
    crTabToggle( $('cr-tabbox-off'), 0 );
    crTabToggle( $('cr-tabbox-on' ), 1 );
    // Do the comment hiding
    $$( crCommentSelector ).each( function (comment) {
	if(comment == recommendedheader) {
	  recommendedheader.setStyle('background', '#fff');
	  recommendedheader.setStyle('display', 'block');
	} else {
	  var commentscore = crCommentScores[ comment.commentid() ];
	  if (! commentscore ) { commentscore = 0 }
	  if ( commentscore < crRecommendedThreshold ) {
	    comment.setStyle('background', '#ffe');
	    //(function(){comment.setStyle('display', 'none')}).delay(250);
	    comment.setStyle('display', 'none');
	  } else {
	    comment.setStyle('background', '#ffe');
	    //(function(){comment.setStyle('background', '#fff')}).delay(250);	
	    comment.setStyle('background', '#fff');
	  }
	}
      });
  } else {  // Turn it off it was on
    // Switch the flag
    crRecommendedView = 0;
    // Update the tab box
    crTabToggle( $('cr-tabbox-off'), 1 );
    crTabToggle( $('cr-tabbox-on' ), 0 );
    // Do the comment showing
    $$( crCommentSelector ).each( function (comment) {
	if(comment == recommendedheader) {
	  recommendedheader.setStyle('display', 'none');
	} else {
	  comment.setStyle('display','block');
	  comment.setStyle('background','#fff');
	}
      });
  }
}

function crAddVoteBox () {
var recommendedheader = $('recommendedheader');
  // Iterate through every comment
  $$( crCommentSelector ).each( function (comment) {
      if(comment == recommendedheader) {
	// don't do anything with it!
      } else {
	comment.adopt( crBuildVoteBox( comment.commentid() ) );
      }
    });
}

function crTabToggle ( tab, selectFlag ) {
  if (selectFlag) {
    tab.setStyle('background', '#fff');
    tab.setStyle('border-bottom-color', '#fff');
    tab.setStyle('font-weight', 'bold' );
  } else {
    tab.setStyle('background', '#eee');
    tab.setStyle('border-bottom-color', '#ccc');
    tab.setStyle('font-weight', 'normal' );
  }
}

function crAddTabs () {
  // Lets get a recommended comment count...
  var recommendedCount = 0;
  var allCount = 0;

  $each( crCommentScores, function( score, commentid ) {
      if ( score > crRecommendedThreshold ) {
	recommendedCount += 1;
      }
    });
  
  $$( crCommentSelector ).each( function () { allCount += 1; } );

  allCount -= 1; // because the header counts for one

	
  // Create tabs...
  var tabs = new Element( 'div', { 'id': 'cr-tabbox', 'class': 'cr-tabhead' } );
	
  var tabLeft = new Element( 'div', { 'id': 'cr-tabbox-off', 'class': 'cr-tab' } );
  tabLeft.setHTML('<a href="javascript:crToggleRecommendedView()">All Comments ('+ allCount +')</a>');

  var tabRight = new Element( 'div', { 'id': 'cr-tabbox-on', 'class': 'cr-tab' } );
  tabRight.setHTML('<a href="javascript:crToggleRecommendedView()">Most Recommended Comments (' + recommendedCount + ') </a>');

  tabs.adopt( tabLeft  );
  tabs.adopt( tabRight );

  tabs.injectBefore( $('commenthead') );
}

(function() {
  crAddVoteBox();
  crAddTabs();
  crToggleRecommendedView();
}).delay(1500);

