﻿

$(document).ready(function () {

	$(document.body).on('click', '#ready_to_submit', function (e) {
		e.preventDefault();
		var ready_text = $('#ready_text').val();
		var education_count = 0;
		var work_history_count = 0;
		var specialties_count = 0;
		var references_count = 0;

		$.ajax({
			type: 'POST',
			url: '/Monitors/MonitorCount/',
			data: {},
			dataType: 'json',
			async: false,
			success: function (data) {
				if (data) {
					education_count = parseInt(data.education_count);
					work_history_count = parseInt(data.work_history_count);
					specialties_count = parseInt(data.specialties_count);
					references_count = parseInt(data.references_count);

					if (education_count == 0 || work_history_count == 0 || specialties_count == 0 || references_count < 2) {
						return displayErrorMessage('You need at least one entry for education, work history, specialties, and two references.')
					}

					if (ready_text != 'ready') {
						return displayErrorMessage('Please make sure you enter "ready" (case sensitive) in the box.');
					}

					if (confirm('Are you sure you are prepared to submit? ')) {
						$.ajax({
							type: 'POST',
							url: '/Monitors/ReadySubmit/',
							data: { id: current_monitor_id },
							dataType: 'json',
							async: false,
							success: function (data) {
								document.location.reload();
							}
						});
					}
				}
			}
		});
	});

	$(document.body).on('click', '#save_monitor', function (e) {
		e.preventDefault();
		var $this = $(this);
		var $form = $('#monitor_form form');
		var form_values = $('#monitor_form input, #monitor_form select, #monitor_form textarea').serializeObject(false, '', true);
		var target = ($this.data('admin')) ? '/Admin/MonitorProfile/' : '/Monitors/MonitorProfile/';
        var isreg = ($this.data('reg')) ? true : false;
        var monitor_id = $('#Monitor_MonitorID').val();

        if (monitor_id == 0) {
            form_values.MonitorStartYear = Now().split('/')[2];
            form_values.Phone = 'NA';
            form_values.Zip = '00000';
            form_values.City = 'NA';
            form_values.State = 'NA';
            form_values.Address1 = 'NA';
        }

		if ($('#new_password').val() !== '' && $('#confirm_password').val() != $('#new_password').val()) {
			return displayErrorMessage('Passwords must match.');
		} else {
			form_values.Password = $('#new_password').val();
        }
		
		$.validator.unobtrusive.parse($form);
		$form.validate();
		var is_valid = $form.valid();

		if (!is_valid || $('#monitor_form .field-validation-error').length > 0) {
			return displayErrorMessage('There were validation errors, please see fields with red text under them.');
		} else {
			$.ajax({
				type: 'POST',
				url: target,
				data: form_values,
				dataType: 'html',
				async: false,
                success: function (data) {					
                    if (monitor_id == 0) {
                        $('#approved_monitors_tab').trigger('click');
                        closeDialog();                        
                    }
					displayInfoMessage('Monitor profile has been updated.');
				}
			});
		}		
	});	

	$(document.body).on('click', '.decline_project', function (e) {
		e.preventDefault();
		var $this = $(this);
		var this_id = $this.data('id');
		var project_id = $this.data('project-id');
		current_project_resources_id = this_id;
		current_project_id = project_id;
		loadDialog('ProjectDeclined', { id: project_id });
	});

	$(document.body).on('keyup', '#decline_reason', function (e) {
		var textlimit = 255;
		var $this = $(this);
		var tlength = $this.val().length;
		$this.val($this.val().substring(0, textlimit));
		var tlength = $this.val().length;
		remain = parseInt(tlength);
		$('#remain').text(textlimit - remain);		
	});

	$(document.body).on('click', '#final_decline_project', function (e) {
		var decline_reason = $('#decline_reason').val();

		if (decline_reason == '') {
			return displayErrorMessage('You must enter a reason to decline the project.');
		}

		$.ajax({
			type: 'POST',
			url: '/Monitors/DeclineProject/',
			data: {
				this_id: current_project_resources_id,
				accept: 'No',
				reason: decline_reason
			},
			dataType: 'html',
			async: false,
			success: function (data) {
				$('#pending_' + current_project_resources_id).remove();
				$('#pending_projects_count').text(parseInt($('#pending_projects_count').text()) - 1);
				if ($('#pending_projects tbody tr').length == 0) {
					$('#pending_projects_div').addClass('hidden');
				}

				displayInfoMessage('Project declined.');
				closeDialog();
			}
		});
	});

	$(document.body).on('click', '.accept_project', function (e) {
		e.preventDefault();
		var $this = $(this);
		var this_id = $this.data('id');
		var project_id = $this.data('project-id');
		current_project_resources_id = this_id;
		current_project_id = project_id;
		loadDialog('ProjectConfirmed', { id: project_id });
	});

	$(document.body).on('click', '#final_accept_project', function (e) {
		$.ajax({
			type: 'POST',
			url: '/Monitors/AcceptProject/',
			data: {
				this_id: current_project_resources_id,
				accept: 'Yes'
			},
			dataType: 'html',
			async: false,
			success: function (data) {				
				if ($('#screening_projects').length > 0) {
					var row = $('#pending_' + current_project_resources_id).remove().clone();
					$('#screening_projects tbody').append(row);
					$('#pending_button_' + current_project_resources_id).html('').removeClass('button-td-large').addClass('button-td-date');					
					$('#screening_projects_div').removeClass('hidden');
					$('#screening_projects_count').text(parseInt($('#screening_projects_count').text()) + 1);
					$('#pending_projects_count').text(parseInt($('#pending_projects_count').text()) - 1);
				}
				else {
					$('#pending_' + current_project_resources_id).remove();
					$('#pending_projects_count').text(parseInt($('#pending_projects_count').text()) - 1);
				}
				if ($('#pending_projects tbody tr').length == 0) {
					$('#pending_projects_div').addClass('hidden');
				}
				
				displayInfoMessage('Project accepted.');
				closeDialog();
			}
		});
	});

	$(document.body).on('click', '.view_project', function (e) {
		e.preventDefault();
		var $this = $(this);
		var this_id = $this.data('id');
		var project_id = $this.data('project-id');
		current_project_resources_id = this_id;
		current_project_id = project_id;
		current_project_status = $this.data('project-status');
		loadDialog('Project', { id: project_id });
	});

	$(document.body).on('click', '.timesheet_project', function (e) {
		e.preventDefault();
		var $this = $(this);
		var this_id = $this.data('id');
		var project_id = $this.data('project-id');
		current_project_resources_id = this_id;
		current_project_id = project_id;
		//loadDialog('Timesheet', { id: project_id, date: Now() });		
		$('.nav-main a[thisadmin="/Monitors/Timesheets/"]:visible').trigger('click');
	});

	$(document.body).on('change', '#Project_List, #ts_date', function (e) {
		var project_id = $('#Project_List').val() || 0;
		var ts_date = $('#ts_date').val() || '';
		if (project_id == 0) {
			return displayErrorMessage('You must choose a project.');
		} else if (ts_date == '') {
			return displayErrorMessage('You must choose a week for the timesheet.');
		} else {
			current_project_id = project_id;
			$('#timesheet_load_content').html(wait_html).load('/Partial/Timesheet/' + project_id + '/?ts_date=' + ts_date, function () {

			});
		}
	});

	$(document.body).on('click', '.edit_timesheet', function (e) {
		e.preventDefault();

		var $this = $(this);
		var this_date = $this.data('timesheet-date');
		current_sponsor_id = $this.data('sponsor-id');

		$('.timesheet-days[data-timesheet-date!="' + this_date + '"], #finalize_timesheet_hours, .edit_timesheet').addClass('hidden').removeClass('timesheet-header');
		$('.timesheet-days[data-timesheet-date="' + this_date + '"]').addClass('timesheet-header');		
		$('.timesheet-days[data-timesheet-date="' + this_date + '"] .back_timesheet').removeClass('hidden');

		$('#ts_edit_' + this_date.replace(/\//g, '')).removeClass('hidden').html(wait_html).load('/Partial/TimesheetDetails/' + current_project_id + '/?ts_date=' + this_date, function () {
      		$('.add_timesheet[data-date-unhide="' + this_date.replace(/\//g, '') + '"]').removeClass('hidden');
		});
	});

	$(document.body).on('click', '.add_timesheet', function (e) {
		e.preventDefault();

		var $this = $(this);
		var this_date = $this.data('timesheet-date');
		current_sponsor_id = $this.data('sponsor-id');

		if ($('#row_0').length > 0) {
			return displayErrorMessage('Finish saving the first item before trying to add another.');
        }

        $('#row_norecords').remove();
        var add_html = '<div class="form-group" id="row_0"><div class="timesheet-row"><div class="col-md-2 text-right"><label class="control-label">Details</label></div><div class="col-md-6"><select id="category_0" class="form-control"></select></div><div class="col-md-2"><input type="text" class="form-control form-control-shortest timesheet-hours" id="hours_0" value="0" placeholder="Hours" /></div><div class="col-md-2"><button type="button" class="btn btn-sm btn-primary save_timesheet_item" data-timesheet-date="' + this_date + '" data-timesheet-id="0"><span class="glyphicon glyphicon-floppy-disk"></span></button> <button type="button" class="btn btn-sm btn-danger cancel_timesheet_item" data-timesheet-date="' + this_date + '" data-timesheet-id="0"><span class="glyphicon glyphicon-ban-circle"></span></button></div><br class="clear" /></div>\r\n<div class="timesheet-row bottom-row"><div class="col-md-2 text-right"><label class="control-label">Notes</label></div><div class="col-md-10"><textarea rows="3" type="text" class="form-control" id="notes_0" value="" placeholder="Notes"></textarea></div></div></div>';
		var first_select = $('#category_none').html();
		if ($('#edit_timesheet_details div').length == 0) {
			$('#edit_timesheet_details').append(add_html);
		}
		else {
			$('#edit_timesheet_details div:first').before(add_html);
		}		

		$('#category_0').html(first_select);
		$('#category_0 option:first').prop('selected', true);
	
	});

	$(document.body).on('click', '.back_timesheet', function (e) {
		e.preventDefault();

		$('.timesheet-days, #finalize_timesheet_hours, .edit_timesheet').removeClass('hidden').removeClass('timesheet-header');
		$('.timesheet-detail-edit, .back_timesheet, .add_timesheet').addClass('hidden');
		$('.timesheet-detail-edit').html('');
		
	});

	$(document.body).on('click', '.cancel_timesheet_item', function (e) {
		e.preventDefault();
		$('#row_0').remove();
	});

	$(document.body).on('click', '.save_timesheet_item', function (e) {
		e.preventDefault();

		var timesheet_info = {};
		var $this = $(this);
		var timesheet_id = $this.data('timesheet-id');
		var this_date = $this.data('timesheet-date');
		timesheet_info.TimesheetID = timesheet_id;
		timesheet_info.IsMobile = $('#ismobile_' + timesheet_id).val();
		timesheet_info.Hours = $('#hours_' + timesheet_id).val();
		timesheet_info.Notes = $('#notes_' + timesheet_id).val();
		timesheet_info.Category = $('#category_' + timesheet_id).val();
		timesheet_info.TSDate = this_date;
		timesheet_info.MonitorID = current_monitor_id;
		timesheet_info.ProjectID = current_project_id;
		timesheet_info.SponsorID = current_sponsor_id;

		if (!isNumeric(timesheet_info.Hours)) {
			return displayErrorMessage('Hours must be a number.');
		}
		$.ajax({
			type: 'POST',
			url: '/Monitors/UpdateTimesheets/',
			data: timesheet_info,
			dataType: 'json',
			async: false,
			success: function (data) {				
				if (timesheet_id == 0) {
                    var html = '<div class="form-group" id="row_' + data.TimesheetID + '"><div class="timesheet-row"><div class="col-md-2 text-right"><label class="control-label">Details</label></div><div class="col-md-6"><select id="category_' + data.TimesheetID + '" class="form-control"></select></div><div class="col-md-2"><input type="text" class="form-control form-control-shortest timesheet-hours" id="hours_' + data.TimesheetID + '" value="' + timesheet_info.Hours + '" placeholder="Hours" /></div><div class="col-md-2"><button type="button" class="btn btn-sm btn-primary save_timesheet_item" data-timesheet-date="' + timesheet_info.TSDate + '" data-timesheet-id="' + data.TimesheetID + '"><span class="glyphicon glyphicon-floppy-disk"></span></button><button type="button" class="btn btn-sm btn-danger del_timesheet_item" data-timesheet-date="' + timesheet_info.TSDate + '" data-timesheet-id="' + data.TimesheetID + '"><span class="glyphicon glyphicon-remove"></span></button></div><br class="clear" /></div><div class="timesheet-row"><div class="col-md-2 text-right"><label class="control-label">Notes</label></div><div class="col-md-10"><textarea rows="3" type="text" class="form-control" id="notes_' + data.TimesheetID + '" value="" placeholder="Notes">' + timesheet_info.Notes + '</textarea></div></div></div>';
					$('#row_0').replaceWith(html);
					$('#category_' + data.TimesheetID).html($('#category_none').html()).val(timesheet_info.Category);
				}
				displayInfoMessage('Hours updated.');
				updateHours(this_date);
			}
		});
	});

	$(document.body).on('click', '.del_timesheet_item', function (e) {
		e.preventDefault();

		var $this = $(this);
		var timesheet_id = $this.data('timesheet-id');
		var this_date = $this.data('timesheet-date');
		if (confirm('Are you sure you want to delete this timesheet item?')) {
            $.ajax({ type: 'POST', url: '/Monitors/DeleteTimesheets/' + timesheet_id, data: {}, dataType: 'json', async: false, success: function (data) { $('#row_' + timesheet_id).remove(); displayInfoMessage('Hours removed.'); } });
			updateHours(this_date);
		}		

	});

	$(document.body).on('click', '#finalize_timesheet_hours', function (e) {
		e.preventDefault();
		var $this = $(this);
		
		if ($this.hasClass('disabled')) {
			return displayMessage('You submitted this week\'s timesheet, this function is disabled.');
		}

		var project_id = $this.data('project-id');
        var this_dates = $this.data('timesheet-dates');
        var week_start = $this.data('week-start');
		var timesheet_info = {};
		timesheet_info.project_id = project_id;
		timesheet_info.dates = this_dates;
		timesheet_info.monitor_id = current_monitor_id;

		$.ajax({
			type: 'POST',
			url: '/Monitors/SubmitTimesheets/',
			data: timesheet_info,
			dataType: 'json',
			async: false,
            success: function (data) {
                $('#submitted').html('<span class="text-success">Yes (Locked)</span><br /><a href="/Partial/TimesheetPrint/' + project_id + '/?ts_date=' + week_start + '&print-only=true" target="_new"><i class="fas fa-print fa-fw mr-1"></i> Print Timesheet</a>');
                $('.edit_timesheet, #finalize_timesheet_hours').addClass('disabled').prop('disabled', true);
                $('#unfinalize_timesheet_hours, #move_ts').removeClass('hidden');
				displayInfoMessage('Hours submitted for approval.');				
			}
		});
    });

    $(document.body).on('click', '#unfinalize_timesheet_hours', function (e) {
        e.preventDefault();
        var $this = $(this);

        if (!confirm('Are you sure you want to unsubmit?')) {
            return false;
        }

        var project_id = $this.data('project-id');
        var this_dates = $this.data('timesheet-dates');
        var week_start = $this.data('week-start');
        var timesheet_info = {};
        timesheet_info.project_id = project_id;
        timesheet_info.dates = this_dates;
        timesheet_info.monitor_id = current_monitor_id;

        $.ajax({
            type: 'POST',
            url: '/Monitors/UnSubmitTimesheets/',
            data: timesheet_info,
            dataType: 'json',
            async: false,
            success: function (data) {
                $('#submitted').html('<span class="text-danger">No</span>');
                $('.edit_timesheet, #finalize_timesheet_hours').removeClass('disabled').prop('disabled', false);
                $('#unfinalize_timesheet_hours, #move_ts').addClass('hidden');
                displayInfoMessage('Hours un-submitted for approval.');
            }
        });
    });

	$(document.body).on('click', '.save_availability', function (e) {
		e.preventDefault();
		var availability_info = {};
		var $this = $(this);
		var month = $this.data('month');
		var year = $this.data('year');
		var this_id = $this.attr('data-id');
		var availability = $('#availability_' + month + year).val() || '';

		if (this_id > 0 || this_id == 0 && availability != '') {
			availability_info.this_id = this_id;
			availability_info.CalMonth = month;
			availability_info.CalYear = year;
			availability_info.Available = availability == '' ? null : availability;
			availability_info.MonitorID = current_monitor_id;

			$.ajax({
				type: 'POST',
				url: '/Monitors/UpdateAvailability/',
				data: availability_info,
				dataType: 'json',
				async: false,
				success: function (data) {
					displayInfoMessage('Availability updated.');
					if (!availability_info.Available) {
						$('.save_availability[data-id="' + this_id + '"]').attr('data-id', 0);
					}
				}
			});
		} else {
			displayInfoMessage('Nothing to update. Fill in availability to something other than "x" to update.')
		}
	});

	$(document.body).on('click', '#save_all_availability', function (e) {
		e.preventDefault();
		$('.save_availability').trigger('click');
	});

	$(document.body).on('click', 'button.edit, a.edit', function (e) {
		e.preventDefault();
		var $this = $(this);
		var this_id = $this.data('id');
		var section_to_load = (current_monitor_admin_section != '') ? 'Monitors' + current_monitor_admin_section : current_admin_section;
        console.log(section_to_load);
        loadDialog(section_to_load, { id: this_id });
	});

	$(document.body).on('click', 'button.del', function (e) {
		e.preventDefault();
		var $this = $(this);
		var this_id = $this.data('id');
		if (window.confirm('Are you sure you want to delete this item?')) {
			$.ajax({
				type: 'POST',
				url: '/Monitors/DeleteItem/',
                data: { id: this_id, section: (current_monitor_admin_section == '' ? current_admin_section.replace('Monitors', '') : current_monitor_admin_section) },
				dataType: 'json',
				async: false,
				success: function (data) {
					$('#item_' + this_id).remove();
					updateCount();
					displayInfoMessage('Data for ' + current_admin_section + ' updated.');
				}
			});
		}
	});

    $(document.body).on('change', '#TherapeuticArea, #TS', function (e) {
		e.preventDefault();
		var $this = $(this);		
        var area = $this.val();
        var $target = $(($this.attr('id') == 'TherapeuticArea') ? '#Indication' : '#' + $this.attr('id').replace('TS', 'Indication'));
        if (area == '') {
            $target.empty();			
		} else {
			$.getJSON('/Monitors/GetIndicationByArea/', { area: area }, function (result) {
                 if ($target.length > 0) {
                    $target.empty();
                    $target.append($('<option value="">Choose an Indication</option>'));
                    $(result).each(function () { $target.append($('<option></option>').val(this.Indication).text(this.Indication)); });
                }
			});
		}
		
	});

	$(document.body).on('click', '#save', function (e) {
		var $form = $('#dialog_form form');		
		var form_values = $('#dialog_form form input, #dialog_form form select').serializeObject(false, '', true); 
		var section_to_save = (current_monitor_admin_section != '') ? 'Monitors' + current_monitor_admin_section : current_admin_section;		

        if ($('.allow-once').length > 0) {
            var this_text = $('.does-exist').val();
            if ($('td.allow-once:contains("' + this_text + '")').length > 0) {
                return displayErrorMessage("You already entered this.");
            }
        } 

		if (current_admin_section == 'MonitorsCertifications') {
			if ($('#Certification').val() == 'Other' && $('#Monitor_Certification_Other').val() == '') {				
				$('span[data-valmsg-for="Monitor_Certification.Other"]').text('If other is chosen, you must enter text in the "Other" field.');
				return false;
			}
			else {
				$('span[data-valmsg-for="Monitor_Certification.Other"]').text('');
			}
        }
        
		$.validator.unobtrusive.parse($form);
		$form.validate();
		var is_valid = $form.valid();

		if (!is_valid || $('#dialog_form .field-validation-error').length > 0) {
			return displayErrorMessage('There were validation errors, please see fields with red text under them.');
		} else {
			$.ajax({
				type: 'POST',
				url: '/Monitors/Update' + section_to_save + '/',
				data: form_values,
				dataType: 'json',
				async: false,
                success: function (data) {	                                                                                         
					if (current_monitor_admin_section == '') {
						$('.nav-main a[thisadmin="' + current_admin_section.replace('Monitors', '/Monitors/') + '/"]:visible').click();
					} else {
                        $('#' + current_monitor_admin_section.toLowerCase() + '_div').load('/Monitors/' + current_monitor_admin_section + '/' + current_monitor_id, function () {
                            updateCount();
                        });
                    }
					closeDialog();
					displayInfoMessage('Data for ' + current_admin_section + ' updated.');
				}
			});

		}
    });

    $(document.body).on('click', '.upload_resume', function (e) {
        $('a[thisadmin="/Monitors/Files/"]').trigger('click');
    });

    $(document.body).on('change keyup', '#file_title', function () {
		enableUpload($('#file_title').val() != '' && $('#upload_type').val() != '');
	});

	$(document.body).on('change', '#upload_type', function () {
		enableUpload($('#file_title').val() != '' && $('#upload_type').val() != '');
	});

});

function enableUpload(enable) {
	$('#upload_question_decoy').toggleClass('hidden', enable);
	$('#upload_question').toggleClass('hidden', !enable);	
}

function updateHours(TSDate) {
	var total_hours = 0;
	$('.timesheet-hours').each(function () {
		total_hours = total_hours + parseFloat($(this).val());
	})
	$('#hours_update_' + TSDate.replace(/\//g, '')).text(total_hours);
	
	total_hours = 0;
	$('.hours-daily').each(function () {
		total_hours = total_hours + parseFloat($(this).text());
	});

	$('#hours_total').text(total_hours);
	
}

function upload(selector, upload_type, init_this) {
    var data = {};
    data.monitor_id = current_monitor_id;
    

    new Ajax_upload('#' + selector, {
        action: '/Monitors/Upload',
        onSubmit: function (file, ext) {
            if (!(ext && /^(doc|docx|pdf)$/.test(ext))) {
                return displayErrorMessage('Error: invalid file extension, must be doc, docx, or pdf.');
            }
            if ($('#upload_type').val() == '') {
                return displayErrorMessage('Please choose an upload type.');
            }
            if ($('#file_title').val() == '') {
                return displayErrorMessage('Please choose a name for the file.');
            } else {
                data.ext = ext;
                data.upload_type = $('#upload_type').val();
                data.file_title = $('#file_title').val();
                console.log(data);
                this.setData(data);
                this.disable();
                $('#image_loading').removeClass('hidden');
            }
        },
        onComplete: function (file, response) {
            var this_string = $.parseJSON(response.toString());
            var this_path = this_string.image_name.replace(/\|/g, "\\");
            $('#image_loading').addClass('hidden');
            displayInfoMessage('File has been uploaded.');
            $('#files_table tbody').append('<tr id="item_' + this_string.image_id + '"><td><a href="/File/' + this_string.image_id + '" target="_new">' + this_string.file_title + ' ' + ' - Download</a></td><td>' + data.upload_type + '</td><td>' + Now(true) + '</td><td class="button-td"><button type="button" class="btn btn-sm btn-danger del" data-id="' + this_string.image_id + '"><span class="glyphicon glyphicon-trash"></span></button></td></tr>');
            $('.no-data').remove();
            updateCount();
            this.enable();
        }
    });

    if (init_this) {
        $('input[name="files"]:last').click();
    }
    return this;
}

function updateCount() {
	var section = (current_monitor_admin_section == '' ? current_admin_section.replace('Monitors', '') : current_monitor_admin_section).toLowerCase();
	current_count_span = $('.' + section.toLowerCase() + '_count');
	current_count = $('#panels_load_content table:first tbody tr').not('.no-records, .no-data').length;
	//console.log(current_count)
	//console.log(current_count_span)
	//console.log(section)
	if (current_count == 0) {
		$('#panels_load_content table:first tbody').append('<tr class="no-data"><td colspan="' + $('#panels_load_content table:first thead tr th').length + '" align="center">No results for ' + section + '. <a href="javascript:void(0)" class="edit" data-id="0">add one.</a></td></tr>')
	}
	if (current_count_span.length > 0) {
		current_count_span.text(current_count);
	}
}