
var selectedForumPostID = "";
var e_forum = null;

/**
 * Shows the table of contents chapters
 */
function showTableOfContents() {
	$("#tableOfContentChapters").show();
	$("#hideTableOfContentLink").show();
	$("#showTableOfContentLink").hide();
}


/**
 * Hides the table of contents chapters.
 */
function hideTableOfContents() {
	$("#tableOfContentChapters").hide();
	$("#showTableOfContentLink").show();
	$("#hideTableOfContentLink").hide();
}


// Forms


/**
 * Set the edit type fields in the edit form and the edit settings form to the correct values. 
 */
$(function() {
	if ($("div.editForm div.editertType textarea").length == 1) {
		$("div.editForm div.editertType textarea")[0].value = textEdit;
	}

	if ($("table.settingsForm div.editertType textarea").length == 1) {
		$("table.settingsForm div.editertType textarea")[0].value = settingEdit;
	}
});


// tabbed interface


/**
 * The indexes of the tabs in use
 */
var READ_TAB_INDEX = 0;
var EDIT_TAB_INDEX = 1;
var REVISIONS_TAB_INDEX = 2;
var DISCUSSIONS_TAB_INDEX = 3;
var SETTINGS_TAB_INDEX = 4;
var SEARCH_TAB_INDEX = 5;
var isForside = false;


/**
 * The document id of the current section (used for drag and drop section navigator)
 */ 
var currentID = "";


function selectTab(index) {
  $("#iknowbook-tabbed-content").tabs('select', index);
}


function enableLink(linkElement, onClick) {
  linkElement.hover(
    function(e){this.style.cursor = "pointer";},
    function(e){this.style.cursor = "normal";}
  ).click(onClick);
}


/**
 * Loads HTML contents of an object using ajax
 * 
 * @param   targetElement    the element to load HTML content to
 * @param   urlName          url pattern name 
 *                           (base path is /ikbViewer/page/iknowbook/ajax/[urlName])
 * @param   objID            the identificator for the object
 * @param   onSuccess        a callback function run at successful retrieval.
 *                           The recieved data is placed in the object "response".
 */
function loadElementForObject(targetElement, urlName, objID, onSuccess) {

  targetElement.load(
    "/ikbViewer/page/iknowbook/ajax/" + urlName, 
    {"p_document_id":objID},
    function(response, textStatus, XMLHttpRequest){
      if(textStatus == "success") {
        onSuccess();
      }
    }
  );
}


/**
 * Returns the full path to this page. 
 */
function getFullPath() {
 return window.location + "";
}


/**
 * Get the document id for the document. 
 * @return The document id of the document are for. 
 */
function getDocumentId() {
	if (isForside) {
		return documentId;
	}
	return subdocID;
}


function saveForumComment(params, parentID) {
    $.post(
      "/ikbViewer/pls/iknowbook.saveForumPost", 
      {
        p_title:params.title,
        p_description:params.text,
        p_author:params.author,
        p_parent_id:parentID
      },
      function(data, textStatus){
        if(textStatus == "success") {
          selectedForumPostID = data; //Set new object as current one
          e_forum.jforum.reloadObjects(e_forum);
        }
      }
    );

}


/**
 * Loads a the discussion forum
 * 
 * @param 	documentID	the ID of the parent document
 */
function loadForum(documentID) {
  e_forum.jforum({
    //data:objs,
    ajaxUrl: "/ikbViewer/page/iknowbook/json/discussions",
    ajaxParams:{"p_document_id":documentID},
    columns:[
      {
        "name":"Tittel",
        "class":"forum-col1",
        "dataField":"title",
        "submitable":true
      },
      {
        "name":"Av",
        "class":"forum-col2",
        "dataField":"author",
        "submitable":true
      },
      {
        "name":"Dato",
        "class":"forum-col3",
        "dataField":"created",
        "submitable":false
      }/*,
      {
        "name":"Oppdatert",
        "class":"forum-col4",
        "dataField":"changed",
        "submitable":false
      }*/
    ],
    actions:[
      {
        name:"Rediger",
        content:'<div class="jdimlist-icon-action-edit"> </div>',
        className:"action_edit",
        classHover:"action_edit_hover", 
        handler:function(e, obj){
          //Open form
          window.open('http://login.demo.iknowbase.com:7778/xnet/shared/publish?p_styleset_id=17087&p_document_id=' + obj.attr("id") + '&p_form_back_url=http://login.demo.iknowbase.com:7778/ikbViewer/page/iknowbook/section?p_document_id=${viewer.param.p_document_id}^p_subdoc_id=${viewer.param.p_subdoc_id}^tab=' + DISCUSSIONS_TAB_INDEX,'vindu2','left=' + (screen.width-600)/2 + ', top=' + (screen.height-550)/2 + ',scrollbars=yes,resizable=yes,height=550,width=750'); vindu.focus();
        }
      },
      {
        name:"Slett",
        content:'<div class="jdimlist-icon-action-delete"> </div>',
        className:"action_delete",
        classHover:"action_delete_hover", 
        handler:function(e, obj){
          //TODO: Possible weakness: Is the action element clickable even if there is no generated icon?
          //Call delete function
          //parameters: document ID, version number, portlet ID (irrelevant, send empty string)
          iKnowBase.ContentViewer.deleteDocument(obj.attr("id"), "", "");
        }
      }
    ],
    onSubmit:function(e, submitParams, parentID){
        saveForumComment(submitParams, parentID);
      },
    maxFirstLevel:3
  });

}


/**
 * Scrolls the page. 
 * @param id The id of the element to scroll to, empty to scroll to the top.
 */
function scrollPage(id) {
	// prepend the # if not already present
	id = id == undefined || id == null ? "" : id;
	var id = id.indexOf("#") != 0 && id.length != 0 ? ("#" + id) : id;
	var destinationElement = $(id);
	var destination = id.length != 0 ? $(destinationElement).offset().top : 0;
	$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, "slow");
	return false;
}


/**
 * Inits the scroll links.
 */ 
function initScrollLinks() {
	// the view tab is loaded with ajax, uise livequery to the click handler to 
	// all these ajax links
	$(".backToTopLink").livequery("click", function() {
		scrollPage("");
	});
}


/**
 * Returns true if the current page is a printer friendly page. 
 */
function isPrinterFriendlyPage() {
	if (window.location.href.indexOf("printer-friendly") > -1) {
		return true;
	}
	return false;
}


/**
 * Hides the version tab.
 */
