//Javascript library for NUSA Tipline module
//Stephan Arrington - Late 2008
//Based loosly on code from Shoutbox by );disterics

if (typeof(Drupal) == "undefined" || !Drupal.nusatipline) {    
    Drupal.nusatipline = {};
 }


//Global, evil, nothing to see here please move along, this is not the code you are looking for..
var key = '';
var time = '';
var submitform = '';
var canMod = 'false';
var lineid = '';

Drupal.nusatipline.offset = 1;

//Decorate posts by type, classes only applied for moderators 
Drupal.nusatipline.decorateTiplineItems = function () {
	//unbind listeners to prevent duplicate
	$(".items").unbind('click');

	//bind listener
	$(".items").bind('click', function(e) {
		e.stopPropagation();
		var target = e.target; 
		
  	if ($(target).is(".tip_report")) {
			var p = $(target).parents("div[@id^='id_']");
			var id = p.attr("id");
			var tid = id.split("_");
			$.post("/content/tipline/js/report/" + tid[1] + "/");
			p.addClass("reported");
			return false;
		}
		//reply
		else if ($(target).parent().is(".replyTip")) {
			Drupal.nusatipline.tipReply(target);
			return false;
		}
		//show more
		else if ($(target).parents().is(".expand_link") && $(target).parents().is(".tiplineToggle")) {
			$(target).parents("div[@id^='id_']").removeClass("contentClosed").addClass("contentOpen");
			return false;
		}
		//show less
		else if ($(target).parents().is(".contract_link")) {
			if(e.shiftKey) { 
				var textSpan = $(target).parents(".edit-tips");
				if($(textSpan).is(".edit-tips")) {
					$(textSpan).parent().removeClass("tiplineToggle");
					$(textSpan).parent().children(".showLess").remove();
					var id = $(textSpan).parents("div[@id^='id_']").attr("id");
					var tid = id.split("_"); tid = tid[1];
					var revert = $(textSpan).html();

					var textarea = '<div class="eip"><textarea class="resizable eip_' + tid + '" rows="4">' + revert + "</textarea>";
					var button = '<div><input type="button" value="Save Changes" class="saveButton" /> <input type="button" value="Cancel" class="cancelButton" /></div></div>';

					$(textSpan).after(textarea+button).remove();
	        Drupal.textareaAttach();
          $(".grippie").removeAttr("style");
	
			    $('.saveButton').click( function(e) {
               //var tip = $(this).parent().siblings(0).val();
               var tip = $(this).parent().parent().find('textarea').val();
               var par = $(this).parent().parent();
						   $.post("/content/tipline/js/edit/" + tid , {'tip': tip }, 
                  function(data) {
						        $(par).after("<span class='commentEntryFullText edit-tips'>" +data+ "</span>").remove();
                  }
               );
					});
          $('.cancelButton').click( function() {
						  var tip = revert;
						  $(this).parent().parent().after("<span class='commentEntryFullText edit-tips'>" + tip + "</span>").remove();
          });	
			  }
			} else {
				if ($(target).parents().is(".tiplineToggle")) {
					$(target).parents("div[@id^='id_']").removeClass("contentOpen").addClass("contentClosed");
					return false;
				}
			}
        return false;
		}
		//approve 
		else if ($(target).parent().is(".approveTip")) {
			var p = $(target).parents("div[@id^='id_']");
			var id = p.attr("id");
			var tid = id.split("_");
			$.post("/content/tipline/js/moderate/" + tid[1] + "/Approved/");
			p.removeClass("rejected").removeClass("unmoderated").removeClass("questionable").addClass("approved");
			return false;
		}
		//reject/deny
		else if ($(target).parent().is(".rejectTip")) {
			var p = $(target).parents("div[@id^='id_']");
			var id = p.attr("id");
			var tid = id.split("_");
			$.post("/content/tipline/js/moderate/" + tid[1] + "/Denied/");
			p.removeClass("approved").removeClass("unmoderated").removeClass("questionable").addClass("rejected");
			return false;
		}
		//question/inappropriate
		else if ($(target).parent().is(".questionTip")) {
			var p = $(target).parents("div[@id^='id_']");
			var id = p.attr("id");
			var tid = id.split("_");
			$.post("/content/tipline/js/moderate/" + tid[1] + "/Flagged/");
			p.removeClass("rejected").removeClass("unmoderated").removeClass("approved").addClass("questionable");
			return false;
		}
		//promote
		else if ($(target).is(".promoteTip")) {
			var p = $(target).parents("div[@id^='id_']");
			var id = p.attr("id");
			var tid = id.split("_");
			$.post("/content/tipline/js/promote/" + tid[1]);
			p.removeClass("notPromoted").addClass("promoted");
			return false;
		}
		//remove promotion
		else if ($(target).is(".demoteTip")) {
			var p = $(target).parents("div[@id^='id_']");
			var id = p.attr("id");
			var tid = id.split("_");
			$.post("/content/tipline/js/promote/" + tid[1]);
			p.removeClass("promoted").addClass("notPromoted");
			return false;
		}
		//promoteuser
		else if ($(target).is(".promoteUserIcon")) {
			var p = $(target).parents("div[@id^='id_']");
			var uid = $(target).parents(".tipAuthorWrapper").attr('uid');
			$.post("/content/tipline/js/rolemanager/" + uid + "/promote/");
			p.removeClass("isDefaultUser").removeClass("isDemotedUser").addClass("isPromotedUser");
			return false;
		}
		//demote user
		else if ($(target).is(".demoteUserIcon")) {
			var p = $(target).parents("div[@id^='id_']");
			var uid = $(target).parents(".tipAuthorWrapper").attr('uid');
			$.post("/content/tipline/js/rolemanager/" + uid + "/demote/");
			p.removeClass("isPromotedUser").removeClass("isDefaultUser").addClass("isDemotedUser");
			return false;
		}
		//promote mod
		else if ($(target).is(".promoteModIcon")) {
			var p = $(target).parents("div[@id^='id_']");
			var uid = $(target).parents(".tipAuthorWrapper").attr('uid');
			$.post("/content/tipline/js/rolemanager/" + uid + "/makemod/");
			p.removeClass("isPromotedUser").removeClass("isDefaultUser").addClass("isModerator");
			return false;
		}
		//demote mod
		else if ($(target).is(".demoteModIcon")) {
			var p = $(target).parents("div[@id^='id_']");
			var uid = $(target).parents(".tipAuthorWrapper").attr('uid');
			$.post("/content/tipline/js/rolemanager/" + uid + "/takemod/");
			p.removeClass("isModerator").addClass("isPromotedUser");
			return false;
		}
		else {
		}
		
	});

	//Display the identifier on combined tiplines
	if ( $("div#whydothis").length > 0 ) {
		$(".tipline_identifier").show();
	}
	


}

