/*
Script: Function.js
	Contains Function Prototypes like create, bind, pass, and delay.

License:
	MIT-style license.
*/

if(typeof($splat) != "function") {
	function $splat(obj){
		var type = $type(obj);
		return (type) ? ((type != 'array' && type != 'arguments') ? [obj] : obj) : [];
	};
}
Function.prototype.create = function(options) {
	var self = this;
	options = options || {};
	return function(event){
		var args = options.arguments;
		args = (args != undefined) ? $splat(args) : Array.prototype.slice(arguments, (options.event) ? 1 : 0);
		if (options.event) args = [event || window.event].extend(args);
		var returns = function(){
			return self.apply(options.bind || null, args);
		};
		if (options.delay) return setTimeout(returns, options.delay);
		if (options.periodical) return setInterval(returns, options.periodical);
		if (options.attempt) return $try(returns);
		return returns();
	};
};
Function.prototype.extend = function(properties) {
	for (var property in properties) this[property] = properties[property];
	return this;
};
Function.prototype.run = function(args, bind) {
	return this.apply(bind, $splat(args));
};
Function.prototype.pass = function(args, bind) {
	return this.create({bind: bind, arguments: args});
};
Function.prototype.bind = function(bind, args) {
	return this.create({bind: bind, arguments: args});
};
Function.prototype.bindWithEvent = function(bind, args) {
	return this.create({bind: bind, arguments: args, event: true});
};
Function.prototype.attempt = function(args, bind) {
	return this.create({bind: bind, arguments: args, attempt: true})();
};
Function.prototype.delay = function(delay, bind, args) {
	return this.create({bind: bind, arguments: args, delay: delay})();
};
Function.prototype.periodical = function(periodical, bind, args) {
	return this.create({bind: bind, arguments: args, periodical: periodical})();
};


if(!Array.prototype.each) {
	Array.prototype.each = function(pFc, pContext) {
		var vSz = this.length;
		if(typeof(pFc) != "function") throw new TypeError();
		
		var vThis = arguments[1];
		if(!pContext) pContext = vThis;
		for(var vLoop = 0; vLoop < this.length; vLoop++) {
			if(vLoop in this) pFc.call(pContext, this[vLoop], vLoop, this);
		}
	};
}
if(!Object.prototype.each) {
	Object.prototype.each = Array.prototype.each;
}
if(!Object.prototype.clone) {
	Object.prototype.clone = function() {
		var vNew = (this instanceof Array) ? [] : {};
		for (var vProp in this) {
			if(vProp == 'clone') continue;
			if(this[vProp] && (typeof(this[vProp]) == "object")) {
				if(typeof(this[vProp].getTime) == "function") vNew[vProp] = new Date(this[vProp]);
				else vNew[vProp] = this[vProp].clone();
			} else vNew[vProp] = this[vProp];
		}
		return vNew;
	};
}
if((typeof(NodeList) != "undefined") && !NodeList.prototype.each) {
	NodeList.prototype.each = function(pFc, pContext) {
		var vSz = this.length;
		if(typeof(pFc) != "function") throw new TypeError();
		
		var vThis = arguments[1];
		if(!pContext) pContext = vThis;
		for(var vLoop = 0; vLoop < this.length; vLoop++) {
			if(vLoop in this) pFc.call(pContext, this.item(vLoop), vLoop, this);
		}
	};
}
if((typeof(HTMLCollection) != "undefined") && !HTMLCollection.prototype.each) {
	HTMLCollection.prototype.each = NodeList.prototype.each;
}
if(!Date.prototype.mmddyyyy) {
	Date.prototype.mmddyyyy = function(pSeparator) {
		if(!pSeparator) pSeparator = "/";
		var vString = "";
		var vNumber = this.getMonth() + 1;
		if(vNumber < 10) vString = "0";
		vString += vNumber + pSeparator;
		vNumber = this.getDate();
		if(vNumber < 10) vString += "0";
		vString += vNumber + pSeparator;
		vString += this.getFullYear();
		
		return vString;
	}
}
if(!Date.prototype.yyyymmdd) {
	Date.prototype.yyyymmdd = function(pSeparator) {
		if(!pSeparator) pSeparator = "-";
		var vString = this.getFullYear() + pSeparator;
		var vNumber = this.getMonth() + 1;
		if(vNumber < 10) vString += "0";
		vString += vNumber + pSeparator;
		vNumber = this.getDate();
		if(vNumber < 10) vString += "0";
		vString += vNumber;
		
		return vString;
	}
}

YAHOO.util.DataSource.Parser.monitusDate = function(pDate) {
		var vDate = null;
		if(YAHOO.lang.isValue(pDate) && !(pDate instanceof Date)) vDate = new Date(pDate);
		else return pDate;
		if(vDate instanceof Date) return vDate;
		YAHOO.log("Could not convert data " + YAHOO.lang.dump(pDate) + " to type Date", "warn", this.toString());
		return null;
};

YAHOO.widget.DataTable.prototype.getTdEl = function(cell) {
	var Dom = YAHOO.util.Dom,
	lang = YAHOO.lang,
	elCell,
	el = Dom.get(cell);
	// Validate HTML element
	if(el && (el.ownerDocument == document)) {
		// Validate TD element
		if(el.nodeName.toLowerCase() != "td") {
			// Traverse up the DOM to find the corresponding TR element
			elCell = Dom.getAncestorByTagName(el, "td");
		} else elCell = el;
		// Make sure the TD is in this TBODY
		if(elCell && (elCell.parentNode.parentNode == this._elTbody)) {
			// Now we can return the TD element
			return elCell;
		}
	} else if(cell) {
		var oRecord, nColKeyIndex;
		if(lang.isString(cell.columnKey) && lang.isString(cell.recordId)) {
			oRecord = this.getRecord(cell.recordId);
			var oColumn = this.getColumn(cell.columnKey);
			if(oColumn) nColKeyIndex = oColumn.getKeyIndex();
		}
		if(cell.record && cell.column && cell.column.getKeyIndex) {
			oRecord = cell.record;
			nColKeyIndex = cell.column.getKeyIndex();
		}
		var elRow = this.getTrEl(oRecord);
		if((nColKeyIndex !== null) && elRow && elRow.cells && elRow.cells.length > 0) {
			return elRow.cells[nColKeyIndex] || null;
		}
	}
	return null;
};
YAHOO.widget.DataTable.prototype.newRecord = function() {
	return null;
};
YAHOO.widget.DataTable.prototype.addNewRow = function() {
	this.addRow(this.newRecord());
	this.render();
	return false;
};
YAHOO.widget.DataTable.prototype.deleteSelectedRow = function() {
	var vSelection = this.getSelectedRows();
	if(vSelection) this.deleteRows(this.getRecord(vSelection[0]));
	this.render();
	return false;
};
YAHOO.widget.DataTable.prototype.requery = function(pNewRequest, pCallback) {
	if(pCallback) {
		if(!this.waitPanel) {
			this.waitPanel = new YAHOO.widget.Panel("wait", 
				{ width:"240px", 
				  fixedcenter:true, 
				  close:false, 
				  draggable:false, 
				  zindex:4,
				  modal:true,
				  visible:false
				} 
			);
			this.waitPanel.setHeader("Working, please wait...");
			this.waitPanel.setBody('<img src="http://l.yimg.com/a/i/us/per/gr/gp/rel_interstitial_loading.gif" />');
			this.waitPanel.render(document.body);
		}
		this.waitPanel.show();
	}
	
	if(pCallback) this.getDataSource().sendRequest((!pNewRequest ? this.get('initialRequest') : pNewRequest), pCallback);
	else this.getDataSource().sendRequest((!pNewRequest ? this.get('initialRequest') : pNewRequest), {
		success: this.onDataReturnInitializeTable,
		failure: this.onDataReturnInitializeTable,
		scope: this,
		argument: this.getState()
	});
};
YAHOO.widget.DataTable.prototype.recordSetChanged = function(pOriginals) {
	if(!pOriginals) return true;
	var vSet = this.getRecordSet().getRecords();
	if(vSet.length != pOriginals.length) return true;
	var vFields = this.getDataSource().responseSchema.fields;
	for(var vLoop = 0; vLoop < vSet.length; vLoop++) {
		var vRecord = vSet[vLoop];
		var vOriginal = pOriginals[vLoop];
		for(var vLoop2 = 0; vLoop2 < vFields.length; vLoop2++) {
			var vField = vFields[vLoop2].key;
			var vValue = vRecord.getData(vField);
			var vOriginalValue = vOriginal.getData(vField);
			if(YAHOO.monitus.objectChanged(vOriginalValue, vValue)) return true;
		}
	}
	return false;
};
YAHOO.widget.DataTable.prototype.getRecordLiterals = function() {
	var vRecords = this.getRecordSet().getRecords();
	var vResult = [];
	for(var vLoop = 0; vLoop < vRecords.length; vLoop++) {
		var vRecord = {};
		for(var vProp in vRecords[vLoop]["_oData"]) {
			if(typeof(vRecords[vLoop]["_oData"][vProp]) != "function") vRecord[vProp] = vRecords[vLoop]["_oData"][vProp];
		}
		vResult[vResult.length] = vRecord;
	}
	return vResult;
};
YAHOO.widget.DataTable.prototype.recordSetToJSON = function() {
	return YAHOO.lang.JSON.stringify(this.getRecordSet().getRecords());
};

