//
// Facility Scheduler Scripts
//

// from dav glass

/*
alert(typeof(YAHOO));

if (typeof(YAHOO) != 'undefined') {
	alert("YAHOO exists");
}
else {
	alert("Important files from http://yui.yahooapis.com were not loaded");
}
*/

function isArray(testObject) {	 
    return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject.length === 'number';
}

$A = YAHOO.util.Anim;
$E = YAHOO.util.Event;
$D = YAHOO.util.Dom;
$T = YAHOO.Tools;
$ = YAHOO.util.Dom.get;
$$ = YAHOO.util.Dom.getElementsByClassName;

YAHOO.namespace ("FacilityScheduler");

// globals
var timeout; 
var timeoutRefresh;
var timeoutProcessingError;
var root;
var dateStart;
var dateEnd;
var checkpoint = 0;
var dlgClicky = null;
var lngSystemID = $('objSystemID').innerHTML;
var fsLocations = null;
var fsPeriods = null;
var fsBellSchedules = null;

//
//
//
function showhide(elementID) {
	var el = $(elementID); 
	if (el.style.display == 'none') {
		el.style.display = 'block';
	}
	else {
		el.style.display = 'none';
	}
}

//
// new 2008.09.22
//
function timeTextFromMinutes(lngMinutes) {
	var strHour = lngMinutes / 60;
	var strMinute = lngMinutes % 60;
	var strAMPM = "am";
	//alert("minutes=" + lngMinutes);
	//alert("strHour" + strHour);
	if (strHour > 11) { 
		strAMPM = "pm";
		strHour = strHour - 12;
	}
	//alert("strHour" + strHour);
	if (strHour == 0) {
		strHour = 12;
	}
	//alert("strMinute" + strMinute);
	if (strMinute < 10) {
		strMinute = "0" + strMinute;
	}	
	//alert("ddd");
	return strHour + ":" + strMinute + strAMPM;	
	//alert("eee");
}

//
//
//
function breakout_of_frame()
{
  if (top.location != location) {
    top.location.href = document.location.href ;
  }
}
$E.addListener(window, 'load', breakout_of_frame());

//
//
//
function updateTime()
{
	if (document.getElementById("objUpdateTime"))
	{
		var dtmTime = new Date();
		var dtmHours = dtmTime.getHours();
		var dtmMinutes = dtmTime.getMinutes();
		var strAMPM = "am";
		if (dtmHours > 11) { strAMPM = "pm"; }
		if (dtmHours > 12) { dtmHours = dtmHours - 12; }
		if (dtmMinutes < 10) { dtmMinutes = "0" + dtmMinutes; }
		document.getElementById("objUpdateTime").innerHTML = dtmHours + ":" + dtmMinutes + strAMPM;
	}
}

//
// from AVS
//
function RoundTripTime() {

	return;
	//var NewHTML = "{Round Trip Time not calculated}";
	//var Today = new Date();
	//var ThisMillisecond = Today.getTime();
	//var y = $('objLocalDifference');
	//var SubmitTime = $('objSubmitTime');
	//var Difference = (ThisMillisecond - SubmitTime.innerHTML)/1000;
	//if (Difference < 200) { NewHTML = 'Round Trip Time = ' + Difference.toString() + ' seconds (only accurate if you did not use your browser\'s Refresh button)'; }
	//y.innerHTML = NewHTML;
}

//
// from AVS
//
function SecondRoundTripTime() {

	var newHTML = "";
	var today = new Date();
	var thisMillisecond = today.getTime();
	var y = $('objLocalDifference');
	var submitTime = $('objSubmitTime');
	var difference = (thisMillisecond - submitTime.innerHTML)/1000;
	newHTML = '2nd Round Trip Time = ' + difference.toString() + ' seconds';
	//y.innerHTML = y.innerHTML + "; " + NewHTML;
	y.innerHtml = 'test';
}

//
// Append Local Submit Time to the outgoing link
//
function AddSubmitTimeToLink(Hyperlink) {
	var RightNow = new Date().getTime();
	if (Hyperlink.indexOf('?') > 0) { NewHyperLink = Hyperlink + '&SubmitTime=' + RightNow; } 
	else { NewHyperLink = Hyperlink + '?SubmitTime=' + RightNow; }
	window.location.replace(NewHyperLink);	
}

//
//
//
function ShowEmptyCellMenu(e, dtmDate, lngPeriodID, lngRoomID) {

	fn_HideMenus();
	
	clearTimeout(timeout);

	var objEmptyCellMenu = $('objEmptyCellMenu');	
	var intLeftPosition = $E.getPageX(e);
	var intTopPosition = $E.getPageY(e);
   					   				
	objEmptyCellMenu.style.top = intTopPosition + 'px';  
	objEmptyCellMenu.style.left = intLeftPosition + 'px';  
    	
	objEmptyCellMenu.innerHTML = objEmptyCellMenu.innerHTML.replace("XDATEX", dtmDate);
	objEmptyCellMenu.innerHTML = objEmptyCellMenu.innerHTML.replace("XPERIODIDX", lngPeriodID);
	objEmptyCellMenu.innerHTML = objEmptyCellMenu.innerHTML.replace("XROOMIDX", lngRoomID);
	objEmptyCellMenu.style.display = "inline";  				
	
	timeout = setTimeout(fn_HideMenus, 7000);

	e = e||event;/* get IE event ( not passed ) */ 
	e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;
	
}

//
//
//
function fn_HideMenus() {
	// HIDE MENUs AFTER 6 SECONDS
	$('objEmptyCellMenu').style.display = "none";
	$('objReservationMenu').style.display = "none";						
}

var ResIDHold = "";
var ResDateHold = "";
var ResPeriodIDHold = "";
var ResRoomIDHold = "";
var ResFlagHold = false;

//
// NEW 2006-05-06
//
function ResMenu(e, dtmDate, lngPeriodID, lngRoomID, lngReservationID) {
	
	// hide any menus that may be visible
	fn_HideMenus();
	// reset menu disappear function
	clearTimeout(timeout);

	var objReservationMenu = $('objReservationMenu');
	var xpos = $E.getPageX(e);
	var ypos = $E.getPageY(e);
   
	ResIDHold = lngReservationID;
	ResDateHold = dtmDate;
	ResPeriodIDHold = lngPeriodID;
	ResRoomIDHold = lngRoomID;

	objReservationMenu.style.top = ypos + 'px';  
	objReservationMenu.style.left = xpos + 'px';  
    	
	objReservationMenu.style.position = "absolute";
	objReservationMenu.style.display = "inline";  				
	
	// prevents the EmptyCellMenu from showing also
	$E.stopEvent(e);
	
	// clear all menus after 6 seconds
	timeout = setTimeout(fn_HideMenus, 7000);
	
}

//
// 
//
function ResMenuEdit() {
	fn_HideMenus();
	parent.location.href = "?sid=" + lngSystemID + "&Action=EditReservation&ReservationID=" + ResIDHold;
}

//
// 
//
function ResMenuDetails() {
	fn_HideMenus();
	var transaction = YAHOO.util.Connect.asyncRequest('GET', 'index.asp?sid=' + lngSystemID + '&Action=CompleteCalendarItem&ReservationID=' + ResIDHold, callback_ResMenuDetails, null); 
}

//
// 
//
function ResMenuSetFlag(FlagCategoryID) {
	fn_HideMenus();
	var transaction = YAHOO.util.Connect.asyncRequest('GET', 'index.asp?sid=' + lngSystemID + '&Action=SetReservationFlag&ReservationID=' + ResIDHold + '&FlagCategoryID=' + FlagCategoryID, callback_ResMenuFlagComplete, null); 
}

//
//
//
function ResMenuNote() {
	fn_HideMenus();
	// alert("future feature");
	// get current note from server
	// display in a popup dialog box
	// send note back to server - or delete note if requested
	// refresh the screen with note icons
	var transaction = YAHOO.util.Connect.asyncRequest('GET', 'index.asp?sid=' + lngSystemID + '&Action=Note&NoteID=' + ResIDHold, callback_Note, null); 

	// old:
	// var transaction = YAHOO.util.Connect.asyncRequest('GET', 'index.asp?Action=ClearReservationFlag&ReservationID=' + ResIDHold, callback_ResMenuFlagComplete, null); 
}

//
// 
//
function ResMenuDelete() {
	fn_HideMenus();
	parent.location.href = "?sid=" + lngSystemID + "&Action=Delete&ID=" + ResIDHold;
}

//
//
//
function ResMenuRequestMatch(ReservationID) {
	if (!ReservationID) {
		ReservationID = ResIDHold;
	}
	fn_HideMenus();
	// old: parent.location.href = "?Action=MatchingRequest&ReservationID=" + ResIDHold;
	var transaction = YAHOO.util.Connect.asyncRequest('GET', 'index.asp?sid=' + lngSystemID + '&Action=MatchingRequest&ReservationID=' + ReservationID, callback_ResMenuRequestMatch, null); 
}

//
// 
//
function ResMenuNewRes() {
	fn_HideMenus();
	parent.location.href = "?sid=" + lngSystemID + "&Action=NewReservation&Date=" + ResDateHold + "&PeriodID=" + ResPeriodIDHold + "&RoomID=" + ResRoomIDHold;
}

//
// 
//
function SendMessage(ContactID) {
	// fn_HideMenus();
	// new 2008-08-11
	var transaction = YAHOO.util.Connect.asyncRequest('GET', 'index.asp?sid=' + lngSystemID + '&Action=SendMessage&ContactID=' + ContactID, callback_SendMessage, null); 
}

//
// 
//
function SendMessageSend(ContactID) {
	// fn_HideMenus();
	// new 2008-08-11
	var Subject = $('inpMessageSubject').value;
	var Body = $('txtMessageBody').value;
	// alert("subject is " + $('inpMessageSubject').value);
	var transaction = YAHOO.util.Connect.asyncRequest('GET', 'index.asp?sid=' + lngSystemID + '&Action=SendMessageSend&ContactID=' + ContactID + "&Subject=" + Subject + "&Body=" + Body, callback_SendMessageSend, null); 
	// dlgSendMessage.destroy();
}

var requester = null;
var tg = null;

//
//
//
function fn_cancelRejection() {

	dlgReject1.hide();
	
}

//
//
//
function fn_Reject(RequestID) {
	var Email = $('inpEmail').value;
	var Message = $('txtMessage').value;
	// alert(Email);
	// alert(Message);
	window.location.href = "?sid=" + lngSystemID + "&Action=RejectRequest&RequestID=" + RequestID + "&Email=" + Email + "&Message=" + Message;
}
//
// new 2008-08-14
// reject request
var dlgReject1
function fn_initiateRejection(RequestID, Email) {

	dlgReject1 = new YAHOO.widget.SimpleDialog("dlgReject1",
		{
			close:true,
			visible:false,
			draggable:true,
			modal:false,
			fixedcenter:true,
			effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration: 0.3},
			constraintoviewport:true
		}
	);
	dlgReject1.setHeader("<span class='cSprite sprite-minus-circle'></span>Reject Request (BETA)");
	var message;
	message = "<div style='width: 100%;'>If you wish to send the requester a message, type that here.<br>If you leave the message blank, no email message will be sent.</div>"
	message += "<form style='margin: 10px;'><div>To:<input id=inpEmail type=text style='width: 100%; display: block;' value='" + Email + "'></div>"
	message += "<div>Message:<textarea id=txtMessage style='width: 100%; display: block;'></textarea></div>"
	message += "</form>"
	message += "<div style='text-align: right; margin: 10px;'><a class='cButton sprite-minus-circle' onclick='fn_Reject(" + RequestID + ");'>Reject Request</a>"
	message += "<a class='cButton sprite-cross' onclick='fn_cancelRejection();'>Cancel</a></div>"
	message += "<div>A copy of the Request will be attached to the email.</div>"
	// message = "Apologies - this feature does not work yet. Coming Soon!"
	dlgReject1.setBody(message);
	// dlgReject1.cfg.setProperty("buttons",[ {text:"OK", handler:handleSDOK, isdefault:true } ]);
	dlgReject1.render(document.body);
	dlgReject1.show();
}

