// Last modified: 04-20-05
var days_of_month = new Array("31","28","31","30","31","30","31","31","30","31","30","31"); // Total number of days in each month
var month_names = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
var win_width = 520;
var win_height = 500;
var leftpos = (screen.width) ? (screen.width-win_width)/2 : 0;
var toppos = (screen.height) ? (screen.height-win_height)/2 : 0;
var settings='height='+win_height+',width='+win_width+',top='+toppos+',left='+leftpos+',screenX='+leftpos+',screenY='+toppos+',scrollbars='+scroll+',resizable'
var buttonClicked = '';

function y2k(number) { return (number < 1000) ? number + 1900 : number; }

function isLeapYear(year) {                          
	return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ? true : false;
}

function isFilled(elm) {
	if (!elm || elm.value == "" || elm.value == null) return false;
   	else return true;
}

function isChecked(form,elementname) {
	
	var returnvalue = false;
    for(i=0; i<form.elements.length; i++) {
         var elem = form.elements[i]
		  if((elem.type == "checkbox" || elem.type == "radio") && elem.name == elementname) {
			   if(elem.checked == true)
				   returnvalue = true;
		  }
    }
	
	return returnvalue;
}

function checkForm(f) {
	var msg = "Please fix these errors:\n";
	var errors = false;
	
	if (f.fname.value == "") {
		msg+="-First name is required\n";
		errors = true;
	}
	if (f.lname.value == "") {
		msg+="-Last name is required\n";
		errors = true;
	}
	if (f.phone.value == "") {
		msg+="-Phone number is required\n";
		errors = true;
	}
	if (f.institution.value == "") {
		msg+="-Institution is required\n";
		errors = true;
	}
	if ( (f.email.value == "") || ( f.email.value.indexOf('@') == -1) ) {
		msg+="-Valid email is required\n";
		errors = true;
	}
	if (errors) {
		window.alert(msg);
		return false;
	}
		
	return true;
}

function verifyEdit(passwd_chars) {
	var msg = "Please fix these errors:\n";
	var errors = false;
	
	if ( (document.register.email.value != "") && ( document.register.email.value.indexOf('@') == -1) ) {
		msg+="-Valid email is required\n";
		errors = true;
	}
	if ( (document.register.password.value != "") && (document.register.password.value.length < passwd_chars) ) {
		msg+="-Min " + passwd_chars + " character password is required\n";
		errors = true;
	}
	if ( (document.register.password.value != "") && (document.register.password.value != document.register.password2.value) ) {
		msg+=("-Passwords to not match\n");
		errors = true;
	}
	if (errors) {
		window.alert(msg);
		return false;
	}
		
	return true;
}

function checkBrowser() {
	if ( (navigator.appName.indexOf("Netscape") != -1) && ( parseFloat(navigator.appVersion) <= 4.79 ) ) {
		newWin = window.open("","message","height=200,width=300");
		newWin.document.writeln("<center><b>This system is optimized for Netscape version 6.0 or higher.<br>" +
					"Please visit <a href='http://channels.netscape.com/ns/browsers/download.jsp' target='_blank'>Netscape.com</a> to obtain an update.");
		newWin.document.close();
	}
}

function help(file) {    
		window.open("help.php#" + file ,"",settings+',scrollbars');    
		void(0);    
}      

function setLocalTimeZone () {
						
	var timeBias = new Array(32)
	
	timeBias["-12"] = "neg_12";
	timeBias["-11"] = "neg_11";
	timeBias["-10"] = "neg_10";
	timeBias["-9"] = "neg_9";
	timeBias["-8"] = "neg_8";
	timeBias["-7"] = "neg_7";
	timeBias["-6"] = "neg_6";
	timeBias["-5"] = "neg_5";
	timeBias["-4"] = "neg_4";
	timeBias["-3.5"] = "neg_3.5";
	timeBias["-3"] = "neg_3";
	timeBias["-2.5"] = "neg_2.5";
	timeBias["-2"] = "neg_2";
	timeBias["-1"] = "neg_1";
	timeBias["0"] = "pos_0";
	timeBias["1"] = "pos_1";
	timeBias["2"] = "pos_2";
	timeBias["3"] = "pos_3";
	timeBias["3.5"] = "pos_3.5";
	timeBias["4"] = "pos_4";
	timeBias["5"] = "pos_5";
	timeBias["5.5"] = "pos_5.5";
	timeBias["6"] = "pos_6";
	timeBias["6.5"] = "pos_6.5";
	timeBias["7"] = "pos_7";
	timeBias["8"] = "pos_8";
	timeBias["9"] = "pos_9";
	timeBias["9.5"] = "pos_9.5";
	timeBias["10"] = "pos_10";
	timeBias["10.5"] = "pos_10.5";
	timeBias["11"] = "pos_11";
	timeBias["12"] = "pos_12";
	timeBias["13"] = "pos_13";
	
	var d = new Date();
	var gmtHours = d.getTimezoneOffset()/60;
	if (gmtHours != 0)
		gmtHours = 0 - gmtHours;
	var curTimeBias = document.getElementById(timeBias[gmtHours]);
	
	curTimeBias.selected = true;		

}					

function getUTCTime () {
		
	var curDateTime = new Date()
  var curHour = curDateTime.getHours() 
     + curDateTime.getTimezoneOffset()/60
  if (curHour > 24)  curHour -= 24
  if (curHour < 0) curHour += 24
  var curMin = curDateTime.getMinutes()
  var curSec = curDateTime.getSeconds()
  var curTime = 
    ((curHour < 10) ? "0" : "") + curHour + ":" 
    + ((curMin < 10) ? "0" : "") + curMin + ":" 
    + ((curSec < 10) ? "0" : "") + curSec 
  
	return curTime;
}

