function InitForm(){
	var dt=new Date();
	document.getElementById('adx_txtStartDate').value = GetLocalDateString(dt);
	document.getElementById('adx_txtEndDate').value = GetLocalDateString(dt);
	$("#txtNumMonthsPosition,#txtNumMonthsDate,#txtNumDays,#txtNumWeeks").addClass("text25");
	$("#txtNumOccurrences,#txtRecurEndDate").addClass("text80");
	$("#ancNewSchedule").addClass("hiding");
	try { disposeDatePicker(); } catch (Error) { } /*Hide selectors*/
	try { disposeTimePicker(); } catch (Error) { } /*Hide selectors*/
	InitFormEvents();
	InitSchedulingEvents();
	GetCustomRecuringText(GetDateFromInputText("adx_txtStartDate", null));
}

function InitFormEvents() {
    /*Recur End Date Icon Events*/
    $("img[id*='imgRecurEndDate']").click(function() {
        initSGrid(String($(this).attr("id")).replace("img", "txt"), '');
        try { disposeTimePicker(); } catch (Error) { } /*Try to hide*/
    });
    
    /*Start Date Icon Events*/
    $("img[id*='imgStartDate']").click(function() {
        initSGrid(String($(this).attr("id")).replace("img", "txt"), String($(this).attr("id")).replace("img", "txt").replace("Start", "End"));
        try { disposeTimePicker(); } catch (Error) { } /*Try to hide*/
    });
    
    /*End Date Icon Events*/
    $("img[id*='imgEndDate']").click(function() {
        initEGrid(String($(this).attr("id")).replace("img", "txt"), String($(this).attr("id")).replace("img", "txt").replace("End", "Start"));
        try { disposeTimePicker(); } catch (Error) { } /*Try to hide*/
    });
    
    /*Recur End Date Text Field Events*/
    $("input:text[name*='txtRecurEndDate']").keypress(function(e) {
        if (e.which == 13) {
            disposeDatePicker();
            validateControls($(this).attr("id"), $(this).attr("id"), String($(this).attr("id")).replace("Start", "End"));
        }
    }).change(function() {
        validateControls($(this).attr("id"), $(this).attr("id"), String($(this).attr("id")).replace("Start", "End"));
    }).attr("autocomplete", "off"); /*Disable autocomplete*/
    
    /*Start Date Text Field Events*/
    $("input:text[name*='StartDate']").keypress(function(e) {
        if (e.which == 13) {
            disposeDatePicker();
            validateControls($(this).attr("id"), $(this).attr("id"), String($(this).attr("id")).replace("Start", "End"));
            validateTimes(String($(this).attr("id")).replace("Date", "Time"));
        }
    }).change(function() {
        validateControls($(this).attr("id"), $(this).attr("id"), String($(this).attr("id")).replace("Start", "End"));
        validateTimes(String($(this).attr("id")).replace("Date", "Time"));
        if ($("#divAdvancedSchedule").length > 0) {
            /*The start date of the event changed, update occurrences*/
            GetCustomRecuringText(GetDateFromInputText($(this).attr("id"), null));
            GenerateInitialSchedule("DATE");
        }
        else {
            /*The start date of the event changed, update occurrences*/
            GenerateInitialSchedule("COUNT");
        } 
    }).attr("autocomplete", "off");    /*Disable autocomplete*/
    
    /*End Date Text Field Events*/
    $("input:text[name*='EndDate']").keypress(function(e) {
        if (e.which == 13) {
            disposeDatePicker();
            validateControls($(this).attr("id"), String($(this).attr("id")).replace("End", "Start"), $(this).attr("id"));
            validateTimes(String($(this).attr("id")).replace("Date", "Time"));
        }
    }).change(function() {
        validateControls($(this).attr("id"), String($(this).attr("id")).replace("End", "Start"), $(this).attr("id"));
        validateTimes(String($(this).attr("id")).replace("Date", "Time"));
    }).attr("autocomplete", "off"); /*Disable autocomplete*/
    
    /*Start Time Text Field Events*/
    $("input:text[id*='StartTime']").click(function() {
        createTimePicker($(this).attr("value"), $(this).attr("id"));
        disposeDatePicker();
    }).keypress(function(e) {
        if (e.which == 13) {
            validateTimes($(this).attr("id"));
        }
    }).change(function() {
        validateTimes($(this).attr("id"));
    }).attr("autocomplete", "off"); /*Disable autocomplete*/
    
    /*End Time Text Field Events*/
    $("input:text[id*='EndTime']").click(function() {
        createDurationPicker($(this).attr("value"), $(this).attr("id"));
        disposeDatePicker();
    }).keypress(function(e) {
        if (e.which == 13) {
            validateTimes($(this).attr("id"));
        }
    }).change(function() {
        validateTimes($(this).attr("id"));
    }).attr("autocomplete", "off"); /*Disable autocomplete*/
}

function IsBlank(pvElementId, pvError) {
    var lIsBlank = false;
    var lElement = document.getElementById(pvElementId);
    if(lElement != null){
		if(trimStr(lElement.value) == ""){ showErrorMessage(pvElementId + "error", pvError); lIsBlank = true; }
		else { hideErrorMessage(pvElementId + "error"); }
	}
	return lIsBlank;
}

function ArrayHas(prArr, prVal) {
    for (var i = 0; i < prArr.length; i++) {
        if (prArr[i] == prVal) { return true; }
    }
    return false;
}
function RemoveNonNums(prText) { return prText.replace(/[^\d]*/, ""); }

function getInputValue(elem){
    var docelem = document.getElementById(elem);
    return (docelem == null) ? "" : docelem.value;
}

function toggleTimeSelectors(){
	var chk = document.getElementById("adx_allday");
	/* Enable or disable time dropdowns according to the users selection */
	document.getElementById("adx_txtStartTime").disabled = chk.checked;
	document.getElementById("adx_txtEndTime").disabled = chk.checked;
	validShedule();
}
function toggleForMidnight(){
	var chk = document.getElementById("adx_midnight");
	/* Enable or disable time dropdowns according to the users selection */
	document.getElementById("adx_txtEndTime").disabled = chk.checked;
	document.getElementById("adx_allday").disabled = chk.checked;
	validShedule();
}
function toggleCategorizations(toggle){
    var categorizations = document.getElementsByName("adx_eventcategorizations");
	if(categorizations != null){
	    for(i=0;i<categorizations.length;i++)
	    {
	        categorizations[i].checked=toggle;
	    }
	}
}

function showErrorMessage(id, text){
    var elem = document.getElementById(id);
    
    if(elem != null){ elem.style.visibility = "visible"; elem.innerHTML = text; }
}
function hideErrorMessage(id){
    var elem = document.getElementById(id);
    if(elem != null){ elem.style.visibility = "hidden"; elem.innerHTML = ""; }
}