/*
	if ( $("div.audit_log").length > 0 ) {
		$(".show_audit").show();//.css("display", "inline");
		$(".show_useraudit").show();
		$(".tipline_identifier").show();
	}		

	$(".show_audit").click(function () {
	//	$(this).fadeOut("slow");
		$.get("/content/tipline/js/audit/" + $(this).attr('id') + "/", function(data) {
			$("div.audit_log").html(data);	
			if(data == '') {
				$("div.audit_log").html("No audit log established.");
			}
		});
	//	$(this).fadeIn("slow");
	});

	$(".show_useraudit").click(function () {
	//	$(this).fadeOut("slow");
		$.get("/content/tipline/js/useraudit/" + $(this).attr('id') + "/", function(data) {
			$("div.audit_log").html(data);	
			if(data == '') {
				$("div.audit_log").html("No audit log established.");
			}
		});
	//	$(this).fadeIn("slow");
	});
}
*/

//Attaching forms: attach the jquery/ajax code to each tipline form
Drupal.nusatipline.attachTiplineAddForms = function () {
	
	//Find and loop through each tipline form
	$("form[@name=tipline_add]").each( function() {
		key = $(this.key).val();
		$(this).parents("div#comments").children("div#items").addClass("tiplineitems-" + key);
		$(this).parents("div#tipline").children("div#items").addClass("tiplineitems-" + key);
		$(this).siblings(".counterdisplay").removeClass("counterdisplay").addClass("counterdisplay-" + key);
		$(this.tip).dodosTextCounter(Drupal.settings.nusatipline.charLimit[0], {counterDisplayClass: "counterdisplay-" + key, addLineBreak:false});
		var options = {
        		url: '/content/tipline/js/add',
		        resetForm: true,
	        	beforeSubmit: Drupal.nusatipline.validate,
	        	success: Drupal.nusatipline.success
		};
		$(this).ajaxForm(options);	
	});
}

Drupal.nusatipline.tipReply = function(replyObj) {
		$(replyObj).hide();
		p = $(replyObj).parents("div[@id^='id_']");		
		var id = p.attr("id");
		var tid = id.split("_");
		id = tid[1];

		var currentDepth = $(p).attr('depth');
		if (currentDepth == '')
			currentDepth = 0;

		$.get("/content/tipline/js/getreplyform/", function(data) {

			var form = $(data);
			form.addClass("replyForm_" + id);
			
			p.children(".commentEntryWrapper").after(form);	
			
			$(form).find("#edit-parent").val(id);
			$(form).find("#edit-depth").val(currentDepth -1);
			
			$("span.counterdisplay-").addClass("counterdisplay-" + id).removeClass("counterdisplay-");
			$(form).find("#edit-tip").dodosTextCounter(Drupal.settings.nusatipline.charLimit[0], {counterDisplayClass: "counterdisplay-" + id, addLineBreak:false});
			
			var options = {
				url: '/content/tipline/js/reply',
				resetForm: true,
				beforeSubmit: Drupal.nusatipline.replyValidate,
				success: Drupal.nusatipline.replySuccess
			};
			
			$(form).ajaxForm(options);
			
			$('.replyCancel').click( function() {
				$(".replyForm_" + id).empty();
					$(replyObj).show();
			});
		});

};