function reserve(type, resourceid, start_date, resid, scheduleid, providerid, is_blackout, view_date, read_only, pending, start_time, end_time) {  
		if (is_blackout == null) { is_blackout = 0; }
		
		var scroll = 'yes';
		
		if (resourceid == null) { resourceid = ''; }
		if (start_date == null) { start_date = ''; }
		if (resid == null) { resid = ''; }
		if (scheduleid == null) { scheduleid = ''; }
		if (providerid == null) { providerid = ''; }
		if (read_only == null) { read_only = ''; }
		if (pending == null) { pending = ''; }
		if (start_time == null) { start_time = ''; }
		if (end_time == null) { end_time = ''; }
		if (view_date == null) { 
			var d = new Date();
			view_date = d.getMonth() + "-" + d.getDate() + "-" + d.getFullYear(); 
		}

		nurl = "/provider/reserve.php?type=" + type + "&resourceid=" + resourceid + "&start_date=" + start_date + "&resid=" + resid + '&scheduleid=' + scheduleid + "&is_blackout=" + is_blackout + "&read_only=" + read_only + "&pending=" + pending + "&start_time=" + start_time + "&end_time=" + end_time + "&providerid=" + providerid + "&date=" + view_date;    
		var resWindow = window.open(nurl,"reserve",settings);
		if(resWindow.focus)
			resWindow.focus();
		void(0);   
}

function backlink(providerid) {  
		var sbWindow = window.open("backlink.php?providerid=" + providerid,"backlink",settings);
		if(sbWindow.focus)
			sbWindow.focus();
		void(0);   
}

function checkDate() {
	var formStr = document.getElementById("jumpWeek");
	var dayNum = new Array();
	dayNum = [31,28,31,30,31,30,31,31,30,31,30,31];
	
	var month = document.getElementById("jumpMonth").value;
	var day = document.getElementById("jumpDay").value;
	var year = document.getElementById("jumpYear").value;
	
	if ( (month > 12) || (day > dayNum[month-1]) ) {
		alert("Please enter valid date value");
		return false;
	}
	
	for (var i=0; i < formStr.childNodes.length-1; i++) {
		if (formStr.childNodes[i].type == "text" || formStr.childNodes[i].type == "textbox" ) {			
			if ( (formStr.childNodes[i].value <= 0) || (formStr.childNodes[i].value.match(/\D+/) != null) ) {
					alert("Please enter valid date value");
					formStr.childNodes[i].focus();
					return false;
			}
		}
	}
	
	changeScheduler(month, day, year, 0, "");
}

function verifyTimes(f) {
	if (f.del && f.del.checked) {
		return confirm("Cancel this appointment?");
	}
	if (parseFloat(f.startTime.value) < parseFloat(f.endTime.value)) {
		return true;
	}
	else {
		window.alert("End time must be later than start time\nCurrent start time: " + f.startTime.value + " Current end time: " + f.endTime.value);
		return false;
	}
}

function checkAdminForm() {
	var f = document.forms[0];
	for (var i=0; i< f.elements.length; i++) {
		if ( (f.elements[i].type == "checkbox") && (f.elements[i].checked == true) )
			return confirm('This will cancel all appointments and permission information for the checked items!\nContinue?');
	}
	alert("No boxes have been checked!");	
	return false;
}

function checkRateForm() {
	var f = document.forms[0];
	for (var i=0; i< f.elements.length; i++) {
		if ( (f.elements[i].type == "checkbox") && (f.elements[i].checked == true) )
			return confirm('This will delete all rate information for the checked items!\nContinue?');
	}
	alert("No boxes have been checked!");	
	return false;
}

function checkSectorForm(f) {
	for (var i=0; i< f.elements.length; i++) {
		if ( (f.elements[i].type == "checkbox") && (f.elements[i].checked == true) )
			return confirm('This will delete all sector information for the checked items!\nContinue?');
	}
	alert("No boxes have been checked!");	
	return false;
}

function checkLocationForm(f) {
	for (var i=0; i< f.elements.length; i++) {
		if ( (f.elements[i].type == "checkbox") && (f.elements[i].checked == true) )
			return confirm('This will delete all location information for the checked items!\nContinue?');
	}
	alert("No boxes have been checked!");	
	return false;
}

function checkProviderLocationForm(f) {
	for (var i=0; i< f.elements.length; i++) {
		if ( (f.elements[i].type == "checkbox") && (f.elements[i].checked == true) )
			return confirm('This will delete all service location information for the checked items!\nContinue?');
	}
	alert("No boxes have been checked!");	
	return false;
}

function checkBoxes() {
	var f = document.train;
	for (var i=0; i< f.elements.length; i++) {
		if (f.elements[i].type == "checkbox")
			f.elements[i].checked = true;
	}
	void(0);
}

function viewUser(user) {
	window.open("/provider/userinfo.php?user="+user,"UserInfo",settings);     
	void(0);    
}

function changeUser() {
	var w = 700;
	var h = 500;
	var leftpos = (screen.width) ? (screen.width-w)/2 : 0;
	var toppos = (screen.height) ? (screen.height-h)/2 : 0;
	var cursettings='height='+h+',width='+w+',top='+toppos+',left='+leftpos+',screenX='+leftpos+',screenY='+toppos+',scrollbars='+scroll+',resizable'
	window.open("/provider/user_select.php","selectuser",cursettings);     
	void(0);    
}

function changeToClient() {
	document.getElementById('change_to_client').style.visibility = 'hidden';
	document.getElementById('select_client').style.visibility = 'visible';
	changeUser();
}

function checkAddResource(f) {
	var msg = "";
	minRes = (parseInt(f.minH.value) * 60) + parseInt(f.minM.value);
	maxRes = (parseInt(f.maxH.value) * 60) + parseInt(f.maxM.value);
	
	if (f.name.value=="")
		msg+="-Resource name is required.\n";
	if (parseInt(minRes) > parseInt(maxRes))
		msg+="-Minimum reservaion time must be less than or equal to maximum";
	if (msg!="") {
		alert("You have the following errors:\n\n"+msg);
		return false;
	}
	
	return true;
}

