var apptSummaryResponseSchema = {resultsList : "data",fields : ["appt_id", "customer_name", "description", "start_tm", "end_tm", "inspector", "street1", "city", "state", "zip", "price", "requested", "appt_status"]};


function formatDate(inputFld) {
	
	if(inputFld != null) {
		var stdToken = '-';
		var inputVal = inputFld.value.replace(/[\s]/g, '').replace(/\//g, stdToken);
		if(inputVal.length >= 8) {
			if(isNum(inputVal, stdToken)) {
				inputValues = inputVal.split(stdToken);
				if(inputValues.length == 3) {
					inputFld.value = roundSingleDigitDayOrMonth(inputValues[0])+'-'+
												 roundSingleDigitDayOrMonth(inputValues[1])+'-'+
												 inputValues[2];
					return;
				}
				else if(inputValues.length == 2 && inputVal.length == 9) {
					inputFld.value = splitDate((inputValues[0]+inputValues[1]), false);
					return;
				}
				else if(inputValues.length == 1) {
					inputFld.value = splitDate( inputValues[0], false);
					return;
				}
			}
		}
		inputFld.value = inputVal;
	}
}

function formatPhone(inputFld) {
	if(inputFld != null) {
		inputFld.value = formatPhoneValue(inputFld.value);
	}
}

function formatPhoneValue(value){
	if (!value || value == "") {
		return '';	
	}
	var inputVal = value.replace(/[\s]/g, '');
	if(inputVal.length == 10) {
		if(isNum(inputVal, '-')) {
			var formattedVal = inputVal.replace(/-/g, '');
			if(formattedVal.length > 6) {
				return formattedVal.substring(0,3)+'-'+formattedVal.substring(3,6)+'-'+formattedVal.substring(6);
			}
			else if(formattedVal.length > 3) {
				return formattedVal.substring(0,3)+'-'+formattedVal.substring(3);
			}
			else if(formattedVal.length > 0) {
				return formattedVal;
			}
		}
	}
	return inputVal;
}

//validates phone is in 999-999-9999 format
function invalidPhonePattern(phone) {
   	var previous = '-';
   	
   	if (!phone) {
   		return true;
   	}
   	
   	//Check that it only has numbers and hyphens
   	if (!isNum(phone, '-')) {
   		return true;
   	}
   	
   	//Check if it has any hyphens.
   	phoneStr = String(phone);
   	
   	if (phoneStr.indexOf("-") < 0) {
   		return true;
   	}

   	phoneStr = trim(phoneStr);
   	
   	//Check for correct length
	if (phoneStr.length != 12) {
		return true;
	}

	for (var i = 0; i < phoneStr.length; i++) {
		var ch = phoneStr.charAt(i);
		if (i == 3 || i == 7) {
			if (ch != '-') {
				return true;
			}
		} else {
			if (ch < "0" || "9" < ch) {
				return true;
			}
		}
	}
	
	//No problems?  It's not invalid
	return false;
}

function formatDateEvent(dateField, e) {
	if (!e)
		var e = window.event;
	if (e.keyCode == 13) {
		formatDate(dateField);
	}
}

function format(field)
//this function formats a numeric field with commas, for thousands
{	field.value=formatValue(field.value);
}

function formatValue(value)
//this function formats a numeric field with commas, for thousands
{	var number = value + "";
	var num ="";
	arr = number.split(',');
	for (i=0;i<arr.length;i++){
		if (arr[i] != "") num += arr[i];
	}
	num = Math.round(num).toString();
	if (num == 0) num="";
	var size = Math.floor(num.length/3);
	var num1="";
	var num2="";
	len = num.length;
	//if (len > 10) {alert('field size should not be greater than 10 digits'); field.focus();}
	if (len > 3){
		for( var i=size; i>0; i--){
			num1 = num.substring(len-3,len);
			if ((num.length - size*3) != 0 || (i != 1)){
				num1 = "," + num1;
			}
			num2 = num1 + num2;
			len-=3;
		}
		num1 = num.substring(0,num.length-size*3);
		num2 = num1 + num2;
		return num2;
	}else
	{
		return num;
	}
}


function isNum(str, special1, special2) 
{
  if (str == null || str == "") {
	  return false;
  }
  var havenonspace = 0;
  var havetrailingspace = 0;
  //remove the negative sign
  var startPos = 0;
  if(str.charAt(0)=='-'){
     startPos=1;
  }
  for (var i = startPos; i < str.length; i++) 
  {
    var ch = str.charAt(i); //str.substring(i, i + 1);
    if(ch == " ") {
      if(havenonspace > 0)
      {
        havetrailingspace = 1;
      }
    }
    if ((ch < "0" || "9" < ch) && ch != special1 && ch != special2 && ch != " ") 
	  {
      return false;
    }
    if(ch != " ") {
      if(havetrailingspace > 0) {
        return false;
      }
      havenonspace = 1;
    }
  }
  return true;
}

function splitDate(inputDate, isYearField) {
	if(inputDate.length > 4) {
		return (inputDate.substring(0,2)+'-'+inputDate.substring(2,4)+'-'+inputDate.substring(4));
	}
	else if(inputDate.length > 2 && !isYearField) {
		return (inputDate.substring(0,2)+'-'+inputDate.substring(2));
	}
	else {
		return inputDate;
	}
}

function roundSingleDigitDayOrMonth(inputStr) {
	if(inputStr.search(/^\d{1}$/) != -1) {
		return ("0"+inputStr);
	}
	return inputStr;
}

function validateDate(inputFld) {
	if(inputFld == null) {
		return false;
	}
	inputFld = trim(inputFld);
	
	if (inputFld.length != 10) {
		return false;
	}
		
	var month = inputFld.substring(0,2);
	var sep1 = inputFld.substring(2,3);
	var day = inputFld.substring(3,5);
	var sep2 = inputFld.substring(5,6);
	var year = inputFld.substring(6,10);
	
	var stdToken = '-';
	if (sep1 != stdToken) {
		return false;
	} 
	if (sep2 != stdToken) {
		return false;
	} 

	if (!isNum(month)) {
		return false;
	}
	if (!isNum(day)) {
		return false;
	}
	if (!isNum(year)) {
		return false;
	}
	if (month < 1 || month > 12) {
		return false;
	}
	if (day < 1 || day > 31) {
		return false;
	}
	if (year < 1900 || year > 2100) {
		return false;
	}
	return true;
}

function ltrim(string) {
    string = String(string);
    var pos = 0;
    while (string.charAt(pos) == " ") {
        pos++;
    }
    return string.substr(pos);
}
function rtrim(string) {
    string = String(string);
    var pos = string.length - 1;
    while (string.charAt(pos) == " ") {
        pos--;
    }
    return string.substring(0, pos + 1);
}
function trim(string) {
    return ltrim(rtrim(string));
}

//Allows only Numeric, Enter, Hyphen and Slash
function numericHyphenSlash(e) {
	if(!e) var e = window.event;
	var keyCode = getkey(e);
	
	if (!keyCode || alwaysOkKey(keyCode)) {
		return;
	}

	if ((keyCode < 48 || keyCode > 57) && keyCode != 13 && keyCode != 45 && keyCode != 47) {
		stopEvent(e);	
	}
}

function removeCommas(field) { 
	mystring = field.value;
	if(!mystring || mystring == '')
		return mystring;
		
	var myarray=mystring.split(','); 
	var amt = "";
	for (var i=0; i<myarray.length; i++) {
		amt= amt + myarray[i];
	} 
	field.value = amt;
}

function numericandDecimal(inputFld, e) {
	if(!e) var e = window.event;
	var keyCode = getkey(e);
	
	if (!keyCode || alwaysOkKey(keyCode)) {
		return;
	}

	var len=inputFld.value.length;
	var oneDecimal = true;
	for(i = 0; i < len; i++) {
		if (inputFld.value.charAt(i) == ".") {
			var oneDecimal = false;
		}
	}

	if (oneDecimal) {
		if ((keyCode < 48 || keyCode > 57) && keyCode != 13 && keyCode != 46) {
			stopEvent(e);	
		}
	}
	else {
		if ((keyCode < 48 || keyCode > 57) && keyCode != 13) {
			stopEvent(e);	
		}
	}
}

//Allows only Numeric, Enter and Hyphen
function numericandHyphen(e) {
	if(!e) var e = window.event;
	var keyCode = getkey(e);
	
	if (!keyCode || alwaysOkKey(keyCode)) {
		return;
	}

	if ((keyCode < 48 || keyCode > 57) && keyCode != 13 && keyCode != 45) {
		stopEvent(e);	
	}
}

function numericandDecimalWithMaxLength(inputFld, e) {
	if(!e) var e = window.event;
	var keyCode = getkey(e);
	
	if (!keyCode || alwaysOkKey(keyCode)) {
		return;
	}
	
	var number = inputFld.value;
	var num ="";
	arr = number.split(',');
	for (i=0;i<arr.length;i++){
		if (arr[i] != "") num += arr[i];
	}
	//alert(num);
	var len=num.length;
	//var len=inputFld.value.length;
	var oneDecimal = true;
	for(i = 0; i < len; i++) {
		if (inputFld.value.charAt(i) == ".") {
			var oneDecimal = false;
		}
	}

	if (oneDecimal) {
	    if(len == inputFld.maxLength - 3) {
	       if(keyCode != 46) {
	    	   stopEvent(e);	
	       }
	    }
	    else if ((keyCode < 48 || keyCode > 57) && keyCode != 13 && keyCode != 46) {
			stopEvent(e);	
		}
	}
	else {
		if ((keyCode < 48 || keyCode > 57) && keyCode != 13) {
			stopEvent(e);	
		}
	}
}

function CommaFormattedTwoDecimalsField(field) {
	if (field.value) {
		var amt = CommaFormattedTwoDecimals(field.value);
		field.value = amt;
	}
}
function CommaFormattedTwoDecimals(amount) {
	var rounded = roundTwoDecimals(amount).toString();
	var a = rounded.split('.',2);
	var i = a[0];
	var d;
	if (a[1]) {
		d = a[1];
	} else {
		d = ''; 
	}
	if (d.length == 0) {
		rounded = i + '.00';
	} else if (d.length == 1) {
		rounded = i + '.' + d + '0';
	} else {
		rounded = i + '.' + d;
	}
	return CommaFormatted(rounded);
}


function CommaFormatted(amount) {
	var delimiter = ","; // replace comma if desired
	var a = amount.split('.',2);
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d == null || d.length < 1) { amount = n; }
	else { amount = n + '.' + d; }
	amount = minus + amount;
	return amount;
}

