// Prepares a dialog and icon to display help text in a floating lightbox
// This includes doing the following manipulations:
//  - wrapping the icon in an anchor which opens the dialog box
//  - creating a dialog box if necessary
//  - populating the dialog box
//  - populating the help icon's title attribute (for the floating tooltip)
//  - hides the help icon when an error occurs (such as a 404)
// 
// Arguments:
//  portletnamespace - The portlet namespace, used to prefix ids - required
//  key - The help mode key, used to generate the url for the AJAX call - required
//  helpiconid - The help icon id - optional (defaults to portletnamespace + "_dialogHelpIcon")
function prepareHelpDialog(portletnamespace, key, helpiconid) {
	// if no help icon id is specified use the default
	if (!helpiconid) {
		helpiconid = portletnamespace + "_dialogHelpIcon";
	}

	// if necessary create a link with the appropriate event handler around the help icon
	helpIcon = $("#" + helpiconid);
	if (helpIcon.parent("a").length == 0) {
		helpIcon.wrap("<a href=\"#\"></a>");
		helpIcon.parent("a").click(function (event) {
			event.preventDefault();
			$("#" + portletnamespace + "_dialogHelp").dialog("open");
		});
	}

	// create a hidden div to load the ajax content
	$("body").append("<div id=\"" + portletnamespace + "_dialogHelpHidden\" style=\"display: none;\"></div>");

	// make the ajax call and populate the hidden div
    $("#" + portletnamespace + "_dialogHelpHidden").load("/business/help/" + key, function (responseText, textStatus, XMLHttpRequest) {
		if (textStatus == "error" || $("#" + portletnamespace + "_dialogHelpHidden #body").contents().length == 0) {
			// Hide the help icon if there is an error
			helpIcon.hide();
		}
		// if necessary create a dialog box for the help
		dialogHelp = $("#" + portletnamespace + "_dialogHelp");
		if (dialogHelp.length == 0) {
			$("body").append("<div id=\"" + portletnamespace + "_dialogHelp\" style=\"display:none\"></div>");
			dialogHelp = $("#" + portletnamespace + "_dialogHelp");
		}

		// populate the dialog box with the results retrieved from the ajax call
        dialogHelp.attr("title", $("#" + portletnamespace + "_dialogHelpHidden #title").text());
    	$("#" + portletnamespace + "_dialogHelpHidden #body").contents().appendTo("#" + portletnamespace + "_dialogHelp");
		dialogHelp.dialog({ autoOpen: false, position: "right", height: 400 }); // Once the div has been populated we can call the dialog function
    	helpIcon.attr("title", "doubleclickstop=[off] cssbody=[tooltipbody] cssheader=[tooltipheader] header=[" + $("#" + portletnamespace + "_dialogHelpHidden #tooltip_title").text() + "] body=[" + $("#" + portletnamespace + "_dialogHelpHidden #tooltip_body").text() + "]");

		// remove the hidden div
    	$("#" + portletnamespace + "_dialogHelpHidden").remove();
      });
}