// check for adding a rate
function checkAddRate(f) {
	var msg = "";

	if (f.duration.value == "")
		msg+="-Duration is required.\n";
	if (f.resourceid.selectedIndex < 0)
		msg+="-Please select a Resource";
	if (f.rate.value == "")
		msg+="-Please select a Rate";
	if (msg!="") {
		alert("You have the following errors:\n\n"+msg);
		return false;
	}
	
	return true;
}

// check for adding a sector
function checkAddSector(f) {
	var msg = "";

	if (f.sectorname.value == "")
		msg+="-Sector name is required.\n";
		
	if (f.subdomain.value == "")
		msg+="-Sub-domain is required.\n";
	
	if (f.description.value == "")
		msg+="-Sector description is required.\n";
		
	if (msg!="") {
		alert("You have the following errors:\n\n"+msg);
		return false;
	}
	
	return true;
}

// check for adding a location
function checkAddLocation(f) {
	var msg = "";

	if (f.location.value == "")
		msg+="-Location is required.\n";
	
	if (f.subdomain.value == "")
		msg+="-Sub-domain is required.\n";
	
	if (f.description.value == "")
		msg+="-Location description is required.\n";

	if (msg!="") {
		alert("You have the following errors:\n\n"+msg);
		return false;
	}
	
	return true;
}


// check for adding a provider location
function checkAddProviderLocation(f) {
	var msg = "";

	if (f.locationdescription.value == "")
		msg+="-Location description is required.\n";
	if (f.address.value == "")
		msg+="-A street address is required.\n";
	if (f.city.value == "")
		msg+="-A city is required.\n";
	if (f.stateid.selectedIndex == 0)
	    msg+="-A state is required.\n";
	if (f.zipcode.value == "")
		msg+="-A zipcode code is required.\n";
		
	if (msg!="") {
		alert("You have the following errors:\n\n"+msg);
		return false;
	}
	
	return true;
}

function checkAddSchedule() {
	var f = document.addSchedule;
	var msg = "";
	
	if (f.scheduleTitle.value=="")
		msg+="-Schedule title is required.\n";
	if (parseInt(f.dayStart.value) > parseInt(f.dayEnd.value))
		msg+="-Invalid start/end times.\n";
	if (f.viewDays.value == "" || parseInt(f.viewDays.value) <= 0)
		msg+="Invalid view days.\n";
	if (f.dayOffset.value == "" || parseInt(f.dayOffset.value) < 0)
		msg+="Invalid day offset.\n";
	if (f.adminEmail.value == "")
		msg+="Admin email is required.\n";

	if (msg!="") {
		alert("You have the following errors:\n\n"+msg);
		return false;
	}
	
	return true;
}

function checkAccountForm(form) {
	
	// check that we have a password
	if (isFilled(form.password) == false) {
		alert("You must provide a Password.");
		form.password.focus();
		return false;
	}
	
	// check that we have a password confirm
	if (isFilled(form.password2) == false) {
		alert("You must provide a Confirm Password.");
		form.password2.focus();
		return false;
	}
	
	// check that the password and the confirm password are the same
	if (form.password.value != form.password2.value) {
		alert("The Password and Confirm Password do not match.");
		form.password.focus();
		return false;
	}
	
	if (form.password.value.length < 6) {
		alert("You must provide a Password of minimum length of 6 characters.");
		form.password.focus();
		return false;
	}

	return true;
	
}

function checkAllBoxes(box) {
    var f = document.forms[0];
	
	for (var i = 0; i < f.elements.length; i++) {
		if (f.elements[i].type == "checkbox" && f.elements[i].name != "notify_user")
			f.elements[i].checked = box.checked;
	}

	void(0);
}

function check_reservation_form(f) {
	
	var recur_ok = false;
	var days_ok = false;
	var is_repeat = false;
	var msg = "";
	
	if (f.interval.value != "none") {
		is_repeat = true;
		if (f.interval.value == "week" || f.interval.value == "month_day") {
			for (var i=0; i < f.elements["repeat_day[]"].length; i++) {
				if (f.elements["repeat_day[]"][i].checked == true)
					days_ok = true;
			}
		}
		else {
			days_ok = true;
		}
		
		if (f.repeat_until.value == "") {
			msg += "- Please choose an ending date\n";
			recur_ok = false;
		}
	}
	else {
		recur_ok = true;
		days_ok = true;
	}
	
	if (days_ok == false) {
		recur_ok = false;
		msg += "- Please select days to repeat on";
	}
	
	if (msg != "")
		alert(msg);
		
	return (msg == "");
}

function check_for_delete(f) {
	if (f.del && (f.del.type == 'checkbox' && f.del.checked == true || f.del.type == 'hidden' && f.del.value == "true"))
		return confirm('Cancel this appointment?');
}

function toggle_fields(box) {
	document.forms[0].elements["table," + box.value + "[]"].disabled = (box.checked == true) ? false : "disabled";
}

function search_user_lname(letter) {
	var frm = navigator.appName == 'Microsoft Internet Explorer' ? document.name_search : document.forms['name_search'];
	frm.fname.value = "";
	frm.lname.value=letter;
	frm.submit();
}

function isIE() {
	return (navigator.appName == 'Microsoft Internet Explorer' ? true : false);
}

function changeDate(month, year) {
	var frm = navigator.appName == 'Microsoft Internet Explorer' ? document.changeMonth : document.forms['changeMonth'];
	frm.month.value = month;
	frm.year.value = year;
	frm.submit();
}