function roundTwoDecimals(value) {
	if(value == null || value == '' ) { 
		return '0.00';
	}
	else {
		var val = new String(value);
		var inputVal = val.replace(/[\s]/g, '');
		inputVal = inputVal.replace(/,/g,"");
		if(isNum(inputVal, '.') && !isNaN(inputVal) && inputVal.length > 0) {
			return Math.round(inputVal*100)/100;
			//inputFld.value = inputVal.toFixed(2);
		}
		else {
			return '0.00';
		}
	}
}


function formatDollarAmtsWDecimals(field) {
	if (field != null && field.value != null && field.value != "") {
		removeCommas(field);
		roundTwoDecimals(field);
		var fieldValue = new String(field.value);
		if (fieldValue.indexOf('.') < 0) {
			fieldValue = fieldValue + ".00";
			field.value = fieldValue;
		} else if (fieldValue.indexOf('.') == fieldValue.length -2) {
			fieldValue = fieldValue + "0";
			field.value = fieldValue;
		}
		field.value = CommaFormatted(field.value);
	} 
}

function roundCurrency(inputFld) {
	if(inputFld != null) {
		inputFld.value = roundCurrencyValue(inputFld.value);
	}
}

function roundCurrencyValue(value) {
	var inputVal = value.replace(/[\s]/g, '');
	inputVal = inputVal.replace(/,/g,"");
	if (inputVal == '.') {
		inputVal = '';
	}
	if(isNum(inputVal, '.') && !isNaN(inputVal) && inputVal.length > 0) {
		return Math.round(inputVal);
	}
	else {
		return inputVal;
	}
}

