var RM_Vars =
{
	headTable  : null,
	bodyTable  : null,
	bodyDiv : null,
	headDiv : null,
	outerDiv : null,
	rowToUpdate : null,
	rmObj : null,
	originalSelects : null,
	filters : null
};

var Dialogs =
{
	warning : null,
	emailRecipient : null,
	confirmDelete : null,
	confirmRevert : null,
	templateView : null,
	
	basicClose : function(theCloser, theDialog)
	{
		Event.observe(theCloser, 'click', function(e)
		{
			Event.stop(e);
			Effect.Fade(theDialog, {duration:0.25, afterFinish:function() {
				if (typeof(IE6Fix) != 'undefined') {
					IE6Fix.fade();
				}			
				Element.toggleClassName(theDialog, 'modal')
			}});
			return false;
		});	
	}
};

var linkobserver =
{
	dead : function(event) {
		Event.stop(event);
		Event.element(event).blur();
		return false;
	}
};

var RM_Utils =
{
	hideAnchor : function(a)
	{
		if (!Element.hasClassName(a, 'deadlink')) {
			Element.addClassName(a, 'deadlink');
			Event.observe(a, 'click', linkobserver.observer);			
		}
	},
	showAnchor : function(a)
	{
		if (Element.hasClassName(a, 'deadlink')) {
			try {
				Element.removeClassName(a, 'deadlink');
				Event.stopObserving(a, 'click', linkobserver.observer);
			} catch (e) { }
		}
	},
	disableRow : function(d, theInputs)
	{
		var i = 0;
		var sz = theInputs.length;
		
		if (typeof(d) != 'undefined') {
			Element.hide(d);
		}
		
		for (i = 0; i < sz; i++) {
			theInputs[i].disabled = true;
		}
	},
	enableRow : function(d, theInputs)
	{
		var i = 0;
		var sz = theInputs.length;	

		Element.show(d);
		for (i = 0; i < sz; i++) {
			theInputs[i].disabled = false;
		}
	},
	setUpClosers : function(rmObj, theDialog, theClosers, updateRowToUpdate)
	{
		var i = 0;
		var sz = theClosers.length;
		
		for (i = 0; i < sz; i++) {
			Event.observe(theClosers[i], 'click', function(e) {
				Event.stop(e);
				Effect.Fade(theDialog, {duration:0.25, afterFinish:function() {
					if (typeof(IE6Fix) != 'undefined') {
						IE6Fix.fade();
					}				
					theDialog.toggleClassName('modal');
				}});
				if (updateRowToUpdate == true && RM_Vars.rowToUpdate) {
					rmObj.updateRow(RM_Vars.rowToUpdate, rmObj);
				}
				RM_Vars.rowToUpdate = null;
				return false;
			});
		}
	},
	getById : function(theId)
	{
		var a = RM_Vars.rmObj.anchors[theId];
		var d = RM_Vars.rmObj.descspans[theId];
		var p = RM_Vars.rmObj.pdfs[theId];
		var c = RM_Vars.rmObj.csvs[theId];
		var x = RM_Vars.rmObj.xlss[theId];
		return new Array(a, d, p, c, x);
	},
	submitForm : function()
	{
		RM_Vars.rmObj.form.submit();
	},
	showPageLoading : function()
	{
		//PageLoading.show();
	},
	hidePageLoading : function()
	{
		//PageLoading.hide();
	}
};

function ReportManagerInit()
{
	if ($('reportManagerTable') != null) {
		linkobserver.observer = linkobserver.dead.bindAsEventListener(linkobserver);
		Dialogs.warning = $('warningDialog');
		Dialogs.confirmDelete = $('confirmDeleteDialog');
		Dialogs.confirmRevert = $('confirmRevertDialog');
		Dialogs.emailRecipient = $('emailRecipientDialog');
		Dialogs.emailRecipientHeight = Element.getStyle(Dialogs.emailRecipient, 'height');
		Dialogs.emailRecipientContainer = $('emailRecipientDialogContainer');
		Dialogs.emailRecipientContainerHeight = Element.getStyle(Dialogs.emailRecipientContainer, 'height');		
		Dialogs.templateView = $('templateViewDialog');
		Dialogs.templateViewContainer = $('templateViewDialogContainer');
		(new ReportManager()).init();
	}
}

function ReportManager()
{
	this.form = $('ReportManager') != null ? $('ReportManager') : $('UserProfile') ;
	this.table = RM_Vars.bodyTable;
	this.selects = this.table.select('select.select');
	if (Prototype.Browser.IE) {
		var counter = 0;
		var i = 0;
		var sz = this.selects.length;
		for (i = 0; i < sz; i++) {
			var optionsLength = this.selects[i].options.length;
			var j;
			var o;
			var text;
			var value;
			for (j = 0; j < optionsLength; j++) {
				o = RM_Vars.originalSelects[counter].options[j].selected;
				text = this.selects[i].options[j].text;
				value = this.selects[i].options[j].value;
				this.selects[i].options[j] = new Option(text, value, false, o);
			}
			counter++;
		}
	}
	this.anchors = this.table.select('a.anchor');
	this.descspans = this.table.select('span.descspan');
	this.pdfs = this.table.select('input.pdfcb');
	this.csvs = this.table.select('input.csvcb');
	this.xlss = this.table.select('input.xlscb');
	this.deleteicons = this.table.select('a.deleteicon');
	RM_Vars.rmObj = this;
	if ($('filters')) {
		RM_Vars.filters = $('filters');
		RM_Vars.filters.IS_CLOSED = false;
	}
	if ($('filtersCaret')) {
		RM_Vars.filtersCaret = $('filtersCaret');
	}
}