//
// used 2008
//
var callback_ChangeField = {
	success: function(o) {
		// alert("success!");
		var elClicky = o.argument.target;
		$D.replaceClass(elClicky, 'cPending', 'cSuccess');
		if (o.responseText.length === 0) {
			$D.addClass(elClicky,'cCNone');
			o.argument.value.innerHTML = 'None';
		}
		else {
			if (o.argument.select) { 
				o.argument.DefaultEl.innerHTML = o.argument.select.value;
			}
			else {
				$D.removeClass(elClicky,'cCNone');
				o.argument.value.innerHTML = o.responseText;
			}
		}
	},
	failure: function(o) {
		alert("async error");
	},
	argument: {},
	timeout: 10000
};

var timHoldTable, timHoldId, timHoldField, timHoldDefaultEl, timHoldThis;

//
// new - the YUI way! Jan 2007
//
function fn_ChangeField(e) {
	var Table = $$('cT','',this)[0].innerHTML;
	var ID = $$('cI','',this)[0].innerHTML;
	var Field = $$('cF','',this)[0].innerHTML;
	var DefaultEl = $$('cV','',this)[0];
	var Type = $$('cY','',this)[0].innerHTML;
	var Select; // don't get value until we get to the switch
	timHoldDefaultEl = DefaultEl;
	var iDefault;
	if (DefaultEl) { iDefault = DefaultEl.innerHTML; }
	var transaction;
	var querystring;
	// doesn't seem to be used anymore: var Response;
	
	// erase Default if it equals NONE
	if ($D.hasClass(this, 'cCNone')) { iDefault = ''; }
	
	// dlgClicky.render(document.body);
	timHoldTable = Table;
	timHoldId = ID;
	timHoldField = Field;
	timHoldThis = this;
	
	$D.replaceClass(Select, 'cSuccess', 'cPending');
	
	switch(Type) {
		case "DropDown": 
			// alert("dropdown test");
			Select = $$('clickySelect','',this)[0];
			if (Select.value != iDefault) { 
				querystring = "?sid=" + lngSystemID + "&Action=ChangeFieldAJAX&Table=" + timHoldTable + "&ID=" + timHoldId + "&Field=" + timHoldField + "&Value=" + Select.value;
				callback_ChangeField.argument.target = timHoldThis;
				callback_ChangeField.argument.value = timHoldDefaultEl;
				callback_ChangeField.argument.select = Select;
				callback_ChangeField.argument.DefaultEl = DefaultEl;
				transaction = YAHOO.util.Connect.asyncRequest('GET', querystring, callback_ChangeField); 
				// alert("change " + Default + " to " + Select);
			}
			break;
		case "TrueFalse": 
			// timHoldDefaultEl.innerHTML = 'updating...';
			if (iDefault == "True") {iDefault = "False";} else {iDefault = "True";}
			querystring = "?sid=" + lngSystemID + "&Action=ChangeFieldAJAX&Table=" + timHoldTable + "&ID=" + timHoldId + "&Field=" + timHoldField + "&Value=" + iDefault;
			callback_ChangeField.argument.target = timHoldThis;
			callback_ChangeField.argument.value = timHoldDefaultEl;
			transaction = YAHOO.util.Connect.asyncRequest('GET', querystring, callback_ChangeField); 
			break;
		default: 
			dlgClicky.cfg.setProperty("context", [this,"tl","bl"]); 
			dlgClicky.show();
			$("objNewValue").value = iDefault;
			$("objNewValue").focus();
			$("objNewValue").select();
	}

}

//
// new - flickr style
// 2008.08.28
//
function fn_EditField(e) {
	var Table = $$('cT','',this)[0].innerHTML;
	var ID = $$('cI','',this)[0].innerHTML;
	var Field = $$('cF','',this)[0].innerHTML;
	var DefaultEl = $$('cV','',this)[0];
	var Type = $$('cY','',this)[0].innerHTML;
	var Select; // don't get value until we get to the switch
	timHoldDefaultEl = DefaultEl;
	var iDefault;
	if (DefaultEl) { iDefault = DefaultEl.innerHTML; }
	var transaction;
	var querystring;
	// doesn't seem to be used anymore: var Response;
	
	// erase Default if it equals NONE
	if ($D.hasClass(this, 'cCNone')) { iDefault = ''; }
	
	// dlgClicky.render(document.body);
	timHoldTable = Table;
	timHoldId = ID;
	timHoldField = Field;
	timHoldThis = this;
	
	$D.replaceClass(Select, 'cSuccess', 'cPending');
	
	switch(Type) {
		case "DropDown": 
			// alert("dropdown test");
			Select = $$('clickySelect','',this)[0];
			if (Select.value != iDefault) { 
				querystring = "?sid=" + lngSystemID + "&Action=ChangeFieldAJAX&Table=" + timHoldTable + "&ID=" + timHoldId + "&Field=" + timHoldField + "&Value=" + Select.value;
				callback_ChangeField.argument.target = timHoldThis;
				callback_ChangeField.argument.value = timHoldDefaultEl;
				callback_ChangeField.argument.select = Select;
				callback_ChangeField.argument.DefaultEl = DefaultEl;
				transaction = YAHOO.util.Connect.asyncRequest('GET', querystring, callback_ChangeField); 
				// alert("change " + Default + " to " + Select);
			}
			break;
		case "TrueFalse": 
			// timHoldDefaultEl.innerHTML = 'updating...';
			if (iDefault == "True") {iDefault = "False";} else {iDefault = "True";}
			querystring = "?sid=" + lngSystemID + "&Action=ChangeFieldAJAX&Table=" + timHoldTable + "&ID=" + timHoldId + "&Field=" + timHoldField + "&Value=" + iDefault;
			callback_ChangeField.argument.target = timHoldThis;
			callback_ChangeField.argument.value = timHoldDefaultEl;
			transaction = YAHOO.util.Connect.asyncRequest('GET', querystring, callback_ChangeField); 
			break;
		default: 
			dlgClicky.cfg.setProperty("context", [this,"tl","bl"]); 
			dlgClicky.show();
			$("objNewValue").value = iDefault;
			$("objNewValue").focus();
			$("objNewValue").select();
	}

}

//
// new - the YUI way! Jan 2007
// called by Tab handler
//
function fn_ChangeField2(clicky) {
	var Table = $$('cT','',clicky)[0].innerHTML;
	var ID = $$('cI','',clicky)[0].innerHTML;
	var Field = $$('cF','',clicky)[0].innerHTML;
	var DefaultEl = $$('cV','',clicky)[0];
	timHoldDefaultEl = DefaultEl;
	var Default = DefaultEl.innerHTML;
	var transaction;
	var querystring;
	// doesn't seem to be used anymore: var Response;
	
	// erase Default if it equals NONE
	if ($D.hasClass(clicky, 'cCNone')) { Default = ''; }

	// dlgClicky.render(document.body);
	timHoldTable = Table;
	timHoldId = ID;
	timHoldField = Field;
	timHoldThis = clicky;
	dlgClicky.cfg.setProperty("context", [clicky,"tl","bl"]); 
	dlgClicky.show();
	$("objNewValue").value = Default;
	$("objNewValue").focus();
	$("objNewValue").select();

}

//
//
//
function UpdateRoomColorCode(lngRoomID, strOldColorCode) {
	var url = 'popup-color.asp?Method=FacilityColor&RoomID=' + lngRoomID;
	// alert(url);
	newwindow = window.open(url,'name','height=200,width=200,top=200,left=400,resizable=no,scrollbars=no,menubar=no,toolbar=no,status=no,location=no');
	if (window.focus) {
		newwindow.focus();
	}
	return false;
	//alert("do we get this far?");
	//var strColorCode = prompt("Change Color Code to: ", strOldColorCode);
	//strColorCode = strColorCode.replace("#", "%23");
	//if (strColorCode !== "")
	//window.location.replace("?Action=UpdateRoomColorCode&ID=" + lngRoomID + "&Color=" + strColorCode); 
}

//
//
//
function requestFormHandler() {

	var Message = "";
	var blnFormIsValid = true;
	
	// alert("starting form handler");
	
	if ($('objName').value === "") {
		$('objName').style.backgroundColor = "yellow";
		blnFormIsValid = false;
		Message = Message + "<li>Please provide your name.</li>";
	} 
	else {
		$('objName').style.backgroundColor = "";
	}

	if ($('objConfirmationEmail').value === "") {
		$('objConfirmationEmail').style.backgroundColor = "yellow";
		blnFormIsValid = false;
		Message = Message + "<li>Please provide your email address.</li>";
	}
	else {
		$('objConfirmationEmail').style.backgroundColor = "";
	}
	
	if ($('objConfirmationEmail').value.indexOf('@') > -1) {
		$('objConfirmationEmail').style.backgroundColor = "yellow";
		blnFormIsValid = false;
		Message = Message + "<li>Do not include '@' or your email domain in the first email field.</li>";
	}
	else {
		$('objConfirmationEmail').style.backgroundColor = "";
	}	
	
	if ($('objEmailDomain').value === "") {
		$('objEmailDomain').style.backgroundColor = "yellow";
		blnFormIsValid = false;
		Message = Message + "<li>Please provide your email domain address (the part after the '@').</li>";
	}
	else {
		$('objEmailDomain').style.backgroundColor = "";
	}
	
	if ($('objDate').value === "") {
		$('objDate').style.backgroundColor = "yellow";
		blnFormIsValid = false;
		Message = Message + "<li>Please provide date information.</li>";
	}
	else {
		$('objDate').style.backgroundColor = "";
	}

	if ($('objPeriod').value === "") {
		$('objPeriod').style.backgroundColor = "yellow";
		blnFormIsValid = false;
		Message = Message + "<li>Please provide time information.</li>";
	}
	else {
		$('objPeriod').style.backgroundColor = "";
	}

	if (blnFormIsValid === false) {
		$('objErrorMessage').innerHTML = "Please fill in the required information before submitting your Request.<BR>&nbsp;" + Message;
		$('objTopOfPage').scrollIntoView(true);
	}

	return (blnFormIsValid);
	
}

//
//
//

//
// YUI stuff from index
//
// step 1: define the object so it is global
var panel_seven;
var panel_colorPop;
var dlgSimple;
var handleSDOK = function(){ this.cancel(); };
var handleSDDestroy = function() {
	this.cancel();
	this.destroy();
}

var newContextMenu;
var newContextMenuItem1;
var colorHold, heightHold, overflowHold, zIndexHold, widthHold;
	
function submitCallback(obj) {
	// alert("Submission succeeded: " + obj.responseText);
	dlgSimple.setHeader("Success");
	dlgSimple.setBody(obj.responseText);
	dlgSimple.cfg.setProperty("icon",YAHOO.widget.SimpleDialog.ICON_INFO);
	dlgSimple.cfg.setProperty("buttons",[ {text:"OK", handler:handleSDOK, isdefault:true } ]);
	// dlgSimple.render(document.body);
	dlgSimple.show();
}

//
// called when someone asks for a Note
//
var callback_Note = {
	success: function(o) { 
		// dlgSimple.hide();
		dlgSimple.setHeader("Reservation Note");
		dlgSimple.setBody(o.responseText);
		dlgSimple.cfg.setProperty("buttons",[ {text:"Done", handler:handleSDOK, isdefault:true } ]);
		dlgSimple.show();
	},
	failure: function(o) { alert("There has been an error and that feature is not available at this time." + o.responseText); }
};

//
// called when someone asks for Reservation Details
//
var callback_ResMenuDetails = {
	success: function(o) { 
		// dlgSimple.hide();
		dlgSimple.setHeader("<span class='cSprite sprite-ticket'>Reservation Details</span>");
		dlgSimple.setBody(o.responseText);
		dlgSimple.cfg.setProperty("buttons",[ {text:"Done", handler:handleSDOK, isdefault:true } ]);
		dlgSimple.show();
	},
	failure: function(o) { alert("There has been an error and that feature is not available at this time." + o.responseText); }
};

