/*
 * 
	bm_comments
 */

;(function($){


$.fn.bm_comments = function($options) {

	// set default options
	var $defaults = {
		onLoad     : function() {}
	};
	
	// extend the options
	var $opts = $.extend($defaults, $options);
	
	// bring the options to the jquery object
	for (var i in $opts) {
		$.bm_comments[i]  = $opts[i];
	}
};

$.extend({bm_comments : {
	COMMENT_SAVE_URL : "php/comments/commentSave.php",
	COMMENTS_GET_URL : "php/comments/commentsGet.php",
	COMMENT_LIST : "#comment-list",
	COMMENT_ADD_BUTTON : "Add Comment",
	COMMENT_SUBMIT_BUTTON : "Submit Comment",
	COMMENT_MINIMUM_LENGTH : 3,
	COMMENT_TAB_MENU : ".comment-tab-menu",
	COMMENT_TAB_CONTAINER : "#comment-tab-container .comment-content",
	SUCCESS : 0,
	eventHandler :function()
	{
		try
		{
			var e = document.getElementById('comment-add-button');
			e.onmouseup = function() 
			{
				$.bm_comments.commentSave(0);
			}
			e = document.getElementById('your-comment');
			e.onfocus = function() {$.bm_comments.commentOnFocus();}
			//e.onblur = function() {commentsOnBlur();}
			

			$($.bm_comments.COMMENT_TAB_MENU+" a").mouseup(function(event){$.bm_comments.commentsTabOnMouseUp(this,event)});

			document.getElementById("comment-add-button").value = $.bm_comments.COMMENTS_SUBMIT_BUTTON; //initialize comments for database use.

			$("#comment-add-button").keypress(function(event) {$.bm_comments.keyPress(this,event)});
			
			//set default values. this deals with caching issue. belong in init function not eventHandler ...
			$("#your-comment").val("");

			$("#comment-list").bind('keyup', function(event) {$.bm_comments.keyUp(this,event);});
			
		} catch(err)
		{
			errorHandler("comments.eventHandler",err);
		}
	},
	keyUp : function(e,evt){
		//alert("id "+$(e).attr("id"));
		var iKey = getKeystroke(evt);
		var bShiftPressed = getShiftPressed(evt);
		var bAltPressed = getAltPressed(evt);
		var bCtrlPressed = getCtrlPressed(evt);
		alert("in key up");
		if (iKey==$.bm_ui.KEY_DOWN_ARROW)
		{
			var index = $($.bm_comments.COMMENT_LIST+" div.row").index($("div.row.active"));
			if(index<= $($.bm_comments.COMMENT_LIST+" div.row").size())
			{
					//alert("add one");
					index++;
			} else
			{ 
					//alert("one");
					index = 0;
			}
			$.bm_comments.commentListMouseover($($.bm_comments.COMMENT_LIST+" div.row").eq(index));
		}
		if (iKey==$.bm_ui.KEY_UP_ARROW){
			var index = $($.bm_comments.COMMENT_LIST+" div.row").index($("div.row.active"));
			if(index>0)
			{
					//alert("add one");
					index--;
			} else
			{ 
					//alert("one");
					index = $($.bm_comments.COMMENT_LIST+" div.row").size();
			}
			$.bm_comments.commentListMouseOver($($.bm_comments.COMMENT_LIST+" div.row").eq(index));
		}
	},
	commentOnFocus : function()
	{
		try
		{
			document.getElementById("your-comment").select();
			//$.bm_main.current_edit_mode = $.bm_main.EDITING_COMMENTS;
			//$("#blind3").css({backgroundColor: $.bm_ui.TEMPLATE_COLOR});
			//NB Non-generic Hardwired reference
			//$("#blind3").css({color:$.bm_ui.BOX_COLOR_DARK});
		} catch(err)
		{
			errorHandler("commentOnFocus",err);
		}
	},
	commentListMouseover : function(e)
	{
		//can be called by click, mouseover or keyboard events
		$.bm_comments.populateEditForm(e);
		$(e).siblings().removeClass("active");
		$(e).addClass("active");

	},
	populateEditForm : function(e){
		var sTempString = $(e).children("span.comment").text();
		//alert("tempstring "+sTempString);
		$("#comment-details-comment").attr("disabled","");
		$("#comment-details-comment").val(sTempString);
		$("#comment-details-comment").attr("disabled","disabled");
		sTempString = $(e).children("span.author").text();
		//alert("tempstring "+sTempString);
		$("#comment-details-author").attr("disabled","");
		$("#comment-details-author").val(sTempString);
		$("#comment-details-author").attr("disabled","disabled");
	},
	commentListClick : function(e){
		$.bm_comments.populateEditForm(e);
	},
	commentSave : function(piCommentKey)
	{
		try
		{
			var sTempString = document.getElementById("your-comment").value;
			if (sTempString.length<$.bm_comments.COMMENT_MINIMUM_LENGTH)
			{
				showError("please enter at least "+$.bm_comments.COMMENT_MINIMUM_LENGTH+" characters.","comment-message");
				return;
			}
			$("#comment-add-button").removeClass("active");
			$("#your-comment").focus();
			var sParams = "?login_name="+$.bm_users.login_name;
			sParams += "&user_key="+$.bm_users.user_key+"&comment=";
			sParams += "&alias="+$("#comment-alias").val();
			sParams +="&comment="+escape($("#your-comment").val());
			sParams +="&comment_title="+escape($("#comment-title").val());
			sParams +="&comment_key="+piCommentKey;
			sParams +="&document_key="+$.bm_docs.document_key;
			sParams +="&document_root_key="+$.bm_docs.document_root_key;

			if ($.bm_users.show_query_params)winWrite("Comments save parameters: "+$.bm_comments.COMMENT_SAVE_URL+sParams);
			//alert("comment sparams "+$.bm_comments.COMMENT_SAVE_URL+sParams);
			httpRequest.open("GET", $.bm_comments.COMMENT_SAVE_URL+sParams, true);
			httpRequest.onreadystatechange = $.bm_comments.commentSave_HttpResponse;
			httpRequest.send(null);	
		} catch(err)
		{
			errorHandler("commentSave",err);
			$.bm_user.query_in_process = false;
		}
	},
	commentSave_HttpResponse : function()
	{
		try
		{
			var sResults = httpRequest.responseText;
			var sResultsArray;
			var e;
			if (httpRequest.readyState == 4) 
			{
				sResultsArray = sResults.split(",");
				if ($.bm_users.show_query_results)winWrite("Comments insert response"+sResults);
				if (sResultsArray[0] == $.bm_comments.SUCCESS)
				{
					$(".comment-tab").removeClass("selected");
					$(".comment-tab").eq(1).addClass("selected");
					$(".comment-content").removeClass("selected");
					$(".comment-content").eq(1).addClass("selected");
					//redraw comments grid. Could just do a row insert.
					$.bm_comments.commentsGetForCurrentDoc();
					messageShow("Your comment has been saved.","#comment-message");
				} else
				{
					errorShow("Your comment has NOT been saved. "+sResultsArray[2],"#comment-message");
				}
				$("#comment-add-button").addClass("active");
			}		
		} catch(err)
		{
			errorHandler("commentsInsertHttpResponse",err);
		}
	},
	commentsGetForCurrentDoc : function()
	{
		try
		{
			var iDocumentKey = $.bm_docs.document_key;
			var iDocumentRootKey = $.bm_docs.document_root_key;

			$('#comments-results').remove();
			$('#comment-details-title').val("");
			$('#comment-details-comment').val("");
			$('#comment-details-author').val("");
			
			var sParams = "?login_name="+escape(document.getElementById("username").value)+"&user_key="+$.bm_users.user_key+"&document_key="+$.bm_docs.document_key+"&document_root_key="+$.bm_docs.document_root_key;
			if ($.bm_users.show_query_params)winWrite("Comments get parameters: "+$.bm_comments.COMMENTS_GET_URL+sParams);
			//alert("comments get sparams "+$.bm_comments.COMMENTS_GET_URL+sParams);
			httpRequest.open("GET", $.bm_comments.COMMENTS_GET_URL+sParams, true);
			httpRequest.onreadystatechange = $.bm_comments.commentsGet_HttpResponse;
			httpRequest.send(null);	
		} catch(err)
		{
			errorHandler("bm_comments.commentGetForCurrentDoc",err);
		}
	},
	commentsGet_HttpResponse : function()
	{
		try
		{
			if (httpRequest.readyState == 4) 
			{
				var sResults = httpRequest.responseText;
				var sResultsArray;
				var e;
				sResultsArray = sResults.split(",");
				if ($.bm_users.show_query_results){winWrite("Comments get results "+sResults)}
				if (sResultsArray[0] == $.bm_comments.SUCCESS)
				{
					$("#comment-list").append(sResultsArray[2]);

					$($.bm_comments.COMMENT_LIST+" .row").mouseover(function() {$.bm_comments.commentListMouseover(this)});
					$($.bm_comments.COMMENT_LIST+" .row").mouseup(function() {$.bm_comments.commentListClick(this)});

					$("#comments-results").bind('keyup', function(event) {$.bm_comments.keyUp(this,event);});

					// Return message structure
					/*
					row-id (programatically generated for purposes of formating)
					evenOdd,
					C.comments,
					A.user_key, 
					A.login_name,
					A.city,
					C.reply_to,
					*/
					//alert("commentGetHttpResponse: The number of elements returned is "+sResultsArray.length+" -"+sResults);
					
					//$.bm_comments.commentsRemoveAndAddNodes(true,"comment-root",sResultsArray);
					
					//commentsShowExistingHideNew();
				} else
				{
					//NB To do - blank existing comments
					//$.bm_comments.commentsRemoveAndAddNodes(false,"comment-root",sResultsArray);
				}
			}
		} catch(err)
		{
			errorHandler("commentsGet_HttpResponse",err);
		}
	},
	commentsTabOnMouseUp : function(e,evt)
	{
		if (gbIE && event.which == 1 || evt.which == 1){
			//trap for left mouse only.
			$.bm_comments.switchCommentsTab(e);
		}
	},
	keyPress : function(e,evt){
		var iKey = getKeystroke(evt);
		if (iKey==$.bm_ui.KEY_ENTER && $(e).attr("id")=="comment-add-button"){$.bm_comments.commentSave(0)}
	},
	switchCommentsTab : function(e)
	{
		// new comment / view comment tab has been clicked
		$($.bm_comments.COMMENT_TAB_MENU+" li.selected").removeClass("selected");
		$(e).parent().addClass("selected");

		var iIndex=$($.bm_comments.COMMENT_TAB_MENU+" li").index($(e).parent());

		$($.bm_comments.COMMENT_TAB_CONTAINER+".selected").removeClass("selected");
		$($.bm_comments.COMMENT_TAB_CONTAINER).eq(iIndex).addClass("selected");	
		$.bm_comments.setFocus(e);
	},
	setFocus : function(e)
	{
		if ($(e).text()=="New"){
			$("#comment-title").focus();
			//By default the comment-alias is the preference alias
			//If the preference alias is empty then the email username is used
			if ($("#comment-alias").val()==""){
				//Populate comment-alias with alias
				$("#comment-alias").val($("#alias").val());
			}
			if ($("#comment-alias").val()==""){
				//Populate comment-alias with alias
				var sTempString = $("#email").val();
				$("#comment-alias").val(sTempString.substr(0,sTempString.indexOf("@")));
			}
		}
		if ($(e).text()=="View")$("#comment-list").focus();
	}
}
})

})(jQuery);