function validOpenEntryForm(){
    var SubmitterIsValid = validSubmitter();
    var EventInformationIsValid = validEventInformation();
    var ScheduleIsValid = validShedule();
    var ImageIsValid = validImage();
    var AttachmentIsValid = validAttachment();
    var OtherInformationIsValid  = validOtherInformation();
    var MultidayWarning = MultidayEvent();
    var InternalWarning = validInternalFields();
    var SchedWarning = CheckSchedule();
    var lIsValid = (SubmitterIsValid && EventInformationIsValid && ScheduleIsValid && ImageIsValid && AttachmentIsValid && OtherInformationIsValid && MultidayWarning && InternalWarning && SchedWarning);
    
    if (lIsValid) {
        if ($("#divAdvancedSchedule").length > 0) { SaveAllRows(); /*ADVANCED SCHEDULING*/ }

        hideErrorMessage("adx_dateerror");
        if ($("#adx_entireschedule").val() == "") {
            showErrorMessage("adx_dateerror", "Please create a schedule for your event by clicking \"Generate Schedule\".");
            return false; /* Generate a schedule*/
        }
        else
        {
            return true;
        }
    }
    else
    {
        return false; /*There are errors being shown*/
    }
}

function validInternalFields() {
    var valid_data = true;
    hideErrorMessage("adxief1error","");
    hideErrorMessage("adxief2error","");
    hideErrorMessage("adxief3error","");
    hideErrorMessage("adxief4error","");
    
	if(document.getElementById("adxief1") != null){
	    var reqValue = getInputValue("adxief1req");
	    var fldValue = document.getElementById("adxief1").value;
	    if (reqValue == "R" && fldValue == ""){
            showErrorMessage("adxief1error","<br />Please enter internal information in the field provided.");
            valid_data = false;
	    }
	  
	}
   /*CHECK FOR SCRIPTING*/
	if (!checkForScript("adxief1")) { valid_data = false; }
   	
	if(document.getElementById("adxief2") != null){
	    var reqValue = getInputValue("adxief2req");
	    var fldValue = document.getElementById("adxief2").value;
	    if (reqValue == "R" && fldValue == ""){
            showErrorMessage("adxief2error","<br />Please enter internal information in the field provided.");
            valid_data = false;
	    }
	 
	}
	   /*CHECK FOR SCRIPTING*/
	if (!checkForScript("adxief2")) { valid_data = false; }
	
		
	if(document.getElementById("adxief3req") != null){
	    var reqValue = getInputValue("adxief3req");
	    var fldValue = document.getElementById("adxief3").value;
	    if (reqValue == "R" && fldValue == ""){
            showErrorMessage("adxief3error","<br />Please enter internal information in the field provided.");
            valid_data = false;
	    }

	}
       if (!checkForScript("adxief3")) { valid_data = false; }
		
	if(document.getElementById("adxief4req") != null){
	    var reqValue = getInputValue("adxief4req");
	    var fldValue = document.getElementById("adxief4").value;
	    if (reqValue == "R" && fldValue == ""){
            showErrorMessage("adxief4error","<br />Please enter internal information in the field provided.");
            valid_data = false;
	    }
	    
	}
	if (!checkForScript("adxief4")) { valid_data = false; }	
    return valid_data;
}

function validSubmitter() {
	var valid_Submitter = true; /* The default is true */
	
	/* Submitter First Name */
	if (IsBlank("adx_fname", "<br />Please enter a First Name in the field provided."))
	    valid_Submitter = false; /*Required*/
	    
	/*CHECK FOR SCRIPTING*/
	if (!checkForScript("adx_fname")) { valid_Submitter = false; }
	
	/* Submitter Last Name */
	if (IsBlank("adx_lname", "<br />Please enter a Last Name in the field provided."))
	    valid_Submitter = false; /*Required*/
	
	/*CHECK FOR SCRIPTING*/
	if (!checkForScript("adx_lname")) { valid_Submitter = false; }
	    
		
	/* Submitter Email */
	if(document.getElementById("adx_email") != null){
	    if (IsBlank("adx_email", "<br />Please enter an Email Address in the field provided.")) {
	        valid_Submitter = false; /*Required*/
	    }
		else {
		    var Email = trimStr(document.getElementById("adx_email").value); /* 100 */
		    if(!CheckEmail(Email)){
			    showErrorMessage("adx_emailerror","<br />The Email Address entered is not valid.");
			    valid_Submitter = false;
		    }
		}
		
		/*CHECK FOR SCRIPTING*/
	if (!checkForScript("adx_email")) { valid_Submitter = false; }
	}
	
	
		
	hideErrorMessage("adx_organizationerror");
	/* Submitter Organization */
	if(document.getElementById("adx_organizationRequired") != null){
	    if (IsBlank("adx_organization", "<br />Please enter an Organization in the field provided."))
	        valid_Submitter = false; /*Required*/
	}
	
	/*CHECK FOR SCRIPTING*/
	if (!checkForScript("adx_organization")) { valid_Submitter = false; }
	
	/* Submitter Phone */
	hideErrorMessage("adx_phoneerror");
	if(document.getElementById("adx_phoneRequired") != null){
	    if (IsBlank("adx_phone", "<br />Please enter a Phone # in the field provided."))
	        valid_Submitter = false; /*Required*/
	}
	/*CHECK FOR SCRIPTING*/
	if (!checkForScript("adx_phone")) { valid_Submitter = false; }
	
    return valid_Submitter;
}

function checkForScript(field){
    if(document.getElementById("adx_enableScripts") != null){
        if (document.getElementById(field) != null) {
            var script_Organization = trimStr(document.getElementById(field).value); 
            var re = new RegExp('<\\s*script','gi');
            var myArray = re.test(script_Organization);
            if (myArray != false){
                showErrorMessage(field + "error","<br>Please remove any scripting from your text!");
                return false;
            }
        }
    }
    return true;   	
}