ReportManager.prototype.init = function()
{
	this.handleSpecialObjects();
	this.initClosers();
	this.initTableRows();
	this.initDeleteRecipient();
	this.initRevertReport();
	this.initCreateRecipient();
	this.initUpdateRecipient();
	this.initRecipientButtons();
	this.initReportCategorySelect();
	this.initTemplateSelect();
	this.initTemplateView();
	this.initToggleFilters();
};
ReportManager.prototype.initToggleFilters = function()
{
	if (RM_Vars.filtersCaret) {
		Event.observe(RM_Vars.filtersCaret, 'click', function(e) { RM_Vars.rmObj.toggleFilters(e); });
	}
};
ReportManager.prototype.toggleFilters = function(e)
{
	Event.stop(e);
	RM_Vars.filtersCaret.blur();
	var i = 0;
	var sz = 0;
	var arr = null;
	
	if (RM_Vars.filters && RM_Vars.rmObj.table && RM_Vars.rmObj.table.parentNode) {
		if (RM_Vars.filters.IS_CLOSED == true) {
			var t = Prototype.Browser.IE ? '185px' : '186px';
			Element.show(RM_Vars.filters);
			RM_Vars.filters.IS_CLOSED = false;
			arr = $$('div#repman div#superTableContainer');
			sz = arr.length;
			for (i = 0; i < sz; i++) {
				Element.setStyle(arr[i], { top : t });
			}
		} else {
			var t = Prototype.Browser.IE ? '108px' : '109px';
			Element.hide(RM_Vars.filters);
			RM_Vars.filters.IS_CLOSED = true;
			arr = $$('div#repman div#superTableContainer');
			sz = arr.length;
			for (i = 0; i < sz; i++) {
				Element.setStyle(arr[i], { top : t });
			}
			Element.hide(RM_Vars.filters);
		}
	}
};
ReportManager.prototype.initTemplateView = function()
{
	var anchors = RM_Vars.rmObj.table.select('td a.anchor');
	
	if (Dialogs.templateView == null) {
		return;
	}
	
	Effect.Fade(Dialogs.templateView, {duration:0.25, afterFinish:function() {
		if (typeof(IE6Fix) != 'undefined') {
			IE6Fix.fade();
		}					
		Dialogs.templateView.hide();
	}});
	
	var counter = 0;
	var i = 0;
	var sz = anchors.length;
	var theAnchor = null;
	var j = 0;

	var closers = Dialogs.templateView.getElementsByClassName('closeDialog');
	var closers_sz = closers.length;
	if (closers_sz > 0) {
		for (i = 0; i < closers_sz; i++) {
			Dialogs.basicClose(closers[i], Dialogs.templateView);
		}
	}

	for (i = 0; i < sz; i++) {
		counter++;
		if (anchors[i].id && anchors[i].id.indexOf('_')) {
			var theId = anchors[i].id.split('_')[1];
			theAnchor = anchors[i];

			Event.observe(theAnchor, 'click', function(e) {
				if ($('userProfile')) {
					var newTop = (Event.pointerY(e) - 100 - Element.getHeight(Dialogs.templateView))+'px';
					Element.setStyle(Dialogs.templateView, { top: newTop });
				}
				Event.stop(e);
				if (!isNaN(theId)) {
					var url = RM_Vars.rmObj.form.action!=null?RM_Vars.rmObj.form.action.replace(/.action/, '!getCustomReportAjax.action'):'UserProfile.getCustomReportDescriptionAjax.action';
					var str = this.href;
					var lastIdx = str.lastIndexOf('/') + 1;
					if (lastIdx > 0 && lastIdx < str.length) {
						var theNewValue = str.substr(this.href.lastIndexOf('/') + 1, this.href.length);
						var theInput = $('customReportIdToProcess');
						theInput.value = theNewValue;
						var params = RM_Vars.rmObj.form.serialize(true);
						var ajaxOptions = {
							method : 'post',
							parameters : params,
							onCreate: function() {
								RM_Utils.showPageLoading();
							},
							onComplete : function(obj) {
								Dialogs.templateViewContainer.innerHTML = obj.responseText;
								Element.toggleClassName(Dialogs.templateView, 'modal');
								Effect.Appear(Dialogs.templateView, typeof(IE6Fix) != 'undefined' ? IE6Fix._appear : {duration : 0.25});
								RM_Utils.hidePageLoading();
							},
							onFailure : function(){}
						};
						new Ajax.Request(url, ajaxOptions);
					}
					return false;
				}
			});
		}
	}
};
ReportManager.prototype.initReportCategorySelect = function()
{
	var obj = $('reportCategory');
	if (obj) {
		Event.observe(obj, 'change', function(e) {
			RM_Vars.rmObj.changeReportCategory(e, obj);
		});
	}
};
ReportManager.prototype.changeReportCategory = function(e, obj)
{
	if ($('template')) {
		$('template').selectedIndex = 0;
	}
	RM_Utils.submitForm();
};
ReportManager.prototype.initTemplateSelect = function()
{
	var obj = $('template');
	if (obj) {
		Event.observe(obj, 'change', function(e) {
			RM_Vars.rmObj.changeTemplate(e, obj);
		});
	}
};
ReportManager.prototype.changeTemplate = function(e, obj)
{
	RM_Utils.submitForm();
};
ReportManager.prototype.initUpdateRecipient = function()
{
	var theAnchors = $$('a.useremail');
	if (theAnchors.length > 0) {
		var i = 0;
		var sz = theAnchors.length;
		var theAnchor = null;
		
		for (i = 0; i < sz; i++) {
			Element.hide(Dialogs.emailRecipient);
			Effect.Fade(Dialogs.emailRecipient, typeof(IE6Fix) != 'undefined' ? IE6Fix._fade : { duration: 0.25 });
			theAnchor = theAnchors[i];
			Event.observe(theAnchor, 'click', function(e)
			{
				Event.stop(e);
				var url = RM_Vars.rmObj.form.action.replace(/.action/, '.getRecipientAjax.action');
				/* randomize the url, try to get around cache problem. */
				var ustr = (new Date()).getTime();
				var params = 'userIdToProcess=' + this.id + '&r=' + parseInt(ustr);
				Dialogs.emailRecipientHeight = Element.getStyle(Dialogs.emailRecipient, 'height');
				Element.setStyle(Dialogs.emailRecipient, { height: Dialogs.emailRecipientHeight });
				Dialogs.emailRecipientContainerHeight = Element.getStyle(Dialogs.emailRecipientContainer, 'height');
				Element.setStyle(Dialogs.emailRecipientContainer, { height: Dialogs.emailRecipientContainerHeight });
				if ($('userProfile')) {
					var newTop = (Event.pointerY(e) - 100 - Element.getHeight(Dialogs.emailRecipient))+'px';
					Element.setStyle(Dialogs.emailRecipient, { top: newTop });
				}				
				var theErrors = document.getElementsByClassName('alert', Dialogs.emailRecipientContainer);
				if (theErrors.length > 0) {
					theErrors.each(function(theError)
					{
						if (theError.tagName.toLowerCase() == 'span') {
							Element.remove(theError);
						}
						if (theError.tagName.toLowerCase() == 'input') {
							Element.removeClassName(theError, 'alert');
						}
					});
				}

				$('erdh2span').innerHTML = updateTitle;
				Element.toggleClassName(Dialogs.emailRecipient, 'modal');
				Effect.Appear(Dialogs.emailRecipient, typeof(IE6Fix) != 'undefined' ? IE6Fix._appear : { duration: 0.25 });
				var ajaxOptions =
				{
					method : 'get',
					parameters : params,
					onComplete : function(obj)
					{
						Dialogs.emailRecipientContainer.innerHTML = obj.responseText;
						RM_Vars.rmObj.initRecipientButtons();
						RM_Vars.rmObj.initClosers();
					},
					onFailure : function(){}
				};
				new Ajax.Request(url, ajaxOptions);
				return false;
			});
		}
		var closers = document.getElementsByClassName('closeDialog', Dialogs.emailRecipient);
		sz = closers.length;
		if (sz > 0) {
			for (i = 0; i < sz; i++) {
				Dialogs.basicClose(closers[i], Dialogs.emailRecipient);
			}
		}
	}
};
ReportManager.prototype.initRecipientButtons = function()
{
	var savebutton = $('recipientCreateSaveButton');
	var updatebutton = $('recipientUpdateSaveButton');
	var cancelbutton = $('recipientCancelButton');

	if (savebutton) {
		savebutton.setStyle({right:'20px'});
		Event.observe(savebutton, 'click', function(e) {
			RM_Vars.rmObj.handleRecipientSaveButton(e);
		});
	}
	if (updatebutton) {
		updatebutton.setStyle({right:'20px'});
		Event.observe(updatebutton, 'click', function(e) {
			RM_Vars.rmObj.handleRecipientUpdateButton(e);
		});
	}
	if (cancelbutton) {
		Dialogs.basicClose(cancelbutton, Dialogs.emailRecipient);
	}
};
ReportManager.prototype.handleRecipientSaveButton = function(e)
{
	var url = RM_Vars.rmObj.form.action.replace(/.action/, '!recipientCreateAjax.action');
	var params = RM_Vars.rmObj.form.serialize(true);
	var ajax_opts = {method:'post', parameters:params,
		onComplete:function(obj) {
			if (RM_Vars.rmObj.recipientSave(obj, true) == true) {
				var h = document.location.href;
				document.location.href = h;
			}
		},
		onFailure : function(){}
	};
	Event.stop(e);
	new Ajax.Request(url, ajax_opts);
	return false;
};
ReportManager.prototype.handleRecipientUpdateButton = function(e)
{
	var url = RM_Vars.rmObj.form.action.replace(/.action/, '!recipientUpdateAjax.action');
	var params = RM_Vars.rmObj.form.serialize(true);
	var ajax_opts = {method:'post', parameters:params,
		onComplete:function(obj) {
			if (RM_Vars.rmObj.recipientSave(obj,false) == true) {
				var h = document.location.href;
				document.location.href = h;
			}
		},
		onFailure : function(){}
	};
	new Ajax.Request(url, ajax_opts);
	return false;
};
ReportManager.prototype.recipientSave = function(obj, isCreate)
{
	if (obj.responseText == '') {
		Effect.Fade(Dialogs.emailRecipient, typeof(IE6Fix) != 'undefined' ? IE6Fix._fade : {duration:0.25});
		return true;
	} else {
		Dialogs.emailRecipientContainer.update(obj.responseText);
		RM_Vars.rmObj.initRecipientButtons();
		RM_Vars.rmObj.initClosers();
		var i = document.getElementsByClassName('alert', Dialogs.emailRecipient).length;

		return document.getElementsByClassName('alert', Dialogs.emailRecipientContainer) ? false : true;
	}
};
ReportManager.prototype.initCreateRecipient = function()
{
	var theLink = $('createEmailRecipient');
	var i = 0;
	var sz = 0;
	
	if (theLink) {
		Element.hide(Dialogs.emailRecipient);
		Effect.Fade(Dialogs.emailRecipient, typeof(IE6Fix) != 'undefined' ? IE6Fix._fade : { duration: 0.25 });
		Event.observe(theLink, 'click', function(e)
		{
			RM_Vars.user = '';
			Event.stop(e);
			var url = RM_Vars.rmObj.form.action!=null?RM_Vars.rmObj.form.action.replace(/.action/, '.getRecipientAjax.action'):'UserProfile.getCustomReportDescriptionAjax.action';
			var params = 'userIdToProcess=' + RM_Vars.user;
			var formElements = Form.getInputs(RM_Vars.rmObj.form, 'text');
			sz = formElements.length;
			if (sz > 0) {
				for (i = 0; i < sz; i++) {
					formElements[i].value = '';
				}
			}
			
			sz = formElements.length;
			if (sz > 0) {
				for (i = 0; i < sz; i++) {
					formElements[i].checked = false;
				}
			}

			Element.setStyle(Dialogs.emailRecipient, { height: Dialogs.emailRecipientHeight });
			if ($('userProfile')) {
				var newTop = (Event.pointerY(e) - Element.getHeight(Dialogs.emailRecipient))+'px';
				Element.setStyle(Dialogs.emailRecipient, { top: newTop });
			}				
			
			$('erdh2span').innerHTML = createTitle;
			Element.toggleClassName(Dialogs.emailRecipient, 'modal');
			Effect.Appear(Dialogs.emailRecipient, typeof(IE6Fix) != 'undefined' ? IE6Fix._appear : { duration: 0.25 });
			var ajaxOptions = {
				method : 'get',
				parameters : params,
				onComplete : function(obj)
				{
					$('emailRecipientDialogContainer').innerHTML = obj.responseText;
					RM_Vars.rmObj.initRecipientButtons();
					RM_Vars.rmObj.initClosers();
				},
				onFailure : function(){}
			};
			new Ajax.Request(url, ajaxOptions);
		});
		var closers = Element.select(Dialogs.emailRecipient, '.closeDialog');
		sz = closers.length;
		if (sz > 0) {
			for (i = 0; i < sz; i++) {
				Dialogs.basicClose(closers[i], Dialogs.emailRecipient);
			}
		}

		var recipientCancelButtonObj = $('recipientCancelButton');
		Dialogs.basicClose(recipientCancelButtonObj, Dialogs.emailRecipient);
	}
};

