$(function() {
               $("#scheduledJobTabContainer").tabs({
                              heightStyle : "content",
                              activate: function( event, ui ) {
                                             if (ui.newTab.text() == 'Active') {
                                                            refreshActiveJobs()
                                             } else {
                                                            refreshCurrentJobs()
                                             }
                              }
               })

               buildCurrentJobsTable()
               buildActiveJobsTable()
               buildConfigPopup()
               buildSchedulePopup()
               buildHistoryPopup()
               refreshCurrentJobs()

})

/* ---------------------------------- Current Jobs table & buttons */

var allJobs = {}
function refreshCurrentJobs() {
               var currentJob = getCurrentJob()
               
               var table = $('#currentJobs').DataTable()
               table.clear()
               
               $.ajax({
                              url : 'ajax/scheduledJobs',
                              dataType : 'json',
                              data : {
                              },
                              error : commonAjaxErrorHandler,
                              success : function(r) {
                                             var selectedRowIndex = -1
                                             
                                             allJobs = {}
                                             for (var i = 0; i < r.jobs.length; i++) {
                                                            var job = r.jobs[i]
                                                            allJobs['' + job.id] = job
                                                            if (currentJob && currentJob.id == job.id)
                                                                           selectedRowIndex = i
                                                                           
                                                            var row = table.row.add(job).draw().node();
                                                            
                                                            $(row).data('job', job);
                                                            
                                             }
                                             
                                             if (selectedRowIndex != -1) {
                                                            table.row(selectedRowIndex).select();
                                             }
                                                            
                                             updateResumeAndPauseButtons();
                                             forceFocusOnInfoMessage();
                              }
               })
}

function showButtons() {
               
               updateJobManagementButtons()
               updateResumeAndPauseButtons()
}

function updateJobManagementButtons() {
               
               if ($('#currentJobs tr.selected').length == 1) {
                              $('#execute').show()
                              $('#config').show()
                              $('#schedule').show()
                              $('#history').show()
               } else {
                              $('#execute').hide()
                              $('#config').hide()
                              $('#schedule').hide()
                              $('#history').hide()
               }
               
}

function updateResumeAndPauseButtons() {
               var table = $('#currentJobs').DataTable()
               var tableData = table.data()
               
               if (tableData == null || !tableData.length)
                              return

               var hasPausedItem = false
               var hasRunningItem = false
               for (var i = 0; i < tableData.length; i++) {
                              hasPausedItem = hasPausedItem || (tableData[i].status == 'PAUSED')
                              hasRunningItem = hasRunningItem || (tableData[i].status == 'WAITING')
               }
               
               $('#resumeAll').toggle(hasPausedItem)
               $('#pauseAll').toggle(hasRunningItem)
}

function forceFocusOnInfoMessage() {
               
               if($('#informationMessageDiv').is(':visible')){
                              $('#informationMessageDiv p').focus()
               }
}

function forceFocusOnTableHeader() {
	$(this).parent().focus()	
}

function buildCurrentJobsTable() {
               var table = $('#currentJobs').DataTable({
                              "columnDefs" : [{
                                             "targets" : 0,
                                             "data" : function(row, type, set, meta) {
                                                            return row.jobName
                                             }
                              }, {
                                             "targets" : 1,
                                             "data" : function(row, type, set, meta) {
                                                            return row.jobDescription
                                             }
                              }, {
                                             "targets" : 2,
                                             "data" : function(row, type, set, meta) {
                                                            return row.jobScheduleDescription
                                             }
                              }, {
                                             "targets" : 3,
                                             "data" : function(row, type, set, meta) {
                                                            return row.nextFireTime
                                             }
                              }, {
                                             "targets" : 4,
                                             "data" : function(row, type, set, meta) {
                                                            return row.status
                                             }
                              }],
                              pageLength: 5,
                              paging : true,
                              autowidth : true,
                              searching : false,
                              select : 'single'
               })

               $('#currentJobs tbody').on('click', 'tr', function() {
                              var data = table.row(this).data()
                              $("#currentJobs").data('selectedJobName', data.jobName)
                              showButtons(data)
               })
}

/* ---------------------------------- Active Jobs table & buttons */