function validEventInformation() {
	var valid_EventInformation = true; /* The default is true */

	
	/* Event Name */
	if(document.getElementById("adx_eventname") != null){
	    if (IsBlank("adx_eventname", "<br />Please enter an Event Name in the field provided.")) {
	        valid_EventInformation = false; /*Required*/
	    }
		else {
		    var EventName = trimStr(document.getElementById("adx_eventname").value); /* 100 */
		    if (EventName.length>100){
		        showErrorMessage("adx_eventnameerror","<br>The Event Name allows for 100 characters.  There are currently "+EventName.length+" entered.");
			    valid_EventInformation = false;
		    }
		}	
	}
	
    /*CHECK FOR SCRIPTING*/
	if (!checkForScript("adx_eventname")) { valid_EventInformation = false; }

		
	var categorizations = document.getElementsByName("adx_eventcategorizations");
	if(categorizations != null){
	    var ctgryselected = false;
	    for (i=0;i<categorizations.length;i++)
        {
            if(categorizations[i].checked){ctgryselected=true;}
        }
		if(ctgryselected == false){
			showErrorMessage("adx_eventcategorizationserror","<br>Please select an Event Categorization from the field provided.");
			valid_EventInformation = false;
		}
		else{hideErrorMessage("adx_eventcategorizationserror");}
	}
	
	/* Event Description */
	if(document.getElementById("adx_eventdescription") != null){
	    if (IsBlank("adx_eventdescription", "<br />Please enter an Event Description in the field provided.")) {
	        valid_EventInformation = false; /*Required*/
	    }
		else {
		    var EventDescription = trimStr(document.getElementById("adx_eventdescription").value); /* 1000 */
		    if (EventDescription.length>1000){
		        showErrorMessage("adx_eventdescriptionerror","<br>The Event Description allows for 1000 characters.  There are currently "+EventDescription.length+" entered.");
			    valid_EventInformation = false;
		    }
		}
	}
	
	/*CHECK FOR SCRIPTING*/
	if (!checkForScript("adx_eventdescription")) { valid_EventInformation = false; }			
	
	/*Contact Name*/
	hideErrorMessage("adx_cntnameerror");
	if(document.getElementById("adx_cntnameRequired") != null){
	    if (IsBlank("adx_cntname", "<br />Please enter a Contact Name in the field provided.")) {
	        valid_EventInformation = false; /*Required*/
	    }
	}	
  	/*CHECK FOR SCRIPTING*/
	if (!checkForScript("adx_cntname")) { valid_EventInformation = false; }
	
	/*Contact Phone*/
	hideErrorMessage("adx_cntphoneerror");
	if(document.getElementById("adx_cntphoneRequired") != null){
	    if (IsBlank("adx_cntphone", "<br />Please enter a Contact Phone in the field provided.")) {
	        valid_EventInformation = false; /*Required*/
	    }
	}
	/*CHECK FOR SCRIPTING*/
	if (!checkForScript("adx_cntphone")) { valid_EventInformation = false; }
	
	/*Contact Email*/
	hideErrorMessage("adx_cntemailerror");
	if(document.getElementById("adx_cntemailRequired") != null){
	    if (IsBlank("adx_cntemail", "<br />Please enter a Contact Email in the field provided.")) {
	        valid_EventInformation = false; /*Required*/
	    }
	}
	if (!checkForScript("adx_cntemail")) { valid_EventInformation = false; }	
	
	if (document.getElementById("adx_cntemail") != null) {
	    var ContactEmail = trimStr(document.getElementById("adx_cntemail").value); /* 255 */
	    if (ContactEmail != "" && CheckEmail(ContactEmail) == false) {
	        /*INVALID FORMAT*/
	        showErrorMessage("adx_cntemailerror", "<br />The Email Address entered is not valid.");
	        valid_EventInformation = false;
	    }
	}
		
	return valid_EventInformation;
}

function validShedule(){
    var valid_Schedule = true; /* The default is true */

    if (!$("#rowSCHD6_GeneratedSchedule").hasClass("hiding")) {
        /*Generated schedule is shown, this validation no longer applies */
        return true;
    }
	
	/* Get separate date and times */
	var lSD = GetDateFromInputText("adx_txtStartDate", null);
	var lST = GetTimeFromInputText("adx_txtStartTime", null);
	var lED = GetDateFromInputText("adx_txtEndDate", null);
	var lET = GetTimeFromInputText("adx_txtEndTime", null);
		
	/* Get combined date and times */
	var lSDT = getDateInput("adx_txtStart"); var lEDT = getDateInput("adx_txtEnd");
	
	/* Always make sure error message are hidden */
	hideErrorMessage("adx_dateerror");
	if(lET == null && lST != null){
	    /*End Time & No Start Time*/
		showErrorMessage("adx_dateerror","An end time cannot be specified without a start time.");
		valid_Schedule = false; /* An end time without a start time is invalid */
	}
	else{
		if(lST != null && lET != null){
			/* Start & End Time */
			var lCheckDates = true;
			
			if(GetUTCDateString(lSD) == GetUTCDateString(lED) && lET == "0:0") {
			    /*Identical Dates & Ending At "midnight"*/
			    lCheckDates = false; /*Interpret this end time as end of day*/
			}
			
			if(lCheckDates && lSDT >= lEDT){
				showErrorMessage("adx_dateerror","The start date selected cannot be after the end date. Please change your selections.");
				valid_Schedule = false; /* The starting date must be less than the ending date. */
			}
		}
		else if(lST != null && lET == null){
			/* Start Time & No End Time */
			if(lSD > lED){
				showErrorMessage("adx_dateerror","The start date selected cannot be after the end date. Please change your selections.");
				valid_Schedule = false; /* The starting date must be less than the ending date */
			}
		}
		else{
			/* No Time */
			if(lSD > lED){
				showErrorMessage("adx_dateerror","The start date selected cannot be after the end date. Please change your selections.");
				valid_Schedule = false; /* The starting date must be less than the ending date */
			}
		}	
	}

	if (valid_Schedule == true && GetRecurType() == "One Time") {
	    /* This should only be done when the schedule is valid. */
	    $("#txtNumOccurrences").val("1");
	}
		
	return valid_Schedule; /* Return if this was a valid schedule */
}

function Multidaydropdown(){
    /*GET THE START & END DATES*/
    var StartDate = GetDateFromInputText("adx_txtStartDate", null);
    var EndDate = GetDateFromInputText("adx_txtEndDate", null);
  
    /*CALCULATE THE DAYS BETWEEN THE TWO DATES*/
    var one_day=1000*60*60*24;
    var days_apart = Math.ceil((EndDate-StartDate)/one_day);
      
    /*GET A REFERRENCE TO THE DROPDOWN TO MODIFY*/
    var ctrl = GetRecurType();
    
    /*GET A REFERRENCE TO THE CURRENTLY SELECTED OPTION & HOW MANY ITEMS THERE ARE*/
    var startingSelectedIndex = ctrl.selectedIndex;
    var startingItemsCount = ctrl.options.length;  // how many items are in the dropdown
            
    /*REMOVE THE OLD OPTIONS*/
    while(ctrl.options.length>1) { ctrl.options[1] = null; }
    
    /*READD ALL THE OPTIONS*/
    ctrl.options[0] = new Option("None","One Time");
    ctrl.options[1] = new Option("Daily","Interval1");
    ctrl.options[2] = new Option("Weekly","Weekly1");
    ctrl.options[3] = new Option("Monthly","Monthly by Date1");
    ctrl.options[4] = new Option("Yearly","Yearly by Date");
    
    if(days_apart>=30){
        //THE EVENT SPANS 30+ CONTINUOUS DAYS
        ctrl.options[1] = null; /*REMOVE DAILY*/
        ctrl.options[1] = null; /*REMOVE WEEKLY*/
        ctrl.options[1] = null; /*REMOVE MONTHLY*/
    }
    else if(days_apart>=7){
        //THE EVENT SPANS 7-30 CONTINUOUS DAYS
        ctrl.options[1] = null; /*REMOVE DAILY*/
        ctrl.options[1] = null; /*REMOVE WEEKLY*/
    }
    else if(days_apart>=1){
        //THE EVENT SPANS 2-6 CONTINUOUS DAYS
        ctrl.options[1] = null; /*REMOVE DAILY*/
    }
    
    /*RESELECT THE ITEM THE USER LAST HAD SELECTED*/
    var endingItemDelta = ctrl.options.length - startingItemsCount;
    var endingSelectedIndex = startingSelectedIndex+endingItemDelta;         
    if(endingSelectedIndex>0){ctrl.selectedIndex = endingSelectedIndex;}
}