// Function to change the Scheduler on selected date click
function changeScheduler(m, d, y, isPopup, scheduleid) {
	newDate = m + '-' + d + '-' + y;
	keys = new Array();
	vals = new Array();

	// Get everything up to the "?" (if it even exists)
	var queryString = (isPopup) ? window.opener.document.location.search.substring(0): document.location.search.substring(0);
	queryString = queryString.replace("?", "");

	var pairs = queryString.split('&');
	var url = (isPopup) ? window.opener.document.URL.split('?')[0] : document.URL.split('?')[0];
	var schedid = ""
	
	if (scheduleid == "") {
		for (var i=0;i<pairs.length;i++)
		{
			var pos = pairs[i].indexOf('=');
			if (pos >= 0)
			{
				var argname = pairs[i].substring(0,pos);
				var value = pairs[i].substring(pos+1);
				keys[keys.length] = argname;
				vals[vals.length] = value;		
			}
		}
		
		for (i = 0; i < keys.length; i++) {
			if (keys[i] == "scheduleid") {
				schedid = vals[i];
			}
		}
	}
	else {
		schedid	= scheduleid;
	}
	
	if (isPopup)
		window.opener.location = url + "?date=" + newDate + "&scheduleid=" + schedid;
	else
		document.location.href = url + "?date=" + newDate + "&scheduleid=" + schedid;
}

function showSummary(object, e, text, restype) {
	myLayer = document.getElementById(object);
	myLayer.innerHTML = text;
	
	// if no restype, use default background color and font color
	if (!restype) {
		bgcolor = "#ffffff";
		color = "#000000";
	}
	else
		switch (restype) {
			case "booked": 
				bgcolor = "#ff6600";
				color = "#ffffff";
				break;
			case "blackout":
				bgcolor = "#999999";
				color = "#ffffff";
				break;
			default:
				bgcolor = "#ffffff";
				color = "#000000";
		}
		
	w = parseInt(myLayer.style.width);
	h = parseInt(myLayer.style.height);

    if (e != '') {
        if (navigator.appName == 'Microsoft Internet Explorer') {
            x = e.clientX;
            y = e.clientY;
            browserX = document.body.offsetWidth - 25;
			x += document.body.scrollLeft;			// Adjust for scrolling on IE
    		y += document.body.scrollTop;
        }
        else {
            x = e.pageX;
            y = e.pageY;
            browserX = window.innerWidth - 35;
        }
    }
	
	x1 = x + 20;		// Move out of mouse pointer
	y1 = y + 20;
	
	// Keep box from going off screen
	if (x1 + w > browserX)
		x1 = browserX - w;
    
	myLayer.style.left = parseInt(x1)+ "px";
	myLayer.style.top = parseInt(y1) + "px";
	myLayer.style.background = bgcolor;
	myLayer.style.color = color;
	myLayer.style.visibility = "visible";
}

function moveSummary(object, e) {

	myLayer = document.getElementById(object);
	w = parseInt(myLayer.style.width);
	h = parseInt(myLayer.style.height);

    if (e != '') {
        if (navigator.appName == 'Microsoft Internet Explorer') {
            x = e.clientX;
            y = e.clientY;
			browserX = document.body.offsetWidth -25;
			x += document.body.scrollLeft;
			y += document.body.scrollTop;
        }
        else {
            x = e.pageX;
            y = e.pageY;
			browserX = window.innerWidth - 30;
        }
    }

	x1 = x + 20;	// Move out of mouse pointer	
	y1 = y + 20;
	
	// Keep box from going off screen
	if (x1 + w > browserX)
		x1 = browserX - w;

    myLayer.style.left = parseInt(x1) + "px";
    myLayer.style.top = parseInt(y1) + "px";
}

function hideSummary(object) {
	myLayer = document.getElementById(object);
	myLayer.style.visibility = 'hidden';
}

function resOver(cell, color) {
	cell.style.backgroundColor=color;
	cell.style.cursor='hand'
}

function resOut(cell, color) {
	cell.style.backgroundColor = color;
}

function showHideDays(opt) {
	e = document.getElementById("days");
	
	if (opt.options[2].selected == true || opt.options[4].selected == true) {
		e.style.visibility = "visible";
		e.style.display = navigator.appName == 'Microsoft Internet Explorer' ? "inline" : "table";
	}
	else {
		e.style.visibility = "hidden";
		e.style.display = "none";
	}
	
	e = document.getElementById("week_num")
	if (opt.options[4].selected == true) {
		e.style.visibility = "visible";
		e.style.display = navigator.appName == 'Microsoft Internet Explorer' ? "inline" : "table";
	}
	else {
		e.style.visibility = "hidden";
		e.style.display = "none";
	}
}

function chooseDate(input_box, m, y) {
	var file = "recurCalendar.php?m=" + m + "&y="+ y;
	if (navigator.appName == 'Microsoft Internet Explorer') {
		yVal = "top=" + 200;
		xVal = "left=" + 500;
	}
	if (!navigator.appName == 'Microsoft Internet Explorer') {
		yVal = "screenY=" + 200;
		xVal = "screenX=" + 500
	}
	window.open(file, "calendar",yVal + "," + xVal + ",height=270,width=220,resizable=no,status=no,menubar=no");
	void(0);
}

function selectRecurDate(m, d, y, isPopup) {
	f = window.opener.document.forms[0];
	f._repeat_until.value = m + "/" + d + "/" + y;
	f.repeat_until.value = f._repeat_until.value;
	window.close();
}

function setSchedule(sid) {
	f = document.getElementById("setDefaultSchedule");
	f.scheduleid.value = sid;
	f.submit();
}

function changeSchedule(sel) {
	var url = document.URL.split('?')[0];
	document.location.href = url + "?scheduleid=" + sel.options[sel.selectedIndex].value;
}

function showHideCpanelTable(element) {
	var expires = new Date();
	var time = expires.getTime() + 2592000000;
	expires.setTime(time);
	var showHide = "";
	if (document.getElementById(element).style.display == "none") {
		document.getElementById(element).style.display='block';
		showHide = "show";
	} else {
		document.getElementById(element).style.display='none';
		showHide = "hide";
	}
	
	document.cookie = element + "=" + showHide + ";expires=" + expires.toGMTString();
}