function hideVersionTab() {
	$(".versionTabLink").remove();
	REVISIONS_TAB_INDEX = 200;
	DISCUSSIONS_TAB_INDEX = DISCUSSIONS_TAB_INDEX - 1;
	SETTINGS_TAB_INDEX = SETTINGS_TAB_INDEX - 1;
	SEARCH_TAB_INDEX = SEARCH_TAB_INDEX -1;
}


/**
 * Hides the discussions tab. 
 */
function hideDiscussionsTab() {
	$(".discussionTabLink").remove();
	DISCUSSIONS_TAB_INDEX = 100;
	SETTINGS_TAB_INDEX = SETTINGS_TAB_INDEX - 1;
	SEARCH_TAB_INDEX = SEARCH_TAB_INDEX  - 1;
}


/**
 * Hides the settings tab.
 */
function hideSettingsTab() {
	$(".settingsTabLink").remove();
	SETTINGS_TAB_INDEX = 98;
	SEARCH_TAB_INDEX = 3;
}


/**
 * Hides the editTab.
 */
function hideEditTab() {
	$(".editTabLink").remove();
	// set the other indexes correct
	EDIT_TAB_INDEX = 99;
	REVISIONS_TAB_INDEX = 1;
	DISCUSSIONS_TAB_INDEX = 2;
	SETTINGS_TAB_INDEX = 3;
	SEARCH_TAB_INDEX = 4;
}


/**
 * Returns true if the discussion tab is to be shown, false otherwise. 
 */
function isDiscussionTabShown() {
	if ("Nei" == toggleDiscussions || "No" == toggleDiscussions) {
		return false;
	}
	return true;
}


/**
 * Returns true if the settings tab is to be shown, false otherwise. 
 */
function isSettingsTabShown() {
	if ($(".settingsForm").length == 0) {
		return false;
	}
	return true;
}


/**
 * Returns true if the edit tab is to be shown, false otherwise. 
 */
function isEditTabShown() {
	if ($(".editForm").length == 0) {
		return false;
	}
	return true;
}


/**
 * Based on the access constraints set some parts of the book might not be present. Hide 
 * the tabs for them.
 */
function hideTabs() {
	// check if the edit form is present
	if (!isEditTabShown()) {
		// user has no access to edit the document
		hideEditTab();
	}
	// check if the settingsform is present
	if (!isSettingsTabShown()) {
		// user has no access to settings, remove the tab
		hideSettingsTab();
	}
	if (!isDiscussionTabShown()) {
		hideDiscussionsTab();
	}
}


/**
 * Prepares the tabs. 
 */
function prepareTabs() {
	// remove the onClick from the ikb menu (call_ikb_homeplace) and 
	// add the # to the non ajax links
	var tabs = $("#iknowbook-tabbed-content");
	$("div", tabs).each(function() {
		$(this).children("a").removeAttr("onClick");
		$(this).children("a").removeAttr("onclick");
		var linkValue = $(this).children("a").attr("href");
		if (linkValue.indexOf("http") == -1) {
			$(this).children("a").attr("href", ("#" + linkValue));
		}
		else {
			$(this).children("a").attr("href", decodeURIComponent(linkValue));
		}
	});
	hideTabs();
	
	// no version tab for gard
	hideVersionTab();
}



/**
 * Disables voting (used when the user has voted once).
 */
function disableVoting() {
	$("#iknowbook-vote-rate-user").jrate("option", "voteable", false);
}



/**
 * Rounds a given float number, includes half integers (1.6 -> 1.5).
 * @param numberValue The number to round. 
 * @return The rounded number.
 */
function roundNumber(numberValue) {
	var fraction = numberValue - Math.floor(numberValue);
	if (fraction == 0) {
		// nothind to round
		return numberValue;
	}
	
	var rounded = Math.floor(numberValue);
	if (fraction >= 0.75) {
		return rounded + 1;
	}
	else if (fraction >= 0.5) {
		return rounded + 0.5;
	}
	else if (fraction >= 0.25) {
		return rounded + 0.5;
	}
	
	return rounded;
}


/**
 * Reloads the average vote.
 */
function reloadAverageVote() {
	$.get("/ikbViewer/pls/iknowbook.getVoteAverage?p_document_id=" + getDocumentId() + "&", null, function(data) {		
		data = setVoteDecimalSeparator(data, getDatabaseDecimalSeparator(), ".");
		$("#iknowbook-vote-rate-avg").jrate("option", "rating", roundNumber(parseFloat(data)));
 	});
}


/**
 * Loads the vote count.
 */
function loadVoteCount() {
	$.get("/ikbViewer/pls/iknowbook.getVoteCount?p_document_id=" + getDocumentId() + "&", null, function(data) {				
		$(".iknowbook-voute-count").html(data);
 	});
}


/**
 * Stores a given vote in the database. 
 * @param voteValue The vote to store. 
 */
function storeVote(voteValue) {
	voteValue = setVoteDecimalSeparator(voteValue, ".", getDatabaseDecimalSeparator());
	$.post(
        "/ikbViewer/pls/iknowbook.saveVote",
        {
          "p_document_id": getDocumentId(),
          "p_vote_value": voteValue
        },
        function(data, textStatus) {
          if(textStatus == "success"){
			loadVoteCount();
			reloadAverageVote();
          }
        }
	);
}


/**
 * Replaces the decimal separator in a number. 
 * @param number The number to replace the decimalvalue in.
 * @param currentSeparator The current decimal separator to replace. 
 * @param decimalSeparator The decimal separator to be used in number. 
 * @return Number with the decimal separator as decimalSeparator as a string.  
 */
function setVoteDecimalSeparator(number, currentSeparator, decimalSeparator) {
	number = number + "";
	return number.replace(currentSeparator, decimalSeparator);
}


/**
 * Gets the decimal separator in use in the database.
 * @return The decimal separator in use in the database.  
 */
function getDatabaseDecimalSeparator() {
	var startIndex = 0;
	if (decimalNumber.indexOf("0") == 0) {
		// the decimal number starts with 0
		startIndex = 1;
	}
	return decimalNumber.substring(startIndex, startIndex + 1);
	
}


/**
 * Enables the rating.
 */