var activeJobs = {}
function refreshActiveJobs() {
               var table = $('#activeJobs').DataTable()
               table.clear()
               
               $.ajax({
                              url : 'ajax/scheduledJobs/active',
                              dataType : 'json',
                              error : commonAjaxErrorHandler,
                              success : function(r) {
                                             activeJobs = {}
                                             for (var i = 0; i < r.jobs.length; i++) {
                                                            var job = r.jobs[i]
                                                            activeJobs['' + job.id] = job
                                             }
                                             
                                             table.rows.add(r.jobs)
                                             table.draw()
                              }
               })
}

function buildActiveJobsTable() {
               var table = $('#activeJobs').DataTable({
                              "columnDefs" : [{
                                             "targets" : 0,
                                             "data" : function(row, type, set, meta) {
                                                            return row.jobName
                                             }
                              }, {
                                             "targets" : 1,
                                             "data" : function(row, type, set, meta) {
                                                            return row.formattedStartDate
                                             }
                              }, {
                                             "targets" : 2,
                                             "data" : function(row, type, set, meta) {
                                                            return row.runBy
                                             }
                              }, {
                                             "targets" : 3,
                                             "data" : function(row, type, set, meta) {
                                                            return row.status
                                             }
                              }],
                              pageLength: 5,
                              paging : true,
                              autowidth : true,
                              searching : false,
                              select : 'single'
               })
}

/* ---------------------------------- Execute button */

function submitJobExecution() {
               doubleClickSafeguard($("#execute"))
               var jobName = $('#currentJobs tr.selected td:eq(0)').text();

               if (!jobName) return
               
               $.ajax({
                              url : 'ajax/scheduledJobs/execute',
                              dataType : 'json',
                              data : {
                                             jobName : jobName
                              },
                              error : commonAjaxErrorHandler,
                              success : function() {
                                             showInformationMessage(jobName + " has been scheduled. Go to the History page to check the job completion status.")
                                             refreshCurrentJobs()
                              }
               })
}

/* ---------------------------------- Config dialog */

function buildConfigPopup() {
               $("#configFieldsWrapper").dialog({
                              autoOpen : false,
                              modal : true,
                              width : 850,
                              height : 400,
                              closeOnEscape : true,
                              draggable : true,
                              resizable : true,
                              buttons : [{
           id: "configPopupSubmit",
           text: "Submit",
           click: submitJobConfigUpdate
                              }, {
           id: "configPopupCancel",
           text: "Cancel",
           click: function() {
                                                            $(this).dialog('close')
           }
                              }]
               })
}

function popupConfigEdit() {
               var job = getCurrentJob()
               
               $("#configJobName").text(job ? job.jobName : '')
               $("#configJobNameInput").val(job ? job.jobName : '')
               $("#configGroupName").val(job ? job.groupName : '')
               $("#configJobDescription").text(job ? job.jobDescription : '')
               $("#configJobNextFireTime").text(job && job.nextFireTime ? job.nextFireTime : '')
               $("#configJobExistingStatus").text(job ? job.status : '')
               $("#configJobEmails").val(job ? job.emailDistributionList : '')
               $("#configJobStatus").val(job ? job.status.toUpperCase() : '')
               $("#configJobPreviousStatus").val(job ? job.previousTriggerStatus : '')
               $("#configFieldsWrapper").dialog('open')
}

function submitJobConfigUpdate() {
               doubleClickSafeguard($("#configPopupSubmit"))
               var jobName = $("#configJobNameInput").val()
               
               $.ajax({
                              url : 'ajax/scheduledJobs/configUpdate',
                              dataType : 'json',
                              data : {
                                             jobName : jobName,
                                             groupName : $("#configGroupName").val(),
                                             emails : $("#configJobEmails").val(),
                                             jobStatus : $("#configJobStatus").val(),
                                             previousJobStatus : $("#configJobPreviousStatus").val()
                              },
                              error : commonAjaxErrorHandler,
                              success : function() {
                                             showInformationMessage(jobName + " updated successfully.")
                                             $("#configFieldsWrapper").dialog('close')
                                             refreshCurrentJobs()
                              }
               })
}

/* ---------------------------------- Schedule dialog */