ReportManager.prototype.initDeleteRecipient = function()
{
	var deleteIcons = this.deleteicons;
	var closers = Element.select(Dialogs.confirmDelete, '.closeDialog');
	var i = 0;
	var sz = deleteIcons.length;
	var delico = null;
	if (sz > 0) {
		for (i = 0; i < sz; i++) {
			this.user = deleteIcons[i].id;
			this.state = ApplicationConstants.STATE_DELETE;
			
			if (closers.length > 0) {
				Element.hide(Dialogs.confirmDelete);
				delico = deleteIcons[i];
			}
		}
	}

	sz = closers.length;
	if (sz > 0) {
		for (i = 0; i < sz; i++) {
			Dialogs.basicClose(closers[i], Dialogs.confirmDelete);
		}
	}	

	var no = $('confirmAnswerNo');
	Dialogs.basicClose(no, Dialogs.confirmDelete);
};

ReportManager.prototype.initRevertReport = function()
{
	var deleteIcons = this.deleteicons;
	var closers = Element.select(Dialogs.confirmRevert, '.closeDialog');
	var i = 0;
	var sz = deleteIcons.length;
	var delico = null;
	if (sz > 0) {
		for (i = 0; i < sz; i++) {
			this.user = deleteIcons[i].id;
			this.state = ApplicationConstants.STATE_DELETE;
			
			if (closers.length > 0) {
				Element.hide(Dialogs.confirmRevert);
				delico = deleteIcons[i];
			}
		}
	}

	sz = closers.length;
	if (sz > 0) {
		for (i = 0; i < sz; i++) {
			Dialogs.basicClose(closers[i], Dialogs.confirmRevert);
		}
	}	

	var no = $('confirmAnswerNo');
	Dialogs.basicClose(no, Dialogs.confirmRevert);
};