function enableRating() {
	if ("Nei" == toggleRating || "No" == toggleRating) {
		$("#iknowbook-vote").hide();
		return;
	}
	// load the average rating
	$.get("/ikbViewer/pls/iknowbook.getVoteAverage?p_document_id=" + getDocumentId() + "&", null, function(data) {
		data = setVoteDecimalSeparator(data, getDatabaseDecimalSeparator(), ".");				
		$("#iknowbook-vote-rate-avg").html("").jrate({
			voteable: false,
			initRate: roundNumber(parseFloat(data))
		});
 	});
	
  // Enable vote
  $("#iknowbook-vote-rate-user").html("").jrate({
    onVote: function(voteValue){
      storeVote(voteValue);
	  disableVoting();
      return true;
    }
  });
  
  loadVoteCount();
}


/**
 * Enables the comment link.
 */
function enableCommentLink() {
 enableLink($(".discussion-action"), function(e){ 
  selectTab(DISCUSSIONS_TAB_INDEX); 
 });
}


/**
 * A tab has been shown. 
 * @param event The event indicating the tab has been shown. 
 * @param ui The tab context. 
 */
function tabShown(event, ui) {
 currentTab = ui.index;
 // fix problem with non ajax edit and settings tab not being shown on load 
 // TODO this is a quick fix for the demo
 if (ui.index == EDIT_TAB_INDEX) {
  $("#iknowbook-panel-edit").show();
 }
 else if (ui.index == SETTINGS_TAB_INDEX) {
  $("#iknowbook-panel-settings").show();
 }
 else if (ui.index == SEARCH_TAB_INDEX) {
	search();
 }
}


/**
 * A tab has been loaded. According to which tab is loaded some links might need to
 * their back link rewritten.
 * @param event The event indicating the tab has loaded. 
 * @param ui The tab context. 
 */
function tabLoaded(event, ui) {
 if (ui.index == DISCUSSIONS_TAB_INDEX) {
  // rewrite the Add discussion link
  rewrite_links(["div.add-discussion a"], getFullPath() + "^tab=" + DISCUSSIONS_TAB_INDEX);
 }
 else if (ui.index == READ_TAB_INDEX) {
  // rewrite the "Svar p� kommentar" link
  rewrite_links(["div.xnCommentActions a:first-child"], getFullPath());
 }
}


/**
 * Loads the about part of the page. 
 * @param docId The id of the document to load the responsible for. 
 */
function loadAbout(docId) {
  loadElementForObject(
    $("#iknowbook-about"), 
    "about", 
    docId,
    function(){
		if(!isSettingsTabShown()) {
			$(".iknowbook-config").hide();
		}
		else {
			enableLink(
			$("#iknowbook-about > .iknowbook-floating-action"), function(e){
				scrollPage(""); 
				selectTab(SETTINGS_TAB_INDEX); 
			});
		}
	}
  );
}


/**
 * Loads the responsible.
 * @param docId The id of the document to load the responsible for. 
 */
function loadResponsible(docId) {
  loadElementForObject(
    $("#iknowbook-responsible"), 
    "responsible", 
    docId,
    function(){
    }
  );
}


// Initializes the iknowbook
$(function(){
  if (isPrinterFriendlyPage() || !access) {
	// no tabs in the printer friendly page or the user has no access to the document
	return;
  }
  
  initFormLinks();
  enableCommentLink();
  hidePersonalAcl();
  
  // Load tabs
  prepareTabs();
  var e_tabs = $("#iknowbook-tabbed-content");
  var tabInstance = e_tabs.tabs({
    selected: currentTab,
    fx: { opacity : "toggle" },
    select: function(e, ui) {
      currentTab = ui.index; 
    },
    show: function(e, ui) { 
      tabShown(e, ui);
    },
    load: function(event, ui) {
     tabLoaded(event, ui);
    }
  });

  loadResponsible(getDocumentId());
  loadAbout(getDocumentId());
  enableRating();
  initScrollLinks();
});


/**
 * Hides the possibility to add personal acls. The personal acl utility is not
 * working with the newest version of ext, hide it until it works with the newest ext version.
 */ 
function hidePersonalAcl() {
	// the book edit form
	$("td.acl").children("a").hide();
}


/**
 * Moves the form links into the form (above the tiny fields)
 */
function initFormLinks() {
	$("div.formLinks").appendTo("div.formLinksContainer");
}


// drag and drop section links


/**
 * Gets the id of the dropped tiny object based on the jquery droppable object. 
 * @param droppable The jquery droppable object to get the tiny id based on. 
 * @return The id for the tiny object some content has been dropped on. 
 */
function getDroppedTinyId(droppable) {
	if (droppable == null || droppable == undefined || droppable.length == 0) {
		return "";
	}
	return $(droppable).find("iframe").attr("id");
}


/**
 * Creates the html code to insert into tiny for a dropped element.
 * @param draggable The jquery draggable dropped onto tiny.
 * @return The html code to insert into tiny based on the draggable as a string. 
 */
function createTinyHtmlCode(draggable) {
	if (draggable == null || draggable == undefined || draggable.length == 0) {
		return "";
	}
	if (draggable.filter("img.bookImgPreview").length > 0) {
		// setting the mce_src prevents tiny from changing the images url
		return '<img alt="' + draggable.attr("alt") + '" src="' + draggable.attr("src") + '" mce_src="' + draggable.attr("src") + '" />';
	}
	else {
		var html = '<a title="' + draggable.html() + '" onClick="' + draggable.attr("onClick") + '" href="' + draggable.attr("href") + '"';
		return html + '>' + draggable.html() + '</a>';
	}
}


$(function() {
	// the z-index of the dialogs increases for each time they are shown
	// set a high zIndex so the links are dragged over the dialogs
	$(".sectionLink").draggable({
		helper: "clone", 
		iframeFix: true,
		revert: "invalid",
		containment: "body",
		zIndex: 1000
	});
	$(".iknowbook-text").droppable({
			drop: function(event, ui) {
				//tinyMCE.getInstanceById(getDroppedTinyId(this)).activate();
				//tinyMCE.execCommand('mceFocus', false, getDroppedTinyId(this));
				//moveCursorToEnd(getDroppedTinyId(this));
				//alert("carriage: " + tinyMCE.getInstanceById(getDroppedTinyId(this)).selection.getBookmark());
				tinyMCE.getInstanceById(getDroppedTinyId(this)).execCommand('mceInsertContent', false, createTinyHtmlCode(ui.draggable));
			},
			accept: ".sectionLink, .iKnowBookLink, img.bookImgPreview"
	});
});


function moveCursorToEnd(editor_id) {
    var inst = tinyMCE.getInstanceById(editor_id);
    tinyMCE.execInstanceCommand(editor_id,"selectall", false, null);
    if (tinyMCE.isMSIE) {
        rng = inst.getRng();
        rng.collapse(false);
        rng.select();
    }
    else {
        sel = inst.getSel();
        sel.collapseToEnd();
    }
}