var muStart;var muEnd;
function MultidayEvent(){   
    /* Get separate date and times */
	var lSD = GetDateFromInputText("adx_txtStartDate", null);
	var lST = GetTimeFromInputText("adx_txtStartTime", null);
	var lED = GetDateFromInputText("adx_txtEndDate", null);
	var lET = GetTimeFromInputText("adx_txtEndTime", null);
		
	/* Get combined date and times */
	var lSDT = getDateInput("adx_txtStart"); var lEDT = getDateInput("adx_txtEnd");
	    
    /*If the start and end are the same day never show a message*/
    if (GetLocalDateString(lSD) == GetLocalDateString(lED))
        return true; /*Start & Ends on same day*/
    
    var allday = document.getElementById("adx_allday").checked;
    		
	/*Check if the dates entered have changed to redo comparison and messaging.*/
    if(muStart != null && muEnd != null){
        if (GetLocalDateString(lSD) == GetLocalDateString(muStart)) {
            hideErrorMessage("adx_multidayerror"); /*Start date changed*/
        }
        else
        {
            if (GetLocalDateString(lED) == GetLocalDateString(muEnd))
                hideErrorMessage("adx_multidayerror"); /*End date changed*/
        }
    }
    
    /*Set the multiday comparison times for future reference*/
	muStart=lSD; muEnd=lED;
   
    /*CALCULATE THE DAYS BETWEEN THE TWO DATES*/
    var lOneDay = 1000*60*60;
    var lHoursApart = Math.ceil((lSD-lED)/lOneDay);
          
    var lMultiDay = true;
    
    if(muStart < muEnd){
	    if((hours_apart/24) >= 1) {
    	    if(document.getElementById("adx_multidayerror")!=null){
	            if(document.getElementById("adx_multidayerror").style.visibility == "visible"){
    		        lMultiDay = true; /*Do not show the message again*/
    		        showErrorMessage("adx_multidayerror","You have selected a date and time pattern that makes this a multi-day event and not a single day event that follows a recurring series pattern.  This multi-day event has a continous duration of <B> "  +   hours_apart  +  " hours.</B>  Are you sure that you want to create a multi-day event or a single day event that recurs on multiple days?  You may either edit your schedule selections above or continue forward with your current selections by completing the remainder of the form and using the appropriate buttons at the bottom of this form.");
                }
                else if (document.getElementById("adx_multidayerror").style.visibility == "hidden"){
                    lMultiDay = false; /*Allow the message to be seen one time*/
                    showErrorMessage("adx_multidayerror","You have selected a date and time pattern that makes this a multi-day event and not a single day event that follows a recurring series pattern.  This multi-day event has a continous duration of <B> "  +   hours_apart  +  " hours.</B>  Are you sure that you want to create a multi-day event or a single day event that recurs on multiple days?  You may either edit your schedule selections above or continue forward with your current selections by completing the remainder of the form and using the appropriate buttons at the bottom of this form.");
	            }
	        }
	    }
	    else { hideErrorMessage("adx_multidayerror"); }
	
	    return lMultiDay;
	}		
}

function validOtherInformation(){
	/* The default is true */
	var valid_OtherInformation = true;
	
	/* This validates all the custom imput fields. */
	var AddmissionInformation = validOtherInformationHelper("adx_admission"); /* 255 */
  /*CHECK FOR SCRIPTING*/
    if (!checkForScript("adx_admission")) { valid_EventInformation = false; }	
    
	var OtherDetails = validOtherInformationHelper("adx_otherdetails"); /* 500 */
	
	/*CHECK FOR SCRIPTING*/
	if (!checkForScript("adx_otherdetails")) { valid_OtherInformation = false; }
	
	var Custom1 = validOtherInformationHelper("adx_custom1"); /* 255 */
	/*CHECK FOR SCRIPTING*/
	if (!checkForScript("adx_custom1")) { valid_OtherInformation = false; }
	
	var Custom2 = validOtherInformationHelper("adx_custom2"); /* 255 */
	if (!checkForScript("adx_custom2")) { valid_OtherInformation = false; }
		
	var InternalNotes; /* 1000 */
	if(document.getElementById("adx_internalnotes") != null){
		InternalNotes = trimStr(document.getElementById("adx_internalnotes").value);
		if (InternalNotes.length>1000){
            /* Tell the user to they exceeded this fields limit*/
		    showErrorMessage("adx_internalnoteserror","<br>Internal Notes allow for 1000 characters. There are currently "+InternalNotes.length+" entered.");
		    valid_OtherInformation=false;
        }
        else{hideErrorMessage("adx_internalnoteserror");}
	}
	
	/*CHECK FOR SCRIPTING*/
	if (!checkForScript("adx_internalnotes")) { valid_OtherInformation = false; }
	
		
	var facilityRoomSelection = true;
	hideErrorMessage("adx_eventlocationserror"); /*Hide error messages by default*/
	if(document.getElementById("adx_facilitycalendar")!=null){
	    /*There is a facility identifier*/
	    if (document.getElementById("adx_facilitycalendar").value == "Y") {
	        var lSel = GetSelectedFacilities();
	        if (lSel != "" && !AllRoomsSelected(lSel)) {
	            /*This is a facility calendar and all facility selections must be at the room level*/
                facilityRoomSelection=false;
                showErrorMessage("adx_eventlocationserror", "<br />Please select only Room(s) from the list provided.");           
	        } 
	    }
	}
	
	return AddmissionInformation && OtherDetails && Custom1 && Custom2 && facilityRoomSelection && valid_OtherInformation;
}