//
// called when someone asks for Matching Request
//
var callback_ResMenuRequestMatch = {
	success: function(o) { 
		// dlgSimple.hide();
		dlgSimple.setHeader("Matching Request");
		dlgSimple.setBody(o.responseText);
		dlgSimple.cfg.setProperty("buttons",[ {text:"OK", handler:handleSDOK, isdefault:true } ]);
		dlgSimple.show();
	},
	failure: function(o) { alert("There has been an error and that feature is not available at this time." + o.responseText); }
};

//
// called when someone asks for Matching Request   frank
//
var dlgSendMessage
var callback_SendMessage = {
	success: function(o) { 
		// dlgSimple.hide();
		dlgSendMessage = new YAHOO.widget.SimpleDialog("dlgSendMessage",
			{
				close: true,
				visible: false,
				draggable: true,
				modal: false,
				fixedcenter: true,
				effect: {effect:YAHOO.widget.ContainerEffect.FADE, duration: 0.3},
				constraintoviewport: true
			}
		);
		dlgSendMessage.setHeader("<span class='cSprite sprite-mail'></span>Send Message (BETA)");
		dlgSendMessage.setBody(o.responseText);
		// dlgSendMessage.cfg.setProperty("buttons",[ {text:"OK", handler:handleSDOK, isdefault:true } ]);
		dlgSendMessage.cfg.queueProperty("width", "400px");
		dlgSendMessage.render(document.body);
		dlgSendMessage.show();
		
	},
	failure: function(o) { alert("There has been an error and that feature is not available at this time." + o.responseText); }
};

//
// called when someone asks for Matching Request
//
var dlgSendMessageSend
var callback_SendMessageSend = {
	success: function(o) { 
		// dlgSimple.hide();
		dlgSendMessageSend = new YAHOO.widget.SimpleDialog("dlgSendMessageSend",
			{
				close:true,
				visible:false,
				draggable:true,
				modal:false,
				fixedcenter:true,
				effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration: 0.3},
				constraintoviewport:true
			}
		);
		dlgSendMessageSend.setHeader("<span class='cSprite sprite-mail'></span>Message Sent (BETA)");
		dlgSendMessageSend.setBody(o.responseText);
		dlgSendMessageSend.render(document.body);
		dlgSendMessageSend.cfg.setProperty("buttons",[ {text:"OK", handler:handleSDOK, isdefault:true } ]);
		// setProperty comes AFTER a render
		dlgSendMessageSend.show();
		dlgSendMessage.destroy();
		return false;
	},
	failure: function(o) { alert("There has been an error and that feature is not available at this time." + o.responseText); }
};

//
// called when request returns from adding/removing flag from reservation menu
//
var callback_ResMenuFlagComplete = {
	success: function(o) { 
		fn_RefreshReservations();
	},
	failure: function(o) { alert("There has been an error and that feature is not available at this time." + o.responseText); }
};

//
// you clicked on a reservation whose click event was created by an event listener
//
function fn_ReservationMenu(e, resDetails) { 
	
	clearTimeout(timeout);
	fn_HideMenus();
	
	// global variables
	ResFlagHold = this.flags;
	ResIDHold = this.id;
	ResDateHold = this.date;
	ResPeriodIDHold = this.periodId;
	ResRoomIDHold = this.locationId;

	var objReservationMenu = $('objReservationMenu');
	objReservationMenu.style.top = $E.getPageY(e) + 'px';  
	objReservationMenu.style.left = $E.getPageX(e) + 'px';
	objReservationMenu.style.position = "absolute";
	objReservationMenu.style.display = "inline";  
	
	// prevents the EmptyCellMenu from showing also
	$E.stopEvent(e);
		
	// clear all menus after 7 seconds
	timeout = setTimeout(fn_HideMenus, 7000);

}

//
// change background color a hovered reservation
//
function hoverReservation(e) {
	// pukey green
	var offsetHeightHold;
	colorHold = this.style.backgroundColor;
	this.style.backgroundColor = '#bbddbb';
	heightHold = this.style.height;
	offsetHeightHold = this.offsetHeight;
	this.style.height = '';
	if (this.offsetHeight < offsetHeightHold) { this.style.height = heightHold; }
	overflowHold = this.style.overflow;
	this.style.overflow = 'visible';
	zIndexHold = this.style.zIndex;
	this.style.zIndex = 8000;
	// now change everything with the same reservationGroupId
	//widthHold = this.style.width;
	//this.style.width = '';
}

//
//
//
function unHoverReservation(e) {
	this.style.backgroundColor = colorHold;
	this.style.height = heightHold;
	this.style.overflow = overflowHold;
	this.style.zIndex = zIndexHold;
	//this.style.width = widthHold;
}

//
//
//
function ResDetails(id, date, periodId, locationId, groupId, flags) {
	this.id = id;
	this.date = date;
	this.periodId = periodId;
	this.locationId = locationId;
	this.groupId = groupId;
	this.flags = flags;
}

