/* {{{ Copyright 2003,2004 Adam Donnison <adam@saki.com.au>

    This file is part of the collected works of Adam Donnison.

    This file is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This file is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

}}} */
	
// If we are an IE window, set undefined to null.  This is an ECMAscript
// standard, but then MS makes its own standards.
if (navigator.userAgent.indexOf('MSIE') != -1)
  var undefined = null;

/* {{{ function center_window
 * Create the window options clause required to ensure a window is
 * centered over the calling window.  A width or height of 0 or less
 * results in using the corresponding value for the parent window.
 * e.g. 0,0 results in a window exactly the same size and overlapping
 * the parent exactly.
 */
function center_window(width, height)
{
  var ix = window.outerWidth;
  var iy = window.outerHeight;
  var mx = window.screenX;
  var my = window.screenY;
  var result;

  var cx;
  var cy;

  if (width <= 0) {
    width = ix;
    cx = mx;
  } else {
    mx += ( ix / 2 );
    mx -= ( width / 2 );
    cx = Math.round(mx);
  }
  if (height <= 0) {
    cy = my;
    height = iy;
  } else {
    my += ( iy / 2 );
    my -= ( height / 2 );
    cy = Math.round(my);
  }

  result = 'screenX=' + cx + ',screenY=' + cy
  + ',outerHeight=' + height + ',outerWidth=' + width;
  return result;
}
//}}}

//{{{1 Class Comparable
// Define new Comparable object capable of being used to store
// data in an array.

//{{{2 constructor CompItem
function CompItem(key, data)
{
  this.key = key;
  this.data = data;
  this.compare = comp_keys;
  this.equals = comp_equal;
}
//2}}}

//{{{2 function comp_keys
// Compare function to compare two Comparable objects
function comp_keys(target)
{
  if (this.key == target.key)
    return 0;
  if (this.key < target.key)
    return -1;
  return 1;
}
//2}}}

//{{{2 function comp_equal
function comp_equal(target)
{
  if (this.key == target)
    return true;
  return false;
}
//2}}}


// {{{2 Comparison array class constructor
function Comparable()
{
  this.list = new Array();
  this.add = ca_add;
  this.find = ca_find;
  this.length = ca_length;
  this.get = ca_get;
	this.search = ca_search;
  this.count = 0;
}
//2}}}

//{{{2 function ca_add
function ca_add(key, data)
{
	var last_id = this.search(key);
	if (last_id != -1) {
		this.list[last_id] = new CompItem(key, data);
	} else {
		this.list[this.count] = new CompItem(key, data);
		this.count++;
	}
  // this.list.push(new CompItem(key, data));
}
//2}}}

//{{{2 function ca_find
function ca_find(key)
{
  var end = this.list.length;
  for ( var i = 0; i < end; i++)
  {
    cp = this.list[i];
    if (cp.equals(key))
      return cp.data;
  }
  return undefined;
}
//2}}}

//{{{2 function ca_search
function ca_search(key)
{
  var end = this.list.length;
  for ( var i = 0; i < end; i++)
  {
    cp = this.list[i];
    if (cp.equals(key))
      return i;
  }
  return -1;
}
//2}}}

//{{{2 function ca_length
function ca_length()
{
  return this.list.length;
}
//2}}}

//{{{2 function ca_get
function ca_get(id)
{
  return this.list[id];
}
//2}}}
//1}}}

//{{{1 Class HTMLex
//{{{2 Constructor HTMLex
function HTMLex()
{
  this.addTable = _HTMLaddTable;
  this.addRow = _HTMLaddRow;
  this.addHeader = _HTMLaddHeader;
  this.addHeaderNode = _HTMLaddHeaderNode;
  this.addCell = _HTMLaddCell;
  this.addCellNode = _HTMLaddCellNode;
  this.addTextInput = _HTMLaddTextInput;
  this.addHidden = _HTMLaddHidden;
  this.addTextNode = _HTMLaddTextNode;
  this.addNode = _HTMLaddNode;
  this.addSpan = _HTMLaddSpan;
  this.addSelect = _HTMLaddSelect;
  this.addOption = _HTMLaddOption;
}
//2}}}

//{{{2 function _HTMLaddTable
function _HTMLaddTable(id, width, border)
{
  var c = new Comparable;
  if (width)
    c.add('width', width);
  if (border)
    c.add('border', border);
  if (id)
    c.add('id', id);
  return this.addNode('TABLE', false, c);
}
//2}}}

//{{{2 function _HTMLaddRow
function _HTMLaddRow(id)
{
  var tr = document.createElement('TR');
  if (id)
    tr.setAttribute('id', id);
  return tr;
}
//2}}}

