/*  Copyright Mihai Bazon, 2002-2005  |  www.bazon.net/mishoo
 * -----------------------------------------------------------
 *
 * The DHTML Calendar, version 1.0 "It is happening again"
 *
 * Details and latest version at:
 * www.dynarch.com/projects/calendar
 *
 * This script is developed by Dynarch.com.  Visit us at www.dynarch.com.
 *
 * This script is distributed under the GNU Lesser General Public License.
 * Read the entire license text here: http://www.gnu.org/licenses/lgpl.html
 */

// $Id: calendar.js,v 1.51 2005/03/07 16:44:31 mishoo Exp $

/** The Calendar object constructor. */
Calendar = function (firstDayOfWeek, dateStr, onSelected, onClose) {
	// member variables
	this.activeDiv = null;
	this.currentDateEl = null;
	this.getDateStatus = null;
	this.getDateToolTip = null;
	this.getDateText = null;
	this.timeout = null;
	this.onSelected = onSelected || null;
	this.onClose = onClose || null;
	this.dragging = false;
	this.hidden = false;
	this.minYear = 1970;
	this.maxYear = 2050;
	this.dateFormat = Calendar._TT["DEF_DATE_FORMAT"];
	this.ttDateFormat = Calendar._TT["TT_DATE_FORMAT"];
	this.isPopup = true;
	this.weekNumbers = true;
	this.firstDayOfWeek = typeof firstDayOfWeek == "number" ? firstDayOfWeek : Calendar._FD; // 0 for Sunday, 1 for Monday, etc.
	this.showsOtherMonths = false;
	this.dateStr = dateStr;
	this.ar_days = null;
	this.showsTime = false;
	this.time24 = true;
	this.yearStep = 2;
	this.hiliteToday = true;
	this.multiple = null;
	// HTML elements
	this.table = null;
	this.element = null;
	this.tbody = null;
	this.firstdayname = null;
	// Combo boxes
	this.monthsCombo = null;
	this.yearsCombo = null;
	this.hilitedMonth = null;
	this.activeMonth = null;
	this.hilitedYear = null;
	this.activeYear = null;
	// Information
	this.dateClicked = false;

	// one-time initializations
	if (typeof Calendar._SDN == "undefined") {
		// table of short day names
		if (typeof Calendar._SDN_len == "undefined")
			Calendar._SDN_len = 3;
		var ar = new Array();
		for (var i = 8; i > 0;) {
			ar[--i] = Calendar._DN[i].substr(0, Calendar._SDN_len);
		}
		Calendar._SDN = ar;
		// table of short month names
		if (typeof Calendar._SMN_len == "undefined")
			Calendar._SMN_len = 3;
		ar = new Array();
		for (var i = 12; i > 0;) {
			ar[--i] = Calendar._MN[i].substr(0, Calendar._SMN_len);
		}
		Calendar._SMN = ar;
	}
};

// ** constants

/// "static", needed for event handlers.
Calendar._C = null;

/// detect a special case of "web browser"
Calendar.is_ie = ( /msie/i.test(navigator.userAgent) &&
		   !/opera/i.test(navigator.userAgent) );

Calendar.is_ie5 = ( Calendar.is_ie && /msie 5\.0/i.test(navigator.userAgent) );

/// detect Opera browser
Calendar.is_opera = /opera/i.test(navigator.userAgent);

/// detect KHTML-based browsers
Calendar.is_khtml = /Konqueror|Safari|KHTML/i.test(navigator.userAgent);

// BEGIN: UTILITY FUNCTIONS; beware that these might be moved into a separate
//        library, at some point.

Calendar.getAbsolutePos = function(el) {
	var SL = 0, ST = 0;
	var is_div = /^div$/i.test(el.tagName);
	if (is_div && el.scrollLeft)
		SL = el.scrollLeft;
	if (is_div && el.scrollTop)
		ST = el.scrollTop;
	var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
	if (el.offsetParent) {
		var tmp = this.getAbsolutePos(el.offsetParent);
		r.x += tmp.x;
		r.y += tmp.y;
	}
	return r;
};

Calendar.isRelated = function (el, evt) {
	var related = evt.relatedTarget;
	if (!related) {
		var type = evt.type;
		if (type == "mouseover") {
			related = evt.fromElement;
		} else if (type == "mouseout") {
			related = evt.toElement;
		}
	}
	while (related) {
		if (related == el) {
			return true;
		}
		related = related.parentNode;
	}
	return false;
};

Calendar.removeClass = function(el, className) {
	if (!(el && el.className)) {
		return;
	}
	var cls = el.className.split(" ");
	var ar = new Array();
	for (var i = cls.length; i > 0;) {
		if (cls[--i] != className) {
			ar[ar.length] = cls[i];
		}
	}
	el.className = ar.join(" ");
};

Calendar.addClass = function(el, className) {
	Calendar.removeClass(el, className);
	el.className += " " + className;
};

// FIXME: the following 2 functions totally suck, are useless and should be replaced immediately.
Calendar.getElement = function(ev) {
	var f = Calendar.is_ie ? window.event.srcElement : ev.currentTarget;
	while (f.nodeType != 1 || /^div$/i.test(f.tagName))
		f = f.parentNode;
	return f;
};

Calendar.getTargetElement = function(ev) {
	var f = Calendar.is_ie ? window.event.srcElement : ev.target;
	while (f.nodeType != 1)
		f = f.parentNode;
	return f;
};

Calendar.stopEvent = function(ev) {
	ev || (ev = window.event);
	if (Calendar.is_ie) {
		ev.cancelBubble = true;
		ev.returnValue = false;
	} else {
		ev.preventDefault();
		ev.stopPropagation();
	}
	return false;
};

Calendar.addEvent = function(el, evname, func) {
	if (el.attachEvent) { // IE
		el.attachEvent("on" + evname, func);
	} else if (el.addEventListener) { // Gecko / W3C
		el.addEventListener(evname, func, true);
	} else {
		el["on" + evname] = func;
	}
};

Calendar.removeEvent = function(el, evname, func) {
	if (el.detachEvent) { // IE
		el.detachEvent("on" + evname, func);
	} else if (el.removeEventListener) { // Gecko / W3C
		el.removeEventListener(evname, func, true);
	} else {
		el["on" + evname] = null;
	}
};

Calendar.createElement = function(type, parent) {
	var el = null;
	if (document.createElementNS) {
		// use the XHTML namespace; IE won't normally get here unless
		// _they_ "fix" the DOM2 implementation.
		el = document.createElementNS("http://www.w3.org/1999/xhtml", type);
	} else {
		el = document.createElement(type);
	}
	if (typeof parent != "undefined") {
		parent.appendChild(el);
	}
	return el;
};

// END: UTILITY FUNCTIONS

// BEGIN: CALENDAR STATIC FUNCTIONS

/** Internal -- adds a set of events to make some element behave like a button. */
Calendar._add_evs = function(el) {
	with (Calendar) {
		addEvent(el, "mouseover", dayMouseOver);
		addEvent(el, "mousedown", dayMouseDown);
		addEvent(el, "mouseout", dayMouseOut);
		if (is_ie) {
			addEvent(el, "dblclick", dayMouseDblClick);
			el.setAttribute("unselectable", true);
		}
	}
};

Calendar.findMonth = function(el) {
	if (typeof el.month != "undefined") {
		return el;
	} else if (typeof el.parentNode.month != "undefined") {
		return el.parentNode;
	}
	return null;
};

Calendar.findYear = function(el) {
	if (typeof el.year != "undefined") {
		return el;
	} else if (typeof el.parentNode.year != "undefined") {
		return el.parentNode;
	}
	return null;
};

Calendar.showMonthsCombo = function () {
	var cal = Calendar._C;
	if (!cal) {
		return false;
	}
	var cal = cal;
	var cd = cal.activeDiv;
	var mc = cal.monthsCombo;
	if (cal.hilitedMonth) {
		Calendar.removeClass(cal.hilitedMonth, "hilite");
	}
	if (cal.activeMonth) {
		Calendar.removeClass(cal.activeMonth, "active");
	}
	var mon = cal.monthsCombo.getElementsByTagName("div")[cal.date.getMonth()];
	Calendar.addClass(mon, "active");
	cal.activeMonth = mon;
	var s = mc.style;
	s.display = "block";
	if (cd.navtype < 0)
		s.left = cd.offsetLeft + "px";
	else {
		var mcw = mc.offsetWidth;
		if (typeof mcw == "undefined")
			// Konqueror brain-dead techniques
			mcw = 50;
		s.left = (cd.offsetLeft + cd.offsetWidth - mcw) + "px";
	}
	s.top = (cd.offsetTop + cd.offsetHeight) + "px";
};

Calendar.showYearsCombo = function (fwd) {
	var cal = Calendar._C;
	if (!cal) {
		return false;
	}
	var cal = cal;
	var cd = cal.activeDiv;
	var yc = cal.yearsCombo;
	if (cal.hilitedYear) {
		Calendar.removeClass(cal.hilitedYear, "hilite");
	}
	if (cal.activeYear) {
		Calendar.removeClass(cal.activeYear, "active");
	}
	cal.activeYear = null;
	var Y = cal.date.getFullYear() + (fwd ? 1 : -1);
	var yr = yc.firstChild;
	var show = false;
	for (var i = 12; i > 0; --i) {
		if (Y >= cal.minYear && Y <= cal.maxYear) {
			yr.innerHTML = Y;
			yr.year = Y;
			yr.style.display = "block";
			show = true;
		} else {
			yr.style.display = "none";
		}
		yr = yr.nextSibling;
		Y += fwd ? cal.yearStep : -cal.yearStep;
	}
	if (show) {
		var s = yc.style;
		s.display = "block";
		if (cd.navtype < 0)
			s.left = cd.offsetLeft + "px";
		else {
			var ycw = yc.offsetWidth;
			if (typeof ycw == "undefined")
				// Konqueror brain-dead techniques
				ycw = 50;
			s.left = (cd.offsetLeft + cd.offsetWidth - ycw) + "px";
		}
		s.top = (cd.offsetTop + cd.offsetHeight) + "px";
	}
};

// event handlers

Calendar.tableMouseUp = function(ev) {
	var cal = Calendar._C;
	if (!cal) {
		return false;
	}
	if (cal.timeout) {
		clearTimeout(cal.timeout);
	}
	var el = cal.activeDiv;
	if (!el) {
		return false;
	}
	var target = Calendar.getTargetElement(ev);
	ev || (ev = window.event);
	Calendar.removeClass(el, "active");
	if (target == el || target.parentNode == el) {
		Calendar.cellClick(el, ev);
	}
	var mon = Calendar.findMonth(target);
	var date = null;
	if (mon) {
		date = new Date(cal.date);
		if (mon.month != date.getMonth()) {
			date.setMonth(mon.month);
			cal.setDate(date);
			cal.dateClicked = false;
			cal.callHandler();
		}
	} else {
		var year = Calendar.findYear(target);
		if (year) {
			date = new Date(cal.date);
			if (year.year != date.getFullYear()) {
				date.setFullYear(year.year);
				cal.setDate(date);
				cal.dateClicked = false;
				cal.callHandler();
			}
		}
	}
	with (Calendar) {
		removeEvent(document, "mouseup", tableMouseUp);
		removeEvent(document, "mouseover", tableMouseOver);
		removeEvent(document, "mousemove", tableMouseOver);
		cal._hideCombos();
		_C = null;
		return stopEvent(ev);
	}
};

Calendar.tableMouseOver = function (ev) {
	var cal = Calendar._C;
	if (!cal) {
		return;
	}
	var el = cal.activeDiv;
	var target = Calendar.getTargetElement(ev);
	if (target == el || target.parentNode == el) {
		Calendar.addClass(el, "hilite active");
		Calendar.addClass(el.parentNode, "rowhilite");
	} else {
		if (typeof el.navtype == "undefined" || (el.navtype != 50 && (el.navtype == 0 || Math.abs(el.navtype) > 2)))
			Calendar.removeClass(el, "active");
		Calendar.removeClass(el, "hilite");
		Calendar.removeClass(el.parentNode, "rowhilite");
	}
	ev || (ev = window.event);
	if (el.navtype == 50 && target != el) {
		var pos = Calendar.getAbsolutePos(el);
		var w = el.offsetWidth;
		var x = ev.clientX;
		var dx;
		var decrease = true;
		if (x > pos.x + w) {
			dx = x - pos.x - w;
			decrease = false;
		} else
			dx = pos.x - x;

		if (dx < 0) dx = 0;
		var range = el._range;
		var current = el._current;
		var count = Math.floor(dx / 10) % range.length;
		for (var i = range.length; --i >= 0;)
			if (range[i] == current)
				break;
		while (count-- > 0)
			if (decrease) {
				if (--i < 0)
					i = range.length - 1;
			} else if ( ++i >= range.length )
				i = 0;
		var newval = range[i];
		el.innerHTML = newval;

		cal.onUpdateTime();
	}
	var mon = Calendar.findMonth(target);
	if (mon) {
		if (mon.month != cal.date.getMonth()) {
			if (cal.hilitedMonth) {
				Calendar.removeClass(cal.hilitedMonth, "hilite");
			}
			Calendar.addClass(mon, "hilite");
			cal.hilitedMonth = mon;
		} else if (cal.hilitedMonth) {
			Calendar.removeClass(cal.hilitedMonth, "hilite");
		}
	} else {
		if (cal.hilitedMonth) {
			Calendar.removeClass(cal.hilitedMonth, "hilite");
		}
		var year = Calendar.findYear(target);
		if (year) {
			if (year.year != cal.date.getFullYear()) {
				if (cal.hilitedYear) {
					Calendar.removeClass(cal.hilitedYear, "hilite");
				}
				Calendar.addClass(year, "hilite");
				cal.hilitedYear = year;
			} else if (cal.hilitedYear) {
				Calendar.removeClass(cal.hilitedYear, "hilite");
			}
		} else if (cal.hilitedYear) {
			Calendar.removeClass(cal.hilitedYear, "hilite");
		}
	}
	return Calendar.stopEvent(ev);
};

Calendar.tableMouseDown = function (ev) {
	if (Calendar.getTargetElement(ev) == Calendar.getElement(ev)) {
		return Calendar.stopEvent(ev);
	}
};

Calendar.calDragIt = function (ev) {
	var cal = Calendar._C;
	if (!(cal && cal.dragging)) {
		return false;
	}
	var posX;
	var posY;
	if (Calendar.is_ie) {
		posY = window.event.clientY + document.body.scrollTop;
		posX = window.event.clientX + document.body.scrollLeft;
	} else {
		posX = ev.pageX;
		posY = ev.pageY;
	}
	cal.hideShowCovered();
	var st = cal.element.style;
	st.left = (posX - cal.xOffs) + "px";
	st.top = (posY - cal.yOffs) + "px";
	return Calendar.stopEvent(ev);
};

Calendar.calDragEnd = function (ev) {
	var cal = Calendar._C;
	if (!cal) {
		return false;
	}
	cal.dragging = false;
	with (Calendar) {
		removeEvent(document, "mousemove", calDragIt);
		removeEvent(document, "mouseup", calDragEnd);
		tableMouseUp(ev);
	}
	cal.hideShowCovered();
};

Calendar.dayMouseDown = function(ev) {
	var el = Calendar.getElement(ev);
	if (el.disabled) {
		return false;
	}
	var cal = el.calendar;
	cal.activeDiv = el;
	Calendar._C = cal;
	if (el.navtype != 300) with (Calendar) {
		if (el.navtype == 50) {
			el._current = el.innerHTML;
			addEvent(document, "mousemove", tableMouseOver);
		} else
			addEvent(document, Calendar.is_ie5 ? "mousemove" : "mouseover", tableMouseOver);
		addClass(el, "hilite active");
		addEvent(document, "mouseup", tableMouseUp);
	} else if (cal.isPopup) {
		cal._dragStart(ev);
	}
	if (el.navtype == -1 || el.navtype == 1) {
		if (cal.timeout) clearTimeout(cal.timeout);
		cal.timeout = setTimeout("Calendar.showMonthsCombo()", 250);
	} else if (el.navtype == -2 || el.navtype == 2) {
		if (cal.timeout) clearTimeout(cal.timeout);
		cal.timeout = setTimeout((el.navtype > 0) ? "Calendar.showYearsCombo(true)" : "Calendar.showYearsCombo(false)", 250);
	} else {
		cal.timeout = null;
	}
	return Calendar.stopEvent(ev);
};

Calendar.dayMouseDblClick = function(ev) {
	Calendar.cellClick(Calendar.getElement(ev), ev || window.event);
	if (Calendar.is_ie) {
		document.selection.empty();
	}
};

Calendar.dayMouseOver = function(ev) {
	var el = Calendar.getElement(ev);
	if (Calendar.isRelated(el, ev) || Calendar._C || el.disabled) {
		return false;
	}
	if (el.ttip) {
		if (el.ttip.substr(0, 1) == "_") {
			el.ttip = el.caldate.print(el.calendar.ttDateFormat) + el.ttip.substr(1);
		}
		el.calendar.tooltips.innerHTML = el.ttip;
	}
	if (el.navtype != 300) {
		Calendar.addClass(el, "hilite");
		if (el.caldate) {
			Calendar.addClass(el.parentNode, "rowhilite");
		}
	}
	return Calendar.stopEvent(ev);
};

Calendar.dayMouseOut = function(ev) {
	with (Calendar) {
		var el = getElement(ev);
		if (isRelated(el, ev) || _C || el.disabled)
			return false;
		removeClass(el, "hilite");
		if (el.caldate)
			removeClass(el.parentNode, "rowhilite");
		if (el.calendar)
			el.calendar.tooltips.innerHTML = _TT["SEL_DATE"];
		return stopEvent(ev);
	}
};

/**
 *  A generic "click" handler :) handles all types of buttons defined in this
 *  calendar.
 */
Calendar.cellClick = function(el, ev) {
	var cal = el.calendar;
	var closing = false;
	var newdate = false;
	var date = null;
	if (typeof el.navtype == "undefined") {
		if (cal.currentDateEl) {
			Calendar.removeClass(cal.currentDateEl, "selected");
			Calendar.addClass(el, "selected");
			closing = (cal.currentDateEl == el);
			if (!closing) {
				cal.currentDateEl = el;
			}
		}
		cal.date.setDateOnly(el.caldate);
		date = cal.date;
		var other_month = !(cal.dateClicked = !el.otherMonth);
		if (!other_month && !cal.currentDateEl)
			cal._toggleMultipleDate(new Date(date));
		else
			newdate = !el.disabled;
		// a date was clicked
		if (other_month)
			cal._init(cal.firstDayOfWeek, date);
	} else {
		if (el.navtype == 200) {
			Calendar.removeClass(el, "hilite");
			cal.callCloseHandler();
			return;
		}
		date = new Date(cal.date);
		if (el.navtype == 0)
			date.setDateOnly(new Date()); // TODAY
		// unless "today" was clicked, we assume no date was clicked so
		// the selected handler will know not to close the calenar when
		// in single-click mode.
		// cal.dateClicked = (el.navtype == 0);
		cal.dateClicked = false;
		var year = date.getFullYear();
		var mon = date.getMonth();
		function setMonth(m) {
			var day = date.getDate();
			var max = date.getMonthDays(m);
			if (day > max) {
				date.setDate(max);
			}
			date.setMonth(m);
		};
		switch (el.navtype) {
		    case 400:
			Calendar.removeClass(el, "hilite");
			var text = Calendar._TT["ABOUT"];
			if (typeof text != "undefined") {
				text += cal.showsTime ? Calendar._TT["ABOUT_TIME"] : "";
			} else {
				// FIXME: this should be removed as soon as lang files get updated!
				text = "Help and about box text is not translated into this language.\n" +
					"If you know this language and you feel generous please update\n" +
					"the corresponding file in \"lang\" subdir to match calendar-en.js\n" +
					"and send it back to <mihai_bazon@yahoo.com> to get it into the distribution  ;-)\n\n" +
					"Thank you!\n" +
					"http://dynarch.com/mishoo/calendar.epl\n";
			}
			alert(text);
			return;
		    case -2:
			if (year > cal.minYear) {
				date.setFullYear(year - 1);
			}
			break;
		    case -1:
			if (mon > 0) {
				setMonth(mon - 1);
			} else if (year-- > cal.minYear) {
				date.setFullYear(year);
				setMonth(11);
			}
			break;
		    case 1:
			if (mon < 11) {
				setMonth(mon + 1);
			} else if (year < cal.maxYear) {
				date.setFullYear(year + 1);
				setMonth(0);
			}
			break;
		    case 2:
			if (year < cal.maxYear) {
				date.setFullYear(year + 1);
			}
			break;
		    case 100:
			cal.setFirstDayOfWeek(el.fdow);
			return;
		    case 50:
			var range = el._range;
			var current = el.innerHTML;
			for (var i = range.length; --i >= 0;)
				if (range[i] == current)
					break;
			if (ev && ev.shiftKey) {
				if (--i < 0)
					i = range.length - 1;
			} else if ( ++i >= range.length )
				i = 0;
			var newval = range[i];
			el.innerHTML = newval;
			cal.onUpdateTime();
			return;
		    case 0:
			// TODAY will bring us here
			if ((typeof cal.getDateStatus == "function") &&
			    cal.getDateStatus(date, date.getFullYear(), date.getMonth(), date.getDate())) {
				return false;
			}
			break;
		}
		if (!date.equalsTo(cal.date)) {
			cal.setDate(date);
			newdate = true;
		} else if (el.navtype == 0)
			newdate = closing = true;
	}
	if (newdate) {
		ev && cal.callHandler();
	}
	if (closing) {
		Calendar.removeClass(el, "hilite");
		ev && cal.callCloseHandler();
	}
};

// END: CALENDAR STATIC FUNCTIONS

// BEGIN: CALENDAR OBJECT FUNCTIONS

/**
 *  This function creates the calendar inside the given parent.  If _par is
 *  null than it creates a popup calendar inside the BODY element.  If _par is
 *  an element, be it BODY, then it creates a non-popup calendar (still
 *  hidden).  Some properties need to be set before calling this function.
 */
Calendar.prototype.create = function (_par) {
	var parent = null;
	if (! _par) {
		// default parent is the document body, in which case we create
		// a popup calendar.
		parent = document.getElementsByTagName("body")[0];
		this.isPopup = true;
	} else {
		parent = _par;
		this.isPopup = false;
	}
	this.date = this.dateStr ? new Date(this.dateStr) : new Date();

	var table = Calendar.createElement("table");
	this.table = table;
	table.className = 'c_table';
	table.cellSpacing = 0;
	table.cellPadding = 0;
	table.calendar = this;
	Calendar.addEvent(table, "mousedown", Calendar.tableMouseDown);

	var div = Calendar.createElement("div");
	this.element = div;
	div.className = "calendar";
	if (this.isPopup) {
		div.style.position = "absolute";
		div.style.display = "none";
	}
	div.appendChild(table);

	var thead = Calendar.createElement("thead", table);
	var cell = null;
	var row = null;

	var cal = this;
	var hh = function (text, cs, navtype) {
		cell = Calendar.createElement("td", row);
		cell.colSpan = cs;
		cell.className = "c_button";
		if (navtype != 0 && Math.abs(navtype) <= 2)
			cell.className += " nav";
		Calendar._add_evs(cell);
		cell.calendar = cal;
		cell.navtype = navtype;
		cell.innerHTML = "<div unselectable='on'>" + text + "</div>";
		return cell;
	};

	row = Calendar.createElement("tr", thead);
	var title_length = 6;
	(this.isPopup) && --title_length;
	(this.weekNumbers) && ++title_length;

	//hh("?", 1, 400).ttip = Calendar._TT["INFO"];
	hh("&#x00d7;", 1, 200).ttip = Calendar._TT["CLOSE"];
	this.title = hh("", title_length, 300);
	this.title.className = "title";
	if (this.isPopup) {
		this.title.ttip = Calendar._TT["DRAG_TO_MOVE"];
		this.title.style.cursor = "move";
		hh("&#x00d7;", 1, 200).ttip = Calendar._TT["CLOSE"];
	}

	row = Calendar.createElement("tr", thead);
	row.className = "headrow";

	this._nav_py = hh("&#x00ab;", 1, -2);
	this._nav_py.ttip = Calendar._TT["PREV_YEAR"];

	this._nav_pm = hh("&#x2039;", 1, -1);
	this._nav_pm.ttip = Calendar._TT["PREV_MONTH"];

	this._nav_now = hh(Calendar._TT["TODAY"], this.weekNumbers ? 4 : 3, 0);
	this._nav_now.ttip = Calendar._TT["GO_TODAY"];

	this._nav_nm = hh("&#x203a;", 1, 1);
	this._nav_nm.ttip = Calendar._TT["NEXT_MONTH"];

	this._nav_ny = hh("&#x00bb;", 1, 2);
	this._nav_ny.ttip = Calendar._TT["NEXT_YEAR"];

	// day names
	row = Calendar.createElement("tr", thead);
	row.className = "daynames";
	if (this.weekNumbers) {
		cell = Calendar.createElement("td", row);
		cell.className = "name wn";
		cell.innerHTML = Calendar._TT["WK"];
	}
	for (var i = 7; i > 0; --i) {
		cell = Calendar.createElement("td", row);
		if (!i) {
			cell.navtype = 100;
			cell.calendar = this;
			Calendar._add_evs(cell);
		}
	}
	this.firstdayname = (this.weekNumbers) ? row.firstChild.nextSibling : row.firstChild;
	this._displayWeekdays();

	var tbody = Calendar.createElement("tbody", table);
	this.tbody = tbody;

	for (i = 6; i > 0; --i) {
		row = Calendar.createElement("tr", tbody);
		if (this.weekNumbers) {
			cell = Calendar.createElement("td", row);
		}
		for (var j = 7; j > 0; --j) {
			cell = Calendar.createElement("td", row);
			cell.calendar = this;
			Calendar._add_evs(cell);
		}
	}

	if (this.showsTime) {
		row = Calendar.createElement("tr", tbody);
		row.className = "time";

		cell = Calendar.createElement("td", row);
		cell.className = "time";
		cell.colSpan = 2;
		cell.innerHTML = Calendar._TT["TIME"] || "&nbsp;";

		cell = Calendar.createElement("td", row);
		cell.className = "time";
		cell.colSpan = this.weekNumbers ? 4 : 3;

		(function(){
			function makeTimePart(className, init, range_start, range_end) {
				var part = Calendar.createElement("span", cell);
				part.className = className;
				part.innerHTML = init;
				part.calendar = cal;
				part.ttip = Calendar._TT["TIME_PART"];
				part.navtype = 50;
				part._range = [];
				if (typeof range_start != "number")
					part._range = range_start;
				else {
					for (var i = range_start; i <= range_end; ++i) {
						var txt;
						if (i < 10 && range_end >= 10) txt = '0' + i;
						else txt = '' + i;
						part._range[part._range.length] = txt;
					}
				}
				Calendar._add_evs(part);
				return part;
			};
			var hrs = cal.date.getHours();
			var mins = cal.date.getMinutes();
			var t12 = !cal.time24;
			var pm = (hrs > 12);
			if (t12 && pm) hrs -= 12;
			var H = makeTimePart("hour", hrs, t12 ? 1 : 0, t12 ? 12 : 23);
			var span = Calendar.createElement("span", cell);
			span.innerHTML = ":";
			span.className = "colon";
			var M = makeTimePart("minute", mins, 0, 59);
			var AP = null;
			cell = Calendar.createElement("td", row);
			cell.className = "time";
			cell.colSpan = 2;
			if (t12)
				AP = makeTimePart("ampm", pm ? "pm" : "am", ["am", "pm"]);
			else
				cell.innerHTML = "&nbsp;";

			cal.onSetTime = function() {
				var pm, hrs = this.date.getHours(),
					mins = this.date.getMinutes();
				if (t12) {
					pm = (hrs >= 12);
					if (pm) hrs -= 12;
					if (hrs == 0) hrs = 12;
					AP.innerHTML = pm ? "pm" : "am";
				}
				H.innerHTML = (hrs < 10) ? ("0" + hrs) : hrs;
				M.innerHTML = (mins < 10) ? ("0" + mins) : mins;
			};

			cal.onUpdateTime = function() {
				var date = this.date;
				var h = parseInt(H.innerHTML, 10);
				if (t12) {
					if (/pm/i.test(AP.innerHTML) && h < 12)
						h += 12;
					else if (/am/i.test(AP.innerHTML) && h == 12)
						h = 0;
				}
				var d = date.getDate();
				var m = date.getMonth();
				var y = date.getFullYear();
				date.setHours(h);
				date.setMinutes(parseInt(M.innerHTML, 10));
				date.setFullYear(y);
				date.setMonth(m);
				date.setDate(d);
				this.dateClicked = false;
				this.callHandler();
			};
		})();
	} else {
		this.onSetTime = this.onUpdateTime = function() {};
	}

	var tfoot = Calendar.createElement("tfoot", table);

	row = Calendar.createElement("tr", tfoot);
	row.className = "footrow";

	cell = hh(Calendar._TT["SEL_DATE"], this.weekNumbers ? 8 : 7, 300);
	cell.className = "ttip";
	if (this.isPopup) {
		cell.ttip = Calendar._TT["DRAG_TO_MOVE"];
		cell.style.cursor = "move";
	}
	this.tooltips = cell;

	div = Calendar.createElement("div", this.element);
	this.monthsCombo = div;
	div.className = "combo";
	for (i = 0; i < Calendar._MN.length; ++i) {
		var mn = Calendar.createElement("div");
		mn.className = Calendar.is_ie ? "label-IEfix" : "label";
		mn.month = i;
		mn.innerHTML = Calendar._SMN[i];
		div.appendChild(mn);
	}

	div = Calendar.createElement("div", this.element);
	this.yearsCombo = div;
	div.className = "combo";
	for (i = 12; i > 0; --i) {
		var yr = Calendar.createElement("div");
		yr.className = Calendar.is_ie ? "label-IEfix" : "label";
		div.appendChild(yr);
	}

	this._init(this.firstDayOfWeek, this.date);
	parent.appendChild(this.element);
};

/** keyboard navigation, only for popup calendars */
Calendar._keyEvent = function(ev) {
	var cal = window._dynarch_popupCalendar;
	if (!cal || cal.multiple)
		return false;
	(Calendar.is_ie) && (ev = window.event);
	var act = (Calendar.is_ie || ev.type == "keypress"),
		K = ev.keyCode;
	if (ev.ctrlKey) {
		switch (K) {
		    case 37: // KEY left
			act && Calendar.cellClick(cal._nav_pm);
			break;
		    case 38: // KEY up
			act && Calendar.cellClick(cal._nav_py);
			break;
		    case 39: // KEY right
			act && Calendar.cellClick(cal._nav_nm);
			break;
		    case 40: // KEY down
			act && Calendar.cellClick(cal._nav_ny);
			break;
		    default:
			return false;
		}
	} else switch (K) {
	    case 32: // KEY space (now)
		Calendar.cellClick(cal._nav_now);
		break;
	    case 27: // KEY esc
		act && cal.callCloseHandler();
		break;
	    case 37: // KEY left
	    case 38: // KEY up
	    case 39: // KEY right
	    case 40: // KEY down
		if (act) {
			var prev, x, y, ne, el, step;
			prev = K == 37 || K == 38;
			step = (K == 37 || K == 39) ? 1 : 7;
			function setVars() {
				el = cal.currentDateEl;
				var p = el.pos;
				x = p & 15;
				y = p >> 4;
				ne = cal.ar_days[y][x];
			};setVars();
			function prevMonth() {
				var date = new Date(cal.date);
				date.setDate(date.getDate() - step);
				cal.setDate(date);
			};
			function nextMonth() {
				var date = new Date(cal.date);
				date.setDate(date.getDate() + step);
				cal.setDate(date);
			};
			while (1) {
				switch (K) {
				    case 37: // KEY left
					if (--x >= 0)
						ne = cal.ar_days[y][x];
					else {
						x = 6;
						K = 38;
						continue;
					}
					break;
				    case 38: // KEY up
					if (--y >= 0)
						ne = cal.ar_days[y][x];
					else {
						prevMonth();
						setVars();
					}
					break;
				    case 39: // KEY right
					if (++x < 7)
						ne = cal.ar_days[y][x];
					else {
						x = 0;
						K = 40;
						continue;
					}
					break;
				    case 40: // KEY down
					if (++y < cal.ar_days.length)
						ne = cal.ar_days[y][x];
					else {
						nextMonth();
						setVars();
					}
					break;
				}
				break;
			}
			if (ne) {
				if (!ne.disabled)
					Calendar.cellClick(ne);
				else if (prev)
					prevMonth();
				else
					nextMonth();
			}
		}
		break;
	    case 13: // KEY enter
		if (act)
			Calendar.cellClick(cal.currentDateEl, ev);
		break;
	    default:
		return false;
	}
	return Calendar.stopEvent(ev);
};

/**
 *  (RE)Initializes the calendar to the given date and firstDayOfWeek
 */
Calendar.prototype._init = function (firstDayOfWeek, date) {
	var today = new Date(),
		TY = today.getFullYear(),
		TM = today.getMonth(),
		TD = today.getDate();
	this.table.style.visibility = "hidden";
	var year = date.getFullYear();
	if (year < this.minYear) {
		year = this.minYear;
		date.setFullYear(year);
	} else if (year > this.maxYear) {
		year = this.maxYear;
		date.setFullYear(year);
	}
	this.firstDayOfWeek = firstDayOfWeek;
	this.date = new Date(date);
	var month = date.getMonth();
	var mday = date.getDate();
	var no_days = date.getMonthDays();

	// calendar voodoo for computing the first day that would actually be
	// displayed in the calendar, even if it's from the previous month.
	// WARNING: this is magic. ;-)
	date.setDate(1);
	var day1 = (date.getDay() - this.firstDayOfWeek) % 7;
	if (day1 < 0)
		day1 += 7;
	date.setDate(-day1);
	date.setDate(date.getDate() + 1);

	var row = this.tbody.firstChild;
	var MN = Calendar._SMN[month];
	var ar_days = this.ar_days = new Array();
	var weekend = Calendar._TT["WEEKEND"];
	var dates = this.multiple ? (this.datesCells = {}) : null;
	for (var i = 0; i < 6; ++i, row = row.nextSibling) {
		var cell = row.firstChild;
		if (this.weekNumbers) {
			cell.className = "day wn";
			cell.innerHTML = date.getWeekNumber();
			cell = cell.nextSibling;
		}
		row.className = "daysrow";
		var hasdays = false, iday, dpos = ar_days[i] = [];
		for (var j = 0; j < 7; ++j, cell = cell.nextSibling, date.setDate(iday + 1)) {
			iday = date.getDate();
			var wday = date.getDay();
			cell.className = "day";
			cell.pos = i << 4 | j;
			dpos[j] = cell;
			var current_month = (date.getMonth() == month);
			if (!current_month) {
				if (this.showsOtherMonths) {
					cell.className += " othermonth";
					cell.otherMonth = true;
				} else {
					cell.className = "emptycell";
					cell.innerHTML = "&nbsp;";
					cell.disabled = true;
					continue;
				}
			} else {
				cell.otherMonth = false;
				hasdays = true;
			}
			cell.disabled = false;
			cell.innerHTML = this.getDateText ? this.getDateText(date, iday) : iday;
			if (dates)
				dates[date.print("%Y%m%d")] = cell;
			if (this.getDateStatus) {
				var status = this.getDateStatus(date, year, month, iday);
				if (this.getDateToolTip) {
					var toolTip = this.getDateToolTip(date, year, month, iday);
					if (toolTip)
						cell.title = toolTip;
				}
				if (status === true) {
					cell.className += " disabled";
					cell.disabled = true;
				} else {
					if (/disabled/i.test(status))
						cell.disabled = true;
					cell.className += " " + status;
				}
			}
			if (!cell.disabled) {
				cell.caldate = new Date(date);
				cell.ttip = "_";
				if (!this.multiple && current_month
				    && iday == mday && this.hiliteToday) {
					cell.className += " selected";
					this.currentDateEl = cell;
				}
				if (date.getFullYear() == TY &&
				    date.getMonth() == TM &&
				    iday == TD) {
					cell.className += " today";
					cell.ttip += Calendar._TT["PART_TODAY"];
				}
				if (weekend.indexOf(wday.toString()) != -1)
					cell.className += cell.otherMonth ? " oweekend" : " weekend";
			}
		}
		if (!(hasdays || this.showsOtherMonths))
			row.className = "emptyrow";
	}
	this.title.innerHTML = Calendar._MN[month] + ", " + year;
	this.onSetTime();
	this.table.style.visibility = "visible";
	this._initMultipleDates();
	// PROFILE
	// this.tooltips.innerHTML = "Generated in " + ((new Date()) - today) + " ms";
};

Calendar.prototype._initMultipleDates = function() {
	if (this.multiple) {
		for (var i in this.multiple) {
			var cell = this.datesCells[i];
			var d = this.multiple[i];
			if (!d)
				continue;
			if (cell)
				cell.className += " selected";
		}
	}
};

Calendar.prototype._toggleMultipleDate = function(date) {
	if (this.multiple) {
		var ds = date.print("%Y%m%d");
		var cell = this.datesCells[ds];
		if (cell) {
			var d = this.multiple[ds];
			if (!d) {
				Calendar.addClass(cell, "selected");
				this.multiple[ds] = date;
			} else {
				Calendar.removeClass(cell, "selected");
				delete this.multiple[ds];
			}
		}
	}
};

Calendar.prototype.setDateToolTipHandler = function (unaryFunction) {
	this.getDateToolTip = unaryFunction;
};

/**
 *  Calls _init function above for going to a certain date (but only if the
 *  date is different than the currently selected one).
 */
Calendar.prototype.setDate = function (date) {
	if (!date.equalsTo(this.date)) {
		this._init(this.firstDayOfWeek, date);
	}
};

/**
 *  Refreshes the calendar.  Useful if the "disabledHandler" function is
 *  dynamic, meaning that the list of disabled date can change at runtime.
 *  Just * call this function if you think that the list of disabled dates
 *  should * change.
 */
Calendar.prototype.refresh = function () {
	this._init(this.firstDayOfWeek, this.date);
};

/** Modifies the "firstDayOfWeek" parameter (pass 0 for Synday, 1 for Monday, etc.). */
Calendar.prototype.setFirstDayOfWeek = function (firstDayOfWeek) {
	this._init(firstDayOfWeek, this.date);
	this._displayWeekdays();
};

/**
 *  Allows customization of what dates are enabled.  The "unaryFunction"
 *  parameter must be a function object that receives the date (as a JS Date
 *  object) and returns a boolean value.  If the returned value is true then
 *  the passed date will be marked as disabled.
 */
Calendar.prototype.setDateStatusHandler = Calendar.prototype.setDisabledHandler = function (unaryFunction) {
	this.getDateStatus = unaryFunction;
};

/** Customization of allowed year range for the calendar. */
Calendar.prototype.setRange = function (a, z) {
	this.minYear = a;
	this.maxYear = z;
};

/** Calls the first user handler (selectedHandler). */
Calendar.prototype.callHandler = function () {
	if (this.onSelected) {
		this.onSelected(this, this.date.print(this.dateFormat));
	}
};

/** Calls the second user handler (closeHandler). */
Calendar.prototype.callCloseHandler = function () {
	if (this.onClose) {
		this.onClose(this);
	}
	this.hideShowCovered();
};

/** Removes the calendar object from the DOM tree and destroys it. */
Calendar.prototype.destroy = function () {
	var el = this.element.parentNode;
	el.removeChild(this.element);
	Calendar._C = null;
	window._dynarch_popupCalendar = null;
};

/**
 *  Moves the calendar element to a different section in the DOM tree (changes
 *  its parent).
 */
Calendar.prototype.reparent = function (new_parent) {
	var el = this.element;
	el.parentNode.removeChild(el);
	new_parent.appendChild(el);
};

// This gets called when the user presses a mouse button anywhere in the
// document, if the calendar is shown.  If the click was outside the open
// calendar this function closes it.
Calendar._checkCalendar = function(ev) {
	var calendar = window._dynarch_popupCalendar;
	if (!calendar) {
		return false;
	}
	var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev);
	for (; el != null && el != calendar.element; el = el.parentNode);
	if (el == null) {
		// calls closeHandler which should hide the calendar.
		window._dynarch_popupCalendar.callCloseHandler();
		return Calendar.stopEvent(ev);
	}
};

/** Shows the calendar. */
Calendar.prototype.show = function () {
	var rows = this.table.getElementsByTagName("tr");
	for (var i = rows.length; i > 0;) {
		var row = rows[--i];
		Calendar.removeClass(row, "rowhilite");
		var cells = row.getElementsByTagName("td");
		for (var j = cells.length; j > 0;) {
			var cell = cells[--j];
			Calendar.removeClass(cell, "hilite");
			Calendar.removeClass(cell, "active");
		}
	}
	this.element.style.display = "block";
	this.hidden = false;
	if (this.isPopup) {
		window._dynarch_popupCalendar = this;
		Calendar.addEvent(document, "keydown", Calendar._keyEvent);
		Calendar.addEvent(document, "keypress", Calendar._keyEvent);
		Calendar.addEvent(document, "mousedown", Calendar._checkCalendar);
	}
	this.hideShowCovered();
};

/**
 *  Hides the calendar.  Also removes any "hilite" from the class of any TD
 *  element.
 */
Calendar.prototype.hide = function () {
	if (this.isPopup) {
		Calendar.removeEvent(document, "keydown", Calendar._keyEvent);
		Calendar.removeEvent(document, "keypress", Calendar._keyEvent);
		Calendar.removeEvent(document, "mousedown", Calendar._checkCalendar);
	}
	this.element.style.display = "none";
	this.hidden = true;
	this.hideShowCovered();
};

/**
 *  Shows the calendar at a given absolute position (beware that, depending on
 *  the calendar element style -- position property -- this might be relative
 *  to the parent's containing rectangle).
 */
Calendar.prototype.showAt = function (x, y) {
	var s = this.element.style;
	s.left = x + "px";
	s.top = y + "px";
	this.show();
};

/** Shows the calendar near a given element. */
Calendar.prototype.showAtElement = function (el, opts) {
	var self = this;
	var p = Calendar.getAbsolutePos(el);
	if (!opts || typeof opts != "string") {
		this.showAt(p.x, p.y + el.offsetHeight);
		return true;
	}
	function fixPosition(box) {
		if (box.x < 0)
			box.x = 0;
		if (box.y < 0)
			box.y = 0;
		var cp = document.createElement("div");
		var s = cp.style;
		s.position = "absolute";
		s.right = s.bottom = s.width = s.height = "0px";
		document.body.appendChild(cp);
		var br = Calendar.getAbsolutePos(cp);
		document.body.removeChild(cp);
		if (Calendar.is_ie) {
			br.y += document.body.scrollTop;
			br.x += document.body.scrollLeft;
		} else {
			br.y += window.scrollY;
			br.x += window.scrollX;
		}
		var tmp = box.x + box.width - br.x;
		if (tmp > 0) box.x -= tmp;
		tmp = box.y + box.height - br.y;
		if (tmp > 0) box.y -= tmp;
	};
	this.element.style.display = "block";
	Calendar.continuation_for_the_fucking_khtml_browser = function() {
		var w = self.element.offsetWidth;
		var h = self.element.offsetHeight;
		self.element.style.display = "none";
		var valign = opts.substr(0, 1);
		var halign = "l";
		if (opts.length > 1) {
			halign = opts.substr(1, 1);
		}
		// vertical alignment
		switch (valign) {
		    case "T": p.y -= h; break;
		    case "B": p.y += el.offsetHeight; break;
		    case "C": p.y += (el.offsetHeight - h) / 2; break;
		    case "t": p.y += el.offsetHeight - h; break;
		    case "b": break; // already there
		}
		// horizontal alignment
		switch (halign) {
		    case "L": p.x -= w; break;
		    case "R": p.x += el.offsetWidth; break;
		    case "C": p.x += (el.offsetWidth - w) / 2; break;
		    case "l": p.x += el.offsetWidth - w; break;
		    case "r": break; // already there
		}
		p.width = w;
		p.height = h + 40;
		self.monthsCombo.style.display = "none";
		fixPosition(p);
		self.showAt(p.x, p.y);
	};
	if (Calendar.is_khtml)
		setTimeout("Calendar.continuation_for_the_fucking_khtml_browser()", 10);
	else
		Calendar.continuation_for_the_fucking_khtml_browser();
};

/** Customizes the date format. */
Calendar.prototype.setDateFormat = function (str) {
	this.dateFormat = str;
};

/** Customizes the tooltip date format. */
Calendar.prototype.setTtDateFormat = function (str) {
	this.ttDateFormat = str;
};

/**
 *  Tries to identify the date represented in a string.  If successful it also
 *  calls this.setDate which moves the calendar to the given date.
 */
Calendar.prototype.parseDate = function(str, fmt) {
	if (!fmt)
		fmt = this.dateFormat;
	this.setDate(Date.parseDate(str, fmt));
};

Calendar.prototype.hideShowCovered = function () {
	if (!Calendar.is_ie && !Calendar.is_opera)
		return;
	function getVisib(obj){
		var value = obj.style.visibility;
		if (!value) {
			if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function") { // Gecko, W3C
				if (!Calendar.is_khtml)
					value = document.defaultView.
						getComputedStyle(obj, "").getPropertyValue("visibility");
				else
					value = '';
			} else if (obj.currentStyle) { // IE
				value = obj.currentStyle.visibility;
			} else
				value = '';
		}
		return value;
	};

	var tags = new Array("applet", "iframe", "select");
	var el = this.element;

	var p = Calendar.getAbsolutePos(el);
	var EX1 = p.x;
	var EX2 = el.offsetWidth + EX1;
	var EY1 = p.y;
	var EY2 = el.offsetHeight + EY1;

	for (var k = tags.length; k > 0; ) {
		var ar = document.getElementsByTagName(tags[--k]);
		var cc = null;

		for (var i = ar.length; i > 0;) {
			cc = ar[--i];

			p = Calendar.getAbsolutePos(cc);
			var CX1 = p.x;
			var CX2 = cc.offsetWidth + CX1;
			var CY1 = p.y;
			var CY2 = cc.offsetHeight + CY1;

			if (this.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) {
				if (!cc.__msh_save_visibility) {
					cc.__msh_save_visibility = getVisib(cc);
				}
				cc.style.visibility = cc.__msh_save_visibility;
			} else {
				if (!cc.__msh_save_visibility) {
					cc.__msh_save_visibility = getVisib(cc);
				}
				cc.style.visibility = "hidden";
			}
		}
	}
};

/** Internal function; it displays the bar with the names of the weekday. */
Calendar.prototype._displayWeekdays = function () {
	var fdow = this.firstDayOfWeek;
	var cell = this.firstdayname;
	var weekend = Calendar._TT["WEEKEND"];
	for (var i = 0; i < 7; ++i) {
		cell.className = "day name";
		var realday = (i + fdow) % 7;
		if (i) {
			cell.ttip = Calendar._TT["DAY_FIRST"].replace("%s", Calendar._DN[realday]);
			cell.navtype = 100;
			cell.calendar = this;
			cell.fdow = realday;
			Calendar._add_evs(cell);
		}
		if (weekend.indexOf(realday.toString()) != -1) {
			Calendar.addClass(cell, "weekend");
		}
		cell.innerHTML = Calendar._SDN[(i + fdow) % 7];
		cell = cell.nextSibling;
	}
};

/** Internal function.  Hides all combo boxes that might be displayed. */
Calendar.prototype._hideCombos = function () {
	this.monthsCombo.style.display = "none";
	this.yearsCombo.style.display = "none";
};

/** Internal function.  Starts dragging the element. */
Calendar.prototype._dragStart = function (ev) {
	if (this.dragging) {
		return;
	}
	this.dragging = true;
	var posX;
	var posY;
	if (Calendar.is_ie) {
		posY = window.event.clientY + document.body.scrollTop;
		posX = window.event.clientX + document.body.scrollLeft;
	} else {
		posY = ev.clientY + window.scrollY;
		posX = ev.clientX + window.scrollX;
	}
	var st = this.element.style;
	this.xOffs = posX - parseInt(st.left);
	this.yOffs = posY - parseInt(st.top);
	with (Calendar) {
		addEvent(document, "mousemove", calDragIt);
		addEvent(document, "mouseup", calDragEnd);
	}
};

// BEGIN: DATE OBJECT PATCHES

/** Adds the number of days array to the Date object. */
Date._MD = new Array(31,28,31,30,31,30,31,31,30,31,30,31);

/** Constants used for time computations */
Date.SECOND = 1000 /* milliseconds */;
Date.MINUTE = 60 * Date.SECOND;
Date.HOUR   = 60 * Date.MINUTE;
Date.DAY    = 24 * Date.HOUR;
Date.WEEK   =  7 * Date.DAY;

Date.parseDate = function(str, fmt) {
	var today = new Date();
	var y = 0;
	var m = -1;
	var d = 0;
	var a = str.split(/\W+/);
	var b = fmt.match(/%./g);
	var i = 0, j = 0;
	var hr = 0;
	var min = 0;
	for (i = 0; i < a.length; ++i) {
		if (!a[i])
			continue;
		switch (b[i]) {
		    case "%d":
		    case "%e":
			d = parseInt(a[i], 10);
			break;

		    case "%m":
			m = parseInt(a[i], 10) - 1;
			break;

		    case "%Y":
		    case "%y":
			y = parseInt(a[i], 10);
			(y < 100) && (y += (y > 29) ? 1900 : 2000);
			break;

		    case "%b":
		    case "%B":
			for (j = 0; j < 12; ++j) {
				if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; }
			}
			break;

		    case "%H":
		    case "%I":
		    case "%k":
		    case "%l":
			hr = parseInt(a[i], 10);
			break;

		    case "%P":
		    case "%p":
			if (/pm/i.test(a[i]) && hr < 12)
				hr += 12;
			else if (/am/i.test(a[i]) && hr >= 12)
				hr -= 12;
			break;

		    case "%M":
			min = parseInt(a[i], 10);
			break;
		}
	}
	if (isNaN(y)) y = today.getFullYear();
	if (isNaN(m)) m = today.getMonth();
	if (isNaN(d)) d = today.getDate();
	if (isNaN(hr)) hr = today.getHours();
	if (isNaN(min)) min = today.getMinutes();
	if (y != 0 && m != -1 && d != 0)
		return new Date(y, m, d, hr, min, 0);
	y = 0; m = -1; d = 0;
	for (i = 0; i < a.length; ++i) {
		if (a[i].search(/[a-zA-Z]+/) != -1) {
			var t = -1;
			for (j = 0; j < 12; ++j) {
				if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { t = j; break; }
			}
			if (t != -1) {
				if (m != -1) {
					d = m+1;
				}
				m = t;
			}
		} else if (parseInt(a[i], 10) <= 12 && m == -1) {
			m = a[i]-1;
		} else if (parseInt(a[i], 10) > 31 && y == 0) {
			y = parseInt(a[i], 10);
			(y < 100) && (y += (y > 29) ? 1900 : 2000);
		} else if (d == 0) {
			d = a[i];
		}
	}
	if (y == 0)
		y = today.getFullYear();
	if (m != -1 && d != 0)
		return new Date(y, m, d, hr, min, 0);
	return today;
};

/** Returns the number of days in the current month */
Date.prototype.getMonthDays = function(month) {
	var year = this.getFullYear();
	if (typeof month == "undefined") {
		month = this.getMonth();
	}
	if (((0 == (year%4)) && ( (0 != (year%100)) || (0 == (year%400)))) && month == 1) {
		return 29;
	} else {
		return Date._MD[month];
	}
};

/** Returns the number of day in the year. */
Date.prototype.getDayOfYear = function() {
	var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
	var then = new Date(this.getFullYear(), 0, 0, 0, 0, 0);
	var time = now - then;
	return Math.floor(time / Date.DAY);
};

/** Returns the number of the week in year, as defined in ISO 8601. */
Date.prototype.getWeekNumber = function() {
	var d = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
	var DoW = d.getDay();
	d.setDate(d.getDate() - (DoW + 6) % 7 + 3); // Nearest Thu
	var ms = d.valueOf(); // GMT
	d.setMonth(0);
	d.setDate(4); // Thu in Week 1
	return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1;
};

/** Checks date and time equality */
Date.prototype.equalsTo = function(date) {
	return ((this.getFullYear() == date.getFullYear()) &&
		(this.getMonth() == date.getMonth()) &&
		(this.getDate() == date.getDate()) &&
		(this.getHours() == date.getHours()) &&
		(this.getMinutes() == date.getMinutes()));
};

/** Set only the year, month, date parts (keep existing time) */
Date.prototype.setDateOnly = function(date) {
	var tmp = new Date(date);
	this.setDate(1);
	this.setFullYear(tmp.getFullYear());
	this.setMonth(tmp.getMonth());
	this.setDate(tmp.getDate());
};

/** Prints the date in a string according to the given format. */
Date.prototype.print = function (str) {
	var m = this.getMonth();
	var d = this.getDate();
	var y = this.getFullYear();
	var wn = this.getWeekNumber();
	var w = this.getDay();
	var s = {};
	var hr = this.getHours();
	var pm = (hr >= 12);
	var ir = (pm) ? (hr - 12) : hr;
	var dy = this.getDayOfYear();
	if (ir == 0)
		ir = 12;
	var min = this.getMinutes();
	var sec = this.getSeconds();
	s["%a"] = Calendar._SDN[w]; // abbreviated weekday name [FIXME: I18N]
	s["%A"] = Calendar._DN[w]; // full weekday name
	s["%b"] = Calendar._SMN[m]; // abbreviated month name [FIXME: I18N]
	s["%B"] = Calendar._MN[m]; // full month name
	// FIXME: %c : preferred date and time representation for the current locale
	s["%C"] = 1 + Math.floor(y / 100); // the century number
	s["%d"] = (d < 10) ? ("0" + d) : d; // the day of the month (range 01 to 31)
	s["%e"] = d; // the day of the month (range 1 to 31)
	// FIXME: %D : american date style: %m/%d/%y
	// FIXME: %E, %F, %G, %g, %h (man strftime)
	s["%H"] = (hr < 10) ? ("0" + hr) : hr; // hour, range 00 to 23 (24h format)
	s["%I"] = (ir < 10) ? ("0" + ir) : ir; // hour, range 01 to 12 (12h format)
	s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy; // day of the year (range 001 to 366)
	s["%k"] = hr;		// hour, range 0 to 23 (24h format)
	s["%l"] = ir;		// hour, range 1 to 12 (12h format)
	s["%m"] = (m < 9) ? ("0" + (1+m)) : (1+m); // month, range 01 to 12
	s["%M"] = (min < 10) ? ("0" + min) : min; // minute, range 00 to 59
	s["%n"] = "\n";		// a newline character
	s["%p"] = pm ? "PM" : "AM";
	s["%P"] = pm ? "pm" : "am";
	// FIXME: %r : the time in am/pm notation %I:%M:%S %p
	// FIXME: %R : the time in 24-hour notation %H:%M
	s["%s"] = Math.floor(this.getTime() / 1000);
	s["%S"] = (sec < 10) ? ("0" + sec) : sec; // seconds, range 00 to 59
	s["%t"] = "\t";		// a tab character
	// FIXME: %T : the time in 24-hour notation (%H:%M:%S)
	s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn;
	s["%u"] = w + 1;	// the day of the week (range 1 to 7, 1 = MON)
	s["%w"] = w;		// the day of the week (range 0 to 6, 0 = SUN)
	// FIXME: %x : preferred date representation for the current locale without the time
	// FIXME: %X : preferred time representation for the current locale without the date
	s["%y"] = ('' + y).substr(2, 2); // year without the century (range 00 to 99)
	s["%Y"] = y;		// year with the century
	s["%%"] = "%";		// a literal '%' character

	var re = /%./g;
	if (!Calendar.is_ie5 && !Calendar.is_khtml)
		return str.replace(re, function (par) { return s[par] || par; });

	var a = str.match(re);
	for (var i = 0; i < a.length; i++) {
		var tmp = s[a[i]];
		if (tmp) {
			re = new RegExp(a[i], 'g');
			str = str.replace(re, tmp);
		}
	}

	return str;
};

Date.prototype.__msh_oldSetFullYear = Date.prototype.setFullYear;
Date.prototype.setFullYear = function(y) {
	var d = new Date(this);
	d.__msh_oldSetFullYear(y);
	if (d.getMonth() != this.getMonth())
		this.setDate(28);
	this.__msh_oldSetFullYear(y);
};

// END: DATE OBJECT PATCHES


// global object that remembers the calendar
window._dynarch_popupCalendar = null;
/*  Copyright Mihai Bazon, 2002, 2003  |  http://dynarch.com/mishoo/
 * ---------------------------------------------------------------------------
 *
 * The DHTML Calendar
 *
 * Details and latest version at:
 * http://dynarch.com/mishoo/calendar.epl
 *
 * This script is distributed under the GNU Lesser General Public License.
 * Read the entire license text here: http://www.gnu.org/licenses/lgpl.html
 *
 * This file defines helper functions for setting up the calendar.  They are
 * intended to help non-programmers get a working calendar on their site
 * quickly.  This script should not be seen as part of the calendar.  It just
 * shows you what one can do with the calendar, while in the same time
 * providing a quick and simple method for setting it up.  If you need
 * exhaustive customization of the calendar creation process feel free to
 * modify this code to suit your needs (this is recommended and much better
 * than modifying calendar.js itself).
 */

// $Id: calendar-setup.js,v 1.25 2005/03/07 09:51:33 mishoo Exp $

/**
 *  This function "patches" an input field (or other element) to use a calendar
 *  widget for date selection.
 *
 *  The "params" is a single object that can have the following properties:
 *
 *    prop. name   | description
 *  -------------------------------------------------------------------------------------------------
 *   inputField    | the ID of an input field to store the date
 *   displayArea   | the ID of a DIV or other element to show the date
 *   button        | ID of a button or other element that will trigger the calendar
 *   eventName     | event that will trigger the calendar, without the "on" prefix (default: "click")
 *   ifFormat      | date format that will be stored in the input field
 *   daFormat      | the date format that will be used to display the date in displayArea
 *   singleClick   | (true/false) wether the calendar is in single click mode or not (default: true)
 *   firstDay      | numeric: 0 to 6.  "0" means display Sunday first, "1" means display Monday first, etc.
 *   align         | alignment (default: "Br"); if you don't know what's this see the calendar documentation
 *   range         | array with 2 elements.  Default: [1900, 2999] -- the range of years available
 *   weekNumbers   | (true/false) if it's true (default) the calendar will display week numbers
 *   flat          | null or element ID; if not null the calendar will be a flat calendar having the parent with the given ID
 *   flatCallback  | function that receives a JS Date object and returns an URL to point the browser to (for flat calendar)
 *   disableFunc   | function that receives a JS Date object and should return true if that date has to be disabled in the calendar
 *   onSelect      | function that gets called when a date is selected.  You don't _have_ to supply this (the default is generally okay)
 *   onClose       | function that gets called when the calendar is closed.  [default]
 *   onUpdate      | function that gets called after the date is updated in the input field.  Receives a reference to the calendar.
 *   date          | the date that the calendar will be initially displayed to
 *   showsTime     | default: false; if true the calendar will include a time selector
 *   timeFormat    | the time format; can be "12" or "24", default is "12"
 *   electric      | if true (default) then given fields/date areas are updated for each move; otherwise they're updated only on close
 *   step          | configures the step of the years in drop-down boxes; default: 2
 *   position      | configures the calendar absolute position; default: null
 *   cache         | if "true" (but default: "false") it will reuse the same calendar object, where possible
 *   showOthers    | if "true" (but default: "false") it will show days from other months too
 *
 *  None of them is required, they all have default values.  However, if you
 *  pass none of "inputField", "displayArea" or "button" you'll get a warning
 *  saying "nothing to setup".
 */
Calendar.setup = function (params) {
	function param_default(pname, def) { if (typeof params[pname] == "undefined") { params[pname] = def; } };

	param_default("inputField",     null);
	param_default("displayArea",    null);
	param_default("button",         null);
	param_default("eventName",      "click");
	param_default("ifFormat",       "%Y/%m/%d");
	param_default("daFormat",       "%Y/%m/%d");
	param_default("singleClick",    true);
	param_default("disableFunc",    null);
	param_default("dateStatusFunc", params["disableFunc"]);	// takes precedence if both are defined
	param_default("dateText",       null);
	param_default("firstDay",       null);
	param_default("align",          "Br");
	param_default("range",          [1900, 2999]);
	param_default("weekNumbers",    true);
	param_default("flat",           null);
	param_default("flatCallback",   null);
	param_default("onSelect",       null);
	param_default("onClose",        null);
	param_default("onUpdate",       null);
	param_default("date",           null);
	param_default("showsTime",      false);
	param_default("timeFormat",     "24");
	param_default("electric",       true);
	param_default("step",           2);
	param_default("position",       null);
	param_default("cache",          false);
	param_default("showOthers",     false);
	param_default("multiple",       null);

	var tmp = ["inputField", "displayArea", "button"];
	for (var i in tmp) {
		if (typeof params[tmp[i]] == "string") {
			params[tmp[i]] = document.getElementById(params[tmp[i]]);
		}
	}
	if (!(params.flat || params.multiple || params.inputField || params.displayArea || params.button)) {
		alert("Calendar.setup:\n  Nothing to setup (no fields found).  Please check your code");
		return false;
	}

	function onSelect(cal) {
		var p = cal.params;
		var update = (cal.dateClicked || p.electric);
		if (update && p.inputField) {
			p.inputField.value = cal.date.print(p.ifFormat);
			if (typeof p.inputField.onchange == "function")
				p.inputField.onchange();
		}
		if (update && p.displayArea)
			p.displayArea.innerHTML = cal.date.print(p.daFormat);
		if (update && typeof p.onUpdate == "function")
			p.onUpdate(cal);
		if (update && p.flat) {
			if (typeof p.flatCallback == "function")
				p.flatCallback(cal);
		}
		if (update && p.singleClick && cal.dateClicked)
			cal.callCloseHandler();
	};

	if (params.flat != null) {
		if (typeof params.flat == "string")
			params.flat = document.getElementById(params.flat);
		if (!params.flat) {
			alert("Calendar.setup:\n  Flat specified but can't find parent.");
			return false;
		}
		var cal = new Calendar(params.firstDay, params.date, params.onSelect || onSelect);
		cal.showsOtherMonths = params.showOthers;
		cal.showsTime = params.showsTime;
		cal.time24 = (params.timeFormat == "24");
		cal.params = params;
		cal.weekNumbers = params.weekNumbers;
		cal.setRange(params.range[0], params.range[1]);
		cal.setDateStatusHandler(params.dateStatusFunc);
		cal.getDateText = params.dateText;
		if (params.ifFormat) {
			cal.setDateFormat(params.ifFormat);
		}
		if (params.inputField && typeof params.inputField.value == "string") {
			cal.parseDate(params.inputField.value);
		}
		cal.create(params.flat);
		cal.show();
		return false;
	}

	var triggerEl = params.button || params.displayArea || params.inputField;
	triggerEl["on" + params.eventName] = function() {
		var dateEl = params.inputField || params.displayArea;
		var dateFmt = params.inputField ? params.ifFormat : params.daFormat;
		var mustCreate = false;
		var cal = window.calendar;
		if (dateEl)
			params.date = Date.parseDate(dateEl.value || dateEl.innerHTML, dateFmt);
		if (!(cal && params.cache)) {
			window.calendar = cal = new Calendar(params.firstDay,
							     params.date,
							     params.onSelect || onSelect,
							     params.onClose || function(cal) { cal.hide(); });
			cal.showsTime = params.showsTime;
			cal.time24 = (params.timeFormat == "24");
			cal.weekNumbers = params.weekNumbers;
			mustCreate = true;
		} else {
			if (params.date)
				cal.setDate(params.date);
			cal.hide();
		}
		if (params.multiple) {
			cal.multiple = {};
			for (var i = params.multiple.length; --i >= 0;) {
				var d = params.multiple[i];
				var ds = d.print("%Y%m%d");
				cal.multiple[ds] = d;
			}
		}
		cal.showsOtherMonths = params.showOthers;
		cal.yearStep = params.step;
		cal.setRange(params.range[0], params.range[1]);
		cal.params = params;
		cal.setDateStatusHandler(params.dateStatusFunc);
		cal.getDateText = params.dateText;
		cal.setDateFormat(dateFmt);
		if (mustCreate)
			cal.create();
		cal.refresh();
		if (!params.position)
			cal.showAtElement(params.button || params.displayArea || params.inputField, params.align);
		else
			cal.showAt(params.position[0], params.position[1]);
		return false;
	};

	return cal;
};
// ** I18N

// Calendar EN language
// Author: Mihai Bazon, <mihai_bazon@yahoo.com>
// Encoding: any
// Distributed under the same terms as the calendar itself.

// For translators: please use UTF-8 if possible.  We strongly believe that
// Unicode is the answer to a real internationalized world.  Also please
// include your contact information in the header, as can be seen above.

// full day names
Calendar._DN = new Array
("Sunday",
 "Monday",
 "Tuesday",
 "Wednesday",
 "Thursday",
 "Friday",
 "Saturday",
 "Sunday");

// Please note that the following array of short day names (and the same goes
// for short month names, _SMN) isn't absolutely necessary.  We give it here
// for exemplification on how one can customize the short day names, but if
// they are simply the first N letters of the full name you can simply say:
//
//   Calendar._SDN_len = N; // short day name length
//   Calendar._SMN_len = N; // short month name length
//
// If N = 3 then this is not needed either since we assume a value of 3 if not
// present, to be compatible with translation files that were written before
// this feature.

// short day names
Calendar._SDN = new Array
("Sun",
 "Mon",
 "Tue",
 "Wed",
 "Thu",
 "Fri",
 "Sat",
 "Sun");

// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 0;

// full month names
Calendar._MN = new Array
("January",
 "February",
 "March",
 "April",
 "May",
 "June",
 "July",
 "August",
 "September",
 "October",
 "November",
 "December");

// short month names
Calendar._SMN = new Array
("Jan",
 "Feb",
 "Mar",
 "Apr",
 "May",
 "Jun",
 "Jul",
 "Aug",
 "Sep",
 "Oct",
 "Nov",
 "Dec");

// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "About the calendar";

Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"For latest version visit: http://www.dynarch.com/projects/calendar/\n" +
"Distributed under GNU LGPL.  See http://gnu.org/licenses/lgpl.html for details." +
"\n\n" +
"Date selection:\n" +
"- Use the \xab, \xbb buttons to select year\n" +
"- Use the " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " buttons to select month\n" +
"- Hold mouse button on any of the above buttons for faster selection.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Time selection:\n" +
"- Click on any of the time parts to increase it\n" +
"- or Shift-click to decrease it\n" +
"- or click and drag for faster selection.";

Calendar._TT["PREV_YEAR"] = "Prev. year (hold for menu)";
Calendar._TT["PREV_MONTH"] = "Prev. month (hold for menu)";
Calendar._TT["GO_TODAY"] = "Go Today";
Calendar._TT["NEXT_MONTH"] = "Next month (hold for menu)";
Calendar._TT["NEXT_YEAR"] = "Next year (hold for menu)";
Calendar._TT["SEL_DATE"] = "Select date";
Calendar._TT["DRAG_TO_MOVE"] = "Drag to move";
Calendar._TT["PART_TODAY"] = " (today)";

// the following is to inform that "%s" is to be the first day of week
// %s will be replaced with the day name.
Calendar._TT["DAY_FIRST"] = "Display %s first";

// This may be locale-dependent.  It specifies the week-end days, as an array
// of comma-separated numbers.  The numbers are from 0 to 6: 0 means Sunday, 1
// means Monday, etc.
Calendar._TT["WEEKEND"] = "0,6";

Calendar._TT["CLOSE"] = "Close";
Calendar._TT["TODAY"] = "Today";
Calendar._TT["TIME_PART"] = "(Shift-)Click or drag to change value";

// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";

Calendar._TT["WK"] = "wk";
Calendar._TT["TIME"] = "Time:";
//<script>
/*
 * Position functions
 *
 * This script was designed for use with DHTML Menu 4
 *
 * This script was created by Erik Arvidsson
 * (http://webfx.eae.net/contact.html#erik)
 * for WebFX (http://webfx.eae.net)
 * Copyright 2002
 * 
 * For usage see license at http://webfx.eae.net/license.html	
 *
 * Version: 1.1
 * Created: 2002-05-28
 * Updated: 2002-06-06	Rewrote to use getBoundingClientRect(). This solved
 *						several bugs related to relative and absolute positened
 *						elements
 *
 *
 */

// This only works in IE5 and IE6+ with both CSS1 and Quirk mode

var posLib = {

	getIeBox:		function (el) {
		return this.ie && el.document.compatMode != "CSS1Compat";
	},
	
	// relative client viewport (outer borders of viewport)
	getClientLeft:	function (el) {
		var r = el.getBoundingClientRect();
		return r.left - this.getBorderLeftWidth(this.getCanvasElement(el));
	},

	getClientTop:	function (el) {
		var r = el.getBoundingClientRect();
		return r.top - this.getBorderTopWidth(this.getCanvasElement(el));
	},

	// relative canvas/document (outer borders of canvas/document,
	// outside borders of element)
	getLeft:	function (el) {
		return this.getClientLeft(el) + this.getCanvasElement(el).scrollLeft;
	},

	getTop:	function (el) {
		return this.getClientTop(el) + this.getCanvasElement(el).scrollTop;
	},

	// relative canvas/document (outer borders of canvas/document,
	// inside borders of element)
	getInnerLeft:	function (el) {
		return this.getLeft(el) + this.getBorderLeftWidth(el);
	},

	getInnerTop:	function (el) {
		return this.getTop(el) + this.getBorderTopWidth(el);
	},

	// width and height (outer, border-box)
	getWidth:	function (el) {
		return el.offsetWidth;
	},

	getHeight:	function (el) {
		return el.offsetHeight;
	},

	getCanvasElement:	function (el) {
		var doc = el.ownerDocument || el.document;	// IE55 bug
		if (doc.compatMode == "CSS1Compat")
			return doc.documentElement;
		else
			return doc.body;
	},

	getBorderLeftWidth:	function (el) {
		return el.clientLeft;
	},

	getBorderTopWidth:	function (el) {
		return el.clientTop;
	},

	getScreenLeft:	function (el) {
		var doc = el.ownerDocument || el.document;	// IE55 bug
		var w = doc.parentWindow;
		return w.screenLeft + this.getBorderLeftWidth(this.getCanvasElement(el)) +
			this.getClientLeft(el);
	},

	getScreenTop:	function (el) {
		var doc = el.ownerDocument || el.document;	// IE55 bug
		var w = doc.parentWindow;
		return w.screenTop + this.getBorderTopWidth(this.getCanvasElement(el)) +
			this.getClientTop(el);
	}
};

posLib.ua =		navigator.userAgent;
posLib.opera =	/opera [56789]|opera\/[56789]/i.test(posLib.ua);
posLib.ie =		(!posLib.opera) && /MSIE/.test(posLib.ua);
posLib.ie6 =	posLib.ie && /MSIE [6789]/.test(posLib.ua);
posLib.moz =	!posLib.opera && /gecko/i.test(posLib.ua);//<script>
/*
 * ScrollButton
 *
 * This script was designed for use with DHTML Menu 4
 *
 * This script was created by Erik Arvidsson
 * (http://webfx.eae.net/contact.html#erik)
 * for WebFX (http://webfx.eae.net)
 * Copyright 2002
 *
 * For usage see license at http://webfx.eae.net/license.html
 *
 * Version: 1.02
 * Created: 2002-05-28
 * Updated:	???			Memory management updates
 *			2003-09-23	Changed to using onunload instead onbeforeunload
 *
 */

////////////////////////////////////////////////////////////////////////////////////
// scroolButtonCache
//

var scrollButtonCache = {
	_count:		0,
	_idPrefix:	"-scroll-button-cache-",

	getId:	function () {
		return this._idPrefix + this._count++;
	},

	remove:	function ( o ) {
		delete this[ o.id ];
	}
};

function ScrollButton( oEl, oScrollContainer, nDir ) {
	this.htmlElement = oEl;
	this.scrollContainer = oScrollContainer;
	this.dir = nDir;

	this.id = scrollButtonCache.getId();
	scrollButtonCache[ this.id ] = this;

	this.makeEventListeners();
	this.attachEvents();
}

ScrollButton.scrollIntervalPause = 100;
ScrollButton.scrollAmount = 18;

ScrollButton.prototype.startScroll = function () {
	this._interval = window.setInterval(
		"ScrollButton.eventListeners.oninterval(\"" + this.id + "\")",
		ScrollButton.scrollIntervalPause );
};

ScrollButton.prototype.endScroll = function () {
	if ( this._interval != null ) {
		window.clearInterval( this._interval );
		delete this._interval;
	}
};

ScrollButton.prototype.makeEventListeners = function () {

	if ( this.eventListeners != null )
		return;

	this.eventListeners = {
		onmouseover:	new Function( "ScrollButton.eventListeners.onmouseover(\"" + this.id + "\")" ),
		onmouseout:		new Function( "ScrollButton.eventListeners.onmouseout(\"" + this.id + "\")" ),
		onunload:	new Function( "ScrollButton.eventListeners.onunload(\"" + this.id + "\")" )
	};
};

ScrollButton.prototype.attachEvents = function () {
	if ( this.eventListeners == null )
		return;

	this.htmlElement.attachEvent( "onmouseover", this.eventListeners.onmouseover );
	this.htmlElement.attachEvent( "onmouseout", this.eventListeners.onmouseout );
	window.attachEvent( "onunload", this.eventListeners.onunload );
};

ScrollButton.prototype.detachEvents = function () {
	if ( this.eventListeners == null )
		return;

	//this.htmlElement.detachEvent( "onmouseover", this.eventListeners.onmouseover );
	
	//this.htmlElement.detachEvent( "onmouseout", this.eventListeners.onmouseout );
	window.detachEvent( "onunload", this.eventListeners.onunload );
};

ScrollButton.prototype.destroy = function () {
	this.endScroll();
	this.detachEvents();

	this.htmlElement = null;
	this.scrollContainer = null;
	this.eventListeners = null;

	scrollButtonCache.remove( this );
};

ScrollButton.eventListeners = {
	onmouseover:	function ( id ) {
		scrollButtonCache[id].startScroll();
	},

	onmouseout:		function ( id ) {
		scrollButtonCache[id].endScroll();
	},

	oninterval:		function ( id ) {
		var oThis = scrollButtonCache[id];
		switch ( oThis.dir ) {
			case 8:
				oThis.scrollContainer.scrollTop -= ScrollButton.scrollAmount;
				break;

			case 2:
				oThis.scrollContainer.scrollTop += ScrollButton.scrollAmount;
				break;

			case 4:
				oThis.scrollContainer.scrollLeft -= ScrollButton.scrollAmount;
				break;

			case 6:
				oThis.scrollContainer.scrollLeft += ScrollButton.scrollAmount;
				break;
		}
	},

	onunload:	function ( id ) {
		scrollButtonCache[id].destroy();
	}
};/*----------------------------------------------------------------------------\
|                             DHTML Menu 4.28                                 |
|-----------------------------------------------------------------------------|
|                         Created by Erik Arvidsson                           |
|                  (http://webfx.eae.net/contact.html#erik)                   |
|                      For WebFX (http://webfx.eae.net/)                      |
|-----------------------------------------------------------------------------|
| A menu system for Internet Explorer 5.5+ Win32 that allows menus to extend  |
| outside the browser window limits.                                          |
|-----------------------------------------------------------------------------|
|                  Copyright (c) 1999 - 2003 Erik Arvidsson                   |
|-----------------------------------------------------------------------------|
| This software is provided "as is", without warranty of any kind, express or |
| implied, including  but not limited  to the warranties of  merchantability, |
| fitness for a particular purpose and noninfringement. In no event shall the |
| authors or  copyright  holders be  liable for any claim,  damages or  other |
| liability, whether  in an  action of  contract, tort  or otherwise, arising |
| from,  out of  or in  connection with  the software or  the  use  or  other |
| dealings in the software.                                                   |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| This  software is  available under the  three different licenses  mentioned |
| below.  To use this software you must chose, and qualify, for one of those. |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| The WebFX Non-Commercial License          http://webfx.eae.net/license.html |
| Permits  anyone the right to use the  software in a  non-commercial context |
| free of charge.                                                             |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| The WebFX Commercial license           http://webfx.eae.net/commercial.html |
| Permits the  license holder the right to use  the software in a  commercial |
| context. Such license must be specifically obtained, however it's valid for |
| any number of  implementations of the licensed software.                    |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| GPL - The GNU General Public License    http://www.gnu.org/licenses/gpl.txt |
| Permits anyone the right to use and modify the software without limitations |
| as long as proper  credits are given  and the original  and modified source |
| code are included. Requires  that the final product, software derivate from |
| the original  source or any  software  utilizing a GPL  component, such  as |
| this, is also licensed under the GPL license.                               |
|-----------------------------------------------------------------------------|
| 2002-05-28 | First version                                                  |
| 2002-06-07 | Updated default cssFile value to "skins/winclassic.css"        |
|            | instead of "winclassic.css"                                    |
| 2002-06-10 | (4.1) Lots of changes. Rewrote measuring and positioning       |
|            | routines to prevent screen flicker. As well as general code    |
|            | optimization.                                                  |
| 2002-07-03 | getInsetRight and getInsetBottom broke in the last update.     |
|            | Radio and Check box did not check disabled state correctly.    |
| 2002-07-25 | Created a work around for a weird bug that did not show first  |
|            | menu. Disabled browser keyboard shortcuts when menus are open. |
|            | Added workaround for buggy dual monitor drivers.               |
| 2002-09-05 | Fixed cases where the caching of the CSS failed and caused the |
|            | cached menu size to be incorrect.                              |
| 2002-09-05 | Insets were ignored for vertical menus.                        |
| 2002-09-06 | Some properties have been moved to the prototype to make	      |
|            | customizing easier.                                            |
| 2002-09-24 | Minor changes to prevent size errors.                          |
| 2002-10-22 | Added second argument to Menu add.                             |
|            | Added support for Menu cssText.                                |
| 2002-10-29 | (4.2) Lots of work to work around IE memory bugs.              |
| 2002-11-03 | Typo in MenuBar goToNextMenuItem                               |
| 2002-11-23 | The height and width were not correctly limited in show.       |
| 2002-12-04 | Changed to use onunload instead of onbeforeunload.             |
|            | Onbeforeunload was causing troubles with certain links.        |
| 2003-03-07 | Fixed bug in MenuButton toHtml and added MenuBar invalidate    |
|            | also created a clone extension (menu4.clone.js)                |
| 2003-04-01 | added document arguments to MenuBar create and write.          |
|            | Better mnemonic handling when HTML is used                     |
|            | onclose, onshow and onbeforeshow                               |
| 2003-09-12 | Updated mnemonic code and fixed an itemIndex bug when adding   |
|            | items.                                                         |
| 2003-09-23 | The scrollbutton.js still used onbeforeunload                  |
| 2003-10-15 | Add support for keyboardAccelKey2 (defaults to F10). Also      |
|            | fixed so that Esc on last menu correctly goes to the menu bar. |
| 2003-11-24 | Changed the MenuButton constructor to not fail if sub menu is  |
|            | left out. This allows you to set the sub menu later. A sub     |
|            | menu is still needed!                                          |
|-----------------------------------------------------------------------------|
| Dependencies: poslib.js       Used to find positions of elements            |
|               scrollbutton.js	Used for the buttnos that allows the menu     |
|                               to be scrollable                              |
|-----------------------------------------------------------------------------|
| Created 2002-05-28 | All changes are in the log above. | Updated 2003-11-24 |
\----------------------------------------------------------------------------*/


////////////////////////////////////////////////////////////////////////////////////
// menuCache
//

var menuCache = {
	_count:		0,
	_idPrefix:	"-menu-cache-",

	getId:	function () {
		return this._idPrefix + this._count++;
	},

	remove:	function ( o ) {
		delete this[ o.id ];
	}
};

////////////////////////////////////////////////////////////////////////////////////
// Menu
//

function Menu() {
	this.items = [];
	this.parentMenu = null;
	this.parentMenuItem = null;
	this.popup = null;
	this.shownSubMenu = null;
	this._aboutToShowSubMenu = false;

	this.selectedIndex = -1;
	this._drawn = false;
	this._scrollingMode = false;
	this._showTimer = null;
	this._closeTimer = null;

	this._onCloseInterval = null;
	this._closed = true;
	this._closedAt = 0;

	this._cachedSizes = {};
	this._measureInvalid = true;

	this.id = menuCache.getId();
	menuCache[ this.id ] = this;
}

Menu.prototype.cssFile = "skins/winclassic.css";
Menu.prototype.cssText = null;
Menu.prototype.mouseHoverDisabled = false;
Menu.prototype.showTimeout = 250;
Menu.prototype.closeTimeout = 250;

Menu.keyboardAccelKey = 27;				// the keyCode for the key tp activate
Menu.keyboardAccelKey2 = 121;			// the menubar
Menu.keyboardAccelProperty = "ctrlKey";	// when this property is true default
										// actions will be canceled on a menu
// Use -1 to disable keyboard invoke of the menubar
// Use "" to allow all normal keyboard commands inside the menus

Menu.prototype.add = function ( mi, beforeMi ) {
	if ( beforeMi != null ) {
		var items = this.items;
		var l = items.length;
		var i = 0;
		for ( ; i < l; i++ ) {
			if ( items[i] == beforeMi )
				break;
		}
		this.items = items.slice( 0, i ).concat( mi ).concat( items.slice( i, l ) );
		// update itemIndex
		for (var j = i; j < l + 1; j++)
			this.items[j].itemIndex = j;
	}
	else {
		this.items.push( mi );
		mi.itemIndex = this.items.length - 1;
	}

	mi.parentMenu = this;
	if ( mi.subMenu ) {
		mi.subMenu.parentMenu = this;
		mi.subMenu.parentMenuItem = mi;
	}
	return mi;
};

Menu.prototype.remove = function ( mi ) {
	var res = [];
	var items = this.items;
	var l = items.length;
	for (var i = 0; i < l; i++) {
		if ( items[i] != mi ) {
			res.push( items[i] );
			items[i].itemIndex = res.length - 1;
		}
	}
	this.items = res;
	mi.parentMenu = null;
	return mi;
};



Menu.prototype.toHtml = function () {

	var items = this.items;
	var l = items.length
	var itemsHtml = new Array( l );
	for (var i = 0; i < l; i++)
		itemsHtml[i] = items[i].toHtml();

	return  "<html><head>" +
			(this.cssText == null ?
				"<link type=\"text/css\" rel=\"StyleSheet\" href=\"" + this.cssFile + "\" />" :
				"<style type=\"text/css\">" + this.cssText + "</style>") +
			"</head><body class=\"menu-body\">" +
			"<div class=\"outer-border\"><div class=\"inner-border\">" +
			"<table id=\"scroll-up-item\" cellspacing=\"0\" style=\"display: none\">" +
			"<tr class=\"disabled\"><td>" +
			"<span class=\"disabled-container\"><span class=\"disabled-container\">" +
			"5" +
			"</span></span>" + "</td></tr></table>" +
			"<div id=\"scroll-container\">" +
			"<table cellspacing=\"0\">" +

			itemsHtml.join( "" ) +

			"</table>" +
			"</div>" +
			"<table id=\"scroll-down-item\" cellspacing=\"0\" style=\"display: none\">" +
			"<tr><td>" +
			"<span class=\"disabled-container\"><span class=\"disabled-container\">" +
			"6" +
			"</span></span>" +
			"</td></tr></table>" +
			"</div></div>" +
			"</body></html>";
};


Menu.prototype.createPopup = function () {
	var w;
	var pm = this.parentMenu;
	if ( pm == null )
		w = window;
	else
		w = pm.getDocument().parentWindow;

	this.popup = w.createPopup();
};

Menu.prototype.getMeasureDocument = function () {

	if ( this.isShown() && this._drawn )
		return this.getDocument();

	var mf = Menu._measureFrame;
	if ( mf == null ) {
		// should be top document
		mf = Menu._measureFrame = document.createElement("IFRAME");
		var mfs = mf.style;
		mfs.position = "absolute";
		mfs.visibility = "hidden";
		mfs.left = "-100px";
		mfs.top = "-100px";
		mfs.width = "10px";
		mfs.height = "10px";
		mf.frameBorder = 0;
		document.body.appendChild( mf );
	}

	var d = mf.contentWindow.document

	if ( Menu._measureMenu == this && !this._measureInvalid )
		return d;

	d.open( "text/html", "replace" );
	d.write( this.toHtml() );
	d.close();

	Menu._measureMenu = this;
	this._measureInvalid = false;

	return d;
};

Menu.prototype.getDocument = function () {
	if ( this.popup )
		return this.popup.document;
	else
		return null;
};

Menu.prototype.getPopup = function () {
	if ( this.popup == null )
		this.createPopup();
	return this.popup;
};

Menu.prototype.invalidate = function () {
	if ( this._drawn ) {
		// do some memory cleanup
		if ( this._scrollUpButton )
			this._scrollUpButton.destroy();
		if ( this._scrollDownButton )
			this._scrollDownButton.destroy();

		var items = this.items;
		var l = items.length;
		var mi;
		for ( var i = 0; i < l; i++ ) {
			mi = items[i];
			mi._htmlElement_menuItem = null;
			mi._htmlElement = null;
		}

		this.detachEvents();
	}
	this._drawn = false;
	this.resetSizeCache();
	this._measureInvalid = true;
};

Menu.prototype.redrawMenu = function () {
	this.invalidate();
	this.drawMenu();
};

Menu.prototype.drawMenu = function () {

	if ( this._drawn ) return;

	this.getPopup();

	var d = this.getDocument();
	d.open( "text/html", "replace" );
	d.write( this.toHtml() );
	d.close();
	this._drawn = true;

	// set up scroll buttons
	var up = d.getElementById( "scroll-up-item" );
	var down = d.getElementById( "scroll-down-item" );
	var scrollContainer = d.getElementById( "scroll-container" );
	new ScrollButton( up, scrollContainer, 8 );
//	new ScrollButton( down, scrollContainer, 2 );

	// bind menu items to the table rows
	var rows = scrollContainer.firstChild.tBodies[0].rows;
	var items = this.items;
	var l = rows.length;
	var mi;
	for ( var i = 0; i < l; i++ ) {
		mi = items[i];
		rows[i]._menuItem = mi;
		mi._htmlElement = rows[i];
	}

	// hook up mouse
	this.hookupMenu( d );
};

Menu.prototype.show = function ( left, top, w, h ) {

	var pm = this.parentMenu;
	if ( pm )
		pm.closeAllSubs( this );

	var wasShown = this.isShown();

	if ( typeof this.onbeforeshow == "function" && !wasShown )
		this.onbeforeshow();

	this.drawMenu();

	if ( left == null ) left = 0;
	if ( top == null ) top = 0;
	w = w || Math.min( window.screen.width, this.getPreferredWidth() );
	h = h || Math.min( window.screen.height, this.getPreferredHeight() );

	this.popup.show( left, top, w, h );

	// work around a bug that sometimes occured with large pages when
	// opening the first menu
	if ( this.getPreferredWidth() == 0 ) {
		this.invalidate();
		this.show( left, top, w, h );
		return;
	}

	this.fixScrollButtons();
	this.fixScrollEnabledState();

	// clear selected item
	if ( this.selectedIndex != -1 ) {
		if ( this.items[ this.selectedIndex ] )
			this.items[ this.selectedIndex ].setSelected( false );
	}

	if ( pm ) {
		pm.shownSubMenu = this;
		pm._aboutToShowSubMenu = false;
	}

	window.clearTimeout( this._showTimer );
	window.clearTimeout( this._closeTimer );

	this._closed = false;
	this._startClosePoll();

	if ( typeof this.onshow == "function" && !wasShown && this.isShown() )
		this.onshow();
};

Menu.prototype.isShown = function () {
	this._checkCloseState();
	return this.popup != null && this.popup.isOpen;
};

Menu.prototype.fixSize = function () {
	var w = Math.min( window.screen.width, this.getPreferredWidth() );
	var h = Math.min( window.screen.height, this.getPreferredHeight() );
	var l = Math.max( 0, this.getLeft() );
	var t = Math.max( 0, this.getTop() );

	this.popup.show( l, t, w, h );
};

Menu.prototype.getWidth = function () {
	var d = this.getDocument();
	if ( d != null )
		return d.body.offsetWidth;
	else
		return 0;
};

Menu.prototype.getHeight = function () {
	var d = this.getDocument();
	if ( d != null )
		return d.body.offsetHeight;
	else
		return 0;
};

Menu.prototype.getPreferredWidth = function () {
	this.updateSizeCache();
	return this._cachedSizes.preferredWidth;
};

Menu.prototype.getPreferredHeight = function () {
	this.updateSizeCache();
	return this._cachedSizes.preferredHeight;
};

Menu.prototype.getLeft = function () {
	var d = this.getDocument();
	if ( d != null )
		return d.parentWindow.screenLeft;
	else
		return 0;
};

Menu.prototype.getTop = function () {
	var d = this.getDocument();
	if ( d != null )
		return d.parentWindow.screenTop;
	else
		return 0;
};


// Depreciated. Use show instead
Menu.prototype.setLeft = function ( l ) {
	throw new Error("Depreciated. Use show instead");
	//var t = this.getTop();
	//this.setLocation( l, t );
};

// Depreciated. Use show instead
Menu.prototype.setTop = function ( t ) {
	throw new Error("Depreciated. Use show instead");
	//var l = this.getLeft();
	//this.setLocation( l, t );
};

// Depreciated. Use show instead
Menu.prototype.setLocation = function ( l, t ) {
	throw new Error("Depreciated. Use show instead");
	//var w = this.getWidth();
	//var h = this.getHeight();
	//this.popup.show( l, t, w, h );
};

// Depreciated. Use show instead
Menu.prototype.setRect = function ( l, t, w, h ) {
	throw new Error("Depreciated. Use show instead");
	//this.popup.show( l, t, w, h );
};

Menu.prototype.getInsetLeft = function () {
	this.updateSizeCache();
	return this._cachedSizes.insetLeft;
};

Menu.prototype.getInsetRight = function () {
	this.updateSizeCache();
	return this._cachedSizes.insetRight;
};

Menu.prototype.getInsetTop = function () {
	this.updateSizeCache();
	return this._cachedSizes.insetTop;
};

Menu.prototype.getInsetBottom = function () {
	this.updateSizeCache();
	return this._cachedSizes.insetBottom;
};


Menu.prototype.areSizesCached = function () {
	var cs = this._cachedSizes;
	return this._drawn &&
		"preferredWidth" in cs &&
		"preferredHeight" in cs &&
		"insetLeft" in cs &&
		"insetRight" in cs &&
		"insetTop" in cs &&
		"insetBottom" in cs;
};





// depreciated
Menu.prototype.cacheSizes = function ( bForce ) {
	return updateSizeCache( bForce );
};

Menu.prototype.resetSizeCache = function () {
	this._cachedSizes = {};
};

Menu.prototype.updateSizeCache = function ( bForce ) {
	if ( this.areSizesCached() && !bForce )
		return;

	var d = this.getMeasureDocument();
	var body = d.body;

	var cs = this._cachedSizes = {};	// reset
	var scrollContainer = d.getElementById( "scroll-container" );

	// preferred width
	cs.preferredWidth = d.body.scrollWidth;

	// preferred height
	scrollContainer.style.overflow = "visible";
	cs.preferredHeight = body.firstChild.offsetHeight; //body.scrollHeight;
	scrollContainer.style.overflow = "hidden";

	// inset left
	cs.insetLeft = posLib.getLeft( scrollContainer );

	// inset right
	cs.insetRight = body.scrollWidth - posLib.getLeft( scrollContainer ) -
					scrollContainer.offsetWidth;

	// inset top
	var up = d.getElementById( "scroll-up-item" );
	if ( up.currentStyle.display == "none" )
		cs.insetTop = posLib.getTop( scrollContainer );
	else
		cs.insetTop = posLib.getTop( up );

	// inset bottom
	var down = d.getElementById( "scroll-down-item" );
	if ( down.currentStyle.display == "none" ) {
		cs.insetBottom = body.scrollHeight - posLib.getTop( scrollContainer ) -
						scrollContainer.offsetHeight;
	}
	else {
		cs.insetBottom = body.scrollHeight - posLib.getTop( down ) -
						down.offsetHeight;
	}
};




Menu.prototype.fixScrollButtons = function () {
	var d = this.getDocument();
	var up = d.getElementById( "scroll-up-item" );
	var down = d.getElementById( "scroll-down-item" );
	var scrollContainer = d.getElementById( "scroll-container" );
	var scs = scrollContainer.style;

	if ( scrollContainer.scrollHeight > this.getHeight() ) {

		up.style.display = "";
		down.style.display = "";

		scs.height = "";
		scs.overflow = "visible";
		scs.height = Math.max( 0, this.getHeight() -
			( d.body.scrollHeight - scrollContainer.offsetHeight ) ) + "px";
		scs.overflow = "hidden";

		this._scrollingMode = true;
	}
	else {
		up.style.display = "none";
		down.style.display = "none";
		scs.overflow = "visible";
		scs.height = "";

		this._scrollingMode = false;
	}
};

Menu.prototype.fixScrollEnabledState = function () {
	var d = this.getDocument();
	var up = d.getElementById( "scroll-up-item" );
	var down = d.getElementById( "scroll-down-item" );
	var scrollContainer = d.getElementById( "scroll-container" );
	var tr;

	tr = up.rows[0];
	if ( scrollContainer.scrollTop == 0 ) {
		if ( tr.className == "hover" || tr.className == "disabled-hover" )
			tr.className = "disabled-hover";
		else
			tr.className = "disabled";
	}
	else {
		if ( tr.className == "disabled-hover" || tr.className == "hover" )
			tr.className = "hover";
		else
			tr.className = "";
	}

	tr = down.rows[0];
	if ( scrollContainer.scrollHeight - scrollContainer.clientHeight <=
												scrollContainer.scrollTop ) {

		if ( tr.className == "hover" || tr.className == "disabled-hover" )
			tr.className = "disabled-hover";
		else
			tr.className = "disabled";
	}
	else {
		if ( tr.className == "disabled-hover" || tr.className == "hover" )
			tr.className = "hover";
		else
			tr.className = "";
	}
};

Menu.prototype.closeAllMenus = function () {
	if ( this.parentMenu )
		this.parentMenu.closeAllMenus();
	else
		this.close();
};

Menu.prototype.close = function () {
	this.closeAllSubs();

	window.clearTimeout( this._showTimer );
	window.clearTimeout( this._closeTimer );

	if ( this.popup )
		this.popup.hide();

	var pm = this.parentMenu;
	if ( pm && pm.shownSubMenu == this )
		pm.shownSubMenu = null;

	this.setSelectedIndex( -1 );
	this._checkCloseState();
};

Menu.prototype.closeAllSubs = function ( oNotThisSub) {
	// go through items and check for sub menus
	var items = this.items;
	var l = items.length;
	for (var i = 0; i < l; i++) {
		if ( items[i].subMenu != null && items[i].subMenu != oNotThisSub )
			items[i].subMenu.close();
	}
};

Menu.prototype.getSelectedIndex = function () {
	return this.selectedIndex;
};

Menu.prototype.setSelectedIndex = function ( nIndex ) {
	if ( this.selectedIndex == nIndex ) return;

	if ( nIndex >= this.items.length )
		nIndex = -1;

	var mi;

	// deselect old
	if ( this.selectedIndex != -1 ) {
		mi = this.items[ this.selectedIndex ];
		mi.setSelected( false );
	}

	this.selectedIndex = nIndex;
	mi = this.items[ this.selectedIndex ];
	if ( mi != null )
		mi.setSelected( true );
};

Menu.prototype.goToNextMenuItem = function () {
	var i = 0;
	var items = this.items;
	var length = items.length;
	var index = this.getSelectedIndex();
	var tmp;

	do {
		if ( index == -1 || index >= length )
			index = 0;
		else
			index++;
		i++;
		tmp = items[index]
	} while ( !( tmp != null && tmp instanceof MenuItem &&
			!(tmp instanceof MenuSeparator) || i >= length ) )

	if ( tmp != null )
		this.setSelectedIndex( index );
};

Menu.prototype.goToPreviousMenuItem = function () {

	var i = 0;
	var items = this.items;
	var length = items.length;
	var index = this.getSelectedIndex();
	var tmp;

	do {
		if ( index == -1 || index >= length )
			index = length - 1;
		else
			index--;
		i++;
		tmp = items[index]
	} while ( !( tmp != null && tmp instanceof MenuItem &&
			!(tmp instanceof MenuSeparator) || i >= length ) )

	if ( tmp != null )
		this.setSelectedIndex( index );
};

Menu.prototype.goToNextMenu = function () {
	var index = this.getSelectedIndex();
	var mi = this.items[ index ];

	if ( mi && mi.subMenu && !mi.disabled ) {
		mi.subMenu.setSelectedIndex( 0 );
		mi.showSubMenu( false );
	}
	else {
		// go up to root and select next
		var mb = this.getMenuBar();
		if ( mb != null )
			mb.goToNextMenuItem();
	}
};

Menu.prototype.goToPreviousMenu = function () {
	if ( this.parentMenuItem && this.parentMenuItem instanceof MenuButton ) {
		this.parentMenu.goToPreviousMenuItem();
	}
	else if ( this.parentMenuItem ) {
		this.close();
	}
};

Menu.prototype.getMenuBar = function () {
	if ( this.parentMenu == null )
		return null;
	return this.parentMenu.getMenuBar();
};

Menu.prototype.makeEventListeners = function () {
	if ( this.eventListeners != null )
		return;

	this.eventListeners = {
		onscroll:			new Function( "eventListeners.menu.onscroll(\"" + this.id + "\")" ),
		onmouseover:		new Function( "eventListeners.menu.onmouseover(\"" + this.id + "\")" ),
		onmouseout:			new Function( "eventListeners.menu.onmouseout(\"" + this.id + "\")" ),
		onmouseup:			new Function( "eventListeners.menu.onmouseup(\"" + this.id + "\")" ),
		onmousewheel:		new Function( "eventListeners.menu.onmousewheel(\"" + this.id + "\")" ),
		onreadystatechange:	new Function( "eventListeners.menu.onreadystatechange(\"" + this.id + "\")" ),
		onkeydown:			new Function( "eventListeners.menu.onkeydown(\"" + this.id + "\")" ),
		oncontextmenu:		new Function( "eventListeners.menu.oncontextmenu(\"" + this.id + "\")" ),
		onunload:			new Function( "eventListeners.menu.onunload(\"" + this.id + "\")" )
	};
};

Menu.prototype.detachEvents = function () {
	if ( this.eventListeners == null )
		return;

	var d = this.getDocument();
	var w = d.parentWindow;
	var scrollContainer = d.getElementById("scroll-container");

	scrollContainer.detachEvent( "onscroll", this.eventListeners.onscroll );
	d.detachEvent( "onmouseover", this.eventListeners.onmouseover );
	d.detachEvent( "onmouseout", this.eventListeners.onmouseout );
	d.detachEvent( "onmouseup", this.eventListeners.onmouseup );
	d.detachEvent( "onmousewheel", this.eventListeners.onmousewheel );
	if (this.cssText == null) {
		var linkEl = d.getElementsByTagName("LINK")[0];
		linkEl.detachEvent( "onreadystatechange", this.eventListeners.onreadystatechange );
	}
	d.detachEvent( "onkeydown", this.eventListeners.onkeydown );
	d.detachEvent( "oncontextmenu", this.eventListeners.oncontextmenu );
	// prevent IE to keep menu open when navigating away
	window.detachEvent( "onunload", this.eventListeners.onunload );
}

Menu.prototype.hookupMenu = function ( d ) {

	this.detachEvents();
	this.makeEventListeners();

	var oThis = this;
	var d = this.getDocument();
	var w = d.parentWindow;
	var scrollContainer = d.getElementById("scroll-container");

	// listen to the onscroll
	scrollContainer.attachEvent( "onscroll", this.eventListeners.onscroll );
	d.attachEvent( "onmouseover", this.eventListeners.onmouseover );
	d.attachEvent( "onmouseout", this.eventListeners.onmouseout );
	d.attachEvent( "onmouseup", this.eventListeners.onmouseup );
	d.attachEvent( "onmousewheel", this.eventListeners.onmousewheel );

	// if css file is not loaded we need to wait for it to load.
	// Once loaded fix the size

	if (this.cssText == null) {
		var linkEl = d.getElementsByTagName("LINK")[0];
		if ( linkEl.readyState != "complete") {
			linkEl.attachEvent( "onreadystatechange", this.eventListeners.onreadystatechange );
		}
	}

	d.attachEvent( "onkeydown", this.eventListeners.onkeydown );
	d.attachEvent( "oncontextmenu", this.eventListeners.oncontextmenu );
	// prevent IE to keep menu open when navigating away
	window.attachEvent( "onunload", this.eventListeners.onunload );

	var all = d.all;
	var l = all.length;
	for ( var i = 0; i < l; i++ )
		all[i].unselectable = "on";
};

Menu.prototype.handleKeyEvent = function ( oEvent ) {

	if ( this.shownSubMenu )
		// sub menu handles key event
		return;

	var nKeyCode = oEvent.keyCode;

	switch ( nKeyCode ) {
		case 40:	// down
			this.goToNextMenuItem();
			break;

		case 38:	// up
			this.goToPreviousMenuItem();
			break;

		case 39:	// right
			this.goToNextMenu();
			break;

		case 37:	// left
			this.goToPreviousMenu();
			break;

		case 13:	// enter
			var mi = this.items[ this.getSelectedIndex() ];
			if ( mi )
				mi.dispatchAction();
			break;

		case 27:	// esc
			this.close();

			// should close menu and go to parent menu item
			break;

		case Menu.keyboardAccelKey:
		case Menu.keyboardAccelKey2:
			this.closeAllMenus();
			break;

		default:
			// find any mnemonic that matches
			var c = String.fromCharCode( nKeyCode ).toLowerCase();
			var items = this.items;
			var l = items.length;
			for ( var i = 0; i < l; i++ ) {
				if ( items[i].mnemonic == c ) {
					items[i].dispatchAction();
					break;
				}
			}
	}

	// cancel default action
	oEvent.returnValue = false;
	oEvent.keyCode = 0;
};

// poll close state and when closed call _onclose
Menu.prototype._startClosePoll = function () {
	var oThis = this;
	window.clearInterval( this._onCloseInterval );
	this._onCloseInterval = window.setInterval(
		"eventListeners.menu.oncloseinterval(\"" + this.id + "\")", 100 );
};

Menu.prototype._checkCloseState = function () {
	var closed = this.popup == null || !this.popup.isOpen;
	if ( closed && this._closed != closed ) {
		this._closed = closed;
		this._closedAt = new Date().valueOf();
		window.clearInterval( this._onCloseInterval );
		if ( typeof this._onclose == "function" ) {
			var e = this.getDocument().parentWindow.event;
			if ( e != null && e.keyCode == 27 )
				this._closeReason = "escape";
			else
				this._closeReason = "unknown";
			this._onclose();
		}
		if ( typeof this.onclose == "function" )
			this.onclose();
	}
};

Menu.prototype._isCssFileLoaded = function () {
	if (this.cssText != null)
		return true;

	var d = this.getMeasureDocument();
	var l = d.getElementsByTagName("LINK")[0];
	return l.readyState == "complete";
};

Menu.prototype.destroy = function () {
	var l = this.items.length;
	for ( var i = l -1; i >= 0; i-- )
		this.items[i].destroy();

	this.detachEvents();
	this.items = [];
	this.parentMenu = null;
	this.parentMenuItem = null;
	this.shownSubMenu = null;
	this._cachedSizes = null;
	this.eventListeners = null;

	if ( this.popup != null ) {
		var d = this.popup.document;
		d.open("text/plain", "replace");
		d.write("");
		d.close();
		this.popup = null;
	}

	if ( Menu._measureMenu == this ) {
		Menu._measureMenu = null;
		var d = Menu._measureFrame.contentWindow.document;
		d.open("text/plain", "replace");
		d.write("");
		d.close();
		Menu._measureFrame.parentNode.removeChild(Menu._measureFrame);
		Menu._measureFrame = null;
	}

	menuCache.remove( this );
};

////////////////////////////////////////////////////////////////////////////////////
// MenuItem
//

function MenuItem( sLabelText, fAction, sIconSrc, oSubMenu ) {
	// public
	this.icon = sIconSrc || "";
	this.text = sLabelText;
	this.action = fAction;

	this.subMenu = oSubMenu;
	this.parentMenu = null;

	// private
	this._selected = false;
	this._useInsets = true;	// should insets be taken into account when showing sub menu

	this.id = menuCache.getId();
	menuCache[ this.id ] = this;
}

MenuItem.prototype.subMenuDirection = "horizontal";
MenuItem.prototype.disabled = false;
MenuItem.prototype.mnemonic = null;
MenuItem.prototype.shortcut = null;
MenuItem.prototype.toolTip = "";
MenuItem.prototype.target = null;
MenuItem.prototype.visible = true;

MenuItem.prototype.toHtml = function () {
	var cssClass = this.getCssClass();
	var toolTip = this.getToolTip();

	return	"<tr" +
			(cssClass != "" ? " class=\"" + cssClass + "\"" : "") +
			(toolTip != "" ? " title=\"" + toolTip + "\"" : "") +
			(!this.visible ? " style=\"display: none\"" : "") +
			">" +
			this.getIconCellHtml() +
			this.getTextCellHtml() +
			this.getShortcutCellHtml() +
			this.getSubMenuArrowCellHtml() +
			"</tr>";
};

MenuItem.prototype.getTextHtml = function () {
	var s = this.text;
	if ( !s || !this.mnemonic )
		return s;

	// replace character with <u> character </u>
	// /^(((<([^>]|MNEMONIC)+>)|[^MNEMONIC])*)(MNEMONIC)/i
	var re = new RegExp( "^(((<([^>]|" + this.mnemonic + ")+>)|[^<" +
						this.mnemonic + "])*)(" + this.mnemonic + ")", "i" );
	re.exec( s );
	if ( RegExp.index != -1 && RegExp.$5 != "" )
		return RegExp.$1 + "<u>" + RegExp.$5 + "</u>" + RegExp.rightContext;
	else
		return s;
};


MenuItem.prototype.getIconHtml = function () {
	return this.icon != "" ? "<img src=\"" + this.icon + "\">" : "<span>&nbsp;</span>";
};

MenuItem.prototype.getTextCellHtml = function () {
	return "<td class=\"label-cell\" nowrap=\"nowrap\">" +
			this.makeDisabledContainer(
				this.getTextHtml()
			) +
			"</td>";
};

MenuItem.prototype.getIconCellHtml = function () {
	return "<td class=\"" +
			(this.icon != "" ? "icon-cell" : "empty-icon-cell") +
			"\">" +
			this.makeDisabledContainer(
				this.getIconHtml()
			) +
			"</td>";
};

MenuItem.prototype.getCssClass = function () {
	if ( this.disabled && this._selected )
		return "disabled-hover";
	else if ( this.disabled )
		return "disabled";
	else if ( this._selected )
		return "hover";

	return "";
};

MenuItem.prototype.getToolTip = function () {
	return this.toolTip;
};

MenuItem.prototype.getShortcutHtml = function () {
	if ( this.shortcut == null )
		return "&nbsp;";

	return this.shortcut;
};

MenuItem.prototype.getShortcutCellHtml = function () {
	return "<td class=\"shortcut-cell\" nowrap=\"nowrap\">" +
			this.makeDisabledContainer(
				this.getShortcutHtml()
			) +
			"</td>";
};

MenuItem.prototype.getSubMenuArrowHtml = function () {
	if ( this.subMenu == null )
		return "&nbsp;";

	return 4;	// right arrow using the marlett (or webdings) font
};

MenuItem.prototype.getSubMenuArrowCellHtml = function () {
	return "<td class=\"arrow-cell\">" +
			this.makeDisabledContainer(
				this.getSubMenuArrowHtml()
			) +
			"</td>";
};

MenuItem.prototype.makeDisabledContainer = function ( s ) {
	if ( this.disabled )
		return	"<span class=\"disabled-container\"><span class=\"disabled-container\">" +
				s + "</span></span>";
	return s;
};

MenuItem.prototype.dispatchAction = function () {
	if ( this.disabled )
		return;

	this.setSelected( true );

	if ( this.subMenu ) {
		if ( !this.subMenu.isShown() )
			this.showSubMenu( false );
		return;
	}

	if ( typeof this.action == "function" ) {
		this.setSelected( false );
		this.parentMenu.closeAllMenus();
		this.action();

	}
	else if ( typeof this.action == "string" ) {	// href
		this.setSelected( false );
		this.parentMenu.closeAllMenus();
		if ( this.target != null )
			window.open( this.action, this.target );
		else
			document.location.href = this.action;
	}
};

MenuItem.prototype.setSelected = function ( bSelected ) {
	if ( this._selected == bSelected )	return;

	this._selected = Boolean( bSelected );

	var tr = this._htmlElement;
	if ( tr )
		tr.className = this.getCssClass();

	if ( !this._selected )
		this.closeSubMenu( true );

	var pm = this.parentMenu;
	if ( bSelected ) {

		pm.setSelectedIndex( this.itemIndex );
		this.scrollIntoView();

		// select item in parent menu as well
		if ( pm.parentMenuItem )
			pm.parentMenuItem.setSelected( true );
	}
	else
		pm.setSelectedIndex( -1 );

	if ( this._selected ) {
		// clear timers for parent menu
		window.clearTimeout( pm._closeTimer );
	}
};


MenuItem.prototype.getSelected = function () {
	return this.itemIndex == this.parentMenu.selectedIndex;
};

MenuItem.prototype.showSubMenu = function ( bDelayed ) {
	var sm = this.subMenu;
	var pm = this.parentMenu;
	if ( sm && !this.disabled ) {

		pm._aboutToShowSubMenu = true;

		window.clearTimeout( sm._showTimer );
		window.clearTimeout( sm._closeTimer );

		var showTimeout = bDelayed ? sm.showTimeout : 0;

		var oThis = this;
		sm._showTimer = window.setTimeout(
			"eventListeners.menuItem.onshowtimer(\"" + this.id + "\")",
			showTimeout );
	}
};

MenuItem.prototype.closeSubMenu = function ( bDelay ) {
	var sm = this.subMenu;
	if ( sm ) {
		window.clearTimeout( sm._showTimer );
		window.clearTimeout( sm._closeTimer );

		if ( sm.popup ) {
			if ( !bDelay )
				sm.close();
			else {
				var oThis = this;
				sm._closeTimer = window.setTimeout(
					"eventListeners.menuItem.onclosetimer(\"" + this.id + "\")",
					sm.closeTimeout );
			}
		}
	}
};

MenuItem.prototype.scrollIntoView = function () {
	if ( this.parentMenu._scrollingMode ) {
		var d = this.parentMenu.getDocument();
		var sc = d.getElementById( "scroll-container" );
		var scrollTop = sc.scrollTop;
		var clientHeight = sc.clientHeight;
		var offsetTop = this._htmlElement.offsetTop;
		var offsetHeight = this._htmlElement.offsetHeight;

		if ( offsetTop < scrollTop )
			sc.scrollTop = offsetTop;
		else if ( offsetTop + offsetHeight > scrollTop + clientHeight )
			sc.scrollTop = offsetTop + offsetHeight - clientHeight;
	}
};



MenuItem.prototype.positionSubMenu = function () {
	var dir = this.subMenuDirection;
	var el = this._htmlElement;
	var useInsets = this._useInsets;
	var sm = this.subMenu;

	var oThis = this;

	if ( !sm._isCssFileLoaded() ) {
		window.setTimeout(
			"eventListeners.menuItem.onpositionsubmenutimer(\"" + this.id + "\")",
			1 );
		return;
	}

	// find parent item rectangle
	var rect = {
		left:	posLib.getScreenLeft( el ),
		top:	posLib.getScreenTop( el ),
		width:	el.offsetWidth,
		height:	el.offsetHeight
	};

	var menuRect = {
		left:		sm.getLeft(),
		top:		sm.getTop(),
		width:		sm.getPreferredWidth(),
		height:		sm.getPreferredHeight(),
		insetLeft:		useInsets ? sm.getInsetLeft() : 0,
		insetRight:		useInsets ? sm.getInsetRight() : 0,
		insetTop:		useInsets ? sm.getInsetTop() : 0,
		insetBottom:	useInsets ? sm.getInsetBottom() : 0
	};

	// work around for buggy graphics drivers that screw up the screen.left
	var screenWidth = screen.width;
	var screenHeight = screen.height;
	while ( rect.left > screenWidth )
		screenWidth += screen.width;
	while ( rect.top > screenHeight )
		screenHeight += screen.height;

	var left, top, width = menuRect.width, height = menuRect.height;

	if ( dir == "vertical" ) {
		if ( rect.left + menuRect.width - menuRect.insetLeft <= screenWidth )
			left = rect.left - menuRect.insetLeft;
		else if ( screenWidth >= menuRect.width )
			left = screenWidth - menuRect.width;
		else
			left = 0;

		if ( rect.top + rect.height + menuRect.height - menuRect.insetTop <= screenHeight )
			top = rect.top + rect.height - menuRect.insetTop;
		else if ( rect.top - menuRect.height + menuRect.insetBottom >= 0 )
			top = rect.top - menuRect.height + menuRect.insetBottom;
		else {	// use largest and resize
			var sizeAbove = rect.top + menuRect.insetBottom;
			var sizeBelow = screenHeight - rect.top - rect.height + menuRect.insetTop;
			if ( sizeBelow >= sizeAbove ) {
				top = rect.top + rect.height - menuRect.insetTop;
				height = sizeBelow;
			}
			else {
				top = 0;
				height = sizeAbove;
			}
		}
	}
	else {
		if ( rect.top + menuRect.height - menuRect.insetTop <= screenHeight )
			top = rect.top - menuRect.insetTop;
		else if ( rect.top + rect.height - menuRect.height + menuRect.insetBottom >= 0)
			top = rect.top + rect.height - menuRect.height + menuRect.insetBottom;
		else if ( screenHeight >= menuRect.height )
			top = screenHeight - menuRect.height;
		else {
			top = 0;
			height = screenHeight
		}

		if ( rect.left + rect.width + menuRect.width - menuRect.insetLeft <= screenWidth )
			left = rect.left + rect.width - menuRect.insetLeft;
		else if ( rect.left - menuRect.width + menuRect.insetRight >= 0 )
			left = rect.left - menuRect.width + menuRect.insetRight;
		else if ( screenWidth >= menuRect.width )
			left = screenWidth - menuRect.width;
		else
			left = 0;
	}

	var scrollBefore = sm._scrollingMode;
	sm.show( left, top, width, height );
	if ( sm._scrollingMode != scrollBefore )
		this.positionSubMenu();
};


MenuItem.prototype.destroy = function () {
	if ( this.subMenu != null )
		this.subMenu.destroy();

	this.subMenu = null;
	this.parentMenu = null;
	var el = this._htmlElement
	if ( el != null )
		el._menuItem = null;
	this._htmlElement = null;

	menuCache.remove( this );
};


///////////////////////////////////////////////////////////////////////////////
// CheckBoxMenuItem extends MenuItem
//
function CheckBoxMenuItem( sLabelText, bChecked, fAction, oSubMenu ) {

	this.MenuItem = MenuItem;
	this.MenuItem( sLabelText, fAction, null, oSubMenu);

	// public
	this.checked = bChecked;
}

CheckBoxMenuItem.prototype = new MenuItem;

CheckBoxMenuItem.prototype.getIconHtml = function () {
	return "<span class=\"check-box\">" +
		(this.checked ? "a" : "&nbsp;") +
		"</span>";
};

CheckBoxMenuItem.prototype.getIconCellHtml = function () {
	return "<td class=\"icon-cell\">" +
			this.makeDisabledContainer(
				this.getIconHtml()
			) +
			"</td>";
};

CheckBoxMenuItem.prototype.getCssClass = function () {
	var s = (this.checked ? " checked" : "");
	if ( this.disabled && this._selected )
		return "disabled-hover" + s;
	else if ( this.disabled )
		return "disabled" + s;
	else if ( this._selected )
		return "hover" + s;

	return s;
};

CheckBoxMenuItem.prototype._menuItem_dispatchAction =
	MenuItem.prototype.dispatchAction;
CheckBoxMenuItem.prototype.dispatchAction = function () {
	if (!this.disabled) {
		this.checked = !this.checked;
		this._menuItem_dispatchAction();
		this.parentMenu.invalidate();
		this.parentMenu.closeAllMenus();
	}
};


///////////////////////////////////////////////////////////////////////////////
// RadioButtonMenuItem extends MenuItem
//
function RadioButtonMenuItem( sLabelText, bChecked, sRadioGroupName, fAction, oSubMenu ) {
	this.MenuItem = MenuItem;
	this.MenuItem( sLabelText, fAction, null, oSubMenu );

	// public
	this.checked = bChecked;
	this.radioGroupName = sRadioGroupName;
}

RadioButtonMenuItem.prototype = new MenuItem;

RadioButtonMenuItem.prototype.getIconHtml = function () {
	return "<span class=\"radio-button\">" +
		(this.checked ? "n" : "&nbsp;") +
		"</span>";
};

RadioButtonMenuItem.prototype.getIconCellHtml = function () {
	return "<td class=\"icon-cell\">" +
			this.makeDisabledContainer(
				this.getIconHtml()
			) +
			"</td>";
};

RadioButtonMenuItem.prototype.getCssClass = function () {
	var s = (this.checked ? " checked" : "");
	if ( this.disabled && this._selected )
		return "disabled-hover" + s;
	else if ( this.disabled )
		return "disabled" + s;
	else if ( this._selected )
		return "hover" + s;

	return s;
};

RadioButtonMenuItem.prototype._menuItem_dispatchAction =
	MenuItem.prototype.dispatchAction;
RadioButtonMenuItem.prototype.dispatchAction = function () {
	if (!this.disabled) {
		if ( !this.checked ) {
			// loop through items in parent menu
			var items = this.parentMenu.items;
			var l = items.length;
			for ( var i = 0; i < l; i++ ) {
				if ( items[i] instanceof RadioButtonMenuItem ) {
					if ( items[i].radioGroupName == this.radioGroupName ) {
						items[i].checked = items[i] == this;
					}
				}
			}
			this.parentMenu.invalidate();
		}

		this._menuItem_dispatchAction();
		this.parentMenu.closeAllMenus();
	}
};


///////////////////////////////////////////////////////////////////////////////
// MenuSeparator extends MenuItem
//
function MenuSeparator() {
	this.MenuItem = MenuItem;
	this.MenuItem();
}

MenuSeparator.prototype = new MenuItem;

MenuSeparator.prototype.toHtml = function () {
	return "<tr class=\"" + this.getCssClass() + "\"" +
			(!this.visible ? " style=\"display: none\"" : "") +
			"><td colspan=\"4\">" +
			"<div class=\"separator-line\"></div>" +
			"</td></tr>";
};

MenuSeparator.prototype.getCssClass = function () {
	return "separator";
};


////////////////////////////////////////////////////////////////////////////////////
// MenuBar extends Menu
//
function MenuBar() {
	this.items = [];
	this.parentMenu = null;
	this.parentMenuItem = null;
	this.shownSubMenu = null;
	this._aboutToShowSubMenu = false;

	this.active = false;
	this.id = menuCache.getId();
	menuCache[ this.id ] = this;
}
MenuBar.prototype = new Menu;

MenuBar.prototype._document = null;

MenuBar.leftMouseButton = 1;

MenuBar.prototype.toHtml = function () {
	var items = this.items;
	var l = items.length;
	var itemsHtml = new Array( l );
	for (var i = 0; i < l; i++ )
		itemsHtml[i] = items[i].toHtml();

	return "<div class=\"menu-bar\" id=\"" + this.id + "\">" +
		itemsHtml.join( "" ) +
		"</div>";
};

MenuBar.prototype.invalidate = function () {
	if (this._htmlElement) {
		this.detachEvents();
		var oldEl = this._htmlElement;
		var newEl = this.create(this._document);
		oldEl.parentNode.replaceChild(newEl, oldEl);
	}
};

MenuBar.prototype.createPopup = function () {};
MenuBar.prototype.getPopup= function () {};
MenuBar.prototype.drawMenu = function () {};

MenuBar.prototype.getDocument = function () {
	return this._document;
};

MenuBar.prototype.show = function ( left, top, w, h ) {};
MenuBar.prototype.isShown = function () { return true; };
MenuBar.prototype.fixSize = function () {}

MenuBar.prototype.getWidth = function () {
	return this._htmlElement.offsetWidth;
};

MenuBar.prototype.getHeight = function () {
	return this._htmlElement.offsetHeight;
};

MenuBar.prototype.getPreferredWidth = function () {
	var el = this._htmlElement;
	el.runtimStyle.whiteSpace = "nowrap";
	var sw = el.scrollWidth;
	el.runtimStyle.whiteSpace = "";
	return sw + parseInt( el.currentStyle.borderLeftWidth ) +
				parseInt( el.currentStyle.borderRightWidth );
};

MenuBar.prototype.getPreferredHeight = function () {
	var el = this._htmlElement;
	el.runtimStyle.whiteSpace = "nowrap";
	var sw = el.scrollHeight;
	el.runtimStyle.whiteSpace = "";
	return sw + parseInt( el.currentStyle.borderTopWidth ) +
				parseInt( el.currentStyle.borderBottomWidth );
};

MenuBar.prototype.getLeft = function () {
	return posLib.getScreenLeft( this._htmlElement );
};
MenuBar.prototype.getTop = function () {
	return posLib.getScreenLeft( this._htmlElement );
};
MenuBar.prototype.setLeft = function ( l ) {};
MenuBar.prototype.setTop = function ( t ) {};
MenuBar.prototype.setLocation = function ( l, t ) {};
MenuBar.prototype.setRect = function ( l, t, w, h ) {};
MenuBar.prototype.getInsetLeft = function () {
	return parseInt( this._htmlElement.currentStyle.borderLeftWidth );
};
MenuBar.prototype.getInsetRight = function () {
	return parseInt( this._htmlElement.currentStyle.borderRightWidth );
};
MenuBar.prototype.getInsetTop = function () {
	return parseInt( this._htmlElement.currentStyle.borderTopWidth );
};
MenuBar.prototype.getInsetBottom = function () {
	return parseInt( this._htmlElement.currentStyle.borderBottomWidth );
};
MenuBar.prototype.fixScrollButtons = function () {};
MenuBar.prototype.fixScrollEnabledState = function () {};

MenuBar.prototype.makeEventListeners = function () {
	if ( this.eventListeners != null )
		return;

	this.eventListeners = {
		onmouseover:		new Function( "eventListeners.menuBar.onmouseover(\"" + this.id + "\")" ),
		onmouseout:			new Function( "eventListeners.menuBar.onmouseout(\"" + this.id + "\")" ),
		onmousedown:		new Function( "eventListeners.menuBar.onmousedown(\"" + this.id + "\")" ),
		onkeydown:			new Function( "eventListeners.menuBar.onkeydown(\"" + this.id + "\")" ),
		onunload:			new Function( "eventListeners.menuBar.onunload(\"" + this.id + "\")" )
	};
};

MenuBar.prototype.detachEvents = function () {
	if ( this.eventListeners == null )
		return;

	this._htmlElement.detachEvent( "onmouseover",	this.eventListeners.onmouseover );
	this._htmlElement.detachEvent( "onmouseout", this.eventListeners.onmouseout );
	this._htmlElement.detachEvent( "onmousedown", this.eventListeners.onmousedown );
	this._document.detachEvent( "onkeydown", this.eventListeners.onkeydown );
	window.detachEvent( "onunload", this.eventListeners.onunload );
}

MenuBar.prototype.hookupMenu = function ( element ) {
	if ( !this._document )
		this._document = element.document;

	this.detachEvents();
	this.makeEventListeners();

	// create shortcut to html element
	this._htmlElement = element;
	element.unselectable = "on";

	// and same for menu buttons
	var cs = element.childNodes;
	var items = this.items;
	var l = cs.length;
	for ( var i = 0; i < l; i++ ) {
		items[i]._htmlElement = cs[i];
		cs[i]._menuItem = items[i];
	}

	// hook up events
	element.attachEvent( "onmouseover",	this.eventListeners.onmouseover );
	element.attachEvent( "onmouseout", this.eventListeners.onmouseout );
	element.attachEvent( "onmousedown", this.eventListeners.onmousedown );
	this._document.attachEvent( "onkeydown", this.eventListeners.onkeydown );
	window.attachEvent( "onunload", this.eventListeners.onunload );
};

function getMenuItemElement( el ) {
	while ( el != null && el._menuItem == null)
		el = el.parentNode;
	return el;
}

function getTrElement( el ) {
	while ( el != null && el.tagName != "TR" )
		el = el.parentNode;
	return el;
}

MenuBar.prototype.write = function (oDocument) {
	this._document = oDocument || document;
	this._document.write( this.toHtml() );
	var el = this._document.getElementById( this.id );
	this.hookupMenu( el );
};

MenuBar.prototype.create = function (oDocument) {
	this._document = oDocument || document;
	var dummyDiv = this._document.createElement( "DIV" );
	dummyDiv.innerHTML = this.toHtml();
	var el = dummyDiv.removeChild( dummyDiv.firstChild );
	this.hookupMenu( el );
	return el;
};

MenuBar.prototype.handleKeyEvent = function ( e ) {
	if ( this.getActiveState() == "open" )
		return;

	var nKeyCode = e.keyCode;

	if ( this.active && e[ Menu.keyboardAccelProperty ] ) {
		e.returnValue = false;
		e.keyCode = 0;
	}

	if ( nKeyCode == Menu.keyboardAccelKey || nKeyCode == Menu.keyboardAccelKey2 ) {
		if ( !e.repeat ) {
			this.toggleActive();
		}
		e.returnValue = false;
		e.keyCode = 0;
		return;
	}

	if ( !this.active ) {
		// do not set return value to true
		return;
	}

	switch ( nKeyCode ) {
		case 39:	// right
			this.goToNextMenuItem();
			e.returnValue = false;
			break;

		case 37:	// left
			this.goToPreviousMenuItem();
			e.returnValue = false;
			break;

		case 40:	// down
		case 38:	// up
		case 13:	// enter
			var mi = this.items[ this.getSelectedIndex() ];
			if ( mi ) {
				mi.dispatchAction();
				if ( mi.subMenu )
					mi.subMenu.setSelectedIndex( 0 );
			}
			e.returnValue = false;
			break;

		case 27:	// esc
			// we need to make sure that the menu bar looses its current
			// keyboard activation state

			this.setActive( false );
			e.returnValue = false;
			break;

		default:
			// find any mnemonic that matches
			var c = String.fromCharCode( nKeyCode ).toLowerCase();
			var items = this.items;
			var l = items.length;
			for ( var i = 0; i < l; i++ ) {
				if ( items[i].mnemonic == c ) {
					items[i].dispatchAction();
					e.returnValue = false;
					break;
				}
			}
	}
};

MenuBar.prototype.getMenuBar = function () {
	return this;
};

MenuBar.prototype._menu_goToNextMenuItem = Menu.prototype.goToNextMenuItem;
MenuBar.prototype.goToNextMenuItem = function () {
	var expand = this.getActiveState() == "open";
	this._menu_goToNextMenuItem();
	var mi = this.items[ this.getSelectedIndex() ];
	if ( expand && mi != null ) {
		window.setTimeout(
			"eventListeners.menuBar.ongotonextmenuitem(\"" + this.id + "\")",
			1 );
	}
};

MenuBar.prototype._menu_goToPreviousMenuItem = Menu.prototype.goToPreviousMenuItem;
MenuBar.prototype.goToPreviousMenuItem = function () {
	var expand = this.getActiveState() == "open";
	this._menu_goToPreviousMenuItem();
	var mi = this.items[ this.getSelectedIndex() ];
	if ( expand && mi != null ) {
		window.setTimeout(
			"eventListeners.menuBar.ongotopreviousmenuitem(\"" + this.id + "\")",
			1 );
	}
};

MenuBar.prototype._menu_setSelectedIndex = Menu.prototype.setSelectedIndex;
MenuBar.prototype.setSelectedIndex = function ( nIndex ) {
	this._menu_setSelectedIndex( nIndex );
	this.active = nIndex != -1;
};

MenuBar.prototype.setActive = function ( bActive ) {
	if ( this.active != bActive ) {
		this.active = Boolean( bActive );
		if ( this.active ) {
			this.setSelectedIndex( 0 );
			this.backupFocused();
			window.focus();
		}
		else {
			this.setSelectedIndex( -1 );
			this.restoreFocused();
		}
	}
};

MenuBar.prototype.toggleActive = function () {
	if ( this.getActiveState() == "active" )
		this.setActive( false );
	else if ( this.getActiveState() == "inactive" )
		this.setActive( true );
};

// returns active, inactive or open
MenuBar.prototype.getActiveState = function () {
	if ( this.shownSubMenu != null || this._aboutToShowSubMenu)
		return "open";
	else if ( this.active )
		return "active";
	else
		return "inactive";
};

MenuBar.prototype.backupFocused = function () {
	this._activeElement = this._document.activeElement;
};

MenuBar.prototype.restoreFocused = function () {
	try {
		this._activeElement.focus();
	}
	catch (ex) {}
	delete this._activeElement;

};

MenuBar.prototype.destroy = function () {
	var l = this.items.length;
	for ( var i = l -1; i >= 0; i-- )
		this.items[i].destroy();

	this.detachEvents();
	this._activeElement = null;
	this._htmlElement = null;
	this._document = null;
	this.items = [];
	this.shownSubMenu = null;
	this.eventListeners = null;

	menuCache.remove( this );
};

////////////////////////////////////////////////////////////////////////////////////
// MenuButton extends MenuItem
//
function MenuButton( sLabelText, oSubMenu ) {
	this.MenuItem = MenuItem;
	this.MenuItem( sLabelText, null, null, oSubMenu );

	// private
	this._hover = false;
	this._useInsets = false;	// should insets be taken into account when showing sub menu
}

MenuButton.prototype = new MenuItem;
MenuButton.prototype.subMenuDirection = "vertical";

MenuButton.prototype.scrollIntoView = function () {};
MenuButton.prototype.toHtml = function () {
	var cssClass = this.getCssClass();
	var toolTip = this.getToolTip();

	if ( this.subMenu && !this.subMenu._onclose )
		this.subMenu._onclose = new Function( "eventListeners.menuButton.onclose(\"" + this.id + "\")" );

	return	"<span unselectable=\"on\" " +
			(cssClass != "" ? " class=\"" + cssClass + "\"" : "") +
			(toolTip != "" ? " title=\"" + toolTip + "\"" : "") +
			(!this.visible ? " style=\"display: none\"" : "") +
			"><span unselectable=\"on\" class=\"left\"></span>" +
			"<span unselectable=\"on\" class=\"middle\">" +
				this.getTextHtml() +
			"</span>" +
			"<span unselectable=\"on\" class=\"right\"></span>" +
			"</span>";
};

MenuButton.prototype.getCssClass = function () {
	if ( this.disabled && this._selected )
		return "menu-button disabled-hover";
	else if ( this.disabled )
		return "menu-button disabled";
	else if ( this._selected ) {
		if ( this.parentMenu.getActiveState() == "open" ) {
			return "menu-button active";
		}
		else
			return "menu-button hover";
	}
	else if ( this._hover )
		return "menu-button hover";

	return "menu-button ";
};

MenuButton.prototype.subMenuClosed = function () {

	if ( this.subMenu._closeReason == "escape" )
		this.setSelected( true );
	else
		this.setSelected( false );

	if ( this.parentMenu.getActiveState() == "inactive" )
		this.parentMenu.restoreFocused();
};

MenuButton.prototype.setSelected = function ( bSelected ) {

	var oldSelected = this._selected;
	this._selected = Boolean( bSelected );

	var tr = this._htmlElement;
	if ( tr )
		tr.className = this.getCssClass();

	if ( this._selected == oldSelected )
		return;

	if ( !this._selected )
		this.closeSubMenu( true );

	if ( bSelected ) {
		this.parentMenu.setSelectedIndex( this.itemIndex );
		this.scrollIntoView();
	}
	else
		this.parentMenu.setSelectedIndex( -1 );
};





////////////////////////////////////////////////////////////////////////////////////
// event listener
//

var eventListeners = {
	menu: {
		onkeydown:	function ( id ) {
			var oThis = menuCache[id];
			var w = oThis.getDocument().parentWindow;
			oThis.handleKeyEvent( w.event );
		},
		onunload:	function ( id ) {
			if (id in menuCache) {
				menuCache[id].closeAllMenus();
				menuCache[id].destroy();
			}
			// else already destroyed
		},
		oncontextmenu:	function ( id ) {
			var oThis = menuCache[id];
			var w = oThis.getDocument().parentWindow;
			w.event.returnValue = false;
		},

		onscroll:	function ( id ) {
			menuCache[id].fixScrollEnabledState();
		},

		onmouseover:	function ( id ) {

			var oThis = menuCache[id];
			var w = oThis.getDocument().parentWindow;

			var fromEl	= getTrElement( w.event.fromElement );
			var toEl	= getTrElement( w.event.toElement );

			if ( toEl != null && toEl != fromEl ) {
				var mi = toEl._menuItem;
				if ( mi ) {
					if ( !mi.disabled || oThis.mouseHoverDisabled ) {
						mi.setSelected( true );
						mi.showSubMenu( true );
					}
				}
				else {	// scroll button
					if (toEl.className == "disabled" || toEl.className == "disabled-hover" )
						toEl.className = "disabled-hover";
					else
						toEl.className = "hover";
					oThis.selectedIndex = -1;
				}
			}
		},

		onmouseout:	function ( id ) {
			var oThis = menuCache[id];
			var w = oThis.getDocument().parentWindow;

			var fromEl	= getTrElement( w.event.fromElement );
			var toEl	= getTrElement( w.event.toElement );

			if ( fromEl != null && toEl != fromEl ) {

				var id = fromEl.parentNode.parentNode.id;
				var mi = fromEl._menuItem;

				if ( id == "scroll-up-item" || id == "scroll-down-item" ) {
					if (fromEl.className == "disabled-hover" || fromEl.className == "disabled" )
						fromEl.className = "disabled";
					else
						fromEl.className = "";
					oThis.selectedIndex = -1;
				}

				else if ( mi &&
					( toEl != null || mi.subMenu == null || mi.disabled ) ) {

					mi.setSelected( false );
				}
			}

		},

		onmouseup:	function ( id ) {
			var oThis = menuCache[id];
			var w = oThis.getDocument().parentWindow;

			var srcEl	= getMenuItemElement( w.event.srcElement );

			if ( srcEl != null ) {
				var id = srcEl.parentNode.parentNode.id;
				if ( id == "scroll-up-item" || id == "scroll-down-item" ) {
					return;
				}

				oThis.selectedIndex = srcEl.rowIndex;
				var menuItem = oThis.items[ oThis.selectedIndex ];
				menuItem.dispatchAction();
			}
		},

		onmousewheel:	function ( id ) {
			var oThis = menuCache[id];
			var d = oThis.getDocument();
			var w = d.parentWindow;
			var scrollContainer = d.getElementById("scroll-container");
			scrollContainer.scrollTop -= 3 * w.event.wheelDelta / 120 * ScrollButton.scrollAmount;
		},

		onreadystatechange:	function ( id ) {
			var oThis = menuCache[id];
			var d = oThis.getDocument();
			var linkEl = d.getElementsByTagName("LINK")[0];
			if ( linkEl.readyState == "complete" ) {
				oThis.resetSizeCache();	// reset sizes
				oThis.fixSize();
				oThis.fixScrollButtons();
			}
		},

		oncloseinterval:	function ( id ) {
			 menuCache[id]._checkCloseState();
		}
	},


	menuItem:	{
		onshowtimer:	function ( id ) {
			var oThis = menuCache[id];
			var sm = oThis.subMenu;
			var pm = oThis.parentMenu;
			var selectedIndex = sm.getSelectedIndex();

			pm.closeAllSubs( sm );
			window.setTimeout( "eventListeners.menuItem.onshowtimer2(\"" + id + "\")", 1);
		},

		onshowtimer2:	function ( id ) {
			var oThis = menuCache[id];
			var sm = oThis.subMenu;
			var selectedIndex = sm.getSelectedIndex();
			oThis.positionSubMenu();
			sm.setSelectedIndex( selectedIndex );
			oThis.setSelected( true );
		},

		onclosetimer:	function ( id ) {
			var oThis = menuCache[id];
			var sm = oThis.subMenu;
			sm.close();
		},

		onpositionsubmenutimer:	function ( id ) {
			var oThis = menuCache[id];
			var sm = oThis.subMenu;
			sm.resetSizeCache();	// reset sizes
			oThis.positionSubMenu();
			sm.setSelectedIndex( 0 );
		}
	},

	menuBar:	{
		onmouseover:	function ( id ) {
			var oThis = menuCache[id];

			var e = oThis.getDocument().parentWindow.event;
			var fromEl = getMenuItemElement( e.fromElement );
			var toEl = getMenuItemElement( e.toElement );

			if ( toEl != null && toEl != fromEl ) {

				var mb = toEl._menuItem;
				var m = mb.parentMenu;

				if ( m.getActiveState() == "open" ) {
					window.setTimeout( function () {
						mb.dispatchAction();
					}, 1);
				}
				else if ( m.getActiveState() == "active" ) {
					mb.setSelected( true );
				}
				else {
					mb._hover = true;
					toEl.className = mb.getCssClass();
				}
			}
		},

		onmouseout:	function ( id ) {
			var oThis = menuCache[id];

			var e = oThis.getDocument().parentWindow.event;
			var fromEl = getMenuItemElement( e.fromElement );
			var toEl = getMenuItemElement( e.toElement );

			if ( fromEl != null && toEl != fromEl ) {
				var mb = fromEl._menuItem;
				mb._hover = false;
				fromEl.className = mb.getCssClass();
			}
		},

		onmousedown:	function ( id ) {
			var oThis = menuCache[id];

			var e = oThis.getDocument().parentWindow.event;
			if ( e.button != MenuBar.leftMouseButton )
				return;

			var el = getMenuItemElement( e.srcElement );

			if ( el != null ) {
				var mb = el._menuItem;
				if ( mb.subMenu ) {
					mb.subMenu._checkCloseState();
					if ( new Date() - mb.subMenu._closedAt > 100 ) {	// longer than the time to
																		// do the hide
						mb.dispatchAction();
					}
					else {
						mb._hover = true;
						mb._htmlElement.className = mb.getCssClass();
					}
				}
			}
		},

		onkeydown:	function ( id ) {
			var oThis = menuCache[id];
			var e = oThis.getDocument().parentWindow.event;
			oThis.handleKeyEvent( e );
		},

		onunload:	function ( id ) {
			menuCache[id].destroy();
		},

		ongotonextmenuitem:	function ( id ) {
			var oThis = menuCache[id];
			var mi = oThis.items[ oThis.getSelectedIndex() ];
			mi.dispatchAction();
			if ( mi.subMenu )
				mi.subMenu.setSelectedIndex( 0 );
		},

		ongotopreviousmenuitem:	function ( id ) {
			var oThis = menuCache[id];
			var mi = oThis.items[ oThis.getSelectedIndex() ];
			mi.dispatchAction();
			if ( mi.subMenu )
				mi.subMenu.setSelectedIndex( 0 );
		}
	},

	menuButton: {
		onclose:	function ( id ) {
			menuCache[id].subMenuClosed();
		}
	}
};/*
 * This script was created by Erik Arvidsson (http://webfx.eae.net/contact.html#erik)
 * for WebFX (http://webfx.eae.net
 * Copyright 2001
 *
 * For usage see license at http://webfx.eae.net/license.html
 *
 * Created: 2001-03-17
 */

/*
 * This file depends on emulateAttachEvent and extendEventObject
 * found in ieemu.js to get Mozilla to work
 *
 * Styling is currently done in a separate css files
 * cb2.css
 *
 */

/*
Cool Button 2 API
=================
createButton(table.rows[0].cells[2]);
table.rows[0].cells[2].setEnabled(false);
table.rows[0].cells[2].setToggle(true);
table.rows[0].cells[2].setAlwaysUp(true);
onaction is event that is fired when clicked !
*/

/* Set up IE Emualtion for Mozilla */
if (window.moz == true && (typeof window.emulateAttachEvent != "function" || typeof window.extendEventObject != "function"))
	alert("Error! IE Emulation file not included.");

if (window.moz) {
	emulateAttachEvent();
	extendEventObject();
}
/* end Mozilla specific emulation initiation */

function createButton(el) {
	if(el!=null)
	{
	el.attachEvent("onmouseover",	createButton.overCoolButton);
	el.attachEvent("onmouseout",	createButton.outCoolButton);
	el.attachEvent("onmousedown",	createButton.downCoolButton);
	el.attachEvent("onmouseup",		createButton.upCoolButton);
	el.attachEvent("onclick",		createButton.clickCoolButton);
	el.attachEvent("ondblclick",	createButton.clickCoolButton);
	el.attachEvent("onkeypress",	createButton.keypressCoolButton);
	el.attachEvent("onkeyup",		createButton.keyupCoolButton);
	el.attachEvent("onkeydown",		createButton.keydownCoolButton);
	el.attachEvent("onfocus",		createButton.focusCoolButton);
	el.attachEvent("onblur",		createButton.blurCoolButton);

	el.className = "coolButton";

	el.setEnabled	= createButton.setEnabled;
	el.getEnabled	= createButton.getEnabled;
	el.setValue		= createButton.setValue;
	el.getValue		= createButton.getValue;
	el.setToggle	= createButton.setToggle;
	el.getToggle	= createButton.getToggle;
	el.setAlwaysUp	= createButton.setAlwaysUp;
	el.getAlwaysUp	= createButton.getAlwaysUp;

	el._enabled		= true;
	el._toggle		= false;
	el._value		= false;
	el._alwaysUp	= false;

	return el;
	}
}

createButton.LEFT = window.moz ? 0 : 1;

/* event listeners */

createButton.overCoolButton = function () {
	var toEl = createButton.getParentCoolButton(window.event.toElement);
	var fromEl = createButton.getParentCoolButton(window.event.fromElement);
	if (toEl == fromEl || toEl == null) return;

	toEl._over = true;

	if (!toEl._enabled) return;

	createButton.setClassName(toEl);
};

createButton.outCoolButton = function () {
	var toEl = createButton.getParentCoolButton(window.event.toElement);
	var fromEl = createButton.getParentCoolButton(window.event.fromElement);
	if (toEl == fromEl || fromEl == null) return;

	fromEl._over = false;
	fromEl._down = false;

	if (!fromEl._enabled) return;

	createButton.setClassName(fromEl);
};

createButton.downCoolButton = function () {
	if (window.event.button != createButton.LEFT) return;

	var el = createButton.getParentCoolButton(window.event.srcElement);
	if (el == null) return;

	el._down = true;

	if (!el._enabled) return;

	createButton.setClassName(el);
};

createButton.upCoolButton = function () {
	if (window.event.button != createButton.LEFT) return;

	var el = createButton.getParentCoolButton(window.event.srcElement);
	if (el == null) return;

	el._down = false;

	if (!el._enabled) return;

	if (el._toggle)
		el.setValue(!el._value);
	else
		createButton.setClassName(el);
};

createButton.clickCoolButton = function () {
	var el = createButton.getParentCoolButton(window.event.srcElement);
	el.onaction = el.getAttribute("onaction");
	if (el == null || !el._enabled || el.onaction == "" || el.onaction == null) return;

	if (typeof el.onaction == "string")
		el.onaction = new Function ("event", el.onaction);

	el.onaction(window.event);
};

createButton.keypressCoolButton = function () {
	var el = createButton.getParentCoolButton(window.event.srcElement);
	if (el == null || !el._enabled || window.event.keyCode != 13) return;

	el.setValue(!el._value);

	if (el.onaction == null) return;

	if (typeof el.onaction == "string")
		el.onaction = new Function ("event", el.onaction);
	
	el.onaction(window.event);
};

createButton.keydownCoolButton = function () {
	var el = createButton.getParentCoolButton(window.event.srcElement);
	if (el == null || !el._enabled || window.event.keyCode != 32) return;
	createButton.downCoolButton();
};

createButton.keyupCoolButton = function () {
	var el = createButton.getParentCoolButton(window.event.srcElement);
	if (el == null || !el._enabled || window.event.keyCode != 32) return;
	createButton.upCoolButton();
	
	//el.setValue(!el._value);	// is handled in upCoolButton()
	
	if (el.onaction == null) return;
	
	if (typeof el.onaction == "string")
		el.onaction = new Function ("event", el.onaction);
	
	el.onaction(window.event);
};

createButton.focusCoolButton = function () {
	var el = createButton.getParentCoolButton(window.event.srcElement);
	if (el == null || !el._enabled) return;
	createButton.setClassName(el);
};

createButton.blurCoolButton = function () {
	var el = createButton.getParentCoolButton(window.event.srcElement);
	if (el == null) return;
	
	createButton.setClassName(el)
};

createButton.getParentCoolButton = function (el) {
	if (el == null) return null;
	if (/coolButton/.test(el.className))
		return el;
	return createButton.getParentCoolButton(el.parentNode);
};

/* end event listeners */

createButton.setClassName = function (el) {
	var over = el._over;
	var down = el._down;
	var focused;
	try {
		focused = (el == document.activeElement && el.tabIndex > 0);
	}
	catch (exc) {
		focused = false;
	}
	
	if (!el._enabled) {
		if (el._value)
			el.className = "coolButtonActiveDisabled";
		else
			el.className = el._alwaysUp ? "coolButtonUpDisabled" : "coolButtonDisabled";
	}
	else {
		if (el._value) {
			if (over || down || focused)
				el.className = "coolButtonActiveHover";
			else
				el.className = "coolButtonActive";
		}
		else {
			if (down)
				el.className = "coolButtonActiveHover";
			else if (over || el._alwaysUp || focused)
				el.className = "coolButtonHover";
			else
				el.className = "coolButton";
		}
	}
};

createButton.setEnabled = function (b) {
	if (this._enabled != b) {
		this._enabled = b;
		createButton.setClassName(this, false, false);
		if (!window.moz) {
			if (b)
				this.innerHTML = this.firstChild.firstChild.innerHTML;
			else
				this.innerHTML = "<span class='coolButtonDisabledContainer'><span class='coolButtonDisabledContainer'>" + this.innerHTML + "</span></span>";
		}
	}
};

createButton.getEnabled = function () {
	return this._enabled;
};

createButton.setValue = function (v, bDontTriggerOnChange) {
	if (this._toggle && this._value != v) {
		this._value = v;
		createButton.setClassName(this, false, false);
		
		this.onchange = this.getAttribute("onchange");
		
		if (this.onchange == null || this.onchange == "" || bDontTriggerOnChange) return;
		
		if (typeof this.onchange == "string")
			this.onchange = new Function("", this.onchange);

		this.onchange();
	}
};

createButton.getValue = function () {
	return this._value;
};

createButton.setToggle = function (t) {
	if (this._toggle != t) {
		this._toggle = t;
		if (!t) this.setValue(false);
	}
};

createButton.getToggle = function () {
	return this._toggle;
};

createButton.setAlwaysUp = function (up) {
	if (this._alwaysUp != up) {
		this._alwaysUp = up;
		createButton.setClassName(this, false, false);
	}
};

createButton.getAlwaysUp = function () {
	return this._alwaysUp;
};
var ie = document.all != null;
var moz = !ie && document.getElementById != null && document.layers == null;

/*
if (moz) {	// set up ie environment for Moz

	extendEventObject();
	//emulateAttachEvent();
	//emulateFromToElement();
	emulateEventHandlers(["click", "dblclick", "mouseover", "mouseout",
							"mousedown", "mouseup", "mousemove",
							"keydown", "keypress", "keyup"]);
	emulateDocumentAll();
	emulateElement()
	emulateCurrentStyle(["left", "right", "top", "bottom", "width", "height"]);

	// Mozilla returns the wrong button number
	Event.LEFT = 1;
	Event.MIDDLE = 2;
	Event.RIGHT = 3;
	

	
}
else {
	Event = {};
	// IE is returning wrong button number as well :-)
	Event.LEFT = 1;
	Event.MIDDLE = 4;
	Event.RIGHT = 2;
}
*/





/*
 * Extends the event object with srcElement, cancelBubble, returnValue,
 * fromElement and toElement
 */
function extendEventObject() {
	Event.prototype.__defineSetter__("returnValue", function (b) {
		if (!b) this.preventDefault();
	});
	
	Event.prototype.__defineSetter__("cancelBubble", function (b) {
		if (b) this.stopPropagation();
	});
	
	Event.prototype.__defineGetter__("srcElement", function () {
		var node = this.target;
		while (node.nodeType != 1) node = node.parentNode;
		return node;
	});

	Event.prototype.__defineGetter__("fromElement", function () {
		var node;
		if (this.type == "mouseover")
			node = this.relatedTarget;
		else if (this.type == "mouseout")
			node = this.target;
		if (!node) return;
		while (node.nodeType != 1) node = node.parentNode;
		return node;
	});

	Event.prototype.__defineGetter__("toElement", function () {
		var node;
		if (this.type == "mouseout")
			node = this.relatedTarget;
		else if (this.type == "mouseover")
			node = this.target;
		if (!node) return;
		while (node.nodeType != 1) node = node.parentNode;
		return node;
	});
	
	Event.prototype.__defineGetter__("offsetX", function () {
		return this.layerX;
	});
	Event.prototype.__defineGetter__("offsetY", function () {
		return this.layerY;
	});
}

/*
 * Emulates element.attachEvent as well as detachEvent
 */
function emulateAttachEvent() {
	HTMLDocument.prototype.attachEvent = 
	HTMLElement.prototype.attachEvent = function (sType, fHandler) {
		var shortTypeName = sType.replace(/on/, "");
		fHandler._ieEmuEventHandler = function (e) {
			window.event = e;
			return fHandler();
		};
		this.addEventListener(shortTypeName, fHandler._ieEmuEventHandler, false);
	};

	HTMLDocument.prototype.detachEvent = 
	HTMLElement.prototype.detachEvent = function (sType, fHandler) {
		var shortTypeName = sType.replace(/on/, "");
		if (typeof fHandler._ieEmuEventHandler == "function")
			this.removeEventListener(shortTypeName, fHandler._ieEmuEventHandler, false);
		else
			this.removeEventListener(shortTypeName, fHandler, true);
	};
}

/*
 * This function binds the event object passed along in an
 * event to window.event
 */
function emulateEventHandlers(eventNames) {
	for (var i = 0; i < eventNames.length; i++) {	
		document.addEventListener(eventNames[i], function (e) {
			window.event = e;
		}, true);	// using capture
	}
}

/*
 * Simple emulation of document.all
 * this one is far from complete. Be cautious
 */
 
function emulateAllModel() {
	var allGetter = function () {
		var a = this.getElementsByTagName("*");
		var node = this;
		a.tags = function (sTagName) {
			return node.getElementsByTagName(sTagName);
		};
		return a;
	};
	HTMLDocument.prototype.__defineGetter__("all", allGetter);
	HTMLElement.prototype.__defineGetter__("all", allGetter);
}

function extendElementModel() {
	HTMLElement.prototype.__defineGetter__("parentElement", function () {
		if (this.parentNode == this.ownerDocument) return null;
		return this.parentNode;
	});
	
	HTMLElement.prototype.__defineGetter__("children", function () {
		var tmp = [];
		var j = 0;
		var n;
		for (var i = 0; i < this.childNodes.length; i++) {
			n = this.childNodes[i];
			if (n.nodeType == 1) {
				tmp[j++] = n;
				if (n.name) {	// named children
					if (!tmp[n.name])
						tmp[n.name] = [];
					tmp[n.name][tmp[n.name].length] = n;
				}
				if (n.id)		// child with id
					tmp[n.id] = n
			}
		}
		return tmp;
	});
	
	HTMLElement.prototype.contains = function (oEl) {
		if (oEl == this) return true;
		if (oEl == null) return false;
		return this.contains(oEl.parentNode);		
	};
}

/*

document.defaultView.getComputedStyle(el1,<BR>null).getPropertyValue('top');

*/
function emulateCurrentStyle(properties) {
	HTMLElement.prototype.__defineGetter__("currentStyle", function () {
		var cs = {};
		var el = this;
		for (var i = 0; i < properties.length; i++) {
			//cs.__defineGetter__(properties[i], function () {
			//	window.status = "i: " + i	;
			//	return document.defaultView.getComputedStyle(el, null).getPropertyValue(properties[i]);
			//});
			cs.__defineGetter__(properties[i], encapsulateObjects(el, properties[i]));
		}
		return cs;
	});
}
// used internally for emualteCurrentStyle
function encapsulateObjects(el, sProperty) {
	return function () {
		return document.defaultView.getComputedStyle(el, null).getPropertyValue(sProperty);
	};
}

function emulateHTMLModel() {

	// This function is used to generate a html string for the text properties/methods
	// It replaces '\n' with "<BR"> as well as fixes consecutive white spaces
	// It also repalaces some special characters	
	function convertTextToHTML(s) {
		s = s.replace(/\&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\n/g, "<BR>");
		while (/\s\s/.test(s))
			s = s.replace(/\s\s/, "&nbsp; ");
		return s.replace(/\s/g, " ");
	}

	HTMLElement.prototype.insertAdjacentHTML = function (sWhere, sHTML) {
		var df;	// : DocumentFragment
		var r = this.ownerDocument.createRange();
		
		switch (String(sWhere).toLowerCase()) {
			case "beforebegin":
				r.setStartBefore(this);
				df = r.createContextualFragment(sHTML);
				this.parentNode.insertBefore(df, this);
				break;
				
			case "afterbegin":
				r.selectNodeContents(this);
				r.collapse(true);
				df = r.createContextualFragment(sHTML);
				this.insertBefore(df, this.firstChild);
				break;
				
			case "beforeend":
				r.selectNodeContents(this);
				r.collapse(false);
				df = r.createContextualFragment(sHTML);
				this.appendChild(df);
				break;
				
			case "afterend":
				r.setStartAfter(this);
				df = r.createContextualFragment(sHTML);
				this.parentNode.insertBefore(df, this.nextSibling);
				break;
		}	
	};

	HTMLElement.prototype.__defineSetter__("outerHTML", function (sHTML) {
	   var r = this.ownerDocument.createRange();
	   r.setStartBefore(this);
	   var df = r.createContextualFragment(sHTML);
	   this.parentNode.replaceChild(df, this);
	   
	   return sHTML;
	});

	HTMLElement.prototype.__defineGetter__("canHaveChildren", function () {
		switch (this.tagName) {
			case "AREA":
			case "BASE":
			case "BASEFONT":
			case "COL":
			case "FRAME":
			case "HR":
			case "IMG":
			case "BR":
			case "INPUT":
			case "ISINDEX":
			case "LINK":
			case "META":
			case "PARAM":
				return false;
		}
		return true;
	});

	HTMLElement.prototype.__defineGetter__("outerHTML", function () {
		var attr, attrs = this.attributes;
		var str = "<" + this.tagName;
		for (var i = 0; i < attrs.length; i++) {
			attr = attrs[i];
			if (attr.specified)
				str += " " + attr.name + '="' + attr.value + '"';
		}
		if (!this.canHaveChildren)
			return str + ">";
		
		return str + ">" + this.innerHTML + "</" + this.tagName + ">";
	});


	HTMLElement.prototype.__defineSetter__("innerText", function (sText) {
		this.innerHTML = convertTextToHTML(sText);
		return sText;		
	});

	var tmpGet;
	HTMLElement.prototype.__defineGetter__("innerText", tmpGet = function () {
		var r = this.ownerDocument.createRange();
		r.selectNodeContents(this);
		return r.toString();
	});

	HTMLElement.prototype.__defineSetter__("outerText", function (sText) {
		this.outerHTML = convertTextToHTML(sText);
		return sText;
	});
	HTMLElement.prototype.__defineGetter__("outerText", tmpGet);

	HTMLElement.prototype.insertAdjacentText = function (sWhere, sText) {
		this.insertAdjacentHTML(sWhere, convertTextToHTML(sText));
	};

}var loadcomplete=0;
var oldloadcomplete=0;
// Browser Detection
isMac = (navigator.appVersion.indexOf("Mac")!=-1) ? true : false;
NS4 = (document.layers) ? true : false;
IEmac = ((document.all)&&(isMac)) ? true : false;
IE4plus = (document.all) ? true : false;
IE4 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 4.")!=-1)) ? true : false;
IE5 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 5.")!=-1)) ? true : false;
ver4 = (NS4 || IE4plus) ? true : false;
NS6 = (!document.layers) && (navigator.userAgent.indexOf('Netscape')!=-1)?true:false;

// Body onload utility (supports multiple onload functions)
var gSafeOnload = new Array();
function SafeAddOnload(f)
{
	if (IEmac && IE4)  // IE 4.5 blows out on testing window.onload
	{
		window.onload = SafeOnload;
		gSafeOnload[gSafeOnload.length] = f;
	}
	else if (window.onload)
	{
		if (window.onload != SafeOnload)
		{
			gSafeOnload[0] = window.onload;
			window.onload = SafeOnload;
		}
		gSafeOnload[gSafeOnload.length] = f;
	}
	else
		window.onload = f;
}
function SafeOnload()
{
	for (var i=0;i<gSafeOnload.length;i++)
		gSafeOnload[i]();
}

function isInt(numIn)
{
	var checknum = parseInt(numIn);
	return !isNaN(checknum);
}

// Make an object visible
function showObject(obj)
{
        if (NS4) obj.visibility = "show";
        else if (IE4plus||NS6) obj.visibility = "visible";
}

// Hides an object
function hideObject(obj) 
{
        if (NS4) obj.visibility = "hide";
        else if (IE4plus||NS6) obj.visibility = "hidden";
}

// Move a layer
function moveTo(obj,xL,yL) 
{
        obj.left = xL;
        obj.top = yL;
}

// Browser window width
function getWindowWidth()
{
	if (NS4 || NS6)
		return window.innerWidth;
	else if (IE4plus)
		return document.body.clientWidth;
}

function getObjLoc(oIn)
{
	var oOut = new Object();
	oOut.top = 0;
	oOut.left = 0;

	if ((IE4plus && !isMac) || (IEmac && IE5) )
	{
		oOut.left = oIn.offsetLeft;
		oOut.top = oIn.offsetTop;
		var newp = oIn.offsetParent;
		while(newp != null)
		{
			oOut.left += newp.offsetLeft;
			oOut.top += newp.offsetTop;
			newp = newp.offsetParent;
		}
		if (IEmac)
		{	
			oOut.left += parseInt(document.body.leftMargin);
			oOut.top +=  parseInt(document.body.topMargin);
		}
	}
	else if (NS4)
	{
		oOut.left = oIn.x;
		oOut.top = oIn.y;
	}
	else if (isMac && IE4)
	{
		var el = oIn;
		do
		{
			if (isInt(el.offsetTop))
				oOut.top += el.offsetTop;
			if (isInt(el.offsetLeft))
				oOut.left += el.offsetLeft;
			el = el.parentElement;
		} while (el.tagName != "BODY");
		if (navigator.appVersion.indexOf("4.5")>=0)
			oOut.top = oOut.top - 15;
	}
	else if (NS6)
	{
		var b=document.getElementsByTagName('body')[0];
		oOut.left = oIn.offsetLeft+b.offsetLeft;
		oOut.top = oIn.offsetTop+b.offsetTop;
	}
	return oOut;
}


function createLayer(name,left,top,width,height,html)
{
	var nL;

	if (IE4plus)
	{
		var divhtml = '<div id=' + name + ' style="z-index:50000000;visibility:hidden;left:' + left +
			'px;top:' + top + 'px;width:' + width +
			'px;height:' + height + 'px;position:absolute">' +
			html + '</div>';
		document.body.insertAdjacentHTML('beforeEnd', divhtml);
		nL = document.all[name].style
	}
	else if (NS4)
	{
		nL=new Layer(width);
		nL.name = name;
		nL.left=left;
		nL.top=top;
		nL.clip.width=width;
		nL.clip.height=height;
		nL.document.open();
		nL.document.write(html);
		nL.document.close();
	}
	else if (NS6)
	{
		var nL = document.createElement("DIV");
		nL.innerHTML = html;
		var mybody=document.body;
		mybody.appendChild(nL);
		nL.style.position = "absolute";
		nL.style.visibility = "hidden";
		nL.style.left = left;
		nL.style.top = top;
		nL.style.width = width;
		nL.style.height = height;
		nL.id = name;
		nL = nL.style;
	}
	return nL;
}

function DMD_GetContentHTML()
{
	//	var html = '<center><I><FONT face="trebuchet ms" color=white size="3"><STRONG>Please wait while loading ...</STRONG></FONT></I><BR>';
	//	html += '<FONT color=white face="trebuchet ms" size="3"><STRONG>www.centre.biz</STRONG></FONT><BR>';
	//	html += '<IMG src="images/spacer.gif" width=2 height=8 border=0><BR>';
	//	html += '<a href="http://javascript.about.com/gi/pages/mmail.htm"><IMG src="images/subscribe.gif" width=66 height=17 border=0></a></center>';
	var html="";
	return html;
}

function DMD_GetWindowHTML()
{
	//	var html = '<map name="DMDMap">';
	//	html += '<area href="javascript:gDialog.ShowLayers(false)" shape="rect" coords="' + (this.width - 24) + ', 0, ' + this.width + ', 18"></map>';
	//	html += '<img src="' + this.imgURL + '" width="' + this.width + '" height="' + this.height + '" border="0" usemap="#DMDMap" >';
	var html = '<img style="cursor:wait;" src="' + this.imgURL + '" width="' + this.width + '" height="' + this.height + '" border="0">';
	//var html="";
	return html;
}

function createOverlayLayer()
{
	var nL;
	var left = 0;
	var top = 0;
	var name = "overlay";
	var html = "";

	if (IE4plus)
	{
		var width = isMac ? document.body.offsetWidth : document.body.scrollWidth;
		var height = isMac ? document.body.offsetHeight : document.body.scrollHeight;
		var divhtml = '<div  id=' + name + ' style="visibility:visible;left:' + left +
			'px;top:' + top + 'px;width:' + width +
			'px;height:' + height + 'px;position:absolute; cursor:wait; background: url(images/misc/transoverlay.gif) repeat">' +
			html + '</div>';
		document.body.insertAdjacentHTML('beforeEnd', divhtml);
		nL = document.all[name].style
	}
	else if (NS4)
	{
		var width = document.width;
		var height = document.height;
		nL=new Layer(width);
		nL.name = name;
		nL.left=left;
		nL.top=top;
		nL.height = height;
		nL.clip.width = width;
		nL.clip.height = height;
		nL.visibility = "show";
		nL.background = "images/misc/transoverlay.gif";
		nL.document.open();
		nL.document.write('<table background="images/misc/transoverlay.gif"><tr><td><img src="images/blank.gif" width="' + width + '" height="' + height +'"></td></tr></table>');
		nL.document.close();
	}
	else if (NS6)
	{
		var nL = document.createElement("DIV");
		nL.innerHTML = "";
		var mybody=document.body;
		mybody.appendChild(nL);
		nL.style.position = "absolute";
		nL.style.visibility = "visible";
		nL.style.left = left;
		nL.style.top = top;
		nL.style.width = document.body.offsetWidth+document.body.offsetLeft;
		nL.style.height = document.body.offsetHeight+document.body.offsetTop;
		nL.style.background = "url(images/misc/transoverlay.gif)";
		nL.id = name;
		nL = nL.style;
	}
	return nL;
}

function getCenter()
{
	var clientHeight;
	var clientWidth;
	var docTop;
	var docLeft;
	
    if (IE4plus) 
    {
      clientHeight = document.body.clientHeight;
      clientWidth = document.body.clientWidth;
      docTop = document.body.scrollTop;
      docLeft = document.body.scrollLeft;
    } 
    else if (NS4 || NS6)
    {
      // Fudge for the scrollbars
      clientHeight = window.innerHeight -20;
      clientWidth = window.innerWidth - 20;
      docTop = window.pageYOffset;
      docLeft = window.pageXOffset;
	}
    
    var loc = new Object();
    loc.x = docLeft + clientWidth/2;
    loc.y = docTop + clientHeight/2;
    return loc;
}

function DMD_Display()
{
	if (IE4plus || NS4 || NS6)
	{
		if (!this.dvo)
			this.dvo = createOverlayLayer();

		if (!this.dv)
			this.dv = createLayer("dmdwindow",0,0,this.width,this.height,this.GetWindowHTML());

		if (!this.dvc)
			this.dvc = createLayer("dmdcontent",0,0,this.width-4,this.height-18,this.GetContentHTML());

		var loc = getCenter();
		this.dv.left = loc.x - this.width/2;
		this.dv.top = loc.y - this.height/2;

		this.dvc.left = loc.x + 4 - this.width/2;
		this.dvc.top = loc.y + 18 - this.height/2;
		this.ShowLayers(true);
	}
}


function DMD_ShowLayers(show)
{
	if (show)
	{
		showObject(this.dv);
		showObject(this.dvc);
		showObject(this.dvo);
	}
	else
	{
		hideObject(this.dv);
		hideObject(this.dvc);	
		hideObject(this.dvo);	
	}
}

function DHTMLModalDialog(imageURL,width,height)
{
	this.width = width;
	this.height = height;
	this.imgURL = imageURL;

	this.dv = null;
	this.dvc = null;
	this.dvo = null;

	this.GetWindowHTML = DMD_GetWindowHTML;
	this.GetContentHTML = DMD_GetContentHTML;
	this.ShowLayers = DMD_ShowLayers;
	this.Display = DMD_Display
}

function HandleResize()
{
	location.reload();
	return false;
}

if (NS4)
{
	window.captureEvents(Event.RESIZE);
	window.onresize = HandleResize;
}

var gDialog = new DHTMLModalDialog("images/misc/transoverlay.gif",249,140);/*
var width = document.body.clientWidth * .50;
var height = document.body.clientHeight * .50;

var posx = (document.body.clientWidth - width)/2;
var posy = (document.body.clientHeight - height)/4;
*/
var selectedtab="1";
var selectedtabId="infinimeDiv";
//if(location.href.indexOf("http://infinimation.com")!=-1)
	var historycounter=0;
var historyintermcounter=0;
var historypointer=0;
var ignoreHistory=0;
function RemoveWhiteSpace(str)
{
     var str1 = (str).replace(/^\s*|\s*$/g,'');
     return str1;
}

function GetFirstParentOfType(obj,tag)
{
	while(obj.tagName.toLowerCase()!=tag.toLowerCase() && obj.tagName.toLowerCase()!="body")
	{
		obj = obj.parentNode;
		
	}
	return obj;
}

// OLpageDefaults(RELX,posx,RELY,posy,FILTER,STATUS,'InfiniOffice Help Manager',WIDTH,width,HEIGHT,height,FADEIN,38,FADEOUT,38,STICKY,BGCOLOR,'#1E64B4',FGCOLOR,'aliceblue');

function cut(arr, i)
{
   var pre = arr.slice(0,i);
   var post = arr.slice(i+1, arr.length);
   return pre.concat(post);
}

function ParseValues(str)
{
	if (str!="")
	{
		var sSearch = str;
		if (sSearch.length > 0)
		{
	    	var recValues = sSearch.split('|');

			var arr1 = new Array(recValues.length-1);
			for (var j = 0; j < recValues.length; j++)
			{
				var asKeyValues = recValues[j].split('&');
				var asKeyValue = '';

				arr1[j] = new Array(asKeyValues.length-1);

				for (var i = 0; i < asKeyValues.length; i++)
				{
					asKeyValue = asKeyValues[i].split('=');
	            	arr1[j][asKeyValue[0]] = asKeyValue[1];

				}
			}
		}
		return arr1;
	}
	else
	{
		return new Array();
	}
}

function showWiz(args)
{
	var w = screen.availWidth-12;
	var h = screen.availHeight-50;
	var wd;
	
    if (args==undefined)
		wd = window.open('https://'+location.hostname+'/registration/signup.php','','left=0,top=0,toolbar=no, location=no, directories=no, status=yes, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no, width='+w+', height='+h) ;
	else
		wd = window.open('https://'+location.hostname+'/registration/signup.php?'+args,'','left=0,top=0,toolbar=no, location=no, directories=no, status=yes, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no, width='+w+', height='+h) ;
}


function ShowWindow(url,scroll,width,height,name)
{
	if(width == undefined && height == undefined)
	{
		width=.80;
		height=.70;
	}
	
	if (scroll == undefined)
		scroll="yes";
	
	if (name == undefined)
		name = "win";
		
	var w = parent.document.body.clientWidth*width;
	var h = screen.height*height;
	
	var x = (parent.document.body.clientWidth - w)/2;
	var y = (screen.height - h)/4;

	return OpenWindow(name,w,h,y,x,"yes","yes",scroll,"no","no",url,"");
}

function pop(scr) //used in vooffice reports
{

	var r = Math.random();
	var w = parent.document.body.clientWidth*.80;
	var h = screen.height*.70;
	var x = (parent.document.body.clientWidth+w);
	var y = (screen.height+h);

//	url='<?=$PHP_SELF ?>?&SCREEN='+scr+'&sid=<?= $mysession->sessionid ?>'
	window.open(scr,target='_blank','left=40,top=70,toolbar=no,location=no,status=no,resizable=yes,menubar=no,scrollbars=yes,width='+(screen.availWidth-75)+',height='+(screen.availHeight-100))	
	
}

function OpenWindow(strName,iW,iH,TOP,LEFT,R,S,SC,T,TB,URL,TYPE)
{
	if (TYPE=="modal" || TYPE=="modalIframe")
	{
		var sF=""
		sF+=T?'titlebar='+T+',':'';
		sF+=TB?'help:'+TB+';':'';
		sF+=S?'status:'+S+';':'';
		sF+=SC?'scroll:'+SC+';':'';
		sF+=R?'resizable:'+R+';':'';
		sF+=iW?'dialogWidth:'+iW+'px;':'';
		sF+=iH?'dialogHeight:'+iH+'px;':'';
		sF+=TOP?'dialogTop:'+TOP+'px;':'';
		sF+=LEFT?'dialogLeft:'+LEFT+'px;':'';
		if (TYPE=="modal")
		window.showModalDialog(URL+"&r="+Math.round(Math.random()*1000000),"",sF);
	}
	else
	{
		var sF=""
		sF += iW?'width='+iW+',':'';
		sF+=iH?'height='+iH+',':'';
		sF+=R?'resizable='+R+',':'';
		sF+=S?'status='+S+',':'';
		sF+=SC?'scrollbars='+SC+',':'';
	//	sF+=T?'titlebar='+T+',':'';
		sF+=TB?'toolbar='+TB+',':'';
		sF+=TB?'menubar='+TB+',':'';
		sF+=TOP?'top='+TOP+',':'';
		sF+=LEFT?'left='+LEFT+',':'';

		//var HMW=window.open(URL?URL:'about:blank',strName?strName:'',sF);
		var HMW=window.open(URL?URL:'about:blank',strName?strName:'',sF);		
		if ( (document.window != null) && (!HMW.opener) )
		HMW.opener=document.window;
		HMW.focus();
	}

}

//========================================
//ACCESSING QUERYSTRING THROUGH JAVASCRIPT
//========================================
function QueryString(url)
{
	var oQuery = new Object();
	var sSearch;

	if (url)
		sSearch = url;
	else
		sSearch = document.location.search.substring(1);

	if (sSearch.length > 0)
	{
		var asKeyValues = sSearch.split('&');
		var asKeyValue = '';
		for (var i = 0; i < asKeyValues.length; i++)
		{
			asKeyValue = asKeyValues[i].split('=');
			oQuery[asKeyValue[0]] = asKeyValue[1];
		}
	}
	return oQuery;
}


// Trim leading,traailing and middle spaces in a string
function trim(value) {
   var temp = value;
   var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
   if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
   var obj = / +/g;
   temp = temp.replace(obj, " ");
   if (temp == " ") { temp = ""; }
   return temp;
}

// Trim leading,traailing and middle spaces in all fields of a form
function trimAll()
{//alert();
	var frms = document.forms;
	//alert(document);
	//alert(document.forms);
	var arr;

	for(i=0;i<frms.length;i++)
	{
		arr = frms[i].elements;
		for(j=0;j<arr.length;j++)
		{
			if(arr[j].type == "textarea" || arr[j].type == "text")
				arr[j].value = trim(arr[j].value);
		}
	}
}

// Javascript Error Message
function ShowError(errorList)
{
	var msg = "";

	msg  = "______________________________________________________\n\n";
	msg += "The form could not continue because of the following error(s).\n";
	msg += "Please correct these error(s) and re-continue.\n";
	msg += "______________________________________________________\n\n";

	msg += errorList;
	alert(msg);
}

// To check Windows SP2
function CheckBrowserSP2()
{ 
	var issp2 = false; 
	issp2 = (window.navigator.userAgent.indexOf("SV1")!= -1); 

	if (issp2)
	{ 
		alert('This browser is internet Explorer in sp2') 
		return true;
	} 
	else 
	{ 
		alert('This browser is not internet Explorer in sp2'); 
		return false;
	}
}

// Date functions starts here

var dtCh= "-";
var minYear=1900;
var maxYear=2100;

function isInteger(s)
{
	var i;
	for (i = 0; i < s.length; i++){
		// Check that current character is number.
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
	}
	// All characters are numbers.
	return true;
}

function stripCharsInBag(s, bag)
{
	var i;
	var returnString = "";
	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.
	for (i = 0; i < s.length; i++){
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}

function daysInFebruary (year)
{
	// February has 29 days in any year evenly divisible by four,
	// EXCEPT for centurial years which are not also divisible by 400.
	return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) 
{
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   }
   return this
}

function isDate(dtStr)
{
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : dd-mm-yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid year")
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
	return true
}

// date functions ends here


// Cookie functions starts here

// utility function to retrieve an expiration date in proper
// format; pass three integer parameters for the number of days, hours,
// and minutes from now you want the cookie to expire (or negative
// values for a past date); all three parameters are required,
// so use zeros where appropriate
function getExpDate(days, hours, minutes) {
    var expDate = new Date( );
    if (typeof days == "number" && typeof hours == "number" && 
        typeof hours == "number") {
        expDate.setDate(expDate.getDate( ) + parseInt(days));
        expDate.setHours(expDate.getHours( ) + parseInt(hours));
        expDate.setMinutes(expDate.getMinutes( ) + parseInt(minutes));
        return expDate.toGMTString( );
    }
}
   
// utility function called by getCookie( )
function getCookieVal(offset) {
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1) {
        endstr = document.cookie.length;
    }
    return unescape(document.cookie.substring(offset, endstr));
}
   
// primary function to retrieve cookie by name
function getCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
            return getCookieVal(j);
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break; 
    }
    return "";
}
   
// store cookie value with optional details as needed
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape (value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
   
// remove the cookie by setting ancient expiration date
function deleteCookie(name,path,domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

// Cookie functions ends here


// Hide or Show Group (eg. <tr group="anygroup"> ... </tr> )
function ShowGroup(tableid,gname,show)
{
	//alert(tableid+','+gname+','+show);
	if (show == undefined)
		show = "";
	else if (!show)
		show = "none";
	//alert(document.getElementById(tableid));
	var trs = document.getElementById(tableid).rows;
	//alert(trs.length);
	for (var i=0;i<trs.length;i++)
	{
		//alert(trs[i].value+'|'+trs[i].getAttribute("group"));
		if (trs[i].getAttribute("group")==gname)
		{
			if (trs[i].style.display.toLowerCase() != show)
				trs[i].style.display = show;
		}	
	}
}

function ShowTr()
{
	var args = arguments;
	for (var i=0; i<args.length; i++)
	{
		if (document.getElementById(args[i]))
			document.getElementById(args[i]).style.display = "";
	}
}

function HideTr()
{
	var args = arguments;
	for (var i=0; i<args.length; i++)
	{
		if (document.getElementById(args[i]))
			document.getElementById(args[i]).style.display = "none";
	}
}

function getIframeID(el)
{
	var myTop;
	if (window.frameElement) 
	{
		myTop = window.frameElement;
	} 
	else if (window.top) 
	{
		myTop = window.top;
		var myURL = el.location.href;
		var iFs = myTop.document.getElementsByTagName('iframe');
		var x, i = iFs.length;
		while ( i-- )
		{
			x = iFs[i];
			if (x.src && x.src == myURL)
			{
				myTop = x;
				break;
			}
		}
	}
	if (myTop){
		return myTop.id;
	} 
	else 
	{
		return null;
	}
}

function trimString(str,len)
{
	if(str!=null)
	{
		if (str.length <= len)
			return str;
		else	
			return str.substr(0,len-3)+'...';
	}
}

function GetProjectLabel(projectname,path)
{
//	alert("->GetProjectLabel("+projectname+","+path+")");
	path = projectname+"/"+path;
	path = path.substring(0,path.length-1);
	var re = new RegExp('/' , 'g');
	path = path.replace(re,' &rsaquo; ');
	return path;
}


/************* String functions **************/

String.prototype.trim = function() 
{
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() 
{
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() 
{
	return this.replace(/\s+$/,"");
}

/************************************************/

/************** Base 64 Encoding Decoding ***************/
function encode64(input) 
{
   
   var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
   
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);
  
   return output;
}

function decode64(input) 
{
   var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
   
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   } while (i < input.length );

   return output;
}

//********************************************************/
//********* Ajax Functions ****//////
/*	
	function PostAjaxScreen(url,form,args,isUrl) 
	{
		var i = Math.round(10000000*Math.random());
	 		 		
		if(!isUrl)
			url = "index.php?SCREEN=" + url +'&sid='+_sessionid_ ;
		url = url + "&isajaxcall=1&rand="+i;

		if(!form)
		{
			alert('form is null');
			return false;
		}
	
		if(!args)
			args = Object();
			
		if(!args.onSucess)
			args.onSuccess = AjaxCallback;
			
		if(!args.onFailure)
			args.onFailure = AjaxReportError ;
			
		if(!args.onException)
			args.onException = AjaxException;
				
		srcW.ShowWaitDialog();
		
		alert(Ajax);
		alert(form.parent.parent.frames['IFControl'].request);
//		form.parent.parent.frames['IFControl'].request(args);
		var myAjax = new parent.parent.frames['IFControl'].Ajax.Request( url, args );
					
	}*/
	
	function PostAjaxScreen(url,form,obj,isUrl) 
	{
		//alert();
	 	var i = Math.round(10000000*Math.random());
	 		 		
	 	if(!isUrl)
	 		url = "index.php?SCREEN=" + url +'&sid='+_sessionid_ ;
	 	url = url + "&rand="+i;
		
		if(!form)
		{
			alert('form is null');
			return false;
		}
	
		var args = obj;
		//alert("form:"+form);
		data = Form.serialize(form);
		
		//alert("url:"+url);
//		if(obj.params)
//			args.parameters = obj.params;
			
		if(args)
		{
			
			if(!args.method)
				args.method =  'post';
				
			if(!args.parameters)
				args.parameters = data;	
			else
				args.parameters += '&' + data;
				//args.parameters.push(data);
				
			if(!args.onSuccess)
				args.onSuccess = AjaxCallback;
				
			if(!args.onFailure)
				args.onFailure = AjaxReportError ;
				
			if(!args.onException)
				args.onException = AjaxException;
		}
		else
		{
			args = Object();
			args.method =  'post';
			args.parameters = data;	
			args.onFailure = AjaxReportError;
			args.onSuccess = AjaxCallback;	
			args.onException = AjaxException;
		}
				
		if(typeof(srcW) != 'undefined' && typeof(srcW.ShowWaitDialog) != 'undefined')	
			srcW.ShowWaitDialog();
			//alert(srcW.ShowWaitDialog);
		//alert(parent.parent.Ajax.Request);
		//if(typeof(parent.parent.document.getElementById('IFControl'))!="undefined")
		//	var myAjax = new parent.parent.document.getElementById('IFControl').contentWindow.Ajax.Request( url, args );
		//else
			var myAjax = new Ajax.Request( url, args );
	}
	function ShowLastAjaxScreen()
	{
		var cookie = getCookie('last_ajax_action');
		var lastsid = getCookie('last_sid');

		if(cookie && _sessionid_==lastsid )			
		{
				var op = JSON.decode(cookie);
				alert(op.url+'|'+op.args);	
		}	
	}
	function LoadLastAjaxScreen()
	{
		var cookie = getCookie('last_ajax_action');
		var lastsid = getCookie('last_sid');
		if(cookie && _sessionid_==lastsid )			
		{
				var op = JSON.decode(cookie);
				LoadAjaxScreen(op.url,op.args,true);	
		}		
		else
			LoadAjaxScreen('showemailaccounts');

		
	}
	function ControlAct(controller,action,isUrl)
	{
		var i = Math.round(10000000*Math.random());
	 		 	var url;	
		if(!isUrl)
			url = "index.php?SCREEN=" + url +'&sid='+_sessionid_ ;
		
		url = url + "&rand="+i;
		url = "main.php?controller=" + controller + "&action=" + action +"&sid=" + _sessionid_ ;
//		var args = obj;
		var args = {};
		if(args)
		{
			if(!args.onSuccess)
				args.onSuccess = AjaxCallback;
				
			if(!args.onFailure)
				args.onFailure = AjaxReportError ;
				
			if(!args.onException)
				args.onException = AjaxException;
			
		}
		else
		{
			args = Object();
			args.method =  'post';
			args.onFailure = AjaxReportError;
			args.onSuccess = AjaxCallback;	
			args.onException = AjaxException;
		}
		
		if(!args.deleteList)	
		{
				if(typeof(list)=="object" && list.GetItemCount() >0)
				list.DeleteAllItems();	
		}		
		//alert("load"+mylink.length);		
		var link;
		if(typeof(mylink)!="undefined")
			link = mylink;
		else
			link = parent.mylink;			
		
		
		setCookie("last_sid", _sessionid_); 
		if(typeof(link)!="undefined")
		{
			if(link.length !=0 && link[link.length-1]['url']==url&& link[link.length-1]['args']==args)
	    	{
	    		return false;
	    	}		
	
			if (!args.skipHistory)
			{
				// History work
		    	var op = {"url":url,"args":args};
		    	op = JSON.encode(op);
		    	setCookie("last_ajax_action", op); 
		    	//alert('co:'+getCookie("last_ajax_action"));
				link[link.length] = {"url":url,"args":args};
				parent.tmpindex=link.length-1;
			}
		}
		// Loading div
		if(typeof(srcW) != 'undefined')	
			srcW.ShowWaitDialog();
		//alert(url);
		var w;
		var myAjax ;
		
//		if(Ajax)
			myAjax = new Ajax.Request( url, args );
//		else if(parent.frames['IFControl'].Ajax)
//			myAjax= parent.frames['IFControl'].Ajax.Request( url, args );
//		else
//			myAjax= parent.parent.frames['IFControl'].Ajax.Request( url, args );

//		alert("End"+mylink.length+"tmpindex"+tmpindex);
			
	}
	function html_entity_decode(str)
	{   
		var  tarea=document.createElement('textarea');    
		tarea.innerHTML = str; 
		return tarea.value;    
		tarea.parentNode.removeChild(tarea);
	}
	function check_hash_old() 
	{
		//debugger;
		if(loading==1)
		{
			//alert('file is loaing....');
			return;
		}
		current_hash1 = document.getElementById('historyFrame').contentWindow.document.body.innerHTML;
		latestHash = '#'+html_entity_decode(current_hash1);
		latestHashString = latestHash.split('&');
		urlHash = latestHash;
		
		latestHashString =  latestHash; //temp
		
		//windownHash = window.location.hash.split('&');
		windownHash = window.location.hash;//temp
		
		
		winURL= window.location.hash.split('&');
		winURL= window.location.hash;
		
		//alert(winURL[0]+'--'+latestHashString[0]);
		//return; 
		//alert(urlHash);
	   if(urlHash!='#test' & urlHash!='#stop')
	   {
		   	if ( winURL != latestHashString ) 
		    {
		    	//alert('reloadto::::'+urlHash);
		    	var urls = urlHash.split('#');
		    	var url = urls[1];
		    	
		    	/*succurl = latestHashString[1];
		    	onsucstring = succurl.split('objsuc=');
		    	onsuc = onsucstring[1];
		    	var obj = {onSuccess:onsuc};*/
		    	//alert(url+'--'+obj)
		    	
		    	LoadAjaxScreen(url);
		       // current_hash = window.location.hash;
		       // page_change( current_hash.substr( 1,  current_hash.length) );
		    }
		    
		    //else
		    //	alert('rehnedo');
	   }
	   else if(urlHash=='#stop')
	   {
	   }
	  // else
	  //     	LoadAjaxScreen('mainpage');
		
	  // alert('done');
	}
	var c=0;
	var loading=0;
	servername = "infinimation.com";
	function UpdateHash(url)
	{
		window.location.hash="aa"+Math.round(10000000*Math.random());
		window.location.hash=url;
		var current_hash = window.location.hash;
	}
	
	/*
	 	var historycounter=0;
		var historypointer=0;
	 * */
	function LoadAjaxScreen(url,obj,isUrl) 
	{
		//alert(ShowIFControl);	
		ShowIFControl();
		if( _siteprefix_=="")
			var href = '';
		else
			var href = 'http://www.infinime.com';
		if( _siteprefix_=="123")
		{
			//alert(parent._start_)
			if(parent._start_==0)
			{
				//alert("setting cookie");
				var op = {"val":_sessionid_};
		    	op = JSON.encode(op);
		    	setCookie(_sessionid_, op); 
		    	test = getCookie(_sessionid_);
		    	if(test=='')
		    	{
		    		alert('Cookies are currently not enabled. Please enable your browser cookies.');
		    		return;
		    	}
		    	parent._start_=1;
			}
			else if(parent._start_==1)
			{
				//alert("getting cookie--"+_sessionid_+"--");
				op1 = getCookie(_sessionid_);
				//alert(op1);
				if(op1=="")
				{
					alert("You are unable to continue, Your IP Address is not authenticated");
					//url = "noauth";
					//location.href=href;
					return;
				}
				else
				{
					op1 = JSON.decode(op1);
				
					if(op1["val"]!=parent._checkwith_)
					{
						//alert(op1["val"]+'====='+parent._checkwith_);
						alert("You are unable to continue, Your IP Address is not authenticated");
						//url = "noauth";					
						//location.href=href;
						return;
					}
				}
			}
		}
		loading =1;
		/*window.location.hash="aa"+Math.round(10000000*Math.random());
		window.location.hash=url;
		var current_hash = window.location.hash;*/
		//alert(document.getElementById('historyFrame').contentWindow.document.body.innerHTML);
		//alert('server'+parent.server);
		//debugger;
		/*
		ignoreHistory=1;
		if(ignoreHistory==0)
		{
			if(location.href.indexOf("http://infinimation.com")!=-1)
				var c = ++historycounter;
			else
				var c = ++parent.historycounter;	
			parent.document.getElementById('MEHistoryFrame').contentWindow.document.body.innerHTML='';
			parent.document.getElementById('MEHistoryFrame').src='http://'+servername+'/history.php?var='+escape(url)+'&counter='+c;
		}
		ignoreHistory=0;*/
		var i = Math.round(10000000*Math.random());
		if(!isUrl)
			url = "index.php?SCREEN=" + url +'&sid='+_sessionid_ ;
		
		url = url + "&rand="+i;
		//url = "main.php?controller=Test&action=showtest&sid=" + _sessionid_ ;
		var args = obj;
		if(args)
		{
			if(!args.onSuccess)
			{
				args.onSuccess = AjaxCallback;
				ShowBlockDiv("");
			}
				
			if(!args.onFailure)
				args.onFailure = AjaxReportError ;
				
			if(!args.onException)
				args.onException = AjaxException;
			
		}
		else
		{
			ShowBlockDiv("");
			args = Object();
			args.method =  'post';
			args.onFailure = AjaxReportError;
			args.onSuccess = AjaxCallback;	
			args.onException = AjaxException;
		}
		if(!args.deleteList)	
		{
				if(typeof(list)=="object" && list.GetItemCount() >0)
				list.DeleteAllItems();	
		}	
		//alert("load"+mylink.length);		
		var link;
		if(typeof(mylink)!="undefined")
			link = mylink;
		else
			link = parent.mylink;			
		

		setCookie("last_sid", _sessionid_); 
		if(typeof(link)!="undefined")
		{
			if(link.length !=0 && link[link.length-1]['url']==url&& link[link.length-1]['args']==args)
	    	{
	    		return false;
	    	}		
	
			if (!args.skipHistory)
			{
				// History work
		    	var op = {"url":url,"args":args};
		    	op = JSON.encode(op);
		    	setCookie("last_ajax_action", op); 
		    	//alert('co:'+getCookie("last_ajax_action"));
				link[link.length] = {"url":url,"args":args};
				parent.tmpindex=link.length-1;
			}
		}
		// Loading div
		if(typeof(srcW) != 'undefined')	
			srcW.ShowWaitDialog();
		//alert(url);
		var w;
		var myAjax ;
//		if(Ajax)
			myAjax = new Ajax.Request( url, args );
//		else if(parent.frames['IFControl'].Ajax)
//			myAjax= parent.frames['IFControl'].Ajax.Request( url, args );
//		else
//			myAjax= parent.parent.frames['IFControl'].Ajax.Request( url, args );

//		alert("End"+mylink.length+"tmpindex"+tmpindex);
	}


	
 
  	function AjaxCallback(response)
 	{
		HideBlockDiv();
		try
		{
			// For backward compatibility option, will remove later when fully on ajax
			/*if (frames['IFControl'] && frames['IFControl'].frames['operationsarea'] && frames['IFControl'].frames['operationsarea'].showDiv)
				frames['IFControl'].frames['operationsarea'].showDiv('ajaxDivContent');
			else if(getIframeID(this) == 'IFControl' && frames['operationsarea'].showDiv)
				frames['operationsarea'].showDiv('ajaxDivContent');
			*/

			if (document.getElementById('projectNav'))
				document.getElementById('projectNav').style.display='none';
			
			if (document.getElementById('documentDivContent'))
				AjaxCallbackWorker(response,'documentDivContent',true);							
			else
				AjaxCallbackWorker(response,'ajaxDivContent');
		}
		catch(e)
		{
			alert('Exp in callbackworker:'+e.description);
		}	
  	}
	function AjaxCallbackWorker(response,divName,popup)
	{
		loading =0;
		//alert('worker');
		//debugger;
		if($('projectNav'))
		{
	 		if($('projectNav').style.display == 'block')
			{
				$('ajaxDivContent').style.height = '95%';
			}
			else
				$('ajaxDivContent').style.height = '100%';
		}	
		
 		if(typeof(srcW) != 'undefined')
 			srcW.HideWaitDialog();
		try
		{
			/*Tariq:used in ibz.sharetaskrights need to open screen in popup wizard and callback will be always document*/
			if(popup==true)
			{
				doc = document;
				var divElement = doc.getElementById(divName);
				parent.srcW.HideWaitDialog();
			}
			else if(typeof(divName) != 'object')
			{
				if(document.getElementById('IFControl'))
				{
					if(_browsername_!='Mozilla')
						doc = document.getElementById('IFControl').contentWindow.document;
					else
						doc = document.getElementById('IFControl').contentDocument;
				}
				else if(parent.document.getElementById('IFControl'))
				{
					if(parent.document.getElementById('IFControl').contentWindow.document)
						doc = parent.document.getElementById('IFControl').contentWindow.document;
					else
						doc = parent.document.getElementById('IFControl').contentDocument;
				}
				else
				{	
					if(document)
						doc = document;
					else
						doc= contentDocument;	
				}
	
				var divElement = doc.getElementById(divName);
			}
			else
			{
				var divElement = divName;
			}	
			doc = divElement.ownerDocument;
			//alert(doc.title);
			// Fix: Calling ajax screen from no ajax screen, opens navigate first and load ajax screen content from cookie of history

			if(divElement == null)
			{
				doc.location.href="/index.php?SCREEN=navigate&sid=" + _sessionid_ ;
			}
			else
				divElement.innerHTML = "";
			

			if(divElement == null)
				return;
			var stags = response.responseText.extractScripts();
			// Fix for external JS files in ajax request
			var matchAll = new RegExp('(?:<script.*src=(.)*?>)((\n|\r|.)*?)(?:<\/script>)', 'img');
			var scripts = response.responseText.match(matchAll);
			if (scripts == null) scripts = [];
			// To avoid duplicate loading
			var scriptFiles = [];
			var sc = doc.getElementsByTagName('script');
			for (var index=0; index<sc.length; index++)
			{
				if (sc[index].src != '')
				{
					
					/*if(sc[index].attributes[0].nodeValue)
					
					scriptFiles[sc[index].src] = 1;
					
					*/
					if(_browsername_=='Mozilla')
						scriptFiles[sc[index].attributes[0].nodeValue] = 1;
					else 				
						scriptFiles[sc[index].src] = 1;
					
				}
			}

			var exScripts = [];
			for (var x=0;x<scripts.length;x++)
			{
				var matchOne = /(?:<script.*src=[' "]?(([^'"])*)['"]? ?.*>)((\n|\r|.)*?)(?:<\/script>)/im;
				var js = scripts[x].match(matchOne)[1];

				// skip if already included
				if (typeof(scriptFiles[js]) != 'undefined')
					continue;

				if(js.substring(js.length-3,js.length) == "gif")
				{
					continue;	
				}	
				var s1 = doc.createElement('SCRIPT');
				//s1.type = 'text/javascript'; 
				s1.setAttribute('type', 'text/javascript');
				s1.src = js
				
//				(s1.src);
//				alert(js);
				exScripts[exScripts.length] = s1;
			//	divElement.getElementsByTagName('head')[0].appendChild(s1);
			//	divElement.appendChild(s1);
			}

			for (var i1=0;i1<exScripts.length;i1++)
			{
				//alert(exScripts[i1]);
				doc.getElementsByTagName('head')[0].appendChild(exScripts[i1]);
				//doc.appendChild(exScripts[i1]);
			}
			
			
			divElement.innerHTML = response.responseText;
//			alert('opening window');
//			var winObj = window.open(response.responseText);
//			winObj.document.write(response.responseText);
			
			for (var i=0;i<stags.length;i++)
			{
				if(stags[i] == "")
					continue;
				
				var s = doc.createElement("SCRIPT");
				s.text = stags[i];
				divElement.appendChild(s);				
			}
			
				
		}
		catch(e)
		{
			
			alert('Exception:'+e.description);
		}
		response = null;
		stags = null;
		scripts = null;	
		/* to stop the movement of servicebar*/
		/*for (i=0;i<doc.links.length;i++)
		{
			doc.links[i].setAttribute("href","javascript:void(null)");
		}
		*/
	}

	function AjaxException(objRequest, ex)
	{
		alert(ex);
	}

	function AjaxReportError(response)
	{
		HideBlockDiv();
		alert("Error:There is some error in completing this request. Please try again later.");
		response = null;
	}

///*********End Ajax Functions *********
//********************************************************

	// Navigation Functions
 	function Back()
	{
		//alert('back index'+tmpindex);
//		debugger;
		var postBack;		
		var urls;
	
		if(parent.mylink.length==undefined||parent.tmpindex==0||parent.mylink.length==0)
		{
			//document.getElementById('prevButton').disabled = true;
			//alert('No Previous Record found');
			return false;
		}
	
		parent.tmpindex--;
		//alert("back data"+mylink[tmpindex]['url']);
		
		postBack=parent.mylink[parent.tmpindex]['args'];
		urls=parent.mylink[parent.tmpindex]['url'];
		
		srcW.ShowWaitDialog();
		//var myAjax = new parent.parent.frames['IFControl'].Ajax.Request( urls, postBack );			
		var myAjax = new Ajax.Request( urls, postBack );			
//		alert(parent.tmpindex);
	}
	
	function Fwd()
	{
		//alert("fwd s"+mylink.length);
		//alert('fedindex'+tmpindex);
		var postFwd;
		var urls2;
		if(parent.mylink.length==0||parent.tmpindex<0||((parent.mylink.length-1)==parent.tmpindex))
		{	
			//alert('No Fwd Record found');
			//document.getElementById('nextButton').disabled = true;
			return false;
		}
		
		parent.tmpindex++;	
		postFwd=parent.mylink[parent.tmpindex]['args'];
		urls2=parent.mylink[parent.tmpindex]['url'];
		
		srcW.ShowWaitDialog();
		//var myAjax = new parent.parent.frames['IFControl'].Ajax.Request( urls2, postFwd );	
		var myAjax = new Ajax.Request( urls2, postFwd );	
	}	
	function ReLoad()
	{
		//alert("Start"+mylink.length);		
		//alert('back index'+tmpindex);
		//debugger;
		var postBack;		
		var urls;
	
		if(parent.mylink.length==undefined||parent.tmpindex==0||parent.mylink.length==0)
		{
			LoadAjaxScreen('showemailaccounts');
			//alert('No Previous Record found');
			return false;
		}
	
		parent.tmpindex;
		//alert("back data"+mylink[tmpindex]['url']);
		
		postBack=parent.mylink[parent.tmpindex]['args'];
		urls=parent.mylink[parent.tmpindex]['url'];
		
		srcW.ShowWaitDialog();
		LoadLastAjaxScreen();
		//var myAjax = new parent.parent.frames['IFControl'].Ajax.Request( urls, postBack );			
//		alert(parent.tmpindex);
	}
	
	// Calendar control date format	
	function validateDate(dateString) 
	{
	    var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
	    if ( (dateString!='') && (dateString.match(RegExPattern)))
	        return true; 
	    
	    return false; 
	}
	
	//Event Notifier
	function EventNotifier(evt,args)
	{
		OnNotification(evt,args);
	}
	function playPhoneRecord(sid,type,id)
	{
		var uid=list.items[0]['uid'];
		
		ShowWindow("/misc/play.php?type="+type+"&uniqueid="+uid+"&sid="+sid+"&recordid="+id,'no',.2,.2);
	}
	function ShowBlockDiv(message)
	{	
		var message = "";
		if (document.getElementById('blockDiv'))
			w=document.getElementById('blockDiv');
		else if(parent.document.getElementById('blockDiv'))
			w=parent.document.getElementById('blockDiv');
		else if(parent.parent.document.getElementById('blockDiv'))
			w=parent.parent.document.getElementById('blockDiv');
		else if(document.getElementById('IFControl').contentWindow.document.getElementById('blockDiv'))
			w = document.getElementById('IFControl').contentWindow.document.getElementById('blockDiv');
		
		if(w)
		{
			w.style.display="";
			/*if(message!='undefined')
				w.innerHTML="<b><span class='disablespantext'>"+message+"</span></b>";
				*/ 
		}
		
	}
	function HideBlockDiv()
	{
		if (frames['IFControl'])
			w=frames['IFControl'];
		else if(parent.frames['IFControl'])
			w=parent.frames['IFControl'];
		else if(parent.parent.frames['IFControl'])
			w=parent.parent.frames['IFControl'];

		if (document.getElementById('blockDiv'))
			w1=document.getElementById('blockDiv');
		else if(parent.document.getElementById('blockDiv'))
			w1=parent.document.getElementById('blockDiv');
		else if(parent.parent.document.getElementById('blockDiv'))
			w1=parent.parent.document.getElementById('blockDiv');
		else if(document.getElementById('IFControl').contentWindow.document.getElementById('blockDiv'))
			w1 = document.getElementById('IFControl').contentWindow.document.getElementById('blockDiv');	
		
		if(w1)
			w1.style.display="none";
	}
	//custom alert
	function alert1(msg,type)
	{
		/*
		 * type undefined or 0 ---- Error
		 * type=1 msg
		 * */
		ShowMsgDiv(msg,'');
		
		if (document.getElementById('btnDivOk'))
			d=document;
		else if(parent.document.getElementById('btnDivOk'))
			d=parent.document;		
		else if(parent.parent.document.getElementById('btnDivOk'))
			parent.parent.document;					

		if(typeof msgType=='undefined' || msgType==0)
			d.getElementById('headermsg').innerHTML="<b>Oops!</b>";
			
		d.getElementById('btnDivCancel').style.display='none';
		d.getElementById('btnDivContinue').style.display='none';
		d.getElementById('btnDivOk').style.display='';
	}
	/*
	 * type=1 --- cancel and continue
	 * type=2---- ok
	 * */
	function ShowBtn(type)
	{
		if (document.getElementById('btnDivOk'))
			d=document;
		else if(parent.document.getElementById('btnDivOk'))
			d=parent.document;		
		else if(parent.parent.document.getElementById('btnDivOk'))
			parent.parent.document;					

		if(typeof msgType=='undefined' || msgType==0)
			d.getElementById('headermsg').innerHTML="<b>Preview!</b>";
			
		if(type==1)
		{
			d.getElementById('btnDivCancel').style.display='';
			d.getElementById('btnDivContinue').style.display='';
			d.getElementById('btnDivOk').style.display='none';
		}
		else if(type==2)
		{
			d.getElementById('btnDivCancel').style.display='none';
			d.getElementById('btnDivContinue').style.display='none';
			d.getElementById('btnDivOk').style.display='';
		}
	}
	function ShowMsgDiv(message,continueClick,isImg)
	{	
		//debugger;
		if (document.getElementById('popupMsgDiv'))
			d=document;
		else if(parent.document.getElementById('popupMsgDiv'))
			d=parent.document;
		else if(parent.parent.document.getElementById('popupMsgDiv'))
			d=parent.parent.document;
		
		
		if(d)
		{
			w=d.getElementById('popupMsgDiv');
			w1=d.getElementById('popupMsgDivMessage');
			b1=d.getElementById('btnDivContinue');
			t1=d.getElementById('popupMsgDivTable');
			t2=d.getElementById('popupMsgDivTable2');
				
			d.getElementById('btnDivCancel').style.display='';
			d.getElementById('btnDivContinue').style.display='';
			d.getElementById('btnDivOk').style.display='none';
	
			if(isImg=='yes')
			{
				ShowBtn(2)
				w.style.display="";
				w.style.height='500px';
				w1.style.height='250px';
				t2.style.paddingTop='310';
			}
			else
			{
				w.style.display="";
				w.style.height='500px';
				w1.style.height='200px';
				t2.style.paddingTop='310';
			}
			
			if(message!='undefined')
			{
				w1.innerHTML=message;
				b1.onclick=function(){eval(continueClick)};
			}
		}
		
	}
	function HideMsgDiv()
	{

		if (frames['IFControl'])
			w=frames['IFControl'];
		else if(parent.frames['IFControl'])
			w=parent.frames['IFControl'];
		else if(parent.parent.frames['IFControl'])
			w=parent.parent.frames['IFControl'];

		//w.document.getElementById('blockDiv').style.display="none";
		
		if (document.getElementById('popupMsgDiv'))
		{
			w1=document.getElementById('popupMsgDiv');
			w2=document.getElementById('popupMsgDivMessage');
		}
		else if(parent.document.getElementById('popupMsgDiv'))
		{
			w1=parent.document.getElementById('popupMsgDiv');
			w2=parent.document.getElementById('popupMsgDivMessage');		
		}
		else if(parent.parent.document.getElementById('popupMsgDiv'))
		{
			w1=parent.parent.document.getElementById('popupMsgDiv');
			w2=parent.parent.document.getElementById('popupMsgDivMessage');			
		}
		
		
		if(w1)
			w1.style.display="none";
		if(w2)
			w2.innerHTML="";


	}
// This code was written by Tyler Akins and has been placed in the
// public domain.  It would be nice if you left this header intact.
// Base64 code from Tyler Akins -- http://rumkin.com

var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

function encode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + 
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);
   
   return output;
}

function decode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   } while (i < input.length);

   return output;
}

function SetScreenOutline(params,height)	// height => factor,to adjust the height of the contentDiv  
{
	var factor = document.getElementById('treeTd').offsetWidth; 
	if(typeof(params)== 'undefined')
		params = '';
		
	if(params != 'InfiniV')// ultimate jugar to adjust the height of newly uploaded page from Infini V
	{
		document.getElementById('contentdiv1').style.height = document.body.clientHeight - 85 + 'px'; 
		// document.getElementById('ajaxDivContent').style.height = document.body.clientHeight - 85 + 'px'; 
	}
	if(typeof(height) != 'undefined')
		document.getElementById('contentdiv1').style.height = document.body.clientHeight - height + 'px';
		
	document.getElementById('ajaxDivContent').style.width = document.body.clientWidth - factor + 'px'; 
	document.getElementById('contentdiv1').style.width = document.body.clientWidth - factor-25 + 'px'; 
}

function customWizCallback(response) // productWizCallBack
{
	if(document.getElementById('wizardDiv'))
		var wizardDiv = document.getElementById('wizardDiv');
	else
	{
		var wizardDiv = document.createElement('div');
		document.getElementById('projectSummaryDivContent').innerHTML = "";
		document.getElementById('projectSummaryDivContent').appendChild(wizardDiv);
		wizardDiv.style.display = 'none';
	}
	if(typeof(wizardDiv) != 'undefined')
	{
		try
		{
			AjaxCallbackWorker(response,wizardDiv);
			wizardDiv.style.display="block";
		}
		catch(e)
		{
			alert("Exception::Function__ customWizCallback1()::"+e);
		}
	}
}
function OpenControl(url,params,isScroll,width,height,wname,closeFlag)
{
	//OpenWizard('/misc/uploadfiles.php?label=<?=$label?>&projectid=<?=$projectid?>&projectpath=<?=$projectpath?>&type=<?=$caller?>','no','0.5','0.45','url','true');
	var obj = OpenWizard(url+'?'+params,isScroll,width,height,wname,closeFlag);
	obj.setCloseCallback(onCloseControlCB);
}
function ShowIFControl()
{
	if(document.getElementById('IFControl'))
		document.getElementById('IFControl').style.display='';
	if(document.getElementById('IFExternal'))
		document.getElementById('IFExternal').style.display='none';

}/*
List of functions in this file

function isDomainName(value)
function isAlphabet(value)
function isUsername(value)
function isRequired(value)
function isWavFile(value)
function isPassword(value)
function isAlphaSpace(value)
function isAlphaNumericSpace(value)
function isAlphaNumeric(value)
function isDigit(value)
function isAmount(value)
function isSpecialPhone(value)
function isEmail(value)
function isValidEmail (value) /// allows . and - in the email address too
function isMultiEmail(value)
function isPhone(value)
function isAscii(value)
*/

function isDomainName(value)
{
//var x = new RegExp("^(http://)?(www\.)?([A-Za-z0-9_]{2,})(\.[A-Za-z]{2,5})+$");
//var x = new RegExp("^[A-Za-z0-9_\-]{3,}([\.]{1,1}[A-Za-z]{2,5})+$");
var x = new RegExp("([A-Za-z0-9_\-]{2,}[\.]{1,1})+([A-Za-z]{2,5})$");
return x.test(value);
}

function isAlphabet(value)
{
var x = new RegExp("^[A-Za-z]+$");
return x.test(value);
}

function isQuickName(value)
{
var x = new RegExp("^[_A-Za-z0-9-]+$");
return x.test(value);
}

function isUsername(value)
{
var x = new RegExp("^[A-Za-z][A-Za-z0-9_]{0,}$");
return x.test(value);
}

function isRequired(value)
{
if (value!="")
	return true;
else
	return false;
/*
var x = new RegExp("^.{1,}$");
return x.test(value);
*/
}

function isWavFile(value)
{
value = value.toLowerCase();
var x = new RegExp("^.{1,}[\.]wav$");
return x.test(value);
}

function isPassword(value)
{
var x = new RegExp("^.{2,}$");
return x.test(value);
}

function isAccountName(value)
{
	var x = new RegExp("^.{2,}@.{2,}$");
	return x.test(value);
}

function isAlphaSpace(value)
{
	if (typeof(value)!="object")
	{	
		var x = new RegExp("^[A-Za-z][A-Za-z ]*$");
		return x.test(value);
	}
	else 
	{
		
	}	
}

function isAlphaNumericSpace(value)
{
	if (typeof(value)!="object")
	{
		var x = new RegExp("^[A-Za-z0-9@][@A-Za-z0-9 \.]*$");
		return x.test(value);
	}
	else
	{
		var x = new RegExp("^[A-Za-z0-9@][@A-Za-z0-9 \.]*$");
		return x.test(value);
	}
}

function isUserName(value)
{
	if (typeof(value)!="object")
	{
		var x = new RegExp("^[A-Za-z0-9][A-Za-z0-9_]*$");
		return x.test(value);
	}
	else
	{
		var x = new RegExp("^[A-Za-z0-9@][@A-Za-z0-9]*$");
		return x.test(value);
	}
}

function isAlphaNumeric(value)
{
var x = new RegExp("^[A-Za-z0-9]{2,}$");
return x.test(value);
}

function isDigit(value)
{
var x = new RegExp("^[0-9]+$");
return x.test(value);
}

function isDecimal(value)
{
var x = new RegExp("^[0-9]+(\.[0-9]+)?$");
return x.test(value);
}

function isAmount(value)
{
var x = new RegExp("^[0-9]+(\.[0-9]{1,5})?$");
return x.test(value);
}

function isSpecialPhone(value)
{
var x = new RegExp("^[0-9]{7,20}$");
return x.test(value);
}

function isEmail(value)
{
//var x = new RegExp("^[A-Za-z][A-Za-z0-9_\.]{1,}@[A-Za-z0-9_\-]{2,5}(\.[A-Za-z]{2,5})+$");
var x = new RegExp("^[A-Za-z][A-Za-z0-9_]{0,}@([A-Za-z0-9_\-]{1,}[\.]{1,1})+([A-Za-z]{2,5})$");
return x.test(value);
}

function isValidEmail ( value )
{
var x = new RegExp("^[A-Za-z0-9][A-Za-z0-9_\.\-]{0,}@([A-Za-z0-9_\-]{1,}[\.]{1,1})+([A-Za-z]{2,5})$");
return x.test(value); // allows . and - in the email address
}

function isValidServer ( value )
{
var x = new RegExp("^[A-Za-z0-9.]{1,}$");
return x.test(value); // allows . and - in the email address
}

function isMultiEmail(value)
{
var x = new RegExp("^([A-Za-z][A-Za-z0-9_\.\-]{0,}@([A-Za-z0-9_\-]{1,}[\.]{1,1})+([A-Za-z]{2,5})([\,]{0,}))+$"); // Multiple Emails
return x.test(value);
}

function isPhone(value)
{
var x = new RegExp("^[+][0-9]{1,3}[(][0-9]{1,3}[)][0-9]{3}-[0-9]{4}$");
return x.test(value);
}

function isAscii(value)
{
var x = new RegExp("^[\x20-\x7E\x0A\x0D]*$");
return x.test(value);
}

// ======================== //
// VAILIDATION FUNCTIONS v2 //
// ======================== //

function isValidNonEmpty(o)
{
	if (!isRequired(o.value))
	{
		//alert("Field '"+o.name+"' must have numbers");
		alert("Value must not be empty");
		o.focus();
		o.className='errorHighlight';
		return false;
	}
	else
	{
		o.className='';
		return true;	
	}
}

function isValidNumber(o)
{
	if (!isDigit(o.value))
	{
		//alert("Field '"+o.name+"' must have numbers");
//		alert("Value must have numbers");
		o.focus();
		o.className='errorHighlight';
		return false;
	}
	else
	{
		o.className='';
		return true;	
	}
}

function isValidAmount(o)
{
	if (!isAmount(o.value))
	{
		//alert("Field '"+o.name+"' must have numbers");
		//alert("Value must be decimal");
		o.focus();
		o.className='errorHighlight';
		return false;
	}
	else
	{
		o.className='';
		return true;	
	}
}

function isValidNonZeroNumber(o)
{
	if (!(o.value>0))
	{
		//alert("Field '"+o.name+"' must be greater than zero");
//		alert("Value must be greater than zero");
		o.focus();
		o.className='errorHighlight';
		return false;
	}
	else
	{
		o.className='';
		return true;	
	}
}

function isValidAlphaNumericSpace(o)
{
	if (!isAlphaNumericSpace(o.value))
	{
		alert("Value must contain Alphabets, Numeric or Spaces");
		o.focus();
		o.className='errorHighlight';
		return false;
	}
	else
	{
		o.className='';
		return true;	
	}
}

function isValidDate(o)
{
	if (!isDate(o.value))
	{
		o.focus();
		o.className='errorHighlight';
		return false;
	}
	else
	{
		o.className='';
		return true;	
	}
}
function isWavFile(value)
{
	var x = new RegExp("^.{1,}[\.]wav$");
	return x.test(value);
}
function opencalc()//its a jugar used in htm pages .. this script is included in all the pages so we can use it
{
        window.open("http://www.infinioffice.com/registration/getprice.php","","width=800,height=550,status=yes, menubar=no, scrollbars=yes,left=75,top=100,resizable=yes");
}

/* FILE HEADER **************************************************
** JS Validate
** Author: Karl Seguin, Timo Haberkern
** Homepage: http://jsval.berlios.de/
** Version: 1.3.3
** Copyright 2003, 2005 Timo Haberkern, Karl Seguin

    This file is part of JS Validate.

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

    JS Validate 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.

    You should have received a copy of the GNU Lesser General Public License
    along with JS Validate; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
**
** END HEADER ***************************************************/

function validateCompleteForm (objForm, strErrorClass) {
    return _validateInternal(objForm, strErrorClass, 0);
};

function validateStandard (objForm, strErrorClass) {
    return _validateInternal(objForm, strErrorClass, 1);
};

/***************************************************************
** Internal functions
*****************************************************************/
function _validateInternal(form, strErrorClass, nErrorThrowType){
   var strErrorMessage = ""; var objFirstError = null;
   if (nErrorThrowType == 0){
    strErrorMessage = (form.err) ? form.err : _getLanguageText("err_form");
   };

   var fields = _GenerateFormFields(form);
   for (var i = 0; i < fields.length; ++i){
      var field = fields[i];
      if (!field.IsValid(fields)){
        field.SetClass(strErrorClass);
        if (nErrorThrowType == 1) {
            _throwError(field);
            return false;
        }else{
            if (objFirstError == null){
               objFirstError = field;
            }
            strErrorMessage = _handleError (field, strErrorMessage);
            bError = true;
        }
      } else {
      	field.ResetClass();
      }
   };
   if (objFirstError != null) {
      alert(strErrorMessage);
      objFirstError.element.focus();
      return false;
  };
  return true;
 };

 function _getLanguageText(id){
    objTextsInternal = new _jsVal_Language();
    objTexts = null;
    try {
        objTexts = new jsVal_Language();
    } catch (ignored){};
    switch (id) {
        case "err_form": strResult = (!objTexts || !objTexts.err_form) ? objTextsInternal.err_form : objTexts.err_form; break;
        case "err_enter": strResult = (!objTexts || !objTexts.err_enter) ? objTextsInternal.err_enter : objTexts.err_enter; break;
        case "err_select": strResult = (!objTexts || !objTexts.err_select) ? objTextsInternal.err_select : objTexts.err_select; break;
    };
    return strResult;
 };

 function _GenerateFormFields(form){
   var arr = new Array();
   for (var i = 0; i < form.length; ++i){
      var element = form.elements[i];
      
      
      var index = _getElementIndex(arr,element);
      //if it doesn't already exist, add it to our array, else merge the change
      if (index == -1){
         arr[arr.length] = new Field(element, form);
      }else{
         arr[index].Merge(element)
      };
   };
   return arr;
};

function _getElementIndex(arr, element){
   if (element.name) {
       var elementName = element.name.toLowerCase();
       for (var i = 0; i < arr.length; ++i){
       	  if (arr[i].element.name) { 
			   if (arr[i].element.name.toLowerCase() == elementName){
               	  return i;
               }
          };
       };
   }
   return -1;
};

/***************************************************************
** Standard translation
*****************************************************************/
function _jsVal_Language() {
    this.err_form = "Please enter/select values for the following fields:\n\n";
    this.err_select = "Please select a valid \"%FIELDNAME%\"";
    this.err_enter = "Please enter a valid \"%FIELDNAME%\"";
};

/***************************************************************
** Field Class
*****************************************************************/
function Field(element, form){
   this.type = element.type;
   this.element = element;
   this.exclude = element.exclude || element.getAttribute('exclude');
   this.err = element.err || element.getAttribute('err');
   this.required = _parseBoolean(element.required || element.getAttribute('required'));
   this.realname = element.realname || element.getAttribute('realname');
   this.elements = new Array();
   
   switch (this.type){
      case "textarea":
      case "password":
      case "text":
      case "file":
         this.value = element.value;
         this.minLength = element.minlength || element.getAttribute('minlength');
         this.maxLength = element.maxlength || element.getAttribute('maxlength');
         this.regexp = this._getRegEx(element);
         this.minValue = element.minvalue || element.getAttribute('minvalue');
         this.maxValue = element.maxvalue || element.getAttribute('maxvalue');
         this.equals = element.equals || element.getAttribute('equals');
         this.callback = element.callback || element.getAttribute('callback');
         break;
      case "select-one":
      case "select-multiple":
         this.values = new Array();
         for (var i = 0; i < element.options.length; ++i){
            if (element.options[i].selected && (!this.exclude || element.options[i].value != this.exclude)){
               this.values[this.values.length] = element.options[i].value;
            }
         }
         this.min = element.min || element.getAttribute('min');
         this.max = element.max || element.getAttribute('max');
         this.equals = element.equals || element.getAttribute('equals');
         break;
      case "checkbox":
         this.min = element.min || element.getAttribute('min');
         this.max = element.max || element.getAttribute('max');
         //no break, let it fall through to radio
      case "radio":
          this.required = _parseBoolean(this.required || element.getAttribute('required'));
          this.values = new Array();
          if (element.checked){
             this.values[0] = element.value;
          }
   		         
          this.elements[0] = element;
          break;
   };
};
Field.prototype.Merge = function(element){
   //never negate a require field
   var required = _parseBoolean(element.getAttribute('required'));
   if (required){
      this.required = true;
   };
   //all other cases (except required) we only add if there isn't already a value (first come first served)
   if (!this.err){
      this.err = element.getAttribute('err');
   };
   if (!this.equals){
   	  this.equals = element.getAttribute('equals');
   };
   if (!this.callback){
   	  this.callback = element.getAttribute('callback');
   };
   if (!this.realname){
      this.realname = element.getAttribute('realname');
   };
   if (!this.max){
      this.max = element.getAttribute('max');
   };
   if (!this.min){
      this.min = element.getAttribute('min');
   };
   if (!this.regexp){
      this.regexp = this._getRegEx(element);
   };
   if (element.checked){
      this.values[this.values.length] = element.value;
   };
   this.elements[this.elements.length] = element;
};
Field.prototype.IsValid = function(arrFields){
   switch (this.type){
      case "textarea":
      case "password":
      case "text":
      case "file":
         return this._ValidateText(arrFields);
      case "select-one":
      case "select-multiple":
      case "radio":
      case "checkbox":
         return this._ValidateGroup(arrFields);
      default:
         return true;
   };
};
Field.prototype.SetClass = function(newClassName){
   if ( (newClassName) && (newClassName != "") ) {
       if ( (this.elements) && (this.elements.length > 0)) {
          for (var i = 0; i < this.elements.length; ++i){
          	  if(this.elements[i].className != newClassName){
                this.elements[i].oldClassName = this.elements[i].className;
                this.elements[i].className = newClassName;
              }
          }
       }else{
       	  if(this.element.className != newClassName){
            this.element.oldClassName = this.element.className;
            this.element.className = newClassName;
          }
       };
   }
};
Field.prototype.ResetClass = function(){
	if ( (this.type != "button") && (this.type != "submit") && (this.type != "reset") ) {
   		if ( (this.elements) && (this.elements.length > 0)) {
      		for (var i = 0; i < this.elements.length; ++i){
      			if(this.elements[i].oldClassName){
         	 	  this.elements[i].className = this.elements[i].oldClassName;
         	 	}
         	 	else {
    	  	 	  this.element.className = "";
    	  		}
      		}
   		}else{
   			if(this.elements.oldClassName){
    	  	  this.element.className = this.element.oldClassName;
    	  	}
    	  	else {
    	  	  this.element.className = "";
    	  	}
   		};
	};
};
Field.prototype._getRegEx = function(element){
   regex = element.regexp || element.getAttribute('regexp')
   if (regex == null) return null;
   retype = typeof(regex);
   if (retype.toUpperCase() == "FUNCTION")
       return regex;
   else if ( (retype.toUpperCase() == "STRING") && !(regex == "JSVAL_RX_EMAIL") && !(regex == "JSVAL_RX_TEL")
   				&& !(regex == "JSVAL_RX_PC") && !(regex == "JSVAL_RX_ZIP") && !(regex == "JSVAL_RX_MONEY") 
				&& !(regex == "JSVAL_RX_CREDITCARD") && !(regex == "JSVAL_RX_POSTALZIP")
				&& !(regex == "RX_USERNAME") && !(regex == "RX_PASSWORD")
				&& !(regex == "RX_ALPHANUMSPACE") && !(regex == "RX_VALIDEMAIL")
				&& !(regex == "RX_SPECIALPHONE") && !(regex == "RX_MULTIEMAIL")
				&& !(regex == "RX_ALPHA") && !(regex == "RX_ALPHA")				
				&& !(regex == "JSVAL_RX_INTERNATIONALNUM") && !(regex == "JSVAL_RX_PHONE_EXT")
				&& !(regex == "JSVAL_RX_REQUIRED") && !(regex == "RX_WAVFILE")
				&& !(regex == "JSVAL_RX_VOIPNUM") && !(regex == "RX_NAME")
				&& !(regex == "JSVAL_RX_USERID")
				
				
		)
   {
       nBegin = 0; nEnd = regex.length-1;
       if (regex.charAt(0) == "/") nBegin=1;
       if (regex.charAt(regex.length-1) == "/") nEnd=regex.length-2;
	   
       return new RegExp(regex.slice(nBegin, nEnd));
   }
   else {
       return regex;
   };
};
Field.prototype._ValidateText = function(arrFields){
   if ( (this.required) && (this.callback) ) {
   	  nCurId = this.element.id ? this.element.id : "";
   	  nCurName = this.element.name ? this.element.name : "";
   	  
   	  eval("bResult = "+this.callback+"('"+nCurId+"', '"+nCurName+"', '"+this.value+"');"); 
   	  if (bResult == false) {
   	  	 return false;
   	  };
   } else {	
	   //required value is empty
	   if (this.required && !this.value){
	      return false;
	   };
	   //value less than minlength
	   if (this.value && (this.minLength && this.value.length < this.minLength)){
	      return false;
	   };
	   //value is more than maxlength
	   if (this.value && (this.maxLength && this.value.length > this.maxLength)){
	      return false;
	   };
	   //value fails regular expression
	   if (this.regexp){
	   	  if (!_checkRegExp(this.regexp, this.value))
	   	  {
	   	  	  //the field isn't required, but there is a value
		      if (!this.required && this.value){
		         return false;
		      }
		      if (this.required){
		         return false;
		      }
	   	  }
	   	  else
	   	  {
	   	  	return true;
	   	  };
	   };
	   
	   
	   
	   //check equality
	   if (this.equals){
	   	   for (var i = 0; i < arrFields.length; ++i){
	       	   var field = arrFields[i];
	       	   if ( (field.element.name == this.equals) || (field.element.id == this.equals) ) {
	       	   	  if (field.element.value != this.value) {
	       	   	  	 return false;
	       	   	  };
	       	   	  break;
	       	   };
	       };
	   };
	   
	   //check against minvalue and maxvalue
	   if (this.required){
	      var fValue = parseFloat(this.value);
	      if ((this.minValue || this.maxValue) && isNaN(fValue)){
	         return false;
	      };
	      if ( (this.minValue) && (fValue < this.minValue) ) {
	         return false;
	      };
	      if ( (this.maxValue) && (fValue > this.maxValue) ) {
	         return false
	      };
	   };
   }
   return true;
};
Field.prototype._ValidateGroup = function(arrFields){
   if (this.required && this.values.length == 0){
      return false;
   };
   if (this.required && this.min && this.min > this.values.length){
      return false;
   };
   if (this.required && this.max && this.max < this.values.length){
      return false;
   };
   return true;
};

function _handleError (field, strErrorMessage) {
   var obj = field.element;
   strNewMessage = strErrorMessage + ( (field.realname)? field.realname : ((obj.id) ? obj.id : obj.name) ) + "\n";
   return strNewMessage;
};

function _throwError(field){
   var obj = field.element;
   switch (field.type){
      case "text":
      case "password":
      case "textarea":
      case "file":
         alert(_getError(field, "err_enter"));
         try {
         	obj.focus();
         }
         catch (ignore) {}
         break;
      case "select-one":
      case "select-multiple":
      case "radio":
      case "checkbox":
         alert(_getError(field, "err_select"));
         break;
      };
};

function _getError(field, str){
   var obj = field.element;
   strErrorTemp = (field.err) ? field.err : _getLanguageText(str);
   
   idx = strErrorTemp.indexOf( "\\n" );
   while ( idx > -1 ) {
   	strErrorTemp = strErrorTemp.replace( "\\n", "\n" );
    idx = strErrorTemp.indexOf( "\\n" );
   };
   
   return strErrorTemp.replace("%FIELDNAME%", (field.realname)? field.realname : ((obj.id) ? obj.id : obj.name));
};

function _parseBoolean(value){
   return !(!value || value == 0 || value == "0" || value == "false");
};

function _checkRegExp(regx, value){
	switch (regx){

	case "JSVAL_RX_EMAIL":
	  //return ((/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,5})+$/).test(value));
	  return ((/^[A-Za-z0-9_\\.\\-]{1,180}@([A-Za-z0-9_\\-]{1,180}[\\.]{1,1}){1,5}([A-Za-z]{2,6})$/).test(value));
	  
	case "JSVAL_RX_TEL":
	  return ((/^1?[\- ]?\(?\d{3}\)?[\- ]?\d{3}[\- ]?\d{4}$/).test(value));
	case "JSVAL_RX_PC":
	  return ((/^[a-z]\d[a-z] ?\d[a-z]\d$/i).test(value));
	case "JSVAL_RX_ZIP":
	  return ((/^\d{5}$/).test(value));
	case "JSVAL_RX_MONEY":
	  return ((/^\d+([\.]\d\d)?$/).test(value));
	case "JSVAL_RX_CREDITCARD":
	  return (!isNaN(value));
	case "JSVAL_RX_POSTALZIP":
	  if(value.length == 6 || value.length == 7)
	    return((/^[a-zA-Z]\d[a-zA-Z] ?\d[a-zA-Z]\d$/).test(value));
	  if(value.length == 5 || value.length == 10)
	    return((/^\d{5}(\-\d{4})?$/).test(value));

	case "RX_NAME":
		return ((/^[A-Za-z]{0,}$/).test(value));
	case "RX_USERNAME":
		return ((/^[A-Za-z][A-Za-z0-9_\.]{0,}$/).test(value));
	case "RX_PASSWORD":
		return ((/^.{2,}$/).test(value));
	case "RX_ALPHANUMSPACE":
		return ((/^[A-Za-z0-9@][@A-Za-z0-9 \.]*$/).test(value));

	case "RX_ALPHA":
		return ((/^[0-9][0-9 \.]*$/).test(value));
	case "RX_ASCII":
		return ((/^[\x20-\x7E\x0A\x0D]*$/).test(value));
	case "RX_PHONE":	
		return ((/^[+][0-9]{1,3}[(][0-9]{1,3}[)][0-9]{3}-[0-9]{4}$/).test(value));
	case "RX_MULTIEMAIL":
		return ((/^([ ]{0,}[A-Za-z][A-Za-z0-9_\.\-]{0,}@([A-Za-z0-9_\-]{1,}\.)+([A-Za-z]{2,5})[ ]{0,}[\,]{0,1})+$/).test(value));
		//return ((/^([A-Za-z][A-Za-z0-9_\.\-]{0,}@([A-Za-z0-9_\-]{1,}[\.]{1,1})+([A-Za-z]{2,5})([\,]{0,}))+$/).test(value));
	case "RX_VALIDSERVER":
		return ((/^[A-Za-z0-9.]{1,}$/).test(value));
	case "RX_VALIDEMAIL":
		return ((/^[A-Za-z][A-Za-z0-9_\.\-]{0,}@([A-Za-z0-9_\-]{1,}[\.]{1,1})+([A-Za-z]{2,5})$/).test(value));
	case "RX_SPECIALPHONE":
		return ((/^[0-9]{7,20}$/).test(value));
	case "JSVAL_RX_REQUIRED":
	  return ((/^\d{1}$/).test(value));
	case "JSVAL_RX_PHONE_EXT":
	  return ((/^[0-9]{1,}$/).test(value));
	case "JSVAL_RX_INTERNATIONALNUM":
		return ((/^00([0-9]{8,30})$/).test(value));
		//return ((/^00[0-9]{6,}$/).test(value));
		//return ((/^[0-9]{6,}$/).test(value));
		break;
	case "RX_WAVFILE":
		return ((/^.{1,}[\.]wav$/).test(value.toLowerCase()));
	case "JSVAL_RX_VOIPNUM":
	  	return ((/^\w+([\.-]?\w+)*@\d{8}$/).test(value));
	case "JSVAL_RX_USERID":
	  	return ((/^\w+([\.-]?\w+)+@\d{8}$/).test(value));
	  	
	default:
	  return (regx.test(value));

	};
};//
// openPopUps v1.01 Copyright (c) 2006 openWebWare.com
// This copyright notice MUST stay intact for use.
//
// The perfect pop up window replacement for your advertisements and web 
// applications. Pop up blockers will fail to prevent an openPopUp window 
// from opening. 
//
// This library is free software; you can redistribute it and/or modify 
// it under the terms of the GNU Lesser General Public License as published 
// by the Free Software Foundation; either version 2.1 of the License, or 
// (at your option) any later version.
//
// This library 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 Lesser General Public 
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License along 
// with this library; if not, write to the Free Software Foundation, Inc., 59 
// Temple Place, Suite 330, Boston, MA 02111-1307 USA 

// CSS Diretory
//cssDir = "styles/";

// Images Directory
imageDir = "/images/misc/";

// Include Style Sheet
//document.write('<link rel="stylesheet" type="text/css" href="' +cssDir+ 'styles.css">\n');
document.write('<style type="text/css">.JSWindowTitleStyle   { font-weight: bold; font-size: 11px; font-family: verdana, arial, helvetica, sans serif; color: #FFFFFF; }.JSWindowContentStyle { font-size: 11px; font-family: verdana, arial, helvetica, sans serif; color: #DBEAF7; padding: 5px;}	</style>');


/* ---------------------------------------------------------------------- *\
  Function    : JSWindow()
  Description : creates a new window
  Usage       : JSWindow("title", oContent, [x], [y], [id], [width])
  Arguments   : title    - The title of the window as displayed in the titlebar
	              oContent - The content of the Div called using getElementbyID
								x        - The number of pixels from the left the window appears when first open
								y        - The number of pixels from the top the window appears when first open
	              id       - The <div> this window will use for its content
                width    - The default width of the window                
\* ---------------------------------------------------------------------- */

function JSWindow(title, oContent, x, y, id, width, height, popupColor, minimizeIcon)
{
	
	// define variables
	this.title = title;
	this.oContent = oContent;
  this.width = width;
  this.height = height;
	this.x = x;
	this.y = y;
  this.id = id;
	this.bgcolor = popupColor;
	
	
	// create the table window and define CSS properties
	this.oTable = document.createElement("table");
  this.oTable.id = "Window " + this.id;
	this.oTable.style.width = this.width + "px";
	this.oTable.style.height = this.height + "px";
	this.oTable.style.border = "2px solid #B0C4DE";
  this.oTable.cellSpacing = 0;
	this.oTable.cellPadding = 2;
	this.oTable.border = 0;
	this.oTable.style.backgroundColor = "#FFFFFF";

	// determine the windows position when first open
	this.oTable.style.position = "absolute";
	this.oTable.style.left = this.x + "px";
	this.oTable.style.top = this.y + "px";

	// link from the table to the JSWindow object
	this.oTable.jsWindow = this;

	// if the table is clicked anywhere, show the table in front of other open windows
	this.oTable.onmousedown = JSWindow.prototype.onBringToFront;

	// append to document body
	document.body.appendChild(this.oTable);

	// add a row for the titlebar
	var oTR = this.oTable.insertRow(0);
	oTR.className = "JSWindowTitleStyle";
	
	
	// Title: add the title to the titlebar	
	oTD = oTR.insertCell(0);
	oTD.innerHTML = title;
	oTD.jsWindow = this;
	oTD.onmousedown = JSWindow.prototype.tdOnMouseDown;
	oTD.style.borderBottom = "1px solid #DBEAF7";
	//oTD.style.borderBottom = "1px solid #000000";
	oTD.style.backgroundImage = "url(" + imageDir + "popup_title_bg.jpg)";
	oTD.height = "20";
	oTD.width = "98%";
	
	// Minimize: add the minimize button to the titlebar
	if (minimizeIcon == 1) {
    this.oMinTD = oTR.insertCell(1);
	  this.oMinTD.innerHTML = "<img src='" + imageDir + "popup_minimize.jpg'>";
	  this.oMinTD.onmousedown = JSWindow.prototype.onMinimize;
	  this.oMinTD.jsWindow = this;
    this.oMinTD.style.borderBottom = "1px solid #DBEAF7";
    //this.oMinTD.style.borderBottom = "1px solid #000000";
	  this.oMinTD.style.backgroundImage = "url(" + imageDir + "popup_title_bg.jpg)";
	  this.oMinTD.width = "1%";
	  this.oMinTD.style.paddingRight = "1px";	
  }
	
	// Close: add the close button to the titlebar
	if (minimizeIcon == 1) {
	  oTD = oTR.insertCell(2);
	}
	else {
	  oTD = oTR.insertCell(1); 
	}
	oTD.innerHTML = "<img src='" + imageDir + "popup_close.jpg'>";
	oTD.jsWindow = this;
	oTD.id = "IoFrame"+this.id+"Close";

	oTD.onclick = JSWindow.prototype.onClose;
	oTD.onmousedown = JSWindow.prototype.onClose;
	oTD.style.borderBottom = "1px solid #DBEAF7";
	//oTD.style.borderBottom = "1px solid #000000";
	oTD.style.backgroundImage = "url(" + imageDir + "popup_title_bg.jpg)";
  	oTD.width = "1%";
	oTD.style.paddingLeft = "1px";
	
	// add a row for the window's content
	oTR = this.oTable.insertRow(1);
	
	this.oContentTD = oTR.insertCell(0);
	this.oContentTD.id = 'contentTd'+this.id;
	if (minimizeIcon == 1) {
	  this.oContentTD.colSpan = 3;
	}
	else {
	  this.oContentTD.colSpan = 2;
	}  
	this.oContentTD.style.backgroundColor = this.bgcolor;
	this.oContentTD.className = "JSWindowContentStyle";
 
 
	// use the content from the referenced div as the content for the window
	this.oContentTD.innerHTML = document.all["IoDiv" + this.id].innerHTML;	
}

JSWindow.prototype.onBringToFront = function()
{
	this.jsWindow.bringToFront();
}

JSWindow.prototype.bringToFront = function()
{
	// if not already the last child of the document.body, make it so
	if (document.body.childNodes[document.body.childNodes.length-1] !== this.oTable )
	{
		// move to bottom of document
		document.body.appendChild(this.oTable);
	}
}

JSWindow.prototype.tdOnMouseDown = function()
{
	this.jsWindow.onMouseDown();
}

JSWindow.prototype.onMouseDown = function()
{
	// record that an onmousedown has just occurred
	this.bDown = true;
	
	// link from body to this JSWindow object
	document.body.jsWindow = this;

	// save body mouse handlers
	this.saveMouseMove = document.body.onmousemove;
	this.saveMouseUp = document.body.onmouseup;

	// set new handlers.
	document.body.onmousemove = JSWindow.prototype.bodyOnMouseMove;
	document.body.onmouseup = JSWindow.prototype.bodyOnMouseUp;
}

JSWindow.prototype.bodyOnMouseMove = function(evt)
{
	var e = window.event ? window.event : evt;
	this.jsWindow.onMouseMove(e);
}

JSWindow.prototype.onMouseMove = function(evt)
{
	// if mouse not down, stop the move (for IE only)
	if ( (document.all) && !(evt.button & 1) )
	{
		this.onMouseUp();
		return;
	}
	if ( this.bDown )
	{
		this.dx = parseInt(this.oTable.style.left, 10) - evt.clientX;
		this.dy = parseInt(this.oTable.style.top, 10) - evt.clientY;
		this.bDown = false;
	}
	else
	{
		this.oTable.style.left = Math.max((this.dx + evt.clientX),0) + "px";
		this.oTable.style.top = Math.max((this.dy + evt.clientY),0) + "px";
	}
}

JSWindow.prototype.bodyOnMouseUp = function()
{
	this.jsWindow.onMouseUp();
}

JSWindow.prototype.onMouseUp = function()
{
	document.body.onmouseup = this.saveMouseUp;
	document.body.onmousemove = this.saveMouseMove;
	document.body.jsWindow = null;
}


JSWindow.prototype.onMinimize = function()
{
  this.jsWindow.minimize();
}



JSWindow.prototype.minimize = function()
{
	// hide the content
	this.oContent.style.visibility = "hidden";
	this.oContent.style.position = "absolute";
	document.body.appendChild(this.oContent);
	
	this.oTable.deleteRow(1);
	
	// save current position
	this.saveX = this.oTable.style.left;
	this.saveY = this.oTable.style.top;
	
  // get the "window bar"
	if ( !window.jsWindowBar )
	{
		window.jsWindowBar = document.createElement("span");
	  document.body.appendChild(window.jsWindowBar);
	}
	
	window.jsWindowBar.appendChild(this.oTable);
	this.oTable.style.position = "static";
	this.oTable.style.left = "0px";
	this.oTable.style.top = "0px";
	
	this.oMinTD.innerHTML = "<img src='" + imageDir + "popup_maximize.jpg'>";
	this.oMinTD.onmousedown = JSWindow.prototype.onMaximize;
	this.oTable.style.width = "220px";
    this.oTable.style.borderBottom = "0px";
	
}


JSWindow.prototype.onMaximize = function()
{
	this.jsWindow.maximize();
}

JSWindow.prototype.maximize = function()
{
	document.body.appendChild(this.oTable);
	this.oTable.style.position = "absolute";
	
	this.oTable.style.left = this.saveX;
	this.oTable.style.top = this.saveY;
	this.oTable.style.width = this.width + "px"
	//this.oTable.style.borderBottom = "1px solid #000000";
	this.oTable.style.borderBottom = "1px solid #DBEAF7";
	
	// add the content again.
	oTR = this.oTable.insertRow(1);
	
  	this.oContentTD = oTR.insertCell(0);
	this.oContentTD.colSpan = 3;
	this.oContentTD.innerHTML = document.all["IoDiv" + this.id].innerHTML;
	
	//oTD.appendChild(this.oContent);
	this.oContent.style.position = "static";
	this.oContent.style.visibility = "visible";
	this.oContentTD.style.backgroundColor = this.bgcolor;
	this.oContentTD.className = "JSWindowContentStyle";
	
  	this.oMinTD.style.paddingRight = "1px";	
	this.oMinTD.innerHTML = "<img src='" + imageDir + "popup_minimize.jpg'>";
	this.oMinTD.onmousedown = JSWindow.prototype.onMinimize;

}

JSWindow.prototype.onMaximize = function()
{
	this.jsWindow.maximize();
}

JSWindow.prototype.close = function()
{	
	// remove from browser document
	this.oTable.parentNode.removeChild(this.oTable);
}

JSWindow.prototype.onClose = function()
{
	this.jsWindow.close();
}



/* ---------------------------------------------------------------------- *\
  Function    : hideDiv()
  Description : Hides all Divs on the page.
  Usage       : hideDiv([divNumber])
  Arguments   : divNumber - The number of Divs in the page that must be hidden
\* ---------------------------------------------------------------------- */

function hideDiv(divNumber) {
	for (var count = 1; count <= divNumber;) {
    document.getElementById('IoDiv' + count).style.display = 'none';
		count++;
	}
}



/* ---------------------------------------------------------------------- *\
  Function    : createWindows()
  Description : determines if Window already exists, else calls JSWindow
  Usage       : createWindows([windowID], [width], "title")
  Arguments   : windowID - The <div> this window will use for its content
                width    - The default width of the window
                title    - The title of the window as displayed in the titlebar
\* ---------------------------------------------------------------------- */

function createWindow(title, width, height, popupColor, windowID, minimizeIcon, x, y)
{
if (document.getElementById('Window ' + windowID)) {
  }
else {
  return new JSWindow("&nbsp;" + title, document.getElementById("IoDiv" + windowID), x, y, windowID, width, height, popupColor, minimizeIcon); 
  }
}



/*-----------------------------------------
				Wrapper
	  Irfan Ashraf Friday 8th Sep, 2006
	  		[Barish Walay Dinn]
-----------------------------------------*/

/*----------------------------------------
Function : CreatePopup
Description : This function create div base popup with iframe
Params
	divId	: int type only
	width	: width for div (may apply for iframe)
	height  : height for div (may apply for iframe)
	bgcolor : background color of div
	xPos    : x position of div
	yPos    : y position of div
	url 	: url for iframe
----------------------------------------*/



function CreatePopup(divId, url, width, height, scroll, xPos, yPos, bgcolor)
{
//	alert("DivId:"+divId+", URL:"+url+", Width:"+width+", Height:"+height+", Scroll:"+scroll+", xPOS:"+xPos+", yPOS:"+yPos+", BgColor:"+bgcolor);
	if (bgcolor == undefined)
	{
		bgcolor = "#FFFFFF";
	}

	if(width == undefined && height == undefined)
	{
		width=.70;
		height=.60;
	}

	if (scroll == undefined)
	{	
		scroll="No";
	}

	var w = screen.width*width;
	var h = screen.height*height;
			
	if (xPos == undefined)
	{
		xPos = (screen.width - w)/2;
	}
	
	if (yPos == undefined)
	{
		yPos = (screen.height - h)/4;
	}

	var createDiv = document.createElement("div");
	createDiv.id = "IoDiv"+divId;
	createDiv.style.display = "none";
	createDiv.width = w + "px";
	createDiv.height = h + "px";
	
	
	var createIframe = document.createElement("iframe");

	createIframe.id = "IoFrame"+divId;
	createIframe.src = url;
	createIframe.frameborder = 0;
	createIframe.scrolling = "No";
	createIframe.width = w + "px";
	createIframe.height = h + "px";

	createDiv.appendChild(createIframe);
	
	document.body.appendChild(createDiv);

	/* -------------------------------------------------
	   Function : CreateWindow
	   1. Window Title
	   2. Window Width
	   3. Window Background Color
	   4. Window ID (this would be the ID in for the window's respective <div>)
	   5. Display Minimize Icon (1 for Yes, 0 for No)
	   6. X (The number of pixels from the left the window appears when first open)
	   7. Y (The number of pixels from the top the window appears when first open)
    --------------------------------------------------*/

	
	return createWindow('', w, h, '#FFFFFF', divId, 0, xPos, yPos);
	//createWindow('', 200, 200, '#FFFFFF', 'sdf', 0,100, 100);
	
	
}

function ClosePopup(o)
{
	window.top.document.getElementById(getIframeID(o)+'Close').click();
}
/*  Prototype JavaScript framework, version 1.5.0
 *  (c) 2005-2007 Sam Stephenson
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://prototype.conio.net/
 *
/*--------------------------------------------------------------------------*/

var Prototype = {
  Version: '1.5.0',
  BrowserFeatures: {
    XPath: !!document.evaluate
  },

  ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',
  emptyFunction: function() {},
  K: function(x) { return x }
}

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

var Abstract = new Object();

Object.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
}

Object.extend(Object, {
  inspect: function(object) {
    try {
      if (object === undefined) return 'undefined';
      if (object === null) return 'null';
      return object.inspect ? object.inspect() : object.toString();
    } catch (e) {
      if (e instanceof RangeError) return '...';
      throw e;
    }
  },

  keys: function(object) {
    var keys = [];
    for (var property in object)
      keys.push(property);
    return keys;
  },

  values: function(object) {
    var values = [];
    for (var property in object)
      values.push(object[property]);
    return values;
  },

  clone: function(object) {
    return Object.extend({}, object);
  }
});

Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
}

Function.prototype.bindAsEventListener = function(object) {
  var __method = this, args = $A(arguments), object = args.shift();
  return function(event) {
    return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments)));
  }
}

Object.extend(Number.prototype, {
  toColorPart: function() {
    var digits = this.toString(16);
    if (this < 16) return '0' + digits;
    return digits;
  },

  succ: function() {
    return this + 1;
  },

  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  }
});

var Try = {
  these: function() {
    var returnValue;

    for (var i = 0, length = arguments.length; i < length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }

    return returnValue;
  }
}

/*--------------------------------------------------------------------------*/

var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.callback(this);
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
}
String.interpret = function(value){
  return value == null ? '' : String(value);
}

Object.extend(String.prototype, {
  gsub: function(pattern, replacement) {
    var result = '', source = this, match;
    replacement = arguments.callee.prepareReplacement(replacement);

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += String.interpret(replacement(match));
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
  },

  sub: function(pattern, replacement, count) {
    replacement = this.gsub.prepareReplacement(replacement);
    count = count === undefined ? 1 : count;

    return this.gsub(pattern, function(match) {
      if (--count < 0) return match[0];
      return replacement(match);
    });
  },

  scan: function(pattern, iterator) {
    this.gsub(pattern, iterator);
    return this;
  },

  truncate: function(length, truncation) {
    length = length || 30;
    truncation = truncation === undefined ? '...' : truncation;
    return this.length > length ?
      this.slice(0, length - truncation.length) + truncation : this;
  },

  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },

  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },

  evalScripts: function() {
    return this.extractScripts().map(function(script) { return eval(script) });
  },

  escapeHTML: function() {
    var div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
  },

  unescapeHTML: function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? (div.childNodes.length > 1 ?
      $A(div.childNodes).inject('',function(memo,node){ return memo+node.nodeValue }) :
      div.childNodes[0].nodeValue) : '';
  },

  toQueryParams: function(separator) {
    var match = this.strip().match(/([^?#]*)(#.*)?$/);
    if (!match) return {};

    return match[1].split(separator || '&').inject({}, function(hash, pair) {
      if ((pair = pair.split('='))[0]) {
        var name = decodeURIComponent(pair[0]);
        var value = pair[1] ? decodeURIComponent(pair[1]) : undefined;

        if (hash[name] !== undefined) {
          if (hash[name].constructor != Array)
            hash[name] = [hash[name]];
          if (value) hash[name].push(value);
        }
        else hash[name] = value;
      }
      return hash;
    });
  },

  toArray: function() {
    return this.split('');
  },

  succ: function() {
    return this.slice(0, this.length - 1) +
      String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  },

  camelize: function() {
    var parts = this.split('-'), len = parts.length;
    if (len == 1) return parts[0];

    var camelized = this.charAt(0) == '-'
      ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
      : parts[0];

    for (var i = 1; i < len; i++)
      camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);

    return camelized;
  },

  capitalize: function(){
    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  },

  underscore: function() {
    return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
  },

  dasherize: function() {
    return this.gsub(/_/,'-');
  },

  inspect: function(useDoubleQuotes) {
    var escapedString = this.replace(/\\/g, '\\\\');
    if (useDoubleQuotes)
      return '"' + escapedString.replace(/"/g, '\\"') + '"';
    else
      return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  }
});

String.prototype.gsub.prepareReplacement = function(replacement) {
  if (typeof replacement == 'function') return replacement;
  var template = new Template(replacement);
  return function(match) { return template.evaluate(match) };
}

String.prototype.parseQuery = String.prototype.toQueryParams;

var Template = Class.create();
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
Template.prototype = {
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern  = pattern || Template.Pattern;
  },

  evaluate: function(object) {
    return this.template.gsub(this.pattern, function(match) {
      var before = match[1];
      if (before == '\\') return match[2];
      return before + String.interpret(object[match[3]]);
    });
  }
}

var $break    = new Object();
var $continue = new Object();

var Enumerable = {
  each: function(iterator) {
    var index = 0;
    try {
      this._each(function(value) {
        try {
          iterator(value, index++);
        } catch (e) {
          if (e != $continue) throw e;
        }
      });
    } catch (e) {
      if (e != $break) throw e;
    }
    return this;
  },

  eachSlice: function(number, iterator) {
    var index = -number, slices = [], array = this.toArray();
    while ((index += number) < array.length)
      slices.push(array.slice(index, index+number));
    return slices.map(iterator);
  },

  all: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      result = result && !!(iterator || Prototype.K)(value, index);
      if (!result) throw $break;
    });
    return result;
  },

  any: function(iterator) {
    var result = false;
    this.each(function(value, index) {
      if (result = !!(iterator || Prototype.K)(value, index))
        throw $break;
    });
    return result;
  },

  collect: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      results.push((iterator || Prototype.K)(value, index));
    });
    return results;
  },

  detect: function(iterator) {
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },

  findAll: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },

  grep: function(pattern, iterator) {
    var results = [];
    this.each(function(value, index) {
      var stringValue = value.toString();
      if (stringValue.match(pattern))
        results.push((iterator || Prototype.K)(value, index));
    })
    return results;
  },

  include: function(object) {
    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },

  inGroupsOf: function(number, fillWith) {
    fillWith = fillWith === undefined ? null : fillWith;
    return this.eachSlice(number, function(slice) {
      while(slice.length < number) slice.push(fillWith);
      return slice;
    });
  },

  inject: function(memo, iterator) {
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },

  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.map(function(value) {
      return value[method].apply(value, args);
    });
  },

  max: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value >= result)
        result = value;
    });
    return result;
  },

  min: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value < result)
        result = value;
    });
    return result;
  },

  partition: function(iterator) {
    var trues = [], falses = [];
    this.each(function(value, index) {
      ((iterator || Prototype.K)(value, index) ?
        trues : falses).push(value);
    });
    return [trues, falses];
  },

  pluck: function(property) {
    var results = [];
    this.each(function(value, index) {
      results.push(value[property]);
    });
    return results;
  },

  reject: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },

  sortBy: function(iterator) {
    return this.map(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },

  toArray: function() {
    return this.map();
  },

  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (typeof args.last() == 'function')
      iterator = args.pop();

    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      return iterator(collections.pluck(index));
    });
  },

  size: function() {
    return this.toArray().length;
  },

  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
  }
}

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0, length = iterable.length; i < length; i++)
      results.push(iterable[i]);
    return results;
  }
}

Object.extend(Array.prototype, Enumerable);

if (!Array.prototype._reverse)
  Array.prototype._reverse = Array.prototype.reverse;

Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0, length = this.length; i < length; i++)
      iterator(this[i]);
  },

  clear: function() {
    this.length = 0;
    return this;
  },

  first: function() {
    return this[0];
  },

  last: function() {
    return this[this.length - 1];
  },

  compact: function() {
    return this.select(function(value) {
      return value != null;
    });
  },

  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(value && value.constructor == Array ?
        value.flatten() : [value]);
    });
  },

  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },

  indexOf: function(object) {
    for (var i = 0, length = this.length; i < length; i++)
      if (this[i] == object) return i;
    return -1;
  },

  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },

  reduce: function() {
    return this.length > 1 ? this : this[0];
  },

  uniq: function() {
    return this.inject([], function(array, value) {
      return array.include(value) ? array : array.concat([value]);
    });
  },

  clone: function() {
    return [].concat(this);
  },

  size: function() {
    return this.length;
  },

  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  }
});

Array.prototype.toArray = Array.prototype.clone;

function $w(string){
  string = string.strip();
  return string ? string.split(/\s+/) : [];
}

if(window.opera){
  Array.prototype.concat = function(){
    var array = [];
    for(var i = 0, length = this.length; i < length; i++) array.push(this[i]);
    for(var i = 0, length = arguments.length; i < length; i++) {
      if(arguments[i].constructor == Array) {
        for(var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
          array.push(arguments[i][j]);
      } else {
        array.push(arguments[i]);
      }
    }
    return array;
  }
}
var Hash = function(obj) {
  Object.extend(this, obj || {});
};

Object.extend(Hash, {
  toQueryString: function(obj) {
    var parts = [];

	  this.prototype._each.call(obj, function(pair) {
      if (!pair.key) return;

      if (pair.value && pair.value.constructor == Array) {
        var values = pair.value.compact();
        if (values.length < 2) pair.value = values.reduce();
        else {
        	key = encodeURIComponent(pair.key);
          values.each(function(value) {
            value = value != undefined ? encodeURIComponent(value) : '';
            parts.push(key + '=' + encodeURIComponent(value));
          });
          return;
        }
      }
      if (pair.value == undefined) pair[1] = '';
      parts.push(pair.map(encodeURIComponent).join('='));
	  });

    return parts.join('&');
  }
});

Object.extend(Hash.prototype, Enumerable);
Object.extend(Hash.prototype, {
  _each: function(iterator) {
    for (var key in this) {
      var value = this[key];
      if (value && value == Hash.prototype[key]) continue;

      var pair = [key, value];
      pair.key = key;
      pair.value = value;
      iterator(pair);
    }
  },

  keys: function() {
    return this.pluck('key');
  },

  values: function() {
    return this.pluck('value');
  },

  merge: function(hash) {
    return $H(hash).inject(this, function(mergedHash, pair) {
      mergedHash[pair.key] = pair.value;
      return mergedHash;
    });
  },

  remove: function() {
    var result;
    for(var i = 0, length = arguments.length; i < length; i++) {
      var value = this[arguments[i]];
      if (value !== undefined){
        if (result === undefined) result = value;
        else {
          if (result.constructor != Array) result = [result];
          result.push(value)
        }
      }
      delete this[arguments[i]];
    }
    return result;
  },

  toQueryString: function() {
    return Hash.toQueryString(this);
  },

  inspect: function() {
    return '#<Hash:{' + this.map(function(pair) {
      return pair.map(Object.inspect).join(': ');
    }).join(', ') + '}>';
  }
});

function $H(object) {
  if (object && object.constructor == Hash) return object;
  return new Hash(object);
};
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
  initialize: function(start, end, exclusive) {
    this.start = start;
    this.end = end;
    this.exclusive = exclusive;
  },

  _each: function(iterator) {
    var value = this.start;
    while (this.include(value)) {
      iterator(value);
      value = value.succ();
    }
  },

  include: function(value) {
    if (value < this.start)
      return false;
    if (this.exclusive)
      return value < this.end;
    return value <= this.end;
  }
});

var $R = function(start, end, exclusive) {
  return new ObjectRange(start, end, exclusive);
}

var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new XMLHttpRequest()},
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')}
    ) || false;
  },

  activeRequestCount: 0
}

Ajax.Responders = {
  responders: [],

  _each: function(iterator) {
    this.responders._each(iterator);
  },

  register: function(responder) {
    if (!this.include(responder))
      this.responders.push(responder);
  },

  unregister: function(responder) {
    this.responders = this.responders.without(responder);
  },

  dispatch: function(callback, request, transport, json) {
    this.each(function(responder) {
      if (typeof responder[callback] == 'function') {
        try {
          responder[callback].apply(responder, [request, transport, json]);
        } catch (e) {}
      }
    });
  }
};

Object.extend(Ajax.Responders, Enumerable);

Ajax.Responders.register({
  onCreate: function() {
    Ajax.activeRequestCount++;
  },
  onComplete: function() {
    Ajax.activeRequestCount--;
  }
});

Ajax.Base = function() {};
Ajax.Base.prototype = {
  setOptions: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      encoding:     'UTF-8',
      parameters:   ''
    }
    Object.extend(this.options, options || {});

    this.options.method = this.options.method.toLowerCase();
    if (typeof this.options.parameters == 'string')
      this.options.parameters = this.options.parameters.toQueryParams();
  }
}

Ajax.Request = Class.create();
Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
  _complete: false,

  initialize: function(url, options) {
    this.transport = Ajax.getTransport();
    this.setOptions(options);
    this.request(url);
  },

  request: function(url) {
    this.url = url;
    this.method = this.options.method;
    var params = this.options.parameters;

    if (!['get', 'post'].include(this.method)) {
      // simulate other verbs over post
      params['_method'] = this.method;
      this.method = 'post';
    }

    params = Hash.toQueryString(params);
    if (params && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) params += '&_='

    // when GET, append parameters to URL
    if (this.method == 'get' && params)
      this.url += (this.url.indexOf('?') > -1 ? '&' : '?') + params;

    try {
      Ajax.Responders.dispatch('onCreate', this, this.transport);

      this.transport.open(this.method.toUpperCase(), this.url,
        this.options.asynchronous);

      if (this.options.asynchronous)
        setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);

      this.transport.onreadystatechange = this.onStateChange.bind(this);
      this.setRequestHeaders();

      var body = this.method == 'post' ? (this.options.postBody || params) : null;

      this.transport.send(body);

      /* Force Firefox to handle ready state 4 for synchronous requests */
      if (!this.options.asynchronous && this.transport.overrideMimeType)
        this.onStateChange();

    }
    catch (e) {
      this.dispatchException(e);
    }
  },

  onStateChange: function() {
    var readyState = this.transport.readyState;
    if (readyState > 1 && !((readyState == 4) && this._complete))
      this.respondToReadyState(this.transport.readyState);
  },

  setRequestHeaders: function() {
    var headers = {
      'X-Requested-With': 'XMLHttpRequest',
      'X-Prototype-Version': Prototype.Version,
      'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
    };

    if (this.method == 'post') {
      headers['Content-type'] = this.options.contentType +
        (this.options.encoding ? '; charset=' + this.options.encoding : '');

      /* Force "Connection: close" for older Mozilla browsers to work
       * around a bug where XMLHttpRequest sends an incorrect
       * Content-length header. See Mozilla Bugzilla #246651.
       */
      if (this.transport.overrideMimeType &&
          (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
            headers['Connection'] = 'close';
    }

    // user-defined headers
    if (typeof this.options.requestHeaders == 'object') {
      var extras = this.options.requestHeaders;

      if (typeof extras.push == 'function')
        for (var i = 0, length = extras.length; i < length; i += 2)
          headers[extras[i]] = extras[i+1];
      else
        $H(extras).each(function(pair) { headers[pair.key] = pair.value });
    }

    for (var name in headers)
      this.transport.setRequestHeader(name, headers[name]);
  },

  success: function() {
    return !this.transport.status
        || (this.transport.status >= 200 && this.transport.status < 300);
  },

  respondToReadyState: function(readyState) {
    var state = Ajax.Request.Events[readyState];
    var transport = this.transport, json = this.evalJSON();

    if (state == 'Complete') {
      try {
        this._complete = true;
        (this.options['on' + this.transport.status]
         || this.options['on' + (this.success() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(transport, json);
      } catch (e) {
        this.dispatchException(e);
      }

      if ((this.getHeader('Content-type') || 'text/javascript').strip().
        match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
          this.evalResponse();
    }

    try {
      (this.options['on' + state] || Prototype.emptyFunction)(transport, json);
      Ajax.Responders.dispatch('on' + state, this, transport, json);
    } catch (e) {
      this.dispatchException(e);
    }

    if (state == 'Complete') {
      // avoid memory leak in MSIE: clean up
      this.transport.onreadystatechange = Prototype.emptyFunction;
    }
  },

  getHeader: function(name) {
    try {
      return this.transport.getResponseHeader(name);
    } catch (e) { return null }
  },

  evalJSON: function() {
    try {
      var json = this.getHeader('X-JSON');
      return json ? eval('(' + json + ')') : null;
    } catch (e) { return null }
  },

  evalResponse: function() {
    try {
      return eval(this.transport.responseText);
    } catch (e) {
      this.dispatchException(e);
    }
  },

  dispatchException: function(exception) {
    (this.options.onException || Prototype.emptyFunction)(this, exception);
    Ajax.Responders.dispatch('onException', this, exception);
  }
});

Ajax.Updater = Class.create();

Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
  initialize: function(container, url, options) {
    this.container = {
      success: (container.success || container),
      failure: (container.failure || (container.success ? null : container))
    }

    this.transport = Ajax.getTransport();
    this.setOptions(options);

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    this.options.onComplete = (function(transport, param) {
      this.updateContent();
      onComplete(transport, param);
    }).bind(this);

    this.request(url);
  },

  updateContent: function() {
    var receiver = this.container[this.success() ? 'success' : 'failure'];
    var response = this.transport.responseText;

    if (!this.options.evalScripts) response = response.stripScripts();

    if (receiver = $(receiver)) {
      if (this.options.insertion)
        new this.options.insertion(receiver, response);
      else
        receiver.update(response);
    }

    if (this.success()) {
      if (this.onComplete)
        setTimeout(this.onComplete.bind(this), 10);
    }
  }
});

Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(container, url, options) {
    this.setOptions(options);
    this.onComplete = this.options.onComplete;

    this.frequency = (this.options.frequency || 2);
    this.decay = (this.options.decay || 1);

    this.updater = {};
    this.container = container;
    this.url = url;

    this.start();
  },

  start: function() {
    this.options.onComplete = this.updateComplete.bind(this);
    this.onTimerEvent();
  },

  stop: function() {
    this.updater.options.onComplete = undefined;
    clearTimeout(this.timer);
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },

  updateComplete: function(request) {
    if (this.options.decay) {
      this.decay = (request.responseText == this.lastText ?
        this.decay * this.options.decay : 1);

      this.lastText = request.responseText;
    }
    this.timer = setTimeout(this.onTimerEvent.bind(this),
      this.decay * this.frequency * 1000);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});
function $(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (typeof element == 'string')
    element = document.getElementById(element);
  return Element.extend(element);
}

if (Prototype.BrowserFeatures.XPath) {
  document._getElementsByXPath = function(expression, parentElement) {
    var results = [];
    var query = document.evaluate(expression, $(parentElement) || document,
      null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    for (var i = 0, length = query.snapshotLength; i < length; i++)
      results.push(query.snapshotItem(i));
    return results;
  };
}

document.getElementsByClassName = function(className, parentElement) {
  if (Prototype.BrowserFeatures.XPath) {
    var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
    return document._getElementsByXPath(q, parentElement);
  } else {
    var children = ($(parentElement) || document.body).getElementsByTagName('*');
    var elements = [], child;
    for (var i = 0, length = children.length; i < length; i++) {
      child = children[i];
      if (Element.hasClassName(child, className))
        elements.push(Element.extend(child));
    }
    return elements;
  }
};

/*--------------------------------------------------------------------------*/

if (!window.Element)
  var Element = new Object();

Element.extend = function(element) {
  if (!element || _nativeExtensions || element.nodeType == 3) return element;

  if (!element._extended && element.tagName && element != window) {
    var methods = Object.clone(Element.Methods), cache = Element.extend.cache;

    if (element.tagName == 'FORM')
      Object.extend(methods, Form.Methods);
    if (['INPUT', 'TEXTAREA', 'SELECT'].include(element.tagName))
      Object.extend(methods, Form.Element.Methods);

    Object.extend(methods, Element.Methods.Simulated);

    for (var property in methods) {
      var value = methods[property];
      if (typeof value == 'function' && !(property in element))
        element[property] = cache.findOrStore(value);
    }
  }

  element._extended = true;
  return element;
};

Element.extend.cache = {
  findOrStore: function(value) {
    return this[value] = this[value] || function() {
      return value.apply(null, [this].concat($A(arguments)));
    }
  }
};

Element.Methods = {
  visible: function(element) {
    return $(element).style.display != 'none';
  },

  toggle: function(element) {
    element = $(element);
    Element[Element.visible(element) ? 'hide' : 'show'](element);
    return element;
  },

  hide: function(element) {
    $(element).style.display = 'none';
    return element;
  },

  show: function(element) {
    $(element).style.display = '';
    return element;
  },

  remove: function(element) {
    element = $(element);
    element.parentNode.removeChild(element);
    return element;
  },

  update: function(element, html) {
    html = typeof html == 'undefined' ? '' : html.toString();
    $(element).innerHTML = html.stripScripts();
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  },

  replace: function(element, html) {
    element = $(element);
    html = typeof html == 'undefined' ? '' : html.toString();
    if (element.outerHTML) {
      element.outerHTML = html.stripScripts();
    } else {
      var range = element.ownerDocument.createRange();
      range.selectNodeContents(element);
      element.parentNode.replaceChild(
        range.createContextualFragment(html.stripScripts()), element);
    }
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  },

  inspect: function(element) {
    element = $(element);
    var result = '<' + element.tagName.toLowerCase();
    $H({'id': 'id', 'className': 'class'}).each(function(pair) {
      var property = pair.first(), attribute = pair.last();
      var value = (element[property] || '').toString();
      if (value) result += ' ' + attribute + '=' + value.inspect(true);
    });
    return result + '>';
  },

  recursivelyCollect: function(element, property) {
    element = $(element);
    var elements = [];
    while (element = element[property])
      if (element.nodeType == 1)
        elements.push(Element.extend(element));
    return elements;
  },

  ancestors: function(element) {
    return $(element).recursivelyCollect('parentNode');
  },

  descendants: function(element) {
    return $A($(element).getElementsByTagName('*'));
  },

  immediateDescendants: function(element) {
    if (!(element = $(element).firstChild)) return [];
    while (element && element.nodeType != 1) element = element.nextSibling;
    if (element) return [element].concat($(element).nextSiblings());
    return [];
  },

  previousSiblings: function(element) {
    return $(element).recursivelyCollect('previousSibling');
  },

  nextSiblings: function(element) {
    return $(element).recursivelyCollect('nextSibling');
  },

  siblings: function(element) {
    element = $(element);
    return element.previousSiblings().reverse().concat(element.nextSiblings());
  },

  match: function(element, selector) {
    if (typeof selector == 'string')
      selector = new Selector(selector);
    return selector.match($(element));
  },

  up: function(element, expression, index) {
    return Selector.findElement($(element).ancestors(), expression, index);
  },

  down: function(element, expression, index) {
    return Selector.findElement($(element).descendants(), expression, index);
  },

  previous: function(element, expression, index) {
    return Selector.findElement($(element).previousSiblings(), expression, index);
  },

  next: function(element, expression, index) {
    return Selector.findElement($(element).nextSiblings(), expression, index);
  },

  getElementsBySelector: function() {
    var args = $A(arguments), element = $(args.shift());
    return Selector.findChildElements(element, args);
  },

  getElementsByClassName: function(element, className) {
    return document.getElementsByClassName(className, element);
  },

  readAttribute: function(element, name) {
    element = $(element);
    if (document.all && !window.opera) {
      var t = Element._attributeTranslations;
      if (t.values[name]) return t.values[name](element, name);
      if (t.names[name])  name = t.names[name];
      var attribute = element.attributes[name];
      if(attribute) return attribute.nodeValue;
    }
    return element.getAttribute(name);
  },

  getHeight: function(element) {
    return $(element).getDimensions().height;
  },

  getWidth: function(element) {
    return $(element).getDimensions().width;
  },

  classNames: function(element) {
    return new Element.ClassNames(element);
  },

  hasClassName: function(element, className) {
    if (!(element = $(element))) return;
    var elementClassName = element.className;
    if (elementClassName.length == 0) return false;
    if (elementClassName == className ||
        elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
      return true;
    return false;
  },

  addClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element).add(className);
    return element;
  },

  removeClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element).remove(className);
    return element;
  },

  toggleClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element)[element.hasClassName(className) ? 'remove' : 'add'](className);
    return element;
  },

  observe: function() {
    Event.observe.apply(Event, arguments);
    return $A(arguments).first();
  },

  stopObserving: function() {
    Event.stopObserving.apply(Event, arguments);
    return $A(arguments).first();
  },

  // removes whitespace-only text node children
  cleanWhitespace: function(element) {
    element = $(element);
    var node = element.firstChild;
    while (node) {
      var nextNode = node.nextSibling;
      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
        element.removeChild(node);
      node = nextNode;
    }
    return element;
  },

  empty: function(element) {
    return $(element).innerHTML.match(/^\s*$/);
  },

  descendantOf: function(element, ancestor) {
    element = $(element), ancestor = $(ancestor);
    while (element = element.parentNode)
      if (element == ancestor) return true;
    return false;
  },

  scrollTo: function(element) {
    element = $(element);
    var pos = Position.cumulativeOffset(element);
    window.scrollTo(pos[0], pos[1]);
    return element;
  },

  getStyle: function(element, style) {
    element = $(element);
    if (['float','cssFloat'].include(style))
      style = (typeof element.style.styleFloat != 'undefined' ? 'styleFloat' : 'cssFloat');
    style = style.camelize();
    var value = element.style[style];
    if (!value) {
      if (document.defaultView && document.defaultView.getComputedStyle) {
        var css = document.defaultView.getComputedStyle(element, null);
        value = css ? css[style] : null;
      } else if (element.currentStyle) {
        value = element.currentStyle[style];
      }
    }

    if((value == 'auto') && ['width','height'].include(style) && (element.getStyle('display') != 'none'))
      value = element['offset'+style.capitalize()] + 'px';

    if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
      if (Element.getStyle(element, 'position') == 'static') value = 'auto';
    if(style == 'opacity') {
      if(value) return parseFloat(value);
      if(value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
        if(value[1]) return parseFloat(value[1]) / 100;
      return 1.0;
    }
    return value == 'auto' ? null : value;
  },

  setStyle: function(element, style) {
    element = $(element);
    for (var name in style) {
      var value = style[name];
      if(name == 'opacity') {
        if (value == 1) {
          value = (/Gecko/.test(navigator.userAgent) &&
            !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 0.999999 : 1.0;
          if(/MSIE/.test(navigator.userAgent) && !window.opera)
            element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
        } else if(value == '') {
          if(/MSIE/.test(navigator.userAgent) && !window.opera)
            element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
        } else {
          if(value < 0.00001) value = 0;
          if(/MSIE/.test(navigator.userAgent) && !window.opera)
            element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'') +
              'alpha(opacity='+value*100+')';
        }
      } else if(['float','cssFloat'].include(name)) name = (typeof element.style.styleFloat != 'undefined') ? 'styleFloat' : 'cssFloat';
      element.style[name.camelize()] = value;
    }
    return element;
  },

  getDimensions: function(element) {
    element = $(element);
    var display = $(element).getStyle('display');
    if (display != 'none' && display != null) // Safari bug
      return {width: element.offsetWidth, height: element.offsetHeight};

    // All *Width and *Height properties give 0 on elements with display none,
    // so enable the element temporarily
    var els = element.style;
    var originalVisibility = els.visibility;
    var originalPosition = els.position;
    var originalDisplay = els.display;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = 'block';
    var originalWidth = element.clientWidth;
    var originalHeight = element.clientHeight;
    els.display = originalDisplay;
    els.position = originalPosition;
    els.visibility = originalVisibility;
    return {width: originalWidth, height: originalHeight};
  },

  makePositioned: function(element) {
    element = $(element);
    var pos = Element.getStyle(element, 'position');
    if (pos == 'static' || !pos) {
      element._madePositioned = true;
      element.style.position = 'relative';
      // Opera returns the offset relative to the positioning context, when an
      // element is position relative but top and left have not been defined
      if (window.opera) {
        element.style.top = 0;
        element.style.left = 0;
      }
    }
    return element;
  },

  undoPositioned: function(element) {
    element = $(element);
    if (element._madePositioned) {
      element._madePositioned = undefined;
      element.style.position =
        element.style.top =
        element.style.left =
        element.style.bottom =
        element.style.right = '';
    }
    return element;
  },

  makeClipping: function(element) {
    element = $(element);
    if (element._overflow) return element;
    element._overflow = element.style.overflow || 'auto';
    if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
      element.style.overflow = 'hidden';
    return element;
  },

  undoClipping: function(element) {
    element = $(element);
    if (!element._overflow) return element;
    element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
    element._overflow = null;
    return element;
  }
};

Object.extend(Element.Methods, {childOf: Element.Methods.descendantOf});

Element._attributeTranslations = {};

Element._attributeTranslations.names = {
  colspan:   "colSpan",
  rowspan:   "rowSpan",
  valign:    "vAlign",
  datetime:  "dateTime",
  accesskey: "accessKey",
  tabindex:  "tabIndex",
  enctype:   "encType",
  maxlength: "maxLength",
  readonly:  "readOnly",
  longdesc:  "longDesc"
};

Element._attributeTranslations.values = {
  _getAttr: function(element, attribute) {
    return element.getAttribute(attribute, 2);
  },

  _flag: function(element, attribute) {
    return $(element).hasAttribute(attribute) ? attribute : null;
  },

  style: function(element) {
    return element.style.cssText.toLowerCase();
  },

  title: function(element) {
    var node = element.getAttributeNode('title');
    return node.specified ? node.nodeValue : null;
  }
};

Object.extend(Element._attributeTranslations.values, {
  href: Element._attributeTranslations.values._getAttr,
  src:  Element._attributeTranslations.values._getAttr,
  disabled: Element._attributeTranslations.values._flag,
  checked:  Element._attributeTranslations.values._flag,
  readonly: Element._attributeTranslations.values._flag,
  multiple: Element._attributeTranslations.values._flag
});

Element.Methods.Simulated = {
  hasAttribute: function(element, attribute) {
    var t = Element._attributeTranslations;
    attribute = t.names[attribute] || attribute;
    return $(element).getAttributeNode(attribute).specified;
  }
};

// IE is missing .innerHTML support for TABLE-related elements
if (document.all && !window.opera){
  Element.Methods.update = function(element, html) {
    element = $(element);
    html = typeof html == 'undefined' ? '' : html.toString();
    var tagName = element.tagName.toUpperCase();
    if (['THEAD','TBODY','TR','TD'].include(tagName)) {
      var div = document.createElement('div');
      switch (tagName) {
        case 'THEAD':
        case 'TBODY':
          div.innerHTML = '<table><tbody>' +  html.stripScripts() + '</tbody></table>';
          depth = 2;
          break;
        case 'TR':
          div.innerHTML = '<table><tbody><tr>' +  html.stripScripts() + '</tr></tbody></table>';
          depth = 3;
          break;
        case 'TD':
          div.innerHTML = '<table><tbody><tr><td>' +  html.stripScripts() + '</td></tr></tbody></table>';
          depth = 4;
      }
      $A(element.childNodes).each(function(node){
        element.removeChild(node)
      });
      depth.times(function(){ div = div.firstChild });

      $A(div.childNodes).each(
        function(node){ element.appendChild(node) });
    } else {
      element.innerHTML = html.stripScripts();
    }
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  }
};

Object.extend(Element, Element.Methods);

var _nativeExtensions = false;

if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))
  ['', 'Form', 'Input', 'TextArea', 'Select'].each(function(tag) {
    var className = 'HTML' + tag + 'Element';
    if(window[className]) return;
    var klass = window[className] = {};
    klass.prototype = document.createElement(tag ? tag.toLowerCase() : 'div').__proto__;
  });

Element.addMethods = function(methods) {
  Object.extend(Element.Methods, methods || {});

  function copy(methods, destination, onlyIfAbsent) {
    onlyIfAbsent = onlyIfAbsent || false;
    var cache = Element.extend.cache;
    for (var property in methods) {
      var value = methods[property];
      if (!onlyIfAbsent || !(property in destination))
        destination[property] = cache.findOrStore(value);
    }
  }

  if (typeof HTMLElement != 'undefined') {
    copy(Element.Methods, HTMLElement.prototype);
    copy(Element.Methods.Simulated, HTMLElement.prototype, true);
    copy(Form.Methods, HTMLFormElement.prototype);
    [HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement].each(function(klass) {
      copy(Form.Element.Methods, klass.prototype);
    });
    _nativeExtensions = true;
  }
}

var Toggle = new Object();
Toggle.display = Element.toggle;

/*--------------------------------------------------------------------------*/

Abstract.Insertion = function(adjacency) {
  this.adjacency = adjacency;
}

Abstract.Insertion.prototype = {
  initialize: function(element, content) {
    this.element = $(element);
    this.content = content.stripScripts();

    if (this.adjacency && this.element.insertAdjacentHTML) {
      try {
        this.element.insertAdjacentHTML(this.adjacency, this.content);
      } catch (e) {
        var tagName = this.element.tagName.toUpperCase();
        if (['TBODY', 'TR'].include(tagName)) {
          this.insertContent(this.contentFromAnonymousTable());
        } else {
          throw e;
        }
      }
    } else {
      this.range = this.element.ownerDocument.createRange();
      if (this.initializeRange) this.initializeRange();
      this.insertContent([this.range.createContextualFragment(this.content)]);
    }

    setTimeout(function() {content.evalScripts()}, 10);
  },

  contentFromAnonymousTable: function() {
    var div = document.createElement('div');
    div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
    return $A(div.childNodes[0].childNodes[0].childNodes);
  }
}

var Insertion = new Object();

Insertion.Before = Class.create();
Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
  initializeRange: function() {
    this.range.setStartBefore(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment, this.element);
    }).bind(this));
  }
});

Insertion.Top = Class.create();
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(true);
  },

  insertContent: function(fragments) {
    fragments.reverse(false).each((function(fragment) {
      this.element.insertBefore(fragment, this.element.firstChild);
    }).bind(this));
  }
});

Insertion.Bottom = Class.create();
Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.appendChild(fragment);
    }).bind(this));
  }
});

Insertion.After = Class.create();
Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
  initializeRange: function() {
    this.range.setStartAfter(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment,
        this.element.nextSibling);
    }).bind(this));
  }
});

/*--------------------------------------------------------------------------*/

Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
  initialize: function(element) {
    this.element = $(element);
  },

  _each: function(iterator) {
    this.element.className.split(/\s+/).select(function(name) {
      return name.length > 0;
    })._each(iterator);
  },

  set: function(className) {
    this.element.className = className;
  },

  add: function(classNameToAdd) {
    if (this.include(classNameToAdd)) return;
    this.set($A(this).concat(classNameToAdd).join(' '));
  },

  remove: function(classNameToRemove) {
    if (!this.include(classNameToRemove)) return;
    this.set($A(this).without(classNameToRemove).join(' '));
  },

  toString: function() {
    return $A(this).join(' ');
  }
};

Object.extend(Element.ClassNames.prototype, Enumerable);
var Selector = Class.create();
Selector.prototype = {
  initialize: function(expression) {
    this.params = {classNames: []};
    this.expression = expression.toString().strip();
    this.parseExpression();
    this.compileMatcher();
  },

  parseExpression: function() {
    function abort(message) { throw 'Parse error in selector: ' + message; }

    if (this.expression == '')  abort('empty expression');

    var params = this.params, expr = this.expression, match, modifier, clause, rest;
    while (match = expr.match(/^(.*)\[([a-z0-9_:-]+?)(?:([~\|!]?=)(?:"([^"]*)"|([^\]\s]*)))?\]$/i)) {
      params.attributes = params.attributes || [];
      params.attributes.push({name: match[2], operator: match[3], value: match[4] || match[5] || ''});
      expr = match[1];
    }

    if (expr == '*') return this.params.wildcard = true;

    while (match = expr.match(/^([^a-z0-9_-])?([a-z0-9_-]+)(.*)/i)) {
      modifier = match[1], clause = match[2], rest = match[3];
      switch (modifier) {
        case '#':       params.id = clause; break;
        case '.':       params.classNames.push(clause); break;
        case '':
        case undefined: params.tagName = clause.toUpperCase(); break;
        default:        abort(expr.inspect());
      }
      expr = rest;
    }

    if (expr.length > 0) abort(expr.inspect());
  },

  buildMatchExpression: function() {
    var params = this.params, conditions = [], clause;

    if (params.wildcard)
      conditions.push('true');
    if (clause = params.id)
      conditions.push('element.readAttribute("id") == ' + clause.inspect());
    if (clause = params.tagName)
      conditions.push('element.tagName.toUpperCase() == ' + clause.inspect());
    if ((clause = params.classNames).length > 0)
      for (var i = 0, length = clause.length; i < length; i++)
        conditions.push('element.hasClassName(' + clause[i].inspect() + ')');
    if (clause = params.attributes) {
      clause.each(function(attribute) {
        var value = 'element.readAttribute(' + attribute.name.inspect() + ')';
        var splitValueBy = function(delimiter) {
          return value + ' && ' + value + '.split(' + delimiter.inspect() + ')';
        }

        switch (attribute.operator) {
          case '=':       conditions.push(value + ' == ' + attribute.value.inspect()); break;
          case '~=':      conditions.push(splitValueBy(' ') + '.include(' + attribute.value.inspect() + ')'); break;
          case '|=':      conditions.push(
                            splitValueBy('-') + '.first().toUpperCase() == ' + attribute.value.toUpperCase().inspect()
                          ); break;
          case '!=':      conditions.push(value + ' != ' + attribute.value.inspect()); break;
          case '':
          case undefined: conditions.push('element.hasAttribute(' + attribute.name.inspect() + ')'); break;
          default:        throw 'Unknown operator ' + attribute.operator + ' in selector';
        }
      });
    }

    return conditions.join(' && ');
  },

  compileMatcher: function() {
    this.match = new Function('element', 'if (!element.tagName) return false; \
      element = $(element); \
      return ' + this.buildMatchExpression());
  },

  findElements: function(scope) {
    var element;

    if (element = $(this.params.id))
      if (this.match(element))
        if (!scope || Element.childOf(element, scope))
          return [element];

    scope = (scope || document).getElementsByTagName(this.params.tagName || '*');

    var results = [];
    for (var i = 0, length = scope.length; i < length; i++)
      if (this.match(element = scope[i]))
        results.push(Element.extend(element));

    return results;
  },

  toString: function() {
    return this.expression;
  }
}

Object.extend(Selector, {
  matchElements: function(elements, expression) {
    var selector = new Selector(expression);
    return elements.select(selector.match.bind(selector)).map(Element.extend);
  },

  findElement: function(elements, expression, index) {
    if (typeof expression == 'number') index = expression, expression = false;
    return Selector.matchElements(elements, expression || '*')[index || 0];
  },

  findChildElements: function(element, expressions) {
    return expressions.map(function(expression) {
      return expression.match(/[^\s"]+(?:"[^"]*"[^\s"]+)*/g).inject([null], function(results, expr) {
        var selector = new Selector(expr);
        return results.inject([], function(elements, result) {
          return elements.concat(selector.findElements(result || element));
        });
      });
    }).flatten();
  }
});

function $$() {
  return Selector.findChildElements(document, $A(arguments));
}
var Form = {
  reset: function(form) {
    $(form).reset();
    return form;
  },

  serializeElements: function(elements, getHash) {
    var data = elements.inject({}, function(result, element) {
      if (!element.disabled && element.name) {
        var key = element.name, value = $(element).getValue();
        if (value != undefined) {
          if (result[key]) {
            if (result[key].constructor != Array) result[key] = [result[key]];
            result[key].push(value);
          }
          else result[key] = value;
        }
      }
      return result;
    });

    return getHash ? data : Hash.toQueryString(data);
  }
};

Form.Methods = {
  serialize: function(form, getHash) {
    return Form.serializeElements(Form.getElements(form), getHash);
  },

  getElements: function(form) {
    return $A($(form).getElementsByTagName('*')).inject([],
      function(elements, child) {
        if (Form.Element.Serializers[child.tagName.toLowerCase()])
          elements.push(Element.extend(child));
        return elements;
      }
    );
  },

  getInputs: function(form, typeName, name) {
    form = $(form);
    var inputs = form.getElementsByTagName('input');

    if (!typeName && !name) return $A(inputs).map(Element.extend);

    for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
      var input = inputs[i];
      if ((typeName && input.type != typeName) || (name && input.name != name))
        continue;
      matchingInputs.push(Element.extend(input));
    }

    return matchingInputs;
  },

  disable: function(form) {
    form = $(form);
    form.getElements().each(function(element) {
      element.blur();
      element.disabled = 'true';
    });
    return form;
  },

  enable: function(form) {
    form = $(form);
    form.getElements().each(function(element) {
      element.disabled = '';
    });
    return form;
  },

  findFirstElement: function(form) {
    return $(form).getElements().find(function(element) {
      return element.type != 'hidden' && !element.disabled &&
        ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
    });
  },

  focusFirstElement: function(form) {
    form = $(form);
    form.findFirstElement().activate();
    return form;
  }
}

Object.extend(Form, Form.Methods);

/*--------------------------------------------------------------------------*/

Form.Element = {
  focus: function(element) {
    $(element).focus();
    return element;
  },

  select: function(element) {
    $(element).select();
    return element;
  }
}

Form.Element.Methods = {
  serialize: function(element) {
    element = $(element);
    if (!element.disabled && element.name) {
      var value = element.getValue();
      if (value != undefined) {
        var pair = {};
        pair[element.name] = value;
        return Hash.toQueryString(pair);
      }
    }
    return '';
  },

  getValue: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    return Form.Element.Serializers[method](element);
  },

  clear: function(element) {
    $(element).value = '';
    return element;
  },

  present: function(element) {
    return $(element).value != '';
  },

  activate: function(element) {
    element = $(element);
    element.focus();
    if (element.select && ( element.tagName.toLowerCase() != 'input' ||
      !['button', 'reset', 'submit'].include(element.type) ) )
      element.select();
    return element;
  },

  disable: function(element) {
    element = $(element);
    element.disabled = true;
    return element;
  },

  enable: function(element) {
    element = $(element);
    element.blur();
    element.disabled = false;
    return element;
  }
}

Object.extend(Form.Element, Form.Element.Methods);
//var Field = Form.Element;
var $F = Form.Element.getValue;

/*--------------------------------------------------------------------------*/

Form.Element.Serializers = {
  input: function(element) {
    switch (element.type.toLowerCase()) {
      case 'checkbox':
      case 'radio':
        return Form.Element.Serializers.inputSelector(element);
      default:
        return Form.Element.Serializers.textarea(element);
    }
  },

  inputSelector: function(element) {
    return element.checked ? element.value : null;
  },

  textarea: function(element) {
    return element.value;
  },

  select: function(element) {
    return this[element.type == 'select-one' ?
      'selectOne' : 'selectMany'](element);
  },

  selectOne: function(element) {
    var index = element.selectedIndex;
    return index >= 0 ? this.optionValue(element.options[index]) : null;
  },

  selectMany: function(element) {
    var values, length = element.length;
    if (!length) return null;

    for (var i = 0, values = []; i < length; i++) {
      var opt = element.options[i];
      if (opt.selected) values.push(this.optionValue(opt));
    }
    return values;
  },

  optionValue: function(opt) {
    // extend element because hasAttribute may not be native
    return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
  }
}

/*--------------------------------------------------------------------------*/

Abstract.TimedObserver = function() {}
Abstract.TimedObserver.prototype = {
  initialize: function(element, frequency, callback) {
    this.frequency = frequency;
    this.element   = $(element);
    this.callback  = callback;

    this.lastValue = this.getValue();
    this.registerCallback();
  },

  registerCallback: function() {
    setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  onTimerEvent: function() {
    var value = this.getValue();
    var changed = ('string' == typeof this.lastValue && 'string' == typeof value
      ? this.lastValue != value : String(this.lastValue) != String(value));
    if (changed) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  }
}

Form.Element.Observer = Class.create();
Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.Observer = Class.create();
Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});

/*--------------------------------------------------------------------------*/

Abstract.EventObserver = function() {}
Abstract.EventObserver.prototype = {
  initialize: function(element, callback) {
    this.element  = $(element);
    this.callback = callback;

    this.lastValue = this.getValue();
    if (this.element.tagName.toLowerCase() == 'form')
      this.registerFormCallbacks();
    else
      this.registerCallback(this.element);
  },

  onElementEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  },

  registerFormCallbacks: function() {
    Form.getElements(this.element).each(this.registerCallback.bind(this));
  },

  registerCallback: function(element) {
    if (element.type) {
      switch (element.type.toLowerCase()) {
        case 'checkbox':
        case 'radio':
          Event.observe(element, 'click', this.onElementEvent.bind(this));
          break;
        default:
          Event.observe(element, 'change', this.onElementEvent.bind(this));
          break;
      }
    }
  }
}

Form.Element.EventObserver = Class.create();
Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.EventObserver = Class.create();
Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});
if (!window.Event) {
  var Event = new Object();
}

Object.extend(Event, {
  KEY_BACKSPACE: 8,
  KEY_TAB:       9,
  KEY_RETURN:   13,
  KEY_ESC:      27,
  KEY_LEFT:     37,
  KEY_UP:       38,
  KEY_RIGHT:    39,
  KEY_DOWN:     40,
  KEY_DELETE:   46,
  KEY_HOME:     36,
  KEY_END:      35,
  KEY_PAGEUP:   33,
  KEY_PAGEDOWN: 34,

  element: function(event) {
    return event.target || event.srcElement;
  },

  isLeftClick: function(event) {
    return (((event.which) && (event.which == 1)) ||
            ((event.button) && (event.button == 1)));
  },

  pointerX: function(event) {
    return event.pageX || (event.clientX +
      (document.documentElement.scrollLeft || document.body.scrollLeft));
  },

  pointerY: function(event) {
    return event.pageY || (event.clientY +
      (document.documentElement.scrollTop || document.body.scrollTop));
  },

  stop: function(event) {
    if (event.preventDefault) {
      event.preventDefault();
      event.stopPropagation();
    } else {
      event.returnValue = false;
      event.cancelBubble = true;
    }
  },

  // find the first node with the given tagName, starting from the
  // node the event was triggered on; traverses the DOM upwards
  findElement: function(event, tagName) {
    var element = Event.element(event);
    while (element.parentNode && (!element.tagName ||
        (element.tagName.toUpperCase() != tagName.toUpperCase())))
      element = element.parentNode;
    return element;
  },

  observers: false,

  _observeAndCache: function(element, name, observer, useCapture) {
    if (!this.observers) this.observers = [];
    if (element.addEventListener) {
      this.observers.push([element, name, observer, useCapture]);
      element.addEventListener(name, observer, useCapture);
    } else if (element.attachEvent) {
      this.observers.push([element, name, observer, useCapture]);
      element.attachEvent('on' + name, observer);
    }
  },

  unloadCache: function() {
    if (!Event.observers) return;
    for (var i = 0, length = Event.observers.length; i < length; i++) {
      Event.stopObserving.apply(this, Event.observers[i]);
      Event.observers[i][0] = null;
    }
    Event.observers = false;
  },

  observe: function(element, name, observer, useCapture) {
    element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.attachEvent))
      name = 'keydown';

    Event._observeAndCache(element, name, observer, useCapture);
  },

  stopObserving: function(element, name, observer, useCapture) {
    element = $(element);
    useCapture = useCapture || false;

	if(element==null)
		return;
    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.detachEvent))
      name = 'keydown';

    if (element.removeEventListener) {
      element.removeEventListener(name, observer, useCapture);
    } else if (element.detachEvent) {
      try {
        element.detachEvent('on' + name, observer);
      } catch (e) {}
    }
  }
});

/* prevent memory leaks in IE */
if (navigator.appVersion.match(/\bMSIE\b/))
  Event.observe(window, 'unload', Event.unloadCache, false);
var Position = {
  // set to true if needed, warning: firefox performance problems
  // NOT neeeded for page scrolling, only if draggable contained in
  // scrollable elements
  includeScrollOffsets: false,

  // must be called before calling withinIncludingScrolloffset, every time the
  // page is scrolled
  prepare: function() {
    this.deltaX =  window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
                || 0;
    this.deltaY =  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0;
  },

  realOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.scrollTop  || 0;
      valueL += element.scrollLeft || 0;
      element = element.parentNode;
    } while (element);
    return [valueL, valueT];
  },

  cumulativeOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return [valueL, valueT];
  },

  positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        if(element.tagName=='BODY') break;
        var p = Element.getStyle(element, 'position');
        if (p == 'relative' || p == 'absolute') break;
      }
    } while (element);
    return [valueL, valueT];
  },

  offsetParent: function(element) {
    if (element.offsetParent) return element.offsetParent;
    if (element == document.body) return element;

    while ((element = element.parentNode) && element != document.body)
      if (Element.getStyle(element, 'position') != 'static')
        return element;

    return document.body;
  },

  // caches x/y coordinate pair to use with overlap
  within: function(element, x, y) {
    if (this.includeScrollOffsets)
      return this.withinIncludingScrolloffsets(element, x, y);
    this.xcomp = x;
    this.ycomp = y;
    this.offset = this.cumulativeOffset(element);

    return (y >= this.offset[1] &&
            y <  this.offset[1] + element.offsetHeight &&
            x >= this.offset[0] &&
            x <  this.offset[0] + element.offsetWidth);
  },

  withinIncludingScrolloffsets: function(element, x, y) {
    var offsetcache = this.realOffset(element);

    this.xcomp = x + offsetcache[0] - this.deltaX;
    this.ycomp = y + offsetcache[1] - this.deltaY;
    this.offset = this.cumulativeOffset(element);

    return (this.ycomp >= this.offset[1] &&
            this.ycomp <  this.offset[1] + element.offsetHeight &&
            this.xcomp >= this.offset[0] &&
            this.xcomp <  this.offset[0] + element.offsetWidth);
  },

  // within must be called directly before
  overlap: function(mode, element) {
    if (!mode) return 0;
    if (mode == 'vertical')
      return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
        element.offsetHeight;
    if (mode == 'horizontal')
      return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
        element.offsetWidth;
  },

  page: function(forElement) {
    var valueT = 0, valueL = 0;

    var element = forElement;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;

      // Safari fix
      if (element.offsetParent==document.body)
        if (Element.getStyle(element,'position')=='absolute') break;

    } while (element = element.offsetParent);

    element = forElement;
    do {
      if (!window.opera || element.tagName=='BODY') {
        valueT -= element.scrollTop  || 0;
        valueL -= element.scrollLeft || 0;
      }
    } while (element = element.parentNode);

    return [valueL, valueT];
  },

  clone: function(source, target) {
    var options = Object.extend({
      setLeft:    true,
      setTop:     true,
      setWidth:   true,
      setHeight:  true,
      offsetTop:  0,
      offsetLeft: 0
    }, arguments[2] || {})

    // find page position of source
    source = $(source);
    var p = Position.page(source);

    // find coordinate system to use
    target = $(target);
    var delta = [0, 0];
    var parent = null;
    // delta [0,0] will do fine with position: fixed elements,
    // position:absolute needs offsetParent deltas
    if (Element.getStyle(target,'position') == 'absolute') {
      parent = Position.offsetParent(target);
      delta = Position.page(parent);
    }

    // correct by body offsets (fixes Safari)
    if (parent == document.body) {
      delta[0] -= document.body.offsetLeft;
      delta[1] -= document.body.offsetTop;
    }

    // set position
    if(options.setLeft)   target.style.left  = (p[0] - delta[0] + options.offsetLeft) + 'px';
    if(options.setTop)    target.style.top   = (p[1] - delta[1] + options.offsetTop) + 'px';
    if(options.setWidth)  target.style.width = source.offsetWidth + 'px';
    if(options.setHeight) target.style.height = source.offsetHeight + 'px';
  },

  absolutize: function(element) {
    element = $(element);
    if (element.style.position == 'absolute') return;
    Position.prepare();

    var offsets = Position.positionedOffset(element);
    var top     = offsets[1];
    var left    = offsets[0];
    var width   = element.clientWidth;
    var height  = element.clientHeight;

    element._originalLeft   = left - parseFloat(element.style.left  || 0);
    element._originalTop    = top  - parseFloat(element.style.top || 0);
    element._originalWidth  = element.style.width;
    element._originalHeight = element.style.height;

    element.style.position = 'absolute';
    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.width  = width + 'px';
    element.style.height = height + 'px';
  },

  relativize: function(element) {
    element = $(element);
    if (element.style.position == 'relative') return;
    Position.prepare();

    element.style.position = 'relative';
    var top  = parseFloat(element.style.top  || 0) - (element._originalTop || 0);
    var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);

    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.height = element._originalHeight;
    element.style.width  = element._originalWidth;
  }
}

// Safari returns margins on body which is incorrect if the child is absolutely
// positioned.  For performance reasons, redefine Position.cumulativeOffset for
// KHTML/WebKit only.
if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
  Position.cumulativeOffset = function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      if (element.offsetParent == document.body)
        if (Element.getStyle(element, 'position') == 'absolute') break;

      element = element.offsetParent;
    } while (element);

    return [valueL, valueT];
  }
}

Element.addMethods();// Copyright (c) 2006 SÃ©bastien Gruhier (http://xilinus.com, http://itseb.com)
// 
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// VERSION 1.1

var Window = Class.create();
Window.keepMultiModalWindow = false;
Window.prototype = {
  // Constructor
  // Available parameters : className, title, minWidth, minHeight, maxWidth, maxHeight, width, height, top, left, bottom, right, resizable, zIndex, opacity, recenterAuto, wiredDrag
  //                        hideEffect, showEffect, showEffectOptions, hideEffectOptions, effectOptions, url, draggable, closable, minimizable, maximizable, parent, onload
  //                        add all callbacks (if you do not use an observer)
  //                        onDestroy onStartResize onStartMove onResize onMove onEndResize onEndMove onFocus onBeforeShow onShow onHide onMinimize onMaximize onClose
  
  initialize: function() {
    var id;
    var optionIndex = 0;
    // For backward compatibility like win= new Window("id", {...}) instead of win = new Window({id: "id", ...})
    if (arguments.length > 0) {
      if (typeof arguments[0] == "string" ) {
        id = arguments[0];
        optionIndex = 1;
      }
      else
        id = arguments[0] ? arguments[0].id : null;
    }
    
    // Generate unique ID if not specified
    if (!id)
      id = "window_" + new Date().getTime();
      
    if ($(id))
      alert("Window " + id + " is already registered in the DOM! Make sure you use setDestroyOnClose() or destroyOnClose: true in the constructor");

    this.hasEffectLib = String.prototype.parseColor != null;
    this.options = Object.extend({
      className:         "dialog",
      minWidth:          100, 
      minHeight:         20,
      resizable:         true,
      closable:          true,
      minimizable:       true,
      maximizable:       true,
      draggable:         true,
      userData:          null,
      showEffect:        (this.hasEffectLib ? Effect.Appear : Element.show),
      hideEffect:        (this.hasEffectLib ? Effect.Fade : Element.hide),
      showEffectOptions: {},
      hideEffectOptions: {},
      effectOptions:     null,
      parent:            document.body,
      title:             "&nbsp;",
      url:               null,
      onload:            Prototype.emptyFunction,
      width:             200,
      height:            300,
      opacity:           1,
      recenterAuto:      true,
      wiredDrag:         false,
      closeCallback:     null,
      destroyOnClose:    false
    }, arguments[optionIndex] || {});
    
    if (typeof this.options.top == "undefined" &&  typeof this.options.bottom ==  "undefined") 
      this.options.top = Math.random()*500;
    if (typeof this.options.left == "undefined" &&  typeof this.options.right ==  "undefined") 
      this.options.left = Math.random()*500;

    if (this.options.effectOptions) {
      Object.extend(this.options.hideEffectOptions, this.options.effectOptions);
      Object.extend(this.options.showEffectOptions, this.options.effectOptions);
      if (this.options.showEffect == Element.Appear)
        this.options.showEffectOptions.to = this.options.opacity;
    }
    if (this.hasEffectLib) {
      if (this.options.showEffect == Effect.Appear)
        this.options.showEffectOptions.to = this.options.opacity;
    
      if (this.options.hideEffect == Effect.Fade)
        this.options.hideEffectOptions.from = this.options.opacity;
    }
    if (this.options.hideEffect == Element.hide)
      this.options.hideEffect = function(){ Element.hide(this.element); if (this.options.destroyOnClose) this.destroy(); }.bind(this)
    
    if (this.options.parent != document.body)  
      this.options.parent = $(this.options.parent);
      
    this.element = this._createWindow(id);
    
    // Bind event listener
    this.eventMouseDown = this._initDrag.bindAsEventListener(this);
    this.eventMouseUp   = this._endDrag.bindAsEventListener(this);
    this.eventMouseMove = this._updateDrag.bindAsEventListener(this);
    this.eventOnLoad    = this._getWindowBorderSize.bindAsEventListener(this);
    this.eventMouseDownContent = this.toFront.bindAsEventListener(this);
    this.eventResize = this._recenter.bindAsEventListener(this);
 
    this.topbar = $(this.element.id + "_top");
    this.bottombar = $(this.element.id + "_bottom");
    this.content = $(this.element.id + "_content");
    
    Event.observe(this.topbar, "mousedown", this.eventMouseDown);
    Event.observe(this.bottombar, "mousedown", this.eventMouseDown);
    Event.observe(this.content, "mousedown", this.eventMouseDownContent);
    Event.observe(window, "load", this.eventOnLoad);
    Event.observe(window, "resize", this.eventResize);
    Event.observe(window, "scroll", this.eventResize);
    
    if (this.options.draggable)  {
      var that = this;
      [this.topbar, this.topbar.up().previous(), this.topbar.up().next()].each(function(element) {
        element.observe("mousedown", that.eventMouseDown);
        element.addClassName("top_draggable");
      });
      [this.bottombar.up(), this.bottombar.up().previous(), this.bottombar.up().next()].each(function(element) {
        element.observe("mousedown", that.eventMouseDown);
        element.addClassName("bottom_draggable");
      });
      
    }    
    
    if (this.options.resizable) {
      this.sizer = $(this.element.id + "_sizer");
      Event.observe(this.sizer, "mousedown", this.eventMouseDown);
    }  
    
    this.useLeft = null;
    this.useTop = null;
    if (typeof this.options.left != "undefined") {
      this.element.setStyle({left: parseFloat(this.options.left) + 'px'});
      this.useLeft = true;
    }
    else {
      this.element.setStyle({right: parseFloat(this.options.right) + 'px'});
      this.useLeft = false;
    }
    
    if (typeof this.options.top != "undefined") {
      this.element.setStyle({top: parseFloat(this.options.top) + 'px'});
      this.useTop = true;
    }
    else {
      this.element.setStyle({bottom: parseFloat(this.options.bottom) + 'px'});      
      this.useTop = false;
    }
      
    this.storedLocation = null;
    
    this.setOpacity(this.options.opacity);
    if (this.options.zIndex)
      this.setZIndex(this.options.zIndex)

    if (this.options.destroyOnClose)
      this.setDestroyOnClose(true);

    this._getWindowBorderSize();
    this.width = this.options.width;
    this.height = this.options.height;
    this.visible = false;
    
    this.constraint = false;
    this.constraintPad = {top: 0, left:0, bottom:0, right:0};
    
    if (this.width && this.height)
      this.setSize(this.options.width, this.options.height);
    this.setTitle(this.options.title)
    Windows.register(this);      
  },
  
  // Destructor
  destroy: function() {
    this._notify("onDestroy");
    Event.stopObserving(this.topbar, "mousedown", this.eventMouseDown);
    Event.stopObserving(this.bottombar, "mousedown", this.eventMouseDown);
    Event.stopObserving(this.content, "mousedown", this.eventMouseDownContent);
    
    Event.stopObserving(window, "load", this.eventOnLoad);
    Event.stopObserving(window, "resize", this.eventResize);
    Event.stopObserving(window, "scroll", this.eventResize);
    
    Event.stopObserving(this.content, "load", this.options.onload);

    if (this._oldParent) {
      var content = this.getContent();
      var originalContent = null;
      for(var i = 0; i < content.childNodes.length; i++) {
        originalContent = content.childNodes[i];
        if (originalContent.nodeType == 1) 
          break;
        originalContent = null;
      }
      if (originalContent)
        this._oldParent.appendChild(originalContent);
      this._oldParent = null;
    }

    if (this.sizer)
        Event.stopObserving(this.sizer, "mousedown", this.eventMouseDown);

    if (this.options.url) 
      this.content.src = null

     if(this.iefix) 
      Element.remove(this.iefix);

    Element.remove(this.element);
    Windows.unregister(this);      
  },
    
  // Sets close callback, if it sets, it should return true to be able to close the window.
  setCloseCallback: function(callback) {
    this.options.closeCallback = callback;
  },
  
  // Gets window content
  getContent: function () {
    return this.content;
  },
  
  // Sets the content with an element id
  setContent: function(id, autoresize, autoposition) {
    var element = $(id);
    if (null == element) throw "Unable to find element '" + id + "' in DOM";
    this._oldParent = element.parentNode;

    var d = null;
    var p = null;

    if (autoresize) 
      d = Element.getDimensions(element);
    if (autoposition) 
      p = Position.cumulativeOffset(element);

    var content = this.getContent();
    // Clear HTML (and even iframe)
    this.setHTMLContent("");
    content = this.getContent();
    
    content.appendChild(element);
    element.show();
    if (autoresize) 
      this.setSize(d.width, d.height);
    if (autoposition) 
      this.setLocation(p[1] - this.heightN, p[0] - this.widthW);    
  },
  
  setHTMLContent: function(html) {
    // It was an url (iframe), recreate a div content instead of iframe content
    if (this.options.url) {
      this.content.src = null;
      this.options.url = null;
      
  	  var content ="<div id=\"" + this.getId() + "_content\" class=\"" + this.options.className + "_content\"> </div>";
      $(this.getId() +"_table_content").innerHTML = content;
      
      this.content = $(this.element.id + "_content");
    }
      
    this.getContent().innerHTML = html;
  },
  
  setAjaxContent: function(url, options, showCentered, showModal) {
    this.showFunction = showCentered ? "showCenter" : "show";
    this.showModal = showModal || false;
  
    options = options || {};

    // Clear HTML (and even iframe)
    this.setHTMLContent("");
 
    this.onComplete = options.onComplete;
    if (! this._onCompleteHandler)
      this._onCompleteHandler = this._setAjaxContent.bind(this);
    options.onComplete = this._onCompleteHandler;

    new Ajax.Request(url, options);    
    options.onComplete = this.onComplete;
  },
  
  _setAjaxContent: function(originalRequest) {
    Element.update(this.getContent(), originalRequest.responseText);
    if (this.onComplete)
      this.onComplete(originalRequest);
    this.onComplete = null;
    this[this.showFunction](this.showModal)
  },
  
  setURL: function(url) {
    // Not an url content, change div to iframe
    if (!this.options.url) {
  	  this.options.url = url;
      var content= "<iframe frameborder=\"0\" name=\"" + this.getId() + "_content\"  id=\"" + this.getId() + "_content\" src=\"" + url + "\"> </iframe>";
      $(this.getId() +"_table_content").innerHTML = content;
      
      this.content = $(this.element.id + "_content");
    } else {
  	  this.options.url = url;
	    $(this.element.getAttribute('id') + '_content').src = url;
    }
  },

  getURL: function() {
  	return this.options.url ? this.options.url : null;
  },

  refresh: function() {
    if (this.options.url)
	    $(this.element.getAttribute('id') + '_content').src = this.options.url;
  },
  
  // Stores position/size in a cookie, by default named with window id
  setCookie: function(name, expires, path, domain, secure) {
    name = name || this.element.id;
    this.cookie = [name, expires, path, domain, secure];
    
    // Get cookie
    var value = WindowUtilities.getCookie(name)
    // If exists
    if (value) {
      var values = value.split(',');
      var x = values[0].split(':');
      var y = values[1].split(':');

      var w = parseFloat(values[2]), h = parseFloat(values[3]);
      var mini = values[4];
      var maxi = values[5];

      this.setSize(w, h);
      if (mini == "true")
        this.doMinimize = true; // Minimize will be done at onload window event
      else if (maxi == "true")
        this.doMaximize = true; // Maximize will be done at onload window event

      this.useLeft = x[0] == "l";
      this.useTop = y[0] == "t";

      this.element.setStyle(this.useLeft ? {left: x[1]} : {right: x[1]});
      this.element.setStyle(this.useTop ? {top: y[1]} : {bottom: y[1]});
    }
  },
  
  // Gets window ID
  getId: function() {
    return this.element.id;
  },
  
  // Detroys itself when closing 
  setDestroyOnClose: function() {
    this.options.destroyOnClose = true;
  },
  
  setConstraint: function(bool, padding) {
    this.constraint = bool;
    this.constraintPad = Object.extend(this.constraintPad, padding || {});
    // Reset location to apply constraint
    if (this.useTop && this.useLeft)
      this.setLocation(parseFloat(this.element.style.top), parseFloat(this.element.style.left));
  },
  
  // initDrag event

  _initDrag: function(event) {
    // No resize on minimized window
    if (Event.element(event) == this.sizer && this.isMinimized())
      return;

    // No move on maximzed window
    if (Event.element(event) != this.sizer && this.isMaximized())
      return;
      
    if (isIE && this.heightN == 0)
      this._getWindowBorderSize();
    
    // Get pointer X,Y
    this.pointer = [Event.pointerX(event), Event.pointerY(event)];
    
    if (this.options.wiredDrag) 
      this.currentDrag = this._createWiredElement();
    else
      this.currentDrag = this.element;
      
    // Resize
    if (Event.element(event) == this.sizer) {
      this.doResize = true;
      this.widthOrg = this.width;
      this.heightOrg = this.height;
      this.bottomOrg = parseFloat(this.element.getStyle('bottom'));
      this.rightOrg = parseFloat(this.element.getStyle('right'));
      this._notify("onStartResize");
    }
    else {
      this.doResize = false;

      // Check if click on close button, 
      var closeButton = $(this.getId() + '_close');
      if (closeButton && Position.within(closeButton, this.pointer[0], this.pointer[1])) {
        this.currentDrag = null;
        return;
      }

      this.toFront();

      if (! this.options.draggable) 
        return;
      this._notify("onStartMove");
    }    
    // Register global event to capture mouseUp and mouseMove
    Event.observe(document, "mouseup", this.eventMouseUp, false);
    Event.observe(document, "mousemove", this.eventMouseMove, false);
    
    // Add an invisible div to keep catching mouse event over iframes
    WindowUtilities.disableScreen('__invisible__', '__invisible__');

    // Stop selection while dragging
    document.body.ondrag = function () { return false; };
    document.body.onselectstart = function () { return false; };
    
    this.currentDrag.show();
    Event.stop(event);
  },

  // updateDrag event
  _updateDrag: function(event) {
    var pointer = [Event.pointerX(event), Event.pointerY(event)];    
    var dx = pointer[0] - this.pointer[0];
    var dy = pointer[1] - this.pointer[1];
    
    // Resize case, update width/height
    if (this.doResize) {
      var w = this.widthOrg + dx;
      var h = this.heightOrg + dy;
      
      dx = this.width - this.widthOrg
      dy = this.height - this.heightOrg
      
      // Check if it's a right position, update it to keep upper-left corner at the same position
      if (this.useLeft) 
        w = this._updateWidthConstraint(w)
      else 
        this.currentDrag.setStyle({right: (this.rightOrg -dx) + 'px'});
      // Check if it's a bottom position, update it to keep upper-left corner at the same position
      if (this.useTop) 
        h = this._updateHeightConstraint(h)
      else
        this.currentDrag.setStyle({bottom: (this.bottomOrg -dy) + 'px'});
        
      this.setSize(w , h);
      this._notify("onResize");
    }
    // Move case, update top/left
    else {
      this.pointer = pointer;
      
      if (this.useLeft) {
        var left =  parseFloat(this.currentDrag.getStyle('left')) + dx;
        var newLeft = this._updateLeftConstraint(left);
        // Keep mouse pointer correct
        this.pointer[0] += newLeft-left;
        this.currentDrag.setStyle({left: newLeft + 'px'});
      }
      else 
        this.currentDrag.setStyle({right: parseFloat(this.currentDrag.getStyle('right')) - dx + 'px'});
      
      if (this.useTop) {
        var top =  parseFloat(this.currentDrag.getStyle('top')) + dy;
        var newTop = this._updateTopConstraint(top);
        // Keep mouse pointer correct
        this.pointer[1] += newTop - top;
        this.currentDrag.setStyle({top: newTop + 'px'});
      }
      else 
        this.currentDrag.setStyle({bottom: parseFloat(this.currentDrag.getStyle('bottom')) - dy + 'px'});

      this._notify("onMove");
    }
    if (this.iefix) 
      this._fixIEOverlapping(); 
      
    this._removeStoreLocation();
    Event.stop(event);
  },

   // endDrag callback
   _endDrag: function(event) {
    // Remove temporary div over iframes
     WindowUtilities.enableScreen('__invisible__');
    
    if (this.doResize)
      this._notify("onEndResize");
    else
      this._notify("onEndMove");
    
    // Release event observing
    Event.stopObserving(document, "mouseup", this.eventMouseUp,false);
    Event.stopObserving(document, "mousemove", this.eventMouseMove, false);

    Event.stop(event);
    
    this._hideWiredElement();

    // Store new location/size if need be
    this._saveCookie()
      
    // Restore selection
    document.body.ondrag = null;
    document.body.onselectstart = null;
  },

  _updateLeftConstraint: function(left) {
    if (this.constraint && this.useLeft && this.useTop) {
      var width = this.options.parent == document.body ? WindowUtilities.getPageSize().windowWidth : this.options.parent.getDimensions().width;

      if (left < this.constraintPad.left)
        left = this.constraintPad.left;
      if (left + this.width + this.widthE + this.widthW > width - this.constraintPad.right) 
        left = width - this.constraintPad.right - this.width - this.widthE - this.widthW;
    }
    return left;
  },
  
  _updateTopConstraint: function(top) {
    if (this.constraint && this.useLeft && this.useTop) {        
      var height = this.options.parent == document.body ? WindowUtilities.getPageSize().windowHeight : this.options.parent.getDimensions().height;
      
      var h = this.height + this.heightN + this.heightS;

      if (top < this.constraintPad.top)
        top = this.constraintPad.top;
      if (top + h > height - this.constraintPad.bottom) 
        top = height - this.constraintPad.bottom - h;
    }
    return top;
  },
  
  _updateWidthConstraint: function(w) {
    if (this.constraint && this.useLeft && this.useTop) {
      var width = this.options.parent == document.body ? WindowUtilities.getPageSize().windowWidth : this.options.parent.getDimensions().width;
      var left =  parseFloat(this.element.getStyle("left"));

      if (left + w + this.widthE + this.widthW > width - this.constraintPad.right) 
        w = width - this.constraintPad.right - left - this.widthE - this.widthW;
    }
    return w;
  },
  
  _updateHeightConstraint: function(h) {
    if (this.constraint && this.useLeft && this.useTop) {
      var height = this.options.parent == document.body ? WindowUtilities.getPageSize().windowHeight : this.options.parent.getDimensions().height;
      var top =  parseFloat(this.element.getStyle("top"));

      if (top + h + this.heightN + this.heightS > height - this.constraintPad.bottom) 
        h = height - this.constraintPad.bottom - top - this.heightN - this.heightS;
    }
    return h;
  },
  
  
  // Creates HTML window code
  _createWindow: function(id) {
    var className = this.options.className;
    var win = document.createElement("div");
    win.setAttribute('id', id);
    win.className = "dialog";

    var content;
    if (this.options.url)
      content= "<iframe frameborder=\"0\" name=\"" + id + "_content\"  id=\"" + id + "_content\" src=\"" + this.options.url + "\"> </iframe>";
    else
      content ="<div id=\"" + id + "_content\" class=\"" +className + "_content\"> </div>";
    var closeDiv = this.options.closable ? "<div class='"+ className +"_close' id='"+ id +"_close' onclick='Windows.close(\""+ id +"\", event)'> </div>" : "";
    var minDiv = this.options.minimizable ? "<div class='"+ className + "_minimize' id='"+ id +"_minimize' onclick='Windows.minimize(\""+ id +"\", event)'> </div>" : "";
    var maxDiv = this.options.maximizable ? "<div class='"+ className + "_maximize' id='"+ id +"_maximize' onclick='Windows.maximize(\""+ id +"\", event)'> </div>" : "";
    var seAttributes = this.options.resizable ? "class='" + className + "_sizer' id='" + id + "_sizer'" : "class='"  + className + "_se'";
    var blank = "../themes/default/blank.gif";
    
    win.innerHTML = closeDiv + minDiv + maxDiv + "\
      <table id='"+ id +"_row1' class=\"top table_window\">\
        <tr>\
          <td class='"+ className +"_nw'></td>\
          <td class='"+ className +"_n'><div id='"+ id +"_top' class='"+ className +"_title title_window'>"+ this.options.title +"</div></td>\
          <td class='"+ className +"_ne'></td>\
        </tr>\
      </table>\
      <table id='"+ id +"_row2' class=\"mid table_window\">\
        <tr>\
          <td class='"+ className +"_w'></td>\
            <td id='"+ id +"_table_content' class='"+ className +"_content' valign='top'>" + content + "</td>\
          <td class='"+ className +"_e'></td>\
        </tr>\
      </table>\
        <table id='"+ id +"_row3' class=\"bot table_window\">\
        <tr>\
          <td class='"+ className +"_sw'></td>\
            <td class='"+ className +"_s'><div id='"+ id +"_bottom' class='status_bar'><span style='float:left; width:1px; height:1px'></span></div></td>\
            <td " + seAttributes + "></td>\
        </tr>\
      </table>\
    ";
    Element.hide(win);
    this.options.parent.insertBefore(win, this.options.parent.firstChild);
    Event.observe($(id + "_content"), "load", this.options.onload);
    return win;
  },
  
  
  changeClassName: function(newClassName) {
    var className = this.options.className;
    var id = this.getId();
    var win = this;
    $A(["_close","_minimize","_maximize","_sizer", "_content"]).each(function(value) { win._toggleClassName($(id + value), className + value, newClassName + value) });
    $$("#" + id + " td").each(function(td) {td.className = td.className.sub(className,newClassName) });
    this.options.className = newClassName;
  },
  
  _toggleClassName: function(element, oldClassName, newClassName) {
    if (element) {
      element.removeClassName(oldClassName);
      element.addClassName(newClassName);
    }
  },
  
  // Sets window location
  setLocation: function(top, left) {
    top = this._updateTopConstraint(top);
    left = this._updateLeftConstraint(left);

    this.element.setStyle({top: top + 'px'});
    this.element.setStyle({left: left + 'px'});

    this.useLeft = true;
    this.useTop = true;
  },
    
  getLocation: function() {
    var location = {};
    if (this.useTop)
      location = Object.extend(location, {top: this.element.getStyle("top")});
    else
      location = Object.extend(location, {bottom: this.element.getStyle("bottom")});
    if (this.useLeft)
      location = Object.extend(location, {left: this.element.getStyle("left")});
    else
      location = Object.extend(location, {right: this.element.getStyle("right")});
    
    return location;
  },
  
  // Gets window size
  getSize: function() {
    return {width: this.width, height: this.height};
  },
    
  // Sets window size
  setSize: function(width, height) {    
    width = parseFloat(width);
    height = parseFloat(height);
    
    // Check min and max size
    if (width < this.options.minWidth)
      width = this.options.minWidth;

    if (height < this.options.minHeight)
      height = this.options.minHeight;
      
    if (this.options. maxHeight && height > this.options. maxHeight)
      height = this.options. maxHeight;

    if (this.options. maxWidth && width > this.options. maxWidth)
      width = this.options. maxWidth;

    this.width = width;
    this.height = height;
    var e = this.currentDrag ? this.currentDrag : this.element;
    e.setStyle({width: width + this.widthW + this.widthE + "px"})
    e.setStyle({height: height  + this.heightN + this.heightS + "px"})

    // Update content height
    if (!this.currentDrag || this.currentDrag == this.element) {
      var content = $(this.element.id + '_content');
      content.setStyle({height: height  + 'px'});
      content.setStyle({width: width  + 'px'});
    }
  },
  
  updateHeight: function() {
    this.setSize(this.width, this.content.scrollHeight)
  },
  
  updateWidth: function() {
    this.setSize(this.content.scrollWidth, this.height)
  },
  
  // Brings window to front
  toFront: function() {
    if (Windows.focusedWindow == this) 
      return;
    this.setZIndex(Windows.maxZIndex + 20);
    this._notify("onFocus");
    if (this.iefix) 
      this._fixIEOverlapping(); 
  },
  
  // Displays window modal state or not
  show: function(modal) {
    if (modal) {
      Windows.addModalWindow(this);
      
      this.modal = true;      
      this.setZIndex(Windows.maxZIndex + 20);
      Windows.unsetOverflow(this);
    }
    // To restore overflow if need be
    if (this.oldStyle)
      this.getContent().setStyle({overflow: this.oldStyle});
     
    else{
    	this.getContent().setStyle({overflow: 'auto'});
    }
    
    if (! this.width || !this.height) {
      var size = WindowUtilities._computeSize(this.content.innerHTML, this.content.id, this.width, this.height, 0, this.options.className)
      if (this.height)
        this.width = size + 5
      else
        this.height = size + 5
    }

    this.setSize(this.width, this.height);
    if (this.centered)
      this._center(this.centerTop, this.centerLeft);    
    
    this._notify("onBeforeShow");   
    if (this.options.showEffect != Element.show && this.options.showEffectOptions )
      this.options.showEffect(this.element, this.options.showEffectOptions);  
    else
      this.options.showEffect(this.element);  
      
    this._checkIEOverlapping();
    this.visible = true;
    WindowUtilities.focusedWindow = this
    this._notify("onShow");   
  },
  
  // Displays window modal state or not at the center of the page
  showCenter: function(modal, top, left) {
    this.centered = true;
    this.centerTop = top;
    this.centerLeft = left;

    this.show(modal);
  },
  
  isVisible: function() {
    return this.visible;
  },
  
  _center: function(top, left) {
    var windowScroll = WindowUtilities.getWindowScroll();    
    var pageSize = WindowUtilities.getPageSize();    

    if (!top)
      top = (pageSize.windowHeight - (this.height + this.heightN + this.heightS))/2;
    top += windowScroll.top
    
    if (!left)
      left = (pageSize.windowWidth - (this.width + this.widthW + this.widthE))/2;
    left += windowScroll.left 
    
    this.setLocation(top, left);
    this.toFront();
  },
  
  _recenter: function(event) {
    if (this.modal && this.centered) {
      var pageSize = WindowUtilities.getPageSize();
      // Check for this stupid IE that sends dumb events
      if (this.pageSize && this.pageSize.pageWidth == pageSize.windowWidth && this.pageSize.pageHeight == pageSize.windowHeight) 
        return;
      
      this.pageSize = pageSize;
      // set height of Overlay to take up whole page and show
      if ($('overlay_modal')) {
        $('overlay_modal').style.height = (pageSize.pageHeight + 'px');
        $('overlay_modal').style.width = (pageSize.pageWidth + 'px');
      }    
      if (this.options.recenterAuto)
        this._center(this.centerTop, this.centerLeft);    
    }
  },
  
  // Hides window
  hide: function() {
    this.visible = false;
    if (this.modal) {
      Windows.removeModalWindow(this);
      Windows.resetOverflow();
    }
    // To avoid bug on scrolling bar
    this.oldStyle = this.getContent().getStyle('overflow') || "auto"
    this.getContent().setStyle({overflow: "hidden"});

    this.options.hideEffect(this.element, this.options.hideEffectOptions);  

     if(this.iefix) 
      this.iefix.hide();

    if (!this.doNotNotifyHide)
      this._notify("onHide");
  },

  close: function() {
    // Asks closeCallback if exists
    if (this.visible) {
      if (this.options.closeCallback && ! this.options.closeCallback(this)) 
        return;

      if (this.options.destroyOnClose) {
        var destroyFunc = this.destroy.bind(this);
        if (this.options.hideEffectOptions.afterFinish) {
          var func = this.options.hideEffectOptions.afterFinish;
          this.options.hideEffectOptions.afterFinish = function() {func();destroyFunc() }
        }
        else 
          this.options.hideEffectOptions.afterFinish = function() {destroyFunc() }
      }
      Windows.updateFocusedWindow();
      
      this.doNotNotifyHide = true;
      this.hide();
      this.doNotNotifyHide = false;
      this._notify("onClose");
    }
  },
  
  minimize: function() {
    var r2 = $(this.getId() + "_row2");
    var dh = r2.getDimensions().height;
    
    if (r2.visible()) {
      var h  = this.element.getHeight() - dh;
      this.height -= dh;

      r2.hide()
      this.element.setStyle({height: h + "px"})
      if (! this.useTop) {
        var bottom = parseFloat(this.element.getStyle('bottom'));
        this.element.setStyle({bottom: (bottom + dh) + 'px'});
      }
    } 
    else {      
      var h  = this.element.getHeight() + dh;
      this.height += dh;
      
      this.element.setStyle({height: h + "px"})
      if (! this.useTop) {
        var bottom = parseFloat(this.element.getStyle('bottom'));
        this.element.setStyle({bottom: (bottom - dh) + 'px'});
      }
      r2.show();
      this.toFront();
    }
    this._notify("onMinimize");
    
    // Store new location/size if need be
    this._saveCookie()
  },
  
  maximize: function() {
    if (this.isMinimized())
      return;
  
    if (isIE && this.heightN == 0)
      this._getWindowBorderSize();
      
    if (this.storedLocation != null) {
      this._restoreLocation();
      if(this.iefix) 
        this.iefix.hide();
    }
    else {
      this._storeLocation();
      Windows.unsetOverflow(this);
      
      var windowScroll = WindowUtilities.getWindowScroll();
      var pageSize = WindowUtilities.getPageSize();    
      var left = windowScroll.left;
      var top = windowScroll.top;
      
      if (this.options.parent != document.body) {
        windowScroll =  {top:0, left:0, bottom:0, right:0};
        var dim = this.options.parent.getDimensions();
        pageSize.windowWidth = dim.width;
        pageSize.windowHeight = dim.height;
        top = 0; 
        left = 0;
      }
      
      if (this.constraint) {
        pageSize.windowWidth -= Math.max(0, this.constraintPad.left) + Math.max(0, this.constraintPad.right);
        pageSize.windowHeight -= Math.max(0, this.constraintPad.top) + Math.max(0, this.constraintPad.bottom);
        left +=  Math.max(0, this.constraintPad.left);
        top +=  Math.max(0, this.constraintPad.top);
      }
      
      this.element.setStyle(this.useLeft ? {left: left} : {right: left});
      this.element.setStyle(this.useTop ? {top: top} : {bottom: top});

      this.setSize(pageSize.windowWidth - this.widthW - this.widthE , pageSize.windowHeight - this.heightN - this.heightS)
      this.toFront();
      if (this.iefix) 
        this._fixIEOverlapping(); 
    }
    this._notify("onMaximize");

    // Store new location/size if need be
    this._saveCookie()
  },
  
  isMinimized: function() {
    var r2 = $(this.getId() + "_row2");
    return !r2.visible();
  },
  
  isMaximized: function() {
    return (this.storedLocation != null);
  },
  
  setOpacity: function(opacity) {
    if (Element.setOpacity)
      Element.setOpacity(this.element, opacity);
  },
  
  setZIndex: function(zindex) {
    this.element.setStyle({zIndex: zindex});
    Windows.updateZindex(zindex, this);
  },

  setTitle: function(newTitle) {
    if (!newTitle || newTitle == "") 
      newTitle = "&nbsp;";
      
    Element.update(this.element.id + '_top', newTitle);
  },

  setStatusBar: function(element) {
    var statusBar = $(this.getId() + "_bottom");

    if (typeof(element) == "object") {
      if (this.bottombar.firstChild)
        this.bottombar.replaceChild(element, this.bottombar.firstChild);
      else
        this.bottombar.appendChild(element);
    }
    else
      this.bottombar.innerHTML = element;
  },

  _checkIEOverlapping: function() {
    if(!this.iefix && (navigator.appVersion.indexOf('MSIE')>0) && (navigator.userAgent.indexOf('Opera')<0) && (this.element.getStyle('position')=='absolute')) {
        new Insertion.After(this.element.id, '<iframe id="' + this.element.id + '_iefix" '+ 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' + 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
        this.iefix = $(this.element.id+'_iefix');
    }
    if(this.iefix) 
      setTimeout(this._fixIEOverlapping.bind(this), 50);
  },

  _fixIEOverlapping: function() {
      Position.clone(this.element, this.iefix);
      this.iefix.style.zIndex = this.element.style.zIndex - 1;
      this.iefix.show();
  },
  
  _getWindowBorderSize: function(event) {
    // Hack to get real window border size!!
    var div = this._createHiddenDiv(this.options.className + "_n")
    this.heightN = Element.getDimensions(div).height;    
    div.parentNode.removeChild(div)

    var div = this._createHiddenDiv(this.options.className + "_s")
    this.heightS = Element.getDimensions(div).height;    
    div.parentNode.removeChild(div)

    var div = this._createHiddenDiv(this.options.className + "_e")
    this.widthE = Element.getDimensions(div).width;    
    div.parentNode.removeChild(div)

    var div = this._createHiddenDiv(this.options.className + "_w")
    this.widthW = Element.getDimensions(div).width;
    div.parentNode.removeChild(div);

    // Workaround for IE!!
    if (isIE) {
      this.heightS = $(this.getId() +"_row3").getDimensions().height;
      this.heightN = $(this.getId() +"_row1").getDimensions().height;
    }

    // Safari size fix
    if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
      this.setSize(this.width, this.height);
    if (this.doMaximize)
      this.maximize();
    if (this.doMinimize)
      this.minimize();
  },
 
  _createHiddenDiv: function(className) {
    var objBody = document.body;
    var win = document.createElement("div");
    win.setAttribute('id', this.element.id+ "_tmp");
    win.className = className;
    win.style.display = 'none';
    win.innerHTML = '';
    objBody.insertBefore(win, objBody.firstChild);
    return win;
  },
  
  _storeLocation: function() {
    if (this.storedLocation == null) {
      this.storedLocation = {useTop: this.useTop, useLeft: this.useLeft, 
                             top: this.element.getStyle('top'), bottom: this.element.getStyle('bottom'),
                             left: this.element.getStyle('left'), right: this.element.getStyle('right'),
                             width: this.width, height: this.height };
    }
  },
  
  _restoreLocation: function() {
    if (this.storedLocation != null) {
      this.useLeft = this.storedLocation.useLeft;
      this.useTop = this.storedLocation.useTop;
      
      this.element.setStyle(this.useLeft ? {left: this.storedLocation.left} : {right: this.storedLocation.right});
      this.element.setStyle(this.useTop ? {top: this.storedLocation.top} : {bottom: this.storedLocation.bottom});
      this.setSize(this.storedLocation.width, this.storedLocation.height);
      
      Windows.resetOverflow();
      this._removeStoreLocation();
    }
  },
  
  _removeStoreLocation: function() {
    this.storedLocation = null;
  },
  
  _saveCookie: function() {
    if (this.cookie) {
      var value = "";
      if (this.useLeft)
        value += "l:" +  (this.storedLocation ? this.storedLocation.left : this.element.getStyle('left'))
      else
        value += "r:" + (this.storedLocation ? this.storedLocation.right : this.element.getStyle('right'))
      if (this.useTop)
        value += ",t:" + (this.storedLocation ? this.storedLocation.top : this.element.getStyle('top'))
      else
        value += ",b:" + (this.storedLocation ? this.storedLocation.bottom :this.element.getStyle('bottom'))
        
      value += "," + (this.storedLocation ? this.storedLocation.width : this.width);
      value += "," + (this.storedLocation ? this.storedLocation.height : this.height);
      value += "," + this.isMinimized();
      value += "," + this.isMaximized();
      WindowUtilities.setCookie(value, this.cookie)
    }
  },
  
  _createWiredElement: function() {
    if (! this.wiredElement) {
      if (isIE)
        this._getWindowBorderSize();
      var div = document.createElement("div");
      div.className = "wired_frame " + this.options.className + "_wired_frame";
      
      div.style.position = 'absolute';
      this.options.parent.insertBefore(div, this.options.parent.firstChild);
      this.wiredElement = $(div);
    }
    if (this.useLeft) 
      this.wiredElement.setStyle({left: this.element.getStyle('left')});
    else 
      this.wiredElement.setStyle({right: this.element.getStyle('right')});
      
    if (this.useTop) 
      this.wiredElement.setStyle({top: this.element.getStyle('top')});
    else 
      this.wiredElement.setStyle({bottom: this.element.getStyle('bottom')});

    var dim = this.element.getDimensions();
    this.wiredElement.setStyle({width: dim.width + "px", height: dim.height +"px"});

    this.wiredElement.setStyle({zIndex: Windows.maxZIndex+30});
    return this.wiredElement;
  },
  
  _hideWiredElement: function() {
    if (! this.wiredElement || ! this.currentDrag)
      return;
    if (this.currentDrag == this.element) 
      this.currentDrag = null;
    else {
      if (this.useLeft) 
        this.element.setStyle({left: this.currentDrag.getStyle('left')});
      else 
        this.element.setStyle({right: this.currentDrag.getStyle('right')});

      if (this.useTop) 
        this.element.setStyle({top: this.currentDrag.getStyle('top')});
      else 
        this.element.setStyle({bottom: this.currentDrag.getStyle('bottom')});

      this.currentDrag.hide();
      this.currentDrag = null;
      if (this.doResize)
        this.setSize(this.width, this.height);
    } 
  },
  
  _notify: function(eventName) {
    if (this.options[eventName])
      this.options[eventName](this);
    else
      Windows.notify(eventName, this);
  }
};

// Windows containers, register all page windows
var Windows = {
  windows: [],
  modalWindows: [],
  observers: [],
  focusedWindow: null,
  maxZIndex: 0,

  addObserver: function(observer) {
    this.removeObserver(observer);
    this.observers.push(observer);
  },
  
  removeObserver: function(observer) {  
    this.observers = this.observers.reject( function(o) { return o==observer });
  },
  
  //  onDestroy onStartResize onStartMove onResize onMove onEndResize onEndMove onFocus onBeforeShow onShow onHide onMinimize onMaximize onClose
  notify: function(eventName, win) {  
    this.observers.each( function(o) {if(o[eventName]) o[eventName](eventName, win);});
  },

  // Gets window from its id
  getWindow: function(id) {
    return this.windows.detect(function(d) { return d.getId() ==id });
  },

  // Gets the last focused window
  getFocusedWindow: function() {
    return this.focusedWindow;
  },

  updateFocusedWindow: function() {
    this.focusedWindow = this.windows.length >=2 ? this.windows[this.windows.length-2] : null;    
  },
  
  // Registers a new window (called by Windows constructor)
  register: function(win) {
    this.windows.push(win);
  },
    
  // Add a modal window in the stack
  addModalWindow: function(win) {
    // Disable screen if first modal window
    if (this.modalWindows.length == 0)
      WindowUtilities.disableScreen(win.options.className, 'overlay_modal', win.getId());
    else {
      // Move overlay over all windows
      if (Window.keepMultiModalWindow) {
        $('overlay_modal').style.zIndex = Windows.maxZIndex + 20;
        Windows.maxZIndex += 20;
        WindowUtilities._hideSelect(this.modalWindows.last().getId());
      }
      // Hide current modal window
      else
        this.modalWindows.last().element.hide();
      // Fucking IE select issue
      WindowUtilities._showSelect(win.getId());
    }      
    this.modalWindows.push(win);    
  },
  
  removeModalWindow: function(win) {
    this.modalWindows.pop();
    
    // No more modal windows
    if (this.modalWindows.length == 0)
      WindowUtilities.enableScreen();     
    else {
      if (Window.keepMultiModalWindow) {
        this.modalWindows.last().toFront();
        WindowUtilities._showSelect(this.modalWindows.last().getId());        
      }
      else
        this.modalWindows.last().element.show();
    }
  },
  
  // Registers a new window (called by Windows constructor)
  register: function(win) {
    this.windows.push(win);
  },
  
  // Unregisters a window (called by Windows destructor)
  unregister: function(win) {
    this.windows = this.windows.reject(function(d) { return d==win });
  }, 
  
  // Closes all windows
  closeAll: function() {  
    this.windows.each( function(w) {Windows.close(w.getId())} );
  },
  
  closeAllModalWindows: function() {
    WindowUtilities.enableScreen();     
    this.modalWindows.each( function(win) {win.hide()});    
  },

  // Minimizes a window with its id
  minimize: function(id, event) {
    var win = this.getWindow(id)
    if (win && win.visible)
      win.minimize();
    Event.stop(event);
  },
  
  // Maximizes a window with its id
  maximize: function(id, event) {
    var win = this.getWindow(id)
    if (win && win.visible)
      win.maximize();
    Event.stop(event);
  },

  // Closes a window with its id
  close: function(id, event) {
    var win = this.getWindow(id);
    if (win) 
      win.close()//win.options.destroyOnClose ? win.close() : win.hide();
    if (event)
      Event.stop(event);
  },
  
  unsetOverflow: function(except) {    
    this.windows.each(function(d) { d.oldOverflow = d.getContent().getStyle("overflow") || "auto" ; d.getContent().setStyle({overflow: "hidden"}) });
    if (except && except.oldOverflow)
      except.getContent().setStyle({overflow: except.oldOverflow});
  },

  resetOverflow: function() {
    this.windows.each(function(d) { if (d.oldOverflow) d.getContent().setStyle({overflow: d.oldOverflow}) });
  },

  updateZindex: function(zindex, win) {
    if (zindex > this.maxZIndex)
      this.maxZIndex = zindex;
    this.focusedWindow = win;
  }
};

var Dialog = {
  dialogId: null,
  onCompleteFunc: null,
  callFunc: null, 
  parameters: null, 
    
  confirm: function(content, parameters) {
    // Get Ajax return before
    if (content && typeof content != "string") {
      Dialog._runAjaxRequest(content, parameters, Dialog.confirm);
      return 
    }
    content = content || "";
    
    parameters = parameters || {};
    var okLabel = parameters.okLabel ? parameters.okLabel : "Ok";
    var cancelLabel = parameters.cancelLabel ? parameters.cancelLabel : "Cancel";

    // Backward compatibility
    parameters = Object.extend(parameters, parameters.windowParameters || {});
    parameters.windowParameters = parameters.windowParameters || {};

    parameters.className = parameters.className || "alert";

    var okButtonClass = "class ='" + (parameters.buttonClass ? parameters.buttonClass + " " : "") + " ok_button'" 
    var cancelButtonClass = "class ='" + (parameters.buttonClass ? parameters.buttonClass + " " : "") + " cancel_button'" 
    var content = "\
      <div class='" + parameters.className + "_message'>" + content  + "</div>\
        <div class='" + parameters.className + "_buttons'>\
          <input type='button' value='" + okLabel + "' onclick='Dialog.okCallback()' " + okButtonClass + "/>\
          <input type='button' value='" + cancelLabel + "' onclick='Dialog.cancelCallback()' " + cancelButtonClass + "/>\
        </div>\
    ";
    return this._openDialog(content, parameters)
  },
  
  alert: function(content, parameters) {
    // Get Ajax return before
    if (content && typeof content != "string") {
      Dialog._runAjaxRequest(content, parameters, Dialog.alert);
      return 
    }
    content = content || "";
    
    parameters = parameters || {};
    var okLabel = parameters.okLabel ? parameters.okLabel : "Ok";

    // Backward compatibility
    parameters = Object.extend(parameters, parameters.windowParameters || {});
    parameters.windowParameters = parameters.windowParameters || {};
    
    parameters.className = parameters.className || "alert";
    
    var okButtonClass = "class ='" + (parameters.buttonClass ? parameters.buttonClass + " " : "") + " ok_button'" 
    var content = "\
      <div class='" + parameters.className + "_message'>" + content  + "</div>\
        <div class='" + parameters.className + "_buttons'>\
          <input type='button' value='" + okLabel + "' onclick='Dialog.okCallback()' " + okButtonClass + "/>\
        </div>";
    return this._openDialog(content, parameters)
  },
  
  info: function(content, parameters) {   
    // Get Ajax return before
    if (content && typeof content != "string") {
      Dialog._runAjaxRequest(content, parameters, Dialog.info);
      return 
    }
    content = content || "";
     
    // Backward compatibility
    parameters = parameters || {};
    parameters = Object.extend(parameters, parameters.windowParameters || {});
    parameters.windowParameters = parameters.windowParameters || {};
    
    parameters.className = parameters.className || "alert";
    
    var content = "<div id='modal_dialog_message' class='" + parameters.className + "_message'>" + content  + "</div>";
    if (parameters.showProgress)
      content += "<div id='modal_dialog_progress' class='" + parameters.className + "_progress'>  </div>";

    parameters.ok = null;
    parameters.cancel = null;
    
    return this._openDialog(content, parameters)
  },
  
  setInfoMessage: function(message) {
    $('modal_dialog_message').update(message);
  },
  
  closeInfo: function() {
    Windows.close(this.dialogId);
  },
  
  _openDialog: function(content, parameters) {
    var className = parameters.className;
    
    if (! parameters.height && ! parameters.width) {
      parameters.width = WindowUtilities.getPageSize().pageWidth / 2;
    }
    if (parameters.id)
      this.dialogId = parameters.id;
    else { 
      var t = new Date();
      this.dialogId = 'modal_dialog_' + t.getTime();
      parameters.id = this.dialogId;
    }

    // compute height or width if need be
    if (! parameters.height || ! parameters.width) {
      var size = WindowUtilities._computeSize(content, this.dialogId, parameters.width, parameters.height, 5, className)
      if (parameters.height)
        parameters.width = size + 5
      else
        parameters.height = size + 5
    }
    //parameters.resizable = parameters.resizable || false;
    
    parameters.effectOptions = parameters.effectOptions || {duration: 1};
    parameters.minimizable = false;
    parameters.maximizable = false;
    //parameters.draggable = false;
    parameters.closable = false;
    
    var win = new Window(parameters);
    win.getContent().innerHTML = content;
    win.showCenter(true, parameters.top, parameters.left);  
    win.setDestroyOnClose();
    
    win.cancelCallback = parameters.onCancel || parameters.cancel; 
    win.okCallback = parameters.onOk || parameters.ok;
    
    return win;    
  },
  
  _getAjaxContent: function(originalRequest)  {
      Dialog.callFunc(originalRequest.responseText, Dialog.parameters)
  },
  
  _runAjaxRequest: function(message, parameters, callFunc) {
    if (message.options == null)
      message.options = {}  
    Dialog.onCompleteFunc = message.options.onComplete;
    Dialog.parameters = parameters;
    Dialog.callFunc = callFunc;
    
    message.options.onComplete = Dialog._getAjaxContent;
    new Ajax.Request(message.url, message.options);
  },
  
  okCallback: function() {
    var win = Windows.focusedWindow;
    if (!win.okCallback || win.okCallback(win)) {
      // Remove onclick on button
      $$("#" + win.getId()+" input").each(function(element) {element.onclick=null;})
      win.close();
    }
  },

  cancelCallback: function() {
    var win = Windows.focusedWindow;
    // Remove onclick on button
    $$("#" + win.getId()+" input").each(function(element) {element.onclick=null})
    win.close();
    if (win.cancelCallback)
      win.cancelCallback(win);
  }
}
/*
  Based on Lightbox JS: Fullsize Image Overlays 
  by Lokesh Dhakar - http://www.huddletogether.com

  For more information on this script, visit:
  http://huddletogether.com/projects/lightbox/

  Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
  (basically, do anything you want, just leave my name and link)
*/

var isIE = navigator.appVersion.match(/MSIE/) == "MSIE";

var WindowUtilities = {
  // From script.aculo.us
  getWindowScroll: function() {
    var w = window;
      var T, L, W, H;
      with (w.document) {
        if (w.document.documentElement && typeof documentElement.scrollTop != "undefined") {
          T = documentElement.scrollTop;
          L = documentElement.scrollLeft;
        } else if (w.document.body) {
          T = body.scrollTop;
          L = body.scrollLeft;
        }
        if (w.innerWidth) {
          W = w.innerWidth;
          H = w.innerHeight;
        } else if (w.document.documentElement && typeof documentElement.clientWidth != "undefined") {
          W = documentElement.clientWidth;
          H = documentElement.clientHeight;
        } else {
          W = body.offsetWidth;
          H = body.offsetHeight
        }
      }
      return { top: T, left: L, width: W, height: H };
  }, 
  //
  // getPageSize()
  // Returns array with page width, height and window width, height
  // Core code from - quirksmode.org
  // Edit for Firefox by pHaez
  //
  getPageSize: function(){
    var xScroll, yScroll;

    if (window.innerHeight && window.scrollMaxY) {  
      xScroll = document.body.scrollWidth;
      yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
      xScroll = document.body.scrollWidth;
      yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
      xScroll = document.body.offsetWidth;
      yScroll = document.body.offsetHeight;
    }

    var windowWidth, windowHeight;

    if (self.innerHeight) {  // all except Explorer
      windowWidth = self.innerWidth;
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowWidth = document.documentElement.clientWidth;
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowWidth = document.body.clientWidth;
      windowHeight = document.body.clientHeight;
    }  
    var pageHeight, pageWidth;

    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
      pageHeight = windowHeight;
    } else { 
      pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){  
      pageWidth = windowWidth;
    } else {
      pageWidth = xScroll;
    }

    return {pageWidth: pageWidth ,pageHeight: pageHeight , windowWidth: windowWidth, windowHeight: windowHeight};
  },

   disableScreen: function(className, overlayId, contentId) {
    WindowUtilities.initLightbox(overlayId, className);
    var objBody = document.body;

    // prep objects
     var objOverlay = $(overlayId);

    var pageSize = WindowUtilities.getPageSize();

    // Hide select boxes as they will 'peek' through the image in IE, store old value
    if (contentId && isIE) {
      WindowUtilities._hideSelect();
      WindowUtilities._showSelect(contentId);
    }  
  
    // set height of Overlay to take up whole page and show
    objOverlay.style.height = (pageSize.pageHeight + 'px');
    objOverlay.style.width = (pageSize.windowWidth + 'px');
    objOverlay.style.display = 'block';  
  },

   enableScreen: function(id) {
     id = id || 'overlay_modal';
     var objOverlay =  $(id);
    if (objOverlay) {
      // hide lightbox and overlay
      objOverlay.style.display = 'none';

      // make select boxes visible using old value
      if (id != "__invisible__") 
        WindowUtilities._showSelect();
      
      objOverlay.parentNode.removeChild(objOverlay);
    }
  },

  _hideSelect: function(id) {
    if (isIE) {
      id = id ==  null ? "" : "#" + id + " ";
      $$(id + 'select').each(function(element) {
        if (! WindowUtilities.isDefined(element.oldVisibility)) {
          element.oldVisibility = element.style.visibility ? element.style.visibility : "visible";
          element.style.visibility = "hidden";
        }
      });
    }
  },
  
  _showSelect: function(id) {
    if (isIE) {
      id = id ==  null ? "" : "#" + id + " ";
      $$(id + 'select').each(function(element) {
        if (WindowUtilities.isDefined(element.oldVisibility)) {
          // Why?? Ask IE
          try {
            element.style.visibility = element.oldVisibility;
          } catch(e) {
            element.style.visibility = "visible";
          }
          element.oldVisibility = null;
        }
        else {
          if (element.style.visibility)
            element.style.visibility = "visible";
        }
      });
    }
  },

  isDefined: function(object) {
    return typeof(object) != "undefined" && object != null;
  },
  
  // initLightbox()
  // Function runs on window load, going through link tags looking for rel="lightbox".
  // These links receive onclick events that enable the lightbox display for their targets.
  // The function also inserts html markup at the top of the page which will be used as a
  // container for the overlay pattern and the inline image.
  initLightbox: function(id, className) {
    // Already done, just update zIndex
    if ($(id)) {
      Element.setStyle(id, {zIndex: Windows.maxZIndex + 10});
    }
    // create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
    else {
      var objBody = document.body;
      var objOverlay = document.createElement("div");
      objOverlay.setAttribute('id', id);
      objOverlay.className = "overlay_" + className
      objOverlay.style.display = 'none';
      objOverlay.style.position = 'absolute';
      objOverlay.style.top = '0';
      objOverlay.style.left = '0';
      objOverlay.style.zIndex = Windows.maxZIndex + 10;
       objOverlay.style.width = '100%';
      objBody.insertBefore(objOverlay, objBody.firstChild);
    }
  },
  
  setCookie: function(value, parameters) {
    document.cookie= parameters[0] + "=" + escape(value) +
      ((parameters[1]) ? "; expires=" + parameters[1].toGMTString() : "") +
      ((parameters[2]) ? "; path=" + parameters[2] : "") +
      ((parameters[3]) ? "; domain=" + parameters[3] : "") +
      ((parameters[4]) ? "; secure" : "");
  },

  getCookie: function(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
      begin = dc.indexOf(prefix);
      if (begin != 0) return null;
    } else {
      begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
      end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
  },
    
  _computeSize: function(content, id, width, height, margin, className) {
    var objBody = document.body;
    var tmpObj = document.createElement("div");
    tmpObj.setAttribute('id', id);
    tmpObj.className = className + "_content";

    if (height)
      tmpObj.style.height = height + "px"
    else
      tmpObj.style.width = width + "px"
  
    tmpObj.style.position = 'absolute';
    tmpObj.style.top = '0';
    tmpObj.style.left = '0';
    tmpObj.style.display = 'none';

    tmpObj.innerHTML = content;
    objBody.insertBefore(tmpObj, objBody.firstChild);
    
    var size;
    if (height)
      size = $(id).getDimensions().width + margin;
    else
      size = $(id).getDimensions().height + margin;
    objBody.removeChild(tmpObj);
    return size;
  }  
}

/*
 * Ext JS Library 1.0
 * Copyright(c) 2006-2007, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://www.extjs.com/license
 */

/**
 * @class Ext.util.JSON
 * Modified version of Douglas Crockford"s json.js that doesn"t
 * mess with the Object prototype 
 * http://www.json.org/js.html
 * @singleton
 */

var JSON = new (function(){
    var useHasOwn = {}.hasOwnProperty ? true : false;
    
    // crashes Safari in some instances
    //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
    
    var pad = function(n) {
        return n < 10 ? "0" + n : n;
    };
    
    var m = {
        "\b": '\\b',
        "\t": '\\t',
        "\n": '\\n',
        "\f": '\\f',
        "\r": '\\r',
        '"' : '\\"',
        "\\": '\\\\'
    };

    var encodeString = function(s){
        if (/["\\\x00-\x1f]/.test(s)) {
            return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                var c = m[b];
                if(c){
                    return c;
                }
                c = b.charCodeAt();
                return "\\u00" +
                    Math.floor(c / 16).toString(16) +
                    (c % 16).toString(16);
            }) + '"';
        }
        return '"' + s + '"';
    };
    
    var encodeArray = function(o){
        var a = ["["], b, i, l = o.length, v;
            for (i = 0; i < l; i += 1) {
                v = o[i];
                switch (typeof v) {
                    case "undefined":
                    case "function":
                    case "unknown":
                        break;
                    default:
                        if (b) {
                            a.push(',');
                        }
                        a.push(v === null ? "null" : JSON.encode(v));
                        b = true;
                }
            }
            a.push("]");
            return a.join("");
    };
    
    var encodeDate = function(o){
        return '"' + o.getFullYear() + "-" +
                pad(o.getMonth() + 1) + "-" +
                pad(o.getDate()) + "T" +
                pad(o.getHours()) + ":" +
                pad(o.getMinutes()) + ":" +
                pad(o.getSeconds()) + '"';
    };
    
    /**
     * Encodes an Object, Array or other value
     * @param {Mixed} o The variable to encode
     * @return {String} The JSON string
     */
    this.encode = function(o){
        if(typeof o == "undefined" || o === null){
            return "null";
        }else if(o instanceof Array){
            return encodeArray(o);
        }else if(o instanceof Date){
            return encodeDate(o);
        }else if(typeof o == "string"){
            return encodeString(o);
        }else if(typeof o == "number"){
            return isFinite(o) ? String(o) : "null";
        }else if(typeof o == "boolean"){
            return String(o);
        }else {
            var a = ["{"], b, i, v;
            for (i in o) {
                if(!useHasOwn || o.hasOwnProperty(i)) {
                    v = o[i];
                    switch (typeof v) {
                    case "undefined":
                    case "function":
                    case "unknown":
                        break;
                    default:
                        if(b){
                            a.push(',');
                        }
                        a.push(this.encode(i), ":",
                                v === null ? "null" : this.encode(v));
                        b = true;
                    }
                }
            }
            a.push("}");
            return a.join("");
        }
    };
    
    /**
     * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError.
     * @param {String} json The JSON string
     * @return {Object} The resulting object
     */
    this.decode = function(json){
        return eval("(" + json + ')');
    };
})();/*----------------------------------------\
|      Cross Browser Tree Widget 1.11     |
|-----------------------------------------|
| Created by Emil A. Eklund (eae@eae.net) |
|    For WebFX (http://webfx.eae.net/)    |
|-----------------------------------------|
| This script is  provided as is  without |
| any warranty whatsoever. It may be used |
| free of charge for non commerical sites |
| For commerical use contact  the  author |
| of this script for further details.     |
|-----------------------------------------|
| Created 2000-12-11 | Updated 2002-01-27 |
\----------------------------------------*/


var webFXTreeConfig = {
	rootIcon        : 'images/treeimg/infinioffice2.gif',
	openRootIcon    : 'images/treeimg/infinioffice2.gif',
	folderIcon      : 'images/treeimg/folderclosed.gif',
	openFolderIcon  : 'images/treeimg/folderopen.gif',
	fileIcon        : 'images/treeimg/folderclosed.gif',
	lMinusIcon      : 'images/treeimg/Lminus2.png',
	lPlusIcon       : 'images/treeimg/Lplus2.png',
	tMinusIcon      : 'images/treeimg/Tminus2.png',
	tPlusIcon       : 'images/treeimg/Tplus2.png',
	caller			: 'Project',

	iIcon           : 'images/blank.gif',
	lIcon           : 'images/blank.gif',
	tIcon           : 'images/blank.gif',

	blankIcon       : 'images/blank.gif',
	loadingIcon       : 'images/misc/loading.gif',
	defaultText     : 'Tree Item',
	defaultAction   : 'javascript:void(0);',
	defaultBehavior : 'classic'
};
var nodeid;

var webFXTreeHandler = {
	idCounter : 0,
	idPrefix  : "webfx-tree-object-",
	all       : {},
	behavior  : null,
	selected  : null,
	onSelect  : null, /* should be part of tree, not handler */
	getId     : function() { return this.idPrefix + this.idCounter++; },
	toggle    : function (oItem) { this.all[oItem.id.replace('-plus','')].toggle(); },
	onlyexpand: function (oItem) { ((this.all[oItem.id.replace('-plus','')] != null) ? this.all[oItem.id.replace('-plus','')].onlyexpand() : ""); },
	select    : function (oItem) { this.all[oItem.id.replace('-icon','')].select(); },
	focus     : function (oItem) { this.all[oItem.id.replace('-anchor','')].focus(); },
	blur      : function (oItem) { this.all[oItem.id.replace('-anchor','')].blur(); },
	keydown   : function (oItem, e) { return this.all[oItem.id].keydown(e.keyCode); },
	cookies   : new WebFXCookie(),
	insertHTMLBeforeEnd	:	function (oElement, sHTML) 
	{
		if (oElement.insertAdjacentHTML != null) 
		{
			oElement.insertAdjacentHTML("BeforeEnd", sHTML)
			return;
		}


		var df;	// DocumentFragment
		var r = oElement.ownerDocument.createRange();
		r.selectNodeContents(oElement);
		r.collapse(false);
		df = r.createContextualFragment(sHTML);
		oElement.appendChild(df);
	},
	// self creating
	insertHTMLBeforeBegin	:	function (oElement, sHTML) 
	{
		if (oElement.insertAdjacentHTML != null) 
		{
			oElement.insertAdjacentHTML("AfterBegin", sHTML)
			return;
		}


		var df;	// DocumentFragment
		var r = oElement.ownerDocument.createRange();
		r.selectNodeContents(oElement);
		r.collapse(false);
		df = r.createContextualFragment(sHTML);
		//alert(df)
		oElement.appendChild(df);
	},	
	// IO FIX
	map       : {}
};

/*
 * WebFXCookie class
 */

function WebFXCookie() {
	if (document.cookie.length) { this.cookies = ' ' + document.cookie; }
}

WebFXCookie.prototype.setCookie = function (key, value) {
	document.cookie = key + "=" + escape(value);
}

WebFXCookie.prototype.getCookie = function (key) {
	if (this.cookies) {
		var start = this.cookies.indexOf(' ' + key + '=');
		if (start == -1) { return null; }
		var end = this.cookies.indexOf(";", start);
		if (end == -1) { end = this.cookies.length; }
		end -= start;
		var cookie = this.cookies.substr(start,end);
		return unescape(cookie.substr(cookie.indexOf('=') + 1, cookie.length - cookie.indexOf('=') + 1));
	}
	else { return null; }
}

/*
 * WebFXTreeAbstractNode class
 */

function WebFXTreeAbstractNode(sText, sAction, sActionUp) {
	this.childNodes  = [];
	this.id     = webFXTreeHandler.getId();
	this.text   = sText || webFXTreeConfig.defaultText;
	this.action = sAction || webFXTreeConfig.defaultAction;
	this.actionup = sActionUp || webFXTreeConfig.defaultAction;
	this._last  = false;
	this.path='';
	this.type=''
	this.name=''
	webFXTreeHandler.all[this.id] = this;
}

/*
 * To speed thing up if you're adding multiple nodes at once (after load)
 * use the bNoIdent parameter to prevent automatic re-indentation and call
 * the obj.ident() method manually once all nodes has been added.
 */

WebFXTreeAbstractNode.prototype.add = function (node, bNoIdent) {
	
	//debugger;
	node.parentNode = this;
	this.childNodes[this.childNodes.length] = node;
	var root = this;
	if (this.childNodes.length >=2) {
		this.childNodes[this.childNodes.length -2]._last = false;
	}
	while (root.parentNode) { root = root.parentNode; }
	if (root.rendered) {
		if (this.childNodes.length >= 2) {
				document.getElementById(this.childNodes[this.childNodes.length -2].id + '-plus').src = ((this.childNodes[this.childNodes.length -2].folder)?((this.childNodes[this.childNodes.length -2].open)?webFXTreeConfig.tMinusIcon:webFXTreeConfig.tPlusIcon):webFXTreeConfig.tPlusIcon);
			if (this.childNodes[this.childNodes.length -2].folder) {
				this.childNodes[this.childNodes.length -2].plusIcon = webFXTreeConfig.tPlusIcon;
				this.childNodes[this.childNodes.length -2].minusIcon = webFXTreeConfig.tMinusIcon;
			}
			this.childNodes[this.childNodes.length -2]._last = false;
		}
		this._last = true;
		var foo = this;
		while (foo.parentNode) {
			for (var i = 0; i < foo.parentNode.childNodes.length; i++) {
				if (foo.id == foo.parentNode.childNodes[i].id) { break; }
			}
			if (++i == foo.parentNode.childNodes.length) { foo.parentNode._last = true; }
			else { foo.parentNode._last = false; }
			foo = foo.parentNode;
		}
		webFXTreeHandler.insertHTMLBeforeEnd(document.getElementById(this.id + '-cont'), node.toString());
		
		if ((!this.folder) && (!this.openIcon)) {
			this.icon = webFXTreeConfig.folderIcon;
			this.openIcon = webFXTreeConfig.openFolderIcon;
		}
		if (!this.folder) { this.folder = true; this.collapse(true); }
		if (!bNoIdent) { this.indent(); }
	}
	return node;
}
WebFXTreeAbstractNode.prototype.addTop = function (node, bNoIdent ) {
	node.parentNode = this;
	this.childNodes[this.childNodes.length] = node;
	var root = this;
	if (this.childNodes.length >=2) {
		this.childNodes[this.childNodes.length -2]._last = false;
	}
	while (root.parentNode) { root = root.parentNode; }
	if (root.rendered) {
		if (this.childNodes.length >= 2) {
			document.getElementById(this.childNodes[this.childNodes.length -2].id + '-plus').src = ((this.childNodes[this.childNodes.length -2].folder)?((this.childNodes[this.childNodes.length -2].open)?webFXTreeConfig.tMinusIcon:webFXTreeConfig.tPlusIcon):webFXTreeConfig.tIcon);
			if (this.childNodes[this.childNodes.length -2].folder) {
				this.childNodes[this.childNodes.length -2].plusIcon = webFXTreeConfig.tPlusIcon;
				this.childNodes[this.childNodes.length -2].minusIcon = webFXTreeConfig.tMinusIcon;
			}
			this.childNodes[this.childNodes.length -2]._last = false;
		}
		this._last = true;
		var foo = this;
		while (foo.parentNode) {
			for (var i = 0; i < foo.parentNode.childNodes.length; i++) {
				if (foo.id == foo.parentNode.childNodes[i].id) { break; }
			}
			if (++i == foo.parentNode.childNodes.length) { foo.parentNode._last = true; }
			else { foo.parentNode._last = false; }
			foo = foo.parentNode;
		}
		webFXTreeHandler.insertHTMLBeforeBegin(document.getElementById(this.id + '-cont'), node.toString());
		
		if ((!this.folder) && (!this.openIcon)) {
			this.icon = webFXTreeConfig.folderIcon;
			this.openIcon = webFXTreeConfig.openFolderIcon;
		}
		if (!this.folder) { this.folder = true; this.collapse(true); }
		if (!bNoIdent) { this.indent(); }
	}
	return node;
}
WebFXTreeAbstractNode.prototype.toggle = function() {

//debugger;
	if(this.childNodes.length==0 && this.canParentNode==true)
		GetProjectList(this);
	else
	{
	
		if (this.folder) 
		{
			if (this.open) { this.collapse(); }
			else { this.expand(); }
		}
	}
}

WebFXTreeAbstractNode.prototype.reload = function()	{
	this._removeallchild();
	this.expand();
	
}
WebFXTreeAbstractNode.prototype.onlyexpand = function() {
	if (this.folder) {
		if (!this.open) { this.expand(); }
}	}

WebFXTreeAbstractNode.prototype.select = function() {
	document.getElementById(this.id + '-anchor').focus();
}

WebFXTreeAbstractNode.prototype.deSelect = function() {
	document.getElementById(this.id + '-anchor').className = '';
	webFXTreeHandler.selected = null;
}

WebFXTreeAbstractNode.prototype.focus = function() {
	
	if ((webFXTreeHandler.selected) && (webFXTreeHandler.selected != this)) { webFXTreeHandler.selected.deSelect(); }
	webFXTreeHandler.selected = this;
	if ((this.openIcon) && (webFXTreeHandler.behavior != 'classic')) { document.getElementById(this.id + '-icon').src = this.openIcon; }
	try
	{
		document.getElementById(this.id + '-anchor').className = 'selected';
		document.getElementById(this.id + '-anchor').focus();
	}
	catch(e){}
		
	if (webFXTreeHandler.onSelect) { webFXTreeHandler.onSelect(this); }
}

WebFXTreeAbstractNode.prototype.blur = function() {
	if ((this.openIcon) && (webFXTreeHandler.behavior != 'classic')) { document.getElementById(this.id + '-icon').src = this.icon; }
	document.getElementById(this.id + '-anchor').className = 'selected-inactive';
}

WebFXTreeAbstractNode.prototype.doExpand = function() {
	if (webFXTreeHandler.behavior == 'classic') { document.getElementById(this.id + '-icon').src = this.openIcon; }
	if (this.childNodes.length) {  document.getElementById(this.id + '-cont').style.display = 'block'; }
	this.open = true;
	webFXTreeHandler.cookies.setCookie(this.id.substr(18,this.id.length - 18), '1');
}

WebFXTreeAbstractNode.prototype.doCollapse = function() {
	if (webFXTreeHandler.behavior == 'classic') { document.getElementById(this.id + '-icon').src = this.icon; }
	if (this.childNodes.length) { document.getElementById(this.id + '-cont').style.display = 'none'; }
	this.open = false;
	webFXTreeHandler.cookies.setCookie(this.id.substr(18,this.id.length - 18), '0');
}

WebFXTreeAbstractNode.prototype.expandAll = function() {
	this.expandChildren();
	if ((this.folder) && (!this.open)) { this.expand(); }
}

WebFXTreeAbstractNode.prototype.expandChildren = function() {
	for (var i = 0; i < this.childNodes.length; i++) {
		this.childNodes[i].expandAll();
} }

WebFXTreeAbstractNode.prototype.collapseAll = function() {
	this.collapseChildren();
	if ((this.folder) && (this.open)) { this.collapse(true); }
}

WebFXTreeAbstractNode.prototype.collapseChildren = function() {
	for (var i = 0; i < this.childNodes.length; i++) {
		this.childNodes[i].collapseAll();
} }

WebFXTreeAbstractNode.prototype.indent = function(lvl, del, last, level) {
	/*
	 * Since we only want to modify items one level below ourself,
	 * and since the rightmost indentation position is occupied by
	 * the plus icon we set this to -2
	 */
	if (lvl == null) { lvl = -2; }
	var state = 0;
	for (var i = this.childNodes.length - 1; i >= 0 ; i--) {
		state = this.childNodes[i].indent(lvl + 1, del, last, level);
		if (state) { return; }
	}
	if (del) {
		if ((level >= this._level) && (document.getElementById(this.id + '-plus'))) {
			if (this.folder) {
				document.getElementById(this.id + '-plus').src = (this.open)?webFXTreeConfig.lMinusIcon:kConfig.lPlusIcon;
				this.plusIcon = webFXTreeConfig.lPlusIcon;
				this.minusIcon = webFXTreeConfig.lMinusIcon;
			}
			else { document.getElementById(this.id + '-plus').src = webFXTreeConfig.lIcon; }
			return 1;
	}	}
	var foo = document.getElementById(this.id + '-indent-' + lvl);
	if (foo) {
		if ((del) && (last)) { foo._last = true; }
		if (foo._last) { foo.src =  webFXTreeConfig.blankIcon; }
		else { foo.src =  webFXTreeConfig.iIcon; }
	}
	return 0;
}

/*
 * WebFXTree class
 */

function WebFXTree(sText, sAction, sBehavior, sIcon, sOpenIcon) {
	this.base = WebFXTreeAbstractNode;
	this.base(sText, sAction);
	this.icon      = sIcon || webFXTreeConfig.rootIcon;
	this.openIcon  = sOpenIcon || webFXTreeConfig.openRootIcon;
	/* Defaults to open */
	this.open      = (webFXTreeHandler.cookies.getCookie(this.id.substr(18,this.id.length - 18)) == '0')?false:true;
	this.folder    = true;
	this.rendered  = false;
	this.onSelect  = null;
	if (!webFXTreeHandler.behavior) {  webFXTreeHandler.behavior = sBehavior || webFXTreeConfig.defaultBehavior; }
}

WebFXTree.prototype = new WebFXTreeAbstractNode;

WebFXTree.prototype.setBehavior = function (sBehavior) {
	webFXTreeHandler.behavior =  sBehavior;
};

WebFXTree.prototype.getBehavior = function (sBehavior) {
	return webFXTreeHandler.behavior;
};

WebFXTree.prototype.getSelected = function() {
	if (webFXTreeHandler.selected) { return webFXTreeHandler.selected; }
	else { return null; }
}

WebFXTree.prototype.remove = function() { }

WebFXTree.prototype.expand = function() {
	this.doExpand();
}

WebFXTree.prototype.collapse = function(b) {
	if (!b) { this.focus(); }
	this.doCollapse();
}

WebFXTree.prototype.getFirst = function() {
	return null;
}

WebFXTree.prototype.getLast = function() {
	return null;
}

WebFXTree.prototype.getNextSibling = function() {
	return null;
}

WebFXTree.prototype.getPreviousSibling = function() {
	return null;
}

WebFXTree.prototype.keydown = function(key) {
	if (key == 39) {
		if (!this.open) { this.expand(); }
		else if (this.childNodes.length) { this.childNodes[0].select(); }
		return false;
	}
	if (key == 37) { this.collapse(); return false; }
	if ((key == 40) && (this.open) && (this.childNodes.length)) { this.childNodes[0].select(); return false; }
	return true;
}


WebFXTree.prototype.toString = function() {
	 
	var str = "<div id=\"" + this.id + "\" ondblclick=\"webFXTreeHandler.toggle(this);\" class=\"webfx-tree-item\" onkeydown=\"return webFXTreeHandler.keydown(this, event)\">";
	str += "<img id=\"" + this.id + "-icon\" class=\"webfx-tree-icon\" src=\"" + ((webFXTreeHandler.behavior == 'classic' && this.open)?this.openIcon:this.icon) + "\" onclick=\"webFXTreeHandler.select(this);\"><a href=\"" + this.action + "\" id=\"" + this.id + "-anchor\" onfocus=\"webFXTreeHandler.focus(this);\" onblur=\"webFXTreeHandler.blur(this);\">" + this.text + "</a></div>";
	str += "<div id=\"" + this.id + "-cont\" class=\"webfx-tree-container\" style=\"display: " + ((this.open)?'block':'none') + ";\">";
	for (var i = 0; i < this.childNodes.length; i++) {
		str += this.childNodes[i].toString(i, this.childNodes.length);
	}
	str += "</div>";
	this.rendered = true;
	return str;
};

// IO Fix by Asif Iqbal & Afnan - 16.02.07
WebFXTree.prototype.searchById = function(id) 
{ 	
	return webFXTreeHandler.all[id];
}
WebFXTree.prototype.searchByNodeId = function(nodeId) 
{ 
	return webFXTreeHandler.all[webFXTreeHandler.map[nodeId]];
}

/*
 * WebFXTreeItem class
 */

function WebFXTreeItem(sText, sAction, sActionUp, eParent, sIcon, sOpenIcon,nodeId,path,type,name,nodeType,canParentNode) {

	//debugger;
	this.base = WebFXTreeAbstractNode;
	this.base(sText, sAction, sActionUp);
    this.flagdown = false;
    this.path=path;
    this.type=type;
    this.name=name;
    this.nodeType = nodeType;
    this.canParentNode=canParentNode;
    //debugger;
	/* Defaults to close */
	this.open = (webFXTreeHandler.cookies.getCookie(this.id.substr(18,this.id.length - 18)) == '1')?true:false;
	if (sIcon) { this.icon = sIcon; }

	if (sOpenIcon) { this.openIcon = sOpenIcon; }

	if (eParent) { eParent.add(this); }
		
	
	// IO Fix by Asif Iqbal & Afnan - 16.02.07
	if (nodeId) 
	{
		webFXTreeHandler.map[nodeId] = this.id;
		this.nodeId = nodeId;
	}
}
	
WebFXTreeItem.prototype = new WebFXTreeAbstractNode;

WebFXTreeItem.prototype.remove = function() {
	//alert("remove function");
	//debugger;
	var iconSrc = document.getElementById(this.id + '-plus').src;
	var parentNode = this.parentNode;
	var prevSibling = this.getPreviousSibling(true);
	var nextSibling = this.getNextSibling(true);
	var folder = this.parentNode.folder;
	var last = ((nextSibling) && (nextSibling.parentNode) && (nextSibling.parentNode.id == parentNode.id))?false:true;
	this.getPreviousSibling().focus();
	prevSibling.collapse();
	this._remove();
	
	if (parentNode.childNodes.length == 0) {
		parentNode.folder = false;
		parentNode.open = false;
		lastNodeHiddenDiv = document.getElementById('webfx-tree-object-16-cont');
		
	}
	if (!nextSibling) { parentNode.indent(null, true, last, this._level); }
	if ((prevSibling == parentNode) && !(parentNode.childNodes.length)) {
		prevSibling.folder = false;
		prevSibling.open = false;
		iconSrc = document.getElementById(prevSibling.id + '-plus').src;
		iconSrc = iconSrc.replace('minus', '').replace('plus', '');
		document.getElementById(prevSibling.id + '-plus').src = iconSrc;
		if(typeof(prevSibling.nodeType)!='undefined' && prevSibling.nodeType!="project")
			document.getElementById(prevSibling.id + '-icon').src = webFXTreeConfig.fileIcon;
	}
	if(parentNode.childNodes.length == 0)
	{
		document.getElementById(prevSibling.id + '-plus').src = webFXTreeConfig.blankIcon;
	}
	if (document.getElementById(prevSibling.id + '-plus')) {
		if (parentNode == prevSibling.parentNode) {
			iconSrc = iconSrc.replace('minus', '').replace('plus', '');
			document.getElementById(prevSibling.id + '-plus').src = iconSrc;
}	}	}
/* self created method for colaapsing all the child before deleteing any node*/
WebFXTreeItem.prototype._collapsechild = function() {
	for (var i = this.childNodes.length - 1; i >= 0; i--) {
		this.childNodes[i].collapse();
 	}
}
/* self created method for deleting all the childs of any node*/
WebFXTreeItem.prototype._removeallchild = function() {
	for (var i = this.childNodes.length - 1; i >= 0; i--) {
		this.childNodes[i]._remove();
 	}
}
WebFXTreeItem.prototype._getchildlength = function() {
		return this.childNodes.length;
 	
}
WebFXTreeItem.prototype._remove = function() {
	for (var i = this.childNodes.length - 1; i >= 0; i--) {
		this.childNodes[i]._remove();
 	}
	for (var i = 0; i < this.parentNode.childNodes.length; i++) {
		if (this == this.parentNode.childNodes[i]) {
			for (var j = i; j < this.parentNode.childNodes.length; j++) {
				this.parentNode.childNodes[j] = this.parentNode.childNodes[j+1];
			}
			this.parentNode.childNodes.length -= 1;
			if (i + 1 == this.parentNode.childNodes.length) { this.parentNode._last = true; }
			break;
	}	}
	webFXTreeHandler.all[this.id] = null;
	if (document.getElementById(this.id)) {
		var tmp = document.getElementById(this.id);
		tmp.parentNode.removeChild(tmp);
	}
}

WebFXTreeItem.prototype.expand = function() {
	this.doExpand();
	document.getElementById(this.id + '-plus').src = this.minusIcon;
}

WebFXTreeItem.prototype.collapse = function(b) {
	if (!b) { this.focus(); }
	this.doCollapse();
	document.getElementById(this.id + '-plus').src = this.plusIcon;
}

WebFXTreeItem.prototype.getFirst = function() {
	return this.childNodes[0];
}

WebFXTreeItem.prototype.getLast = function() {
	if (this.childNodes[this.childNodes.length - 1].open) { return this.childNodes[this.childNodes.length - 1].getLast(); }
	else { return this.childNodes[this.childNodes.length - 1]; }
}

WebFXTreeItem.prototype.getNextSibling = function() {
	for (var i = 0; i < this.parentNode.childNodes.length; i++) {
		if (this == this.parentNode.childNodes[i]) { break; }
	}
	if (++i == this.parentNode.childNodes.length) { return this.parentNode.getNextSibling(); }
	else { return this.parentNode.childNodes[i]; }
}

WebFXTreeItem.prototype.getPreviousSibling = function(b) {
	for (var i = 0; i < this.parentNode.childNodes.length; i++) {
		if (this == this.parentNode.childNodes[i]) { break; }
	}
	if (i == 0) { return this.parentNode; }
	else {
		if ((this.parentNode.childNodes[--i].open) || (b && this.parentNode.childNodes[i].folder)) { return this.parentNode.childNodes[i].getLast(); }
		else { return this.parentNode.childNodes[i]; }
} }

WebFXTreeItem.prototype.keydown = function(key) {
	if ((key == 39) && (this.folder)) {
		if (!this.open) { this.expand(); }
		else { this.getFirst().select(); }
		return false;
	}
	else if (key == 37) {
		if (this.open) { this.collapse(); }
		else { this.parentNode.select(); }
		return false;
	}
	else if (key == 40) {
		if (this.open) { this.getFirst().select(); }
		else {
			var sib = this.getNextSibling();
			if (sib) { sib.select(); }
		}
		return false;
	}
	else if (key == 38) { this.getPreviousSibling().select(); return false; }
	return true;
}

WebFXTreeItem.prototype.setFlagDown = function (flag) {
this.flagdown=flag;
}

WebFXTreeItem.prototype.toString = function (nItem, nItemCount) {
	//debugger;
	var foo = this.parentNode;
	
	var indent = '';
	if (nItem + 1 == nItemCount) { this.parentNode._last = true; }
	var i = 0;
	//if(foo!=undefined)
	//{
		while (foo.parentNode) {
			foo = foo.parentNode;
			indent = "<img id=\"" + this.id + "-indent-" + i + "\" src=\"" + ((foo._last)?webFXTreeConfig.iIcon:webFXTreeConfig.iIcon) + "\">"+indent;
			i++;
		}
	//}
	this._level = i;
	if (this.childNodes.length) { this.folder = 1; }
	else { this.open = false; }
	if ((this.folder) || (webFXTreeHandler.behavior != 'classic')) {
		if (!this.icon) { this.icon = webFXTreeConfig.folderIcon; }
		if (!this.openIcon) { this.openIcon = webFXTreeConfig.openFolderIcon; }
	}
	else if (!this.icon) { this.icon = webFXTreeConfig.fileIcon; }
	var label = this.text.replace(/</g, '&lt;').replace(/>/g, '&gt;');
	var isContextMenu;
	if(label == "My Shared Projects")
		isContextMenu = '';
	else if(label == "Shared")
		isContextMenu='';
	else
		isContextMenu = "ContextMenu('"+this.nodeType+"','"+this.path+"','"+this.nodeId+"');"
	
	//var str = "<div id=\"" + this.id + "\" oncontextmenu=\"isContextMenu;return false;\" ondblclick=\"webFXTreeHandler.toggle(this);\" class=\"webfx-tree-item\" onkeydown=\"return webFXTreeHandler.keydown(this, event)\">";
	var str = "<div id=\"" + this.id + "\" oncontextmenu=\"" + isContextMenu + "\" return false;ondblclick=\"webFXTreeHandler.toggle(this);\" class=\"webfx-tree-item\" onkeydown=\"return webFXTreeHandler.keydown(this, event)\">";
	str += indent;
	/*
	 * If canParentNode property of the node is set to true then show the new ajax based node with +icon 
	 * */
	if(this.canParentNode == true)
	{
		// new code use to convert it into ajax based tree
		str += "<img id=\"" + this.id + "-plus\" src=\"" + ((this.folder)?((this.open)?((this.parentNode._last)?webFXTreeConfig.lMinusIcon:webFXTreeConfig.tMinusIcon):((this.parentNode._last)?webFXTreeConfig.lPlusIcon:webFXTreeConfig.tPlusIcon)):((this.parentNode._last)?webFXTreeConfig.lPlusIcon:webFXTreeConfig.tPlusIcon)) + "\" onmousedown=\"webFXTreeHandler.toggle(this);\">";
	}
	else
	{
		//old without ajax
		str += "<img id=\"" + this.id + "-plus\" src=\"" + ((this.folder)?((this.open)?((this.parentNode._last)?webFXTreeConfig.lMinusIcon:webFXTreeConfig.tMinusIcon):((this.parentNode._last)?webFXTreeConfig.lPlusIcon:webFXTreeConfig.tPlusIcon)):((this.parentNode._last)?webFXTreeConfig.lIcon:webFXTreeConfig.tIcon)) + "\" onmousedown=\"webFXTreeHandler.toggle(this);\">";
	}
	//str += "<img id=\"" + this.id + "-plus\" src=\"" + ((this.folder)?((this.open)?((this.parentNode._last)?webFXTreeConfig.lMinusIcon:webFXTreeConfig.tMinusIcon):((this.parentNode._last)?webFXTreeConfig.lPlusIcon:webFXTreeConfig.tPlusIcon)):((this.parentNode._last)?webFXTreeConfig.lIcon:webFXTreeConfig.tIcon)) + "\" onmousedown=\"webFXTreeHandler.toggle(this);\">";
	//	str += "<img id=\"" + this.id + "-icon\" class=\"webfx-tree-icon\" src=\"" + ((webFXTreeHandler.behavior == 'classic' && this.open)?this.openIcon:this.icon) + "\" onclick=\"webFXTreeHandler.select(this);\"><a href=\"" + this.action + "\" id=\"" + this.id + "-anchor\" onfocus=\"webFXTreeHandler.focus(this);\" onblur=\"webFXTreeHandler.blur(this);\">" + label + "</a></div>";
	//	altered here by afnan
	
	//	str += "<img id=\"" + this.id + "-icon\" class=\"webfx-tree-icon\" src=\"" + ((webFXTreeHandler.behavior == 'classic' && this.open)?this.openIcon:this.icon) + "\" onclick=\"webFXTreeHandler.select(this);\"><span onDblClick=\"void(0);\" onClick=\""+this.action+"\" onMouseUp=\""+this.actionup+"\"><a href=\"" + "#" + "\" id=\"" + this.id + "-anchor\" onfocus=\"webFXTreeHandler.focus(this);\" onblur=\"webFXTreeHandler.blur(this);\">" + label + "</a></span></div>";
	// with on mouse out // str += "<span onmouseover=\"var o=document.getElementById('" + this.id + "-anchor'); o.style.textDecoration='underline';o.className='webfx-tree-mouse-out'\" onmouseout=\"var o=document.getElementById('" + this.id + "-anchor'); o.style.textDecoration='none';o.className='webfx-tree-mouse-out'\" onDblClick=\"void(0);\" onClick=\""+this.action+";webFXTreeHandler.onlyexpand(document.getElementById('"+this.id+"-plus'));\" onMouseUp=\""+this.actionup+"\"><img id=\"" + this.id + "-icon\" class=\"webfx-tree-icon\" src=\"" + ((webFXTreeHandler.behavior == 'classic' && this.open)?this.openIcon:this.icon) + "\" onclick=\"webFXTreeHandler.select(this);\"><a href=\"" + "#" + "\" id=\"" + this.id + "-anchor\" onfocus=\"webFXTreeHandler.focus(this);\" onblur=\"webFXTreeHandler.blur(this);\">" + label + "</a></span></div>";
	if(this.canParentNode == true)
		str += "<span onmouseover=\"var o=document.getElementById('" + this.id + "-anchor'); o.style.textDecoration='underline';\" onmouseout=\"var o=document.getElementById('" + this.id + "-anchor'); o.style.textDecoration='none';\" onDblClick=\"void(0);\" onClick=\"webFXTreeHandler.toggle(document.getElementById('"+this.id+"-plus'));"+this.action+";webFXTreeHandler.onlyexpand(document.getElementById('"+this.id+"-plus'));\" onMouseUp=\""+this.actionup+"\"><img id=\"" + this.id + "-icon\" class=\"webfx-tree-icon\" src=\"" + ((webFXTreeHandler.behavior == 'classic' && this.open)?this.openIcon:this.icon) + "\" onclick=\"webFXTreeHandler.select(this);\"><a href=\"" + "javascript:ShowModule()" + "\" id=\"" + this.id + "-anchor\" onfocus=\"webFXTreeHandler.focus(this);\" onblur=\"webFXTreeHandler.blur(this);\">" + label + "</a></span></div>";
	else	
		str += "<span onmouseover=\"var o=document.getElementById('" + this.id + "-anchor'); o.style.textDecoration='underline';\" onmouseout=\"var o=document.getElementById('" + this.id + "-anchor'); o.style.textDecoration='none';\" onDblClick=\"void(0);\" onClick=\""+this.action+";webFXTreeHandler.onlyexpand(document.getElementById('"+this.id+"-plus'));\" onMouseUp=\""+this.actionup+"\"><img id=\"" + this.id + "-icon\" class=\"webfx-tree-icon\" src=\"" + ((webFXTreeHandler.behavior == 'classic' && this.open)?this.openIcon:this.icon) + "\" onclick=\"webFXTreeHandler.select(this);\"><a href=\"" + "javascript:ShowModule()" + "\" id=\"" + this.id + "-anchor\" onfocus=\"webFXTreeHandler.focus(this);\" onblur=\"webFXTreeHandler.blur(this);\">" + label + "</a></span></div>";
	str += "<div id=\"" + this.id + "-cont\" class=\"webfx-tree-container\" style=\"display: " + ((this.open)?'block':'none') + ";\">";
	for (var i = 0; i < this.childNodes.length; i++) {
		str += this.childNodes[i].toString(i,this.childNodes.length);
	}
	str += "</div>";
	this.plusIcon = ((this.parentNode._last)?webFXTreeConfig.lPlusIcon:webFXTreeConfig.tPlusIcon);
	this.minusIcon = ((this.parentNode._last)?webFXTreeConfig.lMinusIcon:webFXTreeConfig.tMinusIcon);
	return str;
}
function ShowModule()
{
//use to replace # in tree node url
}

function GetProjectList(node)
{
	var path ='';
	var type='';
	var name=''
	if(typeof(node.path)=='undefined')
		path=-1;
	else
		path = node.path;
	
	if(typeof(node.type)=='undefined' || node.type=='')	
		type=-1
	else
		type=node.type;
	
	if(typeof(node.name)=='undefined' || node.name=='')	
		name=-1
	else
		name=node.name;	
	 
	if(path == -1 && type==-1 && name==-1) 
	{
		//for all the nodes other than project
		document.getElementById(node.id + '-plus').src = webFXTreeConfig.blankIcon
		return;
	}
	document.getElementById(node.id + '-plus').src = webFXTreeConfig.loadingIcon
	
	if(type=="accounting")
		callback='AccNodeCallback';
	else if(type=="customernodes") //showcustomer list under sales
		callback='CustNodeCallback';
	else if(type=="catalognodes") //showproduct list under product catalog not need at this time
		callback='CatalogNodeCallback';
	else if(type=="questioncatnodes") //use in the category screen for idocs
		callback='CategoryNodeCallback';
	else if(type=="selectreeprojectnodes") //use in the add and edit task screen for selecting particullat project
		callback='SelectTreeProjectNodeCallback';
	else if(type=="selectTreeproject")	 // for select prject tree node hadling click
		{callback='SelectTreeProjectNodeCallback';type="project";}	
	else
		callback='AddTreeNodeCallback';
	var o = new Array(path,type,node.nodeId,name,parent._sessionid_);
	o = JSON.encode(o);		 		
	var url = "index.php?object=ibz.tree&function=ShowAjaxTree&isajaxcall=1";
	var pars = 'param='+o;
	
	var myAjax = new Ajax.Request( url,
		{ method: 'post', parameters: pars, onFailure: ReportError , onSuccess: eval(callback)});		
}
function SelectTreeProjectNodeCallback(response)
{
	response = eval(response.responseText);
	var nodeid = response[0]['nodeId'];
		
	var w;
	var tree;
		
	if(webFXTreeConfig.caller == "documentTree" || webFXTreeConfig.caller=="broadcastTree")
	{
		w = window;
	}
	else
	{
		if(parent.document.getElementById('IFControl'))
			w = parent.document.getElementById('IFControl').contentWindow;
		else
			w = parent.parent.document.getElementById('IFControl').contentWindow;
	}
	
	
	if(w.tree)
	{
		tree = w.tree;
		var parentNode = w.tree.searchByNodeId(nodeid);
	}
	else if	(w.crmTree)
	{	
		tree = w.crmTree;
		var parentNode = w.crmTree.searchByNodeId(nodeid);
	}
	if(parentNode.parentNode.text == "My Personal")
		{parentNode.parentNode.action = "setValue1('"+-1+"','My Personal','"+-1+"');";
		 parentNode.parentNode.actionup = "setValue1('"+-1+"','My Personal','"+-1+"');";}
	
	var nodeid = parentNode.id;
	var count = response[0]['totalCount'];
	var nodes = response[0]['nodes'];
	var projectType = response[0]['type'];
	notParentArr= new Array();
	notParentCount=0;
		
	if(response[0]['totalCount']>0)
	{
		document.getElementById(nodeid + '-plus').src = webFXTreeConfig.lMinusIcon;
	}
	else
	{
		document.getElementById(nodeid + '-plus').src = webFXTreeConfig.blankIcon;
	}
	
	if(nodes != null)
	{
		var obj='';
		if(nodes["project"] != null && typeof(nodes["project"]) != 'undefined')
		{
			if(nodes["project"].totalCount > 0)
			{
				obj = "project";
			} 
		}
		else if(nodes["SupplierProducts"] != null && typeof(nodes["SupplierProducts"]) != 'undefined')
		{
			if(nodes["SupplierProducts"].totalCount > 0)
			{
				obj = "SupplierProducts";
			}
		}
	
		if(obj == '')
		{
			for (var obj in nodes)
			{
				rootnode = nodes[obj].title;
				rootpid = nodes[obj].projectid;
				rootpath = nodes[obj].path;
				rootparentnode = nodes[obj].parentnode;
				rootnodeid = nodes[obj].nodeid;
				rootparentid = nodes[obj].parentnode;
				
				projecttype = nodes[obj].type;
				ownerid = nodes[obj].ownerid;
				branchid = nodes[obj].branchid;
				companyid = nodes[obj].companyid;
				ownername = "Projects List";
				
				var parentNode = tree.searchByNodeId(rootparentid)	
				
				onclick = "setValue1('"+rootpid+"','"+rootnode+"','"+rootpath+"');";

				onclick = "";
				if(!tree.searchByNodeId(rootnodeid))
				{
					onmouseup1="";
					parNodeObj = new w.WebFXTreeItem(rootnode, onclick, onmouseup1, '', 'images/treeimg/projects.png', 'images/treeimg/projects.png',rootnodeid,'-1','','',projecttype,true);	
					parentNode.add(parNodeObj);
				}
				else
					tree.searchByNodeId(rootnodeid).toggle();
	
			 for(x=0;x<nodes[obj].totalCount;x++)
			 	
			 	{
	
			 		childnode = nodes[obj].nodes[x]['title'];
					childpid = nodes[obj].nodes[x]['projectid'];
					childpath = nodes[obj].nodes[x]['path'];
					childparentnode = nodes[obj].nodes[x]['parentnode'];
					childnodeid = nodes[obj].nodes[x]['nodeid'];
					ppath = '|'+childpid+'/';
			 		projectname = childnode;
			 		childNodeObj = "";
			 		
					if(childpath!= -1)
						ppath =ppath+childpath+'/';
					var childparentNode = tree.searchByNodeId(childparentnode)	
					
					if(tree.searchByNodeId(childnodeid))
						continue;

						
					onclick = "setValue1('"+childpid+"','"+projectname+"','"+childpath+"');";
					childNodeObj = new w.WebFXTreeItem(childnode, onclick, "", '', 'images/treeimg/projects_list.png', 'images/treeimg/projects_list.png',childnodeid,ppath,"selectTreeproject",childnode,projecttype,true);
						
					childparentNode.add(childNodeObj);
			 	}
			}
		}
		else
		{
			for(x=0;x<nodes[obj].totalCount;x++)
		 	{
		 		//alert(nodes[obj].nodes[x]['title']);
		 		childnode = nodes[obj].nodes[x]['title'];
		 		comments = nodes[obj].nodes[x]['comments'];
		 		site_prefix = nodes[obj].nodes[x]['site_prefix'];
				childpid = nodes[obj].nodes[x]['projectid'];
				childpath = nodes[obj].nodes[x]['path'];
				projectname = nodes[obj].nodes[x]['projectname'];
				childparentnode = nodes[obj].nodes[x]['parentnode'];
				childnodeid = nodes[obj].nodes[x]['nodeid'];
				hasfolder = nodes[obj].nodes[x]['hasfolder'];
				ppath = '|'+childpid+'/';
				
	
				title=childnode;
				imgsrc="";
					
				if(childpath!= -1)
					ppath =ppath+childpath;
				
				
				if(tree)
				{
					var childparentNode = tree.searchByNodeId(childparentnode)	
				}

				onclick = "setValue1('"+childpid+"','"+childnode+"','"+childpath+"');";
				var subprojecttype = (projecttype == 32 ? "sharedsubproject" : "subproject" );
				if(hasfolder=="true")
					childNodeObj = new w.WebFXTreeItem(title, onclick,'', '', imgsrc, imgsrc,childnodeid,ppath,'selectTreeproject',projectname,subprojecttype,true);	
				else
				{
					childNodeObj = new w.WebFXTreeItem(title, onclick,'', '', imgsrc, imgsrc,childnodeid,ppath,'project',projectname,subprojecttype);		
					notParentArr[notParentCount]=childNodeObj.id;
					notParentCount++;					
				}
				
				childparentNode.add(childNodeObj);
		 	}
		 	for(y=0;y<notParentCount;y++)
		 	{
				document.getElementById(notParentArr[y] + '-plus').src = webFXTreeConfig.blankIcon;
		 	}
		}	
	}
	if(parentNode.parentNode.text == "My Personal")
		{parentNode.parentNode.action = "setValue1('"+-1+"','My Personal','"+-1+"');";
		 parentNode.parentNode.actionup = "setValue1('"+-1+"','My Personal','"+-1+"');";}
	if (parentNode.folder) 
	{
		if (parentNode.open) { parentNode.collapse(); }
		else { parentNode.expand(); }
	}
	response = null;
	/*Ambigious::: it is done bc cookie get deleted when treecontrolfx creates multiple nodes. Tariq8Sep08*/
	 	var op = {"val":_sessionid_};
    	op = JSON.encode(op);
    	setCookie(_sessionid_, op); 
}
function CategoryNodeCallback(response)
{
	//debugger;
	notParentArr= new Array();
	notParentCount=0;
	response = eval(response.responseText);
	var nodeid = response[0]['nodeId'];
	var w;
	if(parent.parent.frames['IFControl'])
		w = parent.parent.frames['IFControl'];
	else
		w = parent.frames['IFControl'];
	var parentNode = w.crmTree.searchByNodeId(nodeid);
	var count = response[0]['totalCount'];
	var custnodes = response[0]['nodes'];
	
	obj="accounts";
	for(x=0;x<custnodes[obj].totalCount;x++)
 	{
 		//alert(nodes[obj].nodes[x]['title']);
 		childnode = custnodes[obj].nodes[x]['title'];
		projectid1 = custnodes[obj].nodes[x]['projectid'];
		path = custnodes[obj].nodes[x]['path'];
		projectname = custnodes[obj].nodes[x]['projectname'];
		childparentnode = custnodes[obj].nodes[x]['parentnode'];
		childnodeid = custnodes[obj].nodes[x]['nodeid'];
		childimgpath = custnodes[obj].nodes[x]['imgpath'];
		firstname = custnodes[obj].nodes[x]['firstname'];			
		catid = custnodes[obj].nodes[x]['catid'];
		canparent = custnodes[obj].nodes[x]['canparent'];
		

		var childparentNode = w.crmTree.searchByNodeId(childparentnode)	
		
		//childNodeObj = new w.WebFXTreeItem(childnode, onclick,onmouseup, '', childimgpath, childimgpath,childnodeid,'-1','','','',true);			
		
		//if(w.crmTree.searchByNodeId(childnodeid))
		//	continue;
		onclick = "";
		onmouseup = ""; 
		if(projectid1!=-1)
			custtitle = firstname+'('+childnode+')';
		else
			custtitle= childnode;
		
		if(canparent=="1")
			childNodeObj = new w.WebFXTreeItem(custtitle, onclick,onmouseup, '', childimgpath, childimgpath,childnodeid,catid,'questioncatnodes','','questioncat',true);	
		else
			childNodeObj = new w.WebFXTreeItem(custtitle, onclick,onmouseup, '', childimgpath, childimgpath,childnodeid,catid,'questioncatnodes','','questioncat');		
		childparentNode.add(childNodeObj);
		
		if(canparent!="1")
		{
				notParentArr[notParentCount]=childNodeObj.id;
				notParentCount++;
		}
 	}
 	if (parentNode.folder) 
	{
		if (parentNode.open) { parentNode.collapse(); }
		else { parentNode.expand(); }
	}
		
	for(y=0;y<notParentCount;y++)
 	{
		document.getElementById(notParentArr[y] + '-plus').src = webFXTreeConfig.blankIcon;
 	}
}
function CatalogNodeCallback(response)
{

	response = eval(response.responseText);
	var nodeid = response[0]['nodeId'];
	
	var w;
	if(parent.parent.frames['IFControl'])
		w = parent.parent.frames['IFControl'];
	else
		w = parent.frames['IFControl'];
	var parentNode = w.crmTree.searchByNodeId(nodeid);
	
	var nodeid = parentNode.id;
	//alert('Res:'+response[0]);
	if(response[0]['totalCount']>0)
		document.getElementById(nodeid + '-plus').src = webFXTreeConfig.lMinusIcon;
	else
		document.getElementById(nodeid + '-plus').src = webFXTreeConfig.blankIcon;
	
	var count = response[0]['totalCount'];
	var nodes = response[0]['nodes'];
	
	var projectType = response[0]['type'];
	
 	// to display list of cust if exist
 	var custcount = response[0]['custtotalCount'];
	var custnodes = response[0]['custnodes'];
 	obj="project";

 	for(x=0;x<custnodes[obj].totalCount;x++)
	 	{
	 		//alert(nodes[obj].nodes[x]['title']);
	 		childnode = custnodes[obj].nodes[x]['title'];
			projectid1 = custnodes[obj].nodes[x]['projectid'];
			path = custnodes[obj].nodes[x]['path'];
			projectname = custnodes[obj].nodes[x]['projectname'];
			childparentnode = custnodes[obj].nodes[x]['parentnode'];
			childnodeid = custnodes[obj].nodes[x]['nodeid'];
			childimgpath = custnodes[obj].nodes[x]['imgpath'];
			firstname = custnodes[obj].nodes[x]['firstname'];			
			
	
			var childparentNode = w.crmTree.searchByNodeId(childparentnode)	
			
			//childNodeObj = new w.WebFXTreeItem(childnode, onclick,onmouseup, '', childimgpath, childimgpath,childnodeid,'-1','','','',true);			
			
			if(w.crmTree.searchByNodeId(childnodeid))
				continue;
			if(projectid1==-1 && path==-1)
				onclick = "parent.LoadAjaxScreen('showcustomerlist&type=64');";
			else
				onclick = "parent.LoadAjaxScreen('showcustomertask&projectId="+projectid1+"&custname="+childnode+"');";
			onmouseup = ""; 
			if(projectid1!=-1)
				custtitle = firstname+'('+childnode+')';
			else
				custtitle= childnode;
			
			childNodeObj = new w.WebFXTreeItem(custtitle, onclick,onmouseup, '', childimgpath, childimgpath,childnodeid,'-1','customernodes','','',true);	
			childparentNode.add(childNodeObj);
			
			if(projectid1!=-1 )
			{
				onclick = "parent.LoadAjaxScreen('showorderlist&pname="+childnode+"&pid="+projectid1+"')";
				onmouseup = "";
				orderNodeId = "Orders--"+childnode;
				ordNodeObj = new w.WebFXTreeItem("Orders", onclick,onmouseup, '', 'images/treeimg/order.jpg', 'images/treeimg/order.jpg',orderNodeId,'-1','','','',true);	
				childNodeObj.add(ordNodeObj);
			}
	 	}
	 	if (parentNode.folder) 
		{
			if (parentNode.open) { parentNode.collapse(); }
			else { parentNode.expand(); }
		}
		response = null;
}
function CustNodeCallback(response)
{
	//debugger;
	response = eval(response.responseText);
	var nodeid = response[0]['nodeId'];
	
	var w;
	if(parent.parent.frames['IFControl'])
		w = parent.parent.frames['IFControl'];
	else
		w = parent.frames['IFControl'];
	var parentNode = w.crmTree.searchByNodeId(nodeid);
	
	var nodeid = parentNode.id;
	if(response[0]['totalCount']>0)
	{
		document.getElementById(nodeid + '-plus').src = webFXTreeConfig.lMinusIcon;
	}
	else
	{
		document.getElementById(nodeid + '-plus').src = webFXTreeConfig.blankIcon;
	}
	
	var count = response[0]['totalCount'];
	var nodes = response[0]['nodes'];
	
	var projectType = response[0]['type'];
	
 	// to display list of cust if exist
 	var custcount = response[0]['custtotalCount'];
	var custnodes = response[0]['custnodes'];
 	obj="project";
 	
 	for(x=0;x<custnodes[obj].totalCount;x++)
	 	{
	 	
	 		//alert(nodes[obj].nodes[x]['title']);
	 		childnode = custnodes[obj].nodes[x]['title'];
			projectid1 = custnodes[obj].nodes[x]['projectid'];
			path = custnodes[obj].nodes[x]['path'];
			projectname = custnodes[obj].nodes[x]['projectname'];
			childparentnode = custnodes[obj].nodes[x]['parentnode'];
			childnodeid = custnodes[obj].nodes[x]['nodeid'];
			childimgpath = custnodes[obj].nodes[x]['imgpath'];
			firstname = custnodes[obj].nodes[x]['firstname'];			
			
	
			var childparentNode = w.crmTree.searchByNodeId(childparentnode)	
			
			//childNodeObj = new w.WebFXTreeItem(childnode, onclick,onmouseup, '', childimgpath, childimgpath,childnodeid,'-1','','','',true);			
			
			if(w.crmTree.searchByNodeId(childnodeid))
				continue;
			if(projectid1==-1 && path==-1)
				onclick = "parent.LoadAjaxScreen('showcustomerlist&type=64');";
			else
				onclick = "parent.LoadAjaxScreen('showcustomertask&projectId="+projectid1+"&custname="+childnode+"');";
			onmouseup = ""; 
			if(projectid1!=-1)
				custtitle = firstname+'('+childnode+')';
			else
				custtitle= childnode;
			
			childNodeObj = new w.WebFXTreeItem(custtitle, onclick,onmouseup, '', childimgpath, childimgpath,childnodeid,'-1','customernodes','','',true);	
			childparentNode.add(childNodeObj);
			
			if(projectid1!=-1 )
			{
				onclick = "parent.LoadAjaxScreen('showorderlist&pname="+childnode+"&pid="+projectid1+"')";
				onmouseup = "";
				orderNodeId = "Orders--"+childnode;
				ordNodeObj = new w.WebFXTreeItem("Orders", onclick,onmouseup, '', 'images/treeimg/order.jpg', 'images/treeimg/order.jpg',orderNodeId,'-1','','','',true);	
				childNodeObj.add(ordNodeObj);
			}
	 	}
	 	if (parentNode.folder) 
		{
			if (parentNode.open) { parentNode.collapse(); }
			else { parentNode.expand(); }
		}
		response = null;
}
function AccNodeCallback(response)
{
	//debugger;
	notParentArr= new Array();
	notParentCount=0;
	response = eval(response.responseText);
	var nodeid = response[0]['nodeId'];
	
	var w;
	if(parent.document.getElementById('IFControl'))
		w = parent.document.getElementById('IFControl').contentWindow;
	else
		w = parent.parent.document.getElementById('IFControl').contentWindow;
	var parentNode = w.crmTree.searchByNodeId(nodeid);
	
	var nodeid = parentNode.id;
	if(response[0]['totalCount']>0)
	{
		document.getElementById(nodeid + '-plus').src = webFXTreeConfig.lMinusIcon;
	}
	else
	{
		document.getElementById(nodeid + '-plus').src = webFXTreeConfig.blankIcon;
	}
	
	var count = response[0]['totalCount'];
	var nodes = response[0]['nodes'];
	var modalid = response[0]['modalId'];  
	var projectType = response[0]['type'];

 	// to display list of cust if exist
 	if(modalid==1) // customer node under sales
 	{
	 	var custcount = response[0]['custtotalCount'];
		var custnodes = response[0]['custnodes'];
	 	obj="project";
	
	
		//alert(nodes[obj].nodes[x]['title']);
		childnode = custnodes[obj].nodes[0]['title'];
		childparentnode = custnodes[obj].nodes[0]['parentnode'];
		childnodeid = custnodes[obj].nodes[0]['nodeid'];
		childimgpath = custnodes[obj].nodes[0]['imgpath'];
	
		var childparentNode = w.crmTree.searchByNodeId(childparentnode)	
		
		if(w.crmTree.searchByNodeId(childnodeid))
			return;
		onclick = "parent.LoadAjaxScreen('showcustomerlist&type=64');";
		onmouseup = ""; 
		custtitle= childnode;
		
		childNodeObj = new w.WebFXTreeItem(custtitle, onclick,onmouseup, '', childimgpath, childimgpath,childnodeid,'-1','customernodes','','',true);	
		childparentNode.add(childNodeObj);
 	}
 	else if(modalid==2) // customer node under buying
 	{
	 	var custcount = response[0]['custtotalCount'];
		var custnodes = response[0]['custnodes'];
	 	obj="project";
	
	
		//alert(nodes[obj].nodes[x]['title']);
		childnode = custnodes[obj].nodes[0]['title'];
		childparentnode = custnodes[obj].nodes[0]['parentnode'];
		childnodeid = custnodes[obj].nodes[0]['nodeid'];
		childimgpath = custnodes[obj].nodes[0]['imgpath'];
	
		var childparentNode = w.crmTree.searchByNodeId(childparentnode)	
		
		if(w.crmTree.searchByNodeId(childnodeid))
			return;
		onclick = "parent.LoadAjaxScreen('showsupplierlist&type=128');";
		onmouseup = ""; 
		custtitle= childnode;
		
		childNodeObj = new w.WebFXTreeItem(custtitle, onclick,onmouseup, '', childimgpath, childimgpath,childnodeid,'-1','customernodes','','',true);	
		childparentNode.add(childNodeObj);
 	}
 	else if(false && modalid==7) // node under system
 	{
 		var custcount = response[0]['custtotalCount'];
		var custnodes = response[0]['custnodes'];
	 	obj="project";
	
		for(var i=0; i<custnodes[obj].nodes.length; i++)
		{
			//alert(custnodes[obj].nodes[i]['title']);
			
			childnode = custnodes[obj].nodes[i]['title'];
			childparentnode = custnodes[obj].nodes[i]['parentnode'];
			childnodeid = custnodes[obj].nodes[i]['nodeid'];
			childimgpath = custnodes[obj].nodes[i]['imgpath'];
			childnodetype = custnodes[obj].nodes[i]['nodetype'];
			childnodescreenparam = custnodes[obj].nodes[i]['screenparam'];
			
			childparentNode = w.crmTree.searchByNodeId(childparentnode)	
			
			if(w.crmTree.searchByNodeId(childnodeid))
				return;
			onclick = "";
			onmouseup = ""; 
			producttitle= childnode;

			onclick = "parent.LoadAjaxScreen('"+childnodescreenparam+"');";	
				
			childNodeObj = new w.WebFXTreeItem(producttitle, onclick,onmouseup, '', childimgpath, childimgpath,childnodeid,'-1','catalognodes');	
			childparentNode.add(childNodeObj);
			
			notParentArr[notParentCount]=childNodeObj.id;
			notParentCount++;
		}
		/*//alert(nodes[obj].nodes[x]['title']);
		childnode = custnodes[obj].nodes[0]['title'];
		childparentnode = custnodes[obj].nodes[0]['parentnode'];
		childnodeid = custnodes[obj].nodes[0]['nodeid'];
		childimgpath = custnodes[obj].nodes[0]['imgpath'];
	
		var childparentNode = w.crmTree.searchByNodeId(childparentnode)	
		
		if(w.crmTree.searchByNodeId(childnodeid))
			return;
		onclick = "parent.LoadAjaxScreen('sharetaskrights');";
		onmouseup = ""; 
		custtitle= childnode;
		
		childNodeObj = new w.WebFXTreeItem(custtitle, onclick,onmouseup, '', childimgpath, childimgpath,childnodeid,'-1','customernodes','','',true);	
		childparentNode.add(childNodeObj);*/
 	}
 	else if(modalid==5) // Product,Category and Job nodes under infinishops
 	{
 		var custcount = response[0]['custtotalCount'];
		var custnodes = response[0]['custnodes'];
	 	obj="project";
		var childparentNode;
	
		//alert(nodes[obj].nodes[x]['title']);
		for(var i=0; i<custnodes[obj].nodes.length; i++)
		{
			//alert(custnodes[obj].nodes[i]['title']);
			
			childnode = custnodes[obj].nodes[i]['title'];
			childparentnode = custnodes[obj].nodes[i]['parentnode'];
			childnodeid = custnodes[obj].nodes[i]['nodeid'];
			childimgpath = custnodes[obj].nodes[i]['imgpath'];
			childnodetype = custnodes[obj].nodes[i]['nodetype'];
			childnodeajaxaction = custnodes[obj].nodes[i]['ajaxaction'];
			ajaxtype = custnodes[obj].nodes[i]['ajaxtype'];
			
			childparentNode = w.crmTree.searchByNodeId(childparentnode)	
			
			if(w.crmTree.searchByNodeId(childnodeid))
				return;
			onclick = "";
			onmouseup = ""; 
			producttitle= childnode;

			isParent=false;
			ajaxfoldertype = 'catalognodes';
			if(childnodetype == 'PRODUCT--')
				onclick = "parent.LoadAjaxScreen('showproductlist&type=64');";
			else if(childnodetype == 'JOB--')
				onclick = "parent.LoadAjaxScreen('showjoblist&type=64');";
			else if(childnodetype == 'CATEGORY--')
				onclick = "parent.LoadAjaxScreen('showcategorylist&type=64');";
			else if(childnodetype == 'EQUOTE--')
				onclick = "parent.LoadAjaxScreen('services&nodeid=67');";		
			else if(childnodetype == 'EPROC--')
				onclick = "parent.LoadAjaxScreen('services&nodeid=84');";						
			else
			{
				if(childnode == 'Affiliate')
					onclick = "parent.LoadAjaxScreen('services_new&nodeid=70');";	
					
				ajaxfoldertype = ajaxtype;
				isParent=true;

			}	
			childNodeObj = new w.WebFXTreeItem(producttitle, onclick,onmouseup, '', childimgpath, childimgpath,childnodeid,childnodeajaxaction,ajaxfoldertype,'','',isParent);	
			childparentNode.add(childNodeObj);
			
			if(isParent==false)
			{
				notParentArr[notParentCount]=childNodeObj.id;
				notParentCount++;
			}
		}
 	}
 	else if(modalid==3 & false) /// create node under products
 	{

 		var custcount = response[0]['custtotalCount'];
		var custnodes = response[0]['custnodes'];
	 	obj="project";
	
	
		//alert(nodes[obj].nodes[x]['title']);
		childnode = custnodes[obj].nodes[0]['title'];
		childparentnode = custnodes[obj].nodes[0]['parentnode'];
		childnodeid = custnodes[obj].nodes[0]['nodeid'];
		childimgpath = custnodes[obj].nodes[0]['imgpath'];
	
		var childparentNode = w.crmTree.searchByNodeId(childparentnode)	
		
		if(w.crmTree.searchByNodeId(childnodeid))
			return;
		onclick = "";
		onmouseup = ""; 
		producttitle= childnode;
		
		onclick = "parent.LoadAjaxScreen('showproductwizard');";
		childNodeObj = new w.WebFXTreeItem(producttitle, onclick,onmouseup, '', childimgpath, childimgpath,childnodeid,'-1','catalognodes','','');	
		childparentNode.add(childNodeObj);
		
		isParent = false;
		if(isParent==false)
		{
			notParentArr[notParentCount]=childNodeObj.id;
			notParentCount++;
		}
 	}			
	obj="accounts";
	//debugger;
	
	for(x=0;x<nodes[obj].totalCount;x++)
 	{
 		//alert(nodes[obj].nodes[x]['title']);
 		childnode = nodes[obj].nodes[x]['title'];
		childurl = nodes[obj].nodes[x]['url'];
		childpath = nodes[obj].nodes[x]['path'];
		projectname = nodes[obj].nodes[x]['projectname'];
		childparentnode = nodes[obj].nodes[x]['parentnode'];
		childnodeid = nodes[obj].nodes[x]['nodeid'];
		childimgpath = nodes[obj].nodes[x]['imgpath'];

		var childparentNode = w.crmTree.searchByNodeId(childparentnode)	
		
		if(w.crmTree.searchByNodeId(childnodeid))
			continue;
		onclick = "parent.LoadAjaxScreen('accountservices&url="+childurl+"');";
		onmouseup = ""; 
		childNodeObj="";
		//childNodeObj = new w.WebFXTreeItem(childnode, onclick,onmouseup, '', childimgpath, childimgpath,childnodeid,'-1','','','',true);	
		childNodeObj = new w.WebFXTreeItem(childnode, onclick,onmouseup, '', childimgpath, childimgpath,childnodeid,'-1');	
		childparentNode.add(childNodeObj);
		if(childNodeObj.canParentNode!=true)
		{
			notParentArr[notParentCount]=childNodeObj.id;
			notParentCount++;
		}
 	}
 	
	if (parentNode.folder) 
	{
		if (parentNode.open) { parentNode.collapse(); }
		else { parentNode.expand(); }
	}
//this code is written to expand all the nodes which are not the parent node
	for(y=0;y<notParentCount;y++)
 	{
		document.getElementById(notParentArr[y] + '-plus').src = webFXTreeConfig.blankIcon;
 	}
 	response = null;
}
function AddTreeNodeCallback(response)
{
	//debugger;
	response = eval(response.responseText);
	var nodeid = response[0]['nodeId'];
		
	var w;
	var tree;
	if(webFXTreeConfig.caller == "documentTree" || webFXTreeConfig.caller == "broadcastTree")
	{
		w = window;
	}
	else
	{
		if(parent.document.getElementById('IFControl'))
			w = parent.document.getElementById('IFControl').contentWindow;
		else
			w = parent.parent.document.getElementById('IFControl').contentWindow;
	}
	
	if(w.tree)
	{
		tree = w.tree;
		var parentNode = w.tree.searchByNodeId(nodeid);
	}
	else if	(w.crmTree)
	{	
		tree = w.crmTree;
		var parentNode = w.crmTree.searchByNodeId(nodeid);
	}
	
	var nodeid = parentNode.id;
	var count = response[0]['totalCount'];
	var nodes = response[0]['nodes'];
	var projectType = response[0]['type'];
	notParentArr= new Array();
	notParentCount=0;
		
	if(response[0]['totalCount']>0)
	{
		document.getElementById(nodeid + '-plus').src = webFXTreeConfig.lMinusIcon;
	}
	else
	{
		document.getElementById(nodeid + '-plus').src = webFXTreeConfig.blankIcon;
	}
	
	if(nodes != null)
	{
		//var obj = (nodes["project"].totalCount > 0 ? "project" : (nodes["SupplierProducts"].totalCount > 0 ? "SupplierProducts" : (nodes["My Shared"].totalCount > 0 ? "My Shared" : '')))
		var obj='';
		if(nodes["project"] != null && typeof(nodes["project"]) != 'undefined')
		{
			if(nodes["project"].totalCount > 0)
			{
				obj = "project";
			} 
		}
		else if(nodes["SupplierProducts"] != null && typeof(nodes["SupplierProducts"]) != 'undefined')
		{
			if(nodes["SupplierProducts"].totalCount > 0)
			{
				obj = "SupplierProducts";
			}
		}
	
		if(obj == '')
		{
			for (var obj in nodes)
			{
				rootnode = nodes[obj].title;
				rootpid = nodes[obj].projectid;
				rootpath = nodes[obj].path;
				rootparentnode = nodes[obj].parentnode;
				rootnodeid = nodes[obj].nodeid;
				rootparentid = nodes[obj].parentnode;
				
				projecttype = nodes[obj].type;
				ownerid = nodes[obj].ownerid;
				branchid = nodes[obj].branchid;
				companyid = nodes[obj].companyid;
				ownername = "Projects List";
				
				var parentNode = tree.searchByNodeId(rootparentid)	
				
				onclick = "";//"LoadAjaxScreen('showorder&name="+orderid+"&projectid="+projectid+"&path="+orderPath+"&display=order&crmtype="+ordCons+"');";
				
				if(!tree.searchByNodeId(rootnodeid))
				{
				//onclick ="javascript:window.top.frames['IFControl'].frames['operationsarea'].projectList('"+projecttype+"','"+ownerid+"','"+branchid+"','"+companyid+"','"+ownername+"');";
					if(webFXTreeConfig.caller == "documentTree" || webFXTreeConfig.caller == "broadcastTree")
					{
						onclick ="";
					}
					else
					{
						if(projecttype == 32)
						{
							onclick = "";
						}
						else
						{
							onclick ="LoadAjaxScreen('showprojects&projectType="+projecttype+"&projectUserId="+ownerid+"&projectBranchId="+branchid+"&projectCompanyId="+companyid+"&projectTitle="+ownername+" Projects&list=true')";
						}
					}
					onmouseup1="";
					parNodeObj = new w.WebFXTreeItem(rootnode, onclick, onmouseup1, '', 'images/treeimg/projects.png', 'images/treeimg/projects.png',rootnodeid,'-1','','',projecttype,true);	
					//alert("bb:"+parentNode.id+'||'+parNodeObj.id);	
					parentNode.add(parNodeObj);
				}
				else
					tree.searchByNodeId(rootnodeid).toggle();
			// for(x=0;x<=10;x++)	
	
			 for(x=0;x<nodes[obj].totalCount;x++)
			 	
			 	{
			 	//	alert(nodes[obj].nodes[x]['title']);
	
			 		childnode = nodes[obj].nodes[x]['title'];
					childpid = nodes[obj].nodes[x]['projectid'];
					childpath = nodes[obj].nodes[x]['path'];
					childparentnode = nodes[obj].nodes[x]['parentnode'];
					childnodeid = nodes[obj].nodes[x]['nodeid'];
					hasfolder = nodes[obj].nodes[x]['hasfolder'];
					ppath = '|'+childpid+'/';
			 		projectname = childnode;
			 		childNodeObj = "";
			 		
					if(childpath!= -1)
						ppath =ppath+childpath+'/';
					var childparentNode = tree.searchByNodeId(childparentnode)	
					
					if(tree.searchByNodeId(childnodeid))
						continue;
					/*old oonclick b4 ajax
					onclick = "javascript:window.top.frames['IFControl'].frames['operationsarea'].ShowProjectItems('"+projectname+"','',0,'','"+childpid+"','"+childpath+"','1');";
					*/
					if(webFXTreeConfig.caller == "documentTree")
					{
						onclick = "LoadAjaxScreen('chatprojectdocument&projectid="+childpid+"&projectpath="+childpath+"&projectTitle="+projectname+"&page=0',{onSuccess:ShowDocumentCallBack});";
						onmouseup1 = "";
						childNodeObj = new w.WebFXTreeItem(childnode, onclick, onmouseup1, '', 'images/treeimg/projects_list.png', 'images/treeimg/projects_list.png',childnodeid,ppath,"project",childnode,projecttype,true);
					}	
					else if(webFXTreeConfig.caller == "broadcastTree")
					{
						onclick = "LoadAjaxScreen('chatprojectdocument&readonly=true&projectid="+childpid+"&projectpath="+childpath+"&projectTitle="+projectname+"&page=0',{onSuccess:ShowDocumentCallBack});";
						onmouseup1 = "";
						childNodeObj = new w.WebFXTreeItem(childnode, onclick, onmouseup1, '', 'images/treeimg/projects_list.png', 'images/treeimg/projects_list.png',childnodeid,ppath,"project",childnode,projecttype,true);
					}	
					else
					{
						if(parent.parent.document.getElementById('IFControl'))
						  onmouseup1 = "javascript:parent.parent.document.getElementById('IFControl').contentWindow.moveContents('"+childpid+"','"+childpath+"','"+projecttype+"');"; 
						else
						 onmouseup1 = "javascript:parent.document.getElementById('IFControl').contentWindow.moveContents('"+childpid+"','"+childpath+"','"+projecttype+"');";
						if(projecttype == 32)
						{
							onclick = "LoadAjaxScreen('showdocuments&projectid="+childpid+"&projectpath="+childpath+"&projectTitle="+projectname+"&page=0');";
							if(hasfolder)
								childNodeObj = new w.WebFXTreeItem(childnode, onclick, onmouseup1, '', 'images/treeimg/projects_list.png', 'images/treeimg/projects_list.png',childnodeid,ppath,"project",childnode,projecttype,true);
							else
								childNodeObj = new w.WebFXTreeItem(childnode, onclick, onmouseup1, '', 'images/treeimg/projects_list.png', 'images/treeimg/projects_list.png',childnodeid,ppath,"project",childnode,projecttype);
						}
						else
						{
							onclick = "LoadAjaxScreen('showprojects&projectid="+childpid+"&projectpath="+childpath+"&projectTitle="+projectname+"&page=0');";
							if(hasfolder=="true")
								childNodeObj = new w.WebFXTreeItem(childnode, onclick, onmouseup1, '', 'images/treeimg/projects_list.png', 'images/treeimg/projects_list.png',childnodeid,ppath,"project",childnode,projecttype,true);
							else
							{	
								childNodeObj = new w.WebFXTreeItem(childnode, onclick, onmouseup1, '', 'images/treeimg/projects_list.png', 'images/treeimg/projects_list.png',childnodeid,ppath,"project",childnode,projecttype);
								notParentArr[notParentCount]=childNodeObj.id;
								notParentCount++;
							}
						}
						
					}
					 				
					childparentNode.add(childNodeObj);
			 	}
			 	for(y=0;y<notParentCount;y++)
			 	{
					document.getElementById(notParentArr[y] + '-plus').src = webFXTreeConfig.blankIcon;
			 	}
			}
		}
		else
		{
			for(x=0;x<nodes[obj].totalCount;x++)
		 	{
		 		//alert(nodes[obj].nodes[x]['title']);
		 		childnode = nodes[obj].nodes[x]['title'];
		 		comments = nodes[obj].nodes[x]['comments'];
		 		site_prefix = nodes[obj].nodes[x]['site_prefix'];
				childpid = nodes[obj].nodes[x]['projectid'];
				childpath = nodes[obj].nodes[x]['path'];
				projectname = nodes[obj].nodes[x]['projectname'];
				childparentnode = nodes[obj].nodes[x]['parentnode'];
				childnodeid = nodes[obj].nodes[x]['nodeid'];
				hasfolder = nodes[obj].nodes[x]['hasfolder'];
				ppath = '|'+childpid+'/';
				
				
				if(parent.parent.document.getElementById('IFControl'))
					onmouseup1 = "javascript:parent.parent.document.getElementById('IFControl').contentWindow.moveContents('"+childpid+"','"+childpath+"','"+projecttype+"');"; 
				else
					onmouseup1 = "javascript:parent.document.getElementById('IFControl').contentWindow.moveContents('"+childpid+"','"+childpath+"','"+projecttype+"');";
	
				if(site_prefix=='crm.')
				{
					if(projecttype == 32)
						title = childnode;
					else
						title=comments;
					imgsrc = "/images/treeimg/products.jpg";
					onclick ="LoadAjaxScreen('showdocuments&tab=no&projectid="+childpid+"&projectpath="+childpath+"&product=yes')";
					childNodeObj = new w.WebFXTreeItem(childnode, onclick, onmouseup1, '', 'images/treeimg/projects_list.png', 'images/treeimg/projects_list.png',childnodeid,ppath,"project",childnode,projecttype,true);
				}
				else
				{
					title=childnode;
					imgsrc="";
					if(webFXTreeConfig.caller == "documentTree" || webFXTreeConfig.caller == "broadcastTree")
					{
						w = window;
						onmouseup1 = "";
						onclick = "LoadAjaxScreen('chatprojectdocument&projectid="+childpid+"&projectpath="+childpath+"&projectTitle="+projectname+"&page=0',{onSuccess:ShowDocumentCallBack});";
						childNodeObj = new w.WebFXTreeItem(childnode, onclick, onmouseup1, '', 'images/treeimg/projects_list.png', 'images/treeimg/projects_list.png',childnodeid,ppath,"project",childnode,projecttype,true);
					}
					else
					{
						if(projecttype == 32)
						{
							onclick = "LoadAjaxScreen('showdocuments&projectid="+childpid+"&projectpath="+childpath+"&projectTitle="+projectname+"&page=0');";
						}
						else
						{
							onclick = "LoadAjaxScreen('showprojects&projectid="+childpid+"&projectpath="+childpath+"&projectTitle="+projectname+"&page=0');";
						}
						
					}					
				}
				if(childpath!= -1)
					ppath =ppath+childpath;
				
				
				if(tree)
				{
					var childparentNode = tree.searchByNodeId(childparentnode)	
					
					//if(tree.searchByNodeId(childnodeid))
						//continue;
				}
				else if(w.crmTree)
				{
					var childparentNode = w.crmTree.searchByNodeId(childparentnode)	
					
					if(w.crmTree.searchByNodeId(childnodeid))
						continue;
				}

				var subprojecttype = (projecttype == 32 ? "sharedsubproject" : "subproject" );
				if(hasfolder=="true")
					childNodeObj = new w.WebFXTreeItem(title, onclick,onmouseup1, '', imgsrc, imgsrc,childnodeid,ppath,'project',projectname,subprojecttype,true);	
				else
				{
					childNodeObj = new w.WebFXTreeItem(title, onclick,onmouseup1, '', imgsrc, imgsrc,childnodeid,ppath,'project',projectname,subprojecttype);		
					notParentArr[notParentCount]=childNodeObj.id;
					notParentCount++;					
				}
				childparentNode.add(childNodeObj);
		 	}
		 	for(y=0;y<notParentCount;y++)
		 	{
				document.getElementById(notParentArr[y] + '-plus').src = webFXTreeConfig.blankIcon;
		 	}
		}	
	}
	
	if (parentNode.folder) 
	{
		if (parentNode.open) { parentNode.collapse(); }
		else { parentNode.expand(); }
	}
	response = null;
	/*Ambigious::: it is done bc cookie get deleted when treecontrolfx creates multiple nodes. Tariq8Sep08*/
	 	var op = {"val":_sessionid_};
    	op = JSON.encode(op);
    	setCookie(_sessionid_, op); 

}

function ReportError()
{
	alert('Error');
}
function ContextMenu(nodeType,path,nodeId)
{
//alert(nodeType+'|'+path+'|'+nodeId);
//debugger;
	if(nodeType=='undefined' || nodeType=="")
		return;
	
	
	if(path !="-1" && nodeType!="questioncat" )
	{
		
		var p = path.split('|');
		var p1 =p[1].split('/');
		var pid= p1[0];
		
		p = path.split('|'+pid+'/');
		var parentPath = p[1].toString();
		if(parentPath=="")
			parentPath =-1;
	}
	else
		parentPath = path;
		//parentPath=path;		

		cleanContextMenu();
		var deleteItemActive = false;
		if(nodeType=="project")
		{
			//alert('nodeId='+nodeId+';nodeType='+nodeType+':prpath='+path+'pid:'+pid+'parentpath'+parentPath);
			createContextItem("Upload File",function(){parent.OpenWizard("/misc/uploadfiles.php?projectid="+pid+"&projectpath="+parentPath+"&nodeType="+nodeType+"&path="+path,"no",0.4,0.35,"url");},deleteItemActive);
			createContextItem("Add Sub Project",function(){parent.OpenWizard("addsubproject&projectId="+pid+"&path="+path+"&nodeId="+nodeId+"&nodeType="+nodeType,"no",.35,.25);},deleteItemActive);
			createContextSeperator();
			createContextItem('Manage Rights',function(){EditRights(pid)},deleteItemActive);
			createContextSeperator();
			createContextItem("Project Blog",function(){StartBlog(pid,-1)},deleteItemActive);
			createContextItem("Delete Project",function(){DeleteItem('project',pid,-1,nodeId);},deleteItemActive);
		}
		else if(nodeType=="questioncat")
		{
			createContextItem("View Questions",function(){ViewQuestions(path);},deleteItemActive);
			createContextItem("Add New category",function(){AddCategory(path);},deleteItemActive);
			createContextItem("Add New Question",function(){AddQuestion(path);},deleteItemActive);
			createContextSeperator();
		}		
		else if(nodeType=="mainproject")
		{
			//alert('nodeId='+nodeId+';nodeType='+nodeType+'path='+path+'pid:'+pid);
			createContextItem("Add Project",function(){parent.OpenWizard("addproject&type=1&nodeId="+nodeId+"&nodeType="+nodeType,"no",.35,.25);;},deleteItemActive);
			createContextSeperator();
		}
		else if(nodeType==17 && path == "-1") //personal path=-1
		{
			//alert('nodeId='+nodeId+';nodeType='+nodeType+'ppath='+path+'pid:'+pid);
			createContextItem("Add Personal Project",function(){parent.OpenWizard("addproject&type=1&nodeId="+nodeId+"&nodeType="+nodeType,"no",.35,.25);;},deleteItemActive);
		}
		else if (nodeType==17) //default or subproject
		{
			/*
			createContextItem("Upload File",function(){parent.OpenWizard("/misc/uploadfiles.php?projectid="+pid+"&projectpath="+parentPath+"&nodeType="+nodeType+"&path="+path,"no",0.4,0.35,"url");},deleteItemActive);
			createContextItem("Add Sub Project",function(){parent.OpenWizard("addsubproject&projectId="+pid+"&path="+path+"&nodeId="+nodeId+"&nodeType="+nodeType+"&projectpath="+parentPath,"no",.35,.25);},deleteItemActive);
			createContextItem('Project Blog',function(){StartBlog(pid,parentPath)},deleteItemActive);
			createContextSeperator();
			*/
			createContextItem("Upload File",function(){parent.OpenWizard("/misc/uploadfiles.php?projectid="+pid+"&projectpath="+parentPath+"&nodeType="+nodeType+"&path="+path,"no",0.4,0.35,"url");},deleteItemActive);
			createContextItem("Add Sub Project",function(){parent.OpenWizard("addsubproject&projectId="+pid+"&path="+path+"&nodeId="+nodeId+"&nodeType="+nodeType,"no",.35,.25);},deleteItemActive);
			createContextSeperator();
			createContextItem('Manage Rights',function(){EditRights(pid)},deleteItemActive);
			createContextSeperator();
			createContextItem("Project Blog",function(){StartBlog(pid,-1)},deleteItemActive);
			createContextItem("Delete Project",function(){DeleteItem('project',pid,-1,nodeId);},deleteItemActive);
			if(parentPath!=-1)
				createContextItem("Delete Sub Project",function(){DeleteItem('subproject',pid,parentPath,nodeId);},deleteItemActive);	
		}
		else if(nodeType==32) //personal+default
		{
			//alert('nodeId='+nodeId+';nodeType='+nodeType+'ppath='+path+'pid:'+pid);
			//createContextItem("Add Shared Project",function(){parent.OpenWizard("addproject&type=1&nodeId="+nodeId+"&nodeType="+nodeType,"no",.35,.25);;},deleteItemActive);
			createContextItem("Upload File",function(){parent.OpenWizard("/misc/uploadfiles.php?projectid="+pid+"&projectpath="+parentPath+"&nodeType="+nodeType+"&path="+path,"no",0.4,0.35,"url");},deleteItemActive);
			createContextItem("Add Sub Project",function(){parent.OpenWizard("addsubproject&projectId="+pid+"&path="+path+"&nodeId="+nodeId+"&nodeType="+nodeType+"&projectpath="+parentPath,"no",.35,.25);},deleteItemActive);
		}
		else if(nodeType==2)//department
		{
			//alert('nodeId='+nodeId+';nodeTpye='+nodeType+'path='+path);
			if(path!=-1)
			{
				createContextItem("Upload File",function(){parent.OpenWizard("/misc/uploadfiles.php?projectid="+pid+"&projectpath="+parentPath+"&nodeType="+nodeType+"&path="+path,"no",0.4,0.35,"url");},deleteItemActive);
				createContextItem("Add Sub Project",function(){parent.OpenWizard("addsubproject&projectId="+pid+"&path="+path+"&nodeId="+nodeId+"&nodeType="+nodeType,"no",.35,.25);},deleteItemActive);
				createContextSeperator();
				createContextItem('Manage Rights',function(){EditRights(pid)},deleteItemActive);
				createContextSeperator();
				createContextItem("Project Blog",function(){StartBlog(pid,-1)},deleteItemActive);
				createContextItem("Delete Project",function(){DeleteItem('project',pid,-1,nodeId);},deleteItemActive);
			}
			else
				createContextItem("Add Global Project",function(){parent.OpenWizard("addproject&type=2&nodeId="+nodeId+"&nodeType="+nodeType,"no",.35,.25);;},deleteItemActive);
		}
		else if(nodeType=="subproject" )
		{
			createContextItem("Upload File",function(){parent.OpenWizard("/misc/uploadfiles.php?projectid="+pid+"&projectpath="+parentPath+"&nodeType="+nodeType+"&path="+path,"no",0.4,0.35,"url");},deleteItemActive);
			createContextItem("Add Sub Project",function(){parent.OpenWizard("addsubproject&projectId="+pid+"&path="+path+"&nodeId="+nodeId+"&nodeType="+nodeType+"&projectpath="+parentPath,"no",.35,.25);},deleteItemActive);
			createContextItem('Project Blog',function(){StartBlog(pid,parentPath)},deleteItemActive);
			createContextSeperator();
	
			if(parentPath!=-1)
				createContextItem("Delete Sub Project",function(){DeleteItem('subproject',pid,parentPath,nodeId);},deleteItemActive);
		}
		else if(nodeType=="sharedsubproject")
		{
			//createContextItem("Upload File",function(){parent.OpenWizard("/misc/uploadfiles.php?projectid="+pid+"&projectpath="+parentPath+"&path="+path,"no",0.4,0.35,"url");},deleteItemActive);
			createContextItem("Add Sub Project",function(){parent.OpenWizard("addsubproject&projectId="+pid+"&path="+path+"&nodeId="+nodeId+"&nodeType="+32+"&projectpath="+parentPath,"no",.35,.25);},deleteItemActive);
			createContextItem("Upload File",function(){parent.OpenWizard("/misc/uploadfiles.php?projectid="+pid+"&projectpath="+parentPath+"&nodeType="+32+"&path="+path,"no",0.4,0.35,"url");},deleteItemActive);
			//createContextItem('Project Blog',function(){StartBlog(pid,parentPath)},deleteItemActive);
			createContextSeperator();
	
			//if(parentPath!=-1)
			//	createContextItem("Delete SubProject",function(){DeleteItem('subproject',pid,parentPath,nodeId);},deleteItemActive);
		}
		else if(nodeType=="productnodes" )
		{
			//alert('nodeId='+nodeId+';nodeTpye='+nodeType);
			createContextSeperator();
			createContextItem("Add Sub Project",function(){parent.OpenWizard("addsubproject&projectId="+pid+"&path="+path+"&nodeId="+nodeId+"&nodeType="+nodeType,"no",.35,.25);},deleteItemActive);
			createContextItem("Add New Step",function(){Publish(pid,parentPath);});
		}
		else if(nodeType=="4" )
		{
			//alert('agaya');
//			alert('nodeId='+nodeId+';nodeTpye='+nodeType);
			//createContextSeperator();
			createContextItem("Create New Page",function(){parent.OpenWizard("addnewwebpage&projectId="+pid+"&path="+path+"&nodeId="+nodeId+"&nodeType="+nodeType+"&projectpath="+parentPath,"no",.30,.15);},deleteItemActive);
		}
		showContextMenu();
}
function EditRights(pid)
{
	parent.LoadAjaxScreen("editprojectrights&pid="+pid);
}
function StartBlog(pid,parentPath)
{
	var o = new Array(pid,parentPath,parent.parent._sessionid_);
	o = JSON.encode(o);		 		
	
	var pars = 'param='+o;
	var url = "index.php?object=task&function=StartBlog&isajaxcall=1&returnType=string";


	var myAjax = new Ajax.Request( url,
		{ method: 'post', parameters: pars, onFailure: ReportError , onSuccess: BlogCallback});	
}
function BlogCallback(response)
{
	o = eval(response.responseText);
	
	if(o[0]["errorcode"]== 100 || o[0]["errorcode"]== 0)	// 0 = success and 100= already exists
	{
		var pid = o[0]["pid"];
		var path = o[0]["path"];
		LoadAjaxScreen("showprojects&taskType=4&type=4&divName=showtaskdetails&projectid="+pid+"&projectpath="+path+"&page=0");
	}
}
function Publish(pid,parentPath)
{
	parent.parent.OpenWizard("addstep&projectId="+pid+"&path="+parentPath,"",.35,.2);
	/*
	var o = new Array(parent.parent._sessionid_);

	o = JSON.encode(o);		 		
	var pars = 'param='+o;
	var url = "index.php?object=project&function=Publish&isajaxcall=1";

	statusgif = "&nbsp;<img src='images/misc/waitstatus.gif' height=13px align=absmiddle>&nbsp;";
	parent.document.getElementById('waitgif').innerHTML=statusgif;

	var myAjax = new Ajax.Request( url,
		{ method: 'post', parameters: pars, onFailure: ReportError , onSuccess: DeleteCallback});		
	*/
}

function DeleteItem(type,pid,parentPath,nodeId)
{
	if(parentPath != -1)
	{
		msg = 'Are you sure you want to delete sub-project ?';
    	if (!confirm(msg))
			return;
    }
	else
	{
		msg = 'Are you sure you want to delete Project?';
    	if (!confirm(msg))
			return;
	}
	var o = new Array(type,pid,parentPath,nodeId,parent.parent._sessionid_);

	o = JSON.encode(o);		 		
	var pars = 'param='+o;
	var url = "index.php?object=project&function=Delete&isajaxcall=1";

	var myAjax = new Ajax.Request( url,
		{ method: 'post', parameters: pars, onFailure: ReportError , onSuccess: DeleteCallback});		
}

function DeleteCallback(response)
{
	//debugger;
	response = eval(response.responseText);
	
	if(response[0]["code"]<0)
	{
		alert(response[0]["errordesc"]);
		return;
	}
	var nodeid = response[0]['nodeid'];
	var path = response[0]['path'];
	if(path==-1)
		strlist="list=true";
	else	
		strlist="list=false";
	var w;
	if(parent.parent.document.getElementById('IFControl'))
		w = parent.parent.document.getElementById('IFControl');
	else
		w = parent.document.getElementById('IFControl');
	
	var node = w.tree.searchByNodeId(nodeid);
	if(!node)
		return;
	
	var pnode = w.tree.searchByNodeId(node.parentNode.nodeId);
	
	pnode._collapsechild();
	node._removeallchild();
	node.remove();
	var ajaxUrl = "index.php?SCREEN=showprojects&sid=" + _sessionid_ +"&projectid="+response[0]['projectid']+"&projectpath=&projectTitle=Project List&="+strlist;

	//var url = "http://" + parent.IFControl.location.host + "/index.php?SCREEN=navigate&sid=" + _sessionid_ +"&divScreen=showprojects&projectid="+pid+"&projectpath=&list=true&projectTitle=Project List";
	var op = {"url":ajaxUrl};

	op = JSON.encode(op);
	setCookie("last_ajax_action", op);

	LoadAjaxScreen('showprojects&projectid='+response[0]['projectid']+'	&projectpath=&projectTitle=&page=0&'+strlist);
}//<script>
//////////////////
// Helper Stuff //
//////////////////

// used to find the Automation server name
function getDomDocumentPrefix() {
	if (getDomDocumentPrefix.prefix)
		return getDomDocumentPrefix.prefix;
	
	var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
	var o;
	for (var i = 0; i < prefixes.length; i++) {
		try {
			// try to create the objects
			o = new ActiveXObject(prefixes[i] + ".DomDocument");
			return getDomDocumentPrefix.prefix = prefixes[i];
		}
		catch (ex) {};
	}

	throw new Error("Could not find an installed XML parser");
}

function getXmlHttpPrefix() {
	if (getXmlHttpPrefix.prefix)
		return getXmlHttpPrefix.prefix;

	var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
	var o;
	for (var i = 0; i < prefixes.length; i++) {
		try {
			// try to create the objects
			o = new ActiveXObject(prefixes[i] + ".XmlHttp");
			return getXmlHttpPrefix.prefix = prefixes[i];
		}
		catch (ex) {};
	}
	
	throw new Error("Could not find an installed XML parser");
}

//////////////////////////
// Start the Real stuff //
//////////////////////////


// XmlHttp factory
function XmlHttp() {}

XmlHttp.create = function () {
	try {
		if (window.XMLHttpRequest) {
			var req = new XMLHttpRequest();

			// some versions of Moz do not support the readyState property
			// and the onreadystate event so we patch it!
			if (req.readyState == null) {
				req.readyState = 1;
				req.addEventListener("load", function () {
					req.readyState = 4;
					if (typeof req.onreadystatechange == "function")
						req.onreadystatechange();
				}, false);
			}
			
			return req;
		}
		if (window.ActiveXObject) {
			return new ActiveXObject(getXmlHttpPrefix() + ".XmlHttp");
		}
	}
	catch (ex) {}
	// fell through
	throw new Error("Your browser does not support XmlHttp objects");
};

// XmlDocument factory
function XmlDocument() {}

XmlDocument.create = function () {
	try {
		// DOM2
		if (document.implementation && document.implementation.createDocument) {
			var doc = document.implementation.createDocument("", "", null);
			
			// some versions of Moz do not support the readyState property
			// and the onreadystate event so we patch it!
			if (doc.readyState == null) {
				doc.readyState = 1;
				doc.addEventListener("load", function () {
					doc.readyState = 4;
					if (typeof doc.onreadystatechange == "function")
						doc.onreadystatechange();
				}, false);
			}
			
			return doc;
		}
		if (window.ActiveXObject)
			return new ActiveXObject(getDomDocumentPrefix() + ".DomDocument");
	}
	catch (ex) {}
	throw new Error("Your browser does not support XmlDocument objects");
};

// Create the loadXML method and xml getter for Mozilla
if (window.DOMParser &&
	window.XMLSerializer &&
	window.Node && Node.prototype && Node.prototype.__defineGetter__) {

	// XMLDocument did not extend the Document interface in some versions
	// of Mozilla. Extend both!
	XMLDocument.prototype.loadXML = 
	Document.prototype.loadXML = function (s) {
		
		// parse the string to a new doc	
		var doc2 = (new DOMParser()).parseFromString(s, "text/xml");
		
		// remove all initial children
		while (this.hasChildNodes())
			this.removeChild(this.lastChild);
			
		// insert and import nodes
		for (var i = 0; i < doc2.childNodes.length; i++) {
			this.appendChild(this.importNode(doc2.childNodes[i], true));
		}
	};
	
	
	/*
	 * xml getter
	 *
	 * This serializes the DOM tree to an XML String
	 *
	 * Usage: var sXml = oNode.xml
	 *
	 */
	// XMLDocument did not extend the Document interface in some versions
	// of Mozilla. Extend both!
	XMLDocument.prototype.__defineGetter__("xml", function () {
		return (new XMLSerializer()).serializeToString(this);
	});
	Document.prototype.__defineGetter__("xml", function () {
		return (new XMLSerializer()).serializeToString(this);
	});
}/*
 * This script was created by Erik Arvidsson (erik(at)eae.net)
 * for WebFX (http://webfx.eae.net)
 * Copyright 2001
 * 
 * For usage see license at http://webfx.eae.net/license.html
 *
 * Version: 1.0
 * Created: 2001-09-27
 * Updated: 2002-01-19	Added some simple error handling and string templates
 *						for reporting the errors
 *			2002-01-28	Fixed loading issues in IE50 and IE55 that made the tree
 *						load twice
 *
 * Dependencies: xtree.js - original xtree library
 *               xtree.css - simple css styling of xtree
 *               xmlextras.js - provides xml http objects and xml document objects
 *
 *	Usage:
 *
 *    <script type="text/javascript" src="xmlextras.js"></script>
 *    <script type="text/javascript" src="xtree.js"></script>
 *    <script type="text/javascript" src="xloadtree.js"></script>
 *    <link type="text/css" rel="stylesheet" href="xtree.css" />
 *
 */

//<script>	Stupid InterDev

webFXTreeConfig.loadingText = "Loading...";
webFXTreeConfig.loadErrorTextTemplate = "Error loading \"%1%\"";
webFXTreeConfig.emptyErrorTextTemplate = "Error \"%1%\" does not contain any tree items";

function WebFXLoadTree(sText, sXmlSrc, sAction, sBehavior, sIcon, sOpenIcon) {
	// call super
	this.WebFXTree = WebFXTree;
	this.WebFXTree(sText, sAction, sBehavior, sIcon, sOpenIcon);
	
	// setup default property values
	this.src = sXmlSrc;
	this.loading = false;
	this.loaded = false;
	this.errorText = "";
	
	// check start state and load if open
	if (this.open)
		_startLoadXmlTree(this.src, this);
	else {
		// and create loading item if not
		this._loadingItem = new WebFXTreeItem(webFXTreeConfig.loadingText);
		this.add(this._loadingItem);
	}
}
WebFXLoadTree.prototype = new WebFXTree;

// override the expand method to load the xml file
WebFXLoadTree.prototype._webfxtree_expand = WebFXTree.prototype.expand;
WebFXLoadTree.prototype.expand = function() {
	if (!this.loaded && !this.loading) {
		// load
		_startLoadXmlTree(this.src, this);
	}
	this._webfxtree_expand();
};
 function WebFXLoadTreeItem(sText, sXmlSrc, sAction, sActionUp, eParent, sIcon, sOpenIcon) {
	// call super
	this.WebFXTreeItem = WebFXTreeItem;
	this.WebFXTreeItem(sText, sAction, sActionUp, eParent, sIcon, sOpenIcon);

	// setup default property values
	this.src = sXmlSrc;
	this.loading = false;
	this.loaded = false;
	this.errorText = "";
	
	// check start state and load if open
	if (this.open)
		_startLoadXmlTree(this.src, this);
	else {
		// and create loading item if not
		this._loadingItem = new WebFXTreeItem(webFXTreeConfig.loadingText);
		this.add(this._loadingItem);
	}
}
WebFXLoadTreeItem.prototype = new WebFXTreeItem;

// override the expand method to load the xml file
WebFXLoadTreeItem.prototype._webfxtreeitem_expand = WebFXTreeItem.prototype.expand;
WebFXLoadTreeItem.prototype.expand = function() {
	if (!this.loaded && !this.loading) {
		// load
		_startLoadXmlTree(this.src, this);
	}
	this._webfxtreeitem_expand();
};
 // creates the xmlhttp object and starts the load of the xml document
function _startLoadXmlTree(sSrc, jsNode) {
	if (jsNode.loading || jsNode.loaded)
		return;
	jsNode.loading = true;
	var xmlHttp = XmlHttp.create();
	xmlHttp.open("GET", sSrc, true);	// async
	xmlHttp.onreadystatechange = function () {
		if (xmlHttp.readyState == 4)
			_xmlFileLoaded(xmlHttp.responseXML, jsNode);
	};
	// call in new thread to allow ui to update
	window.setTimeout(function () {
		xmlHttp.send(null);
	}, 10);
}


// Converts an xml tree to a js tree. See article about xml tree format
function _xmlTreeToJsTree(oNode) {
	// retreive attributes
	var text = oNode.getAttribute("text");
    var action = oNode.getAttribute("action");
    var actionup = oNode.getAttribute("onMouseUp");
	var parent = null;
	var icon = oNode.getAttribute("icon");
	var openIcon = oNode.getAttribute("openIcon");
	var src = oNode.getAttribute("src");

	// create jsNode
	var jsNode;
	if (src != null && src != "")
		jsNode = new WebFXLoadTreeItem(text, src, action, actionup, parent, icon, openIcon);
	else
		jsNode = new WebFXTreeItem(text, action, actionup, parent, icon, openIcon);

	// go through childNOdes
	var cs = oNode.childNodes;
	var l = cs.length;
	for (var i = 0; i < l; i++) {
		if (cs[i].tagName == "tree")
			jsNode.add( _xmlTreeToJsTree(cs[i]), true );
	}
	
	return jsNode;
}

// Inserts an xml document as a subtree to the provided node
function _xmlFileLoaded(oXmlDoc, jsParentNode) {
	if (jsParentNode.loaded)
		return;

	var bIndent = false;
	var bAnyChildren = false;
	jsParentNode.loaded = true;
	jsParentNode.loading = false;

	// check that the load of the xml file went well
	if( oXmlDoc == null || oXmlDoc.documentElement == null) {
		jsParentNode.errorText = parseTemplateString(webFXTreeConfig.loadErrorTextTemplate,
							jsParentNode.src);
	}
	else {
		// there is one extra level of tree elements
		var root = oXmlDoc.documentElement;

		// loop through all tree children
		var cs = root.childNodes;
		var l = cs.length;
		for (var i = 0; i < l; i++) {
			if (cs[i].tagName == "tree") {
				bAnyChildren = true;
				bIndent = true;
				jsParentNode.add( _xmlTreeToJsTree(cs[i]), true);
			}
		}

		// if no children we got an error
		if (!bAnyChildren)
			jsParentNode.errorText = parseTemplateString(webFXTreeConfig.emptyErrorTextTemplate,
										jsParentNode.src);
	}
	
	// remove dummy
	if (jsParentNode._loadingItem != null) {
		jsParentNode._loadingItem.remove();
		bIndent = true;
	}
	
	if (bIndent) {
		// indent now that all items are added
		jsParentNode.indent();
	}
	
	// show error in status bar
	if (jsParentNode.errorText != "")
		window.status = jsParentNode.errorText;
}

// parses a string and replaces %n% with argument nr n
function parseTemplateString(sTemplate) {
	var args = arguments;
	var s = sTemplate;
	
	s = s.replace(/\%\%/g, "%");
	
	for (var i = 1; i < args.length; i++)
		s = s.replace( new RegExp("\%" + i + "\%", "g"), args[i] )
	
	return s;
}// ---------------------------------------------------------------------------
// this script is copyright (c) 2001 by Michael Wallner!
// http://www.wallner-software.com
// mailto:dhtml@wallner-software.com
//
// you may use this script on web pages of your own
// you must not remove this copyright note!
//
// Sie dürfen dieses Script auf Ihren Webseiten verwenden
// Sie dürfen diesen Copyright Hinweis jedoch nicht entfernen!
// ---------------------------------------------------------------------------


// ---------------------------------------------------------------------------
//                 crossbrowser DHTML functions version 1.0
//
// supported browsers:  IE4, IE5, NS4, NS6, MOZ, OP5
// ---------------------------------------------------------------------------


//get browser info
//ermittle den verwendeten Browser
//Unterstutzt IE4, IE5, IE6?, NS4, NS6, Mozilla5 und Opera5
//(Achtung op5 kann sich auch als NS oder IE ausgeben!)
function xbrowserType() {
  this.name = navigator.appName;
  this.version = navigator.appVersion;			        //Version string
  this.dom=document.getElementById?1:0			                //w3-dom
  this.op5=(this.name.indexOf("Opera") > -1 && (this.dom))?1:0	 //Opera Browser
  this.ie4=(document.all && !this.dom)?1:0			           //ie4
  this.ie5=(this.dom && this.version.indexOf("MSIE ") > -1)?1:0	     //IE5, IE6?
  this.ns4=(document.layers && !this.dom)?1:0			           //NS4
  this.ns5=(this.dom && this.version.indexOf("MSIE ") == -1)?1:0 //NS6, Mozilla5

  //test if op5 telling "i'm ie..." (works because op5 doesn't support clip)
  //testen ob sich ein op5 als ie5 'ausgibt' (funktioniert weil op5 kein clip
  //unterstutzt)
  if (this.ie4 || this.ie5) {
    document.write('<DIV id=testOpera style="position:absolute; visibility:hidden">TestIfOpera5</DIV>');
    if (document.all['testOpera'].style.clip=='rect()') {
      this.ie4=0;
      this.ie5=0;
      this.op5=1;
    }
  }

  this.ok=(this.ie4 || this.ie5 || this.ns4 || this.ns5 || this.op5) //any DHTML
  eval ("bt=this");
}
xbrowserType();


//crossbrowser replacement for getElementById (find ns4 sublayers also!)
//ersetzte 'getElementById' (findet auch sublayers in ns4)
function getObj(obj){
//do not use 'STYLE=' attribut in <DIV> tags for NS4!
//zumindest beim NS 4.08 dürfen <DIV> Tags keine 'STYLE=' Angabe beinhalten
//sonst werden die restlichen Layers nicht gefunden! class= ist jedoch erlaubt!

  //search layer for ns4
  //Recursive Suche nach Layer für NS4
  function getRefNS4(doc,obj){
    var fobj=0;
    var c=0
      while (c < doc.layers.length) {
        if (doc.layers[c].name==obj) return doc.layers[c];
	fobj=getRefNS4(doc.layers[c].document,obj)
	if (fobj != 0) return fobj
	c++;
      }
      return 0;
  }

  return (bt.dom)?document.getElementById(obj):(bt.ie4)?
         document.all[obj]:(bt.ns4)?getRefNS4(document,obj):0
}


//get the actual browser window size
//ermittle die größe der Browser Anzeigefläche
//op5 supports offsetXXXX ans innerXXXX but offsetXXXX only after pageload!
//op5 unterstützt sowohl innerXXXX als auch offsetXXXX aber offsetXXXX erst
//nach dem vollständigen Laden der Seite!
function createPageSize(){
  this.width=(bt.ns4 || bt.ns5 || bt.op5)?innerWidth:document.body.offsetWidth;
  this.height=(bt.ns4 || bt.ns5 || bt.op5)?innerHeight:document.body.offsetHeight;
  return this;
}
var screenSize = new createPageSize();

//create a crossbrowser layer object
function createLayerObject(name) {
  this.name=name;
  this.obj=getObj(name);
  this.css=(bt.ns4)?obj:obj.style;
  this.x=parseInt(this.css.left);
  this.y=parseInt(this.css.top);
  this.show=b_show;
  this.hide=b_hide;
  this.moveTo=b_moveTo;
  this.moveBy=b_moveBy;
  this.writeText=b_writeText;
  return this;
}
  
//crossbrowser show
function b_show(){
//  this.visibility='visible'
  this.css.visibility='visible';
}

//crossbrowser hide
function b_hide(){
//  this.visibility='hidden'
  this.css.visibility='hidden';
}

//crossbrowser move absolute
function b_moveTo(x,y){
  this.x = x;
  this.y = y;
  this.css.left=x;
  this.css.top=y;
}

//crossbrowser move relative
function b_moveBy(x,y){
  this.moveTo(this.x+x, this.y+y)
}

//write text into a layer (not supported by Opera 5!)
//this function is not w3c-dom compatible but ns6
//support innerHTML also!
//Opera 5 does not support change of layer content!!
function b_writeText(text) {
   if (bt.ns4) {
     this.obj.document.write(text);
     this.obj.document.close();
   }
   else {
     this.obj.innerHTML=text;
   }
}
/* This notice must be untouched at all times.

wz_dragdrop.js    v. 4.55
The latest version is available at
http://www.walterzorn.com
or http://www.devira.com
or http://www.walterzorn.de

Copyright (c) 2002-2003 Walter Zorn. All rights reserved.
Created 26. 8. 2002 by Walter Zorn (Web: http://www.walterzorn.com )
Last modified: 23. 5. 2004

This DHTML & Drag&Drop Library adds Drag&Drop functionality
to the following types of html-elements:
- images, even if not positioned via layers,
  nor via stylesheets or any other kind of "hard-coding"
- relatively and absolutely positioned layers (DIV elements).
Moreover, it provides extended DHTML abilities.

This program 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 program 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
at http://www.gnu.org/copyleft/gpl.html for more details.
*/


// PATH TO THE TRANSPARENT 1*1 PX IMAGE (required by NS 4 as spacer)
var spacer = 'transparentpixel.gif';




//window.onerror = new Function('return true;');


// Optional commands passed to SET_DHTML() on the html-page (g: may be applied globally, i: individually)
var CLONE            = 'C10nE';   // i  img      clone image
var COPY             = 'C0pY';    // i  img      create copies
var DETACH_CHILDREN  = 'd37aCH';  // i  lyr      detach images
var HORIZONTAL       = 'H0r1Z';   // i  img,lyr  horizontally draggable only
var MAXHEIGHT        = 'm7x8I';   // i  img,lyr  maximum height limit, "
var MAXOFFBOTTOM     = 'm7xd0wN'; // i  img,lyr  downward offset limit
var MAXOFFLEFT       = 'm7x23Ft'; // i  img,lyr  leftward offset limit
var MAXOFFRIGHT      = 'm7x0Ff8'; // i  img,lyr  rightward offset limit
var MAXOFFTOP        = 'm7xu9';   // i  img,lyr  upward offset limit
var MAXWIDTH         = 'm7xW1';   // i  img,lyr  maximum width limit, use with resizable or scalable
var MINWIDTH         = 'm1nw1';   // i  img,lyr  minimum width limit, "
var MINHEIGHT        = 'm1n8I';   // i  img,lyr  minimum height limit, "
var NO_ALT           = 'no81T';   // gi img      disable alt and title attributes
var NO_DRAG          = 'N0d4Ag';  // i  img,lyr  disable draggability
var RESET_Z          = 'r35E7z';  // gi img,lyr  reset z-index when dropped
var RESIZABLE        = 'r5IZbl';  // gi img,lyr  resizable if <ctrl> or <shift> pressed
var SCALABLE         = 'SCLbl';   // gi img,lyr  scalable           "
var SCROLL           = 'sC8lL';   // gi img,lyr  enable auto scroll functionality
var VERTICAL         = 'V3Rt1C';  // i  img,lyr  vertically draggable only

var dd_cursors = new Array(
	'c:default',
	'c:crosshair',
	'c:e-resize',
	'c:hand',
	'c:help',
	'c:move',
	'c:n-resize',
	'c:ne-resize',
	'c:nw-resize',
	'c:s-resize',
	'c:se-resize',
	'c:sw-resize',
	'c:text',
	'c:w-resize',
	'c:wait'
);
var dd_i = dd_cursors.length; while(dd_i--)
	eval('var CURSOR_' + (dd_cursors[dd_i].substring(2).toUpperCase().replace('-', '_')) + ' = "' + dd_cursors[dd_i] + '";');



function WZDD()
{
	this.n = navigator.userAgent.toLowerCase();
	this.db = (document.compatMode && document.compatMode.toLowerCase() != "backcompat")?
		document.documentElement
		: (document.body || null);
	this.op = !!(window.opera && document.getElementById);
	this.op6 = !!(this.op && !(this.db && this.db.innerHTML));
	if (this.op && !this.op6) document.onmousedown = new Function('e',
		'if (((e = e || window.event).target || e.srcElement).tagName == "IMAGE") return false;'
	);
	this.ie = !!(this.n.indexOf("msie") >= 0 && document.all && this.db && !this.op);
	this.iemac = !!(this.ie && this.n.indexOf("mac") >= 0);
	this.ie4 = !!(this.ie && !document.getElementById);
	this.n4 = !!(document.layers && typeof document.classes != "undefined");
	this.n6 = !!(typeof window.getComputedStyle != "undefined" && typeof document.createRange != "undefined");
	this.w3c = !!(!this.op && !this.ie && !this.n6 && document.getElementById);
	this.ce = !!(document.captureEvents && document.releaseEvents);
	this.px = (this.n4 || this.op6)? '' : 'px';
}
var dd = new WZDD();

dd.Int = function(d_x, d_y)
{
	return isNaN(d_y = parseInt(d_x))? 0 : d_y;
};

dd.getWndW = function()
{
	return dd.Int(
		(dd.db && !dd.op && !dd.w3c && dd.db.clientWidth)? dd.db.clientWidth
		: (window.innerWidth || 0)
	);
};

dd.getWndH = function()
{
	return dd.Int(
		(dd.db && !dd.op && !dd.w3c && dd.db.clientHeight)? dd.db.clientHeight
		: (window.innerHeight || 0)
	);
};

dd.getScrollX = function()
{
	return dd.Int(window.pageXOffset || (dd.db? dd.db.scrollLeft : 0));
};

dd.getScrollY = function()
{
	return dd.Int(window.pageYOffset || (dd.db? dd.db.scrollTop : 0));
};

dd.getPageXY = function(d_o)
{
	if (dd.n4 && d_o)
	{
		dd.x = d_o.pageX || 0;
		dd.y = d_o.pageY || 0;
	}
	else
	{
		dd.x = dd.y = 0; //global helper vars
		while (d_o)
		{
			dd.x += dd.Int(d_o.offsetLeft);
			dd.y += dd.Int(d_o.offsetTop);
			d_o = d_o.offsetParent || null;
		}
	}
};

dd.getCssXY = function(d_o)
{
	if (d_o.div)
	{
		if (dd.n4)
		{
			d_o.cssx = d_o.div.x;
			d_o.cssy = d_o.div.y;
		}
		else if (dd.ie4)
		{
			d_o.cssx = d_o.css.pixelLeft;
			d_o.cssy = d_o.css.pixelTop;
		}
		else
		{
			d_o.css.left = d_o.css.top = 0 + dd.px;
			dd.getPageXY(d_o.div);
			d_o.cssx = d_o.x - dd.x;
			d_o.cssy = d_o.y - dd.y;
			d_o.css.left = d_o.cssx + dd.px;
			d_o.css.top = d_o.cssy + dd.px;
		}
	}
	else
	{
		d_o.cssx = 0;
		d_o.cssy = 0;
	}
};

dd.getImgW = function(d_o)
{
	return d_o? dd.Int(d_o.width) : 0;
};

dd.getImgH = function(d_o)
{
	return d_o? dd.Int(d_o.height) : 0;
};

dd.getDivW = function(d_o)
{
	return dd.Int(
		dd.n4? (d_o.div? d_o.div.clip.width : 0)
		: d_o.div? (d_o.div.offsetWidth || d_o.css.pixelWidth || d_o.css.width || 0)
		: 0
	);
};

dd.getDivH = function(d_o)
{
	return dd.Int(
		dd.n4? (d_o.div? d_o.div.clip.height : 0)
		: d_o.div? (d_o.div.offsetHeight || d_o.css.pixelHeight || d_o.css.height || 0)
		: 0
	);
};

dd.getWH = function(d_o)
{
	d_o.w = dd.getDivW(d_o);
	d_o.h = dd.getDivH(d_o);
	if (d_o.css)
	{
		d_o.css.width = d_o.w + dd.px;
		d_o.css.height = d_o.h + dd.px;
		d_o.dw = dd.getDivW(d_o)-d_o.w;
		d_o.dh = dd.getDivH(d_o)-d_o.h;
		d_o.css.width = (d_o.w-d_o.dw) + dd.px;
		d_o.css.height = (d_o.h-d_o.dh) + dd.px;
	}
	else d_o.dw = d_o.dh = 0;
};

dd.getCssProp = function(d_o, d_pn6, d_pstyle, d_pn4)
{
	if (d_o && dd.n6) return ''+window.getComputedStyle(d_o, null).getPropertyValue(d_pn6);
	if (d_o && d_o.currentStyle) return ''+eval('d_o.currentStyle.'+d_pstyle);
	if (d_o && d_o.style) return ''+eval('d_o.style.'+d_pstyle);
	if (d_o && dd.n4) return ''+eval('d_o.'+d_pn4);
	return '';
};

dd.getDiv = function(d_x, d_d)
{
	d_d = d_d || document;
	if (dd.n4)
	{
		if (d_d.layers[d_x]) return d_d.layers[d_x];
		for (var d_i = d_d.layers.length; d_i--;)
		{
			var d_y = dd.getDiv(d_x, d_d.layers[d_i].document);
			if (d_y) return d_y;
		}
	}
	if (dd.ie) return d_d.all[d_x] || null;
	if (d_d.getElementById) return d_d.getElementById(d_x) || null;
	return null;
};

dd.getImg = function(d_o, d_nm, d_xy, d_w)
{
	d_w = d_w || window;
	var d_img;
	if ((d_img = d_w.document.images[d_nm]) && d_img.name == d_nm)
	{
		if (d_xy)
		{
			if (dd.n4)
			{
				dd.getPageXY(d_w);
				d_o.defx = d_img.x + dd.x;
				d_o.defy = d_img.y + dd.y;
			}
			else
			{
				dd.getPageXY(d_img);
				d_o.defx = dd.x;
				d_o.defy = dd.y;
			}
		}
		return d_img;
	}
	if (dd.n4) for (var d_i = d_w.document.layers.length; d_i--;)
	{
		var d_y = dd.getImg(d_o, d_nm, d_xy, d_w.document.layers[d_i]);
		if (d_y) return d_y;
	}
	return null;
};

dd.getParent = function(d_o)
{
	if (dd.n4)
	{
		for (var d_p, d_i = dd.elements.length; d_i--;)
		{
			if (!((d_p = dd.elements[d_i]).is_image) && d_p.div && (d_p.div.document.layers[d_o.name] || d_o.oimg && d_p.div.document.images[d_o.oimg.name]))
				d_p.addChild(d_o, d_p.detach, 1);
		}
	}
	else
	{
		var d_p = d_o.is_image? dd.getImg(d_o, d_o.oimg.name) : (d_o.div || null);
		while (d_p && !!(d_p = d_p.offsetParent || d_p.parentNode || null))
		{
			if (d_p.ddObj)
			{
				d_p.ddObj.addChild(d_o, d_p.ddObj.detach, 1);
				break;
			}
		}
	}
};

dd.getCmd = function(d_o, d_cmd, d_cmdStr)
{
	var d_i = d_o.id.indexOf(d_cmd), d_j,
	d_y = (d_i >= 0)*1;
	if (d_y)
	{
		d_j = d_i+d_cmd.length;
		if (d_cmdStr) d_o.cmd += d_o.id.substring(d_i, d_j);
		d_o.id = d_o.id.substring(0, d_i) + d_o.id.substring(d_j);
	}
	return d_y;
};

dd.getCmdVal = function(d_o, d_cmd, d_cmdStr, int0)
{
	var d_i = d_o.id.indexOf(d_cmd), d_j,
	d_y = (d_o.id.indexOf(d_cmd) >= 0)? dd.Int(d_o.id.substring(d_o.id.indexOf(d_cmd)+d_cmd.length)) : int0? -1 : 0;
	if (!int0 && d_y || int0 && d_y >= 0)
	{
		d_j = d_i+d_cmd.length+d_y.toString().length;
		if (d_cmdStr) d_o.cmd += d_o.id.substring(d_i, d_j);
		d_o.id = d_o.id.substring(0, d_i) + d_o.id.substring(d_j);
	}
	return d_y;
};

dd.addElt = function(d_o, d_p)
{
	dd.elements[dd.elements.length] = dd.elements[d_o.name] = d_o;
	if (d_p) d_p.copies[d_p.copies.length] = d_p.copies[d_o.name] = d_o;
};

dd.mkWzDom = function()
{
	var d_i = dd.elements.length; while(d_i--) dd.getParent(dd.elements[d_i]);
	d_i = dd.elements.length; while(d_i--)
		d_o = dd.elements[d_i];
		if (d_o.children && !d_o.parent)
		{
			var d_j = d_o.children.length; while(d_j--)
				d_o.children[d_j].setZ(d_o.z+d_o.children[d_j].z, 1);
		}
};

dd.addProps = function(d_o)
{
	var d_i, d_c;
	if (d_o.is_image)
	{
		d_o.div = dd.getDiv(d_o.id);
		if (d_o.div && typeof d_o.div.style != "undefined") d_o.css = d_o.div.style;
		d_o.nimg = (dd.n4 && d_o.div)? d_o.div.document.images[0] : (document.images[d_o.id+'NImG'] || null);
		if (!d_o.noalt && !dd.noalt)
		{
			d_o.nimg.alt = d_o.oimg.alt || '';
			if (d_o.oimg.title) d_o.nimg.title = d_o.oimg.title;
		}
		d_o.bgColor = '';
	}
	else
	{
		d_o.bgColor = dd.getCssProp(d_o.div, 'background-color','backgroundColor','bgColor').toLowerCase();
		if (dd.n6 && d_o.div)
		{
			if ((d_c = d_o.bgColor).indexOf('rgb') >= 0)
			{
				d_c = d_c.substring(4, d_c.length-1).split(',');
				d_o.bgColor = '#';
				for (var d_i = 0; d_i < d_c.length; d_i++) d_o.bgColor += parseInt(d_c[d_i]).toString(0x10);
			}
			else d_o.bgColor = d_c;
		}
	}
	if (dd.scalable) d_o.scalable = d_o.resizable^1;
	else if (dd.resizable) d_o.resizable = d_o.scalable^1;
	d_o.setZ(d_o.defz);
	d_o.cursor = d_o.cursor || dd.cursor || 'auto';
	d_o._setCrs(d_o.nodrag? 'auto' : d_o.cursor);
	d_o.visible = true;
};

dd.initz = function()
{
	if (!(dd && (dd.n4 || dd.n6 || dd.ie || dd.op || dd.w3c))) return;
	if (dd.op6) WINSZ(2);
	else if (dd.n6 || dd.ie || dd.op && !dd.op6 || dd.w3c) dd.recalc(1);
	var d_drag = (document.onmousemove == DRAG),
	d_resize = (document.onmousemove == RESIZE);
	if (dd.loadFunc) dd.loadFunc();
	if (d_drag && document.onmousemove != DRAG) dd.setEvtHdl(1, DRAG);
	else if (d_resize && document.onmousemove != RESIZE) dd.setEvtHdl(1, RESIZE);
	if ((d_drag || d_resize) && document.onmouseup != DROP) dd.setEvtHdl(2, DROP);
	dd.setEvtHdl(0, PICK);
};

dd.finlz = function()
{
	if (dd.ie && dd.elements)
	{
		var d_i = dd.elements.length; while (d_i--)
			dd.elements[d_i].del();
	}
};

dd.setEvtHdl = function(d_typ, d_func)
{
	if (!d_typ)
	{
		if (document.onmousedown != d_func) dd.downFunc = document.onmousedown || null;
		document.onmousedown = d_func;
	}
	else if (d_typ&1)
	{
		if (document.onmousemove != d_func) dd.moveFunc = document.onmousemove || null;
		document.onmousemove = d_func;
	}
	else
	{
		if (document.onmouseup != d_func) dd.upFunc = document.onmouseup || null;
		document.onmouseup = d_func;
	}
	if (dd.ce)
	{
		var d_e = (!d_typ)? Event.MOUSEDOWN : (d_typ&1)? Event.MOUSEMOVE : Event.MOUSEUP;
		d_func? document.captureEvents(d_e) : document.releaseEvents(d_e);
	}
};

dd.evt = function(d_e)
{
	this.but = (this.e = d_e || window.event).which || this.e.button || 0;
	this.button = (this.e.type == 'mousedown')? this.but
		: (dd.e && dd.e.button)? dd.e.button
		: 0;
	this.src = this.e.target || this.e.srcElement || null;
	this.src.tag = (this.src.tagName || this.src).toString().toLowerCase();
	this.x = dd.Int(this.e.pageX || this.e.clientX || 0);
	this.y = dd.Int(this.e.pageY || this.e.clientY || 0);
	if (dd.ie)
	{
		this.x += dd.getScrollX() - (dd.ie && !dd.iemac)*1;
		this.y += dd.getScrollY() - (dd.ie && !dd.iemac)*1;
	}
	this.modifKey = this.e.modifiers? (this.e.modifiers&Event.SHIFT_MASK || this.e.modifiers&Event.CONTROL_MASK)
		: (this.e.shiftKey || this.e.ctrlKey || false);
};

dd.recalc = function(d_x)
{
	if (dd.elements)
	{
		var d_o, d_i = dd.elements.length; while(d_i--)
		{
			if (!(d_o = dd.elements[d_i]).is_image && d_o.div)
			{
				dd.getWH(d_o);
				if (d_o.div.pos_rel)
				{
					dd.getPageXY(d_o.div);
					var d_dx = dd.x - d_o.x, d_dy = dd.y - d_o.y;
					d_o.defx += d_dx;
					d_o.x += d_dx;
					d_o.defy += d_dy;
					d_o.y += d_dy;
					var d_p, d_j = d_o.children.length; while(d_j--)
					{
						if (!(d_p = d_o.children[d_j]).detached && (d_o != d_p.defparent || !(d_p.is_image && dd.getImg(d_p, d_p.oimg.name, 1))))
						{
							d_p.defx += d_dx;
							d_p.defy += d_dy;
							d_p.moveBy(d_dx, d_dy);
						}
					}
				}
			}
			else if (d_o.is_image && !dd.op6 && !dd.n4)
			{
				if (dd.n6 && d_x && !d_o.defw) d_o.resizeTo(d_o.defw = dd.getImgW(d_o.oimg), d_o.defh = dd.getImgH(d_o.oimg));
				var d_defx = d_o.defx, d_defy = d_o.defy;
				if (!(d_o.parent && d_o.parent != d_o.defparent) && (d_x || !d_o.detached || d_o.horizontal || d_o.vertical) && dd.getImg(d_o, d_o.oimg.name, 1))
					d_o.moveBy(d_o.defx-d_defx, d_o.defy-d_defy);
			}
		}
	   }
};



function WINSZ(d_x)
{
	if (d_x)
	{
		if (dd.n4 || dd.op6 && d_x&2)
		{
			dd.iW = innerWidth;
			dd.iH = innerHeight;
			if (dd.op6) setTimeout("WINSZ()", 0x1ff);
		}
		window.onresize = new Function('WINSZ();');
	}
	else if ((dd.n4 || dd.op6) && (innerWidth != dd.iW || innerHeight != dd.iH)) location.reload();
	else if (dd.op6) setTimeout("WINSZ()", 0x1ff);
	else if (!dd.n4) setTimeout('dd.recalc()', 0xa);
}
WINSZ(1);



function DDObj(d_o, d_i)
{
	this.id = d_o;
	this.cmd = '';
	this.cpy_n = dd.getCmdVal(this, COPY);
	this.maxoffb = dd.getCmdVal(this, MAXOFFBOTTOM, 0, 1);
	this.maxoffl = dd.getCmdVal(this, MAXOFFLEFT, 0, 1);
	this.maxoffr = dd.getCmdVal(this, MAXOFFRIGHT, 0, 1);
	this.maxofft = dd.getCmdVal(this, MAXOFFTOP, 0, 1);
	var d_j = dd_cursors.length; while(d_j--)
		if (dd.getCmd(this, dd_cursors[d_j], 1)) this.cursor = dd_cursors[d_j].substring(2);
	this.clone = dd.getCmd(this, CLONE, 1);
	this.detach = dd.getCmd(this, DETACH_CHILDREN);
	this.scalable = dd.getCmd(this, SCALABLE, 1);
	this.horizontal = dd.getCmd(this, HORIZONTAL);
	this.noalt = dd.getCmd(this, NO_ALT, 1);
	this.nodrag = dd.getCmd(this, NO_DRAG);
	this.scroll = dd.getCmd(this, SCROLL, 1);
	this.resizable = dd.getCmd(this, RESIZABLE, 1);
	this.re_z = dd.getCmd(this, RESET_Z, 1);
	this.vertical = dd.getCmd(this, VERTICAL);
	this.maxw = dd.getCmdVal(this, MAXWIDTH, 1, 1);
	this.minw = Math.abs(dd.getCmdVal(this, MINWIDTH, 1, 1));
	this.maxh = dd.getCmdVal(this, MAXHEIGHT, 1, 1);
	this.minh = Math.abs(dd.getCmdVal(this, MINHEIGHT, 1, 1));

	this.name = this.id + (d_i || '');
	this.oimg = dd.getImg(this, this.id, 1);
	this.is_image = !!this.oimg;
	this.copies = new Array();
	this.children = new Array();
	this.parent = this.original = null;
	if (this.oimg)
	{
		this.id += 'div' + (d_i || '');
		this.w = dd.getImgW(this.oimg);
		this.h = dd.getImgH(this.oimg);
		this.dw = this.dh = 0;
		this.defz = dd.Int(dd.getCssProp(this.oimg, 'z-index','zIndex','zIndex')) || 1;
		this.defsrc = this.src = this.oimg.src;
		this.htm = '<img name="' + this.id + 'NImG"'+
			' src="' + this.oimg.src + '" '+
			'width="' + this.w + '" height="' + this.h + '">';
		this.t_htm = '<div id="' + this.id +
			'" style="position:absolute;'+
			'left:' + (this.cssx = this.x = this.defx) + 'px;'+
			'top:' + (this.cssy = this.y = this.defy) + 'px;'+
			'width:' + this.w + 'px;'+
			'height:' + this.h + 'px;">'+
			this.htm + '<\/div>';
	}
	else
	{
		if (!!(this.div = dd.getDiv(this.id)) && typeof this.div.style != "undefined") this.css = this.div.style;
		dd.getWH(this);
		if (this.div)
		{
			this.div.ddObj = this;
			this.div.pos_rel = ((this.div.parentNode? this.div.parentNode.tagName : this.div.parentElement? this.div.parentElement.tagName : '').toString().toLowerCase().indexOf('body') < 0);
		}
		dd.getPageXY(this.div);
		this.defx = this.x = dd.x;
		this.defy = this.y = dd.y;
		dd.getCssXY(this);
		this.defz = dd.Int(dd.getCssProp(this.div, 'z-index','zIndex','zIndex'));
	}
	this.defw = this.w || 0;
	this.defh = this.h || 0;
}

DDObj.prototype.moveBy = function(d_x, d_y, d_kds, d_o)
{
	if (!this.div) return;
	this.x += (d_x = dd.Int(d_x));
	this.y += (d_y = dd.Int(d_y));
	if (!d_kds || this.is_image || this.parent != this.defparent)
	{
		(d_o = this.css || this.div).left = (this.cssx += d_x) + dd.px;
		d_o.top = (this.cssy += d_y) + dd.px;
	}
	var d_i = this.children.length; while (d_i--)
	{
		if (!(d_o = this.children[d_i]).detached) d_o.moveBy(d_x, d_y, 1);
		d_o.defx += d_x;
		d_o.defy += d_y;
	}
};

DDObj.prototype.moveTo = function(d_x, d_y)
{
	this.moveBy(dd.Int(d_x)-this.x, dd.Int(d_y)-this.y);
};

DDObj.prototype.hide = function(d_m, d_o, d_p)
{
	if (this.div && this.visible)
	{
		d_p = this.css || this.div;
		if (d_m && !dd.n4)
		{
			this.display = dd.getCssProp(this.div, "display", "display", "display");
			if (this.oimg)
			{
				this.oimg.display = dd.getCssProp(this.oimg, "display", "display", "display");
				this.oimg.style.display = "none";
			}
			d_p.display = "none";
			dd.recalc();
		}
		else d_p.visibility = "hidden";
	}
	this.visible = false;
	var d_i = this.children.length; while (d_i--)
		if (!(d_o = this.children[d_i]).detached) d_o.hide(d_m);
};

DDObj.prototype.show = function(d_o, d_p)
{
	if (this.div)
	{
		d_p = this.css || this.div;
		if (d_p.display && d_p.display == "none")
		{
			d_p.display = this.display || "block";
			if (this.oimg) this.oimg.style.display = this.oimg.display || "inline";
			dd.recalc();
		}
		else d_p.visibility = "visible";
	}
	this.visible = true;
	var d_i = this.children.length; while (d_i--)
		if (!(d_o = this.children[d_i]).detached) d_o.show();
};

DDObj.prototype.resizeTo = function(d_w, d_h, d_o)
{
	if (!this.div) return;
	d_w = (this.w = dd.Int(d_w))-this.dw;
	d_h = (this.h = dd.Int(d_h))-this.dh;
	if (dd.n4)
	{
		this.div.resizeTo(d_w, d_h);
		if (this.is_image)
		{
			this.write('<img src="' + this.src + '" width="' + d_w + '" height="' + d_h + '">');
			(this.nimg = this.div.document.images[0]).src = this.src;
		}
	}
	else if (typeof this.css.pixelWidth != "undefined")
	{
		this.css.pixelWidth = d_w;
		this.css.pixelHeight = d_h;
		if (this.is_image)
		{
			(d_o = this.nimg.style).pixelWidth = d_w;
			d_o.pixelHeight = d_h;
		}
	}
	else
	{
		this.css.width = d_w + dd.px;
		this.css.height = d_h + dd.px;
		if (this.is_image)
		{
			(d_o = this.nimg).width = d_w;
			d_o.height = d_h;
			if (!d_o.complete) d_o.src = this.src;
		}
	}
};

DDObj.prototype.resizeBy = function(d_dw, d_dh)
{
	this.resizeTo(this.w+dd.Int(d_dw), this.h+dd.Int(d_dh));
};

DDObj.prototype.swapImage = function(d_x, d_cp)
{
	if (!this.nimg) return;
	this.nimg.src = d_x;
	this.src = this.nimg.src;
	if (d_cp)
	{
		var d_i = this.copies.length; while (d_i--)
			this.copies[d_i].src = this.copies[d_i].nimg.src = this.nimg.src;
	}
};

DDObj.prototype.setBgColor = function(d_x)
{
	if (dd.n4 && this.div) this.div.bgColor = d_x;
	else if (this.css) this.css.background = d_x;
	this.bgColor = d_x;
};

DDObj.prototype.write = function(d_x, d_o)
{
	this.text = d_x;
	if (!this.div) return;
	if (dd.n4)
	{
		(d_o = this.div.document).open();
		d_o.write(d_x);
		d_o.close();
		dd.getWH(this);
	}
	else if (!dd.op6)
	{
		this.css.height = 'auto';
		this.div.innerHTML = d_x;
		if (!dd.ie4) dd.recalc();
		if (dd.ie4 || dd.n6) setTimeout('dd.recalc();', 0); // n6.0: recalc twice
	}
};

DDObj.prototype.copy = function(d_n, d_p)
{
	if (!this.oimg) return;
	d_n = d_n || 1;
	while (d_n--)
	{
		var d_l = this.copies.length,
		d_o = new DDObj(this.name+this.cmd, d_l+1);
		if (dd.n4)
		{
			d_o.id = (d_p = new Layer(d_o.w)).name;
			d_p.clip.height = d_o.h;
			d_p.visibility = 'show';
			(d_p = d_p.document).open();
			d_p.write(d_o.htm);
			d_p.close();
		}
		else if (dd.db.insertAdjacentHTML) dd.db.insertAdjacentHTML("AfterBegin", d_o.t_htm);
		else if (document.createElement && dd.db && dd.db.appendChild)
		{
			dd.db.appendChild(d_p = document.createElement('div'));
			d_p.innerHTML = d_o.htm;
			d_p.id = d_o.id;
			d_p.style.position = 'absolute';
			d_p.style.width = d_o.w + 'px';
			d_p.style.height = d_o.h + 'px';
		}
		else if (dd.db && dd.db.innerHTML) dd.db.innerHTML += d_o.t_htm;
		d_o.defz = this.defz+1+d_l;
		dd.addProps(d_o);
		d_o.original = this;
		dd.addElt(d_o, this);
		if (this.parent)
		{
			this.parent.addChild(d_o, this.detached);
			d_o.defparent = this.defparent;
		}
		d_o.moveTo(d_o.defx = this.defx, d_o.defy = this.defy);
		if (dd.n4) d_o.defsrc = d_o.src = this.defsrc;
		d_o.swapImage(this.src);
	}
};

DDObj.prototype.addChild = function(d_kd, detach, defp)
{
	if (typeof d_kd != "object") d_kd = dd.elements[d_kd];
	if (d_kd.parent && d_kd.parent == this || d_kd == this || !d_kd.is_image && d_kd.defparent && !defp) return;

	this.children[this.children.length] = this.children[d_kd.name] = d_kd;
	d_kd.detached = detach || 0;
	if (defp) d_kd.defparent = this;
	else if (this == d_kd.defparent && d_kd.is_image) dd.getImg(this, d_kd.oimg.name, 1);
	if (!d_kd.defparent || this != d_kd.defparent)
	{
		d_kd.defx = d_kd.x;
		d_kd.defy = d_kd.y;
	}
	if (!detach)
	{
		d_kd.defz = d_kd.defz+this.defz-(d_kd.parent? d_kd.parent.defz : 0)+(!d_kd.is_image*1);
		d_kd.setZ(d_kd.z+this.z-(d_kd.parent? d_kd.parent.z : 0)+(!d_kd.is_image*1), 1);
	}
	if (d_kd.parent) d_kd.parent._removeChild(d_kd, 1);
	d_kd.parent = this;
};

DDObj.prototype._removeChild = function(d_kd, d_newp)
{
	if (typeof d_kd != "object") d_kd = this.children[d_kd];
	var d_oc = this.children, d_nc = new Array();
	for (var d_i = 0; d_i < d_oc.length; d_i++)
		if (d_oc[d_i] != d_kd) d_nc[d_nc.length] = d_oc[d_i];
	this.children = d_nc;
	d_kd.parent = null;
	if (!d_newp)
	{
		d_kd.detached = d_kd.defp = 0;
		if (d_kd.is_image) dd.getImg(d_kd, d_kd.oimg.name, 1);
	}
};

DDObj.prototype.attachChild = function(d_kd)
{
	(d_kd = (typeof d_kd != "object")? this.children[d_kd]: d_kd).detached = 0;
	d_kd.setZ(d_kd.defz + this.z-this.defz, 1);
};

DDObj.prototype.detachChild = function(d_kd)
{
	(d_kd = (typeof d_kd != "object")? this.children[d_kd]: d_kd).detached = 1;
};

DDObj.prototype.setZ = function(d_x, d_kds)
{
	if (d_kds)
	{
		var d_dz = d_x-this.z,
		d_i = this.children.length; while (d_i--)
			if (!(d_o = this.children[d_i]).detached) d_o.setZ(d_o.z+d_dz, 1);
	}
	dd.z = Math.max(dd.z, this.z = this.div? ((this.css || this.div).zIndex = d_x) : 0);
};

DDObj.prototype.maximizeZ = function()
{
	this.setZ(dd.z+1, 1);
};

DDObj.prototype._resetZ = function(d_o)
{
	if (this.re_z || dd.re_z)
	{
		this.setZ(this.defz);
		var d_i = this.children.length; while (d_i--)
			if (!(d_o = this.children[d_i]).detached) d_o.setZ(d_o.defz);
	}
};

DDObj.prototype.setCursor = function(d_x)
{
	this._setCrs(this.cursor = (d_x.indexOf('c:')+1)? d_x.substring(2) : d_x);
};

DDObj.prototype._setCrs = function(d_x)
{
	if (this.css) this.css.cursor = ((!dd.ie || dd.iemac) && d_x == 'hand')? 'pointer' : d_x;
};

DDObj.prototype.setDraggable = function(d_x)
{
	this.nodrag = !d_x*1;
	this._setCrs(d_x? this.cursor : 'auto');
};

DDObj.prototype.setResizable = function(d_x)
{
	this.resizable = d_x*1;
	if (d_x) this.scalable = 0;
};

DDObj.prototype.setScalable = function(d_x)
{
	this.scalable = d_x*1;
	if (d_x) this.resizable = 0;
};

DDObj.prototype.del = function(d_os, d_o)
{
	if (this.parent && this.parent._removeChild) this.parent._removeChild(this);
	if (this.original)
	{
		this.hide();
		if (this.original.copies)
		{
			d_os = new Array();
			for (var d_i = 0; d_i < this.original.copies.length; d_i++)
				if ((d_o = this.original.copies[d_i]) != this) d_os[d_os.length] = d_os[d_o.name] = d_o;
			this.original.copies = d_os;
		}
	}
	else if (this.is_image)
	{
		this.hide();
		if (this.oimg)
		{
		  if (dd.n4) this.oimg.src = this.defsrc;
		  else this.oimg.style.visibility = 'visible';
		}
	}
	else if (this.moveTo)
	{
		if (this.css) this.css.cursor = 'default';
		this.moveTo(this.defx, this.defy);
		this.resizeTo(this.defw, this.defh);
	}
	d_os = new Array();
	for (var d_i = 0; d_i < dd.elements.length; d_i++)
	{
		if ((d_o = dd.elements[d_i]) != this) d_os[d_os.length] = d_os[d_o.name] = d_o;
		else d_o._free();
	}
	dd.elements = d_os;
	if (!dd.op6 && !dd.n4) dd.recalc();
};

DDObj.prototype._free = function()
{
	for (var d_i in this)
		this[d_i] = null;
	dd.elements[this.name] = null;
};



dd.n4RectVis = function(vis)
{
	for (var d_i = 4; d_i--;)
	{
		dd.rectI[d_i].visibility = dd.rectA[d_i].visibility = vis? 'show' : 'hide';
		if (vis) dd.rectI[d_i].zIndex = dd.rectA[d_i].zIndex = dd.z+2;
	}
};

dd.n4RectPos = function(d_o, d_x, d_y, d_w, d_h)
{
	d_o.x = d_x;
	d_o.y = d_y;
	d_o.clip.width = d_w;
	d_o.clip.height = d_h;
};

// NN4: draw img resize rectangle
dd.n4Rect = function(d_w, d_h)
{
	if (!dd.rectI)
	{
		dd.rectI = new Array();
		dd.rectA = new Array();
	}
	if (!dd.rectI[0])
	{
		for (var d_i = 4; d_i--;)
		{
			(dd.rectI[d_i] = new Layer(1)).bgColor = '#000000';
			(dd.rectA[d_i] = new Layer(1)).bgColor = '#ffffff';
		}
	}
	if (!dd.rectI[0].visibility || dd.rectI[0].visibility == 'hide') dd.n4RectVis(1);
	dd.obj.w = d_w;
	dd.obj.h = d_h;
	for (var d_i = 4; d_i--;)
	{
		dd.n4RectPos(dd.rectI[d_i], dd.obj.x + (!(d_i-1)? (dd.obj.w-1) : 0), dd.obj.y + (!(d_i-2)? (dd.obj.h-1) : 0), d_i&1 || dd.obj.w, !(d_i&1) || dd.obj.h);
		dd.n4RectPos(dd.rectA[d_i], !(d_i-1)? dd.rectI[1].x+1 : (dd.obj.x-1), !(d_i-2)? dd.rectI[2].y+1 : (dd.obj.y-1), d_i&1 || dd.obj.w+2, !(d_i&1) || dd.obj.h+2);
	}
};

dd.reszTo = function(d_w, d_h)
{
	if (dd.n4 && dd.obj.is_image) dd.n4Rect(d_w, d_h);
	else dd.obj.resizeTo(d_w, d_h);
};

dd.embedVis = function(d_vis)
{
	var d_o = new Array('iframe', 'applet', 'embed', 'object');
	var d_i = d_o.length; while (d_i--)
	{
		var d_p = dd.ie? document.all.tags(d_o[d_i]) : document.getElementsByTagName? document.getElementsByTagName(d_o[d_i]) : null;
		if (d_p)
		{
			var d_j = d_p.length; while (d_j--)
			{
				var d_q = d_p[d_j];
				while (d_q.offsetParent || d_q.parentNode)
				{
					if ((d_q = d_q.parentNode || d_q.offsetParent || null) == dd.obj.div)
					{
						d_p[d_j].style.visibility = d_vis;
						break;
					}
				}
			}
		}
	}
};

dd.maxOffX = function(d_x, d_y)
{
	return (
		(dd.obj.maxoffl+1 && (d_y = dd.obj.defx-dd.obj.maxoffl)-d_x > 0
		|| dd.obj.maxoffr+1 && (d_y = dd.obj.defx+dd.obj.maxoffr)-d_x < 0)? d_y
		: d_x
	);
};

dd.maxOffY = function(d_x, d_y)
{
	return (
		(dd.obj.maxofft+1 && (d_y = dd.obj.defy-dd.obj.maxofft)-d_x > 0
		|| dd.obj.maxoffb+1 && (d_y = dd.obj.defy+dd.obj.maxoffb)-d_x < 0)? d_y
		: d_x
	);
};

dd.inWndW = function(d_x, d_y)
{
	var d_wx = dd.getScrollX(),
	d_ww = dd.getWndW();
	return (
		((d_y = d_wx+2)-d_x > 0) || ((d_y = d_wx+d_ww+dd.obj.w-2)-d_x < 0)? d_y
		: d_x
	);
};

dd.inWndH = function(d_x, d_y)
{
	var d_wy = dd.getScrollY(),
	d_wh = dd.getWndH();
	return (
		((d_y = d_wy+2)-d_x > 0) || ((d_y = d_wy+d_wh+dd.obj.h-2)-d_x < 0)? d_y
		: d_x
	);
};

// These two funcs limit the size of element when mouseresized.
// Implemented 22.5.2003 by Gregor Lütolf <gregor@milou.ch>, modified by Walter Zorn
dd.limW = function(d_w)
{
	return (
		(dd.obj.minw-d_w > 0)? dd.obj.minw
		: (dd.obj.maxw > 0 && dd.obj.maxw-d_w < 0)? dd.obj.maxw
		: d_w
	);
};

dd.limH = function(d_h)
{
	return (
		(dd.obj.minh-d_h > 0)? dd.obj.minh
		: (dd.obj.maxh > 0 && dd.obj.maxh-d_h < 0)? dd.obj.maxh
		: d_h
	);
};


// Optional autoscroll-page functionality. Courtesy Cedric Savarese.
// Implemented by Walter Zorn
function DDScroll()
{
	if (!dd.obj || !dd.obj.scroll && !dd.scroll || dd.op || dd.ie4 || dd.whratio)
	{
		dd.scrx = dd.scry = 0;
		return;
	}
	var d_bnd = 0x1c,
	d_wx = dd.getScrollX(), d_wy = dd.getScrollY();
	if (dd.msmoved)
	{
		var d_ww = dd.getWndW(), d_wh = dd.getWndH(), d_y;
		dd.scrx = ((d_y = dd.e.x-d_ww-d_wx+d_bnd) > 0)? (d_y>>=2)*d_y
			: ((d_y = d_wx+d_bnd-dd.e.x) > 0)? -(d_y>>=2)*d_y
			: 0;
		dd.scry = ((d_y = dd.e.y-d_wh-d_wy+d_bnd) > 0)? (d_y>>=2)*d_y
			: ((d_y = d_wy+d_bnd-dd.e.y) > 0)? -(d_y>>=2)*d_y
			: 0;
	}
	if (dd.scrx || dd.scry)
	{
		window.scrollTo(
			d_wx + (dd.scrx = dd.obj.is_resized? dd.limW(dd.obj.w+dd.scrx)-dd.obj.w : dd.obj.vertical? 0 : (dd.maxOffX(dd.obj.x+dd.scrx)-dd.obj.x)),
			d_wy + (dd.scry = dd.obj.is_resized? dd.limH(dd.obj.h+dd.scry)-dd.obj.h : dd.obj.horizontal? 0 : (dd.maxOffY(dd.obj.y+dd.scry)-dd.obj.y))
		);
		dd.obj.is_dragged? dd.obj.moveTo(dd.obj.x+dd.getScrollX()-d_wx, dd.obj.y+dd.getScrollY()-d_wy)
			: dd.reszTo(dd.obj.w+dd.getScrollX()-d_wx, dd.obj.h+dd.getScrollY()-d_wy);
	}
	dd.msmoved = 0;
	window.setTimeout('DDScroll()', 0x33);
}



function PICK(d_ev)
{
	dd.e = new dd.evt(d_ev);
	if (dd.e.x >= dd.getWndW()+dd.getScrollX() || dd.e.y >= dd.getWndH()+dd.getScrollY()) return true; // on scrollbar
	var d_o, d_cmp = -1, d_i = dd.elements.length; while (d_i--)
	{
		d_o = dd.elements[d_i];
		if (dd.n4 && dd.e.but > 1 && dd.e.src == d_o.oimg && !d_o.clone) return false;
		if (d_o.visible && dd.e.but <= 1 && !d_o.nodrag && dd.e.x >= d_o.x && dd.e.x <= d_o.x+d_o.w && dd.e.y >= d_o.y && dd.e.y <= d_o.y+d_o.h)
		{
			if (d_o.z > d_cmp && dd.e.src.tag.indexOf('input') < 0 && dd.e.src.tag.indexOf('textarea') < 0 && dd.e.src.tag.indexOf('select') < 0 && dd.e.src.tag.indexOf('option') < 0)
			{
				d_cmp = d_o.z;
				dd.obj = d_o;
			}
		}
	}
	if (dd.obj)
	{
		dd.e.e.cancelBubble = true;
		var d_rsz = dd.e.modifKey && (dd.obj.resizable || dd.obj.scalable);
		if (dd.op && !dd.op6)
		{
			(d_o = document.getElementById('OpBlUr')).style.pixelLeft = dd.e.x;
			d_o.style.pixelTop = dd.e.y;
			(d_o = d_o.children[0].children[0]).focus();
			d_o.blur();
		}
		else if (dd.ie && !dd.ie4)
		{
			if (document.selection && document.selection.empty) document.selection.empty();
			dd.db.onselectstart = function()
			{
				event.returnValue = false;
			};
		}
		if (d_rsz)
		{
			dd.obj._setCrs('se-resize');
			dd.obj.is_resized = 1;
			dd.whratio = dd.obj.scalable? dd.obj.defw/dd.obj.defh : 0;
			if (dd.ie)
			{
				if (dd.ie4)
				{
					window.dd_x = dd.getScrollX();
					window.dd_y = dd.getScrollY();
				}
				setTimeout(
					'if (dd.obj && document.selection && document.selection.empty)'+
					'{'+
						'document.selection.empty();'+
						'if (dd.ie4) window.scrollTo(window.dd_x, window.dd_y);'+
					'}'
				,0);
			}
			dd.setEvtHdl(1, RESIZE);
			dd.reszTo(dd.obj.w, dd.obj.h);
		}
		else if (!dd.obj.nodrag)
		{
			dd.obj.is_dragged = 1;
			dd.setEvtHdl(1, DRAG);
		}
		dd.setEvtHdl(2, DROP);
		dd.embedVis('hidden');
		dd.obj.maximizeZ();
		dd.ofx = dd.obj.x+dd.obj.w-dd.e.x;
		dd.ofy = dd.obj.y+dd.obj.h-dd.e.y;
		if (window.my_PickFunc) my_PickFunc();
		DDScroll();
		return !(
			dd.obj.is_resized
			|| dd.n4 && dd.obj.is_image
			|| dd.n6 || dd.w3c
		);
	}
	if (dd.downFunc) return dd.downFunc(d_ev);
	return true;
}

function DRAG(d_ev)
{
	if (!dd.obj || !dd.obj.visible) return true;
	if (dd.ie4 || dd.w3c || dd.n6 || dd.obj.children.length > 0xf)
	{
		if (dd.wait) return false;
		dd.wait = 1;
		setTimeout('dd.wait = 0;', 5);
	}
	dd.e = new dd.evt(d_ev);
	if (dd.ie && !dd.e.but)
	{
		DROP(d_ev);
		return true;
	}
	dd.msmoved = 1;
	dd.obj.moveTo(
		dd.obj.vertical? dd.obj.x : dd.maxOffX(dd.inWndW(dd.ofx+dd.e.x)-dd.obj.w),
		dd.obj.horizontal? dd.obj.y : dd.maxOffY(dd.inWndH(dd.ofy+dd.e.y)-dd.obj.h)
	);

	if (window.my_DragFunc) my_DragFunc();
	return false;
}

function RESIZE(d_ev)
{
	if (!dd.obj || !dd.obj.visible) return true;
	if (dd.wait) return false;
	dd.wait = 1;
	setTimeout('dd.wait = 0;', 5);
	dd.e = new dd.evt(d_ev);
	if (dd.ie && !dd.e.but)
	{
		DROP(d_ev);
		return true;
	}
	dd.msmoved = 1;
	var d_w = dd.limW(dd.inWndW(dd.ofx+dd.e.x)-dd.obj.x);
	if (!dd.whratio) var d_h = dd.limH(dd.inWndH(dd.ofy+dd.e.y)-dd.obj.y);
	else
	{
		var d_h = dd.limH(dd.inWndH(Math.round(d_w/dd.whratio)+dd.obj.y)-dd.obj.y);
		d_w = Math.round(d_h*dd.whratio);
	}
	dd.reszTo(d_w, d_h);
	if (window.my_ResizeFunc) my_ResizeFunc();
	return false;
}

function DROP(d_ev)
{
	if (dd.obj)
	{
		if (dd.obj.is_dragged)
		{
			if (!dd.obj.is_image) dd.getWH(dd.obj);
		}
		else if (dd.n4)
		{
			if (dd.obj.is_image)
			{
				dd.n4RectVis(0);
				dd.obj.resizeTo(dd.obj.w, dd.obj.h);
			}
		}
		if (!dd.n4 && !dd.op6 || !dd.obj.is_image) dd.recalc();
		dd.setEvtHdl(1, dd.moveFunc);
		dd.setEvtHdl(2, dd.upFunc);
		if (dd.db) dd.db.onselectstart = null;
		dd.obj._setCrs(dd.obj.cursor);
		dd.embedVis('visible');
		dd.obj._resetZ();
		if (window.my_DropFunc)
		{
			dd.e = new dd.evt(d_ev);
			my_DropFunc();
		}
		dd.msmoved = dd.obj.is_dragged = dd.obj.is_resized = dd.whratio = 0;
		dd.obj = null;
	}
	dd.setEvtHdl(0, PICK);
}



function SET_DHTML()
{
	dd.elements = new Array();
	var d_a = SET_DHTML.arguments, d_ai, d_htm = '', d_o, d_i = d_a.length; while (d_i--)
	{
		if (dd.op6)
		{
			var d_t0 = (new Date()).getTime();
			while ((new Date()).getTime()-d_t0 < 0x99);
		}
		if (!(d_ai = d_a[d_i]).indexOf('c:')) dd.cursor = d_ai.substring(2);
		else if (d_ai == NO_ALT) dd.noalt = 1;
		else if (d_ai == SCROLL) dd.scroll = 1;
		else if (d_ai == RESET_Z) dd.re_z = 1;
		else if (d_ai == RESIZABLE) dd.resizable = 1;
		else if (d_ai == SCALABLE) dd.scalable = 1;
		else
		{
			d_o = new DDObj(d_ai);
			dd.addElt(d_o);
			d_htm += d_o.t_htm || '';
			if (d_o.oimg && d_o.cpy_n)
			{
				var d_j = 0; while (d_j < d_o.cpy_n)
				{
					var d_p = new DDObj(d_o.name+d_o.cmd, ++d_j);
					dd.addElt(d_p, d_o);
					d_p.defz = d_o.defz+d_j;
					d_p.original = d_o;
					d_htm += d_p.t_htm;
				}
			}
		}
	}
	if (dd.n4 || dd.n6 || dd.ie || dd.op || dd.w3c) document.write(
		(dd.n4? '<div style="position:absolute;"><\/div>\n'
		: (dd.op && !dd.op6)? '<div id="OpBlUr" style="position:absolute;visibility:hidden;width:0px;height:0px;"><form><input type="text" style="width:0px;height:0px;"><\/form><\/div>'
		: '') + d_htm
	);
	dd.z = 0x33;
	d_i = dd.elements.length; while (d_i--)
	{
		dd.addProps(d_o = dd.elements[d_i]);
		if (d_o.is_image && !d_o.original && !d_o.clone)
			dd.n4? d_o.oimg.src = spacer : d_o.oimg.style.visibility = 'hidden';
	}
	dd.mkWzDom();
	if (window.onload) dd.loadFunc = window.onload;
	window.onload = dd.initz;
	window.onunload = dd.finlz;
	dd.setEvtHdl(0, PICK);
}

function ADD_DHTML(d_o) // layers only!
{
	d_o = new DDObj(d_o);
	dd.addElt(d_o);
	dd.addProps(d_o);
	dd.mkWzDom();
}




////////////////////////////////////////////////////////////
// If not needed, all code below this line may be removed


// For backward compatibility
dd.d = document;            // < v. 2.72
var RESET_ZINDEX = RESET_Z; // < 3.44
var KEYDOWN_RESIZE = RESIZABLE; // < 4.43
var CURSOR_POINTER = CURSOR_HAND; // < 4.44
var NO_SCROLL = '';         // < v. 4.49




////////////////////////////////////////////////////////////
// FUNCTIONS FOR EXTENDED SCRIPTING
// Use these for your own extensions,
// or to call functions defined elsewhere



/* my_PickFunc IS AUTOMATICALLY CALLED WHEN AN ITEM STARTS TO BE DRAGGED.
The following objects/properties are accessible from here:

- dd.e: current mouse event
- dd.e.property: access to a property of the current mouse event.
  Mostly requested properties:
  - dd.e.x: document-related x co-ordinate
  - dd.e.y: document-related y co-ord
  - dd.e.src: target of mouse event (not identical with the drag drop object itself).
  - dd.e.button: currently pressed mouse button. Left button: dd.e.button <= 1

- dd.obj: reference to currently dragged item.
- dd.obj.property: access to any property of that item.
- dd.obj.method(): for example dd.obj.resizeTo() or dd.obj.swapImage() .
  Mostly requested properties:
	- dd.obj.name: image name or layer ID passed to SET_DHTML();
	- dd.obj.x and dd.obj.y: co-ordinates;
	- dd.obj.w and dd.obj.h: size;
	- dd.obj.is_dragged: 1 while item is dragged, else 0;
	- dd.obj.is_resized: 1 while item is resized, i.e. if <ctrl> or <shift> is pressed, else 0

For more properties and details, visit the API documentation
at http://www.walterzorn.com/dragdrop/api_e.htm (english) or
http://www.walterzorn.de/dragdrop/api.htm (german)    */
function my_PickFunc()
{
}




/* my_DragFunc IS CALLED WHILE AN ITEM IS DRAGGED
See the description of my_PickFunc above for what's accessible from here. */
function my_DragFunc()
{
	//window.status = 'dd.elements.' + dd.obj.name + '.x  = ' + dd.obj.x + '     dd.elements.' + dd.obj.name + '.y = ' + dd.obj.y;
}




/* my_ResizeFunc IS CALLED WHILE AN ITEM IS RESIZED
See the description of my_PickFunc above for what's accessible from here. */
function my_ResizeFunc()
{
	//window.status = 'dd.elements.' + dd.obj.name + '.w  = ' + dd.obj.w + '     dd.elements.' + dd.obj.name + '.h = ' + dd.obj.h;
}




/* THIS ONE IS CALLED ONCE AN ITEM IS DROPPED
See the description of my_PickFunc for what's accessible from here.
Here may be investigated, for example, what's the name (dd.obj.name)
of the dropped item, and where (dd.obj.x, dd.obj.y) it has been dropped... */
function my_DropFunc()
{
}


function uploadScreen ( form_name,sid )
{
 	document.all.attach.value = "Attach";
 	document.all.sid.value = sid;
    //checkContent();
    //if(parent.OpenWizard!=undefined)
  	var obj;
  	if(form_name.name=="composeform")
  	{
		obj=parent.OpenWizard('#');
		//obj.setSize(400,324);
		obj.setSize(600,500);
  		var parm=obj.getId()+"_content";
  		form_name.target=parm;
  		form_name.submit() ;
	
    
  	}
  	else
  	{
  		/*alert(opener.OpenWizard);
		obj=opener.OpenWizard('uploadattachment',"","0.43","0.39");
  		var parm=obj.getId()+"_content";
  		form_name.target=parm;*/

		obj=OpenWizard('#');
		//obj.setSize(400,324);
		obj.setSize(600,500);
		var parm=obj.getId()+"_content";
  		form_name.target=parm;
  		form_name.submit() ;
	
  	}
  	
  	//var parm=obj.getId()+"_content";
  	
  	//alert(form_name.name);

    //alert("val"+document.getElementById(form_name.name).attachRemove.value);
   // form_name.target=parm;
    //form_name.numofattach.value =0;
	//form_name.submit() ;
	//form_name.submit() ;

}
function checkContent()
{
    iHTML = this['spaw1_rEdit'].document.body.innerHTML;
    document.all['spaw1'].value = iHTML;
    document.all['SPAW_spaw1_editor_mode'].value = 'html';
}

var myFocus='to';
var invalidEmail = "";

function setIt(name)
{
    myFocus=name ;
	document.getElementById('toarrow').src = document.getElementById('ccarrow').src =document.getElementById('bccarrow').src ="images/blank.gif";
    if (myFocus == "to")
		document.getElementById('toarrow').src ="images/misc/compose.gif";
    else if (myFocus == "cc")
        document.getElementById('ccarrow').src ="images/misc/compose.gif";
	else if (myFocus == "bcc")
        document.getElementById('bccarrow').src ="images/misc/compose.gif";
}

function existContacts(email, str)
{
	var data = new Array();
	
	data =  str.split(",");

    for ( i =0 ; i < data.length ; i++)
    {
       if(data[i]== email)
            return false;
    }

    return true;
}

function validateEmailIds()
{  
	//checkContent();
    var data = new Array();
	var str = new Array();
	try
	{
		trimAll();
	}
	catch(e)
	{
		//	alert("myerror");
	}	
	str[0] = document.all.mailTo.value ;
    str[1] = document.all.mailCc.value ;
    str[2] = document.all.mailBcc.value ;
	
    if (str[0]=="" && str[1]=="" && str[2]=="" )
        return false;

    for ( j=0 ; j < 3 ;j++)
    {
        if (str[j])
        {
            data = str[j].split(",");
            for ( i =0 ; i < data.length ; i++)
            {
               if(!isValidEmail(data[i]))
               {
                    invalidEmail = data[i];            
                    return false;
               }
            }
        }
    }
    return true;
}

function validateForm( my_form)
{
	
	//SPAW_cleanup_click("spaw1");
  	var fckEditor = FCKeditorAPI.GetInstance('EmailEditor');			
	//debugger;
	//alert($('divFwdEditor').innerHTML);
	var message = fckEditor.GetXHTML();
    //var message=data;

  if (validateEmailIds())
  {
		if (message == "")
	 	{	
	 		alert("Mail is empty");
	 		return false;
	 	}		
		if(document.all.subj.value=="")
		{
			if(confirm("Are you sure to send message with empty subject?"))
             {
//                document.all.comp.value = "Send";
//                $('EmailEditor').value = message;
//				PostAjaxScreen('compose',$(my_form)); 			
				//my_form.submit();
				
				submitEmailForm(my_form,message);
             }
		}
		else
		{
//				document.all.comp.value = "Send";
//				$('EmailEditor').value = message;			
//				PostAjaxScreen('compose',$(my_form)); 
			//my_form.submit();
			
			submitEmailForm(my_form,message);
		}
   }
   else
    {
        if (invalidEmail)
        invalidEmail = ": "+invalidEmail;
        alert("Invalid email address" + invalidEmail);
        invalidEmail = "" ;
    }
  
}

function submitEmailForm(form,message)
{
//	alert("test1");
	//debugger;
	document.all.comp.value = "Send";
//	document.all.attach.value = "";
	$('EmailEditor').Value = message;
	$('content').value = message;
	//alert("d"+$('content').value);						
	//if(form.name == "composeform")
	if(form.name == "sendmail")
	{
		PostAjaxScreen('compose',$(form)); 

	}
	else
	{	
		form.target='_self';
		form.submit();
	}	
}

function editFav (userid, sid,formname, serverName )
{
	var w = parent.document.body.clientWidth*.60;
	var h = screen.height*.60;
	var x = (parent.document.body.clientWidth - w)/2;
	var y = (screen.height - h)/4;
	var url= 'http://'+serverName+'/index.php?SCREEN=editfav&sid='+sid+'&userid='+userid+'&formname='+formname ;

    checkContent();
    
    OpenWindow("Wizard",w,h,y,x,"no","yes","no","no","no",url,"");
}

function addname(emailid)
{
    if (myFocus == "to")
    {
        check = document.all.mailTo.value ;
        if(check)
        {
            if(existContacts(emailid, check))
            {
                document.all.mailTo.value+=",";
                document.all.mailTo.value+=emailid;
            }
        }
        else
            document.all.mailTo.value+=emailid;
    }
    else if (myFocus == "cc")
    {
        check = document.all.mailCc.value ;
        if(check)
        {
            if(existContacts(emailid, check))
            {
                document.all.mailCc.value+=",";
                document.all.mailCc.value+=emailid;
            }
        }
        else
            document.all.mailCc.value+=emailid;
    }
    else if (myFocus == "bcc")
    {
        check = document.all.mailBcc.value ;
        if(check)
        {
            if(existContacts(emailid, check))
            {
                document.all.mailBcc.value+=",";
                document.all.mailBcc.value+=emailid;
            }
        }
        else
            document.all.mailBcc.value+=emailid;
    }
}
var tabCount = 0;
var maxWidth=0;
var curWidth=0;
function CreateTabPanel_New(id,display,backcolor)
{
	if (!display)
		display = "none";
	else if (display == 1)
		display = "";
	else if (display == 0)
		display = "none";
		
	if (!backcolor)
		backcolor = 'black';
		
	this.panelId = id;
	
	var str = '';
	str += '<table style="display:'+display+';height:10px;" id="'+id+'" width="100%" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="black" style="">';
		str += '<tr id="trTabs" width="100%">';
			str += '<td class="" id="'+id+'_emptyTr">&nbsp;</td>';
		str += '</tr>';
		str += '<tr id="trRow" style="background-color:#373536; border:1px #373536 solid" valign=top>';
			str += '<td colspan="99" align="center" class="" height="1"></td>';
		str += '</tr>';
	str += '</table>';

	//if(_browsername_!='Mozilla')
	//		doc = parent.document.getElementById('IFControl').contentWindow.document;
	//else
	//		doc = parent.document.getElementById('IFControl').contentDocument;
	
	//doc.write(str);
	// Fix fox ajax driven screens, parent TD id should be <id+'Container'>
	if (!$(id))
	{
		//alert($(id) +'|'+ parent.frames['IFControl'].document.getElementById(id));
		$(id+'Container').innerHTML += str;
	}	

	this.SelectTab = SelectTab;
	this.SelectTab_New = SelectTab_New;
	this.UpdateTab = UpdateTab;	
	this.AddTab = AddTab;
	this.AddTab_New = AddTab_New;
	this.ClearTabs = ClearTabs;
	this.HighlightTab = HighlightTab;
	this.HighlightTab_New = HighlightTab_New;
	this.BlinkTab = BlinkTab;
	this.DeleteTab = DeleteTab
}
function CreateTabPanel(id,display,backcolor)
{
	if (!display)
		display = "none";
	else if (display == 1)
		display = "";
	else if (display == 0)
		display = "none";
		
	if (!backcolor)
		backcolor = 'white';
		
	this.panelId = id;
	
	var str = '';
	str += '<table style="display:'+display+';height:20px;" id="'+id+'" width="100%" border="0" align="center" cellpadding="0" cellspacing="0">';
		str += '<tr id="trTabs" width="100%">';
			str += '<td class="" id="'+id+'_emptyTr">&nbsp;</td>';
		str += '</tr>';
		str += '<tr id="trRow">';
			str += '<td colspan="99" align="center" class="sidebar" height="1"><img src="/images/blank.gif" height="2"></td>';
		str += '</tr>';
	str += '</table>';

	//if(_browsername_!='Mozilla')
	//		doc = parent.document.getElementById('IFControl').contentWindow.document;
	//else
	//		doc = parent.document.getElementById('IFControl').contentDocument;
	
	//doc.write(str);
	// Fix fox ajax driven screens, parent TD id should be <id+'Container'>
	if (!$(id))
	{
		//alert($(id) +'|'+ parent.frames['IFControl'].document.getElementById(id));
		$(id+'Container').innerHTML += str;
	}	

	this.SelectTab = SelectTab;
	this.UpdateTab = UpdateTab;	
	this.AddTab = AddTab;
	this.AddTab_New = AddTab_New;
	this.ClearTabs = ClearTabs;
	this.HighlightTab = HighlightTab;
	this.BlinkTab = BlinkTab;
	this.DeleteTab = DeleteTab
}

function SelectTab_New(o,action)
{
	if (typeof o == "string")
	{
		this.HighlightTab(o);
	}
	else
	{
		//alert(this.panelId);
		var table = document.getElementById(this.panelId);
		var gid = o.getAttribute("gid");
	
		var tds = table.getElementsByTagName("td");
		for (var i=0;i<tds.length;i++)
		{
			if (tds[i].getAttribute("gid") == gid)
				tds[i].className = 'tabSelected_new';
			else if (tds[i].getAttribute("gid") && tds[i].className != 'tabBlink')
				tds[i].className = 'tabNormal_new';
		}
	}
	action();
}

function SelectTab(o,action)
{
	if (typeof o == "string")
	{
		this.HighlightTab(o);
	}
	else
	{
		//alert(this.panelId);
		var table = document.getElementById(this.panelId);
		var gid = o.getAttribute("gid");
	
		var tds = table.getElementsByTagName("td");
		for (var i=0;i<tds.length;i++)
		{
			if (tds[i].getAttribute("gid") == gid)
				tds[i].className = 'tabSelected';
			else if (tds[i].getAttribute("gid") && tds[i].className != 'tabBlink')
				tds[i].className = 'tabNormal';
		}
	}
	action();
}

function UpdateTab(tid,action,title)
{
	var table = document.getElementById(this.panelId);
	var o = this;	
	
	var tds = table.getElementsByTagName("td");
	for (var i=0;i<tds.length;i++)
	{
		if (tds[i].getAttribute("gid") == tid)
		{
			if (title && tds[i].id == "td_"+tid+"_text")
				tds[i].innerHTML = title;
				
			tds[i].onclick = function(){o.SelectTab(this,action)};
		}
	}
}


function AddTab_New(tid,title,action,tooltip,del,delaction)
{
	var o = this;
	//alert(tid+"||"+title+"||"+action);
	tooltip = (typeof(tooltip) == 'undefined') ? title : tooltip;
	
	var mainTable = document.getElementById(this.panelId);
	var emptyTab = document.getElementById(this.panelId+"_emptyTr");
	var trTabs = mainTable.rows[0];
	var availWidth;
	if(window.screenLeft <50)
		availWidth = '13%';
	else
		availWidth = '25%';
availWidth ="1%";
	var mtd = document.createElement('td');
	mtd.id = tid;
	mtd.align='left';
	mtd.style.width = availWidth;
	

	var ctable = document.createElement('table');
	ctable.border=0;
	ctable.width='100%';
	ctable.height='100%';
	ctable.cellSpacing=0;
	ctable.cellPadding=2;
	

	var ctbody = document.createElement('tbody');	
	var ctr = document.createElement('tr');		
	ctr.setAttribute('gid',tid);

		
	var ctd2 = document.createElement('td');
	//ctd2.nowrap="true";
	ctd2.noWrap=true;
	ctd2.id= 'td1_'+tid+'_text';
	ctd2.className = "tabNormal_new";
	ctd2.setAttribute('gid',tid);
	ctd2.width="100%";
	ctd2.align="center";
	ctd2.title = tooltip;
	ctd2.tooltip = tooltip;
	ctd2.onclick = function(){o.SelectTab_New(ctd2,action);};
	//ctd2.innerHTML = trimString(title,15);
	if(del=='yes')
	{
		ctd2.innerHTML = "&nbsp;&nbsp;&nbsp;"+trimString(title,30)+"&nbsp;&nbsp;";
	}
	else
		ctd2.innerHTML = "&nbsp;&nbsp;&nbsp;"+trimString(title,40)+"&nbsp;&nbsp;";
	ctd2.style.cursor = 'pointer';
	
	
	
	var i3 = document.createElement('img');
	i3.src="/images/dialog/button-max-focus.gif";
	i3.border ="0";
	i3.onclick = function(){o.DeleteTab(tid,delaction);};

	var i3 = document.createElement('span');
	i3.innerHTML="&nbsp;<b><font size=2.5 color='white'>X</font></b>&nbsp;"; //green shade:#18FF00
	i3.onclick = function(){o.DeleteTab(tid,delaction);};

	if(del=='yes')
	{
		//ctd2.innerHTML+="&nbsp;<b><font size=2.5 color='#18FF00'>X</font></b>&nbsp;"
		ctd2.appendChild(i3);
	}
	
	//	var ctdemtpty = document.createElement('<td width="99%">');;
	
	
	ctr.appendChild(ctd2);

	//ctr.appendChild(ctdemtpty);
	//ctbody.appendChild(ctr);
	ctbody.appendChild(ctr);
	ctable.appendChild(ctbody);	
	mtd.appendChild(ctable);
	trTabs.insertBefore(mtd,emptyTab);
//	trTabs.appendChild(mtd);
	tabCount++;
}

function AddTab(tid,title,action,tooltip,del,delaction)
{
	var o = this;
	//alert(tid+"||"+title+"||"+action);
	tooltip = (typeof(tooltip) == 'undefined') ? title : tooltip;
	
	var mainTable = document.getElementById(this.panelId);
	var emptyTab = document.getElementById(this.panelId+"_emptyTr");
	var trTabs = mainTable.rows[0];
	var availWidth;
	if(window.screenLeft <50)
		availWidth = '13%';
	else
		availWidth = '25%';

	var mtd = document.createElement('td');
	mtd.id = tid;
	mtd.align='left';
	mtd.style.width = availWidth;
	
	
	var ctable = document.createElement('table');
	ctable.border=0;
	ctable.cellSpacing=0;
	ctable.cellPadding=0;
	

	var ctbody = document.createElement('tbody');	
	var ctr = document.createElement('tr');		
	ctr.setAttribute('gid',tid);

	var ctd1 = document.createElement('td');
	ctd1.className = "tabNormal";
	ctd1.setAttribute('gid',tid);
	ctd1.width="1%";
	ctd1.align="left";
	
	var i1 = document.createElement('img');
	i1.src="/images/misc/tab_leftcorner.gif";
	i1.height="19";
	i1width="1";
	i1.border ="0";
	
	ctd1.onclick = function(){o.SelectTab(ctd1,action);};
	ctd1.style.cursor = 'pointer';
	ctd1.appendChild(i1);
		
	var ctd2 = document.createElement('td');
	//ctd2.nowrap="true";
	ctd2.noWrap=true;
	ctd2.id= 'td1_'+tid+'_text';
	ctd2.className = "tabNormal";
	ctd2.setAttribute('gid',tid);
	ctd2.width="80%";
	ctd2.align="center";
	ctd2.title = tooltip;
	ctd2.tooltip = tooltip;
	ctd2.onclick = function(){o.SelectTab(ctd1,action);};
	//ctd2.innerHTML = trimString(title,15);
	if(del=='yes')
	{
		ctd2.innerHTML = trimString(title,10);
	}
	else
		ctd2.innerHTML = trimString(title,15);
	ctd2.style.cursor = 'pointer';
	
	var ctd3 = document.createElement('td');
	ctd3.className="tabNormal";
	ctd3.setAttribute('gid',tid);
	ctd3.width="1%";
	ctd3.align ="right";
	ctd3.innerHTML = "&nbsp;";
	
	var i3 = document.createElement('img');
	i3.src="/images/dialog/button-close-focus.gif";
	i3.border ="0";
	i3.onclick = function(){o.DeleteTab(tid,delaction);};

	ctd3.style.cursor = 'pointer';
	ctd3.appendChild(i3);
	
	var ctd4 = document.createElement('td');
	ctd4.className="tabNormal";
	ctd4.setAttribute('gid',tid);
	ctd4.width="1%";
	ctd4.align ="left";
	
	var i4 = document.createElement('img');
	i4.src="/images/misc/tab_rightcorner.gif";
	i4.border ="0";
	i4.width = "10";
	i4.height="19";
	
	ctd4.appendChild(i4);
	ctd4.onclick = function(){o.SelectTab(ctd1,action);};
	ctd4.style.cursor = 'pointer';

	var ctd5 = document.createElement('td');
	ctd5.className="sidebar";
	ctd5.width="1%";
	ctd5.align ="left";
	
	var i5 = document.createElement('img');
	i5.src="images/blank.gif";
	i5.border ="0";
	i5.width = "2";
	i5.height="19";
	ctd5.appendChild(i5);
	//	var ctdemtpty = document.createElement('<td width="99%">');;
	
	ctr.appendChild(ctd1);
	ctr.appendChild(ctd2);
	if(del=='yes')
	{
		ctr.appendChild(ctd3);
	}
	ctr.appendChild(ctd4);
	ctr.appendChild(ctd5);
	//ctr.appendChild(ctdemtpty);
	//ctbody.appendChild(ctr);
	ctbody.appendChild(ctr);
	ctable.appendChild(ctbody);	
	mtd.appendChild(ctable);
	trTabs.insertBefore(mtd,emptyTab);
//	trTabs.appendChild(mtd);
	
}

function ClearTabs()
{
	var mainTable = document.getElementById(this.panelId);
	var emptyTab = document.getElementById(this.panelId+"_emptyTr");
	var str = emptyTab.outerHTML;
	var trTabs = mainTable.rows[0];
	var c = trTabs.cells.length;
	for (var x=0;x<c-1;x++)
	{
		trTabs.deleteCell(0);
	}
}
function HighlightTab_New(tid)
{
	
	var table = document.getElementById(this.panelId);
	if(table==null)
		return;
	var o = this;	
	var gid;
	var tds = table.getElementsByTagName("td");
	for (var i=0;i<tds.length;i++)
	{
		if (gid = tds[i].getAttribute("gid"))
		{
			if (gid == tid)
				tds[i].className = 'tabSelected_new';
			else if(tds[i].className != 'tabBlink')
			{	
				tds[i].className = 'tabNormal_new';
			}	
		}
		
	}
}
function HighlightTab(tid)
{
	var table = document.getElementById(this.panelId);
	if(table==null)
		return;
	var o = this;	
	var gid;
	var tds = table.getElementsByTagName("td");
	for (var i=0;i<tds.length;i++)
	{
		if (gid = tds[i].getAttribute("gid"))
		{
			if (gid == tid)
				tds[i].className = 'tabSelected';
			else if(tds[i].className != 'tabBlink')
			{	
				tds[i].className = 'tabNormal';
			}	
		}
		
	}
}

function BlinkTab(tid)
{
	var table = document.getElementById(this.panelId);
	var o = this;	
	var gid;
	var tds = table.getElementsByTagName("td");
	for (var i=0;i<tds.length;i++)
	{
		if (gid = tds[i].getAttribute("gid"))
		{
			if (gid == tid)
				if(tds[i].className != 'tabSelected')
					tds[i].className = 'tabBlink';
		}
		
	}
}
function DeleteTab(tid,action)
{
	tabCount--;
	var mainTable = document.getElementById(this.panelId);
	var trTabs = mainTable.rows[0];
	if(document.getElementById(tid)!=null)
		trTabs.removeChild(document.getElementById(tid)); 
	action();
	
	if(typeof(document.getElementById('chatDivBody'))!='undefined' && document.getElementById('chatDivBody')!=null)
	{
		var tbObj = document.getElementById('chatDivBody');
		if(tbObj)
		{
			var tCount = tbObj.rows.length;
			if(tCount==0)
			{
				if(typeof(document.getElementById('mainDiv'))!='undefined')
				{
					document.getElementById("mainDiv").style.display = "none";
				}
			}
		}
	}
}/* Grid List starts here */

function GridItems()
{
	this.items = new Array();
}

GridItems.prototype.AddItem = function(row,uid,type,html,srcProjectId,srcProjectPath,fileid)
{

	if (html==undefined)
	{
		html="null";
	}
	
	if (srcProjectId==undefined)
	{	
		//alert(row+","+uid+","+type+","+html+","+srcProjectId+","+srcProjectPath);
		srcProjectId="null";
	}
		
	if (srcProjectPath==undefined)
		srcProjectPath="null";

	//alert(srcProjectId);
	var item = new Array();
	item["row"] = row;
	item["uid"] = uid;
	item["type"] = type;
	item["html"] = html;
	item["srcProjectId"] = srcProjectId;
	item["srcProjectPath"] = srcProjectPath;

	if(typeof(fileid) != "undefined")
		item["fileid"] = fileid;
		
	this.items[this.items.length] = item;
	//this.ShowItems();
}

GridItems.prototype.GetItemCount = function()
{
	return this.items.length;
}

GridItems.prototype.DeleteItem = function(rowno)
{
	for (var i=0; i<this.items.length; i++)
	{
		if (this.items[i]["row"] == rowno)
		{
			this.items = cut(this.items,i);
			break;
		}
	}
}

GridItems.prototype.GetAllItemsHtml = function()
{
	var d="";
	for (var i=0; i<this.items.length; i++)
	{
		d += this.items[i]["html"];
	}
	return d;
}

GridItems.prototype.DeleteAllItems = function()
{
	this.items = null;
	this.items = new Array();
}

GridItems.prototype.Serialize = function()
{
	var d = "";
	for (var i=0; i<this.items.length; i++)
	{
		d += this.items[i]["uid"] + "|" + this.items[i]["type"] + "|" +this.items[i]["srcProjectId"] +  "|" +this.items[i]["srcProjectPath"] + ",";
	}
	return d;
}

GridItems.prototype.CheckSameType = function(type)
{
	for (var i=0;i<this.items.length; i++)
	{
		if (type != this.items[i]["type"] && type+"-all" != this.items[i]["type"])
			return false;
	}

	return true;
}

GridItems.prototype.ShowItems = function()
{
	var d = "";
	for (var i=0; i<this.items.length; i++)
	{
		d += this.items[i]["row"] + " | " + this.items[i]["uid"] + " | " + this.items[i]["type"] + " | " + this.items[i]["srcProjectId"]  + " | " + this.items[i]["srcProjectPath"] + "\n";
	}
	alert(d);
	//window.status=d;
}

GridItems.prototype.SearchItem = function(rowno)
{
	if (this.items.length==0)
	    return false;
	    
	for (var i=0; i<this.items.length; i++)
	{
		if (this.items[i]["row"] == rowno)
		{
			return true;
		}
	}
	return false;
}

GridItems.prototype.GetSource = function()
{
	return this.items[0]["srcProjectId"]
}

GridItems.prototype.GetType = function()
{
	if(this.items.length>0)
		return this.items[0]["type"]
}

GridItems.prototype.GetSourcePath = function()
{
	return this.items[0]["srcProjectPath"]
}

var list = new GridItems();
/* Grid List ends here */

// Global variables 

var ctrlkeypressed = 0;
var shiftkeypressed = 0;
var dflag;
var downFlag=0;
var projectType=0;
var page='';
var filter='';
var callingFrom='';
// Threshold X and Y for movement
var moveXth;
var moveYth;

// Allow detecting content movement
var moveFlag;

var operationval="";

//window.top.selectReply.disabled = true;
//window.top.selectFwd.disabled = true;

var mailId;

// Used in detection click on folder
var folder=0;

var autopreview=1;
// Need to be removed. Modification requires in datafetch.js, screen/navigate
/* // moved in screen/navigate (afnan) was unsure what going wrong
function OpenFaxFile(unique_id)
{
	var w = window.open('downfiles.php?sno='+unique_id+'&file=pdf','newform','width=800, height=600, left=50, top=50, location=no, menubar=no, status=no, toolbar=no, scrollbars=yes, resizable=yes');
	w.focus();
}	
*/
		
// File operation fx starts here			

function createFolder(folderName,projectId, projectPath)
{
	if(!isAlphaNumericSpace(folderName))
	{
		alert("Please enter valid project name");
		return;
	}

	//document.all.foldername.value="";

	// RPC check if folder exist
	// alert(folderName+"|"+projectId+"|"+projectPath);
	/*
	if(rpcSvr.CheckFolderExist(folderName,projectId,projectPath))
	{
		alert("Sub-Project already exist");
		return;
	}	
	*/
	list.DeleteAllItems();
	list.AddItem(0,folderName,"folder","null",projectId, projectPath);
	createFSEntity(projectId,projectPath);
}

function uploadFiles(fileToUpload,projectId,projectPath)
{
	if(!isRequired(fileToUpload))
	{
		alert("Please enter filename to upload");
		return;
	}

	//document.all.filetoupload.value="";
		
	// RPC check if file exist
	var filename = fileToUpload.split("\\");
	filename = filename[filename.length-1];
	// alert(filename+"|"+projectId+"|"+projectPath);
	
	/*
	if(rpcSvr.CheckFileExist(filename,projectId,projectPath))
	{
		alert("File already exist");
		return;
	}	
	*/
	
	var type;
	
	if(_browsername_!='Mozilla')
		doc = parent.document.getElementById('IFControl').contentWindow.document;
	else
		doc = parent.document.getElementById('IFControl').contentDocument;
						
	if (doc.getElementById("activeDiv").value == "allMsgDiv")
		type = "file-all";
	else
		type = "file";
	
	list.DeleteAllItems();
	list.AddItem(0,fileToUpload,type,"null",projectId,projectPath);
    createFSEntity(projectId,projectPath);
}


function createFSEntity(projectId,projectPath)
{
	if(_browsername_!='Mozilla')
		doc = parent.document.getElementById('IFControl').contentWindow.document;
	else
		doc = parent.document.getElementById('IFControl').contentDocument;
						
	
	doc.hideAllPanels();
	if(_browsername_!='Mozilla')
		var f = document.getElementById("operationsarea").contentWindow.document;
	else
		var f = document.getElementById("operationsarea").contentDocument;
	
	f.getElementById('projectid').value=projectId;
	f.getElementById('projectpath').value=projectPath;
	f.getElementById('operation').value="createfs";
	f.getElementById('selecteditems').value = list.Serialize();
	f.getElementById('operate').submit();
	list.DeleteAllItems();
}
// File operation fx ends here


// Search operation fx starts here
function SearchItem(/*type,arg1,arg2,...*/)
{
	var args = arguments;
	var type = args[0];
	var itemid = args[1];

	// Filters
	var f1 = args[2];
	//alert("Search Item : "+ f1);

	//alert('id:'+itemid+' type:'+type+' usertype:'+f1);

	var f2 = args[3]; // Sender
	var f3 = args[4]; // From Date
	var f4 = args[5]; // To Date
	var f5 = args[6]; // Project id
	var f6 = args[7]; // Project path
	//alert("type:"+type+" itemid:"+itemid+" arg2:"+f1+" arg3:"+f2+" arg4:"+f3+" arg5:"+f4);
	
	var re = new RegExp("none", "g");
	var result1 = f3.match(re);
	var result2 = f4.match(re);
   
	if (result1 && result2)
	{f3="";	f4="";	}
	else if(result1)	f3 = "";
	else if(result2)	f4 = "";	
	else
	{
		arr = f3.split("-");
		if (!isDate(arr[2]+"-"+arr[1]+"-"+arr[0]))
			return;
			
		arr = f4.split("-");
		if (!isDate(arr[2]+"-"+arr[1]+"-"+arr[0]))
			return;
	}
	
	if (type=='email')
	{
		var f7 = args[8]; // Text search
		var filter;	
		filter = "subject="+escape(f1);
		filter += "&sender="+escape(f2);	
		filter += "&fromdate="+escape(f3);	
		filter += "&todate="+escape(f4);		
		filter += "&body="+escape(f7);
		//alert("filter:"+filter+" FromDate:"+f3+" Todate:"+f4);
		//return false;
		document.frames["operationsarea"].ShowEmailMessages('','',filter,0,'',f5,f6);
	   
	}
	if (type=='allmsg')
	{
		var f7 = args[8]; // Text search
		var filter;	
		filter = "title="+escape(f1);
		filter += "&type="+escape(f2);	
		filter += "&fromdate="+escape(f3);	
		filter += "&todate="+escape(f4);		
		document.frames["operationsarea"].ShowAllItems(filter,0,'',f5,f6);
	}
	else if (type=='fax')
	{
		var filter;	
		filter = "subject="+escape(f1);
		filter += "&callerid="+escape(f2);	
		filter += "&fromdate="+escape(f3);	
		filter += "&todate="+escape(f4);
		//alert("filter:"+filter+" PrjId:"+f5+" PrjPath:"+f6);
		document.frames["operationsarea"].ShowFaxMessages(itemid,filter,0,'',f5,f6);
	}
	else if (type=='voice')
	{
		var filter;	
		filter = "allocatednumber="+escape(f1);
		filter += "&callerid="+escape(f2);	
		filter += "&fromdate="+escape(f3);	
		filter += "&todate="+escape(f4);	
		document.frames["operationsarea"].ShowVoiceMessages(itemid,filter,0,'',f5,f6);
	    //alert("filter:"+filter+" PrjId:"+f5+" PrjPath:"+f6+" F4:"+f4);
	}
	else if (type=='phone')
	{
		var filter;	
		filter = "subject="+escape(f1);
		filter += "&from="+escape(f2);	
		filter += "&fromdate="+escape(f3);	
		filter += "&todate="+escape(f4);
		//alert("filter:"+filter+" PrjId:"+f5+" PrjPath:"+f6+" PrjPath:"+f4);	
		document.frames["operationsarea"].ShowPhoneMessages(itemid,filter,0,'',f5,f6);
	}	
	else if (type=='call')
	{
		var filter;	
		//filter = "allocatednumber="+escape(f1);
		filter = "dialednumber="+escape(f1);
		filter += "&callerid="+escape(f2);	
		filter += "&fromdate="+escape(f3);	
		filter += "&todate="+escape(f4);	
		document.frames["operationsarea"].ShowPhoneCalls(itemid,filter,0,'',f5,f6);
	    //alert("filter:"+filter+" PrjId:"+f5+" PrjPath:"+f6+" F4:"+f4);
	}
	else if (type=='snail')
	{
		var filter;	
		filter = "sender="+escape(f1);
		if (f2)
			filter += "&status="+escape(f2);	
		filter += "&fromdate="+escape(f3);	
		filter += "&todate="+escape(f4);	
		document.frames["operationsarea"].ShowSnailMail(filter,0,'');
	}	
	else if (type=='file')
	{
		var f7 = args[8]; // Text search
		var filter;	
		filter = "name="+escape(f1);
		filter += "&size="+escape(f2);	
		filter += "&fromdate="+escape(f3);	
		filter += "&todate="+escape(f4);	
		filter += "&text="+escape(f7);	
		//alert("filter:"+filter);	
		document.frames["operationsarea"].ShowProjectItems('',filter,0,'',f5,f6);
	}			
	else if (type=='userlist')
	{
		document.frames["operationsarea"].crmProjectList(f1,itemid);
		//document.frames["operationsarea"].ShowProjectItems(f1,'',filter,0,'',f5,f6);
	}
	else if (type=='crmorders')
	{
		//alert(f1+'|'+f2+'|'+itemid);
		document.frames["operationsarea"].crmOrderList('','',itemid);
		//document.frames["operationsarea"].ShowProjectItems(f1,'',filter,0,'',f5,f6);
	}
	else if (type=='crmUsers')
	{
		var filter;
		filter = "name="+escape(itemid);
		//alert('type:'+type+'| item:'+itemid+'|userType:'+f1+'|filter:'+filter);
		//filter += "&size="+escape(f2);
		document.frames["operationsarea"].ShowCRMUsers(itemid,f1,'','',filter);
		//document.frames["operationsarea"].ShowProjectItems(f1,'',filter,0,'',f5,f6);
	}
}
// Search operation fx ends here

function showCRMTab()
{
	var args = arguments;
	var divName = args[0];
	//alert(document.getElementById("activePanel").value);	

	hideAllPanels();	
	clearPanel(divName);
		
	document.getElementById("activePanel").value = divName;	

	lastDiv = document.getElementById("activeDiv").value;
	if (document.getElementById(lastDiv+"Content"))
		var objDiv = document.getElementById(lastDiv+"Content");

	document.getElementById(divName+"Div").style.display = 'block';

	var divOffset;
	if (lastDiv == "projectSummaryDiv") // No header of size 32 (60-36)
		divOffset = 36;
	else
		divOffset = 68;

	if (divName=="crmchat")
	{
		var type = args[1];

		var halfheight = parseInt(parseInt(objDiv.style.height)/2);		
		var h = parseInt(objDiv.style.height)-halfheight;
		h = h - 32; // 32 is header size, decrease size of header for content
		objDiv.style.height = h;
		
		h = h + 32; // 32 is header size, increase size of header for preview
		document.all.CRMChatFrame.style.height = h;		
	}	
}
// Panel fx starts here
function showPanel(/* divName,projectId,projectPath */)
{
	var args = arguments;
	var divName = args[0];
	//alert(divName);	

	hideAllPanels();	
	clearPanel(divName);
		
	document.getElementById("activePanel").value = divName;	

	lastDiv = document.getElementById("activeDiv").value;
	if (document.getElementById(lastDiv+"Content"))
		var objDiv = document.getElementById(lastDiv+"Content");
	
	/*
	if (document.getElementById(divName+"Div").style.display=='block')
		return;
	*/

	document.getElementById(divName+"Div").style.display = 'block';

	var uploadDivHeight = parseInt(document.all.fileUploadDiv.style.height);
	
	var divOffset;
	if (lastDiv == "projectSummaryDiv") // No header of size 32 (60-36)
		divOffset = 36;
	else
		divOffset = 68;
	
//	var h = parseInt(document.getElementById('IFControl').document.body.clientHeight)-uploadDivHeight-divOffset;
	if(_browsername_!='Mozilla')
		doc = parent.document.getElementById('IFControl').contentWindow.document;
	else
		doc = parent.document.getElementById('IFControl').contentDocument;

	var h = parseInt(doc.body.clientHeight)-uploadDivHeight-divOffset;
	
	if (document.all.projectNav.style.display=="block")
		h-=parseInt(document.getElementById('projectNav').style.height);

	if (divName=="fileUpload" || divName=="folderCreate")
	{
		var projectId = args[1];
		var projectPath = args[2];
		
		if (objDiv)
			objDiv.style.height = h;			
		//document.all.projectMsgDivContent.style.height = h;
		//document.all.faxMsgDivContent.style.height = h;
		
		document.getElementById('uploadProjectId').value=projectId;
		document.getElementById('uploadProjectPath').value=projectPath;
		if (divName=="fileUpload")
			document.all.filetoupload.focus();
		else
			document.getElementById('foldername').focus();
	}
	else if (divName=="searchAllMsg")
	{
		document.getElementById('allMsgDivContent').style.height = h;		
		document.getElementById('allmsgTitle').focus();
	}
	else if (divName=="searchEmail")
	{
		document.getElementById('emailMsgDivContent').style.height = h;		
		document.getElementById('emailsubject').focus();
	}
	else if (divName=="searchProject")
	{
		document.getElementById('projectListDivContents').style.height = h;		
	}
	else if (divName=="searchcrm")
	{
		document.getElementById('crmListDivContents').style.height = h;		
	}
	else if (divName=="searchcustomer")
	{
		document.getElementById('crmCustomerDivContents').style.height = h;		
	}
	else if (divName=="searchFax")
	{
		document.getElementById('faxMsgDivContent').style.height = h;		
		document.getElementById('faxcallerid').focus();
	}
	else if (divName=="searchVoice")
	{
		document.getElementById('voiceMsgDivContent').style.height = h;		
		document.getElementById('voicecallerid').focus();
	}	
	else if (divName=="searchPhone")
	{
		document.getElementById('phoneMsgDivContent').style.height = h;		
		document.getElementById('phonesubject').focus();
	}
	else if (divName=="searchCall")
	{
		document.getElementById('phoneCallDivContent').style.height = h;		
		document.getElementById('phonecallid').focus();
	}	
	else if (divName=="searchSnail")
	{
		document.getElementById('snailMsgDivContent').style.height = h;		
		document.getElementById('snailsender').focus();
	}
	else if (divName=="searchFile")
	{
		document.getElementById('projectMsgDivContent').style.height = h;		
		document.getElementById('filename').focus();
	}					
	else if (divName=="preview")
	{
		var type = args[1];

		var halfheight = parseInt(parseInt(objDiv.style.height)/2);		
		var h = parseInt(objDiv.style.height)-halfheight;
		h = h - 32; // 32 is header size, decrease size of header for content
		objDiv.style.height = h;
		
		h = h + 32; // 32 is header size, increase size of header for preview
		document.getElementById('previewDivContent').style.height = h;		

		/*		
		if (type=="email")
		{
			var halfheight = parseInt(parseInt(objDiv.style.height)/2);		
			var h = parseInt(objDiv.style.height)-halfheight-32; // 32 is header size

			objDiv.style.height = halfheight;
			document.all.previewDivContent.style.height = h;		
		}
		else if (type=="snail")
		{
			var halfheight = parseInt(parseInt(document.all.snailMsgDivContent.style.height)/2);		
			var h = parseInt(document.all.snailMsgDivContent.style.height)-halfheight-32; // 32 is header size

			document.all.snailMsgDivContent.style.height = halfheight;
			document.all.previewDivContent.style.height = h;		
		}
		else if (type=="phone")
		{
			var halfheight = parseInt(parseInt(document.all.phoneMsgDivContent.style.height)/2);		
			var h = parseInt(document.all.phoneMsgDivContent.style.height)-halfheight-32; // 32 is header size

			document.all.phoneMsgDivContent.style.height = halfheight;
			document.all.previewDivContent.style.height = h;		
		}
		*/
	}
}

function hidePanel(divName)
{
	var lastDiv = document.getElementById("activeDiv").value;
	
	if (document.getElementById(lastDiv+"Content"))
		var objDiv = document.getElementById(lastDiv+"Content");
				
	if (lastDiv == "projectSummaryDiv") // No header of size 32 (60-36) 
		divOffset = 36;
	else
		divOffset = 68;

	if(_browsername_!='Mozilla')
		doc = parent.document.getElementById('IFControl').contentWindow.document;
	else
		doc = parent.document.getElementById('IFControl').contentDocument;
												
	//var h = parseInt(document.getElementById('IFControl').document.body.clientHeight)-divOffset;
	var h = parseInt(doc.body.clientHeight)-divOffset;	
	
	if (document.all.projectNav.style.display=="block")
		h-=parseInt(document.getElementById('projectNav').style.height);	

	if (divName=="fileUpload" || divName=="folderCreate")
	{
		if (objDiv)
			objDiv.style.height = h;
			
		/*
		document.all.projectMsgDivContent.style.height = h;
		document.all.faxMsgDivContent.style.height = h;
		document.all.allMsgDivContent.style.height = h;
		*/
	}
	else if (divName=="searchAllMsg")
		document.getElementById('allMsgDivContent').style.height = h;	
	else if (divName=="searchEmail")
		document.getElementById('emailMsgDivContent').style.height = h;	
	else if (divName=="searchFax")
		document.getElementById('faxMsgDivContent').style.height = h;	
	else if (divName=="searchVoice")
		document.getElementById('voiceMsgDivContent').style.height = h;	
	else if (divName=="searchProject")
		document.getElementById('projectListDivContents').style.height = h;	
	else if (divName=="searchcrm")
		document.getElementById('crmListDivContents').style.height = h;	
	else if (divName=="searchPhone")
		document.getElementById('phoneMsgDivContent').style.height = h;	
	else if (divName=="searchSnail")
		document.getElementById('snailMsgDivContent').style.height = h;	
	else if (divName=="searchFile")
		document.getElementById('projectMsgDivContent').style.height = h;		
	else if (divName=="searchCall")
		document.getElementById('phoneCallDivContent').style.height = h;			
	else if (divName=="preview")
	{
		/*
		document.all.emailMsgDivContent.style.height = h;	
		document.all.phoneMsgDivContent.style.height = h;	
		document.all.snailMsgDivContent.style.height = h;				
		*/
		if (objDiv)
			objDiv.style.height = h;		
	}
	
	document.getElementById(divName+"Div").style.display = 'none';
}

function hideAllPanels()
{
	var lastPanel = document.getElementById("activePanel").value
	
	//alert('hid\'g panel:'+lastPanel);	
	if (lastPanel != "none")
		hidePanel(lastPanel);
		
	/*
	hidePanel('fileUpload');
	hidePanel('folderCreate');
	hidePanel('searchEmail');	
	hidePanel('searchFax');	
	hidePanel('searchVoice');		
	hidePanel('searchPhone');	
	hidePanel('searchSnail');
	hidePanel('searchFile');	
	hidePanel('preview');	
	*/
}

function clearPanel(divName)
{
	var elems = document.getElementById(divName+"Div").all;
   	for(var i=0;i<elems.length;i++){
		if(elems[i].type=="radio")
		   	elems[i].checked=false;
		else if(elems[i].type=="checkbox")
		{
			elems[i].click();
		   	if (elems[i].checked)
				elems[i].click();
		}
		else if(elems[i].type=="select-one")
		{
			elems[i].options[0].selected=true;
		}
		else if(elems[i].type=="text" || elems[i].type=="textarea" || elems[i].type=="password") //changes in this line by mustafa
		   	elems[i].value="";
	}
}
// Panel fx ends here
// Item move functions starts here
function moveContents(projectId,projectPath,type)
{
	
	projectType = (typeof(type)!='undefined' ? type : 0);
	if (downFlag==1)
	{
		ShowBlockDiv();	
		if (list.CheckSameType('snail'))
		{
			alert("Snail mail are not allowed to move");
			return;
		}
		
        if(!projectPath)
            projectPath = "null";
            
		//alert('src: '+list.GetSource()+', dst:'+projectId);
		//alert('src: '+list.GetSourcePath()+', dst:'+projectPath);
		if(list.GetSource() == projectId && list.GetSourcePath() == projectPath)
        {
			alert('Cannot move. The source and destination are the same');
			return;
 		}

		if (list.GetItemCount()>0)
		{
			//list.ShowItems();
			//alert('c'+document.getElementById("operationsarea").contentDocument.getElementById("projectid").value);
			if(_browsername_!='Mozilla')
				var f = document.getElementById("operationsarea").contentWindow.document;
			else
				var f = document.getElementById("operationsarea").contentDocument;
			f.getElementById('projectid').value=projectId;
			f.getElementById('projectpath').value=projectPath;
			f.getElementById('operation').value="move";
			f.getElementById('selecteditems').value = list.Serialize();
			//document.frames["operationsarea"].document.all.operate.submit();
			PostAjaxScreen("datafetch",f.getElementById('operate'),{onSuccess:moveContentsCallback});
		}
		downFlag=0;
	}
		
}
function moveContentsCallback(response)
{
	HideBlockDiv();
	var addParameter='';
	//debugger;
	if(typeof(list.items[0])!="undefined")
	{
		if( typeof(list.GetSource())=="undefined")
			pid=-1;
		else
			pid=list.GetSource();
	}
	else
		pid=-1;
	
	if(typeof(list.items[0])!="undefined")
	{
		if(typeof(list.GetSourcePath())=="undefined")
			path=-1;
		else
			path =	list.GetSourcePath();
	}
	else
		path = -1;
	if( isFolder == 1)
	{
		
		isFolder = -1;
		var ajaxUrl = "index.php?SCREEN=showprojects&sid=" + _sessionid_ +"&projectid="+pid+"&projectpath=";
		var url = "http://" + parent.IFControl.location.host + "/index.php?SCREEN=navigate&sid=" + _sessionid_ +"&divScreen=showprojects&projectid="+pid+"&projectpath=";
		var op = {"url":ajaxUrl};
    	op = JSON.encode(op);
		setCookie("last_ajax_action", op);
		//parent.IFControl.location.href = "http://tariq.io.com/index.php?SCREEN=navigate&sid=42e10bcfcdd94f5ad824809e7211f8e4&divScreen=showprojects&projectid="+pid+"&projectpath=";
		parent.IFControl.location.href = url;

		return true;
	
	}
	if( isFolder == 0)
	{
		isFolder = -1;
		var ajaxUrl = "index.php?SCREEN=showprojects&sid=" + _sessionid_ +"&projectid="+pid+"&projectpath=&list=true&projectTitle=Project List";
		var url = "http://" + parent.IFControl.location.host + "/index.php?SCREEN=navigate&sid=" + _sessionid_ +"&divScreen=showprojects&projectid="+pid+"&projectpath=&list=true&projectTitle=Project List";
		var op = {"url":ajaxUrl};
    	op = JSON.encode(op);
		setCookie("last_ajax_action", op);
		//parent.IFControl.location.href = "http://tariq.io.com/index.php?SCREEN=navigate&sid=42e10bcfcdd94f5ad824809e7211f8e4&divScreen=showprojects&projectid=&projectpath=&list=true";
		parent.IFControl.location.href = url;
		return true;
	}
	var divType="";
	var divName="";
	if(typeof(list.GetType()) == 'undefined')
		if(this.callingFrom!='' && this.callingFrom=="email")
			{
				if(this.page!='')
					addParameter+="&page="+this.page;
				if(this.filter!='')
					addParameter+="&filter="+this.filter;
				
				divName="showemailmessages"+addParameter;
			}
	if(list.GetType() == "fax")
		divName="showfaxmessages";
	else if(list.GetType() == "voice")
		divName="showvoicemail";
	else if(list.GetType() == "phone")
		divName="showphonemessage";
	else if(list.GetType() == "call")
		divName="showphonecall";
	else if(list.GetType() == "email")
		{
			if(this.page!='')
				addParameter+="&page="+this.page;
			if(this.filter!='')
				addParameter+="&filter="+this.filter;
			
			divName="showemailmessages"+addParameter;
		}
	else if(list.GetType() == "file-all")
		divName="showdocuments";
	//LoadAjaxScreen('showfaxmessages&projectid='+pid+'&projectpath='+path());
	if(pid==-1 && path==-1 )
		LoadAjaxScreen(divName+'&projectid='+pid+'&projectpath='+path);
	else
	{
		if(projectType==32)
		{
			LoadAjaxScreen('showdocuments&type='+list.GetType()+'&divName='+divName+'&projectid='+pid+'&projectpath='+path);
		}
		else
		{
			LoadAjaxScreen('showprojects&type='+list.GetType()+'&divName='+divName+'&projectid='+pid+'&projectpath='+path);
		}
		
	}			
	list.DeleteAllItems();
	if(typeof(srcW) != 'undefined')
		srcW.HideWaitDialog();
}

function resetContents(dest,id,page,filter)
{
	//alert(dest+','+id);
	//alert('reset');
	this.page = page;
	this.filter = filter;
	if (downFlag==1)
	{
		//alert('src: '+list.GetSource()+', dst:'+dest);
		if(dest=='projectroot')
	    {
			alert('Please move to Project or Sub-project');
	        return;
	    }
	    else if(dest=='personalroot')
	    {
			alert('Please move to Project or Sub-project');
	        return;
	    }		
	    else if(dest=='deptroot')
	    {
			alert('Please move to Project or Sub-project');
	        return;
	    }		
	    else if(dest=='externalroot')
	    {
			alert('Please move to Project or Sub-project');
	        return;
	    }		
	    else if(dest=='companyroot')
	    {
			alert('Please move to Project or Sub-project');
	        return;
	    }		
	    else if(dest=='branchroot')
	    {
			alert('Please move to Project or Sub-project');
	        return;
	    }		
	    else if(dest=='userroot')
	    {
			alert('Please move to Project or Sub-project');
	        return;
	    }
	    		
		if (list.CheckSameType('snail'))
		{
			alert("Movement of Snailmail(s) are not allowed");
			return;
		}
	    if(dest==1)
	    {
			alert('Move to Sent Items is not allowed');
	        return;
	    }
	    else if(dest=='snailroot')
	    {
			alert('Can\'t move item(s) to postal mail node.');
	        return;
	    }
	    else if(dest=='emailroot')
	    {
			alert('Can\'t move item(s) to email root node. Please move to Inbox or Trash');
	        return;
	    }
	    else if(dest=='emailaccountroot')
	    {
			alert('Can\'t move email(s) to email account root node. Please move to Inbox or Trash');
			return;
	    }
		
	    else if(dest=='faxroot')
	    {
			alert('Can\'t move item(s) to fax messages root node. Please move to fax number node');
	        return;
	    }
		else if(dest=='phoneroot')
	    {
			alert('Can\'t move item(s) to phone messages root node. Please move to phone number node');
	        return;
	    }
		else if(dest=='voiceroot')
	    {
			alert('Can\'t move item(s) to voice mail root node. Please move to phone number node');
	        return;
	    }	
		else if(list.GetSource()!='-1' && dest!=0 && dest!=1 && dest!=2)
	    {
			alert('Please move to another Project or Sub-project');
	        return;
	    }	

		
		if(dest!=0 && dest!=1 && dest!=2 && dest!=5) // 0='inbox', 2='trash', 1='outbox' 5='spam'
		{	
			if (!list.CheckSameType(dest))
			{
				alert("This operation is valid only for the same type of item(s)");
				return;
			}
		}
		if(dest >=0 && dest <=5)
			if(list.GetSource() != -1)
			{
				alert('Can\'t move email(s) from project to Email account');
				return;
			}
		if(dest==0 || dest==2)
			if (!list.CheckSameType('email'))
			{
				alert("Only emails are allowed to move");
				return;
			}

		if(list.GetSource() == 'null' && (dest!=0 && dest!=1 && dest!=2))
        {
			alert('Can\'t move item(s). The source and destination are same');
			return;
 		}
		//alert(list.GetItemCount());
		if (list.GetItemCount()>0 )
		{
			//list.ShowItems();
			document.getElementById("operationsarea").contentWindow.document.all.dest.value=dest;
			document.getElementById("operationsarea").contentWindow.document.all.emailaccountid.value=id;
			document.getElementById("operationsarea").contentWindow.document.all.operation.value="reset";
			document.getElementById("operationsarea").contentWindow.document.all.selecteditems.value = list.Serialize();
			PostAjaxScreen("datafetch",document.getElementById("operationsarea").contentWindow.document.all.operate,{onSuccess:moveContentsCallback});
			//document.frames["operationsarea"].document.all.operate.submit();		
			//list.DeleteAllItems();
		}
		
		//*/
		downFlag=0;

	}
}


function deleteEMail(currentFolder,dest,linkid,page,filter,callingFrom)
{
	//alert(currentFolder);
	this.page = page;
	this.filter = filter;
	this.callingFrom = callingFrom;
	deleteContents();
	/*
	if(currentFolder == 1) // if 'trash' (0='inbox', 1='trash', 2='outbox')
	{
		deleteContents();
	}
	else
	{
	    downFlag=1;
        resetContents(dest,linkid)
	}
	*/
}
var isFolder;
function deleteProject(projectId)
{
	isFolder = 0;
	if (confirm('Are you sure you want to delete this project?'))
	{
		list.DeleteAllItems();
		list.AddItem(0,projectId,"project");
		deleteContents(-1,-1,isFolder);
	}
}

function deleteContents(projectId, projectPath, isfolder)
{
	isFolder = isfolder;
	if(isfolder == 1)
	{
		msg = 'Are you sure you want to delete sub-project: \''+projectPath+'\' ?';
    	if (!confirm(msg))
			return;
    }
	//else if(isfolder == 0)
	else if (list.GetType() != "project")
	{
		msg = 'Are you sure you want to delete selected item(s)?';
    	if (!confirm(msg))
			return;
	}

	if(_browsername_!='Mozilla')
		var f = document.getElementById("operationsarea").contentWindow.document;
	else
		var f = document.getElementById("operationsarea").contentDocument;
	
			f.getElementById('projectid').value=(typeof(projectId)=='undefined') ? -1 : projectId;
			f.getElementById('projectpath').value=(typeof(projectPath)=='undefined') ? -1 : projectPath;
			f.getElementById('operation').value="move";
			
	if(projectId)
		f.getElementById('projectid').value=projectId;


	if(projectPath)
			f.getElementById('projectpath').value=projectPath;
		
	if(isfolder)
	{
		// confirm("Are you sure you want to delete project");
		list.DeleteAllItems();
		list.AddItem(0,projectPath,"folder","null",projectId,projectPath);
		//document.frames["operationsarea"].document.all.isfolder.value=isfolder;
	}

	f.getElementById('operation').value="delete";
	f.getElementById('selecteditems').value=list.Serialize();

	PostAjaxScreen("datafetch",f.getElementById('operate'),{onSuccess:moveContentsCallback});
	
}
// Item move / delete functions ends here


// Key capture fx starts here
function isEnterKey(evt)
{

	if(evt=='undefined')
		evt = window.event;
	evt = (evt) ? evt : event;
	if(evt.keyCode == 13 )
		return true;
	else
		return false;
}

function keydown(event)
{
	if(typeof(event)=='undefined')
		event = window.event;
	//window.status='dcode:'+event.keyCode;
	if(event.keyCode==17)
	{
		//window.status = 'dn:'+list.GetSource();
		if (moveFlag==1 && list.GetSource() != -1)
		{
			
			if(_browsername_!='Mozilla')
			{
				
				if(document.getElementById("operationsarea"))
					var f = document.getElementById("operationsarea").contentWindow.document;
				else
				{
					var f = parent.document.getElementById("IFControl").contentWindow.document.getElementById("operationsarea").document;
				}
			}
			else
			{
				if(document.getElementById("operationsarea").contentDocument)
					var f = document.getElementById("operationsarea").contentDocument;
				else
					var f = parent.document.getElementById("IFControl").contentWindow.contentDocument.getElementById("operationsarea").contentDocument
			}
			
			f.getElementById('copy').value=ctrlkeypressed;
			
			if(f.getElementById("ctrldiv"))		
				f.getElementById("ctrldiv").innerHTML="+";
		}
		ctrlkeypressed = 1;
	}
	else
		ctrlkeypressed = 0;
	
	if(event.keyCode==16)
		shiftkeypressed = 1;
	else
		shiftkeypressed = 0;		
}

function keyup(event)
{
	if(typeof(event)=='undefined')
		event = window.event;
	//window.status='ucode:'+event.keyCode;
	if (event.keyCode==17)
	{
		//window.status = 'up:'+list.GetSource();
		if (moveFlag==1 && list.GetSource() != -1)
		{
			document.frames["operationsarea"].document.all.copy.value=ctrlkeypressed;
			document.getElementById("ctrldiv").innerHTML="&nbsp;";
		}
		ctrlkeypressed = 0;
	}
	
	if (event.keyCode==16)
		shiftkeypressed = 0;	
}
// Key capture fx ends here

// Drag n Drop functions starts here
function bcmdClick(caller, sno)
{
	downFlag=0;
	moveFlag=0;
	dd.elements.dragdiv.hide();
	//list.DeleteAllItems();
}

function bcmdMoveClick(event)
{

	if(typeof(event)=='undefined')
		event = window.event;
    if (moveFlag==1)
    {
		var buttonid = event.button;
		//	left button,	  threshold x,						   threshold Y,							 only check once on drag start
		if (buttonid!=2 && ( (Math.abs(moveXth-event.clientX)>1 || Math.abs(moveYth-event.clientY)>1) || downFlag==1) )
		{
			downFlag=1;
			dflag=1;
			dd.elements.dragdiv.moveTo(event.clientX+1 ,event.clientY+1);
			dd.elements.dragdiv.show();
		}
	}
}

function moveDiv(event)
{
	if(typeof(event)=='undefined')
		event = window.event;
	moveFlag=1;
	
	if(_browsername_!='Mozilla')
		doc = parent.document.getElementById('IFControl').contentWindow.document;
	else
		doc =parent.document.getElementById('IFControl').contentDocument;


	//document.all.dragdiv.innerHTML="<span id=ctrldiv style='display: block;'></span> <table cellpadding=2 width=100% cellspacing=0 border=0><tr><td class=dragitem><table width=100% border=0 cellpadding=2 cellspacing=0><tr>"+list.GetAllItemsHtml()+"</tr></table></td></tr></table>";
	doc.getElementById('dragdiv').innerHTML="<table cellspacing=0 cellpadding=0 border=0 width=100%><tr><td colspan=2><img src='images/blank.gif' height='8'></td></tr></table><table class='gridtable' style='padding:0px' cellpadding=0 width=100% cellspacing=0 border=0><tr><td id=ctrldiv class=dragitemHead align=center valign=top width='20'>&nbsp;</td><td ><table width=100% border=0 cellpadding=0 cellspacing=0><tr>"+list.GetAllItemsHtml()+"</tr></table></td></tr></table>";
	//document.all.dragdiv.innerHTML = "15";	
		// Saves X and Y for threshold of movement
	moveXth = event.clientX+1;
	moveYth = event.clientY+1;	
	//dd.elements.dragdiv.moveTo(event.clientX+1 ,event.clientY+1);
}
// Drag n Drop functions ends here


// Highlight fx starts here
function highlightRow(rowId, status,event)
{
	if(typeof(event)=='undefined')
		event = window.event;
	var srcEl = event.srcElement? event.srcElement : event.target; 
	
	if(typeof(srcEl)!='undefined')
	{
		var o = srcEl.parentNode.parentNode;
		var trs = o.getElementsByTagName("tr");
	}
	else
	{
		var trs = document.getElementById(rowId);
	}
	if(trs.length > 0)
	{
		for (var trcount=0;trcount<trs.length;trcount++)
		{
			//alert('checking:'+trs[trcount].id+" / "+rowId);
			if(typeof(trs[trcount])!='undefined')
			{
				if (trs[trcount].id == rowId)
				{
					//alert(rowId+':found');
					var tds = trs[trcount].getElementsByTagName("td");
		
					for (var tdcount=0; tdcount<tds.length;tdcount++)
					{
						if(status) // select (highlight)
						{
							tds[tdcount].style.backgroundColor='highlight';
							tds[tdcount].style.color='white';
						}
						else // deselect
						{
							tds[tdcount].style.backgroundColor='';
							tds[tdcount].style.color='black';
						}
					}
					break;
				}
			}
		}
	}
	else
	{
		var tds = trs.getElementsByTagName("td");
		for (var tdcount=0; tdcount<tds.length;tdcount++)
		{
			if(status) // select (highlight)
			{
				tds[tdcount].style.backgroundColor='highlight';
				tds[tdcount].style.color='white';
			}
			else // deselect
			{
				tds[tdcount].style.backgroundColor='';
				tds[tdcount].style.color='black';
			}
		}
		
	}
}

function highlightAllRows(status,event)
{
	if(typeof(event)=='undefined')
		event = window.event;
	var srcEl = event.srcElement? event.srcElement : event.target; 
	var o = srcEl.parentNode.parentNode;
	//alert(status + "---" + o.outerHTML);
	var arrTR = o.getElementsByTagName("tr");

	//list.ShowItems();
	for(var i=0;i<arrTR.length;i++)
	{
		//alert("TR:"+arrTR[i].outerHTML);
		for (var x=0;x<list.items.length;x++)
		{
		    if (list.items[x]["row"] == arrTR[i].id)
		    {
		        //alert('row '+arrTR[i].id+' ... processing');
		        list.DeleteItem(arrTR[i].id);
				highlightRow(arrTR[i].id,false,event);
				break;
			}
			
		}
		// removed only selected highlighted rows, not all
		// highlightRow(arrTR[i].id,status);
	}
}
// Highlight fx ends here


// TR Mouse down / up functions starts here
selectedFlag = false;
function trMouseUp(caller,sno,srcProjectId,srcProjectPath,event,fileid)
{
	if(typeof(event)=='undefined')
		event = window.event;
	var srcEl = event.srcElement? event.srcElement : event.target; 
	
	var buttonid = event.button;

	if(selectedFlag && (typeof(fileid) != 'undefined' || buttonid!=2) && downFlag==0)
	{
		var rowno = srcEl.parentNode.id;
		
		if(list.SearchItem(rowno)) // if already selected and multiple items are not dragged
		{
			highlightAllRows(false,event);
			var ihtml = "<table width=100% border=0 cellpadding=2 cellspacing=0><tr>"+srcEl.parentNode.innerHTML+"</tr></table>";
			list.AddItem(rowno,sno,caller,ihtml,srcProjectId,srcProjectPath,fileid);
			highlightRow(rowno, true,event);
		}
		selectedFlag = false;					
	}
}
function pause(numberMillis) 
{ 
	var now = new Date(); 
	var exitTime = now.getTime() + numberMillis; 
	while (true) 
	{ 
		now = new Date(); 
		if (now.getTime() > exitTime) 
			return; 
	} 
}

function trClick(/*caller,arg1,arg2,...*/)
{
	if (!autopreview)
		return;
	
	//pause(360); 
	var elem = document.getElementById("emailMsgDivContent");
	//elem.scrollTop = 0;
	
	/*
	var b = event.clientY; 
	alert(b+"||"+elem.scrollTop);	var c =500;// b + elem.scrollTop;
	elem.scrollTop = c;
	alert(c+"\\"+elem.scrollTop);
	*/
	var args = arguments;
	var caller = args[0];
	
	if (caller=="email" || caller=="email-all")
	{
		var mailid = args[1];
		var accountId = args[2];
		var read = args[3];
		var folderid = args[4];
		var projectid = args[6];
		var projectpath = args[7];				
		if (list.CheckSameType("email") || list.CheckSameType("email-all"))
		{
			parent.LoadPreviewScreen("viewmail&preview=1&mailId="+mailid+"&folderId="+folderid+"&read="+read+"&projectid="+projectid+"&projectpath="+projectpath);
			showPanel("preview","email");
		}	
		// mark as read in grid
		event.srcElement.parentElement.className = 'gridcolumnItem';	
		// td reference to focus td after resize
//		var o = args[5];
//		alert(args[5]);
		//alert(args[5]+"|"+args[0]+"|"+args[1]+"|"+args[2]+"|"+args[4]);
//		o.onblur = function() {window.status = 'blurred'; };	
//		o.onfocus = function() {window.status = 'focused'; };	
		if(args[5].focus)
			args[5].focus();
		
	}
	else if (caller=="snail")
	{
		var recid = args[1];
		if (list.CheckSameType("snail"))
		{
			parent.LoadPreviewScreen("showmail&preview=1&recordid="+recid);
			showPanel("preview","snail");
		}			
	}
	else if (caller=="phone" || caller=="phone-all")
	{
		return true;
		var sno = args[1];
		if (list.CheckSameType("phone") || list.CheckSameType("phone-all"))
		{
			event.srcElement.parentElement.className = 'gridcolumnItem';				
			parent.LoadPreviewScreen("phonemsg&preview=1&sno="+sno);
			showPanel("preview","phone");
		}			
	}	
}

function trFolderMouseDown()
{
	var buttonid = window.event.button;
	folder=1;
}

var shiftselection = 0;
function trMouseDown(caller,sno,srcProjectId,srcProjectPath,drag,event)
{
	//debugger;
	if(typeof(event)=='undefined')
		event = window.event;
	if(drag.length == 0)
		drag = 1;	
	if(typeof(drag) == "undefined")
			drag = 1;	
	var srcEl = event.srcElement? event.srcElement : event.target; 
	//alert('Caller:'+caller+'  Sno:'+sno+' srcPId:'+srcProjectId+' srcPPath:'+srcProjectPath);
	var otable = GetFirstParentOfType(srcEl,"table");
	var tableId = otable.id;
	//alert(otable.tagName.toUpperCase());


	rowno = srcEl.parentNode.id;
	//alert(caller+"|"+rowno+"|"+sno+"|"+event.srcElement.parentElement.outerHTML);

	var buttonid = event.button;
	
	//moveDiv();
	if(ctrlkeypressed == 1) // if control key is down/pressed
	{
		shiftselection = 0;
		ctrlkeypressed = 0;

		if ((_browsername_!="Mozilla" && buttonid == 1) || (_browsername_=="Mozilla" && buttonid == 0)) // if left click
		{
			if(list.SearchItem(rowno)) // if already selected
			{
				list.DeleteItem(rowno);
				highlightRow(rowno, false,event);
			}
			else // if not selected
			{
				var ihtml = "<table width=100% border=0 cellpadding=2 cellspacing=0><tr>"+srcEl.parentNode.innerHTML+"</tr></table>";
				list.AddItem(rowno,sno,caller,ihtml,srcProjectId,srcProjectPath);
				highlightRow(rowno, true,event);
			}
		}
	}
	else if (shiftkeypressed==1)
	{
		//debugger;
		shiftkeypressed = 0;
		var re1 = new RegExp("[0-9]+", "g");
		var re2 = new RegExp("tr", "g");					
		
		if ((_browsername_!="Mozilla" && buttonid == 1) || (_browsername_=="Mozilla" && buttonid == 0)) // if left click
		{	
			var itemToSave; // To save item from which selection need to be started
			var itemRow; // Row of saved item
			
			if (shiftselection == 1) // If shift is kept pressed
			{
				itemToSave = list.items[0];
				// get number from string
				itemRow = parseInt(itemToSave["row"].match(/\d+/));
			}
			else
			{
				itemToSave = list.items[list.items.length-1];
				// get number from string
				itemRow = parseInt(itemToSave["row"].match(/\d+/));
				highlightAllRows(false,event);
			}
			
			// get number from string
			var rno = parseInt(rowno.match(/\d+/));
			//alert('row: from'+itemRow+' - to:'+rno);
			// Select from last (saved item) to clicked item 			
			if (itemRow < rno) // (either top to bottom)
			{
				highlightAllRows(false,event);
				for (var i=itemRow;i<=rno;i++)
				{
					//alert('select row:'+i);
					var o = otable.rows[i];
					var rid = o.id;
					var uid = o.getAttribute("uid");

					caller = rid.replace(re1, "").replace(re2, "");
					var ihtml = "<table width=100% border=0 cellpadding=2 cellspacing=0><tr>"+o.innerHTML+"</tr></table>";
					
					list.AddItem(rid,uid,caller,ihtml,srcProjectId,srcProjectPath);
					highlightRow(rid, true,event);		
				}
			}
			else // (or bottom to top)
			{
				highlightAllRows(false,event);
				for (var i=itemRow;i>=rno;i--)
				{
					//alert('select row:'+i);
					var o = otable.rows(i);
					var rid = o.id;
					var uid = o.getAttribute("uid");
					caller = rid.replace(re1, "").replace(re2, "");

					var ihtml = "<table width=100% border=0 cellpadding=2 cellspacing=0><tr>"+o.innerHTML+"</tr></table>";
					list.AddItem(rid,uid,caller,ihtml,srcProjectId,srcProjectPath);
					highlightRow(rid, true,event);		
				}
			}
		}
		shiftselection = 1; // shift is assumed as pressed until normal click or ctrl click
	}
	else
	{
		shiftselection = 0;
		if(!list.SearchItem(rowno)) // if not already selected
		{
		    //used effiecient way to deselect : highlightAllRows(false); implementation inside
			highlightAllRows(false,event);
			var ihtml = "<table width=100% border=0 cellpadding=2 cellspacing=0><tr>"+srcEl.parentNode.innerHTML+"</tr></table>";
			//alert('def:'+caller+"|"+rowno+"|"+sno+"|"+srcProjectId);
			list.AddItem(rowno,sno,caller,ihtml,srcProjectId,srcProjectPath);
			highlightRow(rowno, true,event);
		}
		selectedFlag = true;
	}
	folder=0;
	if(drag)
		moveDiv(event);
	//list.ShowItems();
}
// TR Mouse down / up functions ends here


// On Double click operations starts here
function playPhoneRecord(sid,type,id)
{
	var uid=list.items[0]['uid'];
	
	ShowWindow("/misc/play.php?type="+type+"&uniqueid="+uid+"&sid="+sid+"&recordid="+id,'no',.2,.2);
}

/*function open_file(filepath)
{
	window.open('misc/downloadfile.php?f='+escape(filepath));
}*/

function doThePopUp()
{
	reWin=window.open('http://www.centre.biz/londonOffice/adddepositwizard.php','hell','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=500,height=500,top=200,left=100')
}

function showphonemsg(sno,ssid)
{
	//return true;
	parent.OpenWizard('viewphonemessage&sno='+sno+'&formProjectModule=yes',"no");
	//parent.OpenWizard('showphonemessage&sno='+sno+'&sid='+ssid+'&formProjectModule=yes',"no");
	event.srcElement.parentElement.className = 'gridcolumnItem';	
}

function projectUpClick(ssid,filepath,filename,mymailid)
{	//window.top.OpenWizard('misc/downloadfile.php?f='+escape(filepath),"no",0.2,0.2);
	parent.ShowWindow('misc/downloadfile.php?sessionId='+ssid+'&filename='+filename+'&f='+escape(filepath),"no",0.2,0.2);
}

function showmail(accountId,mailid, ssid,read, folderId,projectid,projectpath)
{
	parent.OpenWizard('viewmail&sid=' + ssid+ '&accountId=' +accountId+ '&mailId=' + mailid + '&read=' + read + '&folderId=' + folderId+ '&projectid=' + projectid+ '&projectpath=' + projectpath,"no");	   

	// mark as read in grid
	event.srcElement.parentElement.className = 'gridcolumnItem';	
}
// On Double click operations endss here


// Function to create Div which will hold content
function createDiv(id)
{
	var height;
	if (id=='projectMsgDivContent')
		height=84;
	else
		height=66;
	if(_browsername_!='Mozilla')
			doc = parent.document.getElementById('IFControl').contentWindow.document;
	else
			doc = parent.document.getElementById('IFControl').contentDocument;
									
	var h = parseInt(doc.body.clientHeight)-height;
	//divtag = '<div onSelectStart="return false;" class="DivColor" STYLE="overflow:auto; width: 100%; height:'+h+'px;padding:0px; margin: 0px;" id="'+id+'"></div>';
	//document.write(divtag);
	
	doc.write('<div onSelectStart="return false;" class="DivColor" STYLE="overflow:auto; width: 100%; height:'+h+'px;padding:0px; margin: 0px;" id="'+id+'">');
	//doc.write(divtag);
	doc.write('</div>');
	
}
	// testing 
function createDiv1(type,id)
{
	if(_browsername_!='Mozilla')
		browserDoc = parent.document.getElementById('IFControl').contentWindow.document;
	else
		browserDoc = parent.document.getElementById('IFControl').contentDocument;
	
	var height;
	if (id=='projectMsgDivContent')
		height=84;
	else
		height=66;
	var h = parseInt(browserDoc.body.clientHeight)-height;
	
	var contentDiv = document.createElement('div');
		contentDiv.id = type+id;
		contentDiv.onSelectStart = function(){ return false; };
		contentDiv.className = 'DivColor';
		contentDiv.style.overflowX = 'hidden';
		contentDiv.style.overflowY = 'scroll';
		contentDiv.style.width = '100%';
		contentDiv.style.height = ''+h+'px';
		contentDiv.style.padding = '0px';
		contentDiv.style.margin = '0px';
		
		var contentTab = document.createElement('table');
			contentTab.className = 'gridtable';
			contentTab.width = '100%';
			
		var contentTbody = document.createElement('tbody');
			var contentTr = document.createElement('tr');
			
				var contentTd1 = document.createElement('td');
					contentTd1.className = 'gridcolumnheader';
					contentTd1.width = '29%';
					var a1 = document.createElement('a');
						a1.href = '#';
						a1.className = 'sortBy';
						a1.id = 'contentCol1';
						a1.innerHTML = 'From';
					contentTd1.appendChild(a1);
						
				var contentTd2 = document.createElement('td');
					contentTd2.className = 'gridcolumnheader';
					contentTd2.width = '40%';
					var a2 = document.createElement('a');
						a2.href = '#';
						a2.className = 'sortBy';
						a2.id = 'contentCol2';
						a2.innerHTML = 'Subject';
					contentTd2.appendChild(a2);
					
				var contentTd3 = document.createElement('td');
					contentTd3.className = 'gridcolumnheader';
					contentTd3.width = '19%';
					var a3 = document.createElement('a');
						a3.href = '#';
						a3.className = 'sortBy';
						a3.id = 'contentCol3';
						a3.innerHTML = 'Date';
					contentTd3.appendChild(a3);

				var contentTd4 = document.createElement('td');
					contentTd4.className = 'gridcolumnheader';
					//contentTd4.width = '29%';
					var a4 = document.createElement('a');
						a4.href = '#';
						a4.className = 'sortBy';
						a4.id = 'contentCol4';
						a4.innerHTML = 'From';
					contentTd4.appendChild(a4);
			
			contentTr.appendChild(contentTd1);
			contentTr.appendChild(contentTd2);
			contentTr.appendChild(contentTd3);
			contentTr.appendChild(contentTd4);
			
		contentTbody.appendChild(contentTr);
		contentTab.appendChild(contentTbody);
	contentDiv.appendChild(contentTab);
	return contentDiv;
}	
function createHeaderDiv(type,id)
{
	var divObj = document.createElement('div');
		divObj.id = type+id;	
		divObj.style.display = 'none';

	var divTab = document.createElement('table');
		divTab.className = 'gridtable';
		divTab.width = '100%';
		
	var divTbody = document.createElement('tbody');
	var divTr = document.createElement('tr');
	var divTd = document.createElement('td');
	
		var headerTab = document.createElement('table');
			headerTab.id = type+'HeaderTable';	
			headerTab.width = '100%';
		var headerTbody = document.createElement('tbody');
			var headerTr = document.createElement('tr');
			var headerTd = document.createElement('td');
				headerTd.colspan = 4; headerTd.className = 'ContentHeader';
			
				var contentTab = document.createElement('table');
				var contentTbody = document.createElement('tbody');
					var imgTr = document.createElement('tr');
					var imgTd = document.createElement('td');
						imgTd.width = '5';
						var headerImg = document.createElement('img');
							headerImg.id = type+'HeaderImg';
							headerImg.src = '/images/headers/phonecall.gif';
							headerImg.height = '20px';
							headerImg.width = '20px';
						imgTd.appendChild(headerImg);
						imgTr.appendChild(imgTd);
	
					var titleTd = document.createElement('td');
						titleTd.width = '100%';
						titleTd.id = type+'HeaderTitle';
						titleTd.align = 'left';
						titleTd.valign = 'middle';
						titleTd.className = 'contentheadertext';
						var titleSpan = document.createElement('span');
							titleSpan.innerHTML = 'Task Summary: &nbsp;';
						titleTd.appendChild(titleSpan);
						imgTr.appendChild(titleTd);
						
				var searchBtnTd = document.createElement('td');
					searchBtnTd.align = 'right';
					var searchBtn = document.createElement('input');
						searchBtn.type = 'button';
						searchBtn.value = 'Search';
						searchBtn.onclick = function(){showPanel('searchVoice','','');};
					searchBtnTd.appendChild(searchBtn);
					imgTr.appendChild(searchBtnTd);
					
				contentTbody.appendChild(imgTr);
				contentTab.appendChild(contentTbody);
			headerTd.appendChild(contentTab);
			headerTr.appendChild(headerTd);
		headerTbody.appendChild(headerTr);
		headerTab.appendChild(headerTbody);
	divTd.appendChild(headerTab);
	
//		var footerTab = document.createElement('table');
//			footerTab.id = 'footer';	
//			footerTab.width = '100%';
//		var footerTbody = document.createElement('tbody');
//			var footerTr = document.createElement('tr');
//			var footerTd = document.createElement('td');
//				footerTd.id = type+'Footer';
//				footerTd.className = 'gridcolumnheader';
//				footerTd.align = 'right';
//				footerTd.width = '100%';
//				footerTd.innerHTML = '&nbsp;';
//			
//				footerTr.appendChild(footerTd);
//			footerTbody.appendChild(footerTr);
//			footerTab.appendChild(footerTbody);
	//divTd.appendChild(footerTab);	adding footer
	
	divTr.appendChild(divTd);
	divTbody.appendChild(divTr);
	divTab.appendChild(divTbody);
	
	divObj.appendChild(divTab);
	document.getElementById('divsContainer').appendChild(divObj);
	return divObj;
}

function createFooterDiv(type,id)
{
	var footerDiv = document.createElement('div');
		footerDiv.id = type+id;	
	var footerTab = document.createElement('table');
		footerTab.id = type+'FooterTable';	
		footerTab.width = '100%';
	var footerTbody = document.createElement('tbody');
		var footerTr = document.createElement('tr');
		var footerTd = document.createElement('td');
			footerTd.id = type+'FooterTd';
			footerTd.className = 'gridcolumnheader';
			footerTd.align = 'right';
			footerTd.width = '100%';
			footerTd.innerHTML = '&nbsp;';
		
			footerTr.appendChild(footerTd);
		footerTbody.appendChild(footerTr);
		footerTab.appendChild(footerTbody);

	footerDiv.appendChild(footerTab);	
	return footerDiv;
}

// Runtime Download Status related functions starts here
function UpdateDownloadStatus(current,total,subject,size)
{

	if(current)	
		document.getElementById('mailcount').innerHTML="Downloading Mails: <b>"+current+"</b> of <b>"+total+"</b>";

	if(subject)	
		document.getElementById('maildetails').innerHTML="Mail Details: "+subject+" ( "+size+" ) ";

	var progress = (current/total)*100;
	document.getElementById('progressimage').style.width=progress+'%';
}

function ShowDownloadDiv(username,display)
{
	if(username)	
	{
		document.getElementById('mailcount').innerHTML="";
		document.getElementById('maildetails').innerHTML="";
		document.getElementById('progressimage').style.width='0%';		
		document.getElementById('mailaccount').innerHTML="Checking Mails for '<b>"+username+"</b>'";
	}
	
	if(display)
		document.getElementById('downloadstatus').style.display='block';
	else
		document.getElementById('downloadstatus').style.display='none';	
}
// Runtime Download Status related functions ends here


// Tree Scrolling code
var treeX;
var treeDown = 0;
var treeWidth;
var oldOnMouseMove;
var oldOnMouseUp;

function ScrollTreeDown(td)
{
	var buttonid = window.event.button;
	if (buttonid!=2)
	{
		td.style.backgroundColor = '#F9F9F9';
		td.style.cursor="w-resize";
		treeDown = 1;
		treeX = event.clientX;		
		treeWidth = parseInt(document.getElementById('divtree').style.width);	
		
		// saving old events
		oldOnMouseMove = document.body.onmousemove;
		oldOnMouseUp = document.body.onmouseup;
		//alert(oldOnMouseMove);
		//alert(oldOnMouseUp);
		
		document.body.onmousemove = ScrollTreeMove;
		document.body.onmouseup = function() {
									treeDown=0;
									document.getElementById('treeSeperator').className = 'sidebar';
									document.getElementById('treeSeperator').style.backgroundColor = '';
									// restoring old events
									document.body.onmouseup=oldOnMouseUp;
									document.body.onmousemove=oldOnMouseMove;
									//alert(document.body.onmouseup);
									//alert(document.body.onmousemove);
									};
	}
}

function ScrollTreeMove()
{
	var buttonid = window.event.button;
	//	left button,	  threshold x,				   only check once on drag start
	if (buttonid!=2 && Math.abs(treeX-event.clientX)>1 && treeDown==1)
	{	
		var offset = treeX-event.clientX;
		
		// limit constraints
		if (treeWidth - offset > 150 && treeWidth - offset < 750 )
		{
			treeX = event.clientX;
			treeWidth = treeWidth - offset;
			document.getElementById('divtree').style.width = treeWidth+'px';
		}
	}
}

// Tree Scrolling code ends here

function ShowStep(id,count)
{
	var x;
	var id;
	for(x=0;x<count;x++)
	{
		if(x!=id)
			document.getElementById('step'+x).style.display="none";
	
	}
	if(document.getElementById('step'+id).style.display== "block")
		document.getElementById('step'+id).style.display ="none";
	else
		document.getElementById('step'+id).style.display="block";
	
	var frame = document.getElementById('iframe_step'+id);
	var src = frame.src;
	frame.src="";
	frame.src=src;
}var x=0;
var timer;
var touser;
var type;
var path;
//var lasturl;
var gcon=false;

	function onLinkClick(sid,orderId,path)
	{
		
		showDiv("crmStatusDiv");
		var url='http://crm.infinioffice.com?SCREEN=navigate&sid='+sid+'&order='+orderId+'&srorder='+orderId+'&projectpath='+path+'&projectname='+orderId+'&page=1&act=16';
		parent.parent.frames['IFControl'].location.href=url;
	}	
		

	// Required for uploading purpose (14/01/05)
	function changeUploadFile(file)
	{
		parent.filetoupload.value = file;
	}
	
	function SyncProductTree(parentNodeId,projectid,path,productcode,productname,sid)
	{
		var nodeId = parentNodeId;
		//alert(nodeId);
		if(!parent.parent.document.getElementById('IFControl').contentWindow.crmTree.searchByNodeId(nodeId))
		{	
			alert('Error');
			return;
		}

		var o = new Array(parentNodeId,projectid,path,productcode,productname,parent.parent._sessionid_);
		o = JSON.encode(o);
		//alert(o);
 		var url = "index.php?object=ibz.tree&function=SearchProduct&isajaxcall=1";
		var pars = 'param='+o  
		//alert(pars);
		srcW.ShowWaitDialog();
		//alert('calling Ajax');
		var myAjax = new Ajax.Request( url,
			{ method: 'post', parameters: pars, onFailure: reportError , onSuccess: SyncProductTreeCallback});		


	}
	function SyncProductTreeCallback(response)
	{
	
		//debugger;
		parent.srcW.HideWaitDialog();	
		response = eval(response.responseText);
		var custcount = response[0]['totalCount'];
		var custnodes = response[0]['nodes'];
		
		var w;
		if(parent.parent.document.getElementById('IFControl'))
			w = parent.parent.document.getElementById('IFControl').contentWindow;
		else
			w = parent.document.getElementById('IFControl').contentWindow;
				
		obj="project";
	 	mainparentnode = custnodes[obj].nodes[0]['parentnode'];
	 	var mainchildparentNode = w.crmTree.searchByNodeId(mainparentnode)	
	 	mainchildparentNode._collapsechild();
	 	mainchildparentNode.collapse();
	 	mainchildparentNode._removeallchild();
	 			 		
	 	for(x=0;x<=custnodes[obj].totalCount;x++)
	 	//for(x=0;x<=26;x++)
		{	
				
	 		childnode = unescape(custnodes[obj].nodes[x]['title']);
	 		 var intIndexOfMatch = childnode.indexOf( "+" );
  
		     // Loop over the string value replacing out each matching substring.
		     while (intIndexOfMatch != -1){
		    	 // Relace out the current instance.
			     childnode = childnode.replace( "+", " " )
		      
			     // Get the index of any next matching substring.
		     	intIndexOfMatch = childnode.indexOf( "+" );
		     }

			projectid1 = custnodes[obj].nodes[x]['projectid'];
			path = custnodes[obj].nodes[x]['path'];
			projectname = custnodes[obj].nodes[x]['projectname'];
			childparentnode = custnodes[obj].nodes[x]['parentnode'];
			childnodeid = custnodes[obj].nodes[x]['nodeid'];
			childimgpath = custnodes[obj].nodes[x]['imgpath'];
			firstname = custnodes[obj].nodes[x]['firstname'];			
			nodename = custnodes[obj].nodes[x]['nodename'];
			ppath='|'+projectid1+'/'+path;
		
			var childparentNode = w.crmTree.searchByNodeId(childparentnode)	
			
			//childNodeObj = new w.WebFXTreeItem(childnode, onclick,onmouseup, '', childimgpath, childimgpath,childnodeid,'-1','','','',true);			
					 	
			if(w.crmTree.searchByNodeId(childnodeid))
				continue;
			onclick = "";
			onmouseup = ""; 

			custtitle=childnode;
			//onclick = "LoadAjaxScreen('showprojects&projectid="+projectid1+"&projectpath="+path+"&projectTitle="+childnode+"&page=0');";
			//for seo demo
			if(path.substring(0, 7)== '9416/9/')
				onclick ="LoadAjaxScreen('showdocuments&tab=no&projectid="+projectid1+"&projectpath="+path+"&product=yes')";
			else if(path.indexOf('/6/')!=-1)
				onclick ="LoadAjaxScreen('updateconference&type=broadcast&readonly=true&tab=no&projectid="+projectid1+"&projectpath="+path+"&product=yes')";	
			else if(path.substring(0, 7)== '9416/2/')
				onclick ="LoadAjaxScreen('showdocuments&tab=no&projectid="+projectid1+"&projectpath="+path+"&product=yes')";
			else
				onclick ="LoadAjaxScreen('showdocuments&tab=no&projectid="+projectid1+"&projectpath="+path+"&product=yes')";				


			childNodeObj = new w.WebFXTreeItem(custtitle, onclick,onmouseup, '', childimgpath, childimgpath,childnodeid,ppath,nodename,'',nodename,true);	
		
			
			childparentNode.add(childNodeObj);
			var a='';
	 	}
	 	/*Ambigious::: it is done bc cookie get deleted when treecontrolfx creates multiple nodes. Tariq8Sep08*/
	 	var op = {"val":_sessionid_};
    	op = JSON.encode(op);
    	setCookie(_sessionid_, op); 
	 	
	 	mainchildparentNode.expand();
	}
	
	function SyncStudioTree(projectid,parentNodeId,orderId,nodeConstant,sid)
	{
	
		var nodeId = parentNodeId;
		if(!parent.parent.document.getElementById('IFControl').contentWindow.crmTree.searchByNodeId(nodeId))
		{	
			alert('Error');
			return;
		}

		var o = new Array(parentNodeId,orderId,projectid,nodeConstant,parent.parent._sessionid_);
		o = JSON.encode(o);
		var url = "index.php?object=ibz.tree&function=SearchInfiniStudio&isajaxcall=1";
		var pars = 'param='+o  
		srcW.ShowWaitDialog();
		var myAjax = new Ajax.Request( url,
			{ method: 'post', parameters: pars, onFailure: reportError , onSuccess: SyncStudioTreeCallback});		


	}
	function SyncStudioTreeCallback(response)
	{
		var invCons = 1<<6;
		var ordCons = 1<<1;
		var customer_user_type = 64;
		
		parent.srcW.HideWaitDialog();
		var resObj = eval(response.responseText);
		
		projectid = resObj[0]["projectid"];
		parentNodeId= resObj[0]["parentnode"];
		orderid= resObj[0]["orderid"];
		
		var w;
		if(parent.parent.document.getElementById('IFControl'))
			w = parent.parent.document.getElementById('IFControl').contentWindow;
		else
			w = parent.document.getElementById('IFControl').contentWindow;

		var parentNode = w.crmTree.searchByNodeId(parentNodeId)	
		
		var ordNodeId = parentNodeId+orderid;
		var projectid = resObj[0]["projectid"];
		var orderPath = resObj[0]["filepath"];
		var path;
		
		onclick = "";
			
		if(!w.crmTree.searchByNodeId(ordNodeId))
		{
			ordNodeObj = new w.WebFXTreeItem(orderid, onclick, '', '', 'images/treeimg/order.jpg', 'images/treeimg/order.jpg',ordNodeId);	
			parentNode.addTop(ordNodeObj);
		}	
		var name;
		var path;
		var displayname;
		var onclick;
			
		for(var x=1; x<resObj.length;x++)
		{
			onclick = "";
			name = resObj[x]["name"];
			path= resObj[x]["filepath"]+name;
			displayname= resObj[x]["displayname"];
			docNodeId  = ordNodeId+name;
			taskId = resObj[x]["taskid"];
			taskType = resObj[x]["tasktype"];
			
			var img;
			
			onclick = "parent.LoadAjaxScreen('showtaskdetails&taskType="+taskType+"&taskId="+taskId+"');"
			img = "images/treeimg/invoice.gif";
				
			
			if(!w.crmTree.searchByNodeId(docNodeId))
			{
				nodeId  = new w.WebFXTreeItem(resObj[x]['displayname'], onclick, '', '', img, img,docNodeId);	
				ordNodeObj.addTop(nodeId);
			}
		}
		
		return;
	}
	
	function SyncOrderTree(projectid,parentNodeId,orderId,sid)
	{
		//alert("parent:"+parentNodeId+" ord:"+orderId+" projectid:"+projectid);
		//alert(parent.parent.frames['IFControl'].crmTree);
		var nodeId = parentNodeId;
		//alert(nodeId);
		if(parent.parent.document.getElementById('IFControl').contentWindow.crmTree)
		if(!parent.parent.document.getElementById('IFControl').contentWindow.crmTree.searchByNodeId(nodeId))
		{	
			alert('Error');
			return;
		}

		var o = new Array(parentNodeId,orderId,projectid,parent.parent._sessionid_);
		o = JSON.encode(o);
		//alert(o);
 		var url = "index.php?object=ibz.tree&function=SearchOrder&isajaxcall=1";
		var pars = 'param='+o  
		//alert(pars);
		srcW.ShowWaitDialog();
		//alert('calling Ajax');
		var myAjax = new Ajax.Request( url,
			{ method: 'post', parameters: pars, onFailure: reportError , onSuccess: SyncOrderTreeCallback});		


	}
	function SyncOrderTreeCallback(response)
	{
		//debugger;
		var invCons = 1<<6;
		var ordCons = 1<<1;
		var customer_user_type = 64;
		
		parent.srcW.HideWaitDialog();
		//alert('Res:'+response.responseText);
		var resObj = eval(response.responseText);
		
		projectid = resObj[0]["projectid"];
		siteprefix = resObj[0]["site_prefix"];
		//alert(siteprefix);
		parentNodeId= resObj[0]["parentnode"];
		orderid= resObj[0]["orderid"];
		var w;
		if(parent.parent.document.getElementById('IFControl'))
			w = parent.parent.document.getElementById('IFControl').contentWindow;
		else
			w = parent.document.getElementById('IFControl').contentWindow;

		if(w.crmTree)
		{
			var parentNode = w.crmTree.searchByNodeId(parentNodeId)	
			
			var ordNodeId = parentNodeId+orderid;
			var projectid = resObj[0]["projectid"];
			if(w.crmTree.searchByNodeId(ordNodeId))
				return;
	
			var orderPath = resObj[0]["filepath"];
			var path;
			//onclick = "parent.frames['IFControl'].frames['operationsarea'].ShowOrders('"+orderid+"','','0','','"+projectid+"','"+path+"','1','"+ordCons+"');";
			onclick = "LoadAjaxScreen('showorder&name="+orderid+"&projectid="+projectid+"&path="+orderPath+"&display=order&crmtype="+ordCons+"');";
			//alert(onclick);
			ordNodeObj = new w.WebFXTreeItem(orderid, onclick, '', '', 'images/treeimg/order.jpg', 'images/treeimg/order.jpg',ordNodeId);	
			parentNode.addTop(ordNodeObj);
			
			var name;
			var path;
			var displayname;
			var onclick;
			//alert(resObj.length);
			
			for(var x=1; x<resObj.length;x++)
			{
				onclick = "";
				name = resObj[x]["name"];
				path= resObj[x]["filepath"]+name;
				displayname= resObj[x]["displayname"];
				docNodeId  = ordNodeId+name;
				var img;
				if(displayname== "Invoice")
				{
					//onclick = "parent.frames['IFControl'].frames['operationsarea'].ShowOrders('"+orderid+"','','0','','"+projectid+"','"+path+"','1','"+invCons+"');";
	 				  onclick = "LoadAjaxScreen('showorder&name="+orderid+"&projectid="+projectid+"&path="+path+"&display=order&crmtype="+invCons+"');";
					img = "images/treeimg/invoice.gif";
				}
				else if(displayname== "Tickets")
				{
					//alert('task:'+path);
					//onclick = "parent.frames['IFControl'].frames['operationsarea'].ShowTasksByPath('"+path+"','"+projectid+"','"+name+"');";
					onclick = "parent.LoadAjaxScreen('dashboard&parentpath="+path+"');";
					
					img = "images/treeimg/invoice.gif";
				}
				else
				{
					//onclick = "parent.frames['IFControl'].frames['operationsarea'].ShowProjectStatus('"+displayname+"','"+customer_user_type+"','','0','','"+projectid+"','"+path+"','-1','1');";
					ordPath = path.split("|"+projectid+"/");
					onclick ="LoadAjaxScreen('showdocuments&tab=no&projectid="+projectid+"&projectpath="+ordPath[1]+"/')";
					img = "images/treeimg/shareddoc.gif";
				}
	//			alert(onclick);	
				nodeId  = new w.WebFXTreeItem(resObj[x]['displayname'], onclick, '', '', img, img,docNodeId);	
				ordNodeObj.addTop(nodeId);
		}
		}
		//parent.parent.frames["IFControl"].frames["operationsarea"].ShowOrders(orderid,"",0,"",projectid,path,"1",ordCons);
		if(siteprefix!="studio.")
			parent.LoadAjaxScreen("showorder&name="+orderid+"&projectid="+projectid+"&path="+orderPath+"&display=order&crmtype="+ordCons);
		parentNode.expand();
		ordNodeObj.expand();
		return;
	}
	
	//SYNC PURCHASE ORDER TREE & ITS CALL BACK
	function SyncPurchaseOrderTree(projectid,parentNodeId,orderId,sid)
	{
		//alert("IN SyncPurchaseOrderTree");
		//alert("projectid"+projectid+"parentNodeId"+parentNodeId+"orderId"+orderId+"sid"+sid);
		var nodeId = parentNodeId;
		if(!parent.parent.document.getElementById('IFControl').contentWindow.crmTree.searchByNodeId(nodeId))
		{	
			alert('Error');
			return;
		}
		var o = new Array(parentNodeId,orderId,projectid,parent.parent._sessionid_);
		o = JSON.encode(o);
		//alert(o);
 		var url = "index.php?object=ibz.tree&function=SearchPurchaseOrder&isajaxcall=1";
		var pars = 'param='+o  
		var myAjax = new Ajax.Request( url,
			{ method: 'post', parameters: pars, onFailure: reportError , onSuccess: SyncPurchaseOrderTreeCallback});		
	}
	function SyncPurchaseOrderTreeCallback(response)
	{
		//alert("IN SyncPurchaseOrderTreeCallback");
		//debugger;
		var invCons = 1<<6;
		var ordCons = 1<<1;
		var customer_user_type = 64;
		
		//parent.srcW.HideWaitDialog();
	  	var resObj = eval(response.responseText);
		
		projectid = resObj[0]["projectid"];
		parentNodeId= resObj[0]["parentnode"];
		orderid= resObj[0]["orderid"];
		var w;
		if(parent.parent.document.getElementById('IFControl'))
			w = parent.parent.document.getElementById('IFControl').contentWindow;
		else
			w = parent.document.getElementById('IFControl').contentWindow;

		var parentNode = w.crmTree.searchByNodeId(parentNodeId)	
		
		var ordNodeId = parentNodeId+orderid;
		var projectid = resObj[0]["projectid"];
		if(w.crmTree.searchByNodeId(ordNodeId))
			return;

		var orderPath = resObj[0]["filepath"];
		var path;
		
		onclick = "LoadAjaxScreen('showporder&name="+orderid+"&projectid="+projectid+"&path="+orderPath+"&display=order&crmtype="+ordCons+"');";
		ordNodeObj = new w.WebFXTreeItem(orderid, onclick, '', '', 'images/treeimg/orderids.gif', 'images/treeimg/orderids.gif',ordNodeId);	
		parentNode.addTop(ordNodeObj);
		var name;
		var path;
		var displayname;
		var onclick;
				
		for(var x=1; x<resObj.length;x++)
		{
			onclick = "";
			name = resObj[x]["name"];
			path= resObj[x]["filepath"]+name;
			displayname= resObj[x]["displayname"];
			docNodeId  = ordNodeId+name;
			var img;
			
			if(displayname == "Products")
			{
 				var Name;
				var Path;
				var Displayname;
				var onClick;
				productNodeId = resObj[x]["nodeid"];
				
 				onclick = "parent.LoadAjaxScreen('showstatuspage&parentpath="+path+"');";
				img = "images/treeimg/products.jpg";
 				nodeObj = new w.WebFXTreeItem(displayname, onclick, '', '', img, img,productNodeId);
				ordNodeObj.addTop(nodeObj);
				//debugger;
 				for(var y=0; y<resObj[x]["producthirarchy"].length;y++)
				{
					onClick = "";
					Name = resObj[x]["producthirarchy"][y]["displayname"];
					Path= resObj[x]["producthirarchy"][y]["path"]+Name;
					Displayname= resObj[x]["producthirarchy"][y]["displayname"];
					NodeId= resObj[x]["producthirarchy"][y]["nodeid"];
					ParentNode= resObj[x]["producthirarchy"][y]["parentnode"];
					//NodeId = docNodeId + Name;
					SubNode  = new w.WebFXTreeItem(Displayname, onClick, '', '', img, img,NodeId);
					
					var parentNode1 = w.crmTree.searchByNodeId(ParentNode)	
					parentNode1.addTop(SubNode);
				}
 			}
			else if(displayname== "Tickets")
			{
				
				onclick = "parent.LoadAjaxScreen('showstatuspage&parentpath="+path+"');";
				img = "images/treeimg/invoice.gif";
				nodeObj  = new w.WebFXTreeItem(resObj[x]['displayname'], onclick, '', '', img, img,docNodeId);	
				ordNodeObj.addTop(nodeObj);
			}
			else
			{
				ordPath = path.split("|"+projectid+"/");
				onclick ="LoadAjaxScreen('showdocuments&tab=no&projectid="+projectid+"&projectpath="+ordPath[1]+"/')";
				img = "images/treeimg/shareddoc.gif";
				nodeObj  = new w.WebFXTreeItem(resObj[x]['displayname'], onclick, '', '', img, img,docNodeId);	
				ordNodeObj.addTop(nodeObj);
			}
		}
		parent.LoadAjaxScreen("showporder&name="+orderid+"&projectid="+projectid+"&path="+orderPath+"&display=order&crmtype="+ordCons);
		return;
	}
	
	
	
	// FUNCTION 4 SECURE FILE & ITS CALLBACK 
	
	function SyncSecureTree(projectid,parentNodeId,orderId,nodeConstant,sid)
	{
		var nodeId = parentNodeId;
		if(!parent.parent.document.getElementById('IFControl').contentWindow.crmTree.searchByNodeId(nodeId))
		{	
			alert('Error');
			return;
		}

		var o = new Array(parentNodeId,orderId,projectid,nodeConstant,parent.parent._sessionid_);
		o = JSON.encode(o);
		var url = "index.php?object=ibz.tree&function=SearchSecureFiles&isajaxcall=1";
		var pars = 'param='+o  
		srcW.ShowWaitDialog();
		var myAjax = new Ajax.Request( url,
			{ method: 'post', parameters: pars, onFailure: reportError , onSuccess: SyncSecureTreeCallback});		


	}
	function SyncSecureTreeCallback(response)
	{
		
		var invCons = 1<<6;
		var ordCons = 1<<1;
		var customer_user_type = 64;
		
		parent.srcW.HideWaitDialog();
		var resObj = eval(response.responseText);
		
		projectid = resObj[0]["projectid"];
		parentNodeId= resObj[0]["parentnode"];
		orderid= resObj[0]["orderid"];
		var w;
		if(parent.parent.document.getElementById('IFControl'))
			w = parent.parent.document.getElementById('IFControl').contentWindow;
		else
			w = parent.document.getElementById('IFControl').contentWindow;

		var parentNode = w.crmTree.searchByNodeId(parentNodeId)	
		
		var ordNodeId = parentNodeId+orderid;
		var projectid = resObj[0]["projectid"];
		if(w.crmTree.searchByNodeId(ordNodeId))
			return;

		var orderPath = resObj[0]["filepath"];
		var path;
		
		//onclick = "LoadAjaxScreen('showorder&name="+orderid+"&projectid="+projectid+"&path="+orderPath+"&display=order&crmtype="+ordCons+"');";
		onclick = "";
		ordNodeObj = new w.WebFXTreeItem(orderid, onclick, '', '', 'images/treeimg/order.jpg', 'images/treeimg/order.jpg',ordNodeId);	
		parentNode.addTop(ordNodeObj);
		
		var name;
		var path;
		var displayname;
		var onclick;
		for(var x=1; x<resObj.length;x++)
		{
			onclick = "";
			name = resObj[x]["name"];
			path= resObj[x]["filepath"]+name;
			displayname= resObj[x]["displayname"];
			docNodeId  = ordNodeId+name;
			var img;
			ordPath = path.split("|"+projectid+"/");
			onclick ="LoadAjaxScreen('showdocuments&allowUpload=false&projectTitle=SecureFiles&tab=no&projectid="+projectid+"&projectpath="+ordPath[1]+"/')";
			img = "images/treeimg/shareddoc.gif";
			nodeId  = new w.WebFXTreeItem(resObj[x]['displayname'], onclick, '', '', img, img,docNodeId);	
			ordNodeObj.addTop(nodeId);
		}		
		parent.LoadAjaxScreen('showdocuments&allowUpload=false&projectTitle=SecureFiles&tab=no&projectid='+projectid+'&projectpath='+ordPath[1]+'/');
		return;
	}
	// END
	
	// SYNC TREE 4 SUPPLIER
	function SyncSupplierTree(parentNodeId,title,sid,usertype,firstname)
	{
    	//debugger;
    	var nodeId = parentNodeId+title;
    	//alert("parentNodeId: "+ parentNodeId+" title: "+ title+" sid: "+ sid+" usertype: "+ usertype+" firstname: "+ firstname);
    	if(parent.parent.document.getElementById('IFControl').contentWindow.crmTree.searchByNodeId(nodeId))	
    		return;
    	var o = new Array(parentNodeId,title,usertype,firstname,parent.parent._sessionid_);
    	o = JSON.encode(o);
    	var url = "index.php?object=ibz.tree&function=SearchSupplier&isajaxcall=1";
    	var pars = 'param='+o;
    	var myAjax = new Ajax.Request( url,
    		{ method: 'post', parameters: pars, onFailure: reportError , onSuccess: SyncSupplierTreeCallback});		
    }
    function SyncSupplierTreeCallback(response)
    {
 		//debugger;
    	//alert("In SyncSupplierTreeCallback");
    	//alert(response.responseText);
    	var resObj = eval(response.responseText);
    	var parentNodeId = resObj[0]["parentnode"];
    	var title = unescape(resObj[0]["title"]);
    	var usertype = resObj[0]["usertype"];
    	//alert("usertype"+usertype);
    	
    	var w;
    	if(parent.parent.document.getElementById('IFControl'))
			w = parent.parent.document.getElementById('IFControl').contentWindow;
		else
			w = parent.document.getElementById('IFControl').contentWindow;
		    	
    	var firstname = unescape(resObj[0]["firstname"]);
    	var parentNode = w.crmTree.searchByNodeId(parentNodeId)	
        var nodeId = parentNodeId+title;
    	var ordNodeId = "Orders--"+title;
		    		   		
    	var projectid = resObj[0]["projectid"];
    	    	
    	if(usertype == 128)
    	{
    		var node = new w.WebFXTreeItem(firstname+' ('+title+')', 'parent.LoadAjaxScreen(\'showcustomertask&projectId='+projectid+'&custname='+title+'\');', '', '', 'images/treeimg/customer.gif', 'images/treeimg/customer.gif',nodeId);	
    		parentNode.addTop(node);
    
    		for(i=0;i<resObj[0]["contants"].length;i++)
    		{
    			nname = resObj[0]["contants"][i]["name"];
    			ntitle = resObj[0]["contants"][i]["comments"];
    			nscreen=resObj[0]["contants"][i]["screen"];
    			node2 = new w.WebFXTreeItem(ntitle, "parent.LoadAjaxScreen('"+nscreen+"&pname=&custname="+title+"&pid="+projectid+"');", '', '', 'images/treeimg/order.gif', 'images/treeimg/order.gif',nname);	
    			node.addTop(node2);
    			parent.LoadAjaxScreen('showcustomertask&projectId='+projectid+'&custname='+title);
    		}
    	}
    	else
    	{
    		var node = new w.WebFXTreeItem(firstname+' ('+resObj[0]['displayname']+')', "javascript:LoadAjaxScreen('showemployee&empname="+title+"&type=256');\"", '', '', 'images/treeimg/projects_list.png', 'images/treeimg/projects_list.png',nodeId);	
    		parentNode.addTop(node);
    		parent.LoadAjaxScreen('showemployee&empname='+title+'&type=256');
    	}
    }
    		
	
	function SyncTree(parentNodeId,title,sid,usertype,firstname)
    	{
    
    		var nodeId = parentNodeId+title;
    
    		if(parent.parent.document.getElementById('IFControl').contentWindow.crmTree.searchByNodeId(nodeId))	
    			return;
    
    		var o = new Array(parentNodeId,title,usertype,firstname,parent.parent._sessionid_);
    		o = JSON.encode(o);
    		//alert(o);
    		
     		var url = "index.php?object=ibz.tree&function=SearchCustomer&isajaxcall=1";
    		var pars = 'param='+o  
    		//alert(pars);
    		srcW.ShowWaitDialog();
    		//alert('calling Ajax');
    		var myAjax = new Ajax.Request( url,
    			{ method: 'post', parameters: pars, onFailure: reportError , onSuccess: SearchUserCallback});		
    
    	}
    	function SearchUserCallback(response)
    	{
    
   			//debugger;
    		if(parent.parent.document.getElementById('IFControl'))
				w = parent.parent.document.getElementById('IFControl').contentWindow;
			else
				w = parent.document.getElementById('IFControl').contentWindow;
			    		
    		parent.srcW.HideWaitDialog();
    		var resObj = eval(response.responseText);
    		
    		//alert(resObj[0]["istudio"]);
    		//alert(response.responseText);
    		var parentNodeId = resObj[0]["parentnode"];
    		var title = unescape(resObj[0]["title"]);
    		var usertype = resObj[0]["usertype"];
    		var firstname = unescape(resObj[0]["firstname"]);
    		var parentNode = w.crmTree.searchByNodeId(parentNodeId)	
        	var nodeId = parentNodeId+title;
    		var ordNodeId = "Orders--"+title;
    		//alert(ordNodeId);
    		
    		var projectid = resObj[0]["projectid"];
    		//debugger;
    		if(usertype == 64)
    		{
    			var node = new w.WebFXTreeItem(firstname+' ('+title+')', 'parent.LoadAjaxScreen(\'showcustomertask&projectId='+projectid+'&custname='+title+'\');', '', '', 'images/treeimg/customer.gif', 'images/treeimg/customer.gif',nodeId);	
    			parentNode.addTop(node);
    
    			//node1 = new parent.parent.frames['IFControl'].WebFXTreeItem('Orders', "parent.LoadAjaxScreen('showorderlist&pname="+title+"&pid="+projectid+"');", '', '', 'images/treeimg/order.gif', 'images/treeimg/order.gif',ordNodeId);	
    			//node.addTop(node1);
    			//parent.LoadAjaxScreen('showcustomertask&projectId='+projectid+'&custname='+title);
    			//alert(resObj[0]["contants"].length);
    			contantslength = resObj[0]["contantslength"];
    			for(i=0;i<contantslength;i++)
    			{
    				nname = resObj[0]["contants"][i]["name"];
    				ntitle = resObj[0]["contants"][i]["comments"];
    				nscreen=resObj[0]["contants"][i]["screen"];
    				node2 = new w.WebFXTreeItem(ntitle, "parent.LoadAjaxScreen('"+nscreen+"&pname=&custname="+title+"&pid="+projectid+"');", '', '', 'images/treeimg/order.jpg', 'images/treeimg/order.jpg',nname);	
    				node.addTop(node2);
    				parent.LoadAjaxScreen('showcustomertask&projectId='+projectid+'&custname='+title);
    					
    			}
    			//if (ischeck)
    			{
    				//node2 = new parent.parent.frames['IFControl'].WebFXTreeItem('InfiniStudio', "parent.LoadAjaxScreen('showinfinistudio&pname=&custname="+title+"&pid="+projectid+"');", '', '', 'images/treeimg/order.gif', 'images/treeimg/order.gif','6493');	
    				//node.addTop(node2);
    				//parent.LoadAjaxScreen('showcustomertask&projectId='+projectid+'&custname='+title);
    			}
    			//node2 = new parent.parent.frames['IFControl'].WebFXTreeItem('InfiniStudio', "parent.LoadAjaxScreen('showorderlist&pname="+title+"&pid="+projectid+"');", '', '', 'images/treeimg/order.gif', 'images/treeimg/order.gif',ordNodeId);	
    			//node.addTop(node1);
    			//parent.LoadAjaxScreen('showcustomertask&projectId='+projectid+'&custname='+title);
    		}
    		else
    		{
    			//var node = new parent.parent.frames['IFControl'].WebFXTreeItem(firstname+' ('+resObj[0]['displayname']+')', "javascript:parent.frames['IFControl'].frames['operationsarea'].ShowHRStatus("+title+",256);\"", '', '', 'images/treeimg/projects_list.png', 'images/treeimg/projects_list.png',nodeId);	
    			var node = new w.WebFXTreeItem(firstname+' ('+resObj[0]['displayname']+')', "javascript:LoadAjaxScreen('showemployee&empname="+title+"&type=256');\"", '', '', 'images/treeimg/projects_list.png', 'images/treeimg/projects_list.png',nodeId);	
    			parentNode.addTop(node);
    			parent.LoadAjaxScreen('showemployee&empname='+title+'&type=256');
    		}
    		
    		//debugger;
    		//parent.document.getElementById(nodeId).className="gridseleced"	;
    		//alert(projectid+'|'+resObj[0]['displayname']);
    		
    	}

	function reportError(response)
	{
		alert("error:"+response.responseText);
	}		/* Browser Detection Script */
browserVars = new browserVarsObj();
if(!browserVars.type.getById) document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = new Function('e', 'browserVars.updateMouse(e)');
//document.onmousemove = function(){browserVars.updateMouse();};

function browserDetect()
{
this.getById = document.getElementById?true:false;
this.layers = document.layers?true:false;
this.ns4 = ((this.layers) && (!this.getById));
this.ns6 = ((navigator.userAgent.indexOf('Netscape6') != -1) && (this.getById));
this.moz = ((navigator.appName.indexOf('Netscape') != -1) && (this.getById) && (!this.ns6));
this.ie  = ((!this.layers) && (this.getById) && (!(this.ns6 || this.moz)));
this.opera = window.opera?true:false;
}


function browserVarsObj()
{
this.updateMouse = browserVarsObjUpdateMouse;
this.updateVars = browserVarsObjUpdateVars;

this.mouseX = 0;
this.mouseY = 0;

this.type = new browserDetect();
this.width = 0;
this.height = 0
this.screenWidth = screen.width;
this.screenHeight = screen.height;
this.scrollWidth = 0;
this.scrollHeight = 0;
this.scrollLeft = 0;
this.scrollTop = 0;
this.updateVars();
}

function browserVarsObjUpdateMouse(e)
{
if(!this.type.ie)
{
this.mouseX = e.pageX;
this.mouseY = e.pageY;
}
else
{
this.mouseX = window.event.clientX + this.scrollLeft;
this.mouseY = window.event.clientY + this.scrollTop;
}
}

function browserVarsObjUpdateVars()
{
if(!this.type.getById)
{
this.width = window.innerWidth;
this.height = window.innerHeight;
this.scrollWidth = document.width;
this.scrollHeight = document.height;
this.scrollLeft = window.pageXOffset;
this.scrollTop = window.pageYOffset;
if(this.width < this.scrollWidth) this.width -= 16
if(this.height < this.scrollHeight) this.height -= 16
}
else
{
if((!(this.type.ns6 || this.type.moz)) && (document.body))
{
this.width = document.body.offsetWidth;
this.height = document.body.offsetHeight;
this.scrollWidth = document.body.scrollWidth;
this.scrollHeight = document.body.scrollHeight;
this.scrollLeft = document.body.scrollLeft;
this.scrollTop = document.body.scrollTop;
}
if((this.type.ns6 || this.type.moz) && (document.body))
{
this.width = window.innerWidth;
this.height = window.innerHeight;
this.scrollWidth = document.body.scrollWidth;
this.scrollHeight = document.body.scrollHeight;
this.scrollLeft = window.pageXOffset;
this.scrollTop = window.pageYOffset;
}
}
}
/*
Script by RoBorg
RoBorg@RoBorg.co.uk
http://www.roborg.co.uk
Do NOT remove this message!
*/

/*
Usage:
myDivObj = new divObject('myDivId', 'document.');
onload="activateDivs()"
myDiv.write('text')
myDiv.setBgColour('#xxxxxx')
myDiv.hide()
myDiv.show()
myDiv.swapImage('imgName', 'src')
myDiv.captureEvents('event', 'action')
myDiv.moveTo(x, y)
myDiv.moveby(x, y)
myDiv.resizeTo(x, y)
myDiv.resizeBy(x, y)
myDiv.clip(top, left, width, height)
*/

divObjectArray = new Array();

function activateDivs()
{
for(var x=0; x<divObjectArray.length; x++)
divObjectArray[x].activate();
}

function divObject(divName, parent)
{
	if(!browserVars.type.getById)
	{
		this.div = parent + divName;
		this.baseDiv = parent + divName;
		this.divName = parent + divName;
		this.write = new Function("text", "this.div.document.open(); this.div.document.write(text); this.div.document.close(); this.width = this.div.clip.width; this.height = this.div.clip.height;");
		this.setBgColour = new Function("colour", "this.div.bgColor = colour;");
		this.setBgImage = new Function("src", "this.div.bgImage = 'url(' + src + ')';");
		this.hide = new Function("this.div.visibility = 'hide';");
		this.show = new Function("this.div.visibility = 'inherit';");
		this.setSize = new Function("left", "top", "width", "height", "this.div.clip.left = left; this.div.clip.top = top; this.div.clip.width = width; this.div.clip.height = height; this.div.width = width; this.div.height = height; this.div.clip.height = height; this.width = width; this.height = height;");
		this.swapImage = new Function("image", "src", "this.div.document.images[image].src = src");
		this.getImageSrc = new Function("image", "return this.div.document.images[image].src");
	}
	else
	{
		this.div = divName;
		this.baseDiv = divName;
		this.divName = divName;
		this.write = new Function("text", "document.getElementById('" + divName + "').innerHTML = text; this.width = this.baseDiv.offsetWidth; this.height = this.baseDiv.offsetHeight;");
		this.setBgColour = new Function("colour", "this.div.backgroundColor = colour;");
		this.setBgImage = new Function("src", "this.div.backgroundImage = 'url(' + src + ')';");
		this.hide = new Function("this.div.visibility = 'hidden';");
		this.show = new Function("this.div.visibility = 'inherit';");
		this.setSize = new Function("left", "top", "width", "height", "setWidthAndHeight", "this.div.clip = 'rect(' + top + ',' + (left+width) + ',' + (top+height) + ',' + left + ')'; if(setWidthAndHeight != false){this.div.width = width; this.div.height = height; this.width = width; this.height = height;}");
		this.swapImage = new Function("image", "src", "document.images[image].src = src");
		this.getImageSrc = new Function("image", "return document.images[image].src");
	}
	this.activate = activateDiv;
	this.setXY = new Function("x", "y", "this.div.left = x; this.div.top = y;");
	this.captureEvents = captureDivEvents;
	this.idNo = divObjectArray.length;
	divObjectArray[divObjectArray.length] = this;
	
	this.width = 0;
	this.height = 0;
	this.originalWidth = 0;
	this.originalHeight = 0;
	this.left = 0;
	this.top = 0;
	this.clipLeft = 0;
	this.clipTop = 0;
	
	this.moveTo = new Function("x", "y", "this.left=x; this.top=y; this.setXY(x, y)");
	this.moveBy = new Function("x", "y", "this.left+=x; this.top+=y; this.setXY(this.left, this.top)");
	this.resizeTo = new Function("x", "y", "this.width=x; this.height=y; this.setSize(this.clipLeft, this.clipTop, this.width, this.height)");
	this.resizeBy = new Function("x", "y", "this.width+=x; this.height+=y; this.setSize(this.clipLeft, this.clipTop, this.width, this.height)");
	this.clip = new Function("left", "top", "width", "height", "setWidthAndHeight", "this.clipLeft=left; this.clipTop=top; this.clipWidth=width; this.clipHeight=height; this.setSize(left, top, width, height, setWidthAndHeight);");
	this.setZIndex = new Function("z", "this.div.zIndex=z;");
}


function activateDiv()
{
if(typeof(this.div) != 'string') return;

if(!browserVars.type.getById)
{
this.baseDiv = eval(this.div);
this.div = this.baseDiv

this.width = this.div.clip.width;
this.height = this.div.clip.height;
this.left = this.div.left;
this.top = this.div.top;
}
else
{
this.baseDiv = document.getElementById(this.div);
this.div = this.baseDiv.style;

this.width = this.baseDiv.offsetWidth;
this.height = this.baseDiv.offsetHeight;
this.left = this.baseDiv.offsetLeft;
this.top = this.baseDiv.offsetTop;
}

this.clipWidth = this.width;
this.clipHeight = this.height;
this.originalWidth = this.width;
this.originalHeight = this.height;
}


function captureDivEvents(eventName, action)
{
if(!browserVars.type.getById)
eval('this.div.captureEvents(Event.' + eventName.toUpperCase() + ')');
eval('this.baseDiv.on' + eventName + ' = new Function("e", "' + action + '")');
}
/*
Script by RoBorg
RoBorg@geniusbug.com
http://javascript.geniusbug.com
Please do not remove or edit this message
*/

function initCMenu()
{
	cMenu = new divObject('cMenuDiv', 'document.');
	cMenu.activate();

	
	if(!browserVars.type.getById)
		document.captureEvents(Event.MOUSEDOWN);
	document.onmousedown = click;
	
	cMenu.div.width = cMenu.width; //<hr> Bug Fix
 
}

function click(e)
{
	if(browserVars.type.ie)
	{
		var button = event.button;
		browserVars.updateVars();
		browserVars.updateMouse();
		//alert(button);
	}
	else
	{
		var button = e.which -1;
	}

	if(button != 2)
	{
		setTimeout("cMenu.hide()", 300);
		return;
	}
	return false;
}

function showContextMenu()
{
	if(browserVars.type.ie)
	{
		browserVars.updateVars();
		browserVars.updateMouse();
	}

	cMenu.moveTo(browserVars.mouseX, browserVars.mouseY);
	cMenu.show();

	return false;
}

function createContextItem(title,fx,deactive)
{
	var tb = document.getElementById("cMenuBody");

	var astyle='';
	if (deactive)
		astyle = 'class="disabled"';
	
	str = '<nobr><img src="/images/blank.gif" width="10"> <a '+astyle+' href="#">'+title+'</a></nobr>';

	var tr = document.createElement('tr');	
	var td = document.createElement('td');
	
	td.width='50px';
	td.className = "out";
	if (!deactive)
	{
		td.onmouseover = function() { this.className='over'; };
		td.onmouseout = function() { this.className='out'; };
		td.onclick = fx;
	}
	
	td.innerHTML = str;
	tr.appendChild(td);
	tb.appendChild(tr);
}

function createContextSeperator()
{
	var tb = document.getElementById("cMenuBody");
	str = '<img src="/images/misc/separator.jpg" width="100%" height="2">';
	var tr = document.createElement('tr');	
	var td = document.createElement('td');
	td.style.paddingLeft='25px';	
	td.innerHTML = str;
	tr.appendChild(td);
	tb.appendChild(tr);
}

function cleanContextMenu()
{
	var tb = document.getElementById("cMenuBody");

	if(navigator.appName == "Microsoft Internet Explorer")
	{
		var len = tb.rows.length;
		var index=len-1;
		for (var i=0;i<len;i++)
		{
			tb.deleteRow(index);
			index=index-1;
		}
	}
	else
	{
		tb.innerHTML='';
				
	}
}// ---------------------------------------------------------------------------
// this script is copyright (c) 2001 by Michael Wallner!
// http://www.wallner-software.com
// mailto:dhtml@wallner-software.com
//
// you may use this script on web pages of your own
// you must not remove this copyright note!
//
// This script featured on Dynamic Drive (http://www.dynamicdrive.com)
// Visit http://www.dynamicdrive.com for full source to this script and more
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
//                   Outlook like navigation bar version 1.2
//
// supported browsers:  IE4, IE5, NS4, NS6, MOZ, OP5
// needed script files: crossbrowser.js
//
// History:
// 1.0: initial version
// 1.1: no Reload in IE and NS6
// 1.2: no Reload in OP5 if width is not changed
// ---------------------------------------------------------------------------

//add one button to a panel
//einen Button zu einem Panel hinzufügen
//img:    image name - Name der Bilddatei
//label:  button caption - Beschriftung des Buttons
//action: javascript on MouseUp event - Javascript beim onMouseUp event

function b_addButton(img, label, tooltip, action) {
  this.img[this.img.length]=img;
  this.lbl[this.lbl.length]=label;
  this.ttip[this.ttip.length]=tooltip;
  this.act[this.act.length]=action;
  this.sta[this.sta.length]=0;  

  return this
}

//reset all panel buttons  (ns4, op5)
//alle Panel Buttons zurücksetzten (ns4, op5)
function b_clear() {
var i
  for (i=0;i<this.sta.length;i++) {
    if (this.sta[i] != 0)
      this.mOut(i);
  }
}


//----------------------------------------------------------------------------
// Panel functions for Netscape 4
//----------------------------------------------------------------------------

// write new htmlcode into the button layer
// schreibe den neuen HTML Code in den Button Layer
function b_mOver_ns4(nr) {
  this.clear();
  l=this.obj.layers[0].layers[nr].document;
  l.open();
  l.write("<Center>")
  l.write("<SPAN class='imgbout'>")
  l.write("<A href='#' onmouseOut='"+this.v+".mOut("+nr+")' ");
  l.write("onMousedown='"+this.v+".mDown("+nr+")'><img src='"+this.img[nr]);
  l.write("' border=0></A></SPAN><Font size=2 face=Arial color=white>");
  l.write(this.lbl[nr]+"</FONT><BR><BR>");
  l.close();
  this.sta[nr]=1;
}

function b_mOut_ns4(nr) {
  l=this.obj.layers[0].layers[nr].document;
  l.open();
  l.write("<Center>")
  l.write("<SPAN class='imgnob'>")
  l.write("<A href='#' onmouseOver='"+this.v+".mOver("+nr+")' ");
  l.write("onmouseOut='"+this.v+".mOut("+nr+")'><img src='"+this.img[nr]);
  l.write("' border=0></A></SPAN><Font size=2 Face=Arial color=white>");
  l.write(this.lbl[nr]+"</FONT><BR><BR>");
  l.close();
  this.sta[nr]=0;
}

function b_mDown_ns4(nr) {
  l=this.obj.layers[0].layers[nr].document;
  l.open();
  l.write("<Center>")
  l.write("<SPAN class='imgbin'>")
  l.write("<A href='#' onmouseOver='"+this.v+".mOver("+nr+")' ");
  l.write("onmouseOut='"+this.v+".mOut("+nr+")' onMouseup='"+this.act[nr]);
  l.write(";"+this.v+".mOver("+nr+")'><img src='"+this.img[nr]);
  l.write("' border=0></A></SPAN><Font size=2 Face=Arial color=white>");
  l.write(this.lbl[nr]+"</FONT><BR><BR>");
  l.close();
  this.sta[nr]=1;
}

//test if scroll buttons should be visible
//teste ob Scroll-Buttons sichtbar sein sollen
function b_testScroll_ns4() {
var i
var j
var k

  i=this.obj.clip.bottom;
  j=this.obj.layers[0].clip.bottom;
  k=parseInt(this.obj.layers[0].top);

  if (k==38)
    this.obj.layers[2].visibility='hide';
  else
    this.obj.layers[2].visibility='show';

  if ((j+k)<i) {
    this.obj.layers[3].visibility='hide';
  }
  else
    this.obj.layers[3].visibility='show';
}

//scroll the panel content up
//scrolle den Panel Inhalt nach Oben
function b_up_ns4(nr) {
    this.ftop = this.ftop - 5;
    this.obj.layers[0].top=this.ftop;
    nr--
    if (nr>0)
      setTimeout(this.v+'.up('+nr+');',10);
    else
      this.testScroll();
}

//scroll the panel content down
//scrolle den Panel Inhalt nach Unten
function b_down_ns4(nr) {
    this.ftop = this.ftop + 5;
    if (this.ftop>=38) {
      this.ftop=38;
      nr=0;
    }
    this.obj.layers[0].top=this.ftop;
    nr--

    if (nr>0)
      setTimeout(this.v+'.down('+nr+');',10);
    else
      this.testScroll();
}

//----------------------------------------------------------------------------
// Panel functions for Opera5
//----------------------------------------------------------------------------

//show one panelbutton layer and hide the others two
//zeige einen Panel Button Layer und verstecke die anderen beiden
function b_mOver_op5(nr) {
  var obj0=getObj(this.name+'_b'+nr+'0')
  var obj1=getObj(this.name+'_b'+nr+'1')
  var obj2=getObj(this.name+'_b'+nr+'2')

  this.clear();
  obj1.style.visibility="VISIBLE";
  obj0.style.visibility="HIDDEN";
  obj2.style.visibility="HIDDEN";
  this.sta[nr]=1;
}

function b_mOut_op5(nr) {
  var obj0=getObj(this.name+'_b'+nr+'0')
  var obj1=getObj(this.name+'_b'+nr+'1')
  var obj2=getObj(this.name+'_b'+nr+'2')

  obj2.style.visibility="visible";
  obj0.style.visibility="hidden";
  obj1.style.visibility="hidden";
  this.sta[nr]=1;
}

function b_mDown_op5(nr) {
  var obj0=getObj(this.name+'_b'+nr+'0')
  var obj1=getObj(this.name+'_b'+nr+'1')
  var obj2=getObj(this.name+'_b'+nr+'2')

  obj0.style.visibility="visible";
  obj1.style.visibility="hidden";
  obj2.style.visibility="hidden";
  this.sta[nr]=1;
}

// ---------------------------------------------------------------------------
// Panel functions for ie4, ie5, ns5, op5
// ---------------------------------------------------------------------------

//test if scroll buttons should be visible
//teste ob Scroll-Buttons sichtbar sein sollen
function b_testScroll() {

  if (bt.op5) {
    var i=parseInt(this.obj.style.pixelHeight);
    var j=parseInt(this.objf.style.pixelHeight);
  }
  else {
    var i=parseInt(this.obj.style.height);
    var j=parseInt(this.objf.style.height);
  }
  var k=parseInt(this.objf.style.top);


  if (k==38)
    this.objm1.style.visibility='hidden';
  else
    this.objm1.style.visibility='visible';

  if ((j+k)<i) {
    this.objm2.style.visibility='hidden';
  }
  else
    this.objm2.style.visibility='visible';
}

//scroll the panel content up
//scrolle den Panel Inhalt nach Oben
function b_up(nr) {
    this.ftop = this.ftop - 5;
    this.objf.style.top=this.ftop;
    nr--
    if (nr>0)
      setTimeout(this.v+'.up('+nr+');',10);
    else
      this.testScroll();
}

//scroll the panel content down
//scrolle den Panel Inhalt nach Unten
function b_down(nr) {
    this.ftop = this.ftop + 5;
    if (this.ftop>=38) {
      this.ftop=38;
      nr=0;
    }
    this.objf.style.top=this.ftop;
    nr--

    if (nr>0)
      setTimeout(this.v+'.down('+nr+');',10);
    else
      this.testScroll();
}

// ---------------------------------------------------------------------------
// Panel object
// ---------------------------------------------------------------------------

//create one panel
function createPanel(name,caption) {
  this.name=name;                  // panel layer ID
  this.ftop=38;                    // actual panel scroll position
  this.obj=null;                   // panel layer object
  this.objc=null;                  // caption layer object
  this.objf=null;                  // panel field layer object
  this.objm1=null;                 // scroll button up
  this.objm2=null;                 // scroll button down
  this.caption=caption;            // panel caption
  this.img=new Array();            // button images
  this.lbl=new Array();            // button labels
  this.ttip=new Array();           // button tooltips
  this.act=new Array();            // button actions
  this.sta=new Array();            // button status (internal)  
  this.addButton=b_addButton;      // add one button to panel
  this.clear=b_clear;              // reset all buttons
  if (bt.ns4) {                          // functions for ns4
	this.mOver=b_mOver_ns4;              // handles mouseOver event
	this.mOut=b_mOut_ns4;                // handles mouseOut & mouseUp event
    this.mDown=b_mDown_ns4;              // handles mouseDown event
    this.testScroll=b_testScroll_ns4;    // test if scroll buttons visible
    this.up=b_up_ns4;                    // scroll panel buttons up
    this.down=b_down_ns4;                // scroll panel buttons down
  }
  if (bt.op5) {                          // functions for op5
	this.mOver=b_mOver_op5;              // handles mouseOver event
    this.mOut=b_mOut_op5;                // handles mouseOut & mouseUp event
    this.mDown=b_mDown_op5;              // handles mouseDown event
  }
  if (!bt.ns4) {                     // functions for all browsers but ns4
    this.testScroll=b_testScroll;    // test if scroll buttons should be visible
    this.up=b_up;                    // scroll panel buttons up
    this.down=b_down;                // scroll panel buttons down
  }

  this.v = this.name + "var";   // global var of 'this'
  eval(this.v + "=this");

  return this
}

//add one panel to the outlookbar
function b_addPanel(panel) {
  panel.name=this.name+'_panel'+this.panels.length
  this.panels[this.panels.length] = panel;
}

//write style sheets
//schreibe die Style sheets
function b_writeStyle() {

  document.write('<STYLE TYPE="text/css">');
  
  // Moved to main site "style.css" with name 'button'
  /*
  document.write('.button {width:300; text-align:center; font-family:Tahoma,Trebuchet MS,Verdana;');
  document.write(' font-size:9pt;font-weight:normal; cursor:hand;');
  document.write(' border: 1px outset #f0f8ff; ');
  document.write(' padding-left: 2px; ');
  document.write(" filter:progid:DXImageTransform.Microsoft.Gradient(GradientType=0,StartColorStr='#FFDBEAF7',EndColorStr='#DD9DB5D1'); ");
  document.write(' background-color:#457CC0;}');
  */
  /*
  document.write(" filter:progid:DXImageTransform.Microsoft.Gradient(GradientType=0,StartColorStr='#FFF6F5F4',EndColorStr='#00D4D0C8'); ");
  document.write(' background-color:#d4d0c8;}');
  */
  document.write('.noLine {text-decoration:none;}');

  document.write('.imgB {color:black; font-family:Tahoma,Trebuchet MS,Verdana; font-size:8pt;}');

  if (bt.op5) {
	document.write('.imgbin {border-width:1; border-style:inset; ');
	document.write('border-color:white;}');
  }
  else {
	document.write('.imgbin {border-width:1; border-style:inset; ');
	document.write('border-color:blue;background-color:#9BA5C2;}');
  }

  if (bt.op5) {
	document.write('.imgbout {border-width:3; border-style:outset; ');
	document.write('border-color:white;}');
  }
  else {
	document.write('.imgbout {border-width:1; border-style:outset; ');
	document.write('border-color:blue;background-color:#b6bdd2;}');
  }
  
  document.write(' .imgnob {border-width:1; border-style:solid; ');
  document.write('border-color:'+this.bgcolor+';}');

  document.write('</STYLE>');

}

// Draw the Outlook Bar
function b_draw() {
var i;
var j;
var t=0;
var h;
var c=0;

  this.writeStyle();

  if (bt.ns5 || bt.op5) c=6;       //two times border width



  if (bt.ns4) {                 //draw OutlookBar for ns4
    //OutlookBar layer..
    document.write('<layer bgcolor='+this.bgcolor+' name='+this.name+' left=');
    document.write(this.xpos+' top='+this.ypos+' width='+this.width);
    document.write(' clip="0,0,'+this.width+','+this.height+'">');

    //one layer for every panel...
    for (i=0;i<this.panels.length;i++) {
      document.write('<Layer name='+this.name+'_panel'+i+' width='+this.width);
       document.write(' top='+i*28+' bgcolor='+this.bgcolor);
       document.write(' clip="0,0,'+this.width+',');
       document.write(this.height-(this.panels.length-1)*28+'">');

       //one layer to host the panel buttons
       document.write('<Layer top=38 width='+this.width+'>');
        mtop=0

        //one layer for every button
        for (j=0;j<this.panels[i].img.length;j++) {
          document.write('<Layer top='+mtop+' width='+this.width);
          document.write('><Center><SPAN class=imgnob>');
          document.write("<A href='#' onmouseOut='"+this.panels[i].v);
		  document.write(".rst("+j+")' onmouseOver='"+this.panels[i].v);
		  document.write(".mOver("+j+")'><img src='"+this.panels[i].img[j]);
		  document.write("' border=0></A></SPAN>");
          document.write("<Font size=2 face=arial color=white>");
          document.write(this.panels[i].lbl[j]+"</FONT><BR><BR>");
         document.write('</Layer>');
         mtop=mtop+this.buttonspace;
        }

       document.write('</Layer>');

       //one layer for the panels caption
       document.write('<Layer top=0 width='+this.width+' clip="0,0,');
	   document.write(this.width+',28" bgcolor=silver class=button ');
	   document.write('onmouseOver="'+this.panels[i].v+'.clear();">');
	   document.write('<A class=noLine href="javascript:'+this.v+'.showPanel(');
	   document.write(i+');" onmouseOver="'+this.panels[i].v+'.clear();">');
	   document.write('<Font Color=black class=noLine>'+this.panels[i].caption);
	   document.write('</Font></A></Layer>');

	   //two layers for scroll-up -down buttons
	   document.write('<Layer visibility=hide top=40 left='+(this.width-20));
	   document.write('><A href="#" onClick="'+this.panels[i].v+'.down(16);" ');
	   document.write('onmouseOver="'+this.panels[i].v+'.clear();"><img ');
       document.write('width=16 height=16 src=images/misc/arrowup.gif border=0>');
       document.write('</A></LAYER><Layer top=');
       document.write((this.height-(this.panels.length)*28)+'<Layer top=');
       document.write((this.height-(this.panels.length)*28)+' left=');
       document.write((this.width-20)+'><A href="#" onClick="');
	   document.write(this.panels[i].v+'.up(16);" onmouseOver="');
       document.write(this.panels[i].v+'.clear();"><img width=16 height=16 ');
       document.write('src=images/misc/arrowdown.gif border=0></A></LAYER>');

      document.write('</LAYER>');
    }
    document.write('</LAYER>');
  }
  else {                             //draw Outlook bar for all browsers but ns4

    //OutlookBar layer..
    document.write('<DIV id='+this.name+' Style="position:absolute; background-repeat: repeat-y; left:');
	//document.write('<DIV id='+this.name+' Style="position:absolute; left:');
    document.write(this.xpos+'; top:'+this.ypos+'; width:'+this.width);
    document.write('; height:'+this.height+'; background-color:'+this.bgcolor);
    document.write('; clip:rect(0,'+this.width+','+this.height+',0)">');
    h=this.height-((this.panels.length-1)*20);

	//one layer for every panel...
    for (i=0;i<this.panels.length;i++) {
      document.write('<DIV id='+this.name+'_panel'+i);
      document.write(' Style="position:absolute; left:0; background-image: url(images/outlookbar/links_bg.jpg); top:'+t);
      document.write('; width:'+this.width+'; height:'+h+'; clip:rect(0px, ');
      document.write(this.width+'px, '+h+'px, 0px); background-color:');
      
	  document.write('transparent;">');
	  //document.write(this.bgcolor+';">');
      t=t+20;

       //one layer to host the panel buttons
      document.write('<div id='+this.name+'_panel'+i);
      document.write('_f Style="position:absolute; left:0; top:38; width:');
      document.write(this.width+'; height:');
      document.write((this.panels[i].img.length*this.buttonspace));
	  
	  document.write('; background-color:transparent;">')
      //document.write('; background-color:'+this.bgcolor+';">')
      mtop=-10;

      //one (ie4, ie5, ns5) or three layers (op5) for every button
      for (j=0;j<this.panels[i].img.length;j++) {
        if (bt.op5) {
          document.write('<DIV id='+this.name+'_panel'+i+'_b'+j);
          document.write('0 class=imgB Style="position:absolute; ');
          document.write('visibility:hidden; left:0; width:'+this.width);
          document.write('; top:'+mtop+'; text-align:center;">');
          document.write('<img alt="' +this.panels[i].ttip[j]+ '" src='+this.panels[i].img[j]);
          document.write(' class=imgbin onmouseUp=\''+this.panels[i].v);
		  document.write('.mOver('+j+');'+this.panels[i].act[j]);
          document.write(';\' onmouseOut="'+this.panels[i].v+'.mOut('+j);
          document.write(');"><BR>'+this.panels[i].lbl[j]+'</DIV>');

          document.write('<DIV id='+this.name+'_panel'+i+'_b'+j+'1 class=imgB');
          document.write(' Style="position:absolute; visibility:hidden; ');
          document.write('left:0; width:'+this.width+'; top:'+mtop);
          document.write('; text-align:center;">');
          document.write('<img alt="' +this.panels[i].ttip[j]+ '" src='+this.panels[i].img[j]);
          document.write(' class=imgbout onmouseDown="'+this.panels[i].v);
          document.write('.mDown('+j+');" onmouseUp=\''+this.panels[i].v);
		  document.write('.mOver('+j+');'+this.panels[i].act[j]);
          document.write(';\' onmouseOut="'+this.panels[i].v+'.mOut('+j);
          document.write(');"><BR>'+this.panels[i].lbl[j]+'</DIV>');

          document.write('<DIV id='+this.name+'_panel'+i+'_b'+j);
          document.write('2 class=imgB Style="position:absolute; ');
          document.write('visibility:visible; left:0; width:'+this.width);
          document.write('; top:'+mtop+'; text-align:center;">');
          document.write('<img alt="' +this.panels[i].ttip[j]+ '" src='+this.panels[i].img[j]+' class=imgnob ');
		  document.write('onmouseOver="'+this.panels[i].v+'.mOver('+j);
          document.write(');"><BR>'+this.panels[i].lbl[j]+'</DIV>');
        }
        else {
          document.write('<DIV id='+this.name+'_panel'+i+'_b'+j+' class=imgB ');
          document.write('Style="position:absolute; left:5; width:'+(this.width-10));
          document.write('; top:'+mtop+'; text-align:center;">');
          document.write('<img alt="' +this.panels[i].ttip[j]+ '" src='+this.panels[i].img[j]+' class=imgnob ');
		  document.write('onmouseOver="this.className=\'imgbout\';" ');
          document.write('onmouseDown="this.className=\'imgbin\';" ');
          document.write('onmouseUp=\'this.className="imgbout";');
          document.write(this.panels[i].act[j]+';\' ');
          document.write('onmouseOut="this.className=\'imgnob\';"><BR>');
          document.write(this.panels[i].lbl[j]+'</DIV>');
        }
        mtop=mtop+this.buttonspace;
      }

      document.write('</DIV>');

      //one layer for the panels caption if not op5!
      if (!bt.op5) {
		document.write('<DIV id='+this.name+'_panel'+i+'_c class=button ');
		document.write('onClick="javascript:'+this.v+'.showPanel('+i);
		document.write(');" style="position:absolute; left:0; top:0; width:');
		document.write((this.width-c)+'; height:'+(20-c)+';"><A href="#" ');
		document.write('onClick="'+this.v+'.showPanel('+i+');this.blur();');
		document.write('return false;" class=noLine><FONT color=black ');
		document.write('class=noLine">'+this.panels[i].caption);
		document.write('</FONT></A></DIV>')
	  }
	  //two layers for scroll-up -down buttons
	  document.write('<DIV id='+this.name+'_panel'+i);
	  document.write('_m1 style="position:absolute; top:23; left:');
	  document.write((this.width-20)+';"><A href="#" onClick="');
	  document.write(this.panels[i].v+'.down(16);this.blur();return false;" ');
	  document.write('onmouseOver="'+this.panels[i].v+'.clear();">');
	  document.write('<img width=16 height=16 src=images/misc/arrowup.gif border=0>');
	  document.write('</A></DIV>');
      document.write('<DIV id='+this.name+'_panel'+i);
      document.write('_m2 style="position:absolute;  top:');
      document.write((this.height-(this.panels.length)*20)+'; left:');
      document.write((this.width-20)+';"><A href="#" onClick="');
      document.write(this.panels[i].v+'.up(16);this.blur();return false" ');
      document.write('onmouseOver="'+this.panels[i].v+'.clear();">');
      document.write('<img width=16 height=16 src=images/misc/arrowdown.gif border=0>');
      document.write('</A></DIV>');


      document.write('</DIV>')

    }
    //Opera bug (Clip!)
    //op5 doesn't support layer clipping! so use top layers for panel caption
    //and two top layers with background-color like page color to hide
    //panel content outside of the outlookbar.
    //op5 unterstützt kein Clip bei Layers! darum erzeugen wir drei top level
    //layers für die Panel Überschrift und zwei top Layers mit der gleichen
    //Hintergrundfarbe wie die HTML Seite um den Panel Inhalt außerhalb des
    //Outlook Bars zu verdecken!
    if (bt.op5) {
      //one layers for panel captions if op5
      for (i=0;i<this.panels.length;i++) {
        document.write('<DIV id='+this.name+'_panel'+i);
        document.write('_c class=button onmouseOver="'+this.panels[i].v);
        document.write('.clear();" onClick="'+this.v+'.showPanel('+i);
        document.write(');" style="position:absolute; left:0; top:0; width:');
        document.write((this.width-c)+'; height:'+(28-c)+';">');
        document.write('<A href="#" ');
        document.write('onClick="'+this.v+'.showPanel('+i+');this.blur();');
        document.write('return false;" class=noLine><FONT color=black ');
        document.write('class=noLine">'+this.panels[i].caption);
        document.write('</FONT></A></DIV>')
      }
      //two layers to hide 'nonvisible' part of panel
      //(op5 doesn't support clipping!)
      //document.write('<DIV style="position:absolute; left:0; top:');
      //document.write(this.height+'; height:300; width:'+this.width);
      //document.write('; background-color:'+this.pagecolor+';"></DIV>');
      //document.write('<DIV style="position:absolute; left:0; top:-300; ');
      //document.write('height:300; width:'+this.width+'; background-color:');
      //document.write(this.pagecolor+';"></DIV>');
    }
    document.write('</DIV>');

  }
  for (i=0;i<this.panels.length;i++) {
    this.panels[i].obj=getObj(this.name+'_panel'+i);
    if (!bt.ns4) {
      this.panels[i].objc=getObj(this.name+'_panel'+i+'_c');
      this.panels[i].objf=getObj(this.name+'_panel'+i+'_f');
      this.panels[i].objm1=getObj(this.name+'_panel'+i+'_m1');
      this.panels[i].objm2=getObj(this.name+'_panel'+i+'_m2');
    }
    this.panels[i].testScroll();
  }

  //activate last panel
  //op5 dosen't support cookies!
  //so get actual panel from url paramter
  if (bt.op5) {
    if (document.location.search=='')  {
      this.showPanel(0);
    }
    else
      this.showPanel(document.location.search.substr(1,1));
  }
  else {
    //actual panel is saved in a cookie
    if (document.cookie)
      this.showPanel(document.cookie);
    else
      this.showPanel(0);
  }
}


// ---------------------------------------------------------------------------
// outlookbar function for ns4
// ---------------------------------------------------------------------------

function b_showPanel_ns4(nr) {
var i
var l
  document.cookie=nr;
  l = this.panels.length;
  for (i=0;i<l;i++) {
    if (i>nr) {
      this.panels[i].obj.top=this.height-((l-i)*28)-1;
    }
    else {
      this.panels[i].obj.top=i*28;
    }
  }
}

// ---------------------------------------------------------------------------
// outlookbar function for ie4, ie5, ns5, op5
// ---------------------------------------------------------------------------

function b_showPanel(nr) {
var i
var l
var o
  document.cookie=nr;
  this.aktPanel=nr;
  l = this.panels.length;
  for (i=0;i<l;i++) {
    if (i>nr) {
      this.panels[i].obj.style.top=this.height-((l-i)*21);
      //Opera doesn't support clip:rect()!
      //so hide non visible panels
      //and move panel caption
      if (bt.op5) {
        this.panels[i].objf.style.visibility='hidden';
        this.panels[i].objc.style.top=this.height-((l-i)*28);
      }
    }
    else {
      this.panels[i].obj.style.top=i*21;
      //Opera doesn't support clip:rect()!
      //so show visible panel
      //and move panel caption
      if (bt.op5) {
        this.panels[i].objf.style.visibility='visible';
        this.panels[i].objc.style.top=i*28;
      }
    }
  }
}

//resize the Outlook Like Bar
//IE4/5 & NS6 -> resize all layers (width & height)
//op5         -> resize only height - reload on width change
//ns4         -> reload on any change!
//
//if you change the width of a layer (style="text-align:center;") then
//the content will not be moved!
function b_resize(x,y,width,height) {
var o
var i
var j
var h
var c=(bt.ns5)?6:0;

   if (bt.ns4)
     location.reload();
   else {
     if (bt.op5 && (width!=this.width))
       if (location.href.indexOf('?')!=-1)
         location.href=location.href.replace(/\?./,"?"+this.aktPanel)
       else
         location.href= location.href+'?'+this.aktPanel;
     else {
       this.xpos=x;
       this.yPos=y;
       this.width=width
       this.height=height

       o=getObj(this.name);
       o.style.left=x;
       o.style.top=y;
       o.style.width=width;
       o.style.height=height;
       o.style.clip='rect(0px '+this.width+'px '+this.height+'px 0px)';

       h=this.height-((this.panels.length-1)*28)

       for (i=0; i<this.panels.length; i++) {

         o=getObj(this.name+'_panel'+i+'_c');
         o.style.width=(this.width-c);

         if (!bt.op5)
           for (j=0;j<this.panels[i].img.length;j++) {
             o=getObj(this.name+'_panel'+i+'_b'+j);
             o.style.width=this.width-10;
           }

         this.panels[i].objm1.style.left=(this.width-20);
         this.panels[i].objm2.style.top=(this.height-(this.panels.length)*28);
         this.panels[i].objm2.style.left=(this.width-20);
         this.panels[i].objf.style.width=this.width;
         this.panels[i].obj.style.width=this.width
         this.panels[i].obj.style.height=h
         this.panels[i].obj.style.pixelHeight=h
         this.panels[i].obj.style.clip='rect(0px '+this.width+'px '+h+'px 0px)';

         this.panels[i].testScroll();
       }
     }
     this.showPanel(this.aktPanel);
   }
}



// ---------------------------------------------------------------------------
// OutlookBar object for ie4, ie5, ns5, op5
// ---------------------------------------------------------------------------

function createOutlookBar(name,x,y,width,height,bgcolor,pagecolor) {
  this.aktPanel=0;                        // last open panel
  this.name=name                          // OutlookBar name
  this.xpos=x;                            // bar x-pos
  this.ypos=y;                            // bar y-pos
  this.width=width;                       // bar width
  this.height=height;                     // bar height
  this.bgcolor=bgcolor;                   // bar background color
  this.pagecolor=pagecolor;               // page bgcolor (op5!)
  this.buttonspace=70                     // distance of panel buttons
  this.panels=new Array()                 // OutlookBar panels
  this.addPanel=b_addPanel;               // add new panel to bar
  this.writeStyle=b_writeStyle;
  this.draw=b_draw;                       // write HTML code of bar
  if (bt.ns4)
    this.showPanel=b_showPanel_ns4;       // make a panel visible (ns4)
  else
    this.showPanel=b_showPanel;           // make a panel visible (!=ns4)
    
  this.resize=b_resize;                   // resize Outlook Like Bar

  this.v = name + "var";                  // global var of 'this'
  eval(this.v + "=this");

  return this
}