//Prepares a dialog and icon to display help text in a floating lightbox
//This includes doing the following manipulations:
//- wrapping the icon in an anchor which opens the dialog box
//- creating a dialog box if necessary
//- populating the dialog box
//- making the dialog box content be displayed using jstree
//- populating the help icon's title attribute (for the floating tooltip)
//- this method does not hide the icon if content is not found
//
//Arguments:
//portletnamespace - The portlet namespace, used to prefix ids - required
//iconid - The help icon id - optional (defaults to portletnamespace + "_dialogHelpIcon")
//tooltipKey - The key that will form the a URL used to populate tooltip contents
//openHelpNode(OPTIONAL) - Node to be displayed when opening the help dialog 
//dialogFile(OPTIONAL) - The file that contains the HTML content for dialog help
//helpForm (OPTIONAL) - Form to submit to ajax help servlet which returns HTML content for dialog help 
function addTooltipDialog(portletnamespace, iconid, tooltipKey, openHelpNode, dialogFile, helpForm) {
	// if necessary create a link with the appropriate event handler around the
	// help icon
	var helpDialogId = portletnamespace + "_DialogHelpDiv";
	var helpIconObj = $("#" + iconid);

	if (openHelpNode != null && openHelpNode != undefined){
	  if (helpIconObj.parent("a").length == 0) {
		helpIconObj.wrap("<a href='#'></a>");
	  }

	  //The onclick event of the help icon should open the help dialog and position
	  //in the relevant help content
	  helpIconObj.parent("a").click( function(event) {
		event.preventDefault();
		$("#" + helpDialogId).dialog("open");
		// Tree instance
		var myTree = jQuery.tree.reference('#' + helpDialogId);
		var branchsToOpen = openHelpNode;
		var branchsArray = branchsToOpen.split(",");
		//Closes open branches so that only the relevant one keeps open
		myTree.close_all(branchsToOpen);
		// Opens node and positions tree correctly
		myTree.open_branch(branchsToOpen);
		myTree.focus();
		// Scrolls into last open element
		myTree.scroll_into_view(branchsArray[branchsArray.length - 1]);
	  });

	  // if not already present creates and populates a dialog box for the help
	  var dialogHelp = $("#" + helpDialogId);
	  if (dialogHelp.length == 0) {
		$("body").append(
				"<div id=\"" + helpDialogId
						+ "\" class=\"help-container\"></div>");
		dialogHelp = $("#" + helpDialogId);
		
		if (helpForm == undefined || helpForm == null || helpForm.length == 0) {
			// Ajax call to populate help dialog
			$.ajax( {
				url : "/dafiles/OBCA/Furniture/optus.com.au/obportal/html/"+dialogFile,
				complete : function (XMLHttpRequest, textStatus) {
					var t = XMLHttpRequest.responseText;
					initializeHelpDialog(t, dialogHelp);
				}
			});
		} else {
			// post help form to ajax servlet to populate help dialog
			$.post("/obportlets/ajax/help/", 
				$("#"+helpForm).serialize(), 
					function(result){
						initializeHelpDialog(result, dialogHelp);
					},
				'text/xml'
			);
		}
	  }
	}

	// Ajax call to populate tooltip	
	$.ajax( {
		url : "/business/help/"+tooltipKey,
		complete : function (XMLHttpRequest, textStatus){
			var t = XMLHttpRequest.responseText;
			
			var elemAux = $("<div>"+t+"</div>");
			
			var tooltipTitle = elemAux.find("#tooltip_title");
			var tooltipBody = elemAux.find("#tooltip_body");
			
			if (tooltipTitle.contents().length > 0) {
				helpIconObj.attr("title",
						  "doubleclickstop=[off] cssbody=[tooltipbody] cssheader=[tooltipheader] header=["
									+ tooltipTitle.text()
									+ "] body=[" 
									+ tooltipBody.text() + "]");
			}
		}
	});
}

function initializeHelpDialog(text, dialogHelp) {
	if (text != null && text.length >0){
		dialogHelp.append(text);
	
		// Makes the dialog content displayed as a jstree
		dialogHelp.tree( {
			ui : {
				dots : false,
				theme_name : "default"
			},
			callback : {
				onopen : function(NODE,TREE_OBJ) {
					/* prevents expanding/collapsing of the custom ordered lists and their parent */
					$(NODE)
						.find('ol.help-list-style-type-decimal > li.closed')
							.each(function () {
								$(this)
									.removeClass('closed')
									.addClass('leaf')
									.parents('ol.help-list-style-type-decimal')
										.parent()
											.removeClass('closed')
											.addClass('leaf');
							});

					/* IE7 doesn't display numbered item if last item is leaf */
					$(NODE).find('ol.help-list-style-type-decimal > li.last').removeClass('last');
					
					/* prevents expanding/collapsing of the custom unordered/bulleted lists and their parent */
					$(NODE)
						.find('ul.help-list-style-type-disc > li')
							.each(function () {
								$(this)
									.removeClass('closed')
									.addClass('leaf')
									.parents('ul.help-list-style-type-disc')
										.parent()
											.removeClass('closed')
											.addClass('leaf');
							});
					
					/* IE7 doesn't display bullet if last item is leaf */
					$(NODE).find('ul.help-list-style-type-disc > li.last').removeClass('last');
				},
				onselect : function(NODE,TREE_OBJ) {
					/* make default click behaviour expand/collapse tree */
					TREE_OBJ.toggle_branch.call(TREE_OBJ, NODE);
				}
			}
		});
	}
	
	// Once the div has been populated we can call the dialog function
	dialogHelp.dialog( {
		autoOpen : false,
		position : "right",
		height : 400,
		bgiframe : true
	});
}