//
// called when Reservation JSON data comes back successfully
// 
var callbackJSON = {
	success: function(o) { 
		
		var objLeftoverCell = $("objLeftovers");
		var objLeftoverTable = 	$("objLeftoverTable");
		var oContainer;
		var oRoom;
		var oDate;
		var oPreviousStartMinute = '';
		var oPreviousEndMinute = '';
		var xy;
		var flag;
		var placeInLeftover = false;

		// alert(o.argument.timtest);

		function fn_placeRes(res, oDestination) {
			var objNewReservationDiv = document.createElement("DIV");
			var resText = '';
			var oContainer;
			var oRoom;
			var resColor;
			var resLocation;
			var resPeriod;
			var strPlural;
			var resParentPeriod;
			var resChildPeriod;
			
			checkpoint = 100;
			
			// build resText
			// need to loop for all flags
			if (res.flags) {
				for (flag in res.flags) {
					// resText += '<img align=right src=flag_' + res.flags[flag] + '.png>';
					resText += '<span class="cSprite sprite-flag-' + res.flags[flag] + '" style="float: right;">&nbsp;</span>';
				}
			}
			checkpoint = 101;
			
			if (root.view == 'List') {
				//fnAlert('[' + res.periodId + ']');
				if (res.periodId == -3) {
					resText += '<div class=formatted>After School</div>';
				} else if (res.periodId === 0) {
					resText += '<div class=formatted>Before School</div>';
				} else if (res.periodId == -1) {
					resText += ''; // do nothing for General Message
				} else if (res.startMinute == -1) {
					resText += '<div class=formatted>Period does not exist today</div>';
				} else {
					//resText += '{' + oPreviousStartMinute + '}';
				//	resText += '[';
				//	resTest += oPreviousRes.startMinute + ']';
				//	if ((res.startMinute == oPreviousRes.startMinute) && (res.endMinute == oPreviousRes.endMinute)) {
				//		resText += '..';
				//	} else {
				//		resText += '--';
				//	}
					resText += '<div class=formatted>' + fn_minuteToTime(res.startMinute) + '-' + fn_minuteToTime(res.endMinute) + '</div>';
					// hold on to minutes to compare with next reservation
					oPreviousRes = res;
					//resText += '[' + oPreviousStartMinute + ']';
				}
			}
			
			checkpoint = 102;
			
			if ((root.view == 'Period' || root.view == 'Kiosk') && res.periodId == -2) {
				resText += '<div class=formatted>' + fn_minuteToTime(res.startMinute) + '-' + fn_minuteToTime(res.endMinute) + '</div>';
			}
			
			checkpoint = 103;
			
			if (res.locationId) {
				resLocation = fn_locationInfo(res.locationId); 
				try {
					resColor = resLocation.color;
					// HA! IE does not like color GREY - change to GRAY
					if (resColor.toLowerCase() == 'grey') { resColor = 'gray'; }
					resText += '<div class=clsResLocation style="background-color: ' + resColor + ';">' + resLocation.name 
					resText += '</div>';
					if (!resLocation.public && !(root.view=='RoomByRoom')) { resText += ' <span class=cPrivateTag>P</span>'; }
				}
				catch(ex) {
					resText += '';
					// for testing purposes:
					// resText += '<div class=clsResLocation>No Location</div>';
				}
			}
			
			checkpoint = 104;
			
			if (res.periodId) {
				// alert("aaa");
				// resPeriod = fn_periodInfo(res.periodId);
				resText += '<div class=clsOwnPeriod>' + res.periodId + "</div>";
			}
			
			checkpoint = 105;
			
			// added 2008-10-04
			resPeriod = fn_periodInfo(res.periodId);
			
			if (resPeriod.parentPeriodId) {
				// alert("has parent");
				resParentPeriod = fn_periodInfo(resPeriod.parentPeriodId);
				resText += '<div class=clsParentPeriod>' + resParentPeriod.shortName + "</div>";
				if (root.hideHalfPeriods) {
					resText += '<div class=clsOwnPeriodName>' + resPeriod.shortName + "</div>";
				}
			}
			
			checkpoint = 106;
			
			if (resPeriod.childPeriodId) {
				// alert("has child");
				for (var yy = 0; yy < resPeriod.childPeriodId.length; yy++) {
					resChildPeriod = fn_periodInfo(resPeriod.childPeriodId[yy]);
					resText += '<div class=clsChildPeriod>' + resChildPeriod.shortName + "</div>";
				}
				if (!root.hideHalfPeriods) {
					resText += '<div class=clsOwnPeriodName>' + resPeriod.shortName + "</div>";
				}
				//resText += 'child';
			}
			
			checkpoint = 107;
			
			if (res.stations && root.view != 'RoomByRoom') {
				resLocation = fn_locationInfo(res.locationId); 
				if (res.stations != 1) { strPlural = 's'; } else { strPlural = ''; }
				resText += '<div class=clsStations>' + res.stations + ' ' + resLocation.stationName + strPlural + '</div>';
			}
			
			checkpoint = 108;
			
			if (res.contact) {
				resText += '<div class=clsResUser>' + res.contact + '</div>';
			}
			
			checkpoint = 109;
			
			if (res.staff) {
				resText += '<div class=clsResStaff>' + res.staff + '</div>';
			}
		//	if (res.startMinute) {
		//		resText += '<div class=clsResStartMinute>' + res.startMinute + '</div>';
		//	}

			checkpoint = 110;
			
			if (res.notes) {
				resText += '<div class=clsResNotes>' + res.notes + '</div>';
			}
			
			checkpoint = 111;

			if (res.custom) {
				resText += '<div class=clsResNotes>' + res.custom.replace(/\+/g, " ") + '</div>';
				}
		//		for (var y = 0; y < res.custom.length; y++) {
		//			resText += '<div class=clsResNotes>' + res.custom[y].replace(/\+/g, " ") + '</div>';
		//		}
			// RoomByRoom - move stations to bottom

			checkpoint = 112;
			
			if (res.stations && root.view == 'RoomByRoom') {
				resText += '<div class=clsStations>' + res.stations + '</div>';
			}
			
			checkpoint = 113;

			if (oDestination) {
				checkpoint = 200;
				// if the table cell exists, append DIV to the table cell
				if (root.view == 'RoomByRoom') {
					checkpoint = 201;
					oRoom = $('oRoom_' + res.date + '_' + res.locationId);
					// new 2008-04-26
					// must check that Room exists - if the room is not active, the script was stalling
					if (oRoom) {
						oDestination = oRoom.parentNode;
						oDestination.appendChild(objNewReservationDiv);
						if (res.locationId != -1) {
							// only apply styles if in the RBR Grid; otherwise General Message
							// that appears below the date with no special formatting
							objNewReservationDiv.style.top = (oRoom.offsetTop-5) + 'px';
							objNewReservationDiv.style.height = '24px';
							iLeft = (9.5+(res.startMinute - root.startTime)/(root.endTime - root.startTime)*90);
								objNewReservationDiv.style.left = iLeft + '%';
							iWidth = (res.endMinute-res.startMinute)/(root.endTime-root.startTime)*90-0.5;
							// was 90;
							//
							// if endTime spills over
							if (res.endMinute > root.endTime) {
								// endTime is spilling over
								// iWidth = (res.endMinute-res.startMinute)/(root.endTime-root.startTime)*90-0.5;
								iWidth = (root.endTime-res.startMinute)/(root.endTime-root.startTime)*90-0.5;
								//alert("abab");
								resText = '<div style="color: red; font-size: 8pt; font-weight: bold;">Until ' + timeTextFromMinutes(res.endMinute) + '</div>' + resText;
								//alert("cdcd");
								// $D.setStyle(objNewReservationDiv, 'color', 'red');
							}
							//
							//alert(iWidth);
							//
							// added because some widths (of invisible items? suddenly became -0.5
							if (iWidth < 0) { iWidth = 2; }
							//
							objNewReservationDiv.style.width = iWidth + '%';
							objNewReservationDiv.style.backgroundColor = String(resColor);
							$D.setStyle(objNewReservationDiv, 'opacity', 0.75);
							
							// $D.setStyle(objNewReservationDiv, 'margin', '0px');
						}
					}
					else {
						// need to add code to append to leftover bin
					}
					//resText = res.startMinute + resText;
				} else {
					checkpoint = 202;
					oDestination.appendChild(objNewReservationDiv);
					// code was here
				}
			} else {
				// otherwise add date/time info and append it to the leftover bin
				checkpoint = 203;
				resPeriod = fn_periodInfo(res.periodId);
				fnAlert('[p:' + res.periodId + ']');
				if (res.date) { fnAlert('RD'); } else { fnAlert('noRD'); }
				if (resPeriod.shortName) { fnAlert('SN'); } else { fnAlert('noSN'); }
				resText = '<div class=clsResDate>' + res.date + '</div><div class=clsResPeriod>' + resPeriod.shortName + '</div>' + resText;
				objLeftoverCell.appendChild(objNewReservationDiv);
				// Leftover table is hidden until really needed
				objLeftoverTable.style.display = 'block';
			}
		
			if (document.fetchReservationGroupID) {
				if (res.groupId == document.fetchReservationGroupID) {
					objNewReservationDiv.style.backgroundColor = 'yellow';
				} else {
					// objNewReservationDiv.style.backgroundColor = 'aqua';
				}
			}	
					
			// throw the reservation HTML into the new DIV
			checkpoint = 204; 
			objNewReservationDiv.innerHTML = resText;
			checkpoint = 205; 
			$D.addClass(objNewReservationDiv, 'clsRes');
			// event listener to pop a menu
			checkpoint = 206; 
			resDetails = new ResDetails(res.id, res.date, res.periodId, res.locationId, res.groupId, res.flags);
			checkpoint = 207; 
			$E.addListener(objNewReservationDiv, "click", fn_ReservationMenu, resDetails, true);
		
			// event listeners to change reservation background color on hover
			checkpoint = 208; 
			$E.addListener(objNewReservationDiv, "mouseover", hoverReservation);
			checkpoint = 209; 
			$E.addListener(objNewReservationDiv, "mouseout", unHoverReservation);
			
			// new: delete formatted time if same as previous
		//	if (root.view == 'List') {
		//		objNewReservationDiv.innerHTML = objNewReservationDiv.innerHTML + ".";
		//	}
		}

		// modify panel
		fnAlert('Reservations received...');
		
		// this should not take more than 15 seconds - set a timeout in case it does
		timeoutProcessingError = window.setTimeout(fn_ResProcessingError, 30000);
		
		//
		// return a location object based on locationId
		//
		function fn_locationInfo(a_locationId) {
			for (var xx = 0; xx < fsLocations.settings.length; xx++) {
				if (fsLocations.settings[xx].id == a_locationId) {
					return fsLocations.settings[xx];
				}
			}
		}
		
		//
		// return a location object based on locationId
		//
		function fn_bellScheduleInfo(a_date, a_periodId) {
			for (var xx = 0; xx < fsBellSchedules.settings.length; xx++) {
				if (fsBellSchedules.settings[xx].id == a_locationId) {
					return fsBellSchedules.settings[xx];
				}
			}
		}
		
		//
		// return a period object based on periodId
		//
		function fn_periodInfo(a_periodId) {
			// alert(a_periodId);
			for (var xx = 0; xx < fsPeriods.settings.length; xx++) {
				if (fsPeriods.settings[xx].id == a_periodId) {
					return fsPeriods.settings[xx];
				}
			}
		}
		
		//
		//
		//
		function fn_sortByStartMinute(a, b) {
			// return 0;
			// fnAlert("c");
			if (a.startMinute && b.startMinute) {
				// startMinute exists for both - otherwise IE was hanging, 
				// but now they are not sorted by location, which is OK, 
				// since Locations are in different Kiosk rows!!
				var x = a.startMinute;
				var y = b.startMinute;
				var resLocation;
				// if (console) { console.log("d"); }
				if (x == y) {
				// if (console) { console.log("e"); }
					x = a.endMinute;
					y = b.endMinute;
					if (x == y && a.locationId && b.locationId) {
						// if (console) { console.log("3rd sort start"); }
						xLocation = fn_locationInfo(a.locationId);
						yLocation = fn_locationInfo(b.locationId);
						if (xLocation && yLocation) {
							x = xLocation.roomorder;
							y = yLocation.roomorder;
						} else {
							x = 0;
							y = 0;
						}
						// if (console) { console.log("3rd sort end"); }			
					}			
				}
			} else {
				// startMinute does NOT exist
				x = 0;
				y = 0;
			}
			// if (console) { console.log("[" + x + "," + y + "]"); }
			return x - y;
			// if (console) { console.log("h"); }
		}
		
		//
		//
		//
		function fn_sortByRoomOrder(a, b) {
			//return 0;
			var resLocation;
			var xLocation = fn_locationInfo(a.locationId);
			var yLocation = fn_locationInfo(b.locationId);
			if (xLocation && yLocation) {
				x = xLocation.roomorder;
				y = yLocation.roomorder;
			} else {
				x = 0;
				y = 0;
			}
			return x - y;
		}
		
		var i;
		var tableCellId;
		
		// now global
		checkpoint = 800;
		// alert(o.responseText);
		root = new Function("return " + o.responseText)();
		checkpoint = 801;
		
		if (root) { 
			fnAlert('Reservations are valid...');
		} else {
			fnAlert('Reservations are NOT valid.');
			fn_ResProcessingError();
		}			

		// remove any existing reservations
		// in the future - check if there even ARE any changes, if not, exit before deleting
		var OldReservations = $$('clsRes','div');
		for (i = 0; i < OldReservations.length; i++) {
			OldReservations[i].parentNode.removeChild(OldReservations[i]);
		}

		// hide LeftOver Bin in case we cleared all those reservations in some other window
		// objLeftoverTable.style.display = 'none';
			
		// and delete any message boxes
		// var OldMessages = $$('clsMessageBox','div')
		// for (i = 0; i < OldMessages.length; i++) {
		//	OldMessages[i].parentNode.removeChild(OldMessages[i]);
		// }

		if (root.view == 'Kiosk') { 
			checkpoint = 300;
			// start the auto refresh chain
			clearTimeout(timeoutRefresh);
			timeoutRefresh = window.setTimeout(fn_AutoRefreshReservations, 120000);
		}		
		
		if (root.reservations) {
			
			checkpoint = 400;
			var reservationsA = root.reservations;
			checkpoint = 401;
			if (root.view != 'RoomByRoom') {
				// 
				// sort reservations (unless RoomByRoom)
				//
				checkpoint = 402;
				oDiv = document.createElement('div');
				checkpoint = 403;
				oDiv.innerHTML = 'Sorting Reservations...';
				checkpoint = 404;
				panel_wait.appendToBody(oDiv);
				checkpoint = 405;
				if (root.view == 'Period') {
					checkpoint = 406;
					reservationsA.sort(fn_sortByRoomOrder);
				} else {
					checkpoint = 407;
					// fnAlert("a");
					reservationsA.sort(fn_sortByStartMinute);
					// fnAlert("b");
					checkpoint = 408;
				}
			}
	
			// alert('here');
			checkpoint = 499;
			 
			// 
			// Process Reservations
			//
			oDiv = document.createElement('div');
			oDiv.innerHTML = 'Processing Reservations...';
			panel_wait.appendToBody(oDiv);
			
			checkpoint = 500; 
			
			for (var x = 0; x < reservationsA.length; x++) {
				
				checkpoint = 501;
				res = root.reservations[x];
			
				resPeriod = fn_periodInfo(res.periodId);
			
			//	if (resPeriod.parentPeriodId) {
			//		alert("1261 has parent");
			//		resParentPeriod = fn_periodInfo(resPeriod.parentPeriodId);
			//	}
			
			//	if (resPeriod.childPeriodId) {
			//		alert("1266 has child");
			//		for (var yy = 0; yy < resPeriod.childPeriodId.length; yy++) {
			//			resChildPeriod = fn_periodInfo(resPeriod.childPeriodId[yy]);
			//			resText += '<div class=clsChildPeriod>' + resChildPeriod.shortName + "</div>";
			//		}
			//		//resText += 'child';
			//	}
			
				// build the target table ID from reservation data
				if (root.view == 'Kiosk') {
					checkpoint = 502;
					tableCellId = "Location_" + res.locationId + "_Period_" + res.periodId;
					if ($(tableCellId)) {
						// actual period id
						fn_placeRes(res, $(tableCellId));
					} 
					else if (resPeriod.parentPeriodId) {
						tableCellId = "Location_" + res.locationId + "_Period_" + resPeriod.parentPeriodId;
						if ($(tableCellId)) {
							// parent period exists
							fn_placeRes(res, $(tableCellId));
						} 
					} 
					else if (resPeriod.childPeriodId) {
						// new 2008-08-11
						// if there was a child period in the JSON data, execution went into this code, and
						// never went to the final ELSE to place in leftover bin
						// just because child periods exist, doesn't mean they exist on this day.
						// will the same problem happen in parent period above?
						placeInLeftover = true;
						for (xy = 0; xy < resPeriod.childPeriodId.length; xy++) {
							tableCellId = "Location_" + res.locationId + "_Period_" + resPeriod.childPeriodId[xy];
							if ($(tableCellId)) {
								// child period exists
								fn_placeRes(res, $(tableCellId));
								placeInLeftover = false;
							}
						}
						// new 2008-08-11 - was placing in leftover bin twice when there are multiple child periods
						// so i added the placeInLeftover flag
						if (placeInLeftover) {
							fn_placeRes(res);
						}	
					} 
					else {
						// just places in leftover?
						fn_placeRes(res);
					}
					checkpoint = 503;
				}
				if (root.view == 'Period') {
					tableCellId = "cell_" + res.date + "_" + res.periodId;
					if ($(tableCellId)) {
						fn_placeRes(res, $(tableCellId));
					} 
					else if (resPeriod.parentPeriodId) {
						// try the parent period
						tableCellId = "cell_" + res.date + "_" + resPeriod.parentPeriodId;
						if ($(tableCellId)) {
							fn_placeRes(res, $(tableCellId));
						} 
					} 
					else if (resPeriod.childPeriodId) {
						// new 2008-08-11
						// if there was a child period in the JSON data, execution went into this code, and
						// never went to the final ELSE to place in leftover bin
						// just because child periods exist, doesn't mean they exist on this day.
						// will the same problem happen in parent period above?
						placeInLeftover = true;
						for (xy = 0; xy < resPeriod.childPeriodId.length; xy++) {
							tableCellId = "cell_" + res.date + "_" + resPeriod.childPeriodId[xy];
							if ($(tableCellId)) {
								//child period exists
								fn_placeRes(res, $(tableCellId));
								placeInLeftover = false;
							} 
						}
						// new 2008-08-11 - was placing in leftover bin twice when there are multiple child periods
						// so i added the placeInLeftover flag
						if (placeInLeftover) {
							fn_placeRes(res);
						}
					} 
					else {
						// just place in leftover
						fn_placeRes(res);
					}
				}
				if (root.view == 'List') {
					tableCellId = "cell_" + res.date + "_-2";
					if ($(tableCellId)) {
						fn_placeRes(res, $(tableCellId));
					} 
					else {
						// just place in leftover
						// works as of 2008-08-11
						fn_placeRes(res);
					}
				}
				if (root.view == 'RoomByRoom') {
					// get date of all oDate containers
					oContainer = $('oContainer' + res.date);
					if (oContainer) { 
						// just deleted 2008-08-11 (didn't appear to be doing anything):
						// oRoom = document.getElementById('oRoom_' + res.date + '_' + res.locationId);
						// deleted a long time ago 
						// oRoom = 'oRoom' + res.locationId;
						if (res.startMinute == -1) {
							// there is no period for this bell schedule, place in leftover bin
							fn_placeRes(res);
						}
						else {
							// period exists - still need to check if time is out of view
							fn_placeRes(res, oContainer);
						}
					} 
					else {
						fn_placeRes(res);
					}
				}
			}
			checkpoint = 1000;
			// dismiss the loading panel
			try { 
				panel_wait.hide();
			}
			catch(err) {
				// do nothing;
				checkpoint = 1001;
			}
			checkpoint = 1002;
		} else {
			// no reservations!
			oDiv = document.createElement('div');
			oDiv.innerHTML = '<b>There are no Reservations on the selected dates.<b>';
			// panel_wait.cfg.queueProperty("buttons", [ { text:"Otay!", handler:handleCancel } ]);
			panel_wait.render(document.body);
			panel_wait.setBody(oDiv);
		}
			
		// update objDataDownloadTime div
		checkpoint = 600;
		var oDDT = $('objDataServerTime');
		checkpoint = 601;
		oDDT.innerHTML = 'Data generated in ' + root.serverTime;
		
		// clear the timeout!
		clearTimeout(timeoutProcessingError);
		
		//panel_wait.hide();
	},
	failure: function(o) {
		panel_wait.setHeader('Refreshing Reservations');
		panel_wait.setBody('<div align=center>Sorry, there was a connection problem. Retrying in 20 seconds...<br>Status: ' + o.status + '/' + o.statusText + '</div>');
		panel_wait.show();
		// hide panel in 5 seconds
		window.setTimeout(fn_HideWaitPanel, 5000);
		// refresh in 20 seconds
		clearTimeout(timeoutRefresh);
		timeoutRefresh = window.setTimeout(fn_AutoRefreshReservations, 20000);
	},
	argument: {},
	timeout: 30000
};