function validOtherInformationHelper(customControlName){
    var validInput=true;
    if(document.getElementById(customControlName) != null){
        var customInput="";/*This is the custom input*/
        if(document.getElementById(customControlName).value == null){
            /* Checkboxes */
            var index=0;
            while(document.getElementById(customControlName+"_"+index)!=null){
                if(document.getElementById(customControlName+"_"+index).checked == true){
                    /* This checkbox was checked */
                    customInput+="<li>"+document.getElementById(customControlName+"_"+index).value+"</li>";
                }
                index++;
            }
        }
        else{
            /* Dropdown or Textbox */
            customInput = trimStr(document.getElementById(customControlName).value);
        }
        
        customInput=trimStr(customInput);
        
        hideErrorMessage(customControlName+"error"); /*By default, hide error messages*/
        if (customInput.length>500){
            /* Tell the user to they exceeded this fields limit*/
		    showErrorMessage(customControlName+"error","<br>This field allows for 500 characters. There are currently "+customInput.length+" entered.");
		    validInput=false;
        }
        else{
            if(document.getElementById(customControlName+"Required") != null && customInput == ""){
                /* Tell the user to select or enter something.*/
	            showErrorMessage(customControlName+"error","<br>This is a required event field.");
	            validInput=false;
            }
        }
    }  
    return validInput;
}

function validImage(){
	if(document.getElementById("adx_image") != null){
		/* Validate the Extention */
		var filepath = document.getElementById("adx_image").value;
			
		if(trimStr(filepath) != ""){
			/* The user selected a file to upload, validate the extention and alt text */
			var filename = filepath.substring(filepath.lastIndexOf("\\") + 1);
			var extention = filename.substring(filename.lastIndexOf(".") + 1);
			extention = extention.toLowerCase();
			
			switch(extention){
				case "gif":/* Graphical Interchange Format */
				case "jpg":/* Joint Photographic Experts Group */
				case "jpeg":/* Joint Photographic Experts Group */
					/* These are the only valid image extentions */
					hideErrorMessage("adx_imageerror");
					break;
				default:
					/* The image uploaded is not valid */
					showErrorMessage("adx_imageerror","<br>The image being uploaded is not a valid type.");
					return(false);
					break;
			}
			
			if (IsBlank("adx_imagealt", "<br />Please enter Image Alt Text in the field provided."))
	            return(false); /*Required*/
		}
	}
	/*SCRIPT CHECK*/
	if (!checkForScript("adx_imagealt")) { return(false); }	
	return(true);	
}

function validAttachment(){
	if(document.getElementById("adx_attachment") != null){
		/* Validate the Extention */
		var filepath = document.getElementById("adx_attachment").value;
		
		if(trimStr(filepath) != ""){
			/* The user selected a file to upload, validate the extention and alt text */
			var filename = filepath.substring(filepath.lastIndexOf("\\") + 1);
			var extention = filename.substring(filename.lastIndexOf(".") + 1);
			
			switch(extention){
				case "gif":/* Graphical Interchange Format */
				case "jpg":/* Joint Photographic Experts Group */
				case "jpeg":/* Joint Photographic Experts Group */
				case "png":/* Portable Network Graphics */
				case "mov":/* Movie */
				case "qt":/* Quick Time */
				case "avi":/* Audio Video Interleave */
				case "wmv":/* Windows Media Video */
				case "wma":/* Windows Media Audio */
				case "wmf":/* Windows Meta File */
				case "wav":/* Wave Type */
				case "mp3":/* Mpeg-3 Type */
				case "m4a":/* Mpeg-4 Audio File Type (iTunes) */
				case "ram":/* Real Audio Media */
				case "doc":/* MS Word */
				case "xls":/* MS Excel */
				case "ppt":/* MS Power Point */
				case "vsd":/* MS Visio */
				case "pdf":/* Personal Document File */
				case "txt":/* Text */
				case "swf":/* Flash */
				case "docx":/* MS Word 2007 */
				case "xlsx":/* MS Excel 2007 */
				case "pptx":/* MS Power Point 2007 */
				case "vsdx":/* MS Visio 2007 */
					/* These are the valid attachment extentions */
					hideErrorMessage("adx_attachmenterror");
					break;
				default:
					/* The attachment uploaded is not valid */
					showErrorMessage("adx_attachmenterror","<br>The attachment being uploaded is not a valid type.");
					return(false);
					break;
			}
			
			if (IsBlank("adx_attachmenttext", "<br />Please enter Attachment Link Text in the field provided."))
	            return(false); /*Required*/
		}
		
	}
	return(true);
}

function GetSelectedFacilities() {
    var lSel = "";
    $.each($("input:checked[name='adx_eventfacilities']"), function() { lSel += "," + $(this).val(); });
    return (lSel == "") ? "" : lSel.substr(1);
}

function AllRoomsSelected(prSel) {
    if (prSel != "") {
        var lSelArray = new Array(); lSelArray = prSel.split(",");
        for (var i = 0; i < lSelArray.length; i++) {
            if (lSelArray[i].split("-")[2] == "0") { return false; /*ROOM NOT SELECTED*/ }
        }
    }
    return true;
}

function getDateInput(start_end){
	/* Check the dates/times selected */
    var lD = GetDateFromInputText(start_end + "Date", null);
    var lT = GetTimeFromInputText(start_end + "Time", null);
	
	if (lD == null)
	    return null;
	else
	    if (lT != null) { lD.setHours(parseInt(lT.split(":")[0]), parseInt(lT.split(":")[1]), 0, 0); }
	
	return lD;
}

function CalculateEndDate(){
    var rectype = GetRecurType();
    var count = $("#txtNumOccurrences").attr("value");
	
	if(count == ""){
	    /* There must be at least 1 occurrence */
	    $("#txtNumOccurrences").val("1");
		count=1;
	}
	
	/* Hide any date references */
	hideErrorMessage("adx_occurdate");
	GenerateInitialSchedule(rectype, count);
}

var lInterval = "Interval";
var lWeekly = "Weekly";
var lMonthlybyPosition = "Monthly by Position";
var lMonthlybyDate = "Monthly by Date";
var lYearlybyDate = "Yearly by Date";

function InitSchedulingEvents() {
    var lAdvSchdCntxt = $("#divAdvancedSchedule");
    if (lAdvSchdCntxt.length > 0) {
        /*ADVANCED SCHEDULING*/
        $("input:radio,input:checkbox", lAdvSchdCntxt).click(function() { GenerateInitialSchedule("DATE"); });

        $("input:text[id*='txtNumDays']", lAdvSchdCntxt).change(function() {
        if (String(GetRecurType()).indexOf(lInterval) >= 0) { GenerateInitialSchedule("DATE"); }
        });

        $("input:text[id*='txtNumWeeks']", lAdvSchdCntxt).change(function() {
        if (String(GetRecurType()).indexOf(lWeekly) >= 0) { GenerateInitialSchedule("DATE"); }
        });

        $("input:text[id*='txtNumMonthsPosition']", lAdvSchdCntxt).change(function() {
        if (String(GetRecurType()).indexOf(lMonthlybyPosition) >= 0) { GenerateInitialSchedule("DATE"); }
        });

        $("input:text[id*='txtNumMonthsDate']", lAdvSchdCntxt).change(function() {
        if (String(GetRecurType()).indexOf(lMonthlybyDate) >= 0) { GenerateInitialSchedule("DATE"); }
        });

        $("input:text[id*='txtNumOccurrences']", lAdvSchdCntxt).change(function() {
        GenerateInitialSchedule("COUNT");
        });

        $("input:text[id*='txtRecurEndDate']", lAdvSchdCntxt).change(function() {
        GenerateInitialSchedule("DATE");
        });
    }
    else {
        /*BASIC SCHEDULING*/
        $("input:text[id*='txtNumOccurrences']").change(function() { GenerateInitialSchedule("COUNT"); });
        $("select[id*='adx_recurtype']").change(function() { GenerateInitialSchedule("COUNT"); });
    }
}