function changeLanguage(opt) {
	var expires = new Date();
	var time = expires.getTime() + 2592000000;
	expires.setTime(time);
	document.cookie = "lang=" + opt.options[opt.selectedIndex].value + ";expires=" + expires.toGMTString() + ";path=/";
	document.location.href = document.URL;
}

function clickTab(tabid, panel_to_show) {
	document.getElementById(tabid.getAttribute("id")).className = "tab-selected";
	rows = document.getElementById("tab-container").getElementsByTagName("td");
	for (i = 0; i < rows.length; i++) {
		if (rows[i].className == "tab-selected" && rows[i] != tabid) {
			rows[i].className = "tab-not-selected";
		}
	}

	div_to_display = document.getElementById(panel_to_show);
	div_to_display.style.display = navigator.appName == 'Microsoft Internet Explorer' ? "inline" : "table";
	divs = document.getElementById("main-tab-panel").getElementsByTagName("div");

	for (i = 0; i < divs.length; i++) {
		// only hide panels with prefix "pnl"
		if (divs[i] != div_to_display && divs[i].getAttribute("id").substring(0,3) == "pnl") {
			divs[i].style.display = "none";
		}
	}
}

function checkCalendarDates() {
	var table = document.getElementById("repeat_table");
	if (table == null) return;
	
	// If the start/end date are not equal, hide the whole repeat section
	if (document.getElementById("hdn_start_date").value != document.getElementById("hdn_end_date").value) {
		table.style.display = "none";
		table.style.visibility = "hidden";	
	}
	else {
		table.style.display = navigator.appName == 'Microsoft Internet Explorer' ? "inline" : "table";
		table.style.visibility = "visible";
	}
}

function showHideMinMax(chk) {
	document.getElementById("minH").disabled = document.getElementById("minM").disabled = document.getElementById("maxH").disabled = document.getElementById("maxM").disabled= chk.checked
}

function moveSelectItems(from, to) {
	from_select = document.getElementById(from);
	to_select = document.getElementById(to);
	
	for (i = 0; i < from_select.options.length; i++) {
		if (from_select.options[i].selected) {
			if (navigator.appName == 'Microsoft Internet Explorer') {
				var option = new Option(from_select.options[i].text, from_select.options[i].value);
				to_select.options.add(option);
				from_select.options.remove(i);
			}
			else {
				to_select.options.add(from_select.options[i]);
			}
			i--;
		}
	}
}

function selectUsers() {
	if (document.getElementById("invited_users")) {
		selectbox = document.getElementById("invited_users");
		for (i = 0; i < selectbox.options.length; i++) {
			selectbox.options[i].selected = true;
		}
	}
}

function changeMyCal(m, d, y, view) {
	var url = document.URL.split('?')[0];
	document.location.href = url + "?date=" + m + "-" + d + "-" + y + "&view=" + view;
}

function changeResCalendar(m, d, y, view, id) {
	var url = document.URL.split('?')[0];
	var type_id = id.split("|");
	var type = type_id[0];
	var p = (type == "s") ? "scheduleid" : "resourceid";
	var id = type_id[1];
	document.location.href = url + "?date=" + m + "-" + d + "-" + y + "&view=" + view + "&" + p + "=" + id;
}

function selectUserForReservation(memberid, fname, lname) {
	var doc = window.opener.document;
	doc.forms[0].memberid.value = memberid;
	
	if (fname && fname != null && lname && lname != null)
		doc.getElementById('name').innerHTML = fname + " " + lname;

	window.close();
}

function adminRowClick(checkbox, row_id, count) {
	var row = document.getElementById(row_id);
	row.className = (checkbox.checked) ? "adminRowSelected" : "cellColor" + (count%2);
}

// Re-populate the days select list when month is changed
function selectDays(begday) {                              

	var today = new Date(); 
	var selected_month = document.getElementById('monthselid').value;
	var selected_year = document.getElementById('yearselid').value;
	
	//Check the year... some browsers return a three digit equivalent
	if(today.getYear() < 1900) {                       
		this_year = (today.getYear() + 1900);
	}
	else {
		this_year = today.getYear();
	}
	
	// get the maximum number of days for the selected month
	if((isLeapYear(selected_year) == true) && (selected_month == 2)) {
		var max_days = 29;
	}
	else {
		var max_days = days_of_month[selected_month-1];
	}
	
	// re-build the day picker
	// don't display any days in the past
	if (selected_year == this_year && selected_month == today.getMonth()+1)
		start_day = today.getDate();
	else
		start_day = 1; 
	
	var days = '<select class="formfield" id="dateselid" name="day">';
	for(i=start_day ; i<=max_days ; i++) {
		if (i == begday)
			days += '<option value="' + i +'" selected>' + i + '</option>';
		else
			days += '<option value="' + i +'">' + i + '</option>';
	}
	days += '</select>';

	// set the DOM object for the day
	if (document.getElementById("dayid"))
		document.getElementById("dayid").innerHTML = days;

}

// Re-populate the months select list when year is changed
function selectMonths(begmonth,begday) {                            
		
	var today = new Date();
	
	//Check the year... some browsers return a three digit equivalent
	if(today.getYear() < 1900) {                       
		this_year = (today.getYear() + 1900);
	}
	else {
		this_year = today.getYear();
	}
	
	// re-build the month date picker                       
	// don't display any months in the past
	if (document.getElementById('yearselid').value == this_year)
		start_month = today.getMonth();
	else
		start_month = 0; 
		
	var mnth = '<select class="formfield" id="monthselid" name="month" onChange="selectDays();">';
	for(x=start_month ; x<12 ; x++) {
		if (x == begmonth)
			mnth += '<option value="' + (x+1) +'" selected>' + month_names[x] + '</option>';
		else
			mnth += '<option value="' + (x+1) +'">' + month_names[x] + '</option>';
	}
	mnth += '</select>';
	
	// set the DOM object for the date
	document.getElementById("monthid").innerHTML = mnth;
	
	// re-build the days selector
	if (document.getElementById("dayid"))
		selectDays(begday);

}