//Auto-refresh timer
Drupal.nusatipline.startTimer = function(delay) {
	Drupal.nusatipline.updateTime();
	Drupal.nusatipline.interval = setInterval("Drupal.nusatipline.refreshTips()", delay);
};

//Refresh tiplines
Drupal.nusatipline.refreshTips = function() {
	$("form[@name=tipline_add]").each( function() {
		var refreshKey = $(this.key).val();
		$.get("/content/tipline/js/view/" + refreshKey + "/" + time + "/newer/", function(data) {
			$(".tiplineitems-" + refreshKey).prepend(data);
			if(data != '') {
				Drupal.nusatipline.decorateTiplineItems();
			}
		});
	});	

	//update time
	Drupal.nusatipline.updateTime();
};

//Update timestamp from the tipline
Drupal.nusatipline.updateTime = function() {
	var currentTime = new Date();
	time = Math.round(currentTime.getTime() / 1000);
};

Drupal.nusatipline.replySuccess = function (responseText) {
     	$(".replyForm_" + lineid).empty();
	$("#id_" + lineid + "_tip").after(responseText);
      	Drupal.nusatipline.updateTime();
        Drupal.nusatipline.decorateTiplineItems();
};

Drupal.nusatipline.replyValidate = function (formData, jqForm, options) {

        //retrieve the form
        var form = jqForm[0];
        submitform = form;
        form.op.disabled = true;
        form.op.value = "Validating";
        //function to utilize
	lineid = form.parent.value;

        //If tip is empty, reject
        if(form.tip.value == '') {
                alert("You must provide text for a tip.");
                submitform.op.disabled = false;
                submitform.op.value = 'submit';
                return false;
        }
        else
                return true;
};

//Setup bindings for tipline
Drupal.nusatipline.setupEventHandler = function(responseText) {

		$("#comments").unbind("click");
		$("#comments").bind("click", function(e){
			
			e.stopPropagation();
			var target = e.target;
			
			if ($(target).is(".showMoreTips") || $(target).is(".showMoreMore") ) {
				
				$("#comments div.moreBar").css("visibility","hidden");
				$.get("/content/tipline/js/view/" + key + "/all/paginated/all/"+Drupal.nusatipline.offset+"/", function(data) {
					$(".tiplineitems-" + key).append(data);
					
					if (data != '') {
						Drupal.nusatipline.decorateTiplineItems();
						$("#comments div.moreBar").css("visibility","visible");
						Drupal.nusatipline.offset++;
					}
				});
				
				return false;
			}	
		});
};

//Success: Post-submit, handle push the response to an approprate location
Drupal.nusatipline.success = function (responseText) {
	if(key != '') {
		$(".tiplineitems-" + key).prepend(responseText);
		//$("div#items").prepend(responseText);
		submitform.op.disabled = false;
		submitform.op.value = 'submit';
	}
	//Warning: This may have unusal results, please use keys when at all possible	
	else {
		$("div#items").prepend(responseText);
	}

	//Decorate the new item
	Drupal.nusatipline.updateTime();
	Drupal.nusatipline.decorateTiplineItems();
};


//Validate: Pre-submit, client side form validation
Drupal.nusatipline.validate = function (formData, jqForm, options) {

	//retrieve the form
    	var form = jqForm[0];	
	submitform = form;
	form.op.disabled = true;
	form.op.value = "Validating";
	//retrieve the form key and store it in an evil global for the success
	//function to utilize
	key = form.key.value;
	
	//If tip is empty, reject
	if(form.tip.value == '') {
		alert("You must provide text for a tip.");
		submitform.op.disabled = false;
		submitform.op.value = 'submit';
		return false;
	}	
	else
		return true;	
};


if (Drupal.jsEnabled) {
    $(document).ready(function() {
			Drupal.nusatipline.attachTiplineAddForms();
			Drupal.nusatipline.decorateTiplineItems();
			Drupal.nusatipline.setupEventHandler();

			if(typeof Drupal.settings != 'undefined') {	
				if(typeof Drupal.settings.nusatipline != 'undefined') {
					if(typeof Drupal.settings.nusatipline.canMod != 'undefined') {
						if(Drupal.settings.nusatipline.canMod[0] == 'true') {
							canMod = 'true';
						}
					}
					if(typeof Drupal.settings.nusatipline.refreshDelay != 'undefined') {
						if(Drupal.settings.nusatipline.refreshDelay[0] > 0) {
							//seconds to milliseconds
							Drupal.nusatipline.startTimer(Drupal.settings.nusatipline.refreshDelay[0] * 1000);
						}
					}
				}
			}
		}
	);
};