// iKnowBook dialogs


/**
 * Set to true if the iKnowBook search dialog has been created. 
 */
var iKnowBookSearchDialogCreated = false;


/**
 * Set to true if the iKnowBook image dialog has been created. 
 */
var iKnowBookImageDialogCreated = false;


/**
 * Set to true if the iKnowBook link dialog has been created. This dialog
 * is used to insert links into the text. 
 */
var iKnowBookLinkDialogCreated = false;


/**
 * Indicates whether the url field is in error state. 
 */
var urlFieldErrorState = false;


/**
 * Indicates whether the text field is in error state. 
 */
var linkTextFieldsErrorState = false;


/**
 * Creates the iknowbook link dialog.
 */
function createLinkDialog() {
	$("#insertLinkDialog").dialog({open: function(event, ui) {
			// wrap the dialog in a tag of class "iKnowBookdialog" this way the css theme used for the dialog is
			// used for this dialog not the rest of the page
			if ($(this).parent().parent().attr("class") != "iKnowBookdialog") {
				$(this).parent().wrap('<div class="iKnowBookdialog"></div>');
			}
			
			// clear the input fields, focus the text fields
			$("#textField").attr("value", "");
			$("#urlField").attr("value", "http://");
			$("#textField")[0].focus();
			$("#textField").focus();
			// clear possible error messages
			$("#urlField").attr("border", "1px solid #BDBDBD");
			$("#urlField").attr("border", "1px solid #BDBDBD");
			setInsertLinkErrorMessage("");
		},
		autoOpen: false,
		height: 180,
		width: 350,
		resizable: false,
		zIndex: 100,
		bgiframe: true
	});
	
	// fixes a problem with the jquery dialog, nee to do this or else the
	// height of the dialog is not correct after the dialog is dragged
	$("#insertLinkDialog").dialog("open");
	$("#insertLinkDialog").dialog("close");
	iKnowBookLinkDialogCreated = true;
}


/**
 * Shows the link dialog to add links to text.
 */
function showLinkDialog() {
	if (!iKnowBookLinkDialogCreated) {
		createLinkDialog();
	} 
	$("#insertLinkDialog").dialog("open");
}


/**
 * Sets a error message in the insert linke dialog. 
 * @param message The message to set, empty to clear the error message. 
 */
function setInsertLinkErrorMessage(message) {
	message = message == undefined || message == null ? "" : message;
	$("#insertLinkErrorMessage").html(message);
}


/**
 * Creates the link to insert. 
 */
function createLinkToInsert() {
	var link = '<a title="' + $("#textField").attr("value") + '"';
	link += 'href="' + $("#urlField").attr("value") + '"';
	if ($("#openInNewWindow").attr("checked") == true) {
		link += 'target="_blank"';
	}
	return link + '>' + $("#textField").attr("value") + '</a>';
}


/**
 * Inserts a link from the insert link dialog into the active tinymce editor. 
 */
function insertLink() {
	var valid = true;
	if ($("textField").attr("value") == "") {
		setInsertLinkErrorMessage(noTextError);
		$("textField").css("border", "1px solid red");
		valid = false;
	}
	if ($("#urlField").attr("value") == "") {
		setInsertLinkErrorMessage(noUrlError);
		$("#urlField").css("border", "1px solid red");
		urlFieldErrorState = true;
		valid = false;
	}
	
	if (valid) {
		tinyMCE.selectedInstance.execCommand('mceInsertContent', false, createLinkToInsert());
	}
}


/**
 * The text fields has been focused. 
 */
function textFieldFocused() {
	if (linkTextFieldsErrorState) {
		setInsertLinkErrorMessage("");
		$("#textField").css("border", "1px solid #BDBDBD");
		linkTextFieldsErrorState = false;
	}
}


/**
 * The text field has lost focus.
 */
function textFieldBlur() {
	if ($("#textField").attr("value") == "") {
		setInsertLinkErrorMessage(noTextError);
		$("#textField").css("border", "1px solid red");
		linkTextFieldsErrorState = true;
	}
	else {
		setInsertLinkErrorMessage("");
		$("#textField").css("border", "1px solid #BDBDBD");
		linkTextFieldsErrorState = false;
	}
}


/**
 * The url field has been focused. 
 */
function urlFieldFocused() {
	if (urlFieldErrorState) {
		setInsertLinkErrorMessage("");
		$("#urlField").css("border", "1px solid #BDBDBD");
		urlFieldErrorState = false;
	}

}



/**
 * The url field has lost the focus. Check for valid input
 */
function urlFieldBlur() {
	if ($("#urlField").attr("value") == "") {
		setInsertLinkErrorMessage(noUrlError);
		$("#urlField").css("border", "1px solid red");
		urlFieldErrorState = true;
	}
	else {
		setInsertLinkErrorMessage("");
		$("#urlField").css("border", "1px solid #BDBDBD");
		urlFieldErrorState = false;
	}
}


/**
 * The helper document used for dragging.
 */
var helperElement;


/**
 * Set the images to be draggable. 
 */
function makeImagesDraggable() {
	// use live query to assign this to all the current and future iKnowBookLinks 
	$("img.bookImgPreview").livequery(function() {
		$(this).draggable({
			iframeFix: true,
			revert: "invalid",
			containment: "body",
			helper: function() {
				if (helperElement == undefined) {
					helperElement = $(this).clone()[0];
					document.body.appendChild(helperElement);
					// set a z-index higher than the window so the draggable link is ontop of the window
					// the windows z-index is increased by 1 each time it is opened
					helperElement.style.zIndex = $("#imageDialog").dialog("option", "zIndex") * 100;
				}
				return helperElement;
			},
			stop: function() {
				helperElement = undefined;
			}
		});
	});
}


/**
 * Creates the iknowbook image dialog.
 */
function createImageDialog() {
	$("#imageDialog").dialog({open: function(event, ui) {
			// wrap the dialog in a tag of class "iKnowBookdialog" this way the css theme used for the dialog is
			// used for this dialog not the rest of the page
			if ($(this).parent().parent().attr("class") != "iKnowBookdialog") {
				$(this).parent().wrap('<div class="iKnowBookdialog"></div>');
			}
		},
		autoOpen: false,
		height: 300,
		width: 470,
		minWidth: 100,
		minHeight: 100,
		maxHeight: 1000,
		maxWidth: 1000,
		zIndex: 100,
		bgiframe: true
	});
	
	// fixes a problem with the jquery dialog, nee to do this or else the
	// height of the dialog is not correct after the dialog is dragged
	$("#imageDialog").dialog("open");
	$("#imageDialog").dialog("close");
	iKnowBookImageDialogCreated = true;
	makeImagesDraggable();
}