//{{{2 function _HTMLaddHeaderNode
function _HTMLaddHeaderNode(node, id, width)
{
  var c = new Comparable;
  if (id)
    c.add('id', id);
  if (width)
    c.add('width', width);
  return this.addNode('TH', node, c);
}
//2}}}

//{{{2 function _HTMLaddHeader
function _HTMLaddHeader(text, id, width)
{
  var c = new Comparable;
  if (id)
    c.add('id', id);
  if (width)
    c.add('width', width);
  return this.addTextNode('TH', text, c);
}
//2}}}

//{{{2 function _HTMLaddCell
function _HTMLaddCell(text, id, width, bold)
{
  var c = new Comparable;
  if (id)
    c.add('id', id);
  if (width)
    c.add('width', width);
  return this.addTextNode('TD', text, c, bold);
}
//2}}}

//{{{2 function _HTMLaddSpan
function _HTMLaddSpan(text, id)
{
  var c = new Comparable;
  if (id)
    c.add('id', id);
  return this.addTextNode('SPAN', text, c);
}
//2}}}

//{{{2 function _HTMLaddCellNode
function _HTMLaddCellNode(node, id, width)
{
  var c = new Comparable;
  if (id)
    c.add('id', id);
  if (width)
    c.add('width', width);
  return this.addNode('TD', node, c);
}
//2}}}
//{{{2 function _HTMLaddTextNode
function _HTMLaddTextNode(type, text, args, bold)
{
  var node = document.createElement(type);
  if (bold) {
    var b = node.appendChild(document.createElement('B'));
    if (text)
      b.appendChild(document.createTextNode(text));
  } else {
    if (text)
      node.appendChild(document.createTextNode(text));
  }
  var i;
  if (args) {
    for (i = args.length() -1; i >=0; i--) {
      var elem = args.get(i);
      node.setAttribute(elem.key, elem.data);
    }
  }
  return node;
}
//2}}}

//{{{2 function _HTMLaddNode
function _HTMLaddNode(type, child, args)
{
  var node = document.createElement(type);
  if (child)
    node.appendChild(child);
  var i;
  for (i = args.length() -1; i >=0; i--) {
    var elem = args.get(i);
    node.setAttribute(elem.key, elem.data);
  }
  return node;
}
//2}}}

//{{{2 function _HTMLaddTextInput
function _HTMLaddTextInput(id, value, size, maxlength)
{
  var c = new Comparable;
  c.add('id', id);
  c.add('name', id);
  c.add('type', 'text');
  if (size)
    c.add('size', size);
  if (maxlength)
    c.add('maxlength', maxlength);
  if (value)
    c.add('value', value);
  return this.addNode('INPUT', false, c);
}
//2}}}

//{{{2 function _HTMLaddHidden
function _HTMLaddHidden(id, value)
{
  var c = new Comparable
  c.add('id', id);
  c.add('name', id);
  c.add('type', 'hidden');
  c.add('value', value);
  return this.addNode('INPUT', false, c);
}
//2}}}

//{{{2 function _HTMLaddSelect
function _HTMLaddSelect(id, cls, multi)
{
  var c = new Comparable;
  c.add('id', id);
  c.add('name', id);
	if (cls)
		c.add('class', cls);
	if (multi)
		c.add('multiple', 'multiple');
  return this.addNode('SELECT', false, c);
}
//2}}}

//{{{2 function _HTMLaddOption
function _HTMLaddOption(value, text, selected)
{
  var c = new Comparable;
  c.add('value', value);
	if (selected)
		c.add('selected', 'selected');
  return this.addTextNode('OPTION', text, c);
}
//2}}}

//1}}}

// class CommonEvent {{{

function CommonEvent(e)
{
  // Handle IE, standard Javascript, and passable fields for non-events.
  // Tuned to run with NS 4 and above and IE 4 and above.
  // Tested with Mozilla 1.7, Firefox 0.8, and IE 5
  var target = null;
  var x = 0;
  var y = 0;
  var type = null;
  var button = null;
  var keycode = null;
  var altKey = false;
  var shiftKey = false;
  var ctrlKey = false;
  var metaKey = false;

  if (e) {
    if (e.target) {
      this.target = e.target;
      this.type = e.type;
      this.x = e.x;
      this.y = e.y;
      if (e.modifiers) {
	this.altKey = (e.modifiers & ALT_MASK) ? true : false;
	this.ctrlKey = (e.modifiers & CONTROL_MASK) ? true : false;
	this.shiftKey = (e.modifiers & SHIFT_MASK) ? true : false;
	this.metaKey = (e.modifiers & META_MASK) ? true : false;
      } else {
	if (e.altKey) this.altKey = true;
	if (e.shiftKey) this.shiftKey = true;
	if (e.ctrlKey) this.ctrlKey = true;
	if (e.metaKey) this.metaKey = true;
      }
      if (e.type.substr(0,3).toLowerCase() == 'key') {
	this.keycode = e.which;
      } else {
	this.button = e.which;
      }
    } else {
      this.target = e;
      this.type = 'field';
    }
  } else if (event) {
    this.target = event.srcElement;
    this.type = event.type;
    this.x = event.x;
    this.y = event.y;
    this.button = event.button;
    this.keycode = event.keyCode;
    this.altKey = event.altKey;
    this.shiftKey = event.shiftKey;
    this.ctrlKey = event.ctrlKey;
  }
}