function getkey(e){
	if (window.event) {
		return window.event.keyCode;
	} else if (e) {
		return e.which;
	} else {
		return null;
	}
}

//Allows only Numeric and Enter
function onlyNumeric(e) {
	if(!e) var e = window.event;
	var keyCode = getkey(e);
	
	if (!keyCode || alwaysOkKey(keyCode)) {
		return;
	}

	if ((keyCode < 48 || keyCode > 57) && keyCode != 13) {
		e.returnValue = false;
		stopEvent(e);	
	}
}

function alwaysOkKey(keyCode) {
	if (!keyCode) {
		return false;
	}
	if (keyCode == 8 || keyCode == 9 || keyCode == 27) {
		return true;
	} else {
		return false;
	}
}

function stopEvent(e) {
	if (!e) {
		return;
	}
	e.returnValue = false;
	if (e.stopPropagation) {
		e.stopPropagation();
		e.preventDefault();
	}
}

function getFormValues(fobj) { 
	var str = ""; 
	var valueArr = null; 
	var val = ""; 
	var cmd = ""; 
	for(var i = 0;i < fobj.elements.length;i++){ 
	    switch(fobj.elements[i].type) {
	        case "text": 
	             str += fobj.elements[i].id + 
	              "=" + escape(fobj.elements[i].value) + "&"; 
	              break; 
	        case "password": 
	             str += fobj.elements[i].id + 
	              "=" + escape(fobj.elements[i].value) + "&"; 
	              break; 
	        case "textarea": 
	             str += fobj.elements[i].id + 
	              "=" + escape(fobj.elements[i].value) + "&"; 
	              break; 
	        case "hidden": 
	             str += fobj.elements[i].id + 
	              "=" + escape(fobj.elements[i].value) + "&"; 
	              break; 
	        case "checkbox": 
	             str += fobj.elements[i].id + 
	              "=" + escape(fobj.elements[i].checked) + "&"; 
	              break; 
	        case "select-one": 
	             str += fobj.elements[i].id + 
	             "=" + fobj.elements[i].options[fobj.elements[i].selectedIndex].value + "&"; 
	             break; 
	    } 
	} 
	str = str.substr(0,(str.length - 1));
	return str;
}