ReportManager.prototype.updateRow = function(obj)
{
	if (obj.id.indexOf('_') > 0) {
		var theId = obj.rememberTheId;
		if (!isNaN(theId)) {
			var theInfo = RM_Utils.getById(theId);
			var theInputs = new Array(theInfo[2], theInfo[3], theInfo[4]);
			
			var url = this.form.action!=null?this.form.action.replace(/.action/, '.getCustomReportDescriptionAjax.action'):'UserProfile.getCustomReportDescriptionAjax.action';
			var params = 'customReportIdToProcess='+obj.value;
			var ajaxOpts = {
				method : 'get',
				parameters : params,
				onSuccess : function(obj)
				{
					RM_Vars.rmObj._updateRow(obj, theId);
				},
				onFailure : function(){}
			};

			if (obj.value == '-1') {
				RM_Vars.rmObj.anchors[theId].href = '';
				var theInputs = new Array(RM_Vars.rmObj.pdfs[theId], RM_Vars.rmObj.csvs[theId], RM_Vars.rmObj.xlss[theId]);
				RM_Utils.hideAnchor(RM_Vars.rmObj.anchors[theId]);
				RM_Utils.disableRow(RM_Vars.rmObj.descspans[theId], theInputs);
				
				return;
			}

			new Ajax.Request(url, ajaxOpts);
		}
	}
};
ReportManager.prototype._updateRow = function(obj, theId, theInfo, theInputs)
{
	var rt = obj.responseText;
	var parts = rt.split(ApplicationConstants.DEFAULT_SEPARATOR);
	var theHref = parts[0];
	var theDescription = parts[1];
	var anchor = RM_Vars.rmObj.anchors[theId];
	var description = RM_Vars.rmObj.descspans[theId];
	var theInputs = new Array(RM_Vars.rmObj.pdfs[theId], RM_Vars.rmObj.csvs[theId], RM_Vars.rmObj.xlss[theId]);

	anchor.href = theHref;
	description.innerHTML = theDescription.truncate(ApplicationConstants.REPMAN_TRUNCATE);
	RM_Utils.showAnchor(anchor);
	RM_Utils.enableRow(description, theInputs);
	RM_Vars.rowToUpdate = null;
};