//
// auto refresh - call the manual refresh, and set a new timeout
//
function fn_AutoRefreshReservations() {
	if (dlgSimple) { dlgSimple.hide(); }
	panel_wait.setHeader('Refreshing Reservations');
	panel_wait.setBody('<div align=center>Retrieving your Reservations...<br><img src="wait.gif" /><br>&nbsp;</div>');
	panel_wait.show();
	fn_RefreshReservations();
	clearTimeout(timeoutRefresh);
	timeoutRefresh = window.setTimeout(fn_AutoRefreshReservations, 120000);
	updateTime();
}

//
//
//
function fn_FirstReservationFetch() {
	panel_wait.render(document.body);
	panel_wait.show();
	fn_RefreshReservations();
}

//
// to be used with manual refresh button
//
function fn_RefreshReservations() {
	
	var transaction;
	var startDate;
	var endDate;
	var i;
	var dStart;
	var dTransaction = new Date();
	var sTransaction;
	
	// empty the grid here
	
	if (root) {
		transaction = YAHOO.util.Connect.asyncRequest('GET', '?sid=' + lngSystemID + '&Action=ReservationJSON&StartDate=' + root.startDate + '&EndDate=' + root.endDate, callbackJSON); 
	} else if (fetchStartDate) {
		// root does not exist, see if fetchStartDate has been defined
		/*
		// day - by - day - used before we optimized MySQL indices
		dStart = new Date(fetchStartDate);
		for (i=0; i<fetchNumberOfDays; i++) {
			dTransaction.setDate(dStart.getDate()+i);
			sTransaction = (dTransaction.getMonth()+1) + '/' + dTransaction.getDate() + '/' + dTransaction.getFullYear();
			callbackJSON.argument.timtest = dTransaction.getDate();
		}
		*/
		transaction = YAHOO.util.Connect.asyncRequest('GET', '?sid=' + lngSystemID + '&Action=ReservationJSON&StartDate=' + fetchStartDate + '&EndDate=' + fetchEndDate, callbackJSON); 
	} else {
		// fetch dates are not defined either, let the server guess - it has been guessing wrong
		transaction = YAHOO.util.Connect.asyncRequest('GET', '?sid=' + lngSystemID + '&Action=ReservationJSON', callbackJSON); 
	}
}

//
//
//
function fn_minuteToTime(minutes) {
	var hours = Math.floor(minutes / 60);
	var minutesLeft = minutes - hours*60; 
	var minuteText = '';
	if (minutesLeft > 0 && minutesLeft < 10) { minuteText = ':0' + minutesLeft; } else if (minutesLeft >= 10) { minuteText = ':' + minutesLeft; } 
	var ampm;
	if (minutes >= 720) { ampm = 'pm'; } else { ampm = 'am'; }
	if (hours >= 13) { hours = hours - 12; }
	return hours + minuteText + ampm;
}

var oPreviousRes;
		
//
//
//
function fnAlert(message) {
	var oDiv = document.createElement('span');
	oDiv.innerHTML = message;
	panel_wait.appendToBody(oDiv);			
}

//
//
//
function fn_HideWaitPanel() {
	panel_wait.hide();
}

var callbackPageTim = {
	success: function(o) { 
		fnAlert("<div style='color: darkgreen; font-weight: bold;'>Tech Support has been paged.</div>");
	},
	failure: function(o) {
		fnAlert("<div style='color: red; font-weight: bold;'>Unable to page Tech Support. Please contact tim@pedesigns.com</div>");
	},
	timeout: 5000
};

//
//
//
function fn_ResProcessingError() {
	// clear the timeout in case we came here differently
	var message = '';
	clearTimeout(timeoutProcessingError);
	if (root) {
		message += '/root exists/start=' + root.startDate + '/end=' + root.endDate; 
	} else if (fetchStartDate) {
		var startDate = fetchStartDate;
		var endDate = fetchEndDate;
		message += '/root doesnt exist/start=' + startDate + '/end=' + endDate; 
		// root does not exist, see if fetchStartDate has been defined
	} else {
		// fetch dates are not defined either, let the server guess - it has been guessing wrong
		message += '/root doesnt exist'; 
	}

	var browser = "";
	if (YAHOO.env.ua.gecko) { browser = 'gecko ' + YAHOO.env.ua.gecko; }
	if (YAHOO.env.ua.ie)  { browser = 'ie ' + YAHOO.env.ua.ie; }
	if (YAHOO.env.ua.webkit) { browser = 'webkit ' + YAHOO.env.ua.webkit; }
	if (YAHOO.env.ua.opera) { browser = 'opera ' + YAHOO.env.ua.opera; }
	
	message += '/checkpoint=' + checkpoint + '/using ' + browser;
	
	fnAlert("<div style='color: maroon; font-weight: bold;'>There has been an error in processing your Reservations. Restarting your browser MAY resolve this problem. Attempting to page Tech Support with details of this problem...</div>");
	var transaction = YAHOO.util.Connect.asyncRequest('GET', '?sid=' + lngSystemID + '&Action=PageTim&Message=' + message, callbackPageTim); 
}

//
//
//		
function submitFailure(obj) {
	alert("Submission Failed: " + obj.status);
}
	
//
// clicky details object	
//
function ClickyDetails(table, id, field, value) {
	this.id = id;
	this.table = table;
	this.field = field;
	this.value = value;
}

//
//
//
var handleClickyReturn = function(k, e) {
	//var DefaultEl = $$('cV','',this)[0];
	timHoldDefaultEl.innerHTML = 'updating...';
	$D.replaceClass(timHoldThis, 'cSuccess', 'cPending');
	
	// alert("aaa");
	dlgClicky.hide();
	el = $("objNewValue");
	querystring = "?sid=" + lngSystemID + "&Action=ChangeFieldAJAX&Table=" + timHoldTable + "&ID=" + timHoldId + "&Field=" + timHoldField + "&Value=" + encodeURIComponent(el.value);
	// alert("bbb");
	callback_ChangeField.argument.target = timHoldThis;
	callback_ChangeField.argument.value = timHoldDefaultEl;
	transaction = YAHOO.util.Connect.asyncRequest('GET', querystring, callback_ChangeField); 
	// alert("ccc");
	return true;
};

//
//
//
var handleClickyTab = function(k, o) {
	
	// stop propagation of TAB, so the browser viewport does not lose focus
	$E.stopEvent(o[1]);
	
	timHoldDefaultEl.innerHTML = 'updating...';
	$D.replaceClass(timHoldThis, 'cSuccess', 'cPending');
	// timHoldThis.style.backgroundColor = 'yellow';
	
	// hide 
	dlgClicky.hide();
	el = $("objNewValue");
	querystring = "?sid=" + lngSystemID + "&Action=ChangeFieldAJAX&Table=" + timHoldTable + "&ID=" + timHoldId + "&Field=" + timHoldField + "&Value=" + encodeURIComponent(el.value);
	callback_ChangeField.argument.target = timHoldThis;
	callback_ChangeField.argument.value = timHoldDefaultEl;
	transaction = YAHOO.util.Connect.asyncRequest('GET', querystring, callback_ChangeField); 
	
	// NOW find the next element
	// get all cC
	var	allClickies = $$("cC");
	var allClickiesLength = allClickies.length;
	for (var i=0; i<allClickiesLength; i++) {
		if (allClickies[i] == timHoldThis) {
			nextClicky = allClickies[i+1];
			if (!nextClicky) { nextClicky = allClickies[0]; }
			i = allClickiesLength;
		}
	}
	fn_ChangeField2(nextClicky);
	return false;
};


//
// seems like we shouldn't have to use EXAMPLE object
// this is run on window.load
// 
YAHOO.example.panels = function() {

	try { 
		var locationString = YAHOO.lang.JSON.stringify(locationJSON);
	    fsLocations = YAHOO.lang.JSON.parse(locationString); 
	} 
	catch (e) { 
	    // alert("Invalid Location data"); 
	}
		
	try { 
		var periodString = YAHOO.lang.JSON.stringify(periodJSON);
	    fsPeriods = YAHOO.lang.JSON.parse(periodString); 
	} 
	catch (e) { 
	    // alert("Invalid Location data"); 
	}
		
	try { 
		var bellScheduleString = YAHOO.lang.JSON.stringify(bellScheduleJSON);
	    fsBellSchedules = YAHOO.lang.JSON.parse(bellScheduleString); 
	} 
	catch (e) { 
	    // alert("Invalid Period data"); 
	} 

	// new 2008-01-27
	// from AVS
	// add clicky to all newClickies
	var newClickies = $$('cC');
	for (i = 0; i < newClickies.length; i++) {
		$E.addListener(newClickies[i], 'click', fn_ChangeField);
	}

	// add listener to all items of class cC2
	var newClickies2 = $$('cC2');
	for (i = 0; i < newClickies2.length; i++) {
		$E.addListener(newClickies2[i], 'click', fn_EditField);
	}

	
	var handleCancel = function() {
		this.cancel();
	};
			
	var handleSubmit = function() {
		this.submit();
	};
			
	panel_seven = new YAHOO.widget.Dialog("panel_seven", 
		{ 
			close:true,  
			visible:false,  
			draggable:true,
			modal:false,
			fixedcenter:true,
			xcontext:['anchorElement','bl','tr'],
			effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration: 0.3},
			constraintoviewport:true
		} 
	); 
				
	var listeners = new YAHOO.util.KeyListener(document, { keys : 27 }, {fn:handleCancel,scope:panel_seven,correctScope:true} );
	panel_seven.cfg.queueProperty("keylisteners", listeners);
	panel_seven.cfg.queueProperty("buttons", [ { text:"Cancel", handler:handleCancel }, { text:"Send Message", handler:handleSubmit }]);
	// panel_seven.cfg.queueProperty('postmethod','form');
	panel_seven.cfg.queueProperty('postmethod','async');
	panel_seven.callback.success = submitCallback;
	panel_seven.callback.failure = submitFailure;
				
	// panel_seven.setHeader('Create Email');
	// panel_seven.setBody('Name: <input name=fldName size=15>');
	// panel_seven.setFooter('Footer'); // gets replaced with buttons
	panel_seven.render(document.body);
	
	//
	// new 2008-1-27 clicky dialog from AVS
	//
	dlgClicky = new YAHOO.widget.Dialog("dlgClicky", {
			close: true, visible: false, draggable: true, modal: false, constraintoviewport: true
		}
	);
	var listenerClickyTab = new YAHOO.util.KeyListener(document, { keys:9 }, { fn:handleClickyTab, scope:dlgClicky, correctScope:true } );
	var listenerClickyReturn = new YAHOO.util.KeyListener(document, { keys:[13, 10] }, { fn:handleClickyReturn, scope:dlgClicky, correctScope:true } );
	var listenerClickyEscape = new YAHOO.util.KeyListener(document, { keys:27 }, { fn:handleCancel, scope:dlgClicky, correctScope:true } );
	dlgClicky.cfg.queueProperty("keylisteners", [listenerClickyReturn, listenerClickyTab, listenerClickyEscape]);
	// dlgClicky.cfg.queueProperty("buttons", [ { text:"Cancel", handler:handleCancel }, { text:"Update", handler:handleSubmit }]);
	dlgClicky.cfg.queueProperty('postmethod','async');
	// dlgClicky.callback.success = newClickySuccess;
	// dlgClicky.callback.failure = newClickyFailure;
	dlgClicky.render(document.body);	

	panel_colorPop = new YAHOO.widget.Dialog("panel_colorPop", 
		{ 
			close:true,  
			visible:false,  
			draggable:true,
			modal:false,
			fixedcenter:true,
			xcontext:['anchorElement','bl','tr'],
			effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration: 0.3},
			constraintoviewport:true
		} 
	); 
				
	panel_colorPop.cfg.queueProperty("keylisteners", listeners);
	panel_colorPop.cfg.queueProperty("buttons", [ { text:"Cancel", handler:handleCancel } ]);