function ShowGeneratedSchedule() {
    $("tr[id*='rowSCHD']").toggleClass("hiding", true);
    $("#rowSCHD6_GeneratedSchedule").removeClass("hiding");
    $("#ancNewSchedule").toggleClass("hiding");
}
function HideGeneratedSchedule() {
    $("tr[id*='rowSCHD']").removeClass("hiding");
    $("#rowSCHD6_GeneratedSchedule").addClass("hiding");
    $("#ancNewSchedule").toggleClass("hiding");
}
function GenerateScheduleClick() {
    GenerateInitialSchedule("COUNT");

    if (mSchedule != null && mSchedule.length > 0) {
        /* Get separate times */
        var lSD = GetDateFromInputText("adx_txtStartDate", null);
        var lED = GetDateFromInputText("adx_txtEndDate", null);
        var lST = GetTimeFromInputText("adx_txtStartTime", null);
        var lET = GetTimeFromInputText("adx_txtEndTime", null);
        var lAD = ($("input:checkbox[id*='adx_allday']").attr("checked")) ? "Y" : "N";
        ShowGeneratedSchedule();
        InitOEMScheduler(mSchedule, (lED - lSD), lST, lET, lAD);
        hideErrorMessage("adx_dateerror");       
    }
    else { HideGeneratedSchedule(); }    
}
function RecurringScheduleClick() { $("#rowSCHD5_AdvancedSchedule").toggleClass("hiding");}
function CustomScheduleClick() { $("#rowSCHD5_AdvancedSchedule").toggleClass("hiding", true); GenerateScheduleClick() }
function NewScheduleClick() { HideGeneratedSchedule(); }

function GetCustomRecuringText(prDate) {
    if (prDate == null) { return; }

    $("#spnMonthByDate").html("On day " + GetDateValue(prDate) + " of every ");

    var lMnPos = GetMonthPositionOfDay(prDate);   
    switch (lMnPos) {
        case 1: $("#spnMonthByPosition").html("On the first " + GetWeekdayName(prDate) + " of every "); break;
        case 2: $("#spnMonthByPosition").html("On the second " + GetWeekdayName(prDate) + " of every "); break;
        case 3: $("#spnMonthByPosition").html("On the third " + GetWeekdayName(prDate) + " of every "); break;
        case 4: $("#spnMonthByPosition").html("On the fourth " + GetWeekdayName(prDate) + " of every "); break;
        case 5: $("#spnMonthByPosition").html("On the fifth " + GetWeekdayName(prDate) + " of every "); break;
    }
    if(document.getElementById("chkSunday") != null){
        var chkID="chk" + GetWeekdayName(prDate)
        document.getElementById("chkSunday").checked = false;
        document.getElementById("chkMonday").checked = false;
        document.getElementById("chkTuesday").checked = false;
        document.getElementById("chkWednesday").checked = false;
        document.getElementById("chkThursday").checked = false;
        document.getElementById("chkFriday").checked = false;
        document.getElementById("chkSaturday").checked = false;
        document.getElementById(chkID).checked = true;
    }
}

function GetRecurType() {
    if ($("#divAdvancedSchedule").length > 0) {
        /*ADVANCED SCHEDULING*/
        if ($("#rowSCHD5_AdvancedSchedule").hasClass("hiding")) { return "One Time"; }
        
        if ($("input:radio[id*='radioInterval']").attr("checked"))
	        return lInterval + GetNum("txtNumDays");
        else if ($("input:radio[id*='radioWeekly']").attr("checked"))
	        return lWeekly + GetNum("txtNumWeeks");
        else if ($("input:radio[id*='radioMonthByPosition']").attr("checked"))
	        return lMonthlybyPosition + GetNum("txtNumMonthsPosition");
        else if ($("input:radio[id*='radioMonthByDate']").attr("checked"))
	        return lMonthlybyDate + GetNum("txtNumMonthsDate");
        else if ($("input:radio[id*='radioYearly']").attr("checked"))
	        return lYearlybyDate;        
    }
    else {
        /*BASIC SCHEDULING*/
        return $("#adx_recurtype option:selected").attr("value");  
    }

    return "One Time"; /*For some reason a recur type cannot be found*/
}

function GetNum(pvField) {
    var lStep = $("input[id*='" +  pvField+ "']").attr("value");
    if (!/^[\d]+$/.test(lStep)){ $("input:text[id*='" +  pvField+ "']").attr("value", "1"); lStep = "1"; }
    if (lStep == "0") { $("input:text[id*='" +  pvField+ "']").attr("value", "1"); lStep = "1"; }
    return lStep;
}

function GetRecurDays(){
    var str = "";
    if(String(GetRecurType()).indexOf("Weekly") >= 0){
	    if($("input:checkbox[id*='chkSunday']").attr("checked")) { str = "Sunday"; }
	    if($("input:checkbox[id*='chkMonday']").attr("checked")) { str = (str=="") ? "Monday" : str+",Monday"; }
	    if($("input:checkbox[id*='chkTuesday']").attr("checked")) { str = (str=="") ? "Tuesday" : str+",Tuesday"; }
	    if($("input:checkbox[id*='chkWednesday']").attr("checked")) { str = (str=="") ? "Wednesday" : str+",Wednesday"; }
	    if($("input:checkbox[id*='chkThursday']").attr("checked")) { str = (str=="") ? "Thursday" : str+",Thursday"; }
	    if($("input:checkbox[id*='chkFriday']").attr("checked")) { str = (str=="") ? "Friday" : str+",Friday"; }
	    if($("input:checkbox[id*='chkSaturday']").attr("checked")) { str = (str=="") ? "Saturday" : str+",Saturday"; }
    }
    return str;
}

function GetRecurDaysArray(prRecurDays) {
    if (prRecurDays != null && $.trim(prRecurDays) != "") {
        var lRDArray = new Array();
        var lRecurDays = String(prRecurDays).split(",");
                
        for (var i = 0; i < lRecurDays.length; i++) {
            switch(lRecurDays[i]){
                case "Sunday": lRDArray[i] = 0; break;
				case "Monday": lRDArray[i] = 1; break;
				case "Tuesday": lRDArray[i] = 2; break;
				case "Wednesday": lRDArray[i] = 3; break;
				case "Thursday": lRDArray[i] = 4; break;
				case "Friday": lRDArray[i] = 5; break;
				case "Saturday": lRDArray[i] = 6; break;
            }
        }
        return lRDArray;
    }
    else { return null; }
}