function getValueOrSpace(value) {
	if (!value || value == ""){ 
		return "&nbsp;";
	} else {
		return value;
	}
}
getArrayKey = function(array, value){
	for(obj in array){
		if(array[obj][1] == value){
			return array[obj][0];
		}
	}
};

getDBArrayKey = function(array, value){
	if (value) {
		for(obj in array){
			if(array[obj].id == value){
				return array[obj].description;
			}
		}
	} else {
		return "";
	}
};

function blankPhone(phone) {
	if (!phone || phone == "" || phone == '000-000-0000') 
		return true;
	return false;
}

function printTextField(field) {
	try {
		return field.innerHTML;
	} catch (e) {
		return "";	
	}
}

function printField(field) {
	if (field) {
		return field;
	} else {
		return "";	
	}
}


function printRow(printWindow, label1, value1, label2, value2) {
	printWindow.document.write("<tr>");
	printWindow.document.write("<td valign='top'>");
	if (label1 != '') {
		printWindow.document.write("<b>" + label1+":</b>");
	} else {
		printWindow.document.write(" ");
	}
	printWindow.document.write("</td>");
	printWindow.document.write("<td valign='top'>");
	printWindow.document.write(printField(value1));
	printWindow.document.write("</td>");
	printWindow.document.write("<td valign='top'>");
	if (label2 != '') {
		printWindow.document.write("<b>" + label2+":</b>");
	} else {
		printWindow.document.write(" ");
	}
	printWindow.document.write("</td>");
	printWindow.document.write("<td valign='top'>");
	printWindow.document.write(printField(value2));
	printWindow.document.write("</td>");
	printWindow.document.write("</tr>");
}