function buildSchedulePopup() {
               $("#scheduleFieldsWrapper").dialog({
                              autoOpen : false,
                              modal : true,
                              width : 850,
                              height : 400,
                              closeOnEscape : true,
                              draggable : true,
                              resizable : true,
                              buttons : [{
           id: "schedulePopupCancel",
           text: "Cancel",
           click: function() {
                                                            $(this).dialog('close')
                                             }
                              }]
               })
               
               $("#scheduleChangeWrapper").dialog({
                              autoOpen : false,
                              modal : true,
                              width : 600,
                              height : 300,
                              closeOnEscape : true,
                              draggable : true,
                              resizable : true,
                              buttons : [{
           id: "scheduleChangePopupSubmit",
           text: "Submit",
           click: submitJobScheduleValidation
       },{
           id: "scheduleChangePopupReset",
           text: "Reset",
           click: function() {
                                                            setScheduleChangeFields()
                                             }
                              }, {
           id: "scheduleChangePopupCancel",
           text: "Cancel",
           click: function() {
                                                            $(this).dialog('close')
                                             }
                              }]
               })
               
               $("#otherDate").datepicker()
               $("#scheduleChangeFrequency").change(function() {
                              scheduleChangeFrequencyUpdated(true)
               })
}

function popupScheduleEdit() {
               var job = getCurrentJob()
               
               $("#scheduleJobName").text(job ? job.jobName : '')
               $("#scheduleJobDescription").text(job ? job.jobDescription : '')
               $("#scheduleJobNextFireTime").text(job ? job.nextFireTime : '')
               $("#scheduleJobExistingStatus").text(job ? job.status : '')
               $("#scheduleJobScheduleDescriptionSpan").text(job ? job.jobScheduleDescription : '')
               
               $("#scheduleJobNameInput").val(job ? job.jobName : '')
               $("#scheduleGroupNameInput").val(job ? job.groupName : '')
               
               setScheduleChangeFields()
               
               $("#scheduleTriggerNameInput").val(job ? job.triggerName : '')
               $("#scheduleTriggerGroupInput").val(job ? job.triggerGroup : '')
               
               $("#scheduleFieldsWrapper").dialog('open')
}

function submitJobScheduleUpdate() {
               doubleClickSafeguard($("#schedulePopupSubmit"));
               var jobName = getCurrentJob().jobName;
               
               $.ajax({
                              url : 'ajax/scheduledJobs/scheduleUpdate',
                              dataType : 'json',
                              data : {
                                             jobName : jobName,
                                             cronExpression : generateCronExpression(),
                                             cronDescription : generateCronFriendlyDescription()
                              },
                              error : commonAjaxErrorHandler,
                              success : function(result) {
                            	  if(result) {
                                     $("#scheduleChangeWrapper").dialog('close');
                                     $("#scheduleFieldsWrapper").dialog('close');
                                     refreshCurrentJobs();
                            	  }
                            	  else {
                            		  /* Produce error message. */
                            		  displayAttentionDialog("Please enter a time that is not in the past.");
                            	  }
                              }
               })
}

function popupScheduleChange() {
               $("#scheduleChangeWrapper").dialog('open')
}