function checkMemberRegisterForm(form,passwd_chars,edit) {
	
	if (isFilled(form.username) == false) {
		alert("You must provide a Username");
		form.username.focus();
		return false;
	}
	
	if (isFilled(form.fname) == false) {
		alert("You must provide your First Name");
		form.fname.focus();
		return false;
	}
	
	if (isFilled(form.lname) == false) {
		alert("You must provide your Last Name");
		form.lname.focus();
		return false;
	}

	if (isFilled(form.phone) == false || (isFilled(form.phone) == true && !validateElement(form.phone,'phonenumber'))) {
		alert("You must provide a valid Phone Number. A valid example is '123-123-1234'");
		form.phone.focus();
		return false;
	}
	
	if (isFilled(form.address) == false) {
	    alert("You must provide your Mailing Address.");
		form.address.focus();
	    return false;
	}
	
	if (isFilled(form.city) == false) {
	    alert("You must provide your City.");
		form.city.focus();
	    return false;
	}
	
	if (form.stateid.selectedIndex == 0) {
		alert("You must select your State.");
		form.stateid.focus();
		return false;
	}
	
	if (isFilled(form.zipcode) == false || (isFilled(form.zipcode) == true && !validateElement(form.zipcode,'zipcode'))) {
	  alert("You must provide a valid Zip Code. A valid example is '12345'");
		form.zipcode.focus();
	  return false;
	}
	
	if (form.gender.selectedIndex == 0) {
		alert("You must select your Gender.");
		form.gender.focus();
		return false;
	}
	
	if (isFilled(form.email) == false || (isFilled(form.email) == true && !validateElement(form.email,'emailaddress'))) {
		alert("You must provide a valid Email Address.");
		form.email.focus();
		return false;
	}

	if (edit == "") {

		// check that we have a password
		if (isFilled(form.password) == false) {
			alert("You must provide a Password.");
			form.password.focus();
			return false;
		}
		
		// check that we have a password confirm
		if (isFilled(form.password2) == false) {
			alert("You must provide a Confirm Password.");
			form.password2.focus();
			return false;
		}
		
		// check that the password and the confirm password are the same
		if (form.password.value != form.password2.value) {
			alert("The Password and Confirm Password do not match.");
			form.password.focus();
			return false;
		}
		
		if (form.password.value.length < passwd_chars) {
			alert("You must provide a Password of minimum length of " + passwd_chars + " characters.");
			form.password.focus();
			return false;
		}
	
	}
	
	return true;
	
}

function checkProviderRegisterForm(form,view,passwd_chars) {
	
	if (view && view == 'profile') {
		
		if (isFilled(form.username) == false) {
			alert("You must provide a Username");
			form.username.focus();
			return false;
		}
		
		if (isFilled(form.fname) == false) {
			alert("You must provide your First Name");
			form.fname.focus();
			return false;
		}
		
		if (isFilled(form.lname) == false) {
			alert("You must provide your Last Name");
			form.lname.focus();
			return false;
		}
		
		if (isFilled(form.phone) == false) {
			alert("You must provide your Phone Number");
			form.phone.focus();
			return false;
		}
		
		if (isFilled(form.address) == false) {
				alert("You must provide your Mailing Address.");
			form.address.focus();
				return false;
		}
		
		if (isFilled(form.city) == false) {
				alert("You must provide your City.");
			form.city.focus();
				return false;
		}
		
		if (form.stateid.selectedIndex == 0) {
				alert("You must select your State.");
				form.stateid.focus();
				return false;
			}
		
		if (isFilled(form.zipcode) == false) {
				alert("You must provide your Zip Code.");
			form.zipcode.focus();
				return false;
		}
		
		if (isFilled(form.email) == false) {
			alert("You must provide your Email Address");
			form.email.focus();
			return false;
		}
		
		checkPassword(form,passwd_chars);
		
	}
	
	if (view && view == 'who') {
	
		if (isFilled(form.bio) == false) {
			alert("You must provide your Bio");
			form.bio.focus();
			return false;
		}

	}
	
	return true;
	
}

function checkProviderSetupForm(form) {
	
	// set total number of days from starting workday to the last workday
	var daysfound = new Array();
	// get an array of days found to be checked
	daysfound = daysFound(form);
	
	if (isFilled(form.bio) == false) {
		alert("You must provide a short Bio.");
		form.bio.focus();
		return false;
	}
	
	if (isFilled(form.services) == false) {
		alert("You must provide a short description of your Services.");
		form.services.focus();
		return false;
	}
	
	if (isFilled(form.scheduleTitle) == false) {
		alert("You must provide a Schedule Title.");
		form.scheduleTitle.focus();
		return false;
	}
	
	if (daysfound && daysfound.length == 0) {
		alert("You must select at least one Work day.");
		//form.workday.focus();
		return false;
	}
	
	if (!checkConsecutiveDays(form)) {
		alert("The workdays selected are not consecutive. Please try again.");
		//form.workday.focus();
		return false;
	}
	
	if (form.dayStart.selectedIndex == 0) {
		alert("Please select the time of day when your first appointment starts.");
		form.dayStart.focus();
		return false;
	}
	
	if (form.dayEnd.selectedIndex == 0) {
		alert("Please select the time of day when your last appointment starts.");
		form.dayEnd.focus();
		return false;
	}
	
	if (parseInt(form.dayStart.value) > parseInt(form.dayEnd.value)) {
		alert("Appointment start and end times overlap.");
		form.dayStart.focus();
		return false;
	}
	
	if (form.timeSpan.selectedIndex == 0) {
		alert("Please select the length of an appointment.");
		form.timeSpan.focus();
		return false;
	}
	
	if (isFilled(form.rate) == false) {
		alert("Please provide a rate for an appointment.");
		form.rate.focus();
		return false;
	}
	
	if (isFilled(form.locationdescription) == false) {
		alert("Please provide a Title for your location.");
		form.locationdescription.focus();
		return false;
	}
	
	if (isFilled(form.address) == false) {
		alert("Please provide an Address for your location.");
		form.address.focus();
		return false;
	}
	
	if (isFilled(form.city) == false) {
		alert("Please provide a City for your location.");
		form.city.focus();
		return false;
	}

	if (form.stateid.selectedIndex == 0) {
		alert("Please select a State for your location.");
		form.stateid.focus();
		return false;
	}
	
	if (isFilled(form.zipcode) == false) {
		alert("Please provide a Zipcode for your location.");
		form.zipcode.focus();
		return false;
	}
	
	// set hidden form variable
	document.getElementById('viewdaysid').value = daysfound.length;
		
	return true;
	
}