var mSchedule;
function GenerateInitialSchedule(prLoopingVariable){  
    mSchedule = new Array(); /*Reassign the public variable*/  		

	var lSD = GetDateFromInputText("adx_txtStartDate", null); /*current event start*/	
	var lRED = GetDateFromInputText("txtRecurEndDate", null); /*recurring end date*/
	var lCount = GetNum("txtNumOccurrences"); /*number of recurrences*/
	if (lRED == null) { prLoopingVariable = "COUNT"; }
	var lRecurType = GetRecurType(); /*recur type*/
	var lRecurDays = GetRecurDays(); /*recur days*/
	var lRecurDaysArray = GetRecurDaysArray(lRecurDays);
	
	/*Looping variable*/
	var lDate = GetLocalDate(GetYearValue(lSD), GetMonthValue(lSD), GetDateValue(lSD), 0, 0);
			
	if (lRecurType.indexOf("One Time") >= 0) {
	    /* Make the occurrence counter 1 */
	    GenerateScheduleArrayHelper(lDate);
	}
	else if (lRecurType.indexOf(lInterval) >= 0) {
	    var lStep = parseInt(RemoveNonNums(lRecurType));
	    while (ContinueGeneratingDates(lCount, lRED, lDate, prLoopingVariable)) {
	        /* These are all occurrences of the event */
	        GenerateScheduleArrayHelper(lDate); lCount--;
	        lDate = GetLocalDate(GetYearValue(lDate), GetMonthValue(lDate), GetDateValue(lDate) + lStep, 0, 0);
	    }
	    showErrorMessage("adx_occurdate","Last Occurrence Date: " + GetLocalDateString(mSchedule[mSchedule.length - 1]));
	}
	else if (lRecurType.indexOf(lWeekly) >= 0) {
	    var lStep = parseInt(RemoveNonNums(lRecurType)) * 7;
	    while (ContinueGeneratingDates(lCount, lRED, lDate, prLoopingVariable)) {
	        if (lRecurDays != "") {
	            if (ArrayHas(lRecurDaysArray, GetDayValue(lDate))) {
	                /* This is a weekly recuring event on select days */
	                GenerateScheduleArrayHelper(lDate); lCount--;
	            }

	            if (GetDayValue(lDate) == 6) {
	                var lFOM = FirstOfWeek(lDate); /*Go to the next week interval*/
	                lDate = GetLocalDate(GetYearValue(lFOM), GetMonthValue(lFOM), GetDateValue(lFOM) + lStep, 0, 0);
	            }
	            else {
	                /*Go to the next day of the week*/
	                lDate = GetLocalDate(GetYearValue(lDate), GetMonthValue(lDate), GetDateValue(lDate) + 1, 0, 0);
	            }
	        }
	        else {
	            /* Force this as a week recuring event */
	            GenerateScheduleArrayHelper(lDate); lCount--;
	            lDate = GetLocalDate(GetYearValue(lDate), GetMonthValue(lDate), GetDateValue(lDate) + lStep, 0, 0);
	        }
	    }
	    showErrorMessage("adx_occurdate","Last Occurrence Date: " + GetLocalDateString(mSchedule[mSchedule.length - 1]));
	}
	else if (lRecurType.indexOf(lMonthlybyDate) >= 0) {
	    
	    var lStep = parseInt(RemoveNonNums(lRecurType));
	    while (ContinueGeneratingDates(lCount, lRED, lDate, prLoopingVariable)) {
	        if (lDate != null) { GenerateScheduleArrayHelper(lDate); lCount--; }
	        else { prCount = 0; /* Stop looking for dates*/ }
	        lDate = NextMonthByDate(lDate, lStep);
	    }
	    showErrorMessage("adx_occurdate", "Last Occurrence Date: " + GetLocalDateString(mSchedule[mSchedule.length - 1]));
	}
	else if (lRecurType.indexOf(lMonthlybyPosition) >= 0) {
	    var lStep = parseInt(RemoveNonNums(lRecurType));
	    while (ContinueGeneratingDates(lCount, lRED, lDate, prLoopingVariable)) {
	        if (lDate != null) { GenerateScheduleArrayHelper(lDate); lCount--; }
	        else { prCount = 0; /* Stop looking for dates*/ }
	        var lDate = NextMonthByPosition(lDate, lStep);
	    }
	    showErrorMessage("adx_occurdate", "Last Occurrence Date: " + GetLocalDateString(mSchedule[mSchedule.length - 1]));
	}
	else if (lRecurType.indexOf("Yearly by Date") >= 0) {
	    while (ContinueGeneratingDates(lCount, lRED, lDate, prLoopingVariable)) {
	        /* These are all occurrences of an event */
	        GenerateScheduleArrayHelper(lDate); lCount--;
	        lDate = GetLocalDate(GetYearValue(lDate) + 1, GetMonthValue(lDate), GetDateValue(lDate), 0, 0);
	    }
	    showErrorMessage("adx_occurdate", "Last Occurrence Date: " + GetLocalDateString(mSchedule[mSchedule.length - 1]));
	}

    if ($("#divAdvancedSchedule").length > 0) {
        /*ADVANCED SCHEDULING*/
        $("#txtNumOccurrences").val(mSchedule.length);
        $("#txtRecurEndDate").val(GetLocalDateString(mSchedule[mSchedule.length - 1]));
        $("#adx_recurtype").val(lRecurType);
        $("#adx_recurdays").val(lRecurDays);
    }
    else {
        /*BASIC SCHEDULING*/
        $("#txtNumOccurrences").val(mSchedule.length);
        $("#adx_occurdate").html(GetLocalDateString(mSchedule[mSchedule.length - 1]));
    }
}

function ContinueGeneratingDates(prCount, prRecEnd, prDate, prLoopVariable) {
    if (prLoopVariable == "COUNT") {
        if (prCount > 0) { return true; }
    }
    else {
        if (prDate == null) { /*Do nothing returns false at the end of this function*/ }
        else if (CompareDates(prDate, prRecEnd) <= 0) { return true; }
    }
    return false;
}

function GenerateScheduleArrayHelper(prDate) {
    var lLen = mSchedule.length; mSchedule[lLen] = prDate;
}

function ShowGenerateScheduleArrayHelper() {
    if (mSchedule != null) {
        var lMSG = "";
        for (var i = 0; i < mSchedule.length; i++) { lMSG = lMSG + mSchedule[i].toString() + "\n"; }
        alertdebug({ nm: "mSchedule", vl: lMSG });
    }
}