function printApptFromDB(appt, phoneTypeArray, addOnsResult, agent, office) {
	OpenWindow=window.open("", "newwin", "height=800, width=800,toolbar=no,scrollbars="+scroll+",menubar=no");
	OpenWindow.document.write("<TITLE>Appointment " + appt.appt_id + " </TITLE>");
	OpenWindow.document.write("<BODY>");
	OpenWindow.document.write("<a href='javascript:window.print()'>print</a>");
	var radon = "";
	if (appt.radon_num && appt.radon_num != '0') {
		radon = ", Radon Number: " + appt.radon_num;
	}
	OpenWindow.document.write("<h1>Appointment " + appt.appt_id + radon + "</h1>");
	OpenWindow.document.write("<table width='100%'>");
	var requested = "No";
	if (appt.requested && appt.requested == 1) {
		requested = "Yes";
	}
	
	var date = '';
	var dateSuffix = '';
	if (appt.startDate) {
		date = appt.startDate;
	}
	if (appt.startHour) {
		if (appt.startHour > 12) {
			appt.startHour = appt.startHour - 12;
			dateSuffix = ' PM';
		} else if (appt.startHour < 12) {
			dateSuffix = ' AM';
		}
		
		if (appt.startMinute) {
			if (appt.startMinute < 10) {
				appt.startMinute = '0' + appt.startMinute;
			}
			date = date + " " + appt.startHour + ":" + appt.startMinute + dateSuffix;
		}
	}
	
	printRow(OpenWindow, "Inspector", appt.first_name + ' ' + appt.last_name, "Date & Time", date);
	printRow(OpenWindow, "Requested", requested, "Price", "$ " + CommaFormattedTwoDecimals(appt.price));
	var additions = "";
	var first = true;
	if (addOnsResult) {
    	for(var addon in addOnsResult){
			if (!first) {
				additions += "; ";
			}
			first = false;
			additions = additions + addOnsResult[addon].description;
		}
	}
	
	printRow(OpenWindow, "Type", appt.apptTypeDescription, "Additions", additions);
	if (appt.description) {
		OpenWindow.document.write("<tr><td><b>Description:</b></td><td colspan='3'>"+ appt.description +"</td></tr>");
	}
	OpenWindow.document.write("<tr><td colspan='4'><hr/></td></tr>");
	printRow(OpenWindow, "Home Price", "$ " + CommaFormattedTwoDecimals(appt.home_prc), "Community", appt.community_nm);
	printRow(OpenWindow, "Home Type", appt.homeTypeDescription, "Builder", appt.builderDescription);
	printRow(OpenWindow, "Year Built", appt.yr_built, "", "");
	OpenWindow.document.write("<tr><td colspan='4'><hr/></td></tr>");
	printRow(OpenWindow, "Customer Name", appt.customer_name, "Phone", formatPhoneValue(appt.phonenumber1) + " " + getDBArrayKey(phoneTypeArray,appt.phonetype1));
	var phone2 = formatPhoneValue(appt.phonenumber2);
	var phone3 = formatPhoneValue(appt.phonenumber3);
	if (!(blankPhone(phone2) && blankPhone(phone3))) {
		printRow(OpenWindow, "Phone", phone2 + " " + getDBArrayKey(phoneTypeArray,appt.phonetype2), "Phone", phone3 + " " + getDBArrayKey(phoneTypeArray,appt.phonetype3));
	}
	var phone4 = formatPhoneValue(appt.phonenumber4);
	var phone5 = formatPhoneValue(appt.phonenumber5);
	if (!(blankPhone(phone4) && blankPhone(phone5))) {
		printRow(OpenWindow, "Phone", phone4 + " " + getDBArrayKey(phoneTypeArray,appt.phonetype4), "Phone", phone5 + " " + getDBArrayKey(phoneTypeArray,appt.phonetype5));
	}
	OpenWindow.document.write("<tr><td colspan='4'><hr/></td></tr>");
	printRow(OpenWindow, "Address", appt.street1, "", "");
	var address2 = appt.street2;
	if (address2 != '' && address2 != 'N/A') {
		printRow(OpenWindow, "", address2, "", "");
	}
	printRow(OpenWindow, "", printField(appt.city) + ", " + printField(appt.state) + " " + printField(appt.zip), "", "");
	OpenWindow.document.write("<tr><td colspan='4'><hr/></td></tr>");
	
	if (agent) {
		printRow(OpenWindow, "Agent Name", agent.name, "E-mail", agent.email);
		printRow(OpenWindow, "Notes", agent.notes, "Phone", formatPhoneValue(agent.phonenumber1) + " " + getDBArrayKey(phoneTypeArray,agent.phonetype1));
		phone2 = formatPhoneValue(agent.phonenumber2);
		phone3 = formatPhoneValue(agent.phonenumber3);
		if (!(blankPhone(phone2) && blankPhone(phone3))) {
			printRow(OpenWindow, "Phone", phone2 + " " +getDBArrayKey(phoneTypeArray,agent.phonetype2), "Phone", phone3 + " " + getDBArrayKey(phoneTypeArray,agent.phonetype3));
		}
		phone4 = formatPhoneValue(agent.phonenumber4);
		phone5 = formatPhoneValue(agent.phonenumber5);
		if (!(blankPhone(phone4) && blankPhone(phone5))) {
			printRow(OpenWindow, "Phone", phone4 + " " + getDBArrayKey(phoneTypeArray,agent.phonetype4), "Phone", phone5 + " " + getDBArrayKey(phoneTypeArray,agent.phonetype5));
		}
	} else {
		OpenWindow.document.write("<tr><td colspan='4'>No Agent</td></tr>");
	}
	OpenWindow.document.write("<tr><td colspan='4'><hr/></td></tr>");
	if (office) {
//		{"data":[{"id":"20","description":"Realty Executives","rel_office_id":"28","office_nm":"One: Gaithersburg, MD",
//			"web_addr":"","manager":"Phil Wineman","phonenumber1":"3019909090","phonetype1":"1","phonenumber2":"3019902672",
//			"phonetype2":"4","phonenumber3":"","phonetype3":"2","phonenumber4":"","phonetype4":"2","phonenumber5":"",
//			"phonetype5":"2","street1":"903 Russell Avenue","street2":"Suite 100","city":"Gaithersburg","state":"MD","zip":"20879","zip_ext":""}]}
		printRow(OpenWindow, "Office Name", office.office_nm, "Manager", office.manager);
		printRow(OpenWindow, "Address", office.street1, "WEB Address", office.web_addr);
		address2 = office.street2;
		if (address2 != '' && address2 != 'N/A') {
			printRow(OpenWindow, "", address2, "", "");
		}
		printRow(OpenWindow, "", office.city + ", " + office.state + " " + office.zip, "", "");
		phone1 = formatPhoneValue(office.phonenumber1);
		phone2 = formatPhoneValue(office.phonenumber2);
		if (!(blankPhone(phone1) && blankPhone(phone2))) {
			printRow(OpenWindow, "Phone", phone1 + " " +getDBArrayKey(phoneTypeArray,office.phonetype1), "Phone", phone2 + " " + getDBArrayKey(phoneTypeArray,office.phonetype2));
		}
		phone3 = formatPhoneValue(office.phonenumber3);
		phone4 = formatPhoneValue(office.phonenumber4);
		if (!(blankPhone(phone3) && blankPhone(phone4))) {
			printRow(OpenWindow, "Phone", phone3 + " " + getDBArrayKey(phoneTypeArray,office.phonetype3), "Phone", phone4 + " " + getDBArrayKey(phoneTypeArray,office.phonetype4));
		}
		phone5 = formatPhoneValue(office.phonenumber5);
		if (!(blankPhone(phone5))) {
			printRow(OpenWindow, "Phone", phone5 + " " + getDBArrayKey(phoneTypeArray,office.phonetype5), "", "");
		}
	} else {
		OpenWindow.document.write("<tr><td colspan='4'>No Office</td></tr>");
	}
	
	if (appt.franchiseDescription && appt.franchiseDescription != "") {
		OpenWindow.document.write("<tr><td colspan='4'><hr/></td></tr>");
		printRow(OpenWindow, "Franchise Name", appt.franchiseDescription, "", "");
	}
	OpenWindow.document.write("</table>");
	OpenWindow.document.write("</BODY>");
	OpenWindow.document.write("</HTML>");

	OpenWindow.document.close();
	self.name="main";
}