/**
 * Shows the image dialog for drag and drop images. 
 */
function showImageDialog() {
	if (!iKnowBookImageDialogCreated) {
		createImageDialog();
	}
	$("#imageDialog").dialog("open");
}


/**
 * Set iKnowBook search results to be draggable. 
 */
function enableIKnowBookSearchResultDragging() {
	// use live query to assign this to all the current and future iKnowBookLinks 
	$(".iKnowBookLink").livequery(function() {
		$(this).draggable({
			iframeFix: true,
			revert: "invalid",
			containment: "body",
			helper: function() {
				if (helperElement == undefined) {
					helperElement = $(this).clone()[0];
					document.body.appendChild(helperElement);
					// set a z-index higher than the window so the draggable link is ontop of the window
					// the windows z-index is increased by 1 each time it is opened
					helperElement.style.zIndex = $("#linkDialog").dialog("option", "zIndex") * 100;
				}
				return helperElement;
			},
			stop: function() {
				helperElement = undefined;
			}
		});
	});
}


/**
 * Searches for iKnowBooks.
 */
function searchForIKnowBooks() {
 	var searchString = $("#iKnowBookSearhField").attr("value");
	if (searchString == undefined || searchString == null || searchString == "") {
		return;
	}
	searchString = encodeURIComponent(searchString);
	var url = $("div.iKnowBookSearchUrl a").attr("href");
	if (url == undefined || url == null || url == "") {
		return;
	}
	
	$.get(url + "?p_book_searchstring=" + searchString, null, function(data) {
		$("div.iKnowBookSearchResults").html(data);
		enableIKnowBookSearchResultDragging();
 	});
}


 
/**
 * Creates the iKnowBook search dialog. 
 */
function createIKnowBookSearchDialog() {
	$("#linkDialog").dialog({
		open: function(event, ui) {
			// wrap the dialog in a tag of class "iKnowBookdialog" this way the css theme used for the dialog is
			// used for this dialog not the rest of the page
			if ($(this).parent().parent().attr("class") != "iKnowBookdialog") {
				$(this).parent().wrap('<div class="iKnowBookdialog"></div>');
			}
		},
		autoOpen: false,
		height: 250,
		width: 500,
		minWidth: 100,
		minHeight: 100,
		maxHeight: 1000,
		maxWidth: 1000,
		zIndex: 100,
		bgiframe: true
	});
	
	// fixes a problem with the jquery dialog, nee to do this or else the
	// height of the dialog is not correct after the dialog is dragged
	$("#linkDialog").dialog("open");
	$("#linkDialog").dialog("close");
	
	// set the key listener to check for the enter key
	$('#iKnowBookSearhField').keyup(function(e) {
		if(e.keyCode == 13) {
			searchForIKnowBooks();
		}
    });
	
	iKnowBookSearchDialogCreated = true;
	enableIKnowBookSearchResultDragging();
}


/**
 * Shows the dialog with iKnowBooks used to link to other iKnowBooks.
 */
function showIknowBookDialog() {
	if (!iKnowBookSearchDialogCreated) {
		createIKnowBookSearchDialog();
	}
	$("#linkDialog").dialog("open");
	$('#iKnowBookSearhField')[0].focus();
}


// search 


/**
 * Searches for content in the iknowbook.
 */
function search() {
	selectTab(SEARCH_TAB_INDEX);
	var searchUrl = $("div.searchUrl a").attr("href");
	var searchString = $("#searhField").attr("value");
	searchUrl += "&p_book_searchstring=" + encodeURIComponent(searchString);
	$.ajax({
		type: "GET",
		url: searchUrl,
		cache: false,
		success: function(data) {
			$("#iknowbook-panel-search").html(data);
		},
		failure: function() {
			$("#iknowbook-panel-search").html($("div.searchError").html());
		}
	});
}


/**
 * Set the key listener to search on enter in the search field
 */
$(function() {
	$('#searhField').keyup(function(e) {
		if(e.keyCode == 13) {
			search();
		}
    });
});	



/**
 * Forum post edit onclick
 */
function editPost(href, target, windowProps) {
  var vindu = window.open(href + "&p_form_back_url=location.href",target,windowProps);
  vindu.focus();
  return false;
}


/**
 * Gos to the discussion tab for a subsection.
 * @param subDocId The document id of the subdocument to go to. 
 */
function gotoSubsectionDiscussions(subDocId) {
	call_ikb_popup(subDocId, 'IKNOWBOOK_SECTION_POPUP_DISCUS', DISCUSSIONS_TAB_INDEX);
}


/**
 * Returns the url of the document to convert to pdf. 
 * @param token The token to use. 
 */
function convertToPdfUrl(token) {
	if (isForside) {
		return escape('http://login.demo.iknowbase.com/ikbViewer/page/iknowbook/printer-friendly?p_document_id=' + documentId + '&_ikbUserToken=' + token);
	}
	else {
		return escape('http://login.demo.iknowbase.com/ikbViewer/page/iknowbook/printer-friendly?p_document_id=' + documentId + '&p_subdoc_id=' + subdocID + '&_ikbUserToken=' + token);
	}
}


/**
 * Converts this document to pdf. 
 */
function convertToPdf() {
	var token = dimensionTree_tree.config.loadParams._ikbUserToken;
	//var url = 'http://portaldev.nsfad.local:7778/ikbResource/getHtmlAsPDF.jsp?url='+ convertToPdfUrl(token);
	var url = '/ikbResource/getPDF.jsp?url='+ convertToPdfUrl(token);
	var vindu = window.open(url,'PDF');
}


/**** Ext tree table of content ****/