//}}}

//{{{ function ucfirst
function ucfirst(s, delim)
{
  if (!delim)
    delim = ' ';
  var a = s.split(delim);
  var res = "";
  var start = false;
  for (var i = 0; i < a.length; i++) {
    if (start)
      res += " ";
    else
      start = true;
    res += a[i].substr(0, 1).toUpperCase() + a[i].substr(1);
  }
  return res;
}
//}}}


/**{{{ function clear_span
 * Removes any children of an element by ID.
 */
function clear_span(id)
{
  var span = document.getElementById(id);
  if (span) {
    if (span.hasChildNodes()) {
      for (var i = span.childNodes.length - 1; i >= 0; i--)
	span.removeChild(span.childNodes.item(i));
    }
  }
  return span;
}
//}}}

//{{{ function show_message
function show_message(fname, txt)
{
  display_message(txt, fname + '_message');
}
//}}}

//{{{ function show_instruction
function show_instruction(txt)
{
  display_message(txt, 'instruct');
}
//}}}

/** {{{ function display_message
 * Generic message display.  This looks for the required element on
 * the page and if found it adds a text node, (or changes an existing
 * one) to the text required.  Used by show_message and show_instruction.
 * The element name is supplied with the 'id=' attribute of the
 * HTML.
 */
function display_message(txt, elem)
{
  var span = document.getElementById(elem);
  if (span == null)
    return;

  var text;
  if (span.hasChildNodes()) {
    text = span.childNodes.item(0);
    text.nodeValue = txt;
  } else {
    text = span.appendChild(document.createTextNode(txt));
  }
}
//}}}

//{{{ clear_message, reset_message, default_instruction
function clear_message(fname)
{
  reset_message( fname + '_message');
}

function clear_instruction()
{
  reset_message('instruct');
}

//}}}

/** {{{ function reset_message
 * Function to clear the text node associated with an element.
 * The element name is supplied with the 'id=' attribute of the
 * HTML.  This can be used to remove text on any node that supports it.
 */
function reset_message(elem)
{
  var span = document.getElementById(elem);
  if (span == null)
    return;

  var text;
  if (span.hasChildNodes()) {
    text = span.childNodes.item(0);
    text.nodeValue = '';
  } else {
    text = span.appendChild(document.createTextNode(''));
  }
}
//}}}

// function find_anchor {{{
// The find_anchor function is usually called when the browser
// is IE based and therefore doesn't use the name to provide
// an index into document.anchors.  Should probably be replaced
// to use getElementById or getElementsByTagName instead of
// relying on browser-specific extensions.
function find_anchor(a)
{
  for (var i = 0; i < document.anchors.length; i++) {
    if (document.anchors[i].name == a)
      return true;
  }
  return false;
}
//}}}

// vim600: fdm=marker ai sw=2:
// vim<600: ai sw=2:

function popUP(mypage, myname, w, h, scroll, titlebar)
{

	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable,status=1'
	win = window.open(mypage, myname, winprops)
	if (parseInt(navigator.appVersion) >= 4) {
		win.window.focus();
	}
}

function checkAll(theForm, cName, allNo_stat) {
	var n=theForm.elements.length;
	for (var i=0;i<n;i++){
		if (theForm.elements[i].className.indexOf(cName) !=-1){
			if (allNo_stat.checked) {
			theForm.elements[i].checked = true;
			} else {
			theForm.elements[i].checked = false;
			}
		}
	}
}

// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
	if (cal.dateClicked) {
		cal.callCloseHandler();
		if (cal.to_id != '') {
			cal.sel.value = date; // just update the date in the input field.
			var copy = document.getElementById(cal.to_id);
			 
			copy.value = cal.date.print("%Y%m%d");
		}
		else {
			if (cal.sel.value != '')
				cal.sel.value += "\n" + date;
			else
				cal.sel.value += date;
		}		
	}
}

// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
  cal.hide();                        // hide the calendar
//  cal.destroy();
  _dynarch_popupCalendar = null;
}

function clickModule(id) {
	if (id != "home")
		document.location.href = "index.php?m=" + id;
	else
		document.location.href = "index.php";
}
	
// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(src_id, to_id, id, format, showsTime, showsOtherMonths) {
  var el = document.getElementById(id);
  var cl = document.getElementById(src_id);
   
  if (_dynarch_popupCalendar != null) {
    // we already have some calendar created
    _dynarch_popupCalendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(0, null, selected, closeHandler);

    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    if (typeof showsTime == "string") {
      cal.showsTime = true;
      cal.time24 = (showsTime == "24");
    }

    if (showsOtherMonths) {
      cal.showsOtherMonths = true;
    }
    _dynarch_popupCalendar = cal;                  // remember it in the global var
    cal.setRange(1900, 2070);        // min/max year allowed.
    cal.create();
  }
  _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
  _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
  _dynarch_popupCalendar.sel = el;                 // inform it what input field we use
  _dynarch_popupCalendar.to_id = to_id;

  // the reference element that we pass to showAtElement is the button that
  // triggers the calendar.  In this example we align the calendar bottom-right
  // to the button.
  _dynarch_popupCalendar.showAtElement(cl, "Br");        // show the calendar
}

function clearDate(comp1, comp2) {
	var el = document.getElementById(comp1);
	el.value = '';
	
	el = document.getElementById(comp2);
	el.value = '';
}

function search() {
	document.searchtext.submit();
}

function reset() {
	document.searchtext.searchtext.value = "-1";
	document.searchtext.submit();
}

// xp_progressbar
// Copyright 2004 Brian Gosselin of ScriptAsylum.com
//
// v1.0 - Initial release
// v1.1 - Added ability to pause the scrolling action (requires you to assign
//        the bar to a unique arbitrary variable).
//      - Added ability to specify an action to perform after a x amount of
//      - bar scrolls. This requires two added arguments.
// v1.2 - Added ability to hide/show each bar (requires you to assign the bar
//        to a unique arbitrary variable).

// var xyz = createBar(
// total_width,
// total_height,
// background_color,
// border_width,
// border_color,
// block_color,
// scroll_speed,
// block_count,
// scroll_count,
// action_to_perform_after_scrolled_n_times
// )

var w3c=(document.getElementById)?true:false;
var ie=(document.all)?true:false;
var N=-1;

function createBar(w,h,bgc,brdW,brdC,blkC,speed,blocks,count,action){
if(ie||w3c){
var t='<div id="_xpbar'+(++N)+'" style="visibility:visible; position:relative; overflow:hidden; width:'+w+'px; height:'+h+'px; background-color:'+bgc+'; border-color:'+brdC+'; border-width:'+brdW+'px; border-style:solid; font-size:1px;">';
t+='<span id="blocks'+N+'" style="left:-'+(h*2+1)+'px; position:absolute; font-size:1px">';
for(i=0;i<blocks;i++){
t+='<span style="background-color:'+blkC+'; left:-'+((h*i)+i)+'px; font-size:1px; position:absolute; width:'+h+'px; height:'+h+'px; '
t+=(ie)?'filter:alpha(opacity='+(100-i*(100/blocks))+')':'-Moz-opacity:'+((100-i*(100/blocks))/100);
t+='"></span>';
}
t+='</span></div>';
document.write(t);
var bA=(ie)?document.all['blocks'+N]:document.getElementById('blocks'+N);
bA.bar=(ie)?document.all['_xpbar'+N]:document.getElementById('_xpbar'+N);
bA.blocks=blocks;
bA.N=N;
bA.w=w;
bA.h=h;
bA.speed=speed;
bA.ctr=0;
bA.count=count;
bA.action=action;
bA.togglePause=togglePause;
bA.showBar=function(){
this.bar.style.visibility="visible";
}
bA.hideBar=function(){
this.bar.style.visibility="hidden";
}
bA.tid=setInterval('startBar('+N+')',speed);
return bA;
}}

function startBar(bn){
var t=(ie)?document.all['blocks'+bn]:document.getElementById('blocks'+bn);
if(parseInt(t.style.left)+t.h+1-(t.blocks*t.h+t.blocks)>t.w){
t.style.left=-(t.h*2+1)+'px';
t.ctr++;
if(t.ctr>=t.count){
eval(t.action);
t.ctr=0;
}}else t.style.left=(parseInt(t.style.left)+t.h+1)+'px';
}

function togglePause(){
if(this.tid==0){
this.tid=setInterval('startBar('+this.N+')',this.speed);
}else{
clearInterval(this.tid);
this.tid=0;
}}

function togglePause(){
if(this.tid==0){
this.tid=setInterval('startBar('+this.N+')',this.speed);
}else{
clearInterval(this.tid);
this.tid=0;
}}

//Setting cookies
function set_cookie_gen ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );
  if ( exp_y )
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }

  if ( path )
        cookie_string += "; path=" + escape ( path );
  if ( domain )
        cookie_string += "; domain=" + escape ( domain );
  if ( secure )
        cookie_string += "; secure";
  
  document.cookie = cookie_string;
}