//	// panel_seven.cfg.queueProperty('postmethod','form');
//	panel_colorPop.callback.success = submitCallback;
//	panel_colorPop.callback.failure = submitFailure;
				
	panel_colorPop.setHeader('Pick a Color');
	panel_colorPop.setBody('hoohah!');
	// panel_seven.setFooter('Footer'); // gets replaced with buttons
	panel_colorPop.render(document.body);
	
	//

	dlgSimple = new YAHOO.widget.SimpleDialog("dlgSimple",
		{
			close:true,
			visible:false,
			draggable:true,
			modal:false,
			fixedcenter:true,
			effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration: 0.3},
			constraintoviewport:true
		}
	);
	// dlgSimple.setHeader("foo");
	// dlgSimple.setBody("bar");
	dlgSimple.render(document.body);
	// alert("123");		
			
//	newContextMenu = new YAHOO.widget.ContextMenu("myContextMenu", { trigger: "contextMenuTest" } );
	//newContextMenuItem1 = new YAHOO.widget.MenuItem("dfdf", { text:"dfdf2", url: "http://mail.yahoo.com" } )
	//newContextMenu.addItems( [{ text:"bobob", url: "http://mail.yahoo.com" }] );
	//newContextMenu.addItem("dave", url: "http://www.yahoo.com");
//	newContextMenu.addItem( { text: "bob" } );
//	newContextMenu.render(document.body);

	// 2008-01-17 new rich text editor
	if ($('objPolicies')) {
		var myEditor1 = new YAHOO.widget.SimpleEditor('objPolicies', { 
			height: '150px', 
			width: '522px', 
			dompath: false, //Turns on the bar at the bottom 
			handleSubmit: true
			// toolbar: { titlebar: 'Test123' }
			}
		);
		myEditor1.render(); 
	}

	if ($('ReservationMessage')) {
		var myEditor2 = new YAHOO.widget.SimpleEditor('ReservationMessage', { 
			height: '150px', 
			width: '522px', 
			dompath: false,
			handleSubmit: true
			}
		);
		myEditor2.render(); 
	}
	
	if ($('Message1')) {
		var myEditor3 = new YAHOO.widget.SimpleEditor('Message1', { 
			height: '150px', 
			width: '522px', 
			dompath: false, 
			handleSubmit: true
			}
		);
		myEditor3.render(); 
	}

	if ($('objMessage2')) {
		var myEditor4 = new YAHOO.widget.SimpleEditor('objMessage2', { 
			height: '150px', 
			width: '522px', 
			dompath: false, //Turns on the bar at the bottom 
			handleSubmit: true
			// toolbar: { titlebar: 'Test123' }
			}
		);
		myEditor4.render(); 
	}

	/*
	if ($('objForegroundColorPicker')) {
		var picker = new YAHOO.widget.ColorPicker("objForegroundColorPicker", {
			showhsvcontrols: true,
			showhexcontrols: true,
		//	images: {
		//		PICKER_THUMB: "picker_thumb.png",
		//		HUE_THUMB: "hue_thumb.png" 
		//	}
		});
	}

	if ($('objBackgroundColorPicker')) {
		var picker = new YAHOO.widget.ColorPicker("objBackgroundColorPicker", {
			showhsvcontrols: true,
			showhexcontrols: true,
		//	images: {
		//		PICKER_THUMB: "picker_thumb.png",
		//		HUE_THUMB: "hue_thumb.png"
		//	}
		});
	}
	*/
	
	/* autocomplete for reservation screen */
		
	if ($('acReservationPatron')) {
		// An XHR DataSource
		var schemaContacts = ["ResultSet.Result", "Name", "ID"];
		var datasourceContacts = new YAHOO.widget.DS_XHR('index.asp', schemaContacts);
		datasourceContacts.responseType = YAHOO.widget.DS_XHR.TYPE_JSON; 
		datasourceContacts.queryMatchContains = true;
		// datasourceContacts.scriptQueryParam = "Action";
		datasourceContacts.scriptQueryAppend = "sid=" + lngSystemID + "&Action=JSONPatrons";
			
		var autocompleteContacts = new YAHOO.widget.AutoComplete("inpPatron", "acPatronContainer", datasourceContacts);
		autocompleteContacts.animVert = false; 
		// autocompleteContacts.delimChar = ",";
		// autocompleteContacts.typeAhead = true;
		autocompleteContacts.forceSelection = true; 
		autocompleteContacts.useIFrame = true; 
		autocompleteContacts.maxResultsDisplayed = 25; 
		autocompleteContacts.minQueryLength = 2;
			
		var autocompleteContactsHandler = function(sType, aArgs) {
			var aData = aArgs[2];
			var id = aData[1]; // depends on where in your schema "id" is defined
			// alert("id="+id);
			$('idHiddenPatron').value = id; 
			// alert($('idHiddenPatron'));
		};
		
		autocompleteContacts.itemSelectEvent.subscribe(autocompleteContactsHandler);
	}

}

	
//
//
//
function clickedEmailLink(email, dates) {
	$('fldMailTo').value = email;
	$('fldMailSubject').value = 'Your AV request for ' + dates;
	panel_seven.show();
	$('fldMailMessage').focus();
	return false;
}
			
//
//
//
function clickedClickyEmailLink(patronID) {					
	// objPatrons_633_Email
	// alert('objPatrons_'+patronID+'_Email'); 
	// alert($('objPatrons_'+patronID+'_Email').innerHTML); 
	$('fldMailTo').value = $('objPatrons_'+patronID+'_Email').innerHTML;
	// $('fldMailSubject').value = subject;
	panel_seven.show();
	$('fldMailMessage').focus();
	return false;
}

//
//
//
function fn_colorPop(elementId, Table, ID, Field, bright) {

	var strHTML;
	var colorcode;
	var reds = ["51", "102", "255", "0", "153", "204"]; 
	var greens = ["0", "51", "102", "153", "204", "255"];
	var blues = greens;
	var red, blue, green;

	if (bright) {
		strHTML = "Please choose a color from<br>this palette of lighter colors:";
	} else {
		strHTML = "Please choose a color from<br>this palette of darker colors:";
	}

	strHTML += "<table class=clsColorPicker>";

	for (var redshelf = 0; redshelf <= 1; redshelf++) { 
		for (var ib = 0; ib <= 5; ib++) {
			strHTML += "<tr>";
			for (var ir = 0; ir <= 2; ir++) {
				for (var ig = 0; ig <= 5; ig++) {
					red = reds[ir+redshelf*3];
					blue = blues[Math.abs(5*(redshelf%2)-ib)];
					green = greens[Math.abs(5*(ir%2)-ig)];
					colorcode = 'rgb(' + red + ', ' + green + ', ' + blue + ')';
					ccavg = (parseInt(red, 10)*600 + parseInt(green, 10)*670 + parseInt(blue, 10)*65)/1000;
					if ((bright && (ccavg > 150)) || (!bright && (ccavg < 200))) {
						strHTML += '<td style="background-color: ' + colorcode + ';" onclick="fn_colorPicked(\'' + elementId + '\', \'' + Table + '\', \'' + ID + '\', \'' + Field + '\', \'' + colorcode + '\')"></td>';
					} else {
						strHTML += '<td></td>';
					}
				}
			}
			strHTML += "</tr>";
		}
	}
	strHTML += "</table>";

	panel_colorPop.setBody(strHTML);
	panel_colorPop.show();
}

//
//
//
function fn_colorPicked(elementId, Table, ID, Field, Response) {
	// hide panel
	panel_colorPop.hide();
	
	// build the querystring
	Response = Response.replace("#", "%23");
	var querystring = "sid=" + lngSystemID + "&Action=ChangeFieldAJAX&Table=" + Table + "&ID=" + ID + "&Field=" + Field + "&Value=" + Response;
	
	// send the request!
	sendRequest(querystring, elementId);
		
}

//
// from davglass YAHOO.Tools
//
function getHeight(elm) {
    elm = $(elm);
    var h = $D.getStyle(elm, 'height');
    if (h == 'auto') {
        elm.style.zoom = 1;
        h = elm.clientHeight + 'px';
    }
    return h;
}

// new 2008-01 the calendar on the main schedule page
//
var calMain = {
	over_cal: false,
	oCalendar: null,
	element: 'calMain',
	container: 'calMainContainer',
	target: 'CalendarSelect1',
	initialize: function () {
		calMain.oCalendar = new YAHOO.widget.Calendar(calMain.element, calMain.container);
		calMain.oCalendar.selectEvent.subscribe(calMain.getDateX, calMain.oCalendar, true);
		$E.addListener(calMain.target, 'focus', calMain.show);
		$E.addListener(calMain.target, 'blur', calMain.hide);
		calMain.oCalendar.render();
		$E.addListener(calMain.container, 'mouseover', calMain.mouseOver);
		$E.addListener(calMain.container, 'mouseout', calMain.mouseOut);
	},
	getDateX: function () {
		var calDate = this.getSelectedDates()[0];
		calDate = (calDate.getMonth() + 1) + '/' + calDate.getDate() + '/' + calDate.getFullYear();
		$(calMain.target).value = calDate;
		calMain.over_cal = false;
		calMain.hide();
	},
	show: function () {
		var xy = $D.getXY(calMain.target);
		$D.setStyle(calMain.container, 'display', 'block');
		xy[1] = xy[1] + parseInt(getHeight(calMain.target), 10) + 3;
		$D.setXY(calMain.container, xy);
	},
	hide: function () {
		if (!calMain.over_cal) { $D.setStyle(calMain.container, 'display', 'none'); }
	},
	mouseOver: function () { calMain.over_cal = true; },
	mouseOut: function () { calMain.over_cal = false; }
};
$E.addListener(window, 'load', calMain.initialize);
	
//
// Load all the new panels; should somehow get this OFF of the example namespace
//	
$E.addListener(window,'load',YAHOO.example.panels);

//
// validate date; from AVS
//
function validateDate(fld) {

    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 ((fld.value.match(RegExPattern)) && (fld.value!=='')) {
        return true; 
    } else {
        return false;
    } 

}