function NextMonthByDate(prDate, prInterval) {
    var lDOM = GetDateValue(prDate);
    var lLastMonth  = GetMonthValue(prDate);
    var lCurMonth = (lLastMonth + prInterval) % 12;
    
    /*Check if we are crossing years*/
    var lAddYear = 0;
    if ((lLastMonth + prInterval) > 11) { lAddYear = 1; }
    
    var lDt = GetLocalDate(GetYearValue(prDate) + lAddYear, lCurMonth, lDOM, 0, 0);
    
    var lLimit = GetLocalDate(GetYearValue(lDt) + 15, GetMonthValue(lDt), GetDateValue(lDt), 0, 0);
    while (lDt < lLimit) {
        if (((lLastMonth + prInterval) % 12) == lCurMonth && GetDateValue(lDt) == lDOM) {
            return lDt; /*This month does contain the desired day*/
        }
        else {            
            /*This month does not contain the desired day, try the next month*/
            lLastMonth = (lLastMonth + prInterval) % 12;
            lCurMonth = (lCurMonth + prInterval) % 12;
                        
            lDt = GetLocalDate(GetYearValue(lDt)+lAddYear, lCurMonth, lDOM, 0, 0);
        }
    }

    return null; /*Past allowable dates for this event.*/ 
}

function GetWeekNumberOfDay(prDt) {
    var lWkCnt = 0;
    var lMonth = GetMonthValue(prDt);
    
    var lDt = GetLocalDate(GetYearValue(prDt), GetMonthValue(prDt), 1, 0, 0);
    while (CompareDates(lDt, prDt) <= 0) {
        if (CompareDates(lDt, prDt) == 0) {
            return lWkCnt; /*The week count of the passed date was found. */
        }
        else {
            if (GetDayValue(lDt) == 6) { lWkCnt++; /* Increment the week counter */ }
        }
                
        /* Go to the next day */
        lDt = GetLocalDate(GetYearValue(lDt), GetMonthValue(lDt), GetDateValue(lDt) + 1, 0, 0);
    }
    
    return null;
}
function GetMonthPositionOfDay(prDt) {
    var lWkCnt = 0;
    var lDt = FirstOfMonth(prDt);
    while (CompareDates(lDt, prDt) <= 0) {
        if (GetDayValue(lDt) == GetDayValue(prDt)) { lWkCnt++; /* Increment the week counter */ }
        
        if (CompareDates(lDt, prDt) == 0) { return lWkCnt; /*At the date passed to this function*/ }
                
        /* Go to the next day */
        lDt = GetLocalDate(GetYearValue(lDt), GetMonthValue(lDt), GetDateValue(lDt) + 1, 0, 0);
    }
}

function NextMonthByPosition(prDate, prInterval) {
    var lWkCnt = GetWeekNumberOfDay(prDate);
    var lMnPos = GetMonthPositionOfDay(prDate);
    var lDOW = GetDayValue(prDate);
    
    var lDt = FirstOfMonth(prDate); /* Looping date */
    var lLimit = GetLocalDate(GetYearValue(lDt) + 15, GetMonthValue(lDt), GetDateValue(lDt), 0, 0);    
    while (lDt < lLimit) {       
        /*
         Go to the first of the next interval month to look for the day needed
         Also adjust the number of weeks to skip the the currect month. If we are looking for
         the 3rd monday there is no reason to check through the first 2 weeks of the month.
         */
        var lFOM = FirstOfMonth(GetLocalDate(GetYearValue(lDt), GetMonthValue(lDt) + prInterval, 1, 0, 0));
        var lCurMonth = GetMonthValue(lFOM); /*The month the new date should end up being in*/
        var lFirstOfMonthDOW = GetDayValue(lFOM);
        if (lFirstOfMonthDOW <= lDOW) { lMnPos--; }
       
        /* lWeekInMonth will be at the start of the week that should contain the day being looked for */
        lWeekInMonth = FirstOfWeek(GetLocalDate(GetYearValue(lFOM), GetMonthValue(lFOM), 1 + (7 * lMnPos), 0, 0));
        lDayInWeek = GetLocalDate(GetYearValue(lWeekInMonth), GetMonthValue(lWeekInMonth), GetDateValue(lWeekInMonth) + lDOW, 0, 0);
                
        if (lCurMonth = GetMonthValue(lDayInWeek)) { return lDayInWeek; }
        else { lDt = lFOM; /*Keep looking*/ }
    }

    return null; /*Past allowable dates for this event.*/    
}

function alertdebug() {
    var lAlert = "";
    for (i = 0; i < arguments.length; i++) { lAlert = lAlert + arguments[i].nm + " = [" + arguments[i].vl + "]\n"; }
    alert(lAlert);
}

function CheckSchedule() {
    var valid_dates = true;
    var lCurrentMainRec = 1;
    $.each($("tr[id*='rowOEMScheduler']"), function() {
        var lSD = $("input:text[id*='StartDate']", $(this)).attr("value");
        var lED = $("input:text[id*='EndDate']", $(this)).attr("value");
        var lST = $("input:text[id*='StartTime']", $(this)).attr("value");
        var lET = $("input:text[id*='EndTime']", $(this)).attr("value");
        var lAD = $("input:checkbox[id*='iA']", $(this)).attr("checked");
        if (lAD) { lST = "12:00:00 AM"; lET = "11:59:59 PM"; }
        var lStartCheckTime = Date.parse(lSD + " " + lST);
        var lEndCheckTime = Date.parse(lED + " " + lET);
        
        var lSecondMainRec = 1;
        $.each($("tr[id*='rowOEMScheduler']"), function() {
            if (lCurrentMainRec != lSecondMainRec) {
                var lSD2 = $("input:text[id*='StartDate']", $(this)).attr("value");
                var lED2 = $("input:text[id*='EndDate']", $(this)).attr("value");
                var lST2 = $("input:text[id*='StartTime']", $(this)).attr("value");
                var lET2 = $("input:text[id*='EndTime']", $(this)).attr("value");
                var lAD2 = $("input:checkbox[id*='iA']", $(this)).attr("checked");
                if (lAD2) { lST2 = "12:00:00 AM"; lET2 = "11:59:59 PM"; }
                var lStartCheckTime2 = Date.parse(lSD2 + " " + lST2);
                var lEndCheckTime2 = Date.parse(lED2 + " " + lET2);
                if ((lStartCheckTime2 >= lStartCheckTime && lStartCheckTime2 < lEndCheckTime)){
                    valid_dates = false;
                }
                if ((lEndCheckTime2 > lStartCheckTime && lEndCheckTime2 <= lEndCheckTime)){
                    valid_dates = false;
                }
            }
            lSecondMainRec += 1;
        });
        lCurrentMainRec += 1;
    });
    if (!valid_dates) {
        showErrorMessage("adx_dateerror", "You have overlapping occurrences in your schedule.");
    }
    return valid_dates;
}