$(function () {
	if (!access) {
		// user has no access to the document
		return;
	}
	Ext.BLANK_IMAGE_URL = '/ressurs/iknowbook/libs/ext30/resources/images/default/s.gif';
	if (isPrinterFriendlyPage()) {
		// no tabs in the printer friendly page
		return;
	}	
	
	// Inits the tree loader used to load the sections
	var treeLoader = new Ext.tree.TreeLoader({
		dataUrl: sectionLoadUrl,
		setMethod: 'POST',
		baseParams: {
			p_document_id: documentId
		},
		preloadChildren: true
	});

	
	/**
	 * Called when the tree has loaded, used to select the active section in the tree. 
	 * @param treeLoader The tree loader object loading nodes. 
	 * @param node The tree node being loaded. 
	 * @param The response object from the server. 
	 */
	function treeLoaded(treeLoader, node, response) {
		var node = sectionTree.getNodeById(getDocumentId());
		if (node != undefined && node != null) {
			node.select();
		}
		// add the tooltip to the newly loaded elements
		addTooltip();
	}
	
	
	// set the load listener to select the active node on load
	treeLoader.addListener("load", treeLoaded);
	treeLoader.addListener("beforeload", addNodeIdParameter);

	
	/**
	 * Adds the tooltip to the tree elements. 
	 */
	function addTooltip() {
		// set the hover handlers, change the class so the elements do not get multiple 
		// hover functions set. This is called everytime a tree node is expanded and loaded
		$(".sectionIndex").hover(function () {
			$("#sectionTooltip").show().css("padding-right", "2px");
			var padding = $.browser.msie ? 1 : 0;
			$("#sectionTooltip").css("height", $(this).height() - padding);
			var tekstElement = $(".x-tree-node-anchor span", this);
			// add the 2px left padding
			$("#sectionTooltip").css("left", tekstElement.offset()['left'] + 2);
			// add the 1px top padding
			$("#sectionTooltip").css("top", tekstElement.offset()['top'] - 1);
			$("#sectionTooltip").html($(this).text());
			$("#sectionTooltip").css("border", "none");
			var backgroundColor = $(this).hasClass("x-tree-selected") ? "#D9E8FB" : "#EEE";
			$("#sectionTooltip").css("background-color", backgroundColor);
		},
		function () {
			// remove the padding when the tooltip is shown, if not the padding
			// is shown in form of white area on the top left
			$("#sectionTooltip").hide().css("padding-right", "0px");
		}).addClass("sectionIndexHover").removeClass("sectionIndex");
	}

	
	// Init the tree
	var sectionTree = new Ext.tree.TreePanel({
		useArrows: true,
		autoScroll: true,
		animate: true,
		enableDD: true,
		ddGroup: 'sections',
		border: false,
		width: 178,
		autoScroll: false,
		ddScroll: false,
		containerScroll: false,
		// auto create TreeLoader
		loader: treeLoader,
		root: {
			nodeType: 'async',
			text: documentTitle,
			draggable: false,
			id: documentId,
			cls: 'iKnowBookIndex'
		}
	});

	
	// render the tree
	sectionTree.render('dndSections');
	sectionTree.getRootNode().expand();

	
	// add listeners
	sectionTree.addListener("click", clicked);
	sectionTree.addListener("contextmenu", showContextMenu);
	sectionTree.addListener("beforenodedrop", beforeNodeDrop);
	sectionTree.addListener("nodedrop", nodeDropped);

	
	// need to put a element over the tiny iframe so we can drag over it
	sectionTree.dragZone.onBeforeDrag = function () {
		if ($("#ingress").length > 0) {
			$("#ingressCover").show();
			coverTinyField("#ingressCover", "#ingress");
		}
		$("#brodtekstCover").show();
		coverTinyField("#brodtekstCover", "#brodtekst");
		return true;
	};

	
	// hide the cover field when the dragoperation is finsihed
	sectionTree.dragZone.afterDragDrop = function () {
		$("#ingressCover").hide();
		$("#brodtekstCover").hide();
		selectActiveNode();
	};

	
	// hide the cover field when the dragoperation has been repaired
	sectionTree.dragZone.afterInvalidDrop = function () {
		$("#ingressCover").hide();
		$("#brodtekstCover").hide();
		selectActiveNode();
	};

	
	/**
	 * Shows a given cover element over a given tinymce field. This is used so we
	 * can drag elements over the tinymce fields. 
	 * @param coverId The id of the cover element to use. 
	 * @param tinyId The id of the tinymce field to cover. 
	 */
	function coverTinyField(coverId, tinyId) {
		var coverField = $(coverId);
		var tinyField = $(tinyId);
		coverField.height(tinyField.height());
		coverField.width(tinyField.width());
		coverField.css("left", tinyField.offset()['left']);
		coverField.css("top", tinyField.offset()['top']);
		coverField.css("opacity", "0.001");
	}

	
	/**
	 * A node has been dropped, reselect the active chapter.  
	 * @param event The event fired. 
	 */
	function nodeDropped(event) {
		selectActiveNode();
	}

	
	/**
	 * Selects the active node. 
	 */
	function selectActiveNode() {
		var node = sectionTree.getNodeById(getDocumentId());
		if (node != undefined && node != null) {
			node.select();
		}
	}

	
	/**
	 * A node has been moved and dropped.
	 * @param event The event fired. 
	 */
	function beforeNodeDrop(event) {
		var node = event.dropNode.id;
		var target = event.target.id;
		var mode = event.point;
		var parent = "";
		if ("append" == mode) {
			// append node to another parent node
			parent = target;
			target = "";
		}
		else if ("above" == mode || "below" == mode) {
			parent = event.target.parentNode.id;
		}

		$.get("/ikbViewer/pls/iknowbook.moveNode", {
			p_document_id: node,
			p_new_parent_id: parent,
			p_target_id: target,
			p_mode: mode
		},
		function (response) {});

		// send request to save the change in the database
		return true;
	}

	
	/**
	 * Shows the context meny for a given node. 
	 * @param node The node right clicked. 
	 * @param event The Ext.EventObject fired. 
	 */
	function showContextMenu(node, event) {
		var addDisabled = node.attributes.add == "" ? true : false;
		var deleteDisabled = node.attributes.add == "" ? true : false;
		var contextMenu = new Ext.menu.Menu({
			items: [{
				text: addRightClick,
				iconCls: 'addSection',
				cls: 'iKnowBookRightClickElement',
				disabled: addDisabled,
				handler: function (e) {
					addSectionContextMenu(node.attributes.id, sectionFormStyleId);
					return true;
				}
			},
			{
				text: editRightClick,
				iconCls: 'editSection',
				cls: 'iKnowBookRightClickElement',
				disabled: deleteDisabled,
				handler: function (e) {
					editDocument(node.attributes.id, node.attributes.bookId);
					return true;
				}
			},
			{
				text: deleteRightClick,
				iconCls: 'deleteSection',
				cls: 'iKnowBookRightClickElement',
				disabled: deleteDisabled,
				handler: function (e) {
					deleteDocument(node);
					return true;
				}
			}]
		});
		contextMenu.showAt(event.getXY());
	}

	
	/**
	 * Opens a section and shows the edit tab as a response to a context menu click.
	 * @param documentId The document if of the document clicked. 
	 * @param bookId The id of the iKnowBook. 
	 */
	function editDocument(documentId, bookId) {
		if (bookId == undefined && window.location.href.indexOf("forside") > -1) {
			// the book itself has been clicked and we are on the page forside
			// activate the edit tab
			selectTab(EDIT_TAB_INDEX);
		}
		else if (bookId == undefined && window.location.href.indexOf("forside") == -1) {
			// the book itself has been clicked, and we are on a page for one of
			// subsections, forward to the correct page
			call_ikb_popup(documentId, 'IKNOWBOOK_BOOK_POUP_TAB_EDIT');
		}
		else if (window.location.href.indexOf("section") > -1 && subdocID == documentId) {
			// the current section has been clicked
			selectTab(EDIT_TAB_INDEX);
		}
		else {
			// a section has been clicked, forward to the correct page
			call_ikb_popup(bookId, 'IKNOWBOOK_SECTION_POPUP_EDIT_R', documentId);
		}
	}

	
	/**
	 * Opens the form to add a section as a response to a context menu click. 
	 * @param documentId The id of the document clicked. 
	 * @param styleId The id of the form to use to add a section. 
	 */
	function addSectionContextMenu(documentId, styleId) {
		if(styleId == undefined || styleId == null) {
			//  might happen if the form is not found in the plsql function
			return;
		}
		var backUrl = window.location.href;
		backUrl = backUrl.replace("&", "^");

		vindu = window.open('/ikbViewer/page/iknowbook/publish?p_style_id=' + styleId + '&p_kanal=' + channel + '&p_parent_id=' + documentId + '&p_type=' + bookType + '&p_form_back_url=' + backUrl + '&', '_form', 'left=' + (screen.width - 850) / 2 + ', top=' + (screen.height - 550) / 2 + ',scrollbars=yes,resizable=yes,height=550,width=850');
		
		vindu.focus();
	}

	
	/**
	 * Deletes a section as a response to a context menu click.
	 * @param node The node to delete.
	 */
	function deleteDocument(node) {
		var p_document = node.attributes.deldoc;
		var com = p_document.replace(/return /, "");
		eval(com);
	}

	
	/**
	 * A tree node has been clicked, open the section 
	 * @param node The node which wash clicked.
	 * @param event The Ext.EventObject fired. 
	 */
	function clicked(node, event) {
		if (node.attributes.bookId == undefined) {
			// the book itself was clicked
			call_ikb_popup(node.attributes.id + '', 'IKNOWBOOK_BOOK_POPUP');
		}
		else {
			// one of the sections was clicked
			call_ikb_popup(node.attributes.bookId + '', 'IKNOWBOOK_SECTION_POPUP', node.attributes.id + '');
		}

		// somehow the cover fields for the tinymce field are shown on a click, hide them again
		$("#ingressCover").hide();
		$("#brodtekstCover").hide();
		return false;
	}

	// set the drop target for the ingress field
	var ingressDropTarget = new Ext.dd.DropTarget('ingressCover', {
		ddGroup: 'sections',
		notifyDrop: function (ddSource, event, data) {
			var id = sectionTree.getSelectionModel().getSelectedNode().attributes.id;
			var text = sectionTree.getSelectionModel().getSelectedNode().attributes.text;
			insertTinyLink("mce_editor_0", id, text);
			selectActiveNode();
			return true;
		}
	});

	
	// set the drop target for the brodtekst fields
	var brodtekstDropTarget = new Ext.dd.DropTarget('brodtekstCover', {
		ddGroup: 'sections',
		notifyDrop: function (ddSource, event, data) {
			var id = sectionTree.getSelectionModel().getSelectedNode().attributes.id;
			var text = sectionTree.getSelectionModel().getSelectedNode().attributes.text;
			var tinyId = "mce_editor_1";
			insertTinyLink(tinyId, id, text);
			selectActiveNode();
			return true;
		}
	});

	
	/**
	 * Inserts a link to a subsection into a tiny mce field as a response to a drag and drop 
	 * from the table of contents. 
	 * @param tinyId The id of the tiny editor to insert into. 
	 * @param id The id of the subsection to insert. 
	 * @param text The text to insert for the link.
	 */
	function insertTinyLink(tinyId, id, text) {
		var link = id == documentId ? createTinyBookLink(id, text) : createTinySectionLink(id, text);
		tinyMCE.getInstanceById(tinyId).execCommand('mceInsertContent', false, link);
	}

	
	/**
	 * Creates a link for a section to insert into tiny as a response to 
	 * a drag and drop from the table of contents. 
	 * @param id The id of the subsection to insert. 
	 * @param text The text to insert for the link.
	 */
	function createTinySectionLink(id, text) {
		var html = '<a title="' + text + '" href="/ikbViewer/page/iknowbook/section?p_document_id=' + documentId + '&p_subdoc_id=' + id + '"';
		return html + '>' + text + '</a>';
	}

	
	/**
	 * Creates a link for the book itself to insert into tiny as a response to 
	 * a drag and drop from the table of contents. 
	 * @param id The id of the subsection to insert. 
	 * @param text The text to insert for the link.
	 */
	function createTinyBookLink(id, text) {
		var html = '<a title="' + text + '" href="/ikbViewer/page/iknowbook/forside?p_document_id=' + id + '"';
		return html + '>' + text + '</a>';
	}

});