//
// new 2008-01-30
//
function validateReservation() {

	var blnValidate = true;
	var fldDate = $('objStartingDate');
	var radRepeatWeekday = $('radRepeatWeekday');
	var fldWeekdayUntil = $('fldWeekdayUntil');
	var radRepeatWeek = $('radRepeatWeek');
	var fldWeekUntil = $('fldWeekUntil');
	var radRepeatDateList = $('radRepeatDateList');
	var fldDateList = $('fldDateList');
	var iLoop = null;
	var blnFacilitySelected = false;
	var blnPeriodSelected = false;
	
	if (!validateDate(fldDate)) {
		alert("Invalid Starting Date");
		blnValidate = false;
		fldDate.style.backgroundColor = "yellow";
	}
	else {
		fldDate.style.backgroundColor = "";
		// Document.All.Date.Value = CDate(Document.All.Date.Value)
	}

	if (radRepeatWeekday.checked && !validateDate(fldWeekdayUntil)) {
		alert("Invalid Weekday Until Date");
		blnValidate = false;
		fldWeekdayUntil.style.backgroundColor = "yellow";
	}
	else {
		if (validateDate(fldWeekdayUntil)) {
			// Document.All.WeekdayUntil.Value = CDate(Document.All.WeekdayUntil.Value);
		}
		fldWeekdayUntil.style.backgroundColor = "";
	}
	
	if  (radRepeatWeek.Checked && !validateDate(fldWeekUntil)) {
		alert("Invalid Week Until Date");
		blnValidate = false;
		fldWeekUntil.style.backgroundColor = "yellow";
	}
	else {
		if (validateDate(fldWeekUntil)) {
			// Document.All.WeekUntil.Value = CDate(Document.All.WeekUntil.Value);
		}
		fldWeekUntil.style.backgroundColor = "";
	}

	if (radRepeatDateList.Checked) {
		strArray = Split(fldDateList, ",");
		var intLastDate = UBound(strArray);
		for (intLoop = 0; intLoop <= intLastDate; intLoop++) {
			if (!validateDate(strArray(intLoop))) { 
				alert("one of the dates is incorrect");
				blnValidate = false;
				fldDateList.style.backgroundColor = "yellow";
			}
			else {
				// strArray(intLoop) = CDate(strArray(intLoop));
			}
		}
		// Document.All.DateList.Value = Join(strArray, ",")
	}
	else {
		fldDateList.style.backgroundColor = ""; 
	}
	
	if (document.frmReservation.fldPatronName.Value = "") {
		document.frmReservation.selPatronID.Value = 0; 
	}
	
	// check to see if any Period is checked
	var periodCount = document.frmReservation.PeriodID.length;
	for (iLoop = 0; iLoop < periodCount; iLoop++) {
		if (document.frmReservation.PeriodID[iLoop].checked) {
			blnPeriodSelected = true;
		}
	}
	if (!blnPeriodSelected) {
		alert("You must select at least one Period");
		blnValidate = false;
	}
	
	// check to see if any Location is checked
	// this only works if there is more than 1 facility
	var locationCount = document.frmReservation.RoomID.length;
	for (iLoop = 0; iLoop < locationCount; iLoop++) {
		if (document.frmReservation.RoomID[iLoop].checked) {
			blnFacilitySelected = true;
		}
	}
	
	// check to see if any of the any open facility boxes are checked.
	
	if (document.frmReservation.AnyRoomInGroup) {
		if (document.frmReservation.AnyRoomInGroup.length) {
			// there are multiple groups to check
			var locationCount2 = document.frmReservation.AnyRoomInGroup.length;
			for (iLoop = 0; iLoop < locationCount2; iLoop++) {
				if (document.frmReservation.AnyRoomInGroup[iLoop].checked) {
					blnFacilitySelected = true;
				}
			}
		}
		else {
			// there is one group to check
			if (document.frmReservation.AnyRoomInGroup.checked) {
				blnFacilitySelected = true;
			}
		}	
	}
		
	if (!blnFacilitySelected) {
		alert("You must select at least one Facility");
		blnValidate = false;
	}
	
	// new 2008-07-21
	// check that every field of class cRequiredResField has some value
	// get all elements
	var elRequired = $$('cRequiredResField');
	// check each element.
	if (elRequired.length > 0) {
		// alert("length=" + elRequired.length);
		for (iLoop = 0; iLoop < elRequired.length; iLoop++) {
			if (elRequired[iLoop].value.length == 0) {
				blnValidate = false;
				alert('One or more Details fields are required.');
				elRequired[iLoop].style.backgroundColor = "yellow";
			}
			else {
				elRequired[iLoop].style.backgroundColor = "";
			}
		}	
	}
	// if no value then blnValidate = false
	
	return blnValidate;

}

// Reservation - Starting Date
var calReservationStartingDate = {
	over_cal: false,
	oCalendar: null,
	element: 'calReservationStartingDate',
	container: 'calReservationStartingDateContainer',
	target: 'objStartingDate',
	initialize: function () {
		calReservationStartingDate.oCalendar = new YAHOO.widget.Calendar(calReservationStartingDate.element, calReservationStartingDate.container);
		calReservationStartingDate.oCalendar.selectEvent.subscribe(calReservationStartingDate.getDateX, calReservationStartingDate.oCalendar, true);
		$E.addListener(calReservationStartingDate.target, 'focus', calReservationStartingDate.show);
		$E.addListener(calReservationStartingDate.target, 'blur', calReservationStartingDate.hide);
		calReservationStartingDate.oCalendar.render();
		$E.addListener(calReservationStartingDate.container, 'mouseover', calReservationStartingDate.mouseOver);
		$E.addListener(calReservationStartingDate.container, 'mouseout', calReservationStartingDate.mouseOut);
	},
	getDateX: function () {
		var calDate = this.getSelectedDates()[0];
		calDate = (calDate.getMonth() + 1) + '/' + calDate.getDate() + '/' + calDate.getFullYear();
		$(calReservationStartingDate.target).value = calDate;
		calReservationStartingDate.over_cal = false;
		calReservationStartingDate.hide();
	},
	show: function () {
		var xy = $D.getXY(calReservationStartingDate.target);
		$D.setStyle(calReservationStartingDate.container, 'display', 'block');
		xy[1] = xy[1] + parseInt(getHeight(calReservationStartingDate.target), 10) + 3;
		$D.setXY(calReservationStartingDate.container, xy);
	},
	hide: function () {
		if (!calReservationStartingDate.over_cal) { $D.setStyle(calReservationStartingDate.container, 'display', 'none'); }
	},
	mouseOver: function () { calReservationStartingDate.over_cal = true; },
	mouseOut: function () { calReservationStartingDate.over_cal = false; }
};
$E.addListener(window, 'load', calReservationStartingDate.initialize);

// Reservation - WeekdayUntil Date
var calReservationWeekdayUntil = {
	over_cal: false,
	oCalendar: null,
	element: 'calReservationWeekdayUntil',
	container: 'calReservationWeekdayUntilContainer',
	target: 'fldWeekdayUntil',
	initialize: function () {
		calReservationWeekdayUntil.oCalendar = new YAHOO.widget.Calendar(calReservationWeekdayUntil.element, calReservationWeekdayUntil.container);
		calReservationWeekdayUntil.oCalendar.selectEvent.subscribe(calReservationWeekdayUntil.getDateX, calReservationWeekdayUntil.oCalendar, true);
		$E.addListener(calReservationWeekdayUntil.target, 'focus', calReservationWeekdayUntil.show);
		$E.addListener(calReservationWeekdayUntil.target, 'blur', calReservationWeekdayUntil.hide);
		calReservationWeekdayUntil.oCalendar.render();
		$E.addListener(calReservationWeekdayUntil.container, 'mouseover', calReservationWeekdayUntil.mouseOver);
		$E.addListener(calReservationWeekdayUntil.container, 'mouseout', calReservationWeekdayUntil.mouseOut);
	},
	getDateX: function () {
		var calDate = this.getSelectedDates()[0];
		calDate = (calDate.getMonth() + 1) + '/' + calDate.getDate() + '/' + calDate.getFullYear();
		$(calReservationWeekdayUntil.target).value = calDate;
		calReservationWeekdayUntil.over_cal = false;
		calReservationWeekdayUntil.hide();
	},
	show: function () {
		var xy = $D.getXY(calReservationWeekdayUntil.target);
		$D.setStyle(calReservationWeekdayUntil.container, 'display', 'block');
		xy[1] = xy[1] + parseInt(getHeight(calReservationWeekdayUntil.target), 10) + 3;
		$D.setXY(calReservationWeekdayUntil.container, xy);
	},
	hide: function () {
		if (!calReservationWeekdayUntil.over_cal) { $D.setStyle(calReservationWeekdayUntil.container, 'display', 'none'); }
	},
	mouseOver: function () { calReservationWeekdayUntil.over_cal = true; },
	mouseOut: function () { calReservationWeekdayUntil.over_cal = false; }
};
$E.addListener(window, 'load', calReservationWeekdayUntil.initialize);

// Reservation - WeekUntil Date
var calReservationWeekUntil = {
	over_cal: false,
	oCalendar: null,
	element: 'calReservationWeekUntil',
	container: 'calReservationWeekUntilContainer',
	target: 'fldWeekUntil',
	initialize: function () {
		calReservationWeekUntil.oCalendar = new YAHOO.widget.Calendar(calReservationWeekUntil.element, calReservationWeekUntil.container);
		calReservationWeekUntil.oCalendar.selectEvent.subscribe(calReservationWeekUntil.getDateX, calReservationWeekUntil.oCalendar, true);
		$E.addListener(calReservationWeekUntil.target, 'focus', calReservationWeekUntil.show);
		$E.addListener(calReservationWeekUntil.target, 'blur', calReservationWeekUntil.hide);
		calReservationWeekUntil.oCalendar.render();
		$E.addListener(calReservationWeekUntil.container, 'mouseover', calReservationWeekUntil.mouseOver);
		$E.addListener(calReservationWeekUntil.container, 'mouseout', calReservationWeekUntil.mouseOut);
	},
	getDateX: function () {
		var calDate = this.getSelectedDates()[0];
		calDate = (calDate.getMonth() + 1) + '/' + calDate.getDate() + '/' + calDate.getFullYear();
		$(calReservationWeekUntil.target).value = calDate;
		calReservationWeekUntil.over_cal = false;
		calReservationWeekUntil.hide();
	},
	show: function () {
		var xy = $D.getXY(calReservationWeekUntil.target);
		$D.setStyle(calReservationWeekUntil.container, 'display', 'block');
		xy[1] = xy[1] + parseInt(getHeight(calReservationWeekUntil.target), 10) + 3;
		$D.setXY(calReservationWeekUntil.container, xy);
	},
	hide: function () {
		if (!calReservationWeekUntil.over_cal) { $D.setStyle(calReservationWeekUntil.container, 'display', 'none'); }
	},
	mouseOver: function () { calReservationWeekUntil.over_cal = true; },
	mouseOut: function () { calReservationWeekUntil.over_cal = false; }
};
$E.addListener(window, 'load', calReservationWeekUntil.initialize);