function submitJobScheduleValidation() {
               
               doubleClickSafeguard($("#scheduleChangePopupSubmit"));
               
               var errors = new Array();
               
               if ($('#scheduleChangeFrequency option:selected').length < 1) {
                              
                              errors.push('<span tabindex="0">Please select a run frequency.</span>');
                              
               } else {
                              
                              var option = $('#scheduleChangeFrequency option:selected').text().trim();
                              
                              if (option == 'Daily Weekly') {
                                             
                                             if ($('#dailyWeeklyOptions input[name="dailyWeeklyOptions"]:checked').length < 1) {
                                                            errors.push('<span tabindex="0">Please select one or more days of the week.</span>');
                                             }
                                             
                              } else if (option == 'Monthly') {
                                             
                                             if ($('#monthlyOptions input[name="scheduleType"]:checked').val() == 'dayOfMonth') {
                                                            if ($('#relativeDayOfMonthValue option:selected').length < 1) {
                                                                           errors.push('<span tabindex="0">Please select a day of the month.</span>');
                                                            }
                                             } else {
                                                            
                                                            if ($('#weekOfMonth option:selected').length < 1) {
                                                                           errors.push('<span tabindex="0">Please select a week of the month.</span>');
                                                            }
                                                            
                                                            if ($('#dayOfWeek option:selected').length < 1) {
                                                                           errors.push('<span tabindex="0">Please select a day of the week.</span>');
                                                            }
                                                            
                                             }

                              } else if (option == 'Quarterly') {
                                             
                                             if ($('#quarterlyDate option:selected').length < 1) {
                                                            errors.push('<span tabindex="0">Please select first or last day of quarter.</span>');
                                             }

                              } else if (option == 'Yearly') {
                                             
                                             if ($('#yearlyOptions input[name="scheduleType"]:checked').val() == 'specificDayOfYear') {
                                                            
                                                            if ($('#yearlyMonth option:selected').length < 1) {
                                                                           errors.push('<span tabindex="0">Please select a month.</span>');
                                                            }
                                                            
                                                            if ($('#yearlyDayOfMonth option:selected').length < 1) {
                                                                           errors.push('<span tabindex="0">Please select a day of the month.</span>');
                                                            }
                                                            
                                             } else {
                                                            
                                                            if ($('#yearlyWeekOfMonth option:selected').length < 1) {
                                                                           errors.push('<span tabindex="0">Please select week of month.</span>');
                                                            }

                                                            if ($('#yearlyDayOfWeek option:selected').length < 1) {
                                                                           errors.push('<span tabindex="0">Please select day of week .</span>');
                                                            }

                                                            if ($('#yearlyRelativeMonth option:selected').length < 1) {
                                                                           errors.push('<span tabindex="0">Please select month.</span>');
                                                            }

                                             }

                              } else {
                                             
                                             if ($('#otherDate').val().length < 1) {
                                                            errors.push('<span tabindex="0">Please select a calendar day.</span>');
                                             }

                              }
                              
               }
               
               if ($('#scheduleChangeStartTimeHour option:selected').length < 1) {
                              errors.push('<span tabindex="0">Please select an hour.</span>');
               }
               
               if ($('#scheduleChangeStartTimeMinute option:selected').length < 1) {
                              errors.push('<span tabindex="0">Please select a minute.</span>')
               }
               
               if (errors.length > 0) {
                              
                              displayAttentionDialog("<span tabindex='0'>Please correct the following errors:</span><ul><li>"
                                                            + errors.join("</li><li>") + "</li></ul>");
               
               } else {
                              
                              submitJobScheduleUpdate();
                              
               }
               
}

function scheduleChangeFrequencyUpdated(selectFirstScheduleType) {
               var runFrequency = $("#scheduleChangeFrequency").val()
               $("#dailyWeeklyOptions").toggle(runFrequency == '1')
               $("#monthlyOptions").toggle(runFrequency == '2')
               $("#quarterlyOptions").toggle(runFrequency == '3')
               $("#yearlyOptions").toggle(runFrequency == '4')
               $("#otherOptions").toggle(runFrequency == '5')
               
               if (selectFirstScheduleType)
                              $("div.scheduleTypeFields:visible input[name='scheduleType']:first").prop('checked', true)
}

