/*
 * 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. 
 */

// default URL path
// this can be updated related to a web app or root domain
// by using setContextName()
var PORTAL_CONTEXT="";
var ACTIONS_PATH = PORTAL_CONTEXT;
var IMAGES_PATH = ACTIONS_PATH +"html/butor_wiki/images/";
var JSP_PATH = ACTIONS_PATH +"html/butor_wiki/jsp/";

function setContextName(name) {
	ACTIONS_PATH = PORTAL_CONTEXT +name +"/";
	IMAGES_PATH = ACTIONS_PATH +"html/butor_wiki/images/";
	JSP_PATH = ACTIONS_PATH +"html/butor_wiki/jsp/";
}

var ELEMENT_NODE=1;    // with the following properties and values.
var ATTRIBUTE_NODE=2;  // Note that these are HTML node types only.
var TEXT_NODE=3;       // For XML-specific nodes, you need to add
var COMMENT_NODE=8;    // other constants here.
var DOCUMENT_NODE=9;
var DOCUMENT_FRAGMENT_NODE=11;

var px = "px";
var _xcoord = 0;
var _ycoord = 0;

var navInfo = new NavInfo();

var is_ie = navInfo.is_ie;

function getElement(name) { 
	var elem = null;
	
	if (document.getElementById) {
		elem = document.getElementById(name);
	}
	if (!elem && document[name]) { 
		elem = document[name];
	}
	if (!elem && document.all) { 
		elem = document.all[name];
	}
	if (!elem && document.layers) { 
		elem = document.layers[name];
	}
	if (!elem && document.getElementsByTagName) {
        var collection = document.getElementsByTagName(name);
        if (collection.length > 0) {
            elem = collection[0];
        }
	}
	return elem;
}

function getStyle(name) {
	var elem = getElement(name);
	if (elem) {
		return elem.style;
	}
	return null;
}

function showhide(name,status) {
	st = getStyle(name);
	if (!st) {
		return;
	}
	
	st.display=(status==0?"none":"block");
	if (document.layers) {
		st.visibility=(status==0?"hide":"show");
	} else {
		st.visibility=(status==0?"hidden":"visible"); 
	}
}

function toggleElm(name) {
	st = getStyle(name);
	if (!st) {
		return;
	}
	flag = !(st.visibility == (document.layers ? "hide" : "hidden"));
	showhide(name, (flag? 0: 1));
	return !flag; // return new status
}


// ===========================

function registerEvent(element, eventName, func) {
	if (is_ie) {
		element.attachEvent("on" + eventName, func);
	} else {
		element.addEventListener(eventName, func, true);
	}
}
function unregisterEvent(element, eventName, func) {
	if (is_ie) {
		element.detachEvent("on" + eventName, func);
	} else {
		element.removeEventListener(eventName, func, true);
	}
}
function stopEvent(ev) {
	if (is_ie) {
		ev.cancelBubble = true;
		ev.returnValue = false;
	} else {
		ev.preventDefault();
		ev.stopPropagation();
	}
}

//---------------------------
function trackMouseClick() {
	registerEvent(document, "click", mouseClickOnDocument);
}
//---------------------------
var _doc_click_listeners = {};
function registerForDocClick(id, listener) {
	_doc_click_listeners[id] = listener;
}
function cancelDocClick(id) {
	_doc_click_listeners[id] = null;
}
function mouseClickOnDocument(event) {
	for (id in _doc_click_listeners) {
		var listener = _doc_click_listeners[id];
		if (listener != null) {
			listener(null);
			_doc_click_listeners[id] = null;
		}
	}
}

//============================
function trackMouseMove() {
	registerEvent(document, "mousemove", mouseMove);
}
//------------------------
function getElementXY(elem) {
	var posx = findPosX(elem);
	var posy = findPosY(elem);
	return [posx, posy]
}

function getPos(elem) {
	var pos = { x:elem.offsetLeft, y:elem.offsetTop };
	if (elem.offsetParent) {
		var pPos = getPos(elem.offsetParent);
		pos.x += tPos.x;
		pos.y += tPos.y;
	}
	return pos;
}