/**
 * Need to add this code to prevent a problem with ext and jquery. This shows if a tree node
 * is dropped on itself or dragged outside of the treepanel. Without this the drag would generate
 * a javascript error.
 */
Ext.lib.Anim = function () {
	var createAnim = function (cb, scope) {
		var animated = true;
		return {
			stop: function (skipToLast) {},
			isAnimated: function () {
				return animated;
			},
			proxyCallback: function () {
				animated = false;
				Ext.callback(cb, scope);
			}
		};
	};
	return {
		scroll: function (el, args, duration, easing, cb, scope) {
			var anim = createAnim(cb, scope);
			el = Ext.getDom(el);
			if (typeof args.scroll.to[0] == 'number') {
				el.scrollLeft = args.scroll.to[0];
			}
			if (typeof args.scroll.to[1] == 'number') {
				el.scrollTop = args.scroll.to[1];
			}
			anim.proxyCallback();
			return anim;
		},
		motion: function (el, args, duration, easing, cb, scope) {
			return this.run(el, args, duration, easing, cb, scope);
		},
		color: function (el, args, duration, easing, cb, scope) {
			var anim = createAnim(cb, scope);
			anim.proxyCallback();
			return anim;
		},
		run: function (el, args, duration, easing, cb, scope, type) {
			var anim = createAnim(cb, scope),
			e = Ext.fly(el, '_animrun');
			var o = {};
			for (var k in args) {
				switch (k) {
				case 'points':
					var by, pts;
					e.position();
					if (by = args.points.by) {
						var xy = e.getXY();
						pts = e.translatePoints([xy[0] + by[0], xy[1] + by[1]]);
					} else {
						pts = e.translatePoints(args.points.to);
					}
					o.left = pts.left;
					o.top = pts.top;
					if (!parseInt(e.getStyle('left'), 10)) {
						e.setLeft(0);
					}
					if (!parseInt(e.getStyle('top'), 10)) {
						e.setTop(0);
					}
					if (args.points.from) {
						e.setXY(args.points.from);
					}
					break;
				case 'width':
					o.width = args.width.to;
					if (args.width.from) {
						e.setWidth(args.width.from);
					}
					break;
				case 'height':
					o.height = args.height.to;
					if (args.height.from) {
						e.setHeight(args.height.from);
					}
					break;
				case 'opacity':
					o.opacity = args.opacity.to;
					if (args.opacity.from)  {
						e.setOpacity(args.opacity.from);
					}
					break;
				case 'left':
					o.left = args.left.to;
					if (args.left.from) {
						e.setLeft(args.left.from);
					}
					break;
				case 'top':
					o.top = args.top.to;
					if (args.top.from) {
						e.setTop(args.top.from);
					}
					break;
				case 'callback':
				case 'scope':
					// jQuery can't handle callback and scope arguments
					break;
				default:
					o[k] = args[k].to;
					if (args[k].from) {
						e.setStyle(k, args[k].from);
					}
					break;
				}
			}
			jQuery(el).animate(o, duration * 1000, undefined, anim.proxyCallback);
			return anim;
		}
	};
} ();