function setScheduleChangeFields(selectFirstScheduleType) {
               var job = getCurrentJob()
               
               /* cron */
               $("#scheduleJobCronInput").val(job ? job.jobSchedule : '')
               $("#scheduleJobScheduleDescriptionInput").val(job ? job.jobScheduleDescription : '')
               
               var runFrequency = job && job.reportSchedule && job.reportSchedule.runFrequency ? job.reportSchedule.runFrequency.value : ''
               $("#scheduleChangeFrequency").val(runFrequency)
               
               var scheduleTypeVal = job && job.reportSchedule && job.reportSchedule.scheduleType ? job.reportSchedule.scheduleType.value : ''
               if (scheduleTypeVal != '')
                              $("input[name='scheduleType'][value='" + scheduleTypeVal + "']").prop('checked', true)
               
               // days of week
               $("input[name='dailyWeeklyOptions']").prop('checked', false)
               if (job && job.reportSchedule && job.reportSchedule.daysOfWeek) {
                              for (var i = 0; i < job.reportSchedule.daysOfWeek.length; i++)
                                             $("input[name='dailyWeeklyOptions'][value='" + job.reportSchedule.daysOfWeek[i].value + "']").prop('checked', true)
               }
               
               // monthly
               $("#relativeDayOfMonthValue").val(job && job.reportSchedule && job.reportSchedule.dayOfMonth ? job.reportSchedule.dayOfMonth.value : '')
               $("#weekOfMonth").val(job && job.reportSchedule && job.reportSchedule.weekOfMonth ? job.reportSchedule.weekOfMonth.value : '')
               $("#dayOfWeek").val(job && job.reportSchedule && job.reportSchedule.dayOfWeek ? job.reportSchedule.dayOfWeek.value : '')
               $("#quarterlyDate").val(job && job.reportSchedule && job.reportSchedule.dayOfQuarter ? job.reportSchedule.dayOfQuarter.value : '')
               
               // yearly
               $("#yearlyMonth").val(job && job.reportSchedule && job.reportSchedule.month ? job.reportSchedule.month.value : '')
               $("#yearlyMonthFixedDay").val(job && job.reportSchedule && job.reportSchedule.numericDayOfMonth != 0 ? job.reportSchedule.numericDayOfMonth : '')
               $("#yearlyWeekOfMonth").val(job && job.reportSchedule ? job.reportSchedule.weekOfMonth : '')
               $("#yearlyDayOfWeek").val(job && job.reportSchedule && job.reportSchedule.dayOfWeek ? job.reportSchedule.dayOfWeek.value : '')
               $("#yearlyRelativeMonth").val(job && job.reportSchedule ? job.reportSchedule.month : '')
               
               // other
               $("#otherDate").val(job && job.reportSchedule && job.reportSchedule.dateToGenerate ? job.reportSchedule.dateToGenerate.date : '')
               
               $("#scheduleChangeStartTimeHour").val(job && job.reportSchedule ? job.reportSchedule.hour : '')
               $("#scheduleChangeStartTimeMinute").val(job && job.reportSchedule ? job.reportSchedule.minute : '')
               
               scheduleChangeFrequencyUpdated(selectFirstScheduleType)
}

function getCurrentJob() {
               return $('#currentJobs tr.selected').data('job');
}

function buildDaysOfWeekCSV() {
               var daysOfWeekCSV = []
               $("input[name='dailyWeeklyOptions']:checked").each(function() {
                              daysOfWeekCSV.push($(this).val())
               })
               return daysOfWeekCSV.join(',')
}

/* ---------------------------------- History dialog */

function buildHistoryPopup() {
               $("#historyFieldsWrapper").dialog({
                              autoOpen : false,
                              modal : true,
                              width : 950,
                              height : 750,
                              closeOnEscape : true,
                              draggable : true,
                              resizable : true,
                              buttons : [{
           id: "historyPopupStatisticsButton",
           text: "Statistics",
           click: popupHistoryStatistics,
           "class": 'statisticsButtonClass'
                              }, {
           id: "historyPopupCancelButton",
           text: "Cancel",
           click: function() {
                                                            $(this).dialog('close')
           }
                              }]
               })
               
               $("#historyStatsFieldsWrapper").dialog({
                              autoOpen : false,
                              modal : true,
                              width : 650,
                              height : 400,
                              closeOnEscape : true,
                              draggable : true,
                              resizable : true,
                              buttons : {
                                 "Close" : function() {
                                                            $(this).dialog('close')
           }
                              }
               })
               
               var table = $('#jobHistoryTable').DataTable({
                              "columnDefs" : [{
                                             "targets" : 0,
                                             "data" : function(row, type, set, meta) {
                                                            return row.formattedStartDate
                                             }
                              }, {
                                             "targets" : 1,
                                             "data" : function(row, type, set, meta) {
                                                            return row.formattedEndDate
                                             }
                              }, {
                                             "targets" : 2,
                                             "data" : function(row, type, set, meta) {
                                                            return row.recordCreatedBy
                                             }
                              }, {
                                             "targets" : 3,
                                             "data" : function(row, type, set, meta) {
                                                            return row.jobStatus
                                             }
                              }, {
                                             "targets" : 4,
                                             "data" : function(row, type, set, meta) {
                                                            return row.jobStatus
                                             }
                              }],
                              pageLength: 5,
                              paging : true,
                              autowidth : true,
                              searching : false,
                              select : 'single'
               })

               $('#jobHistoryTable tbody').on('click', 'tr', function() {
                              var data = table.row(this).data()
                              $("#historyFieldsWrapper").data('selectedHistoryEntry', data)
                              $(".statisticsButtonClass").show()
               })
}