// Retrieving cookies
function get_cookie_gen ( cookie_name )
{
  var results = document.cookie.match ( cookie_name + '=(.*?)(;|$)' );

  if ( results )
    return ( unescape ( results[1] ) );
  else
    return null;
}

//added for show/hide 10July
function togglePanel(bn)
{
	var detailTable = document.getElementById(bn);
       	detailTable.style.display = (detailTable.style.display == "")?"none":"";
       	img = document.getElementById("img_"+bn);
      	img.src=(img.src.indexOf("images/toggle1.gif")!=-1)?"images/toggle2.gif":"images/toggle1.gif";		
      	set_cookie_gen(bn,detailTable.style.display);

}

function setToggle(bn)
{
	var status = get_cookie_gen(bn)
	var detailTable = document.getElementById(bn);
	var detailTableImg=document.getElementById("img_"+bn)
	if(status == null || status == "") {
		detailTable.style.display="";
		detailTableImg.src="images/toggle2.gif";
	}
	else {
		detailTable.style.display="none";
		detailTableImg.src="images/toggle1.gif";
	}
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function openWin(url, name, attr) {
	var popup = window.open(url, name, attr);
	
	//if (!popup.focus) {
		popup.focus();
	//}
}

function getObj(n,d) {
  var p,i,x; 
  if(!d)
      d=document;
   
  if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
  }
  
  if(!(x=d[n])&&d.all)
      x=d.all[n];

  for(i=0;!x&&i<d.forms.length;i++)
      x=d.forms[i][n];

  for(i=0;!x&&d.layers&&i<d.layers.length;i++)
      x=getObj(n,d.layers[i].document);

  if(!x && d.getElementById)
      x=d.getElementById(n);
	  
  return x;
}
function findPosX(obj) {
	var curleft = 0;
	if (document.getElementById || document.all) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	} else if (document.layers) {
		curleft += obj.x;
	}
	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	if (document.getElementById || document.all) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	} else if (document.layers) {
		curtop += obj.y;
	}
	return curtop;
}

function showSubMenu() {
	getObj("subMenuBg").style.display=getObj("subMenu").style.display="block"
	getObj("subMenuBg").style.top=getObj("subMenu").style.top=findPosY(getObj("showSubMenu"))
	getObj("subMenuBg").style.left=getObj("subMenu").style.left=findPosX(getObj("showSubMenu"))
	getObj("subMenuBg").style.width=getObj("subMenu").offsetWidth
	getObj("subMenuBg").style.height=getObj("subMenu").offsetHeight
}
function hideSubMenu(ev) {
	if (!ev) {
		if (window.event)
			var obj = window.event.srcElement;
		else
			var obj = null;
	}
	else 
		var obj = ev.target;
	
	if (obj) {
		if (obj.id!="showSubMenu" && obj.id!="showSubMainMenu") {
			if (getObj("subMenu")) {
				if (getObj("subMenu").style.display=="block") {
					getObj("subMenuBg").style.display="none";
					getObj("subMenu").style.display="none";		
				}
			}
			if (getObj("subMainMenu")) {
				if (getObj("subMainMenu").style.display=="block") {
					getObj("subMainMenuBg").style.display="none";
					getObj("subMainMenu").style.display="none";		
				}
			}		
		}
	}
	
	if (window.menuobj)
		menuobj.style.visibility="hidden"

    if (typeof(ajax_tooltipObj) !== 'undefined' && ajax_tooltipObj.style)
        ajax_hideTooltip();
}

document.onclick=hideSubMenu;

function showSubMainMenu() {
	getObj("subMainMenuBg").style.display=getObj("subMainMenu").style.display="block"
	getObj("subMainMenu").style.top=findPosY(getObj("showSubMainMenu"))
	getObj("subMainMenuBg").style.left=getObj("subMainMenu").style.left=findPosX(getObj("showSubMainMenu"))
	getObj("subMainMenuBg").style.width=getObj("subMainMenu").offsetWidth
	getObj("subMainMenuBg").style.height=getObj("subMainMenu").offsetHeight
}

function toggleEditorMode(sEditorID, sDisable) {
    try {
        if(sDisable) {
            tinyMCE.execCommand("mceRemoveControl", false, sEditorID);
        } else {
            tinyMCE.execCommand("mceAddControl", false, sEditorID);
        }
    } catch(e) {
        //error handling
    }
}

function gotoUrl(url) {
	document.location.href = url;
}

function cancel(msg, url) {
	if(confirm(msg)) 
		gotoUrl(url);
}

function formOnSubmit() {
	return true;
}

function replyOnSubmit() {
	return true;
}

