/*jslint browser: true */
/*global $ */

var dds = {
  
  isInHelpBubble: false,

  /**
   * hide vote and report buttons
   */
  checkVotes: function(e) {
	  var voteCookie = $.cookie("dds_vote");
    if (voteCookie!==null) {
      var votes = voteCookie.split("_");
    
      $.each(votes, function(){
        dds.disableVoteInput(this.toString(), {'animate': false});
      });
    }
    var abuseCookie = $.cookie("dds_abuse");
    if (abuseCookie!==null) {
      votes = abuseCookie.split("_");
    
      $.each(votes, function(){
        $("#vote_"+this.toString()+" .report").hide();
      });
    }
	},
	
	disableVoteInput: function(voteID, opts) {

	  $("#vote_"+voteID+" .vote input").each(function(){
	    var newSrc = $(this).attr('src');
      newSrc = newSrc.replace(".gif", "_disabled.gif");
      if (opts.animate) {
        $(this).css({opacity: 0.5}).attr({"disabled": true, "src": newSrc}).animate({opacity: 1}).css("cursor","default");
      }
      else {
        $(this).attr({"disabled": true, "src": newSrc}).css("cursor","default");
      }
	  });
	  
	  //Fade Vote text too
	  $("#vote_"+voteID+" strong").css({color: "#ccc"});
	},
	
	/**
	 * Create the event handler
	 */
	createNavEvents: function(){
		$("a.nav_button").click(dds.navHandler);
		$(".post form .vote input").click(dds.voteClickHandler);
		$(".post .report").click(dds.abuseClickHandler);
		dds.checkVotes();
	},
	
	
	
	voted: function(data, status)
	{
    if (data.error==='')
    {
	    var forVal = $("#vote_"+data.id+" .vote.for span");
	    forVal.html(data.up);
	  
	    var againstVal = $("#vote_"+data.id+" .vote.against span");
	    againstVal.html(data.down);
    }
    else
    {
      var resp = $("#response_msg");
      if (resp.length!=0)
      {
        resp.fadeOut(250,
          function(){
            $(this).remove();
            $("#vote_"+data.id).prev().append("<p id='response_msg'><strong>"+data.error+"</strong></p>");
          }
        );
      }
      else
      {
        $("#vote_"+data.id).prev().append("<p id='response_msg'><strong>"+data.error+"</strong></p>");
      }
    }
    dds.highlight("#post"+data.id);
	},
	
	reported: function(data, status)
	{
    var resp = $("#response_msg");
    if (resp.length!=0)
    {
      resp.fadeOut(250,
        function(){
          $(this).remove();
          $("#vote_"+data.id).prev().append("<p id='response_msg'><strong>"+data.error+"</strong></p>");
        }
      );
    }
    else
    {
      $("#vote_"+data.id).prev().append("<p id='response_msg'><strong>"+data.error+"</strong></p>");
    }
    
    dds.highlight("#post"+data.id);
	},
	
	voteClickHandler: function(e){
	  var post_id = $(e.target).parent().parent().parent().attr("id").replace(/([^0-9]+)/, '');

    // Disable button
    dds.disableVoteInput(post_id, {'animate': true});

	  // Call ajax and update value
    var name = $(this).attr("name");
    $.post('/vote',{
        vote: name,
        post_id: post_id
      },
      dds.voted,
      "json"
    );
	  return false;
	},
	
	/**
	 * Handles a click on the report abuse button
	 */
	abuseClickHandler: function(e){
    var post_id = $(e.target).parent().parent().parent().attr("id").replace(/([^0-9]+)/, '');

    $(this).fadeOut();
	  $.post('/report',{
        post_id: post_id
      },
      dds.reported,
      "json"  
    );
   
	 return false;
  },
	
	/**
	 * Handler for the navigation event
	 */
	navHandler: function(e) {
		$.get(this.href, {}, function(data){
			$("#latestPosts").html(data);
			dds.createNavEvents();
		});
		return false;
	},
	
	/**
	 * Sets up stuff when the document's ready
	 */
  init: function() {

    $('body').addClass('js');
    
    $('.inline_choice :checkbox').each(function(){
      dds.checkIt(this);
    });
    
    $('.inline_choice :checkbox').click(function(){
      dds.checkIt(this);
    });
    
    $('.inline_choice label').mouseover(function(){
      $(this).addClass('hover');
    });
    
    $('.inline_choice label').mouseout(function(){
      $(this).removeClass('hover');
    });
    
    $('#post_subject').maxlength({maxCharacters: 50, slider: true});
    $('#post_body').maxlength({maxCharacters: 200, slider: true});
    
    dds.email();
    
    if (document.location.hash) {
        dds.highlight(document.location.hash);
    }
    $('#main a[href*=#]').click(function(){            
        var elemId = '#' + $(this).attr('href').split('#')[1];
        dds.highlight(elemId);               
    });
    
    $("#helpLink").after('<div id="help"><div></div></div>');
    $("#help div").load('/help');
    $("#help").hide();
    
    $("#helpLink").click(function(){
      $("#help").slideToggle(500);
      return false;
    });

    //Create nav events
		dds.createNavEvents();
		    
  },
  
  hideHelp: function() {
    $("#help").slideUp(500);
    return false;
  },
  
  checkIt: function(o) {
    if (o.checked) {
      $(o).parent().find('label').addClass('selected');
    }
    else {
      $(o).parent().find('label').removeClass('selected');
    }
  },
  
  email: function() {
    var emailE = ('&#104;&#101;&#108;&#108;&#111;&#064;&#100;&#101;&#097;&#114;&#100;&#111;&#119;&#110;&#105;&#110;&#103;&#115;&#116;&#114;&#101;&#101;&#116;&#046;&#099;&#111;&#109;');
    var href = 'mailto:' + emailE + '?subject=DearDowningStreet';
    $('span.ddsEmail').replaceWith('<a href="'+href+'">' + emailE + '</a>');
  },
  
  highlight: function(elemId){
    var elem = $(elemId);
    elem.css("backgroundColor", "#ffffff"); // hack for Safari
    elem.animate({ backgroundColor: '#dddddd' }, 100);
    setTimeout(function(){
      $(elemId).animate({backgroundColor: "#ffffff"}, 1500);
    },1000);
  }
  
};

$(document).ready(dds.init);