function findPosX(elem) {
	var pos = 0;
	if (elem.offsetParent) {
		while (elem.offsetParent) {
			pos += elem.offsetLeft
			elem = elem.offsetParent;
		}
	} else if (elem.x) {
		pos += elem.x;
	}
	return pos;
}

function findPosY(elem) {
	var pos = 0;
	if (elem.offsetParent) {
		while (elem.offsetParent) {
			pos += elem.offsetTop
			elem = elem.offsetParent;
		}
	} else if (elem.y) {
		pos += elem.y;
	}
	return pos;
}

// ======================
function mouseMove(e) {
  if( !e ) {
    if( window.event ) {
      //DOM
      e = window.event;
    } else {
      //TOTAL FAILURE, WE HAVE NO WAY OF REFERENCING THE EVENT
      return;
    }
  }
  
  if( typeof( e.pageX ) == 'number' ) {
    //NS 4, NS 6+, Mozilla 0.9+
    _xcoord = e.pageX;
    _ycoord = e.pageY;
    
  } else {
    if( typeof( e.clientX ) == 'number' ) {
      //IE, Opera, NS 6+, Mozilla 0.9+
      //except that NS 6+ and Mozilla 0.9+ did pageX ...
      _xcoord = e.clientX;
      _ycoord = e.clientY;
      if( !( ( window.navigator.userAgent.indexOf( 'Opera' ) + 1 ) ||
        ( window.ScriptEngine && ScriptEngine().indexOf( 'InScript' ) + 1 ) ||
        window.navigator.vendor == 'KDE' ) ) {
        if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
          //IE 4, 5 & 6 (in non-standards compliant mode)
          _xcoord += document.body.scrollLeft;
          _ycoord += document.body.scrollTop;
        } else if( document.documentElement &&
          ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
          //IE 6 (in standards compliant mode)
          _xcoord += document.documentElement.scrollLeft;
          _ycoord += document.documentElement.scrollTop;
        }
      }
    } else {
      //TOTAL FAILURE, WE HAVE NO WAY OF OBTAINING THE
      //MOUSE COORDINATES
      return;
    }
  }
  
  //status("x=" +xcoord +", y=" +ycoord);
}

function trim(s) {
	while (s.substring(0,1) == ' ') {
		s = s.substring(1,s.length);
	}
	while (s.substring(s.length-1,s.length) == ' ') {
		s = s.substring(0,s.length-1);
	}
	return s;
}

function comm_createToolButton() {
	if (is_ie) {
		return document.createElement("<input type='button'>");
	} else {
		var el = document.createElement("input");
		el.setAttribute("type", "button");
		return el;
	}
}

function createIFrame(id) {
	var elem = getElement(id);
	if (elem != null) {
		return elem;
	}
	
	if (!document.createElement) {
		return null;
	}
	
	// create the IFrame element
	try {
		var tempIFrame=document.createElement('iframe');
		tempIFrame.setAttribute('id',id);
		tempIFrame.style.border='0px';
		tempIFrame.style.width='0px';
		tempIFrame.style.height='0px';
		elem = document.body.appendChild(tempIFrame);
		
		if (document.frames) {
			// this is for IE5 Mac, because it will only
			// allow access to the document object
			// of the IFrame if we access it through
			// the document.frames array
			elem = document.frames[id];
		}
		
	} catch(exception) {
		// This is for IE5 PC, which does not allow dynamic creation
		// and manipulation of an iframe object. Instead, we'll fake
		// it up by creating our own objects.
		iframeHTML='\<iframe id="' +id +'" style="';
		iframeHTML+='border:0px;';
		iframeHTML+='width:0px;';
		iframeHTML+='height:0px;';
		iframeHTML+='"><\/iframe>';
		document.body.innerHTML+=iframeHTML;
		elem = new Object();
		elem.document = new Object();
		elem.document.location = new Object();
		elem.document.location.iframe = getElement(id);
		elem.document.location.replace = function(location) {
			this.iframe.src = location;
		}
	}
	
	return elem;
}

function getIFrameDoc(iframe) {
	if (iframe.contentDocument) {
		// For NS6
		return iframe.contentDocument; 
		
	} else if (iframe.contentWindow) {
		// For IE5.5 and IE6
		return iframe.contentWindow.document;
		
	} else if (iframe.document) {
		// For IE5
		return iframe.document;
	}
	return null;
}