function countIds(str) {
	if (str == '') 
		return 0;
	else {
		var count = 1;
		var pos = str.indexOf(",", 0);
		
		while(pos != -1) {
			count++;
			pos = str.indexOf(",", pos+1);
		}
	}
	
	return count;
}

function wprint(msg) {
	if (navigator.userAgent.indexOf('MSIE') != -1) {
		alert(msg);
	}
	else {
		window.print();
	}
}

function resetId(field) {
	fd = document.getElementById(field);
	if (fd) {
		fd.value = '';
	}
}

var selTags=document.getElementsByTagName("SELECT");
function fnDropDown(obj,Lay){
    var tagName = document.getElementById(Lay);
	if (tagName) {
	    var leftSide = findPosX(obj);
	    var topSide = findPosY(obj);
	    var maxW = tagName.style.width;
	    var widthM = maxW.substring(0,maxW.length-2);
	    var getVal = eval(leftSide) + eval(widthM);
	    if(getVal  > document.body.clientWidth ){
	        leftSide = eval(leftSide) - eval(widthM);
	        tagName.style.left = leftSide + 30 + 'px';
	    }
	    else
	        tagName.style.left= leftSide - 3 + 'px';
			
		if (Lay == 'menu_export')
			tagName.style.top= topSide + 10 +'px';
		else
			tagName.style.top= topSide + 30 +'px';
	    tagName.style.display = 'block';

		if (typeof(disable_dropdown_hide) == "undefined")
			for (i=0;i<selTags.length;i++)
				selTags[i].style.visibility="hidden"
	}
	//document.getElementById("quickadd").style.display = 'none';
 }

function fnShowDrop(obj){
	var area = document.getElementById(obj);
	
	if (area) {
		area.style.display = 'block';
		//document.getElementById("quickadd").style.display = 'none';
		if (typeof(disable_dropdown_hide) == "undefined")
			for (i=0;i<selTags.length;i++)
				selTags[i].style.visibility="hidden";
	}
}

function fnHideDrop(obj){
	var area = document.getElementById(obj);
	if (area) {
		area.style.display = 'none';
		//document.getElementById("quickadd").style.display = '';
		if (typeof(disable_dropdown_hide) == "undefined")
			for (i=0;i<selTags.length;i++)
				selTags[i].style.visibility="visible";
	}
}

/*
Author: Robert Hashemian
http://www.hashemian.com/

You can use this code in any manner so long as the author's
name, Web address and this disclaimer is kept intact.
********************************************************/
function FormatNumberBy3(num, decpoint, sep) {
  // check for missing parameters and use defaults if so
  if (arguments.length == 2) {
    sep = ",";
  }
  if (arguments.length == 1) {
    sep = ",";
    decpoint = ".";
  }
  // need a string for operations
  num = num.toString();
  // separate the whole number and the fraction if possible
  a = num.split(decpoint);
  x = a[0]; // decimal
  y = a[1]; // fraction
  z = "";


  if (typeof(x) != "undefined") {
    // reverse the digits. regexp works from left to right.
    for (i=x.length-1;i>=0;i--)
      z += x.charAt(i);
    // add seperators. but undo the trailing one, if there
    z = z.replace(/(\d{3})/g, "$1" + sep);
    if (z.slice(-sep.length) == sep)
      z = z.slice(0, -sep.length);
    x = "";
    // reverse again to get back the number
    for (i=z.length-1;i>=0;i--)
      x += z.charAt(i);
    // add the fraction back in, if it was there
    if (typeof(y) != "undefined" && y.length > 0)
      x += decpoint + y;
  }
  return x;
}

function disable_notification(project_id, notify_all_id, notify_project_id, notify_member_id, notify_stakeholder_id) {
    if (project_id != 0) {
        document.getElementById(notify_all_id).disabled = true;
        document.getElementById(notify_project_id).disabled = false;    	
        document.getElementById(notify_member_id).disabled = false;
        document.getElementById(notify_stakeholder_id).disabled = false;
    }
    else {
        document.getElementById(notify_all_id).disabled = false;
        document.getElementById(notify_project_id).disabled = true;    	
        document.getElementById(notify_member_id).disabled = true;
        document.getElementById(notify_stakeholder_id).disabled = true;
    }
}

function attachData(target_mod, self_mod, self_id) {
	window.open('./index.php?m=public&a=search_module_data&dialog=1&target_mod='+target_mod+'&self_mod='+self_mod+'&self_id='+self_id, 'search_modules','height=500,width=750,left=100,top=35,resizable,scrollbars=yes');
}

function attachFile(self_mod, self_id) {
	window.open('./index.php?m=public&a=search_file_data&dialog=1&self_mod='+self_mod+'&self_id='+self_id, 'search_files','height=500,width=750,left=100,top=35,resizable,scrollbars=yes');
}