/**
 * Called before sections are loaded by the treeloader. Adds the document id of the 
 * section to be opened to the parameter which the treeloader sends in the request. 
 * @param treeLoader The tree loader calling this. 
 * @param node The node to load sections for. 
 */
function addNodeIdParameter(treeLoader, node) {
	treeLoader.baseParams.p_document_id = node.attributes.id;
	treeLoader.baseParams.p_book_id = documentId;
	// this parameter is needed to find the active section in the tree loader
	treeLoader.baseParams.p_subdoc_id = subdocID;
	// nodes without children are expanded, the hasChildren property is set to false for nodes 
	// without children, the tree 
	if (node.attributes.hasChildren != undefined) {
		return node.attributes.hasChildren;
	}
	return true;
}
	
	
/*** Ext section chooser ***/

/**
 * The ext tree used in the section chooser. 
 */
var sectionChooserTree;


/**
 * The ext window in use in the section chooser. 
 */
var sectionChooserWindow;


/**
 * Shows the section loader window. 
 */
function showSectionChooser() {
	var sectionChooserTreeLoader = createSectionTreeLoader();
	sectionChooserTree = createTree(sectionTreeRootElement(), sectionChooserTreeLoader);
	sectionChooserWindow = createWindow([sectionChooserTree]);
	sectionChooserWindow.show();
	sectionChooserTree.getRootNode().expand();
}


/**
 * Create a ext window. 
 * @param itemElements The items to add to the window. 
 * @return The window created. 
 */
function createWindow(itemElements) {
	return new Ext.Window({
		title: sectionChooserWindowTitle,
		id: 'sectionChooser',
		border: false,
		layout: 'border',
		width: 300,
		height: 200,
		renderTo: Ext.getBody(),
		layout: 'fit',
		modal: true,
		items: itemElements
	});
}


/**
 * Creates a section chooser tree. 
 * @param rootElement The root element to use. 
 * @param treeLoader The tree loader to use.
 * @return The ext tree created. 
 */ 
function createTree(rootElement, treeLoader) {
	return new Ext.tree.TreePanel({
		useArrows: true,
		autoScroll: true,
		animate: true,
		enableDD: false,
		containerScroll: true,
		border: false,
		width: 178,
		autoScroll: true,
		containerScroll: true,
		// auto create TreeLoader
		loader: treeLoader,
		root: rootElement,
		buttons: [{
			text: allButtonText,
			handler: function () {
				allButtonClicked();
			}
		},
		{
			text: okButtonText,
			handler: function () {
				okButtonClicked();
			}
		},
		{
			text: cancelButtonText,
			handler: function () {
				sectionChooserWindow.close();
			}
		}]
	});
}


/**
 * Creates the root element for the section chooser tree. 
 * @return The root element. 
 */
function sectionTreeRootElement() {
	return {
		nodeType: 'async',
		text: documentTitle,
		draggable: false,
		id: documentId,
		"checked": false,
		cls: 'iKnowBookIndex sectionChooser'
	};
}


/**
 * Creates the ext tree loader for the section tree. 
 * @param return The tree loader created. 
 */ 
function createSectionTreeLoader() {
	var loader = new Ext.tree.TreeLoader({
		dataUrl: sectionLoadUrl,
		setMethod: 'POST',
		baseParams: {
			p_document_id: documentId,
			p_mode: "checked",
			p_documents: documentsToShow
		},
		preloadChildren: true
	});

	// set the load listener to select the active node on load
	loader.addListener("beforeload", addNodeIdParameter);
	return loader;
}


/**
 * The ok button in the section chooser has been clicked.
 */ 
function okButtonClicked() {
	var sections = '',
	selNodes = sectionChooserTree.getChecked();
	Ext.each(selNodes, function (node) {
		if (sections.length > 0) {
			sections += ', ';
		}
		sections += node.id;
	});
	call_ikb_popup(documentId, 'IKNOWBOOK_PRINTER_CHOSEN_SECT', escape(sections));
	sectionChooserWindow.close();
}


/**
 * The all button in the section chooser has been clicked. 
 */
function allButtonClicked() {
	call_ikb_popup(documentId, 'IKNOWBOOK_PRINTER_CHOSEN_SECT', '');
	sectionChooserWindow.close();
}