function initializeCalendar(YAHOO, dialog, calendar) {
	var showBtn = YAHOO.util.Dom.get("show");
	YAHOO.util.Event.on(showBtn, "click", onCalendarClick, YAHOO, dialog, calendar);
}


function onCalendarClick(event, YAHOO, dialog, calendar) {

	var showBtn = YAHOO.util.Dom.get("show");

    // Lazy Dialog Creation - Wait to create the Dialog, and setup document click listeners, until the first time the button is clicked.
    if (!dialog) {

        // Hide Calendar if we click anywhere in the document other than the calendar
        YAHOO.util.Event.on(document, "click", function(e) {
            var el = YAHOO.util.Event.getTarget(e);
            var dialogEl = dialog.element;
            if (el != dialogEl && !YAHOO.util.Dom.isAncestor(dialogEl, el) && el != showBtn && !YAHOO.util.Dom.isAncestor(showBtn, el)) {
                dialog.hide();
            }
        });

        function resetHandler() {
            // Reset the current calendar page to the select date, or 
            // to today if nothing is selected.
            var selDates = calendar.getSelectedDates();
            var resetDate;

            if (selDates.length > 0) {
                resetDate = selDates[0];
            } else {
                resetDate = calendar.today;
            }

            calendar.cfg.setProperty("pagedate", resetDate);
            calendar.render();
        }

        function closeHandler() {
            dialog.hide();
        }

        dialog = new YAHOO.widget.Dialog("container", {
            visible:false,
            context:["show", "tl", "bl"],
            buttons:[ {text:"Reset", handler: resetHandler, isDefault:true}, {text:"Close", handler: closeHandler}],
            draggable:false,
            close:true
        });
        dialog.setHeader('Pick A Date');
        dialog.setBody('<div id="cal"></div>');
        dialog.render(document.body);

        dialog.showEvent.subscribe(function() {
            if (YAHOO.env.ua.ie) {
                // Since we're hiding the table using yui-overlay-hidden, we 
                // want to let the dialog know that the content size has changed, when
                // shown
                dialog.fireEvent("changeContent");
            }
        });
    }

    // Lazy Calendar Creation - Wait to create the Calendar until the first time the button is clicked.
    if (!calendar) {

        calendar = new YAHOO.widget.Calendar("cal", {
            iframe:false,          // Turn iframe off, since container has iframe support.
            hide_blank_weeks:true  // Enable, to demonstrate how we handle changing height, using changeContent
        });
        calendar.render();

        calendar.selectEvent.subscribe(function() {
            if (calendar.getSelectedDates().length > 0) {

                var selDate = calendar.getSelectedDates()[0];

                // Pretty Date Output, using Calendar's Locale values: Friday, 8 February 2008
                var dStr = selDate.getDate();
                var mStr = selDate.getMonth() + 1;
                var yStr = selDate.getFullYear();

                YAHOO.util.Dom.get("searchDate").value =  mStr + "-"+ dStr + "-" + yStr;
                formatDate(YAHOO.util.Dom.get("searchDate"));
            } else {
                YAHOO.util.Dom.get("searchDate").value = "";
            }
            dialog.hide();
        });

        calendar.renderEvent.subscribe(function() {
            // Tell Dialog it's contents have changed, which allows 
            // container to redraw the underlay (for IE6/Safari2)
            dialog.fireEvent("changeContent");
        });
    }

    var seldate = calendar.getSelectedDates();

    if (seldate.length > 0) {
        // Set the pagedate to show the selected date if it exists
        calendar.cfg.setProperty("pagedate", seldate[0]);
        calendar.render();
    }

    dialog.show();

}



function startUpload(){
    document.getElementById('f1_upload_process').style.display = '';
    document.getElementById('f1_upload_result').style.display = 'none';   
    document.getElementById('f1_upload_form').style.display = 'none';
    return true;
}

function stopUpload(success, message, fileName){
    var result = '';
    if (success == 1){
       result = '<span style="color:green;">';
 	if(document.getElementById('fileLinks').innerHTML == ""){
		document.getElementById('fileLinks').innerHTML = "<strong>Uploaded Files:</strong><br/>";
	}
       document.getElementById('fileLinks').innerHTML += "<a href='uploads/" + fileName + "' target='_blank'>" + fileName + "</a><br/>";
    }
    else {
       result = '<span style="color:red;">';
    }
    result += message + '<\/span><br/><br/>';
    document.getElementById('f1_upload_process').style.display = 'none';
    document.getElementById('f1_upload_result').innerHTML = result;
    document.getElementById('f1_upload_result').style.display = '';   
    document.getElementById('f1_upload_form').style.display = '';      
    return true;   
}