function goToPage(page, url) {
	window.location.href = url + "&paging_start=" + page;
}

function deShow(id) {
	var comp = document.getElementById(id);
	if (comp && comp.style.display == 'none') {
		comp.style.display = '';
	}
}

function deHide(id) {
	var comp = document.getElementById(id);
	if (comp && comp.style.display == '') {
		comp.style.display = 'none';
	}
}

var deEditing = false;
var cacheField = '';
var cacheContent = '';
function deMouseOver(field)
{
      if(deEditing)
      {
            return;
      }
      
      deShow("deSpan");
      
      var spanObj = document.getElementById('deSpan');
      var fieldObj = document.getElementById(field);
      
      cacheField = field;
      cacheContent = fieldObj.innerHTML;
      
      posy = findPosY(fieldObj);
      posx = findPosX(fieldObj);
      if(document.all)
      {
    	  spanObj.onclick=deEdit;
      }
      else
      {
    	  spanObj.setAttribute('onclick','deEdit();');
      }
      spanObj.style.left=(posx+fieldObj.offsetWidth -spanObj.offsetWidth)+"px";
      spanObj.style.top=posy+"px";
}

function deCancel() {
	var id = document.getElementById(cacheField);
	id.innerHTML = cacheContent;
	
	cacheField = '';
	cacheContent = '';
	deEditing = false;
}

function deSave(field, id) {
    var poststr = "field="+field+"@@"+id+"&"+field+"="+document.getElementById(field).value;
    ajaxpack.postAjaxRequest("index.php?m=tasks&a=save_field&suppressHeaders=1", poststr, doneDeSave, "txt");
    return false;
}

function doneDeSave() {
    var myajax=ajaxpack.ajaxobj;
    var myfiletype=ajaxpack.filetype;

	if (myajax.readyState == 4){ //if request of file completed
		if (myajax.status==200 || window.location.href.indexOf("http")==-1)	{
            if (myajax.responseText != '') {
            	result = myajax.responseText.split("@@");
            	//alert(myajax.responseText);
            	
                if (result[0] == "SUCCESS") {
                    id = document.getElementById(cacheField);
                    value = result[1];
                    
                    if (id) {
                    	id.innerHTML = value;                    	
                    }
                	
                	cacheField = '';
                	cacheContent = '';
                	deEditing = false;                    
                }
                else {
                	alert(result[1]);
                }
            }
        }
    }
}

function deEdit() {
    var poststr = "field="+cacheField;
    ajaxpack.postAjaxRequest("index.php?m=tasks&a=edit_field&mode=edit&suppressHeaders=1", poststr, doneDeEdit, "txt");

    deHide('deSpan');
    deEditing=true;
    return false;
}

function doneDeEdit() {
    var myajax=ajaxpack.ajaxobj;
    var myfiletype=ajaxpack.filetype;

	if (myajax.readyState == 4){ //if request of file completed
		if (myajax.status==200 || window.location.href.indexOf("http")==-1)	{
            if (myajax.responseText != '') {
            	result = myajax.responseText.split("@@");
            	//alert(myajax.responseText);
            	
                if (result[0] == "SUCCESS") {
                    id = document.getElementById(cacheField);
                    value = result[1];
                    
                    if (id) {
                    	id.innerHTML = value;
                    }
                }
                else {
                	alert(result[1]);
                	deEditing=false;
                }
            }
        }
    }
}

function findPosX(obj) {
	var curleft = 0;
	if (document.getElementById || document.all) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	} else if (document.layers) {
		curleft += obj.x;
	}
	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	if (document.getElementById || document.all) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	} else if (document.layers) {
		curtop += obj.y;
	}

	return curtop;
}

function calcTaskDuration(project_id, start_date_id, end_date_id, duration_type_id, duration_field) {
    var start_date = document.getElementById(start_date_id);
    var end_date = document.getElementById(end_date_id);
    var duration_type = document.getElementById(duration_type_id);

    var start_date_value = '';
    var end_date_value = '';
    
    if (start_date && end_date && duration_type) {
        if (document.getElementById(start_date_id+"_time")) {
        	start_date_value = start_date.value + "" + convertTimeFormat(document.getElementById(start_date_id+"_time").value);
        }
        
        if (document.getElementById(end_date_id+"_time")) {
        	end_date_value = end_date.value + "" + convertTimeFormat(document.getElementById(end_date_id+"_time").value);
        }
        
        var poststr = "project_id="+project_id+"&start_date="+start_date_value+"&end_date="+end_date_value+"&duration_type="+duration_type.value+"&duration_field="+duration_field;
        ajaxpack.postAjaxRequest("index.php?m=projects&a=calc_dates&suppressHeaders=1", poststr, doneCalcTaskDuration, "txt");
    }
}