function checkPassword(form,passwd_chars) {
	
	// check that we have a password
	if (isFilled(form.password) == false) {
		alert("You must provide a Password.");
		form.password.focus();
		return false;
	}
	
	// check that we have a password confirm
	if (isFilled(form.password2) == false) {
		alert("You must provide a Confirm Password.");
		form.password2.focus();
		return false;
	}

	// check that the password and the confirm password are the same
	if (form.password.value != form.password2.value) {
		alert("The Password and Confirm Password do not match.");
		form.password.focus();
		return false;
	}
	
	if (form.password.value.length < passwd_chars) {
		alert("You must provide a Password of minimum length of " + passwd_chars + " characters.");
		form.password.focus();
		return false;
	}
	
}

function checkProviderProfileForm(form,view) {

	if (view && view == 'profile') {
		
		if (isFilled(form.username) == false) {
			alert("You must provide a Username");
			form.username.focus();
			return false;
		}
		
		if (isFilled(form.fname) == false) {
			alert("You must provide your First Name");
			form.fname.focus();
			return false;
		}
		
		if (isFilled(form.lname) == false) {
			alert("You must provide your Last Name");
			form.lname.focus();
			return false;
		}
		
		if (form.gender.selectedIndex == 0) {
			alert("You must provide your Gender");
			form.gender.focus();
			return false;
		}
		
		if (isFilled(form.phone) == false) {
			alert("You must provide your Phone Number");
			form.phone.focus();
			return false;
		}
		
		if (isFilled(form.address) == false) {
				alert("You must provide your Mailing Address.");
			form.address.focus();
				return false;
		}
		
		if (isFilled(form.city) == false) {
				alert("You must provide your City.");
			form.city.focus();
				return false;
		}
		
		if (form.stateid.selectedIndex == 0) {
				alert("You must select your State.");
				form.stateid.focus();
				return false;
			}
		
		if (isFilled(form.zipcode) == false) {
				alert("You must provide your Zip Code.");
			form.zipcode.focus();
				return false;
		}
		
		if (isFilled(form.email) == false) {
			alert("You must provide your Email Address");
			form.email.focus();
			return false;
		}
	}
	else if (view && view == 'who') {
		if (isFilled(form.bio) == false) {
			alert("You must provide your Bio");
			form.bio.focus();
			return false;
		}
	}
	else if (view && view == 'what') {
		if (isFilled(form.services) == false) {
			alert("You must provide your Services");
			form.services.focus();
			return false;
		}
	
		if (form.sectorid.selectedIndex == 0) {
			alert("You must select a Sector.");
			form.sectorid.focus();
			return false;
		}
	}
	else {
			alert("Unable to determine the view");
			return false;
	}
	
	return true;
	
}

function checkConsumerAccountForm(form) {
	
	// check that we have a password
	if (isFilled(form.password) == false) {
		alert("You must provide a Password.");
		form.password.focus();
		return false;
	}
	
	// check that we have a password confirm
	if (isFilled(form.password2) == false) {
		alert("You must provide a Confirm Password.");
		form.password2.focus();
		return false;
	}
	
	// check that the password and the confirm password are the same
	if (form.password.value != form.password2.value) {
		alert("The Password and Confirm Password do not match.");
		form.password.focus();
		return false;
	}
	
	if (form.password.value.length < 6) {
		alert("You must provide a Password of minimum length of 6 characters.");
		form.password.focus();
		return false;
	}

	return true;
	
}

function checkResetPasswordForm(form) {
	
	if (form.password && isFilled(form.password) == true && form.password.value.length < 6) {
		alert("You must provide a Password of minimum length of 6 characters.");
		form.password.focus();
		return false;
	}

	return true;
}

function checkSearchForm(form) {
		
	var msg = "";
	
	// see which submit button was clicked
	if (buttonClicked == 'search' || buttonClicked == 'browse') {
		
		// search requires sector and location
		
		if (buttonClicked == 'search') {
			if (form.searchsectorid.selectedIndex == 0)
				msg+="-Please select a sector.\n";
			if (form.searchlocationid.selectedIndex == 0)
				msg+="-Please select a location.\n";
		}
		// browse requires either a sector or a location
		//else if (buttonClicked == 'browse') {
			//if (form.searchsectorid.selectedIndex == 0 && form.searchlocationid.selectedIndex == 0)
				//msg+="-Please select either a sector or a location.\n";
		//}
		
		if (msg!="") {
			alert("You have the following errors:\n\n"+msg);
			return false;
		}
		else {
			form.formaction.value = buttonClicked;
			form.submit();
			return true;
		}
	}
	else {
		form.formaction.value = 'reset';
		return true;
	}
}