function popupHistory() {
               var currentJob = getCurrentJob()
               $("#historyFieldsJobName").text(currentJob.jobName)
               $("#historyFieldsDescription").text(currentJob.jobDescription)
               $("#historyFieldsNextScheduledTime").text(currentJob.nextFireTime)
               $("#historyFieldsStatus").text(currentJob.status)
               
               $("#historyFieldsWrapper").dialog('open')
               refreshJobHistory()
}

function refreshJobHistory() {
               var currentJob = getCurrentJob()
               
               var table = $('#jobHistoryTable').DataTable()
               table.clear()
               
               $.ajax({
                              url : 'ajax/scheduledJobs/jobHistory',
                              dataType : 'json',
                              data : {
                                             jobName : currentJob.jobName,
                                             jobGroup : currentJob.groupName
                              },
                              error : commonAjaxErrorHandler,
                              success : function(r) {
                                             table.rows.add(r.history)
                                             table.draw()
                              }
               })
}

function popupHistoryStatistics() {
               var job = getCurrentJob()
               var historyEntry = $("#historyFieldsWrapper").data('selectedHistoryEntry')
               $("#statsName").text(job.jobName)
               $("#statsDetails").val(historyEntry.statistics)
               $("#historyStatsFieldsWrapper").dialog('open')
}

/* ---------------------------------- Pause All / Resume All buttons */

function submitPauseAll() {
               doubleClickSafeguard($("#pauseAll"))
               
               confirmDialog('Do you want to pause all the scheduled jobs?', function() {
                                             $.ajax({
                                                            url : 'ajax/scheduledJobs/pauseAll',
                                                            dataType : 'json',
                                                            error : commonAjaxErrorHandler,
                                                            success : function() {
                                                                           showInformationMessage("All the scheduled jobs have been paused successfully.")
                                                                           refreshCurrentJobs()
                                                            }
                                             })
                              }, {
                                             title : 'Pause Scheduled Jobs',
                                             okButtonLabel : 'Yes',
                                             cancelButtonLabel : 'No'
                              })
}

function submitResumeAll() {
               doubleClickSafeguard($("#resumeAll"))
               
               confirmDialog('Do you want to resume all the scheduled jobs?', function() {
                                             $.ajax({
                                                            url : 'ajax/scheduledJobs/resumeAll',
                                                            dataType : 'json',
                                                            error : commonAjaxErrorHandler,
                                                            success : function() {
                                                                           showInformationMessage("All the scheduled jobs have been resumed successfully.")
                                                                           refreshCurrentJobs()
                                                            }
                                             })
                              }, {
                                             title : 'Resume Scheduled Jobs',
                                             okButtonLabel : 'Yes',
                                             cancelButtonLabel : 'No'
                              })
}

/* ---------------------------------- Generate cron expression from GUI */

function generateCronExpression() {
               
               var option = $('#scheduleChangeFrequency option:selected').text();
               
               if (option == 'Daily Weekly') {
                              
                              return generateDailyWeeklyCronExpression();
                              
               } else if (option == 'Monthly') {

                              return generateMonthlyCronExpression();

               } else if (option == 'Quarterly') {

                              return generateQuarterlyCronExpression();

               } else if (option == 'Yearly') {

                              return generateYearlyCronExpression();

               } else {
                              
                              return generateOtherCronExpression();

               }
               
}