function doneCalcTaskDuration() {
    var myajax=ajaxpack.ajaxobj;
    var myfiletype=ajaxpack.filetype;

	if (myajax.readyState == 4){ //if request of file completed
		if (myajax.status==200 || window.location.href.indexOf("http")==-1)	{
            if (myajax.responseText != '') {
            	result = myajax.responseText.split("@@");
            	//alert(myajax.responseText);
            	
                if (result[0] == "SUCCESS") {
                    id = document.getElementById(result[1]);
                    value = result[2];
                    
                    if (id) {
                    	id.value = value;
                    }
                }
                else {
                	// do nothing
                }
            }
        }
    }	
}

function calcTaskEndDate(project_id, start_date_id, duration_id, duration_type_id, end_date_field, end_date_display_field) {
    var start_date = document.getElementById(start_date_id);
    var duration = document.getElementById(duration_id);
    var duration_type = document.getElementById(duration_type_id);
    
    if (start_date && duration && duration_type) {
        var start_date_value = start_date.value;
		
        if (document.getElementById(start_date_id+"_time")) {
        	start_date_value = start_date.value + "" + convertTimeFormat(document.getElementById(start_date_id+"_time").value);
        }
        
        var poststr = "project_id="+project_id+"&start_date="+start_date_value+"&duration="+duration.value+"&duration_type="+duration_type.value+"&end_date_field="+end_date_field+"&end_date_display_field="+end_date_display_field;
        ajaxpack.postAjaxRequest("index.php?m=projects&a=calc_dates&suppressHeaders=1", poststr, doneCalcTaskEndDate, "txt");
    }	
}

function doneCalcTaskEndDate() {
    var myajax=ajaxpack.ajaxobj;
    var myfiletype=ajaxpack.filetype;

	if (myajax.readyState == 4){ //if request of file completed
		if (myajax.status==200 || window.location.href.indexOf("http")==-1)	{
            if (myajax.responseText != '') {
            	result = myajax.responseText.split("@@");
            	//alert(myajax.responseText);
            	
                if (result[0] == "SUCCESS") {
                    id = document.getElementById(result[1]);
                    value = result[2];
                    
                    if (id) {
                    	id.value = value;
                    }
                    
                    id = document.getElementById(result[3]);
                    value = result[4];
                    
                    if (id) {
                    	id.value = value;
                    }
                    
                    id = document.getElementById(result[1]+"_time");
                    
                    if (id) {
                    	id.value = result[5] + ":" + result[6];
                    }
                }
                else {
                	// do nothing
                }
            }
        }
    }	
}

function toggleForm() {
	var toggle_form = document.getElementById("app_form");
	var toggle_desc = document.getElementById("app_form_desc");
	
	if (toggle_form) {
		if (toggle_form.style.display == 'none') {
			toggle_form.style.display = '';
			toggle_desc.style.display = '';
			document.getElementById("app_form_display_link").style.display = 'none';
			document.getElementById("app_form_hide_link").style.display = '';
		}
		else {
			toggle_form.style.display = 'none';
			toggle_desc.style.display = 'none';	
			document.getElementById("app_form_display_link").style.display = '';
			document.getElementById("app_form_hide_link").style.display = 'none';			
		}
		
		set_cookie_gen("app_form_toggle",toggle_form.style.display);		
	}
}

function setToggleForm()
{
	var status = get_cookie_gen("app_form_toggle")

	if(status != null && status != "") {
		toggleForm();
	}
}

function goToView(view, url) {
	window.location.href = url + "&view=" + view;
}

function checkTimeFormat(val) {
	var pos;
	if (val && val.length == 5) {
		if (pos = val.indexOf(":")) {
			var hour = val.substring(0, pos);
			var min = val.substring(pos+1, val.length);
			
			if (hour >= 0 && hour <= 23 && min >= 0 && min <= 59) {
				return true;
			}
		}
	}
	
	return false;
}

function setupTimeField(id) {
	jQuery(function($){  $("#" + id).mask("99:99",{completed:function(){ if(!checkTimeFormat(this.val())) this.val(''); }});});
}

function convertTimeFormat(val) {
	var pos;
	if (val && val.length == 5) {
		if (pos = val.indexOf(":")) {
			var hour = val.substring(0, pos);
			var min = val.substring(pos+1, val.length);

			return hour + "" + min + "00";
		}
	}

	return "000000";
}

function isIE() {
	return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}

function selectMultiAll(this_id) {
	selectBox = document.getElementById(this_id);
	if(selectBox && selectBox.length>0) {
		for (i=0; i < selectBox.length; i++) {
			selectBox.options[i].selected = true;
		}
	}
}