YAHOO.namespace("monitus");
YAHOO.monitus.AjaxDataTable = function(pContainer , pColumnSet , pDataSource , pConfig, pContext, pValidationCallback, pAjaxURL, pCallback) {
	if(arguments.length > 0) {
		YAHOO.monitus.AjaxDataTable.superclass.constructor.call(this, pContainer , pColumnSet , pDataSource , pConfig);
		
		this.ajaxContext = pContext;
		this.validationCallback = pValidationCallback;
		this.ajaxURL = pAjaxURL;
		this.ajaxCallback = pCallback;
		this.originals = this.getRecordSet().getRecords().clone();
		
		this.subscribe("editorSaveEvent", function(pArgs) {
			var vRecord = pArgs.editor.getRecord();
			var vColumn = pArgs.editor.getColumn().getKey();
			pArgs.editor.getDataTable().ajaxSave(vColumn, vRecord);
		});
	}
};
YAHOO.lang.extend(YAHOO.monitus.AjaxDataTable, YAHOO.widget.DataTable);
YAHOO.monitus.AjaxDataTable.prototype.ajaxSave = function(pColumn, pRecord) {
	var vOriginal = this.getOriginal(pRecord);
	if(!vOriginal || (vOriginal.getData(pColumn) != pRecord.getData(pColumn))) {
		var vOK = true;
		var vData = {context: this.ajaxContext, record: pRecord};
		if(this.validationCallback) vOK = this.validationCallback(pRecord, this.ajaxContext, pColumn);
		
		if(vOK) YAHOO.util.Connect.asyncRequest('GET', this.ajaxURL + "&data=" + encodeURIComponent(YAHOO.lang.JSON.stringify(vData)) + "&x=" + (new Date()).getMilliseconds(), {failure: YAHOO.monitus.ajaxFormResponse, success: YAHOO.monitus.ajaxFormResponse, argument:vData});
	}
};
YAHOO.monitus.AjaxDataTable.prototype.getOriginal = function(pRecord) {
	if(!pRecord) return null;
	for(var vLoop = 0; vLoop < this.originals.length; vLoop++) {
		if(this.originals[vLoop].getId() == pRecord.getId()) return this.originals[vLoop].clone();
	}
	return null;
};

YAHOO.monitus.objectChanged = function(pOriginal, pRevised) {
	if(pOriginal && (typeof(pOriginal) == "object") && pRevised && (typeof(pRevised) == "object")) {
		if((typeof(pOriginal.getTime) == "function") && (typeof(pRevised.getTime) == "function")) return (pOriginal.getTime() != pRevised.getTime());
		for(var vProp in pOriginal) {
			if(typeof(pOriginal[vProp]) == "function") continue;
			else if(typeof(pRevised[vProp]) == "undefined") return true;
			else if((typeof(pRevised[vProp]) == "object") && YAHOO.monitus.objectChanged(pOriginal[vProp], pRevised[vProp])) return true;
			else if(pOriginal[vProp] != pRevised[vProp]) return true;
		}
	} else if(pOriginal != pRevised) return true;
};
YAHOO.monitus.Element = function() { };
YAHOO.monitus.Element.prototype.getTag = function() {
	return this.get('element').tagName.toLowerCase();
};
YAHOO.monitus.Element.prototype.getElementByClassName = function(pClassName, pTag) {
	return this.getElementsByClassName(pClassName, pTag)[0];
};
YAHOO.monitus.Element.prototype.getChildren = function() {
	var vChildren = this.get('element').childNodes();
	for(var vLoop = 0; vLoop < vChildren.length; vLoop++) vChildren[vLoop] = YAHOO.util.Dom.get(vChildren[vLoop]);
	return vChildren;
};
YAHOO.monitus.Element.prototype.insertAfter = function(pElement, pAfter) {
	pElement = pElement.get ? pElement.get('element') : pElement;
	pAfter = (pAfter && pAfter.get) ? pAfter.get('element') : pAfter;
	
	var vSibling = YAHOO.util.Dom.getNextSibling(pAfter);
	if(vSibling) return this.insertBefore(pElement, vSibling);
	 return this.get('element').appendChild(pElement);
};

YAHOO.lang.augmentProto(YAHOO.util.Element, YAHOO.monitus.Element);

YAHOO.monitus.DDRow = function(pID, pTable, pGroup, pConfig) {
	YAHOO.monitus.DDRow.superclass.constructor.call(this, pID, pGroup, pConfig);
	YAHOO.util.Dom.addClass(this.getDragEl(),"dnd");
	
	this._table = pTable;
	this._goingUp = false;
	this._lastY = 0;
	this._proxy = null;
	this._source = null;
	this._data = null;
	this._sourceIndex = null;
	this._index = null;
};
YAHOO.lang.extend(YAHOO.monitus.DDRow, YAHOO.util.DDProxy, {
	startDrag: function(pX, pY) {
		var vProxy = this._proxy = this.getDragEl();
		var vSource = this._source = this.getEl();
		
		this._data = this._table.getRecord(this._source).getData();
		this._sourceIndex = vSource.sectionRowIndex;
		YAHOO.util.Dom.setStyle(vSource, "visibility", "hidden");
		vProxy.innerHTML = "<table><tbody>"+vSource.innerHTML+"</tbody></table>";
	},
	endDrag: function(pX, pY) {
		YAHOO.util.Dom.setStyle(this._proxy, "visibility", "hidden");
		YAHOO.util.Dom.setStyle(this._source, "visibility", "");
		this._table.fireEvent("rowsReorderd");
	},
	onDrag: function(pEvent) {
		var vY = YAHOO.util.Event.getPageY(pEvent);
		
		if(vY < this._lastY) this._goingUp = true;
		else if (vY > this._lastY) this._goingUp = false;
		
		this._lastY = vY;
	},
	onDragOver: function(pEvent, pID) {
		var vDestination = YAHOO.util.Dom.get(pID);
		var vDestinationIndex = vDestination.sectionRowIndex;
		var vIndex = this._index;
		
		if((vDestination.nodeName.toLowerCase() === "tr") && !YAHOO.util.Dom.hasClass(vDestination, "nodnd")) {
			if(vIndex !== null) this._table.deleteRow(vIndex);
			else this._table.deleteRow(this._sourceIndex);
			
			this._table.addRow(this._data, vDestinationIndex);
			this._index = vDestinationIndex;
			
			YAHOO.util.DragDropMgr.refreshCache();
		}
	}
});