function generateDailyWeeklyCronExpression() {
               
               var cron = '';
               cron += '0 ';
               cron += $('#scheduleChangeStartTimeMinute option:selected').text().trim();
               cron += ' ';
               cron += $('#scheduleChangeStartTimeHour option:selected').text().trim();
               cron += ' ? * ';
               
               for (var i = 0; i < $('input[name="dailyWeeklyOptions"]:checked').length; i++) {
                              cron += $('input[name="dailyWeeklyOptions"]:checked:eq('+i+')').val();
                              if (i < $('input[name="dailyWeeklyOptions"]:checked').length-1) {
                                             cron += ',';
                              }                             
               }
               
               cron += ' *';
               
               return cron;
               
}

function generateMonthlyCronExpression() {

               var cron = '';
               cron += '0 ';
               cron += $('#scheduleChangeStartTimeMinute option:selected').text().trim();
               cron += ' ';
               cron += $('#scheduleChangeStartTimeHour option:selected').text().trim();
               cron += ' ';
               
               var option= $('#monthlyOptions input[name="scheduleType"]:checked').val();
               
               if (option == 'dayOfMonth') {

                              cron += ' ';
                              cron += $('#relativeDayOfMonthValue option:selected').val();
                              cron += ' * ? * ';

               } else {
                              
                              cron += ' ? * ';
                              cron += $('#dayOfWeek option:selected').val();
                              cron += '#';
                              cron += $('#weekOfMonth option:selected').val();
                              cron += ' * ';
                              
               }
               
               return cron;

}

function generateQuarterlyCronExpression() {

               var cron = '';
               cron += '0 ';
               cron += $('#scheduleChangeStartTimeMinute option:selected').text().trim();
               cron += ' ';
               cron += $('#scheduleChangeStartTimeHour option:selected').text().trim();

               if ($('#quarterlyDate option:selected').text().trim() == 'first') {
                              cron += ' 1 JAN,MAR,JUN,OCT ? *';
               } else {
                              cron += ' L MAR,JUN,SEP,DEC ? *';
               }
              
               return cron;

}

function generateYearlyCronExpression() {

               var cron = '';
               cron += '0 ';
               cron += $('#scheduleChangeStartTimeMinute option:selected').text().trim();
               cron += ' ';
               cron += $('#scheduleChangeStartTimeHour option:selected').text().trim();
               cron += ' ';
               
               var option= $('#yearlyOptions input[name="scheduleType"]:checked').val();

               if (option == 'specificDayOfYear') {
                              
                              cron += $('#yearlyDayOfMonth option:selected').val();
                              cron += ' ';
                              cron += $('#yearlyMonth option:selected').val();
                              cron += ' ? *';

               } else {
            	   	cron += ' ? ';
            	   	cron += $('#yearlyRelativeMonth option:selected').val();
            	   	cron += ' '
            	   	cron += $('#yearlyDayOfWeek option:selected').val();
                    cron += '#';
                    cron += $('#yearlyWeekOfMonth option:selected').val();
                    cron += ' *';
               }
              
               return cron;        

}

function generateOtherCronExpression() {

               var cron = '0 ';
               cron += $('#scheduleChangeStartTimeMinute option:selected').text().trim();
               cron += ' ';
               cron += $('#scheduleChangeStartTimeHour option:selected').text().trim();
               cron += ' ';
               cron += $('#otherDate').val().split('/')[1];
               cron += ' ';
               cron += getCronMonth($('#otherDate').val().split('/')[0]);
               cron += ' ? ';
               cron += $('#otherDate').val().split('/')[2];
               /* Validate that this is after the current time/date */
               
               return cron;

}

function getCronMonth(value) {
               
               if (value=='01') {
                              return 'JAN';
               } else if (value=='02') {
                              return 'FEB';
               } else if (value=='03') {
                              return 'MAR';
               } else if (value=='04') {
                              return 'APR';
               } else if (value=='05') {
                              return 'MAY';
               } else if (value=='06') {
                              return 'JUN';
               } else if (value=='07') {
                              return 'JUL';
               } else if (value=='08') {
                              return 'AUG';
               } else if (value=='09') {
                              return 'SEP';
               } else if (value=='10') {
                              return 'OCT';
               } else if (value=='11') {
                              return 'NOV';
               } else {
                              return 'DEC';
               } 
               
}

/*
 * ---------------------------------- Generate cron friendly description from
 * GUI
 */


