/*
 * Copyright (C) butor.com. All rights reserved.
 *
 * This software is published under the terms of the GNU Library General
 * Public License (GNU LGPL), a copy of which has been included with this
 * distribution in the LICENSE.txt file. 
 */

var MESSAGES_PANE = "msg_pane";
var WYSIWYG_REQUIREMENT_MSG = 'Oh Sorry! the WYSIWYG editor work only with : \n- Internet Explorer 6.0+ \n- Mozilla/5.0+ (Mozilla, Netscape, Firefox, etc) \n- Firefox 1.5+';

function selectResource(curVal, selectHandler, resType) {
	var args = {
		"res" : "",
		"uid" : ""
	};
	
	openDialog("select_res", ACTIONS_PATH +"cr.do?resType=" +resType +"&dirName=" +curVal, args, selectHandler, true);
}

function aclProps(uid) {
	var args = {
		"uid" : uid
	};
	
	openDialog("acl_props",  ACTIONS_PATH +"acl.do", args, aclPropsDone);
}

function aclPropsDone(args) {	
	//TODO alert("acl.js/aclPropsDone(): args=" +args);
}

function documentMetadata(uid, callback) {
	var args = {
		"uid" : uid,
		"callback" : callback
	};
	
	openDialog("document_metadata",  ACTIONS_PATH +"documentmetadata.do?uid=" + uid, args, documentMetadataDone);
}

function documentMetadataDone(args, props) {
	if (args != null) {
		if (args['callback'] != null) {
			// save the uid...
			props['uid'] = args['uid'];
			// call the callback
			args['callback'](props);
		}
	}
}

function groups() {
	openDialog("groups",  ACTIONS_PATH +"dialog.do?dialog=groups", null, null);
}

function users(username) {
	var args={"username":username};
	openDialog("users",  ACTIONS_PATH +"dialog.do?dialog=users", args, null);
}

function initWiki() {
	wiki_initDwr();
	trackMouseClick();
	
	var msgPane = getElement(MESSAGES_PANE);
	if (msgPane) {
		// center on parent
		var body = document.body;
		var x = 0;
		var y = 0;
		if (!document.all) {
			x = (body.offsetWidth - msgPane.offsetWidth) / 2;
			y = 30;
		} else {
			x = (document.outerWidth - msgPane.offsetWidth) / 2;
			y = 30;
		}

		var st = getStyle(MESSAGES_PANE);
//TODO		st.left = x +'px';
//		st.top = y +'px';

		disableWindow();
		showhide(MESSAGES_PANE, 1);
	}
	
	return true;
}

function search(text) {
	window.location='search.do?searchText='+text;
}

function editWysiwyg(uid) {
	if (!(navInfo.is_ie6up || navInfo.is_nav5up)) {
		alert(WYSIWYG_REQUIREMENT_MSG);
		return;
	}
	window.location='editpage.do?editType=wysiwyg&uid=' +uid;
}

function editHtml(uid) {
	window.location='editpage.do?editType=text&uid=' +uid;
}

// TOC stuff ===================================
var _tocState = 'none';
var _tocTargets = new Array();
var _toc = null;
var _toc_top = 30;
var _toc_prev_top = _toc_top;
var _toc_timer = null;

function toc() {
	if (!_toc) {
		// first time, so create the Table Of Content
		createTOC();
		_toc = getElement('toc');
		if (!_toc) {
			return;
		}
	}

	_tocState = (_tocState == 'none') ? 'block' : 'none';
	_toc.style.display = _tocState;	
	var iconClass = "selOn";
	if (_tocState != "block") {
		iconClass = "selOff";
	}
	var tocIcon = getElement("toc_icon");
	setAttribute(tocIcon, "alt", iconClass);
	setAttribute(tocIcon, "class", iconClass);

	if (_tocState != "block") {
		stopToc();
	} else {
		moveToc();
	}
	
	registerEvent(window, "scroll", moveToc);
}

function stopToc() {
	if (_toc_timer != null) {
		clearTimeout(_toc_timer);
	}
}

function moveToc() {
	var pos = 0;
	if (document.body) {
		pos = document.body.scrollTop
	} else if (window.innerHeight) {
		pos = window.pageYOffset
	} else if (document.documentElement && document.documentElement.scrollTop) {
		pos = document.documentElement.scrollTop
	}

	pos += 20;

	if (pos != _toc_prev_top) {
		_toc.style.top = pos;
	}
	_toc_prev_top = pos;
	//_toc_timer = setTimeout('moveToc()',500);
}

