//Created by Sean Kane (http://celtickane.com/labs/feather-ajax/)
//Feather Ajax v1.0.2

// function AjaxObject101() {
function FeatherAjax() {
	this.createRequestObject = function() {
		try {
			var ro = new XMLHttpRequest();
		}
		catch (e) {
			var ro = new ActiveXObject("Microsoft.XMLHTTP");
		}
		return ro;
	}
	this.sndReq = function(action, url, data) {
		if (action.toUpperCase() == "POST") {
			this.http.open(action,url,true);
			this.http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			try {this.http.onreadystatechange = this.handleResponse;}
			catch(ex) {
				this.http.onload = this.handleResponse;
			}
			this.http.send(data);
		}
		else {
			this.http.open(action,url + '?' + data,true);
			try {this.http.onreadystatechange = this.handleResponse;}
			catch(ex) {
				this.http.onload = this.handleResponse;
			}
			this.http.send(null);
		}
	}
	this.handleResponse = function() {
		if ( me.http.readyState == 4) {
			if (typeof me.funcDone == 'function') { me.funcDone();}
		}
		if ((me.http.readyState == 1) && (typeof me.funcWait == 'function')) { me.funcWait(); }
	}
	var me = this;
	this.http = this.createRequestObject();
	
	var funcWait = null;
	var funcDone = null;
}

function loading() {
  document.getElementById('ajax_indicator').style.visibility = 'visible';
}

function loaded() {
  document.getElementById('ajax_indicator').style.visibility = 'hidden';
}

function do_ajax(path) {
  var ao = new FeatherAjax();
  // ao.funcWait = loading;
  // ao.funcDone = loaded;
  ao.sndReq('post', path);
}

function log_content_view(item_id) {
  var ao = new FeatherAjax();
  var url = '/content/log_view/' + item_id;
  ao.sndReq('post', url);
}

function search_got_focus() {
  var ele = document.getElementById('search_text');
  ele.value = '';
  ele.className = 'with_focus';
  return true;
}

function submit_comment(form) {
  var values = $(form).serialize();
  console.log(values);
  $(form).stopPropagation();
  return false;
}

$(function($) {
  Comment.install_handlers();
});

var Application = {
  
  lightboxify : function() {
    $("a[rel^='lightbox']").slimbox({/* Put custom options here */}, null, function(el) {
  		return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
  	});
  }
};