ReportManager.prototype.initClosers = function()
{
	if (Dialogs.warning == null) {
		return;
	}
	
	var closers = Dialogs.warning.select('.closeDialog');
	if (closers.length > 0) {
		RM_Utils.setUpClosers(this, Dialogs.warning, closers, true);
	}
};
ReportManager.prototype.initTableRows = function()
{
	var counter = 0;
	var tbl = this.table;
	var i = 0;
	var sz = this.selects.length;
	
	for (i = 0; i < sz; i++) {
		if (this.selects[i].id.indexOf('_') > 0) {
			theId = this.selects[i].id.split('_')[1];

			if (Dialogs.warning != null) {
				this.selects[i].rememberTheId = theId;
				Event.observe(this.selects[i], 'change', function(e)
				{
					Event.stop(e);
					var oi = $('originalIndividual_' + this.rememberTheId);
					var craid = $('originalCustomReportId_' + this.rememberTheId);
					if (oi.value == 'true' && craid.value != this.value) {
						if ($('userProfile')) {
							var newTop = (Event.pointerY(e) - 100 - Element.getHeight(Dialogs.warning))+'px';
							Element.setStyle(Dialogs.warning, { top: newTop });
						}					
						Element.toggleClassName(Dialogs.warning, 'modal');
						Effect.Appear(Dialogs.warning, typeof(IE6Fix) != 'undefined' ? IE6Fix._appear : { duration: 0.25 });
						RM_Vars.rowToUpdate = this;
					} else {
						RM_Vars.rmObj.updateRow(this);
					}
					return false;
				});
			}

			var d = RM_Vars.rmObj.descspans[theId];
			if(typeof(d) != 'undefined') {
			var str = d.innerHTML;
				if (str.length > ApplicationConstants.REPMAN_TRUNCATE) {
					d.innerHTML = str.truncate(ApplicationConstants.REPMAN_TRUNCATE);
				}
			}
			if (this.selects[i].value == '-1') {
				var theInputs = new Array(RM_Vars.rmObj.pdfs[theId], RM_Vars.rmObj.csvs[theId], RM_Vars.rmObj.xlss[theId]);
				RM_Utils.hideAnchor(RM_Vars.rmObj.anchors[theId]);
				RM_Utils.disableRow(RM_Vars.rmObj.descspans[theId], theInputs);
			}
		}
	}
};

ReportManager.prototype.handleSpecialObjects = function()
{
	var obj = $('applyButton');
	if (obj) {
		Element.hide(obj);
		if (Prototype.Browser.IE == true) {
			obj.setStyle({top:'-20px'});
		}
	}
	obj = $('saveButton');
	if (obj) {
		if (Prototype.Browser.IE == true) {
			obj.setStyle({top:'-20px', left:'490px'});
		}
	}
	obj = $('superTableContainer');
	if (obj) {
		if (Prototype.Browser.IE == true) {
			obj.setStyle({top:'185px'});
		}
	}
	obj = $('templateViewDialog');
	if (obj) {
		obj.setStyle({left:'250px'});
		obj.removeClassName('modal');
		obj.addClassName('modal');
	}
};


function handleAjaxFailure(xhr, ojson) {
	alert('error: ' + xhr.statusText);
}























var Util =
{
	getPageSize: function(parent)
	{
		parent = parent || document.body;
		var windowWidth, windowHeight;
		var pageHeight, pageWidth;
		if (parent != document.body) {
			windowWidth = parent.getWidth();
			windowHeight = parent.getHeight();
			pageWidth = parent.scrollWidth;
			pageHeight = parent.scrollHeight;
		} else {
			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;
			}


			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;
			}

			// 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};
	},

	getWindowScroll: function(parent)
	{
		var T, L, W, H;
		parent = parent || document.body;
		if (parent != document.body) {
			T = parent.scrollTop;
			L = parent.scrollLeft;
			W = parent.scrollWidth;
			H = parent.scrollHeight;
		} else {
			var w = window;
			with (w.document) {
				if (w.document.documentElement && documentElement.scrollTop) {
					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 && documentElement.clientWidth) {
					W = documentElement.clientWidth;
					H = documentElement.clientHeight;
				} else {
					W = body.offsetWidth;
					H = body.offsetHeight
				}
			}
		}
		return { top: T, left: L, width: W, height: H };
	},
	
  /*
    Finds the x position of an object
  */
  findPosX:function(obj){
    var curleft = 0;
    if (obj.offsetParent)
    {
      while (obj.offsetParent)
      {
        curleft += obj.offsetLeft
        obj = obj.offsetParent;
      }
    }
    else if (obj.x)
      curleft += obj.x;
    return curleft;
  },

  /*
    Finds the y position of an object
  */
  findPosY:function(obj){
    var curtop = 0;
    if (obj.offsetParent)
    {
      while (obj.offsetParent)
      {
        curtop += obj.offsetTop
        obj = obj.offsetParent;
      }
    }
    else if (obj.y)
      curtop += obj.y;
    return curtop;
  }	
};