/*
//
// START OF COLOR PICKER EXAMPLE
//
//create a namespace object in the example namespace:
YAHOO.namespace("example.colorpicker")

//create a new object for this module:
YAHOO.example.colorpicker.inDialog = function() {

	//Some shortcuts to use in our example:
	var Event=YAHOO.util.Event,
		Dom=YAHOO.util.Dom,
		lang=YAHOO.lang;

	return {
	
		//In our initialization function, we'll create the dialog;
		//in its render event, we'll create our Color Picker instance.
        init: function() {

            // Instantiate the Dialog
            this.dialog = new YAHOO.widget.Dialog("yui-picker-panel", { 
				width : "500px",
				close: true,
				fixedcenter : true,
				visible : false, 
				constraintoviewport : true,
				buttons : [ { text:"Submit", handler:this.handleSubmit, isDefault:true },
							{ text:"Cancel", handler:this.handleCancel } ]
             });
 
			// Once the Dialog renders, we want to create our Color Picker
			// instance.
            this.dialog.renderEvent.subscribe(function() {
				if (!this.picker) { //make sure that we haven't already created our Color Picker
					YAHOO.log("Instantiating the color picker", "info", "example");
					this.picker = new YAHOO.widget.ColorPicker("yui-picker", {
						container: this.dialog,
						images: {
							PICKER_THUMB: "assets/picker_thumb.png",
							HUE_THUMB: "assets/hue_thumb.png"
						}
						//Here are some other configurations we could use for our Picker:
						//showcontrols: false,  // default is true, false hides the entire set of controls
						//showhexcontrols: true, // default is false
						//showhsvcontrols: true  // default is false
					});

					//listen to rgbChange to be notified about new values
					this.picker.on("rgbChange", function(o) {
						YAHOO.log(lang.dump(o), "info", "example");
					});
				}
			});	
			
			// If we wanted to do form validation on our Dialog, this
			// is where we'd do it.  Remember to return true if validation
			// passes; otherwise, your Dialog's submit method won't submit.
            this.dialog.validate = function() {
				return true;
            };

            // Wire up the success and failure handlers
            this.dialog.callback = { success: this.handleSuccess, thisfailure: this.handleFailure };
            
            // We're all set up with our Dialog's configurations;
			// now, render the Dialog
            this.dialog.render();
			
			// We can wrap up initialization by wiring all of the buttons in our
			// button dashboard to selectively show and hide parts of the
			// Color Picker interface.  Remember that "Event" here is an
			// alias for YAHOO.util.Event and "Event.on" is therfor a shortcut
			// for YAHOO.util.Event.onAvailable -- the standard Dom event attachment
			// method:
            Event.on("show", "click", this.dialog.show, this.dialog, true);
            Event.on("hide", "click", this.dialog.hide, this.dialog, true);
            Event.on("btnhsv", "click", function(e) {
                        var p = this.picker;
                        p.set(p.OPT.SHOW_HSV_CONTROLS, !p.get(p.OPT.SHOW_HSV_CONTROLS));
                    }, this.dialog, true);
            Event.on("btnhex", "click", function(e) {
                        var p = this.picker;
                        p.set(p.OPT.SHOW_HEX_CONTROLS, !p.get(p.OPT.SHOW_HEX_CONTROLS));
                    }, this.dialog, true);
            Event.on("btnrgb", "click", function(e) {
                        var p = this.picker;
                        p.set(p.OPT.SHOW_RGB_CONTROLS, !p.get(p.OPT.SHOW_RGB_CONTROLS));
                    }, this.dialog, true);
            Event.on("btnhexsummary", "click", function(e) {
                        var p = this.picker;
                        p.set(p.OPT.SHOW_HEX_SUMMARY, !p.get(p.OPT.SHOW_HEX_SUMMARY));
                    }, this.dialog, true);
			
			//initialization complete:
			YAHOO.log("Example initialization complete.", "info", "example");

		},
		
		//We'll wire this to our Dialog's submit button:
		handleSubmit: function() {
			//submit the Dialog:
			this.submit();
			//log this step to logger:
			YAHOO.log("Dialog was submitted.", "info", "example");
		},
 
 		//If the Dialog's cancel button is clicked,
		//this function fires
		handleCancel: function() {
			//the cancel method automatically hides the Dialog:
			this.cancel();
			//log this step to logger:
			YAHOO.log("Dialog was submitted.", "info", "example");
		},
		
		//We'll use Connection Manager to post our form data to the
		//server; here, we set up our "success" handler.
		handleSuccess: function(o) {
			YAHOO.log("Connection Manager returned results to the handleSuccess method.", "info", "example");
			var response = o.responseText;
			//On Yahoo servers, we may get some page stamping;
			//we can trim off the trailing comment:
			response = response.split("<!")[0];
			//write the response to the page:
			response = "<strong>The data received by the server was the following:</strong> " + response;
			document.getElementById("resp").innerHTML = response;
		},
		
		handleFailure: function(o) {
			YAHOO.log("Connection Manager returned results to the handleFailure method.", "error", "example");
			YAHOO.log("Response object:" + lang.dump(o), "error", "example");
		}
   
	}


}();

//The earliest safe moment to instantiate a Dialog (or any
//Container element is onDOMReady; we'll initialize then:
YAHOO.util.Event.onDOMReady(YAHOO.example.colorpicker.inDialog.init, YAHOO.example.colorpicker.inDialog, true);

*/
	
/*
YAHOO.util.Event.addListener(window, "load", function() {
    YAHOO.example.Basic = new function() {
        var myColumnDefs = [
            {key:"id", sortable:true, resizeable:true},
            {key:"date", formatter:YAHOO.widget.DataTable.formatDate, sortable:true, sortOptions:{defaultDir:YAHOO.widget.DataTable.CLASS_DESC},resizeable:true},
            {key:"quantity", formatter:YAHOO.widget.DataTable.formatNumber, sortable:true, resizeable:true},
            {key:"amount", formatter:YAHOO.widget.DataTable.formatCurrency, sortable:true, resizeable:true},
            {key:"title", sortable:true, resizeable:true}
        ];

        this.myDataSource = new YAHOO.util.DataSource(YAHOO.example.Data.bookorders);
        this.myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
        this.myDataSource.responseSchema = {
            fields: ["id","date","quantity","amount","title"]
        };

        this.myDataTable = new YAHOO.widget.DataTable("basic",
                myColumnDefs, this.myDataSource, {caption:"DataTable Caption"});
    };
});
*/

//
// Manage Equipment Type
//
YAHOO.util.Event.addListener(window, "load", function() {
	
	// only process if Equipment Type ID exists
	if ($('idGroupContactsDataTable')) {
	
		// YAHOO.example.XHR_JSON = new function() {
		YAHOO.FacilityScheduler.ManageGroupContacts = new function() {

			// alert("aaa");
			
			// not used, keep as example of Parser. Might need to get rid of "12/31/1969" problem
			YAHOO.util.DataSource.Parser['sqlDate'] = function (oData) {
				var parts = oData.split(' ');
				var datePart = parts[0].split('-');
				if (parts.length > 1) {
					var timePart = parts[1].split(':');
					return new Date(datePart[0],datePart[1]-1,datePart[2],timePart[0],timePart[1],timePart[2]);
				} else {
					return new Date(datePart[0],datePart[1]-1,datePart[2]);
				}
			};
			
			// alert("bbb");
			
			// my Editor, sends new value to database via POST
			var myEditor = new YAHOO.widget.TextboxCellEditor({
				asyncSubmitter: function (callback, newValue) {
					var record = this.getRecord(),
						column = this.getColumn(),
						oldValue = this.value,
						datatable = this.getDataTable();
					YAHOO.util.Connect.asyncRequest(
						'POST',
						'index.asp?Action=UpdateDataTableCell', 
						{
							success:function(o) {
								var r = YAHOO.lang.JSON.parse(o.responseText);
								if (r.replyCode == 201) {
									callback(true, r.data);
								} else {
									alert(r.replyText);
									callback();
								}
							},
							failure:function(o) {
								alert(o.statusText);
								callback();
							},
							scope:this
						},
						'Table=Users&Field=' + column.key + '&NewValue=' + 
							escape(newValue) + '&OldValue=' + escape(oldValue) + 
							myBuildUrl(datatable, record)
					);                                              
				}
			})
			
			// alert("ccc");
			
			// creates the Details link with the magnifying glass
			this.formatUrl = function(elCell, oRecord, oColumn, sData) {
				elCell.innerHTML = "<a class='cButton sprite-magnifier-zoom-in' href='index.asp?Action=ShowContact&ContactID=" + oRecord.getData("ID") + "'>Details</a>";
			};

			// creates the tick mark or cross for a Boolean field
			this.formatBoolean = function(elCell, oRecord, oColumn, sData) {
				// sData = 0 for False
				// sData = 1 for True
				if (sData == 0) {
					$D.removeClass(elCell, "clsDTBoolean-True");
					$D.addClass(elCell, "clsDTBoolean-False");
				} else {
					$D.removeClass(elCell, "clsDTBoolean-False");
					$D.addClass(elCell, "clsDTBoolean-True");
				}
			};

			// alert("ddd");
			
			var myColumnDefs = [
				// isPrimaryKey - extension
				// action - extension
				{ key:"ID", isPrimaryKey: true, hidden: true },
				// { key:"InCirculation", label: "In Circulation", sortable: true, action: "FlipBoolean", editor: myEditor, className: "clsDTBoolean", formatter: this.formatBoolean },
				{ key:"UserFirstName", label: "First Name", sortable: true, editor: myEditor },
				{ key:"UserLastName", label: "Last Name", sortable: true, editor: myEditor },
				{ key:"UserEmailAddress", label: "Email Address", sortable: true, editor: myEditor },
				{ key:"Title", sortable: true, editor: myEditor },
				{ key:"Notes2", label: "Notes", editor: myEditor },
				// { key:"DateChecked", label: "Date Checked", sortable: true, editor: myEditor, formatter: YAHOO.widget.DataTable.formatDate, editor: new YAHOO.widget.DateCellEditor() },
				{ key:"Link", label: "", action: "Hyperlink", formatter: this.formatUrl }
			];
			
			// alert("ddd2");
			
			// configuration values for Datatable
			// creates the paginated version
			var myConfigs = { 
				// sortedBy:{key:"areacode",dir:"asc"}, 
				paginator: new YAHOO.widget.Paginator({ 
					rowsPerPage: 25, 
					template: YAHOO.widget.Paginator.TEMPLATE_ROWS_PER_PAGE, 
					rowsPerPageOptions: [10,25,50,100], 
					pageLinks: 5 
				}), 
				draggableColumns: true,
				initialRequest: "Action=JSONGroupContacts&sid=" + lngSystemID
			}
 
			// alert("eee");
			
			this.myDataSource = new YAHOO.util.DataSource("index.asp?");
			this.myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
			this.myDataSource.connXhrMode = "queueRequests";
			this.myDataSource.responseSchema = {
				resultsList: "ResultSet.Result",
				fields: [ "ID", "UserFirstName", "UserLastName", "UserEmailAddress", "Title", "Notes2" ]
			};

			// alert("fff");
			
			// Create the DataTable!
			this.myDataTable = new YAHOO.widget.DataTable("idGroupContactsDataTable", myColumnDefs,
				this.myDataSource, myConfigs);

			// alert("ggg");
				
			// finds the primary key
			var myBuildUrl = function(datatable, record) {
				var url = '';
				var cols = datatable.getColumnSet().keys;
				for (var i = 0; i < cols.length; i++) {
					if (cols[i].isPrimaryKey) {
						url += '&' + cols[i].key + '=' + escape(record.getData(cols[i].key));
					}
				}
				return url;
			};

			// process click anywhere in table data
			var onCellClick = function(oArgs) {
				var target = oArgs.target,
					column = this.getColumn(target),
					record = this.getRecord(target);
					value = record.getData(column.key);
				switch (column.action) {
					case 'delete':
						break; // not using delete right now
						if (confirm('Are you sure?')) {
							
							YAHOO.util.Connect.asyncRequest(
								'GET',
								'index.asp?Action=dtDelete' + myBuildUrl(this,record),
								{
									success: function (o) {
										if (o.responseText == 'Ok') {
											this.deleteRow(target);
										} else {
											alert(o.responseText);
										}
									},
									failure: function (o) {
										alert(o.statusText);
									},
									scope:this
								}
							);
						}
						break;
					case 'FlipBoolean':
						YAHOO.util.Connect.asyncRequest(
							'POST',
							'index.asp?Action=UpdateDataTableCell', 
							{
								success:function(o) {
									var r = YAHOO.lang.JSON.parse(o.responseText);
									if (r.replyCode == 201) {
										this.updateCell(record, column, 1 - value);
									} else {
										alert(r.replyText);
									}
								},
								failure:function(o) {
									alert(o.statusText);
								},
								scope:this
							},
							'Table=Equipment&Field=' + column.key + '&NewValue=' + 
								escape(1-value) + '&OldValue=' + escape(value) + 
								myBuildUrl(this, record)
						);
						break;
					default:
						this.onEventShowCellEditor(oArgs);
						break;
				}
			};

			// subscribe to onCellClick
			this.myDataTable.subscribe('cellClickEvent', onCellClick);
				
		};
	};

});