YAHOO.monitus.ReorderableTable = function(pContainer, pColumns, pDataSource, pConfig) {
	this._drags = {};
	
	pConfig = pConfig || {};
	
	YAHOO.monitus.ReorderableTable.superclass.constructor.call(this, pContainer, pColumns, pDataSource, pConfig);
	
	this.subscribe("initEvent", function() {
		var vRows = this.getTbodyEl().rows;
		
		for(var vLoop = 0; vLoop < vRows.length; vLoop++) {
			var vID = vRows[vLoop].id;
			if(this._drags[vID]) {
				this._drags[vID].unreg();
				delete this._drags[vID];
			}
			this._drags[vID] = new YAHOO.monitus.DDRow(vID, this, "", {invalidHandleClasses: ["nodnd"]});
		}
	});
	this.subscribe("rowAddEvent",function(pEvent){
		var vID = pEvent.record.getId();
		this._drags[vID] = new YAHOO.monitus.DDRow(vID, this, "", {invalidHandleClasses: ["nodnd"]});
	});
};
YAHOO.monitus.ReorderableTable._DEFAULT_CONFIG = YAHOO.widget.DataTable._DEFAULT_CONFIG;

YAHOO.lang.extend(YAHOO.monitus.ReorderableTable, YAHOO.widget.DataTable, {
});

YAHOO.monitus.Wizard = function(pContainer, pConfig) {
	this._baseTitle = "";
	this._currentPage = 0;
	this.pages = [];
	
	pConfig = pConfig || {};
	pConfig.close = true;
	pConfig.modal = true;
	if(pConfig.page) this._currentPage = pConfig.page;
	var vDelegate = pConfig.delegate || this;
	this._previousPage = vDelegate.previousPage || function(pCurrentPage){ return (pCurrentPage > 0) ? (pCurrentPage - 1) : 0; };
	this._nextPage = vDelegate.nextPage || function(pCurrentPage){ return (pCurrentPage < (this.pages.length - 1)) ? (pCurrentPage + 1) : null; };
	this._validatePage = vDelegate.validatePage || function(pCurrentPage, pProposedPage){ return true; };
	this._saveAction = vDelegate.saveAction || function(pCurrentPage){ return null; };
	
	this._setupButtons(pConfig);
	
	YAHOO.monitus.Wizard.superclass.constructor.call(this, pContainer, pConfig);
	
	this._baseTitle = this.header.innerHTML;
	
	// <dl><dt>...</dt><dd>...</dd>...</dl>
	var vPages = this.element.getElementsByTagName("dl");
	if(vPages && (vPages.length > 0)) {
		var vPages = YAHOO.util.Dom.getChildren(vPages[0]);
		if(vPages) {
			for(var vLoop = 0; vLoop < vPages.length; vLoop += 2) {
				var vPage = {title: vPages[vLoop].innerHTML, page: vPages[vLoop + 1]};
				YAHOO.util.Dom.setStyle(vPages[vLoop], "display", "none");
				YAHOO.util.Dom.setStyle(vPage.page, "display", "none");
				this.pages[this.pages.length] = vPage;
			}
		}
	}
	
	this.goToPage(this._currentPage, true);
};
YAHOO.monitus.Wizard._DEFAULT_CONFIG = YAHOO.widget.Dialog._DEFAULT_CONFIG;

YAHOO.lang.extend(YAHOO.monitus.Wizard, YAHOO.widget.Dialog, {
	_goBack: function() {
		this.goToPage(this._previousPage, true); // let the user go back without validation...
	},
	_goNext: function() {
		this.goToPage(this._nextPage);
	},
	_save: function() {
		if(this._saveAction(this._currentPage)()) this.hide();
	},
	_showPage: function(pPage) {
		if((pPage >= 0) && (pPage < this.pages.length)) {
			this._currentPage = pPage;
			
			this.header.innerHTML = this._baseTitle;
			if(this.header.innerHTML != "") this.header.innerHTML += " - ";
			this.header.innerHTML += this.pages[this._currentPage].title;
			
			YAHOO.util.Dom.setStyle(this.pages[this._currentPage].page, "display", "block");
		}
	},
	_hidePage: function(pPage) {
		if((pPage >= 0) && (pPage < this.pages.length)) {
			this.header.innerHTML = this._baseTitle;
			
			YAHOO.util.Dom.setStyle(this.pages[this._currentPage].page, "display", "none");
			
			this._currentPage = -1;
		}
	},
	_setupButtons: function(pConfig) {
		var vButtons = [];
		vButtons[vButtons.length] = { text: "Cancel", handler: this.hide };
		if(this._saveAction(this._currentPage)) vButtons[vButtons.length] = { text: "Save", handler: this._save };
		var vPage = this._previousPage(this._currentPage);
		if(vPage >= 0) vButtons[vButtons.length] = { text: "Back", handler: this._goBack };
		vPage = this._nextPage(this._currentPage);
		vButtons[vButtons.length] = { text: ((vPage == null) ? "Finish" : "Next"), handler: this._goNext, isDefault: true };
		if(pConfig) pConfig.buttons = vButtons;
		else this.cfg.setProperty("buttons", vButtons);
	},
	
	goToPage: function(pPageOrFunction, pForced) {
		var vProposedPage = pPageOrFunction;
		if(typeof(vProposedPage) == "function") vProposedPage = vProposedPage(this._currentPage);
		if(pForced || this._validatePage(this._currentPage, vProposedPage)) {
			if(typeof(pPageOrFunction) == "function") pPageOrFunction = pPageOrFunction(this._currentPage);
			if(pPageOrFunction == null) this.hide();
			else if((pPageOrFunction >= 0) && (pPageOrFunction < this.pages.length)) {
				this._hidePage(this._currentPage);
				this._showPage(pPageOrFunction);
				this._setupButtons();
			}
		}
	}
});

YAHOO.monitus.page_init = new Array();
YAHOO.monitus.page_validator = null;

YAHOO.monitus.se_query_strings = new Array();
YAHOO.monitus.se_query_strings["google"] = "http://www.google.com/search?hl=en&q=site%3A%s%+%q%&pws=0";
YAHOO.monitus.se_query_strings["yahoo"] = "http://search.yahoo.com/search?p=site%3A%s%+%q%";
YAHOO.monitus.se_query_strings["msn"] = "http://search.msn.com/results.aspx?q=site%3A%s%+%q%";

YAHOO.monitus.mprintf = function(pString, pData) {
	for(var vKey in pData) pString = pString.replace(new RegExp("%" + vKey + "%", "g"), pData[vKey]);
	return pString;
};

YAHOO.monitus.radioSelectedValue = function(pRadio) {
	for(var vLoop = 0; vLoop < pRadio.length; vLoop++) {
		if(pRadio[vLoop].checked) return pRadio[vLoop].value;
	}
	return null;
};

YAHOO.monitus.site_search_url = function(pSearchEngine, pSite, pQuery) {
	if(!MONITUS.se_query_strings[pSearchEngine]) return "";
	
	var vURL = MONITUS.se_query_strings[pSearchEngine].replace(/%s%/g, encodeURIComponent(pSite));
	vURL = vURL.replace(/%q%/g, encodeURIComponent(pQuery).replace(/%20/g, '+'));
	
	return vURL;
};