// loaded js, css modules flag
var _loadedModules = "";
/**
 * load one or many js, css modules
 */
function loadModule() {
	if (!document.getElementById) {
		return;
	}
	
	for (var ii=0; ii<arguments.length; ii++){
		var module = arguments[ii]
		if (_loadedModules.indexOf(module) > -1) {
			// already loaded
			return;
		}

		var elem;
		var moduleName = module.toLowerCase();
		if (moduleName.indexOf(".js") > -1) {
			elem = document.createElement('script')
			elem.setAttribute("type","text/javascript");
			elem.setAttribute("src", module);
			
		} else if (moduleName.indexOf(".css") > -1) {
			elem = document.createElement("link")
			elem.setAttribute("rel", "stylesheet");
			elem.setAttribute("type", "text/css");
			elem.setAttribute("href", file);
		}
	
		if (elem) {
			//document.getElementsByTagName("head").item(0).appendChild(elem);
			var hostElem = getElement("head").item(0);
			if (! hostElem) {
				hostElem = getElement("body");
			}
			if (hostElem) {
				hostElem.appendChild(elem);
				_loadedModules += module +", ";
			}
		}
	}
}

// msg ------------------------------------
var _msgDiv = null; // our IFrame object
var _hideMsgTimer = null;
var _stickyMsg = false;
function showMsg(msg, stickyMsg) {
	if (_msgDiv == null) {
		if (!document.createElement) {
			return true;
		}
		_msgDiv = document.createElement("div");
		_msgDiv.id = "floating-msg-panel";
		document.body.appendChild(_msgDiv);
	}
	_stickyMsg = stickyMsg;
	_msgDiv.innerHTML = '&nbsp;&nbsp;' +msg +'&nbsp;&nbsp;';
	_msgDiv.style.visibility = (document.layers ? "show" : "visible");

	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 += 5;

	var left = (getWindowWidth() - _msgDiv.offsetWidth) / 2;
	
	_msgDiv.style.left = left;
	_msgDiv.style.top = pos;
}
function com_showIfNoMsg(message) {
	if (!_msgDiv || _msgDiv.style.visibility != (document.layers ? "show" : "visible")) {
		showMsg(message);
	}
}
function clearMsg() {
	if (_msgDiv == null || _stickyMsg) {
		return;
	}

	if (_hideMsgTimer) {
		clearTimeout(_hideMsgTimer);
	}
	// just wait a litle before hide to avoid flickering	
	_hideMsgTimer = setTimeout(hideMsg, 1200);
}

function hideMsg() {
	_stickyMsg = false;
	if (_msgDiv == null) {
		return;
	}
	
	_msgDiv.innerHTML = "";
	_msgDiv.style.visibility = (document.layers ? "hide" : "hidden");	
//	_msgDiv.style.display = "none";
}

function clearSelect(list) {
	if (!list || !list.options) {
		return;
	}
	while (true) {
		if (list.options.length == 0) {
			break;
		}
		list.options[0] = null;
	}
}

function tokenize(what, sep) {
	if (what == null) {
		return null;
	}
	
	var tokens = [];
	if (sep == null || what.indexOf(sep) == -1) {
		tokens.push(what);
		return tokens;
	}
	
	tokens = what.split(sep);
	return tokens;
}

function toggleMenu(triggerElem, menuName, event) {

	//TODO	
	cancelDocClick(menuName);	
	mouseClickOnDocument(); // hide any poup
	
	var elem = getElement(menuName);
	var st = getStyle(menuName);
	flag = (st.visibility==(document.layers?"show":"visible"));
	if (flag || !triggerElem) {
		showhide(menuName, 0);
		return;
	}

	// show before calculating position because dimensions may be zero
	// if menu is hidden.
	showhide(menuName, 1);

	pos = getElementXY(triggerElem);
	var heightOffset = 10;
	if (triggerElem.offsetHeight) {
		heightOffset = triggerElem.offsetHeight;
	}
	st.top = (pos[1] +heightOffset) +px;
	st.left = pos[0] +px;
	
	var menuWidth = elem.offsetWidth;
	var docWidth = document.body.offsetWidth;
	
	if (pos[0]+ menuWidth > docWidth) {
		var left = pos[0] -((pos[0] + menuWidth) -docWidth);
		if (left<0) {
			left = 0;
		}
		st.left = left +px;
	}

	if (is_ie) {
		stopEvent(window.event);
	}
	registerForDocClick(menuName, function () {toggleMenu(triggerElem, menuName);});	
}