var Overlay =
{
	obj : null,
	tmp : null,
	msg : null,
	txt : 'Page loading...',
	opa : 0.9,
	id  : 'overlay',
	useEffects : (typeof Effect != 'undefined'),
	effectDuration : 0.5,
	anchors : null,
	footerElement : null,
	
	activate : function()
	{
		return true;
	},

	init : function(id, cname)
	{
		if (typeof(IE6Fix) != 'undefined') {
			IE6Fix.hideAllSelects();
		}
		Overlay.tmp = $('overlayTmp');
		if (Overlay.tmp != null) {
			Overlay.tmp.hide();
			Overlay.tmp.setStyle({width:'1px', left:'-5000px'});
			var tmpMsg = Overlay.tmp.select('span')[0];
			Overlay.txt = tmpMsg.innerHTML;
		}
		Overlay.obj = $(Overlay.id);
		if (Overlay.obj != null) {
			Overlay.msg = Overlay.obj.select('span')[0];
			Overlay.txt = Overlay.msg.innerHTML;
		} else {
			Overlay.obj = new Element('div');
			Overlay.obj.id = Overlay.id;
			Overlay.msg = new Element('span').update(Overlay.txt);
			Overlay.obj.appendChild(Overlay.msg);
			Overlay.obj.hide();
			Overlay.msg.show();
			$$('body')[0].appendChild(Overlay.obj);
		}
		
		var pageSize = Util.getPageSize(Overlay.obj.parentNode);
		var hCenter = parseInt((pageSize.pageHeight / 2) - 25);
		var wCenter = parseInt((pageSize.pageWidth / 2)  - 95);
		var oheight = pageSize.pageHeight + 'px';
		var owidth  = pageSize.pageWidth + 'px';

		Overlay.obj.setStyle({
			zIndex : '9999',
			background : '#FFF',
			color: '#000',
			position: 'absolute',
			height : oheight,
			width  : owidth,
			top    : '0',
			left   : '0'
		});
		Overlay.msg.setStyle({
			color : '#000',
			background : '#FFF',
			font : 'bold 14px verdana',
			position: 'absolute',
			left: (wCenter+'px'),
			top:  (hCenter+'px'),
			background: 'transparent url(./images/loading.gif) no-repeat left center',
			paddingLeft: '34px',
			height: '40px',
			lineHeight: '40px',
			verticalAlign: 'middle'
		});
		
		var tmpAnchors = [ $('tab_manager_url'), $('tab_mileage_url') ];
		Overlay.anchors = $$('a.showOverlay').inject(tmpAnchors, function(a, v)
		{
			a.push(v);
			return a;
		});
		Overlay.setUpAnchors();
		Overlay.footerElement = $('footer');
	},

	setUpAnchors : function()
	{
		Overlay.anchors.each(function(anchor)
		{
			if (anchor != null) {
				anchor.observe('click', function(e)
				{
					Event.element(e).blur();
					Overlay.show(false);
				});	
			}
		});
	},

	show : function(fromPageInit)
	{
		if (Overlay.obj == null) {
			Overlay.init();
		}
		if (Overlay.obj == null) {
			return;
		}
		if (Overlay.useEffects == true) {
			if (Overlay.footerElement) {
				Overlay.footerElement.hide();
			}
			if (typeof(IE6Fix) != 'undefined') {
				IE6Fix.hideAllSelects();
			}			
			Overlay.obj.show();
		}
	},

	hide : function()
	{
		if (Overlay.footerElement) {
			Overlay.footerElement.show();
		}
		if (typeof(IE6Fix) != 'undefined') {
			IE6Fix.showAllSelects();
		}		
		Overlay.obj.hide();
	}
};