function generateCronFriendlyDescription() {
               
               var option = $('#scheduleChangeFrequency option:selected').text();
               
               if (option == 'Daily Weekly') {
                              
                              return generateDailyWeeklyCronFriendlyDescription();
                              
               } else if (option == 'Monthly') {

                              return generateMonthlyCronFriendlyDescription();

               } else if (option == 'Quarterly') {

                              return generateQuarterlyCronFriendlyDescription();

               } else if (option == 'Yearly') {

                              return generateYearlyCronFriendlyDescription();

               } else {
                              
                              return generateOtherCronFriendlyDescription();

               }
               
}

function generateDailyWeeklyCronFriendlyDescription() {
               
               var description = '';
               
               description += 'Every ';

               for (var i = 0; i < $('input[name="dailyWeeklyOptions"]:checked').length; i++) {
                              description += $('input[name="dailyWeeklyOptions"]:checked:eq('+i+')').val();
                              if (i < $('input[name="dailyWeeklyOptions"]:checked').length-1) {
                                             description += ',';
                              }                             
               }
               description += ' at ';
               description += $('#scheduleChangeStartTimeHour option:selected').text().trim();
               description += ':';
               description += getMinuteDescription();
               description += '.'; 
               
               return description;
               
}

function generateMonthlyCronFriendlyDescription() {
               
               var description = '';
               
               var option= $('#monthlyOptions input[name="scheduleType"]:checked').val();

               if (option == 'dayOfMonth') {
                              
                              description += 'The '; 
                              description += $('#relativeDayOfMonthValue option:selected').text().trim(); 
                              description += ' day of every month'; 
                                             
               } else {

                              description += 'The '; 
                              description += $('#weekOfMonth option:selected').text().trim(); 
                              description += ' ';
                              description += $('#dayOfWeek option:selected').text().trim(); 
                              description += ' of every month'; 

               }
               
               description += ' at ';
               description += $('#scheduleChangeStartTimeHour option:selected').text().trim();
               description += ':';
               description += getMinuteDescription();
               description += '.'; 
               
               return description;
               
}

function generateQuarterlyCronFriendlyDescription() {
               
               var description = '';
               
               description += 'Runs on the ';
               description += $('#quarterlyDate option:selected').text().trim();
               description += ' day of every quarter at ';
               description += $('#scheduleChangeStartTimeHour option:selected').text().trim();
               description += ':';
               description += getMinuteDescription();
               description += '.'; 
               
               return description;
               
}

function generateYearlyCronFriendlyDescription() {
               
               var description = '';
               
               description += 'Runs yearly on ';
               
               var option= $('#yearlyOptions input[name="scheduleType"]:checked').val();

               if (option == 'specificDayOfYear') {
                              
                              description += 'every '; 
                              description += $('#yearlyMonth option:selected').text().trim(); 
                              description += ' on day '; 
                              description += $('#yearlyDayOfMonth option:selected').text().trim(); 
                              description += ' of the month.'; 
                                             
               } else {

                              description += ' the '; 
                              description += $('#yearlyWeekOfMonth option:selected').text().trim(); 
                              description += ' '; 
                              description += $('#yearlyDayOfWeek option:selected').text().trim(); 
                              description += ' of '; 
                              description += $('#yearlyRelativeMonth option:selected').text().trim(); 

               }
               
               description += ' at ';
               description += $('#scheduleChangeStartTimeHour option:selected').text().trim();
               description += ':';
               description += getMinuteDescription();
               description += '.'; 
               
               return description;
               
}

function generateOtherCronFriendlyDescription() {
               
               var description = '';
               
               description += 'Runs just once on ';
               description += $('#otherDate').val();
               description += ' at ';
               description += $('#scheduleChangeStartTimeHour option:selected').text().trim();
               description += ':';
               description += getMinuteDescription();
               description += '.'; 
               
               return description;
               
}

function getMinuteDescription() {

               var min = $('#scheduleChangeStartTimeMinute option:selected').text().trim();
               
               if (min.length < 2) {
                              min = '0' + $('#scheduleChangeStartTimeMinute option:selected').text().trim();
               }
               
               return min;
               
}