function getAttribute(elem, attr) {
	if (is_ie && attr == "class") {
		attr = "className";
	}
	return elem.getAttribute(attr);
}
function setAttribute(elem, attr, value) {
	if (is_ie && attr == "class") {
		attr = "className";
	}
	elem.setAttribute(attr, value);
}
function clearAttributes(elem, attrs) {
	for (var ii=0; ii<attrs.length; ii++) {
		var attr = attrs[ii];
		if (is_ie && attr == "class") {
			attr = "className";
		}
		elem.removeAttribute(attr);
	}
}
function switchCheckbox(chk) {
	var elem = getElement(chk);
	elem.checked = !elem.checked;
}

function NavInfo() {
// Ultimate client-side JavaScript client sniff.
// (C) Netscape Communications 1999.  Permission granted to reuse and distribute.
// Revised 20 April 98 to add is_nav5up and is_ie5up (see below).

// This peace come from http://www.k-state.edu/tools/browser_type/browser_type.html
//    ...
//
// See http://www.it97.de/JavaScript/JS_tutorial/bstat/navobj.html and
// http://www.it97.de/JavaScript/JS_tutorial/bstat/Browseraol.html
// for detailed lists of userAgent strings.

	// convert all characters to lowercase to simplify testing
	var agt = navigator.userAgent.toLowerCase();

	// *** BROWSER VERSION ***
	// Note: On IE5, these return 4, so use is.ie5up to detect IE5.
	var is_major = parseInt(navigator.appVersion);

	var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
				&& (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
				&& (agt.indexOf('webtv')==-1));
				
	var is_nav_like = (!is_nav && agt.indexOf('mozilla')!=-1);
	
	var is_nav5 = (is_nav && (is_major == 5));
	var is_nav5up = (is_nav && (is_major >= 5));

	var is_nav_like5 = (is_nav_like && (is_major == 5));
	var is_nav_like5up = (is_nav_like && (is_major >= 5));

	var is_ie = false;
	var re = new RegExp("msie [0-9]\.[0-9]");
	var ma = re.exec(agt);
	if (ma != null) {
		is_ie = true;
		var ver = agt.substring(ma.index +5, ma.index +5 +3);
		is_major = parseInt(ver);
	}
  
	var is_ie6  = (is_ie && ((is_major == 5) || (agt.indexOf("msie 5.0")!=-1) || (agt.indexOf("msie 6.0")!=-1)));
	var is_ie6up  = (is_ie && (is_major >= 5));

	var is_opera = (agt.indexOf("opera") != -1);
	var is_webtv = (agt.indexOf("webtv") != -1);

	// *** PLATFORM ***
	var is_win   = ( (agt.indexOf("win")!=-1) || (agt.indexOf("16bit")!=-1) );
	var is_mac	= (agt.indexOf("mac")!=-1);
	var is_linux = (agt.indexOf("inux")!=-1);
	
	this.is_nav = is_nav;
	this.is_nav5up = is_nav5up;

	this.is_nav_like = is_nav_like;
	this.is_nav_like5up = is_nav_like5up;

	this.is_ie = is_ie;
	this.is_ie6 = is_ie6;
	this.is_ie6up = (is_ie6 || is_ie6up);
}

function getWindowWidth() {
	var myWidth = 400;  // guess
	if (typeof(window.innerWidth) == 'number') {
		//Non-IE
		myWidth = window.innerWidth;
	} 
	else if (document.documentElement && document.documentElement.clientWidth) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
	} 
	else if (document.body && document.body.clientWidth) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
	}
	return myWidth;
}

function log(msg) {
	if (console) {
		console(msg);
	}
}