var Comment = {
  
  install_handlers : function() {
    $('form#new_comment_form').submit(function() { return false; });
    $(".submit_comment_button").click( Comment.submit );
    if (Application.logged_in) {
      // Prevent duplicate binding
      $(".arrows .up").unbind('click', Comment.upvote );
      $(".arrows .up").click( Comment.upvote );
      $(".arrows .down").unbind('click', Comment.downvote );
      $(".arrows .down").click( Comment.downvote );
      $(".arrows .upvoted").unbind('click', Comment.destroy_vote );
      $(".arrows .upvoted").click( Comment.destroy_vote );
      $(".arrows .downvoted").unbind('click', Comment.destroy_vote );
      $(".arrows .downvoted").click( Comment.destroy_vote );
    } else {
      $(".arrows .up").click( Comment.login_to_rate );
      $(".arrows .down").click( Comment.login_to_rate );
    }
    return true;
  },

  show_reply : function(comment_id) {
    // Disable previous active replies
    $('.active_reply').html('').hide();
    var reply_html = $('#reply_to').html();
    $('#c_' + comment_id).append(reply_html);
    $('.cancel_link').click( Comment.hide_reply );
    $('#c_' + comment_id + ' div.reply_form_container input.parent_id').val(comment_id);
    $('#c_' + comment_id + ' div.reply_form_container').addClass('active_reply');
    $('#c_' + comment_id + ' textarea:first').focus();
    Comment.install_handlers();
  },
  
  hide_reply : function(event) {
    $(event.target).parents('.reply_form_container:first').html('').hide();
    // $( container ).each(function () {
    //    $(this).html('').hide();
    // });
  },
  
  submit : function(event) {
    var form = $(event.target).parents('form');
    var data = $(form).serialize();
    $('input[type=submit]', form).attr('disabled', 'disabled');
    $.ajax( { url : '/comments/create', data : data, type : 'POST', dataType : 'json',
          success : Comment.handle_submit_response, error : Comment.handle_submit_response } );
    return false;
  },
  
  handle_submit_response : function( data, status ) {
    // TODO: get error handling working properly
    if( 'success' == status ) {
      var parent_id = data.parent_id;
      var comment = data.comment;
      if (parent_id == 0) {
        $('#new_comment_form').after(comment);
      } else {
        $('#c_' + parent_id).after(comment);
      };
      $('textarea.comment_area').val('');
      $('#c_' + data.parent_id + ' div.reply_form_container').html('').hide();
    } else {
      $('.new_comment_form_container').after('<div class="notice_text comment_notice">' + data.responseText + '</div>');
    }
    $('input[type=submit].submit_comment_button').removeAttr('disabled');
  },
  
  rate : function(comment_id, is_upvote) {
    var rating = is_upvote ? '1' : '-1';
    var data = {'rating': rating, 'comment_id': comment_id};
    $.ajax( { url : '/comment_ratings/create', data : data, type : 'POST' });
  },

  upvote : function() {
    if ($(this).hasClass('upvoted')) { return false; }
    var comment_id = $(this).attr('comment_id');
    Comment.rate(comment_id, true);

    var inc = 1;
    // If we're going from Downvote => Upvote, we need to increase the point count by 2
    if ($('#c_' + comment_id + ' .downvoted').hasClass('downvoted')) { inc = 2; }
    $('#c_' + comment_id + ' .downvoted').removeClass('downvoted');
    $(this).addClass('upvoted');

    Comment.set_points(comment_id, inc);

    // Clear the bindings & Re-bind:
    //   Down => Downvote
    //   this => Destroy Vote
    $('#c_' + comment_id + ' .arrow').unbind('click', Comment.destroy_vote);
    $(this).click( Comment.destroy_vote );
    $('#c_' + comment_id + ' .down').unbind('click', Comment.downvote);
    $('#c_' + comment_id + ' .down').click( Comment.downvote );
  },
  
  downvote : function() {
    if ($(this).hasClass('downvoted')) { return false; }
    var comment_id = $(this).attr('comment_id');
    Comment.rate(comment_id, false);

    var dec = -1;
    // If we're going from Upvote => Downvote, we need to drop the point count by 2
    if ($('#c_' + comment_id + ' .upvoted').hasClass('upvoted')) { dec = -2; }

    $('#c_' + comment_id + ' .upvoted').removeClass('upvoted');
    $(this).addClass('downvoted');
    
    Comment.set_points(comment_id, dec);
    
    // Clear the bindings & Re-bind:
    //   Up => Upvote
    //   this => Destroy Vote
    $('#c_' + comment_id + ' .arrow').unbind('click', Comment.destroy_vote);
    $(this).click( Comment.destroy_vote );
    $('#c_' + comment_id + ' .up').unbind('click', Comment.upvote);
    $('#c_' + comment_id + ' .up').click( Comment.upvote );
  },
  
  // inc: increment/decrement (-1 or 1)
  set_points : function(comment_id, inc ) {
    var points = parseInt($('#c_' + comment_id + ' input.c_points').val()) + inc;
    var plural = Comment.pluralized(points);
    $('#c_' + comment_id + ' span.points').html(plural);
    $('#c_' + comment_id + ' input.c_points').val(points); // Set the points back in the hidden input
  },
  
  pluralized : function(num_points) {
    var str = ( Math.abs(num_points) == 1) ? 'point' : 'points';
    return num_points.toString(10) + ' ' + str;
  },
  
  login_to_rate : function() {
    var html = '<div class="notice_text login_to_rate">Please <a href="/login">Login</a> or <a href="/signup">Signup</a> to rate comments.</div>';
    $(this).parents('.c:first').after(html);
  },
  
  destroy_vote : function() {
    var comment_id = $(this).attr('comment_id');
    $.ajax( { url : '/comment_ratings/destroy', data : {'comment_id': comment_id}, type : 'POST' });
    if ( $(this).hasClass('up')) {
      Comment.set_points(comment_id, -1);
    } else {
      Comment.set_points(comment_id, 1);
    }
    $('#c_' + comment_id + ' .upvoted').removeClass('upvoted');
    $('#c_' + comment_id + ' .up').unbind('click', Comment.destroy_vote);
    $('#c_' + comment_id + ' .downvoted').removeClass('downvoted');
    $('#c_' + comment_id + ' .down').unbind('click', Comment.destroy_vote);
  }

};