var SuperTable =
{
	topDiv : null,
	midDiv : null,
	topTable : null,
	bodyTable : null,

	firstInit : function()
	{
		RM_Vars.originalSelects = $$('select.select');
		SuperTable.__init__();
		if ($('reportManagerTable') != null) {
			ReportManagerInit();
		}
	},	
	
   __init__ : function()
  {
    var tables = $$('table.superTable');
    if (tables.length > 0) {
	    tables.each(function(table)
	    {
			try {
				var doNotLock = false;
					if (table.id == '2_table' || table.id == '12_table' 
						|| table.id == '4_table' || table.id == 'customerList_table' 
						|| table.id == '15_table' || table.id == '16_table'
						|| table.id == 'mileageEntryAllUnits_table'  || table.id == 'mileageEntrySingleUnit_table') {
						doNotLock = true;
					}
					if (doNotLock == true) {
						SuperTable.makeScrollableParent(table);
					} else {
						SuperTable.makeScrollable(table);
					}
			} catch (e) {
				if (document.getElementById('overlayTmp')) {
					document.getElementById('overlayTmp').style.display = 'none';
				}
				if (document.getElementById('overlay')) {
					document.getElementById('overlay').style.display = 'none';
				}
				SuperTable.handleTablesForIE();
			}		    	
	    });
	}

	var tds = $$('td.number.string');
	var i = 0;
	var sz = tds.length;
	if (sz > 0) {
		for (i = 0; i < sz; i++) {
			Element.toggleClassName(tds[i], 'string');
		}
	}
    return;
  },
  
  	offsetsForIE : {
		width: -30,
		height: -25,
		scrollbar: - 37
	},
	
	assertIE6 : function()
	{
		return typeof(BrowserDetect) != 'undefined' && BrowserDetect.browser == 'Explorer' && BrowserDetect.version < 7;
	},
  
	resizeTablesForIE : function(obj, w, h)
	{
		if (SuperTable.assertIE6()) {
			var divScrolls = obj.select('div.scroll');
			
			if (divScrolls.length > 0) {
				divScrolls.each(function(divScroll) {
					divScroll.setStyle({
						width: w + 'px',
						height: h + 'px'
					});
				});
			}
			var divMiddles = obj.select('div.scroll div.middle');
			if (divMiddles.length > 0) {
				divMiddles.each(function(divMiddle) {
					divMiddle.setStyle({
						width: w + 'px',
						height: h + SuperTable.offsetsForIE.scrollbar + 'px'
					});
				});
			}
		}
	},
	
	handleTablesForIE : function()
	{
		if (SuperTable.assertIE6()) {
			var w = 0;
			var h = 0;
			var delta_w = 0;
			var delta_h = 0;
			var obj = null;
	
			if ($('reportData') && $('footer')) {
				w = document.body.clientWidth;
				h = Util.findPosY($('footer'))
				delta_w = Util.findPosX($('reportData'));
				delta_h = Util.findPosY($('reportData'));
				obj = $('reportData');
				w -= delta_w;
				h -= delta_h;
		
				if (obj) {
					var new_w = w + SuperTable.offsetsForIE.width;
					var new_h = h + SuperTable.offsetsForIE.height;
					SuperTable.resizeTablesForIE(obj, new_w, new_h);
				}
			}
			if (($('requests') || $('contacts') || $('userProfileSuperTableContainer') ) && $('footer')) {
				$('footer').setStyle({ position: 'static', clear: 'both' });
			}			
		}
	}, 
	
	exapandableRows:false,
	
	makeScrollableParent : function(table)
	{
		var div = $(table.parentNode);
		
		if (div) {
			div.setStyle({ overflow: 'auto' });
			SuperTable.setStyles(div);
			if (SuperTable.exapandableRows == true) {
				SuperTable.parentSub(div);
			}
			SuperTable.setWidth(div);
		}
	},

	makeScrollable : function(table, isInvoiceTable)
	{
		var div = table.parentNode;
		
		if (div && !Element.hasClassName(div,'top') && !Element.hasClassName(div,'middle')) {
			var widget = SuperTable.createNewTable(table);
			table.replace(widget);
				
			var topDiv = widget.getElementsByTagName('div')[0];
			var midDiv = widget.getElementsByTagName('div')[1];
			midDiv.topTable = topDiv.getElementsByTagName('table')[0];
			midDiv.bodyTable = midDiv.getElementsByTagName('table')[0];
				
			SuperTable.setHeaderHeights(widget, topDiv, midDiv, midDiv.bodyTable);
				
			Event.observe(midDiv, 'scroll', function()
			{
				this.topTable.style.left = -1 * (parseInt(this.scrollLeft)) + 'px';
			});

			SuperTable.setStyles(widget);
			if (SuperTable.exapandableRows == true) {
				SuperTable.parentSub(widget);
			}
			SuperTable.setWidth(widget);
			
			SuperTable.handleTablesForIE();
			
			Event.observe(window, 'resize', function()
			{
				SuperTable.handleTablesForIE();
				SuperTable.setWidth(widget);
			}, true );
			
			var calendars = $$('div.scroll div.middle table.superTable tbody tr td.calendar');
			if (calendars.length > 0) {
				calendars.each(function(calendar)
				{
					MileageTemplate.initializeCalendar(calendar);
				});
			}
			
			if (SuperTable.assertIE6()) {
				var x = 0;
				var client_height = document.body.clientHeight;
				var scroll_height = 0;
				var middiv_height = 0;
				var scrollHandle = $$('div#reports.mileage.all div#reportData div.scroll');
				if (scrollHandle.size() > 0) {
					scrollHandle = scrollHandle[0];
					x++;
				}
				var midDivHandle = $$('div#reports.mileage.all div#reportData div.scroll div.middle');
				if (midDivHandle.size() > 0) {
					midDivHandle = midDivHandle[0];
					x++;
				}
				if (x == 2) {
					scroll_height = client_height - 345;
					middiv_height = client_height - 422;
					scrollHandle.setStyle({ height: scroll_height + 'px' });
					midDivHandle.setStyle({ height: middiv_height + 'px' });
				}
			}
		}

		return;
	},

  createNewTable : function(table)
  {
    var outerDiv = document.createElement('div');
        outerDiv.setAttribute('class', 'scroll');
        outerDiv.className = 'scroll';

    var headDiv = document.createElement('div');
        headDiv.setAttribute('class', 'top');
        headDiv.className = 'top';

    var bodyDiv = document.createElement('div');
        bodyDiv.setAttribute('class', 'middle');
        bodyDiv.className = 'middle';

    var headTable = table.cloneNode(true);
    var bodyTable = table.cloneNode(true);

	if (bodyTable.id == 'reportManagerTable' && RM_Vars.bodyTable == null) {
		RM_Vars.bodyTable = bodyTable;
	}
	if (headTable.id == 'reportManagerTable' && RM_Vars.headTable == null) {
		RM_Vars.headTable = headTable;
	}
	if (table.id == 'reportManagerTable') {
		RM_Vars.bodyDiv = bodyDiv;
		RM_Vars.headDiv = headDiv;
		RM_Vars.outerDiv = outerDiv;
	}

	try {
		if (table.id == 'reportManagerTable' || (MileageTemplate && MileageTemplate.isMileageTemplate == true)) {
			SuperTable.cleanUpFields(headTable);
		}
	} catch (e) {
	}

    headDiv.appendChild(headTable);
    bodyDiv.appendChild(bodyTable);
    outerDiv.appendChild(headDiv);
    outerDiv.appendChild(bodyDiv);

    return outerDiv;
  },

  cleanUpFields: function(obj)
  {
  	var inputs = obj.getElementsBySelector('input');
  	var counter = 0;
  	var i = 0;
  	var sz = inputs.length;
  	
  	for (i = 0; i < sz; i++) {
  		inputs[i].id = '';
  		inputs[i].name = (inputs[i].name + '______' + counter++);
  		inputs[i].value = '';
  		inputs[i].disabled = true;
  	}
  	
	inputs = obj.getElementsBySelector('select');
  	sz = inputs.length;
  	
  	for (i = 0; i < sz; i++) {
  		inputs[i].id = '';
  		inputs[i].name = (inputs[i].name + '______' + counter++);
  		inputs[i].value = '';
  		inputs[i].disabled = true;
  	}
  	
  	inputs = $$('div.top input');
  	sz = inputs.length;
  	
  	for (i = 0; i < sz; i++) {
  		inputs[i].id = '';
  		inputs[i].name = (inputs[i].name + '______' + counter++);
  		inputs[i].value = '';
  		inputs[i].disabled = true;
  	}
  },
		
  makeStripes : function(row, subsCount)
  {
				Event.observe(row, 'click', function(e)
				{
					var o = Event.element(e);
					var t = o.tagName.toLowerCase();

					if (t == 'input' || t == 'select' || t == 'option' || t == 'a') {
						return false;
					}
					if (o.hasClassName('enterMileage') || o.hasClassName('__DO_NOT_TOGGLE')) {
						return false;
					}
					Element.toggleClassName(this, 'clicked');
				}, false);

    return subsCount;
  },

  parentSub : function(widget)
  {
  	widget = $(widget);
    var parents = widget.select('tr.parent');
    if (parents.size() < 1) {
    	return;
    }
    var subs = widget.select('tr.sub');
    var i = 0;
    var sz = subs.size();
    
	if (sz > 0) {
		for (i = 0; i < sz; i++) {

			Element.addClassName(subs[i], 'collapsed');
		}
	}
	
	sz = parents.length;
	if (sz > 0) {
		for (i = 0; i < sz; i++) {
			initializeParent(parents[i]);
		}
	}
	
    function toggleSub(sub)
    {
    	Element.toggleClassName(sub, 'expanded');
    	Element.toggleClassName(sub, 'collapsed');
    }

    function initializeParent(parent)
    {
      var icon = parent.select('th')[0];
      Event.observe(icon, 'click', function(icon){ Event.stop(icon); icon = this; toggleParent(icon); });

		/* TODO: make sure this is what we clicked on using Event.element(e) or so......
		 */
      var link = parent.select('td')[2];
      Event.observe(link, 'click',
      	function(link)
      	{
			Event.stop(link);
			link = this;
			toggleParent(link);
		}
	  );

      function toggleParent(icon)
      {
        icon.parentNode.toggleClassName('collapsed');
        icon.parentNode.toggleClassName('expanded');

        var classes = $A(icon.parentNode.classNames());

        for(var i=0; i<classes.length; i++)
        {
          if(classes[i].indexOf('_') == 0){ var parentID = classes[i]; break; }
        }

        if(parentID)
        {
          var theseSubs = widget.select('table tr.sub.'+parentID);
          var i = 0;
          var sz = theseSubs.length;
          for (i = 0; i < sz; i++) {
          	toggleSub(theseSubs[i]);
          }
        }
      }
    }
  },

  setDataTypes : function(row, cols)
  {
    var cells = $A(row.cells);
    var i = 0;
    var sz = cells.length;
    if (sz > 0) {
    	for (i = 0; i < sz; i++) {
    		Element.addClassName(cells[i], cols[cells[i].cellIndex].className);
    	}
    }
  },

  setStyles : function(widget)
  {
  	var t = $(widget).select('table')[0];
  	if (Prototype.Browser.IE && t.id == 'reportManagerTable') {
  		return;
  	}
    var cols = t.select('col');
    var rows = widget.select('table tr');
    var sz = rows.length;
    var i = 0;
    var subsCount = 0;
    
    for (i = 0; i < sz; i++) {
    	if (!Prototype.Browser.IE) {
    		SuperTable.setDataTypes(rows, cols);
    		subsCount = SuperTable.makeStripes(rows[i], subsCount);
    	}
    }    
    return;
  },

  setHeaderHeights : function(widget, topDiv, midDiv, bodyTable)
  {
    var height = Element.getHeight(topDiv.getElementsByTagName('thead')[0]);

   	Element.setStyle(topDiv, 'height:'+height+'px');
    Element.setStyle(midDiv, 'top:'+height+'px');
   	Element.setStyle(bodyTable, 'margin-top:-'+height+'px');

    return;
  },

  setWidth : function(obj)
  {
    var container = $(obj.parentNode);
	
   	if(container && container.getWidth() > obj.getWidth()) {
      container.addClassName('shortTable');
   	  container.removeClassName('justRight');
    } else {
      container.removeClassName('shortTable');
      container.addClassName('justRight');
    }
    return;
  }
}