YAHOO.monitus.date_string_to_date = function(pDateString) {
	var vTokens = pDateString.match(/(\d{2,4})[-\s\/\.](\d{1,2})[-\s\/\.](\d{1,2})/);
	
	if(vTokens) {
		for(var vLoop = 1; vLoop < vTokens.length; vLoop++) vTokens[vLoop] = (vTokens[vLoop] * 1);
		if(vTokens[1] < 100) vTokens[1] += ((vTokens[1] < 70)?2000:1900);
		
		try {
			return new Date(vTokens[1], vTokens[2] - 1, vTokens[3], 0, 0, 0, 0);
		} catch (e) { }
	}
	return null;
};
YAHOO.monitus.date_format = function(pDate, pFormat) {
	if(!pDate || (pDate.getTime() <= 0)) return '-';
	if(!pFormat) pFormat = 'YYYY-MM-DD';
	
	var vYear = parseInt(pDate.getFullYear());
	var vMonth = parseInt(pDate.getMonth()) + 1;
	if(vMonth < 10) vMonth = '0' + vMonth;
	var vDay = parseInt(pDate.getDate());
	if(vDay < 10) vDay = '0' + vDay;
		
	var vResult = pFormat.replace(/YYYY/, vYear);
	vResult = vResult.replace(/YY/, (vYear - 2000));
	vResult = vResult.replace(/MM/, vMonth);
	vResult = vResult.replace(/DD/, vDay);
	return vResult;
};
YAHOO.monitus.number_format = function(pNumber, pDecimals, pForceSign) {
	var vNumberString = '' + pNumber;
	vNumberString = vNumberString.replace(/^\-/, '');
	var vTokens = vNumberString.split('.');
	var vUnits = vTokens[0];
	var vDecimals = "";
	if(vTokens.length <= 1) vTokens[1] = '';
	if(pDecimals != null) {
		if(vTokens[1].length >= pDecimals) vTokens[1] = vTokens[1].substr(0, pDecimals);
		else {
			var vDelta = pDecimals - vTokens[1].length;
			for(var vLoop = 0; vLoop < vDelta; vLoop++) vTokens[1] += '0';
		}
	}
	if(vTokens[1] != "") vDecimals = '.' + vTokens[1];
	var vRE = /(\d+)(\d{3})/;
	while(vRE.test(vUnits)) vUnits = vUnits.replace(vRE, '$1' + ',' + '$2');
	
	var vPrefix = ((pNumber < 0) ? "-" : (pForceSign ? "+" : ""));
	return vPrefix + vUnits + vDecimals;
};
YAHOO.monitus.ordinal_number_format = function(pNumber) {
	var vNumber = YAHOO.monitus.number_format(pNumber, 0, false);
	var vSuffixes = ["th","st","nd","rd"];
	var vValue = (vNumber % 100);
	return vNumber + (vSuffixes[(vValue - 20) % 10] || vSuffixes[vValue] || vSuffixes[0]);
};

YAHOO.monitus.emptycell_formatter = function(pCell, pRecord, pColumn, pData) {
	pCell.innerHTML = "";
};
YAHOO.monitus.string_formatter = function(pCell, pRecord, pColumn, pData) {
	var vEmptyValue = pRecord.getData("emptyStringValue");
	if(!vEmptyValue) vEmptyValue = "";
	pCell.innerHTML = ((pData == "") ? vEmptyValue : pData);
};
YAHOO.monitus.date_formatter = function(pCell, pRecord, pColumn, pData) {
	pCell.innerHTML = YAHOO.monitus.date_format(pData);
};
YAHOO.monitus.number_formatter = function(pCell, pRecord, pColumn, pData) {
	pCell.innerHTML = YAHOO.monitus.number_format(parseFloat(pData), 2);
};
YAHOO.monitus.amount_formatter = function(pCell, pRecord, pColumn, pData) {
	pCell.innerHTML = "$"  + YAHOO.monitus.number_format(parseFloat(pData), 2);
};
YAHOO.monitus.percent_formatter = function(pCell, pRecord, pColumn, pData) {
	pCell.innerHTML = pData + "%";
};
YAHOO.monitus.multiDays_formatter = function(pCell, pRecord, pColumn, pData) {
	var vValue = '';
	for(var vLoop = 0; vLoop < pData.length; vLoop++) {
		var vDay = parseInt(pData[vLoop]);
		switch(vDay) {
			case 6:
				vDay = 'Sat';
				break;
			case 5:
				vDay = 'Fri';
				break;
			case 4:
				vDay = 'Thu';
				break;
			case 3:
				vDay = 'Wed';
				break;
			case 2:
				vDay = 'Tue';
				break;
			case 1:
				vDay = 'Mon';
				break;
			default:
				vDay = 'Sun';
				break;
		}
		vValue += ((vValue == "") ? "" : " ") + vDay;
	}
	pCell.innerHTML = vValue;
};
YAHOO.monitus.description_formatter = function(pCell, pRecord, pColumn, pData) {
	pCell.innerHTML = "<span style='font-size: small; color: #666666;'>"  + pData + "</span>";
};

YAHOO.monitus.strict_positive_number_validate = function(pData) {
	var vNumber = pData * 1;
	if(YAHOO.lang.isNumber(vNumber) && (vNumber > 0)) return vNumber;
	else {
		YAHOO.log("Could not validate data " + YAHOO.lang.dump(pData) + " to type Number", "warn", "");
		return null;
	}
};
YAHOO.monitus.positive_number_validate = function(pData) {
	var vNumber = pData * 1;
	if(YAHOO.lang.isNumber(vNumber) && (vNumber >= 0)) return vNumber;
	else {
		YAHOO.log("Could not validate data " + YAHOO.lang.dump(pData) + " to type Number", "warn", "");
		return null;
	}
};
YAHOO.monitus.day_selection_validate = function(pData) {
	if(!pData || (pData.length == 0)) {
		alert("Pleaase select at least one day");
		return undefined;
	} else return pData;
};

YAHOO.monitus.table_button_clicked = function(oArgs) {
	YAHOO.util.Event.stopEvent(oArgs.event);
	var vAnchor = oArgs.target;
	var vRecord = this.getRecord(vAnchor);
	var vAction = vAnchor.hash.substr(1);
	if(typeof(this.button_clicked) == "function") this.button_clicked(vRecord, vAction);
};

YAHOO.monitus.clean_up_url = function(pValue) {
	var vResult = pValue.replace(/^(?:https?\:\/\/)?([^\/]+(?:\/.*)?)$/i, "$1");
	var vDomain = pValue.replace(/^(?:https?\:\/\/)?([^\/]+)(?:\/.*)?$/i, "$1");
	var vTokens = vDomain.split(".");
	if(vTokens.length < 3) vResult = "www." + vResult;
	return vResult;
};
YAHOO.monitus.lastNdays = function(pDays, pFromPicker, pToPicker) {
		var vDate = new Date();
		pToPicker.setDate(vDate);
		vDate.setHours(vDate.getHours() - (24 * pDays));
		pFromPicker.setDate(vDate);
		return false;
};

YAHOO.monitus.set_field_status = function(pStatusBarId, pMode, pStatus) {
	// pMode = -1 (error), 0 (waiting) or 1 (valid)
	var vStatusField = YAHOO.util.Dom.get(pStatusBarId);
	vStatusField.innerHTML = pStatus;
	YAHOO.util.Dom.setStyle(vStatusField, "display", (pStatus ? "block" : "none"));
	YAHOO.util.Dom.setStyle(vStatusField, "color", ((pMode == 0) ? "#999999" : ((pMode < 0) ? "red" : "green")));
};

YAHOO.monitus.set_module_title = function(pModule, pTitle) {
	var vObject= YAHOO.util.Dom.get(pModule);
	if(pModule) pModule.innerHTML = pTitle;
};

YAHOO.monitus.goToRegistration = function() {
        YAHOO.monitus.login_popup.hide();
        //YAHOO.monitus.register_popup.show();
        document.location = "/index.php/register.html";
        return false;
};

YAHOO.monitus.ProgressIndicator = function(element, imageBaseURL, ghostElement) {
	this.count = 0;
	this.timer = null;
	this.element = element;
	this.element.style.display = "none";
	this.imageBaseURL = imageBaseURL;
	this.ghostElement = ghostElement;
};
YAHOO.monitus.ProgressIndicator.prototype = {
	start: function () {
		if(this.ghostElement) this.ghostElement.style.opacity = 0.5;
		this.element.style.display = "block";
		if (this.timer) clearInterval(this.timer);
		this.tick();
		var localThis = this;
		this.timer = setInterval(function() { localThis.tick() }, 100);
	},
	stop: function () {
		clearInterval(this.timer);
		this.element.style.display = "none";
		if(this.ghostElement) this.ghostElement.style.opacity = 1.0;
	},
	tick: function () {
		var imageURL = this.imageBaseURL + (this.count + 1) + ".png";
		this.element.src = imageURL;
		this.count = (this.count + 1) % 12;
	}
};