function createTOC() {
	// find the nodes to be added to the Page TOC
	findTargets(getElement("wiki_document"));

	if (_tocTargets.length == 0) {
		return;
	}

	// TOP anchor
	var topAnchor = document.createElement('a');
	topAnchor.name = 'tocTop';
	document.body.insertBefore(topAnchor, document.body.childNodes[0]);
	
	// bottom anchor
	var bottomAnchor = document.createElement('a');
	bottomAnchor.name = 'tocBottom';
	document.body.appendChild(bottomAnchor);

	// TOC
	var tocDiv = document.createElement('div');
	tocDiv.id = 'toc';

	tocDiv.appendChild(document.createTextNode("Contents [ "));
	// ---- hide link
	var tocHideLink = document.createElement('a');
	tocDiv.appendChild(tocHideLink);
	tocHideLink.innerHTML = ' hide ';
	tocHideLink.href = 'javascript:toc()';
	// ---- spacer
	tocDiv.appendChild(document.createTextNode(" | "));
	// ---- top link	
	var tocTopLink = document.createElement('a');
	tocDiv.appendChild(tocTopLink);
	tocTopLink.innerHTML = ' top ';
	tocTopLink.href = '#tocTop';
	// ---- top image
	//var img = document.createElement('img');
	//img.src = ACTIONS_PATH +'theme.do?elem=toc_top.gif';
	//tocDiv.appendChild(img);
	// ---- spacer
	tocDiv.appendChild(document.createTextNode(" | "));
	// ---- bottom link
	var tocBottomLink = document.createElement('a');
	tocDiv.appendChild(tocBottomLink);
	tocBottomLink.innerHTML = ' bottom ';
	tocBottomLink.href = '#tocBottom';
	//var img = document.createElement('img');
	//img.src = ACTIONS_PATH +'theme.do?elem=toc_bottom.gif';
	//tocDiv.appendChild(img);
	tocDiv.appendChild(document.createTextNode(" ]"));

	// table of contents elements
	for (var i = 0; i < _tocTargets.length; i++) {
		tocTarget = _tocTargets[i];
		if (tocTarget.id == '') {
			tocTarget.id = 'pageToc' + i;
		}
		
		try {
			var newItem = document.createElement('li');
			var newLink = document.createElement('a');
			newLink.innerHTML = tocTarget.innerHTML;
			newLink.href = '#' + tocTarget.id;
			var level = tocTarget.nodeName.toUpperCase();
			setAttribute(newItem, "class", 'tocLevel' +level);
			newItem.appendChild(newLink);
			tocDiv.appendChild(newItem);
			
		} catch (e) {
			//TODO 
			// IE doesnt like "newLink.innerHTML = tocTarget.innerHTML;" 
			// if tocTarget.innerHTML is not a simple TEXT note.
		}
	}
	  
/*
	// Botom link
	var tocBottomDiv = document.createElement('div');
	setAttribute(tocBottomDiv, "class", 'tocTopBottomLink');
	var tocBottomLink = document.createElement('a');
	tocBottomDiv.appendChild(tocBottomLink);
	tocBottomLink.innerHTML = 'Bottom ';
	tocBottomLink.href = '#tocBottom';
	var img = document.createElement('img');
	img.src = ACTIONS_PATH +'theme.do?elem=toc_bottom.gif';
	tocBottomDiv.appendChild(img);
	tocDiv.appendChild(tocBottomDiv);
*/
	document.body.appendChild(tocDiv);
}

function findTargets(node) {
	if (!node) {
		return;
	}
    name = node.nodeName.toLowerCase();
    if (name == "h1" || name == "h2" || name == "h3" || name == "h4") {
      _tocTargets.push(node);
    }
    if (node.childNodes) {
    	var nodes = node.childNodes;
		for (var i = 0; i < nodes.length; i++) {
			findTargets(nodes[i]);
		}
	}
}
  
function goTocTop() {
	document.location='#tocTop';
}
function goTocBottom() {
	document.location='#tocBottom';
}


// build search index ------------------
var BUILD_SEARCH_INDEX_STATUS = '<img src="theme.do?elem=progress.gif"> Building search index: ';
function buildSearchIndex() {
	showMsg(BUILD_SEARCH_INDEX_STATUS +" ...", true);
	DwrWiki.buildSearchIndex(bsiStatus);
}

function bsiStatus(prcnt) {
	if (prcnt == null) {
		clearMsg();
		return;
	}

	if (prcnt == 100) {
		showMsg(BUILD_SEARCH_INDEX_STATUS +prcnt +"%");
		clearMsg();
		return;
	}
	
	showMsg(BUILD_SEARCH_INDEX_STATUS +prcnt +"%", true);
	setTimeout(function () {
		DwrWiki.getBuildSearchIndexProgressPrcnt(bsiStatus);
		}, 1000);
}

// publish/unlock -------------------------------------

function unlock(uid, showOriginal) {
	showMsg('Unlocking ' + uid + ' ...');
	DwrWiki.unlock(uid, createUnlockHandler(uid, showOriginal));
}

function createUnlockHandler(uid, showOriginal) {
	return function(resp) {
		if (resp) {
			showMsg('Unlock succeeded.');
			removeLockArtifacts(uid);
			if (showOriginal == "1") {
				window.location = 'showpage.do?uid=' + uid;
			}
		}
	}
}

function publish(uid, showOriginal) {
	showMsg('Publishing ' + uid + ' ...');
	DwrWiki.publish(uid, createPublishHandler(uid, showOriginal));
}

function createPublishHandler(uid, showOriginal) {
	return function(resp) {
		if (resp) {
			showMsg('Publish succeeded.');
			removeLockArtifacts(uid);
			if (showOriginal == "1") {
				window.location = 'showpage.do?uid=' + uid;
			}
		}
	}
}

function removeLockArtifacts(uid) {
	var elem = getElement('lock_' + uid);
	if (elem) {
		elem.parentNode.removeChild(elem);
	}
/*A.S. does not exists yet
	var elem = getElement('unlock_' + uid);
	if (elem) {
		elem.parentNode.removeChild(elem);
	}
		
	var elem = getElement('publish_' + uid);
	if (elem) {
		elem.parentNode.removeChild(elem);
	}
*/
}

var __wiki_initDwrDone = false;
function wiki_initDwr() {
	if (DWREngine && !__wiki_initDwrDone) {
		DWREngine.setPreHook(function() {com_showIfNoMsg("Working ...");});
		DWREngine.setPostHook(function() {clearMsg();});
		DWREngine.setTextHtmlHandler(function() {showMsg('Session timed out! Please login and retry again.');});
	}
}