var NotesAPI2 = (function () {
	
	var updateCharCount = function (cntObj , txtObj) {
		var diff = 8000 - (txtObj.get("value") + "").length;
		cntObj.set("text", (diff > 0) ? diff : "None");
		if (diff < 0) {
			alert("You have exceeded the number maximum characters for this note. This note will be truncated to 8000 characters.");
		}
	}
	
	/**
	  * @access Private-State
	  * 
	  * Performs ajax for the notes api.
	  *
	  */
	var apiRequest = function (action, parms, callback, el) {
		var options = {
					override_cache : true,
					onComplete : function ( obj )  {
						EFX.hideOverlay(el);
						callback(obj);
					}
		};
		EFX.showOverlay(el);
		API.request("/home/" + action + "/0", parms, options);
	}
	
	return {
		selectTabByTypeName : function (noteControlerID, noteTypeName, cb_function) {
					var oldEl =$(noteControlerID);
					var response = function (obj) {
						var el = new Element("div");
						el.set("html", obj['html']);
						var newEl = el.children[0];
						newEl.replaces(oldEl);
						eval(obj["js"]);
						if (cb_function) {
							eval(cb_function + '()');
						}
					};
					apiRequest("requestNoteBody", {data: $(noteControlerID + "_NoteControlData").value, NoteType : noteTypeName}, response, oldEl);
				},
		showCreateNote : function (noteControlerID, noteTypeName) {
					$(noteControlerID + "_NoteCreateBody").removeClass("hidden");
					NotesAPI2.updateNoteBodyHeight(noteControlerID);
					$(noteControlerID + "_CreateNewNoteButton").addClass("hidden");
					NotesAPI2.clickRatingOptionHandler(noteControlerID + "_EditOpinion_Positive", noteControlerID + "_EditOpinion_Negative", noteControlerID + "_EditOpinion_Neutral");
					$(noteControlerID + "_CreateText").value = $(noteControlerID + "_CreateDefaultNote").value;
					NotesAPI2.updateCounter($(noteControlerID + "_CreateText"), 8000);
					
					$(noteControlerID + "_Create_RelatedObjectID_New").value = '';
					$(noteControlerID + "_Create_RelatedObjectID_New_Label").value = '';
					$(noteControlerID + "_Create_RelatedObjectID_New").parentNode.addClass('hidden');
					$(noteControlerID + "_relatedObjectOption").removeClass("hidden");
				},
		hideCreateNote : function (noteControlerID, noteTypeName) {
					$(noteControlerID + "_NoteCreateBody").addClass("hidden");
					$(noteControlerID + "_CreateNewNoteButton").removeClass("hidden");
					NotesAPI2.updateNoteBodyHeight(noteControlerID);
				},
		showNoteEditMode : function (noteControlerID, noteID) {
					$(noteControlerID + "_" + noteID + "_NoteOutterBodyEdit").removeClass("hidden");
					$(noteControlerID + "_" + noteID + "_NoteOutterBodyView").addClass("hidden");
					NotesAPI2.updateCounter($(noteControlerID + "_" + noteID + "_EditNoteText"), 8000);
					NotesAPI2.updateNoteBodyHeight(noteControlerID);
				},
		hidewNoteEditMode : function (noteControlerID, noteID) {
					$(noteControlerID + "_" + noteID + "_NoteOutterBodyEdit").addClass("hidden");
					$(noteControlerID + "_" + noteID + "_NoteOutterBodyView").removeClass("hidden");
					NotesAPI2.updateNoteBodyHeight(noteControlerID);
				},
		showNoteEditMenu : function (noteControlerID, noteID) {
					$(noteControlerID + "_" + noteID + "_noteEditControlPanel").removeClass("hidden");
				},
		hidewNoteEditMenu : function (noteControlerID, noteID) {
					$(noteControlerID + "_" + noteID + "_noteEditControlPanel").addClass("hidden");
				},		
		createNote : function (noteControlerID, noteTypeName) {
					var rating = 2;
					if ($(noteControlerID + "_EditOpinion_Positive_Label").className.contains('noteRatingLabelSelected')) {
						rating = 3;
					} else if ($(noteControlerID + "_EditOpinion_Negative_Label").className.contains('noteRatingLabelSelected')) {
						rating = 1;
					} else if (!$(noteControlerID + "_EditOpinion_Positive_Label").className.contains('noteRatingLabelUnselected')) {
						if ($(noteControlerID + "_EditOpinion_Positive").get("checked")) {
							rating = 3;
						} else if ($(noteControlerID + "_EditOpinion_Neutral").get("checked")) {
							rating = 2;
						} else if ($(noteControlerID + "_EditOpinion_Negative").get("checked")) {
							rating = 1;
						}
					}  
					
					var relatedObjectID = null;
					if ($(noteControlerID + "_Create_RelatedObjectID_New_hidden")) {
						var relatedObjectIDInfo = $(noteControlerID + "_Create_RelatedObjectID_New_hidden").value;
						if (relatedObjectIDInfo.length > 2) {
							relatedObjectID = relatedObjectIDInfo.substring(1).split(':')[0];
						}
					}
					
					//print_r($(noteControlerID + "_Create_RelatedObjectID_New").get("name"));
					var data = {
						text : $(noteControlerID + "_CreateText").get("value").trim(),
						rating : rating,
						NoteType : noteTypeName,
						ObjectName : $(noteControlerID + "_CreateObjectName").get("value").trim(),
						ObjectID : $(noteControlerID + "_CreateObjectID").get("value"),
						RelatedObjectName : $(noteControlerID + "_Create_RelatedObjectID_New").get("value") && !$(noteControlerID + "_CreateRelatedObjectID").get("value") ? $(noteControlerID + "_Create_RelatedObjectID_New").get("name").split('_')[0] : $(noteControlerID + "_CreateRelatedObjectName").get("value").trim(),
						RelatedObjectID : $(noteControlerID + "_CreateRelatedObjectID").get("value") ? parseInt($(noteControlerID + "_CreateRelatedObjectID").get("value")) : relatedObjectID,
						htmlID : noteControlerID,
						Ratable : $(noteControlerID + "_CreateNoteRatable").get("value"),
						SubjectObjectName : $(noteControlerID + "_SubjectObjectName").get("value")
					};
					
					var createBody = $(noteControlerID + "_NoteCreateBody");
					var response = function (obj) {
						var noteTableBody = $(noteControlerID + "_NotesBody");
						var el = new Element("div", {}).set("html", obj["html"]);
						var table = el.getElements("table")[0];

						var first = noteTableBody.getFirst();
						if (first)	{
							table.inject(first, "before");
						} else {
							(noteTableBody).adopt(table);
						}
						NotesAPI2.hideCreateNote(noteControlerID, noteTypeName);
						
						var tabCountObj = $(noteControlerID + "_" + noteTypeName + "_Cnt");
						var cnt = tabCountObj.get("title") ? parseInt(tabCountObj.get("title")) + 1 : 1;
						tabCountObj.set("title", cnt);
						tabCountObj.set("text", cnt ? " (" + cnt + ")" : '');
						
						countObjectID = $(noteControlerID + "_NoteCountID").get("value");
						
						if (countObjectID) {
							try { eval(countObjectID + "(" + cnt + ", \"" +  noteControlerID + "\", \"" + noteTypeName + "\")"); }
							catch (ere) {
								if ($(countObjectID)) {
									$(countObjectID).set("text", cnt ? cnt : "");
								} else {
								}
							}
						}
						if (noteControlerID.contains('NotePopup_')) {
							$(noteControlerID).parentNode.parentNode.parentNode.parentNode.destroy();
						}
					}
					
					//print_r(data);
					apiRequest("requestCreateNoteJson", data, response, createBody);
					
				},
		updateNote : function (noteControlerID, noteID, noteTypeName) {
					
					var rating = 2;
					if ($(noteControlerID + "_" + noteID + "_EditUpdateOpinion_Positive_Label").className.contains('noteRatingLabelSelected')) {
						rating = 3;
					} else if ($(noteControlerID + "_" + noteID + "_EditUpdateOpinion_Negative_Label").className.contains('noteRatingLabelSelected')) {
						rating = 1;
					} else if (!$(noteControlerID + "_" + noteID + "_EditUpdateOpinion_Positive_Label").className.contains('noteRatingLabelUnselected')) {
						if ($(noteControlerID + "_" + noteID + "_EditUpdateOpinion_Positive").get("checked")) {
							rating = 3;
						} else if ($(noteControlerID + "_" + noteID + "_EditUpdateOpinion_Neutral").get("checked")) {
							rating = 2;
						} else if ($(noteControlerID + "_" + noteID + "_EditUpdateOpinion_Negative").get("checked")) {
							rating = 1;
						}
					} 
					print_r("dasas");
					try{
					var data = {
						htmlID : noteControlerID,
						noteID : noteID,
						text : $(noteControlerID + "_" + noteID + "_EditNoteText").get("value").trim(),
						rating : rating,
						NoteType : noteTypeName,
						ObjectName : $(noteControlerID + "_" + noteID + "_EditObjectName").get("value").trim(),
						ObjectID : $(noteControlerID + "_" + noteID + "_EditObjectID").get("value"),
						Ratable : $(noteControlerID + "_" + noteID + "_Ratable").get("value")
					};
					} catch(eee) {
						print_r(eee);
					}
					print_r(data);
					
					var noteBody = $(noteControlerID + "_" + noteID + "_NoteOutterBody");
					var response = function (obj) {
						var el = new Element("div", {}).set("html", obj["html"]);
						var table = el.getElements("table")[0];
						(table).replaces(noteBody);
						
						var tabCountObj = $(noteControlerID + "_" + noteTypeName + "_Cnt");
						var cnt = parseInt(tabCountObj.get("title"));
						
						countObjectID = $(noteControlerID + "_NoteCountID").get("value");
						if (countObjectID) {
							print_r(countObjectID + "(" + cnt + ", \"" +  noteControlerID + "\", \"" + noteTypeName + "\")");
							try { eval(countObjectID + "(" + cnt + ", \"" +  noteControlerID + "\", \"" + noteTypeName + "\")"); }
							catch (ere) {
								if ($(countObjectID)) {
									$(countObjectID).set("text", noteCount ? noteCount : "");
								} else {
								}
							}
						}
						NotesAPI2.updateNoteBodyHeight(noteControlerID);
					}
					
					//print_r(data);
					apiRequest("requestUpdateNoteJson", data, response, noteBody);
					
				},
		removeNote : function (noteControlerID, noteID, noteTypeName) {
					if (!confirm("Are you sure you wish to remove this note?")) {
						return;
					}
					var response = function (obj) {
						$(noteControlerID + "_" + noteID + "_NoteOutterBody").addClass("hidden");
						
						var tabCountObj = $(noteControlerID + "_" + noteTypeName + "_Cnt");
						var cnt = parseInt(tabCountObj.get("title")) - 1;
						tabCountObj.set("title", cnt);
						tabCountObj.set("text", cnt ? " (" + cnt + ")" : '');
						
						countObjectID = $(noteControlerID + "_NoteCountID").get("value");
						if (countObjectID) {
							try { eval(countObjectID + "(" + cnt + ", \"" +  noteControlerID + "\", \"" + noteTypeName + "\")"); }
							catch (ere) {
								if ($(countObjectID)) {
									$(countObjectID).set("text", noteCount ? noteCount : "");
								} else {
								}
							}
						}
						NotesAPI2.updateNoteBodyHeight(noteControlerID);
					}
					
					apiRequest('requestRemoveNoteJson', { 'noteID' : noteID }, response, $(noteControlerID + "_" + noteID + "_NoteOutterBody"));
					
				},
		showNotesPopup : function (el, data) {

					noteNUM = 9999;
					var titleID = "notePopupID_" + noteNUM + "_titleCaption", notesPopupWidth = 720, notesPopupHeight = 500;
					var pmnform = new Element ( "div", { "class" : "globalPop", id : "notePopupID_" + noteNUM,  styles : { width: notesPopupWidth } } );
					pmnform.postShowPopup = function (obj) {
						eval(obj["js"]);
						/*$("notePopupID_" + noteNUM + "_Wrapper").getElements("ul.subtab.").each (function (el2) {
							el2.parentNode.setStyle("display", "none");
						});
						$("notePopupID_" + noteNUM + "_Wrapper").getElements("img.addPMNoteCreateShowBtn").each (function (el2) {
							el2.parentNode.setStyle("padding-right", "3px");
						});*/
					}
					var headerElements = Popups.createPopupHeader({ container: pmnform, titleStyle: { background: "#a0b6cb" }, headingAdopts: { }, titleText: "Notes", options: { background: "#a0b6cb" } });
			    	headerElements["headingDiv"].inject(pmnform);
					Popups.showPopup( Popups.getPopupLocation(notesPopupWidth, notesPopupHeight ), pmnform, EFX.loadingImg ( { inject : pmnform } ), "info_" + pmnform.tid, headerElements, {url : "/home/requestPopupJson/0", data : data } );
				},
		updateNoteBodyHeight : function (noteControlerID) {
					var notesMainContainer = $(noteControlerID);
					var noteTableBody = $(noteControlerID + "_NotesBody");
					//var noteTableBody = notesMainContainer.getElement("div.pmNoteHeader");
					var containerType = $(noteControlerID + "_ContainerType").value;
					if (containerType == "fixed") {
						var createBox = $(noteControlerID + "_NoteCreateBody");
						var h2 = notesMainContainer.getSize().y - notesMainContainer.parentNode.getSize().y;
						var popupOffset = (noteControlerID.contains('NotePopup_') ? 32 : 0);
						var noteControlerRequestOffset = (noteControlerID == 'NoteControlerRequest' ? 35 : 0);
						if (createBox.className.contains ("hidden")) {
							noteTableBody.setStyle("height", notesMainContainer.parentNode.getSize().y - popupOffset - noteControlerRequestOffset);
						} else {
							noteTableBody.setStyle("height", notesMainContainer.parentNode.getSize().y - createBox.getSize().y - popupOffset - noteControlerRequestOffset);
						}
						
					} else {
						noteTableBody.parentNode.setStyle("overflow-y", "visible");
						noteTableBody.setStyle("overflow-y", "visible");
					}
				},
		updateCounter : function (e, maxLength) {
					var value = e.get("value").ltrim();
					var cnt = value.length;
					var counterEl = $(e.id + "Count");
					var lines = 4;
					var sz = value.split("\n").length;
					if (lines < sz) {
						lines = sz;
					}
					var fontSize = e.getStyle("font-size"); fontSize = parseInt(fontSize.substring(0, fontSize.length - 2));
					var paddingTop = e.getStyle("padding-top"); paddingTop = parseInt(paddingTop.substring(0, paddingTop.length - 2));
					var paddingBottom = e.getStyle("padding-bottom"); paddingBottom = parseInt(paddingBottom.substring(0, paddingBottom.length - 2));
					
					e.setStyle("height", ((fontSize + 3) * lines + paddingTop + paddingBottom + 11) + "px");

					if (cnt > maxLength) {
						e.set("value", (value.substring(0, maxLength)));
						e.addClass("red");
						counterEl.set("html", "None");
					} else if (cnt == maxLength) {
						counterEl.set("html", "None");
						e.removeClass("red");
						e.set("value", value);
					} else {
						counterEl.set("html", maxLength - cnt);
						e.removeClass("red");
						e.set("value", value);
					}
				},
		clickRatingOptionHandler : function (positiveID, negativeID, selectedID) {
					if (positiveID == selectedID) {
						if ($(positiveID + "_Label").className.contains('noteRatingLabelSelected')) {
							$(positiveID + "_Label").addClass('noteRatingLabelUnselected');
							$(negativeID + "_Label").addClass('noteRatingLabelUnselected');
							$(positiveID + "_Label").removeClass('noteRatingLabelSelected');
							$(negativeID + "_Label").removeClass('noteRatingLabelSelected');
							$(positiveID + "_Label").children[0].src="/images/b_thumbUp.gif";
						} else {
							$(positiveID + "_Label").addClass('noteRatingLabelSelected');
							$(positiveID + "_Label").removeClass('noteRatingLabelUnselected');
							$(negativeID + "_Label").addClass('noteRatingLabelUnselected');
							$(negativeID + "_Label").removeClass('noteRatingLabelSelected');
							$(positiveID + "_Label").children[0].src="/images/b_thumbUp_pressed.gif";
							$(negativeID + "_Label").children[0].src="/images/b_thumbDown.gif";
						}
					} else if (negativeID == selectedID) {
						if ($(negativeID + "_Label").className.contains('noteRatingLabelSelected')) {
							$(positiveID + "_Label").addClass('noteRatingLabelUnselected');
							$(negativeID + "_Label").addClass('noteRatingLabelUnselected');
							$(positiveID + "_Label").removeClass('noteRatingLabelSelected');
							$(negativeID + "_Label").removeClass('noteRatingLabelSelected');
							$(negativeID + "_Label").children[0].src="/images/b_thumbDown.gif";
						} else {
							$(negativeID + "_Label").addClass('noteRatingLabelSelected');
							$(negativeID + "_Label").removeClass('noteRatingLabelUnselected');
							$(positiveID + "_Label").addClass('noteRatingLabelUnselected');
							$(positiveID + "_Label").removeClass('noteRatingLabelSelected');
							$(positiveID + "_Label").children[0].src="/images/b_thumbUp.gif";
							$(negativeID + "_Label").children[0].src="/images/b_thumbDown_pressed.gif";
						}
					} else {
						$(positiveID + "_Label").addClass('noteRatingLabelUnselected');
						$(negativeID + "_Label").addClass('noteRatingLabelUnselected');
						$(positiveID + "_Label").removeClass('noteRatingLabelSelected');
						$(negativeID + "_Label").removeClass('noteRatingLabelSelected');
						$(positiveID + "_Label").children[0].src="/images/b_thumbUp.gif";
						$(negativeID + "_Label").children[0].src="/images/b_thumbDown.gif";
					}
				},
		setupAutoComplete : function (noteControlerID, type2) {

					var url = '';
					if (type2 == 'Client') {
						$(noteControlerID).name = 'Client';
						url = "/findUniqueClientByNameOrID2/advisor/";
					} else if (type2 == 'Request') {
						$(noteControlerID).name = 'Request';
						url = "/findRequestByNameOrID/advisor/";
					}
					
					if (url) {
						print_r(noteControlerID + "_Label");
						$(noteControlerID + "_Label").set("text", $(noteControlerID).name); 
						$(noteControlerID).parentNode.removeClass("hidden");
						MainAPI.setupAutoComplete(noteControlerID, { dataSrc : { url : url } } );
					}
				}
	};
}) ();