function handleDeleteIconOnClick(obj)
{
	var userId = $('ReportManager_userIdToProcess');
	
	if (userId == null) {
		userId = $('UserProfile_userIdToProcess');
	}
	
	userId.value = obj.id;	
	Element.toggleClassName(Dialogs.confirmDelete, 'modal');
	Effect.Appear(Dialogs.confirmDelete, typeof(IE6Fix) != 'undefined' ? IE6Fix._appear : { duration: 0.25 });
	return false;
}

function handleRevertReportOnClick(obj)
{
	var reportAccessId = $('UserProfile_customReportAccessIdToProcess');
	reportAccessId.value = obj.id;
	Element.toggleClassName(Dialogs.confirmRevert, 'modal');
	Effect.Appear(Dialogs.confirmRevert, typeof(IE6Fix) != 'undefined' ? IE6Fix._appear : { duration: 0.25 });
	return false;
}

Event.observe(window, 'load', function()
{
	/* OVERLAY */
	if (typeof(Overlay) == 'object' && Overlay.activate()) {
		try {
			Overlay.init();
		} catch(e) { }
	}
	
	SuperTable.firstInit();
	
	/* OVERLAY */
	if (typeof(Overlay) == 'object' && Overlay.obj != null && Overlay.activate()) {
		try {
			Overlay.hide();
		} catch (e) { }
	}
}, false);