function checkQoTScheduleForm(f) {

	var msg = "";
	
	if (!checkConsecutiveDays(f))
		msg+="-The workdays selected are not consecutive. Please try again.\n";
	if (f.dayStart.selectedIndex == 0)
		msg+="-Please select the time of day when your first appointment starts.\n";
	if (f.dayEnd.selectedIndex == 0)
		msg+="-Please select the time of day when your last appointment starts.\n";
	if (parseInt(f.dayStart.value) > parseInt(f.dayEnd.value))
		msg+="-Invalid appointment start/end times.\n";
	if (f.timeSpan.selectedIndex == 0)
		msg+="-Please select the length of an appointment.\n";
	if (f.rate.value == "")
		msg+="-Please provide a rate for an appointment.\n";
	
	if (msg!="") {
		alert("You have the following errors:\n\n"+msg);
		return false;
	}
	
	// set total number of days from starting workday to the last workday
	var daysfound = new Array();
	// get an array of days found to be checked
	daysfound = daysFound(f);
	document.getElementById('viewdaysid').value = daysfound.length;

	return true;
}

function daysFound(form) {
	
	var days = new Array();
	var j = 0;
	
	// determine the days found to be checked
	for (var i = 0; i<form.elements.length; i++) {
		if ((form.elements[i].name.indexOf('workday') > -1)) {
			if (form.elements[i].checked) {
				days[j] = form.elements[i].value;
				j++;
			}
		}
	}

	return days;
}

function checkConsecutiveDays(form) {
	
	var consecutive = true;
	var j = 0;
	var daysfound = new Array();
	
	// get an array of days found to be checked
	daysfound = daysFound(form);
	
	// determine if the days selected are consectutive
	if (daysfound && daysfound.length > 0) {
		
		// determine starting day index
		for (dayindex=0; dayindex<daysfound.length; dayindex++) {
			if (dayindex == 0) {
				cur = dayindex;
				firstdayindex = cur;
			}
			else {
				prev = cur;
				cur = dayindex;
				if(Math.abs(daysfound[cur]-daysfound[prev]) != 1)
					firstdayindex = dayindex;
			}
		}
		
		// set hidden form with first day index
		document.getElementById('weekdaystartid').value = daysfound[firstdayindex];
		
		//alert('firstdayindex: ' + firstdayindex + ' value: ' + daysfound[firstdayindex]);
		
		// from the first day index, see if the following days are consecutive
		k = firstdayindex;
		count = 0;
		while(count < daysfound.length) {
			if (k == firstdayindex)
				cur = k;
			else {
				prev = cur;
				if (cur == daysfound.length-1) {
					cur = 0;
					k = 0;
				}
				else
					cur = k;
					
				//alert('cur daysfound['+cur+']:' + daysfound[cur] + ' prev daysfound['+prev+']:' + daysfound[prev] + ' diff: ' + Math.abs(daysfound[cur]-daysfound[prev]));
				if(Math.abs(daysfound[cur]-daysfound[prev]) != 1) {
					if(daysfound[cur] == 0 && daysfound[prev] == 6)
						;
					else
						consecutive = false;	
				}
			}	
			k++;
			count++;
		}
		
	}
	else {
		return false;
	}
	
	if (!consecutive)
		return false;
	else
		return true;

}

function formatAmount(e, field) {
	if (!(navigator.appName == "Netscape" || navigator.appName == "Microsoft Internet Explorer"))
		return;
	
	var key;
	if (navigator.appName == 'Microsoft Internet Explorer') {
		key=e.keyCode;
	}
	else {
		key=e.which;
		if (key==13) //return pressed
		return;
	}
	if ((key==37)||(key==39)) //left or right arrow
		return;
	
	temp=field.value.replace(/[^0-9]/g,"");
	temp=temp.replace(/^0+/,"");
	
	while (temp.length<3)
		temp="0"+temp;
	
	if (field.value.search(/-/)!=-1)
		temp="-"+temp;
	
	field.value=temp.substr(0,temp.length-2)+"."+temp.substr(temp.length-2);
}

function checkLoginForm(f) {
	
	var msg = "Please fix these errors:\n";
	var errors = false;

	if (f.username.value == "") {
		msg+="-Username is required\n";
		errors = true;
	}
	if (f.password.value == "") {
		msg+="-Your password is required\n";
		errors = true;
	}
	if (errors) {
		window.alert(msg);
		return false;
	}
		
	return true;

}

// show roster link for a provider booking for a client
function displayRosterLink(attr) {
	document.getElementById('client_roster').style.visibility = attr;	
}

// Validator Object
var valid = new Object();

// REGEX Elements

// matches zipcode codes
//valid.zipcode = /\d{5}(-\d{4})?/;
valid.zipcode = /\d{5}/;

// matches $17.23 or $14,281,545.45 or ...
valid.currency = /\$\d{1,3}(,\d{3})*\.\d{2}/;

// matches 5:04 or 12:34 but not 75:83
valid.time = /^([1-9]|1[0-2]):[0-5]\d$/;

//matches email
valid.emailaddress = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;

// matches phone ###-###-####
valid.phonenumber = /^\(?\d{3}\)?\s|-\d{3}-\d{4}$/;

// International Phone Number
valid.phonenumberinternational = /^\d(\d|-){7,20}/;

// IP Address
valid.ipaddress = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;

// Date xx/xx/xxxx
valid.Date = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;

// State Abbreviation
valid.state = /^(AK|AL|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MI|MN|MO|MS|MT|NB|NC|ND|NH|NJ|NM|NV|NY|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VA|VT|WA|WI|WV|WY)$/i;

// Social Security Number
valid.ssn = /^\d{3}\-\d{2}\-\d{4}$/;

function validateElement(element,type) {

	var pattern = valid[type]; 
	var matched = pattern.exec(element.value); 
	
	if(!matched)               
		return false;

	return true;

}