YAHOO.monitus.SmoothScroll = function() {
	var vBody = YAHOO.util.Dom.get(document.getElementsByTagName('body')[0]);
	var vLinks = vBody.getElementsByTagName("a");
	for(var vLoop = 0; vLoop < vLinks.length; vLoop++) {
		if(vLinks[vLoop].href.indexOf("#") < 0) { return; }
		var vAnchor = vLinks[vLoop].href.replace(/^[^#]*#/, "");
		if(vAnchor) this.setupLink(vLinks[vLoop], YAHOO.util.Dom.getElementBy(function(pAnchor) {
			if((pAnchor.id == vAnchor) || (pAnchor.name == vAnchor)) return true;
			return false;
		}, "a"));
	}
};
YAHOO.monitus.SmoothScroll.prototype.setupLink = function(pLink, pTargetAnchor) {
	YAHOO.util.Event.addListener(pLink, "click", function(pEvent) {
		if(pTargetAnchor) {
			YAHOO.util.Event.preventDefault(pEvent);
			var y = YAHOO.util.Dom.getY(pTargetAnchor);
			var vScroll = new YAHOO.util.Scroll(YAHOO.util.Dom.get(document.getElementsByTagName('body')[0]), {scroll: { to: [0, y] }}, 0.35);
			vScroll.animate();
			pLink.blur();
		}
	});
};

YAHOO.monitus.accordionViewInit = function(pAccordionView) {
	var vObjects = YAHOO.util.Dom.getElementsByClassName("mjoomla_panel_title", "span");
	if(vObjects && (vObjects.length > 0)) {
		for(var vLoop = 0; vLoop < vObjects.length; vLoop++) {
			var vLink = YAHOO.util.Dom.getAncestorByClassName(vObjects[vLoop], "yui-accordion-toggle");
			if(vLink) {
				vObjects[vLoop].accordionView = pAccordionView;
				YAHOO.util.Event.addListener(vObjects[vLoop], "click", function(){this.accordionView._onClick(YAHOO.util.Dom.getAncestorByClassName(this, "yui-accordion-toggle"));});
			}
		}
	}
};

YAHOO.monitus.Editor = function(p_container, p_config) {
	this.html_mode = false;
	this.js_editor = null;
	
	var vExtraCSS = '.monitus-token, .monitus-if { font-family: sans-serif; font-size: 12px; font-weight: bold; padding: 0px 2px; color: white; margin: 0px 3px; }';
	vExtraCSS += '.monitus-token { background-color: #0080ff; }';
	vExtraCSS += '.monitus-if { background-color: #ff8000; text-transform: uppercase; }';
	vExtraCSS += '.monitus-js { background: url(/images/tools/script_code_red.png) 0px 0px no-repeat; height: 16px; width: 16px; margin: 0px 2px; }';
	
	p_config = p_config || {};
	p_config.allowNoEdit = true;
	p_config.extracss = vExtraCSS;
	p_config.toolbar = {
		collapse: true,
		titlebar: 'Editing Tools',
		draggable: false,
		buttonType: 'advanced',
		buttons: [
			{ group: 'fontstyle', label: 'Font Name and Size',
				buttons: [
					{ type: 'select', label: 'Arial', value: 'fontname', disabled: true,
						menu: [
							{ text: 'Arial', checked: true },
							{ text: 'Arial Black' },
							{ text: 'Comic Sans MS' },
							{ text: 'Courier New' },
							{ text: 'Lucida Console' },
							{ text: 'Tahoma' },
							{ text: 'Times New Roman' },
							{ text: 'Trebuchet MS' },
							{ text: 'Verdana' }
						]
					},
					{ type: 'spin', label: '13', value: 'fontsize', range: [ 9, 75 ], disabled: true }
				]
			},
			{ type: 'separator' },
			{ group: 'textstyle', label: 'Font Style',
				buttons: [
					{ type: 'push', label: 'Bold CTRL + SHIFT + B', value: 'bold' },
					{ type: 'push', label: 'Italic CTRL + SHIFT + I', value: 'italic' },
					{ type: 'push', label: 'Underline CTRL + SHIFT + U', value: 'underline' },
					{ type: 'separator' },
					{ type: 'push', label: 'Subscript', value: 'subscript', disabled: true },
					{ type: 'push', label: 'Superscript', value: 'superscript', disabled: true },
					{ type: 'separator' },
					{ type: 'color', label: 'Font Color', value: 'forecolor', disabled: true },
					{ type: 'color', label: 'Background Color', value: 'backcolor', disabled: true },
					{ type: 'separator' },
					{type: 'push', label: 'Edit HTML Code', value: 'editcode'}
				]
			},
			{ type: 'separator' },
			{ group: 'alignment', label: 'Alignment',
				buttons: [
					{ type: 'push', label: 'Align Left CTRL + SHIFT + [', value: 'justifyleft' },
					{ type: 'push', label: 'Align Center CTRL + SHIFT + |', value: 'justifycenter' },
					{ type: 'push', label: 'Align Right CTRL + SHIFT + ]', value: 'justifyright' },
					{ type: 'push', label: 'Justify', value: 'justifyfull' }
				]
			},
			{ type: 'separator' },
			{ group: 'indentlist', label: 'Indenting, Lists',
				buttons: [
					{ type: 'push', label: 'Indent', value: 'indent', disabled: true },
					{ type: 'push', label: 'Outdent', value: 'outdent', disabled: true },
					{ type: 'push', label: 'Create an Unordered List', value: 'insertunorderedlist' },
					{ type: 'push', label: 'Create an Ordered List', value: 'insertorderedlist' }
				]
			},
			{ type: 'separator' },
			{ group: 'insertitem', label: 'Insert Item',
				buttons: [
					{ type: 'push', label: 'HTML Link CTRL + SHIFT + L', value: 'createlink', disabled: true },
					{ type: 'push', label: 'Insert Image', value: 'insertimage' },
					{ type: 'push', label: 'Insert Javascript Snippet', value: 'insertscript' }
				]
			},
			{ type: 'separator' },
			{ group: 'monitusItem', label: 'Monitus tokens',
				buttons: []
			}
		]
	};
	
	YAHOO.monitus.Editor.superclass.constructor.call(this, p_container, p_config);
	
	this.on('afterNodeChange', function() {
		if(this._hasSelection()) {
			this.toolbar.disableButton('insertmontoken');
			this.toolbar.disableButton('insertscript');
		} else {
			this.toolbar.enableButton('insertmontoken');
			this.toolbar.enableButton('insertscript');
			var vElement = this._getSelectedElement();
			if(YAHOO.util.Dom.hasClass(vElement, YAHOO.monitus.Editor.JS_CLASS)) {
				this.toolbar.selectButton('insertscript');
				this.toolbar.deselectButton('insertimage');
			} else {
				this.toolbar.deselectButton('insertscript');
			}
		}
	}, this, true);
	
	this.on('windowinsertscriptClose', function() {
		this.handleWindowClose.call(this);
		this.js_editor = null;
	}, this, true);
	
	this.on('toolbarLoaded', function() {
		var vThis = this;
		var vTokenConfig = {
			type: 'push', //Using a standard push button
			label: 'Insert Monitus Token', //The name/title of the button
			value: 'insertmontoken', //The "Command" for the button
			menu: function() {
				var vMenu = new YAHOO.widget.Menu("insertmontokenMenu", {
					xy: [-9000,-9000],
					visible: false,
					zindex: 50000
				});
				var fcListToItems = function(pList) { // pList: [{<label>: <object>, ...}, ...]
					var vItems = [];
					for(var vLoop = 0; vLoop < pList.length; vLoop++) {
						var vSection = [];
						for(var vLoop2 in pList[vLoop]) {
							if(typeof(pList[vLoop][vLoop2]) != "function") {
								vSection.push({text: vLoop2, onclick: { fn: vThis.cmd_insertmontoken, obj: {editor: vThis, token: pList[vLoop][vLoop2]} }});
							}
						}
						vItems.push(vSection);
					}
					return vItems;
				};
				vMenu.addItems(fcListToItems(vThis.tokens_list()));
				vMenu.beforeShowEvent.subscribe(function() {
					vMenu.cfg.setProperty('context', [
						this.toolbar.getButtonByValue('insertmontoken').get('element'),
						'tl',
						'bl'
					]);
				}, vThis, true);
				vMenu.render(YAHOO.util.Dom.get("pq_wizard"));
				vMenu.element.style.visibility = 'hidden';
				return vMenu;
			}()
		};
		this.toolbar.addButtonToGroup(vTokenConfig, 'monitusItem');
		
		this.toolbar.on('editcodeClick', function() {
			var vTextArea = this.get('element');
			var vFrame = this.get('iframe').get('element');
			
			if(this.html_mode) {
				this.html_mode = false;
				this.toolbar.set('disabled', false);
				this.setEditorHTML(vTextArea.value);
				if(!this.browser.ie) this._setDesignMode('on');
				
				YAHOO.util.Dom.removeClass(vFrame, 'editor-hidden');
				YAHOO.util.Dom.addClass(vTextArea, 'editor-hidden');
				this.show();
				this._focusWindow();
			} else {
				this.html_mode = true;
				YAHOO.util.Dom.addClass(vFrame, 'editor-hidden');
				vTextArea.value = this.getEditorHTML();
				YAHOO.util.Dom.removeClass(vTextArea, 'editor-hidden');
				this.toolbar.set('disabled', true);
				this.toolbar.getButtonByValue('editcode').set('disabled', false);
				this.toolbar.selectButton('editcode');
				if(this.dompath) this.dompath.innerHTML = 'Editing HTML Code';
				this.hide();
			}
			return false;
		}, this, true);
		
		this.toolbar.on('insertscriptClick', function() {
			var vElement = this._getSelectedElement();
			if(YAHOO.util.Dom.hasClass(vElement, YAHOO.monitus.Editor.JS_CLASS)) {
				this.currentElement = [vElement];
				this.handleScriptWindow.call(this);
				return false;
			}
		}, this, true);
		
		this.on('cleanHTML', function(ev) {
			this.get('element').value = ev.html;
		}, this, true);
		
		this.on('editorDoubleClick', function() {
			var vElement = this.currentElement[0];
			if(YAHOO.util.Dom.hasClass(vElement, YAHOO.monitus.Editor.JS_CLASS)) {
				this.closeWindow(); // close image window
				this.currentElement = [vElement];
				this.handleScriptWindow.call(this);
				return false;
			}
		}, this, true);
		this.on('afterRender', function() {
			var vWrapper = this.get('editor_wrapper');
			vWrapper.appendChild(this.get('element'));
			this.setStyle('width', '100%');
			this.setStyle('height', '100%');
			this.setStyle('visibility', '');
			this.setStyle('top', '');
			this.setStyle('left', '');
			this.setStyle('position', '');
			
			this.addClass('editor-hidden');
		}, this, true);
	}, this, true);
	
	this.on('windowRender', function() {
		if(!this._windows.insertscript || !this._windows.insertscript.body || (this._windows.insertscript.body == "")) {
			var vBody = document.createElement('div');
			vBody.innerHTML = '<textarea id="monitus-js-snippet" style="position: relative; margin: 0px 5px; height: 70px; width: 400px;"></textarea><br style="clear: both;" />';
			this._windows.insertscript = {
				body: vBody
			};
		}
	});
};
YAHOO.monitus.Editor._DEFAULT_CONFIG = YAHOO.widget.Editor._DEFAULT_CONFIG;
YAHOO.monitus.Editor.TOKEN_CLASS = "monitus-token";
YAHOO.monitus.Editor.IF_CLASS = "monitus-if";
YAHOO.monitus.Editor.JS_CLASS = "monitus-js";

YAHOO.lang.extend(YAHOO.monitus.Editor, YAHOO.widget.Editor, {
	tokens_list: function() {
		return [];
	},
	handleWindowClose: function() {
		var vField = YAHOO.util.Dom.get("monitus-js-snippet");
		if(vField) {
			var vElement = this.currentElement[0];
			if(YAHOO.util.Dom.hasClass(vElement, YAHOO.monitus.Editor.JS_CLASS)) {
				vElement.setAttribute("script", vField.value.replace(/\r?\n/img, "&cr;").replace(/"/img, '&quot;'));
				vField.value = "";
			}
		}
	},
	handleScriptWindow: function() {
		this.js_editor = new YAHOO.widget.EditorWindow('insertscript', {width: '415px'});
		
		this.js_editor.setHeader('Edit Javascript Snippet');
		
		this.on('afterOpenWindow', function() {
			var vField = YAHOO.util.Dom.get("monitus-js-snippet");
			if(vField) {
				var vElement = this.currentElement[0];
				if(vElement && YAHOO.util.Dom.hasClass(vElement, YAHOO.monitus.Editor.JS_CLASS)) {
					vField.value = vElement.getAttribute("script").replace(/&cr;/img, "\n").replace(/&quot;/img, '"');
				} else vField.value = "";
				this.nodeChange();
			}
			this.get('panel').syncIframe();
		}, this, true);
		
		this.openWindow(this.js_editor);
	},
	cmd_insertmontoken: function(pEventType, pEvent, pObject) {
		if(pObject) {
			var vLabel = this.cfg.getProperty("text");
			var vConditional = pObject.token.match(/^\[/i);
			var vBlock = '&nbsp;<span class="' + (vConditional ? YAHOO.monitus.Editor.IF_CLASS : YAHOO.monitus.Editor.TOKEN_CLASS) + ' yui-noedit" token="' + pObject.token + '">' + vLabel + '</span>&nbsp;';
			if(vConditional) {
				vBlock += '&nbsp;<span class="' + YAHOO.monitus.Editor.IF_CLASS + ' yui-noedit" token="]' + pObject.token.substr(1) + '[">ELSE</span>&nbsp;';
				vBlock += '&nbsp;<span class="' + YAHOO.monitus.Editor.IF_CLASS + ' yui-noedit" token="' + pObject.token.substr(1) + ']">END ' + vLabel + '</span>&nbsp;';
			}
			pObject.editor.execCommand('inserthtml', vBlock);
		}
	},
	cmd_insertscript: function() {
		this.execCommand('insertimage', '/images/tools/script_code_red.png');
		this.currentElement[0].className = YAHOO.monitus.Editor.JS_CLASS;
		this.currentElement[0].setAttribute("script", "// script goes here");
		this.handleScriptWindow.call(this);
		
		return false;
	}
});

YAHOO.monitus.IntervalCalendar = function(p_container, p_config) {
	this.propState = 0;
	
	p_config = p_config || {};
	p_config.multi_select = true;
	
	YAHOO.monitus.IntervalCalendar.superclass.constructor.call(this, p_container, p_config);
	
	this.beforeSelectEvent.subscribe(this._on_before_select, this, true);
	this.selectEvent.subscribe(this._on_select, this, true);
	this.beforeDeselectEvent.subscribe(this._on_before_deselect, this, true);
	this.deselectEvent.subscribe(this._on_deselect, this, true);
};
YAHOO.monitus.IntervalCalendar._DEFAULT_CONFIG = YAHOO.widget.CalendarGroup._DEFAULT_CONFIG;

YAHOO.lang.extend(YAHOO.monitus.IntervalCalendar, YAHOO.widget.CalendarGroup, {
	date_string : function(p_date) {
		var v_tokens = [];
		v_tokens[this.cfg.getProperty(YAHOO.monitus.IntervalCalendar._DEFAULT_CONFIG.MDY_MONTH_POSITION.key)-1] = (p_date.getMonth() + 1);
		v_tokens[this.cfg.getProperty(YAHOO.monitus.IntervalCalendar._DEFAULT_CONFIG.MDY_DAY_POSITION.key)-1] = p_date.getDate();
		v_tokens[this.cfg.getProperty(YAHOO.monitus.IntervalCalendar._DEFAULT_CONFIG.MDY_YEAR_POSITION.key)-1] = p_date.getFullYear();
		var v_separator = this.cfg.getProperty(YAHOO.monitus.IntervalCalendar._DEFAULT_CONFIG.DATE_FIELD_DELIMITER.key);
		return v_tokens.join(v_separator);
	},
	date_human_string : function(p_date) {
		var v_tokens = [];
		v_tokens[v_tokens.length] = p_date.getFullYear();
		var v_number = (p_date.getMonth() + 1);
		if(v_number < 10) v_number = "0" + v_number;
		v_tokens[v_tokens.length] = v_number;
		var v_number = p_date.getDate();
		if(v_number < 10) v_number = "0" + v_number;
		v_tokens[v_tokens.length] = v_number;
		var v_separator = "-";
		return v_tokens.join(v_separator);
	},
	interval_string: function(p_from, p_to) {
		var v_separator = this.cfg.getProperty(YAHOO.monitus.IntervalCalendar._DEFAULT_CONFIG.DATE_RANGE_DELIMITER.key);
		return (this.date_string(p_from) + v_separator + this.date_string(p_to));
	},
	interval_human_string: function(p_from, p_to) {
		var v_separator = '-';
		return (this.date_human_string(p_from) + " to " + this.date_human_string(p_to));
	},
	get_interval : function() {
		var v_dates = this.getSelectedDates();
		if(v_dates.length > 0) {
			var v_from = v_dates[0];
			var v_to = v_dates[v_dates.length - 1];
			return [v_from, v_to];
		}
		return [];
	},
	set_interval : function(p_date1, p_date2) {
		var v_ordered = (p_date1 <= p_date2);
		var v_from = v_ordered ? p_date1 : p_date2;
		var v_to = v_ordered ? p_date2 : p_date1;
		this.cfg.setProperty('selected', this.interval_string(v_from, v_to), false);
		this.propState = 2;
	},
	reset_interval : function() {
		this.cfg.setProperty('selected', [], false);
		this.propState = 0;
	},
	_on_before_select : function(t,a,o) {
		this.propState = (this.propState + 1) % 3;
		if(this.propState == 0) {
			this.deselectAll();
			this.propState++;
		}
	},
	_on_select : function(t,a,o) {
		var v_dates = this.getSelectedDates();
		if(v_dates.length > 1) {
			var v_from = v_dates[0];
			var v_to = v_dates[v_dates.length - 1];
			this.cfg.setProperty('selected', this.interval_string(v_from, v_to), false);
		}
		this.render();
	},
	_on_before_deselect : function(t,a,o) {
		if(this.propState != 0) return false;
	},
	_on_deselect : function(t,a,o) {
		if(this.propState == 1) {
			this.propState = 0;
			this.deselectAll();
			var v_date_array = a[0][0];
			var v_date = YAHOO.widget.DateMath.getDate(v_date_array[0], v_date_array[1] - 1, v_date_array[2]);
			var v_page = this.getCalendarPage(v_date);
			if(v_page) {
				v_page.beforeSelectEvent.fire();
				this.cfg.setProperty('selected', this.date_string(v_date), false);
				v_page.selectEvent.fire([v_date_array]);
			}
			 return false;
		}
	}
});

YAHOO.monitus.DatePicker = function(buttonContainerID, fieldID, selectedDate, minDate, maxDate,wTime) {
	this.field = YAHOO.util.Dom.get(fieldID);
	this.menu = new YAHOO.widget.Overlay(fieldID + "Calendar", { visible: false, zIndex: 100 });
	this.button = new YAHOO.widget.Button({ type: "menu", id:fieldID + "DatePicker", label:selectedDate, menu:this.menu, container:buttonContainerID});
	this.saveTime = wTime;
	
	var vThis = this;
	this.button.on("appendTo", function () {
		vThis.menu.setBody(" ");
		vThis.menu.body.id = fieldID + "CalContainer";
		vThis.menu.render(vThis.button.get("container"));
	}, this, true);
	
	this.onButtonClick = function() {
		var vCalendar = new YAHOO.widget.Calendar("buttoncalendar", vThis.menu.body.id, {pagedate: vThis.button.get("label").replace(/(\d+)\/\d+(\/\d+)/, "$1$2"), minDate: minDate, maxdate: maxDate});
		vCalendar.render();
		vCalendar.changePageEvent.subscribe(function() {
			window.setTimeout(function() {
				vThis.menu.show();
			}, 0);
		}, vThis, true);
		vCalendar.selectEvent.subscribe(function(p_sType, p_aArgs) {
			if(p_aArgs) {
				var aDate = p_aArgs[0][0];
				var nMonth = aDate[1];
				var nDay = aDate[2];
				var nYear = aDate[0];
				vThis.setDate(new Date(nYear, (nMonth - 1), nDay));
				//vThis.button.set("label", (nMonth + "/" + nDay + "/" + nYear));
				//vThis.field.value = (nYear + "/" + nMonth + "/" + nDay);
			}
			if(typeof(vThis.valueSelectedCallback) == "function") vThis.valueSelectedCallback(vThis.field);
			vThis.menu.hide();
		}, vThis, true);
		vThis.unsubscribe("click", vThis.onButtonClick);
	};
	this.button.on("click", this.onButtonClick);
};
YAHOO.monitus.DatePicker.prototype.setDate = function(pDate) {
	this.button.set("label", ((pDate.getMonth() + 1) + "/" + pDate.getDate() + "/" + pDate.getFullYear()));
	this.field.value = (pDate.getFullYear() + "/" + (parseInt(pDate.getMonth()) + 1) + "/" + pDate.getDate() );
	if(this.saveTime) {
		var vCurrentDate = new Date();
		this.field.value += " " + vCurrentDate.getHours() + ":" + vCurrentDate.getMinutes() + ":" + vCurrentDate.getSeconds();
	}
};

YAHOO.monitus.videoHelpPane = function(pTargetID, pOverlayTitle, pVideoPath, pWidth, pHeight, pBgColor) {
	var vTarget = YAHOO.util.Dom.get(pTargetID);
	if(vTarget) {
		if(!pOverlayTitle) pOverlayTitle = "Monitus Help";
		vTarget.vidOverlay = new YAHOO.widget.Panel("vidHelp_vid" + pTargetID, 
				{ width: parseInt(pWidth) + 20 + "px", 
				  fixedcenter:true, 
				  close:true, 
				  draggable:true, 
				  zindex:10000000,
				  modal:false,
				  visible:false,
				  effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.25}
				}
		);
		vTarget.vidOverlay.setHeader(pOverlayTitle);
		vTarget.vidOverlay.setBody('<div id="vidHelp_media' + pTargetID +'"></div>');
		var vID = "vidHelp_cws" + pTargetID;
		vTarget.vidOverlay.beforeShowEvent.subscribe(function() {
			if(!pVideoPath.match(/^http/i)) pVideoPath = "http://site.rtml-training.com/screencasts/" + pVideoPath;
			this.swf = new SWFObject(pVideoPath, vID, pWidth, pHeight, "9.0.28", pBgColor);
			this.swf.addParam("quality", "best");
			this.swf.addParam("allowFullScreen", "true");
			this.swf.addParam("scale", "showall");
			this.swf.addParam("allowScriptAccess", "always");
			this.swf.addParam("autostart", "false");
			if(typeof(YAHOO.monitus.videoHelpCustom) == "function") YAHOO.monitus.videoHelpCustom(pTargetID, this.swf);
			this.swf.write("vidHelp_media" + pTargetID);
		});
		vTarget.vidOverlay.beforeHideEvent.subscribe(function() {
			var vObject = document.getElementById(vID);
			if(vObject) {
				vObject.parentNode.removeChild(vObject);
			}
		});
		vTarget.vidOverlay.render(document.body);
	}
};
// pButtons div should be of class "mjoomla_video_help"
YAHOO.monitus.videoHelpButton = function(pButtonID, pOverlayTitle, pVideoPath, pWidth, pHeight, pBgColor) {
	var vButton = new YAHOO.widget.Button({title: "View a screencast", id:"vidHlp_" + pButtonID, container: pButtonID });
	YAHOO.monitus.videoHelpPane(pButtonID, pOverlayTitle, pVideoPath, pWidth, pHeight, pBgColor);
	vButton.on("click", function() {
		this.vidOverlay.show();
	});
	return vButton;
};

YAHOO.monitus.ajaxObjectToData = function(pObject, pData) {
	if(!pObject) return;
	var vIndex = (((typeof(pObject.id) == "undefined") || (pObject.id == "")) ? pObject.name : pObject.id);
	if((typeof(pObject.type) != "undefined") && (pObject.type == "checkbox")) pData[vIndex] = (pObject.checked ? 1 : 0);
	else pData[vIndex] = pObject.value;
};
YAHOO.monitus.ajaxFormResponse = function(pConnection) {
	if(pConnection.status > 0) { // 0 is when we move away from the page before ajax returns...
		var vOK = false;
		if(pConnection.status == 200) {
			var vResponse = null;
			try { vResponse = eval("(" + pConnection.responseText + ")"); } catch(e) { }
			
			if(!vResponse) alert("ERROR: " + pConnection.responseText + " (2)");
			else {
				if(vResponse.error != "") alert("ERROR: " + vResponse.error + " (3)");
				else vOK = true;
			}
		} else alert("ERROR: " + pConnection.status + "(1)");
		if(pConnection.argument) {
			if(typeof(pConnection.argument.context) != "undefined") {
				var vTable = YAHOO.monitus[pConnection.argument.context];
				if(vTable) {
					if(!vOK) {
						var vOriginal = vTable.getOriginal(pConnection.argument.record);
						vTable.updateRow(pConnection.argument.record, vOriginal);
					}
					if(vTable.ajaxCallback) vTable.ajaxCallback(vOK, pConnection.argument.record, pConnection.argument.context);
					vTable.render();
				}
			} else {
				if(!vOK) pConnection.argument.value = pConnection.argument._mon_old_value;
				if(pConnection.argument.form._mon_ajaxCalback) pConnection.argument.form._mon_ajaxCalback(vOK, pConnection.argument);
			}
		}
	}
};
YAHOO.monitus.ajaxFormSave = function(pObject) {
	if((typeof(pObject._mon_old_value) == "undefined") || (pObject.value != pObject._mon_old_value) || (pObject._mon_old_value == "_null_")) {
		var vData = null;
		if(pObject.form._mon_validationCallback) vData = pObject.form._mon_validationCallback(pObject);
		else {
			vData = {};
			YAHOO.monitus.ajaxObjectToData(pObject, vData);
		}
		
		if(vData) YAHOO.util.Connect.asyncRequest('GET', pObject.form._mon_ajaxURL + "&data=" + encodeURIComponent(YAHOO.lang.JSON.stringify(vData)) + "&x=" + (new Date()).getMilliseconds(), {failure: YAHOO.monitus.ajaxFormResponse, success: YAHOO.monitus.ajaxFormResponse, argument:pObject});
	}
};
YAHOO.monitus.ajaxFormInit = function(pForm, pValidationCallback, pAjaxURL, pCallback) {
	if(typeof(pForm) == "string") pForm = YAHOO.util.Dom.get(pForm);
	if(pForm) {
		pForm._mon_validationCallback = pValidationCallback;
		pForm._mon_ajaxURL = pAjaxURL;
		pForm._mon_ajaxCalback = pCallback;
		
		var vObject = null;
		var vEvent = "";
		
		// input fields: text, hidden(?), radios, checkboxes
		var vObjects = pForm.getElementsByTagName("input");
		for(var vLoop = 0; vLoop < vObjects.length; vLoop++) {
			vObject = vObjects[vLoop];
			vObject._mon_old_value = ((vObject.type == "checkbox") ? "_null_" : vObject.value);
			
			vEvent = "blur";
			if((vObject.type == "checkbox") || (vObject.type == "radio")) vEvent = "click";
			YAHOO.util.Event.addListener(vObject, vEvent, function() { YAHOO.monitus.ajaxFormSave(this); });
		}
		// textareaas
		var vObjects = pForm.getElementsByTagName("textarea");
		for(var vLoop = 0; vLoop < vObjects.length; vLoop++) {
			vObject = vObjects[vLoop];
			vObject._mon_old_value = vObject.value;
			
			YAHOO.util.Event.addListener(vObject, "blur", function() { YAHOO.monitus.ajaxFormSave(this); });
		}
		
		// select menus
		var vObjects = pForm.getElementsByTagName("select");
		for(var vLoop = 0; vLoop < vObjects.length; vLoop++) {
			vObject = vObjects[vLoop];
			vObject._mon_old_value = vObject.value;
			
			YAHOO.util.Event.addListener(vObject, "change", function() { YAHOO.monitus.ajaxFormSave(this); });
		}
	}
};

YAHOO.monitus.init = function() {
	if(YAHOO.env.ua.ie == 0) {
		// SmoothScrolling
		new YAHOO.monitus.SmoothScroll();
	}
	
	// make tooltips automatically
	var vLinks = YAHOO.util.Dom.getElementsByClassName("mjoomla_tooltip", "a", document);
	for(var vLoop = 0; vLoop < vLinks.length; vLoop++) {
		new YAHOO.widget.Tooltip("tip_" + vLinks[vLoop].id, {context: vLinks[vLoop].id});
	}
	
	// adjust forms and pagination links
	var vCurrentLocation = document.location.pathname;
	if(document.location.hash && (document.location.hash != "")) vCurrentLocation += "#" + document.location.hash;
	var vPagination = YAHOO.util.Dom.getElementsByClassName("pagination", "ul", document);
	for(var vLoop = 0; vLoop < vPagination.length; vLoop++) {
		vLinks = vPagination[vLoop].getElementsByTagName("a");
		for(var vLoop2 = 0; vLoop2 < vLinks.length; vLoop2++) vLinks[vLoop2].href = vLinks[vLoop2].href.replace(/^.+\?/i, vCurrentLocation + "?");
	}
	if(document.location.search && (document.location.search != "")) vCurrentLocation += document.location.search;
	var vForms = YAHOO.util.Dom.getElementsByClassName("adminForm", "form", document);
	for(var vLoop = 0; vLoop < vForms.length; vLoop++) vForms[vLoop].action = vCurrentLocation;
	
	// catch the referrer
	var vTokens = document.location.search.match(/ref\=([^&]+)/);
	var vReferer = (vTokens ? vTokens[1] : null);
	if(vReferer)
		YAHOO.util.Cookie.set("m_ref", vReferer, {expires: new Date((new Date()).getTime() + (7 * 24 * 3600000))});
	else
		vReferer = YAHOO.util.Cookie.get("m_ref");
	
	var vField = YAHOO.util.Dom.get("referer");
	if(vField)
		vField.value = vReferer;
	
	for(var vLoop = 0; vLoop < YAHOO.monitus.page_init.length; vLoop++) YAHOO.monitus.page_init[vLoop]();
	
	if(document.location.search.match(/(\?|\&)reg\=1(\&|$)/i)) YAHOO.monitus.register_popup.makeKeyResponder();
};

YAHOO.util.Event.addListener(window, "load", YAHOO.monitus.init);
