﻿// current level
current_user_id = readCookie('MFH_UserID');
current_user_name = (readCookie('username') != '') ? readCookie('username') : 'Guest';
current_full_name = (readCookie('MFH_FullName') != '') ? readCookie('MFH_FullName') : 'Guest';
current_sponsor_id = 0;
current_monitor_id = 0;
current_monitor_level = '';
current_sponsor_status = 'NonApproved';
current_monitor_type = '';
current_user_type_id = 0;

current_admin_id = 0;
current_admin_type = '';
current_admin_section = '';
current_monitor_admin_section = '';
current_monitor_admin_view = '';
current_sponsor_admin_section = '';
current_sponsor_admin_view = '';
current_path = document.location.href.toLowerCase();
current_project_resources_id = 0;
current_project_resources_accept = '';
current_project_id = 0;
current_project_status = '';
current_project_add_type = '';
current_count_span = '';
current_selected_monitors = [];
current_selected_monitors_html = [];

// wait msg
wait_html = '<div style="margin:20px;text-align:center">Loading...<br><img src="/images/ajax-progress.gif"></div>';

window.addEventListener("pageshow", function (event) {
    var historyTraversal = event.persisted ||
        (typeof window.performance != "undefined" &&
            window.performance.navigation.type === 2);
    if (historyTraversal) {
        // Handle page restore.
        window.location.reload();
    }
});

$(document).ready(function () {

    $(document).ajaxError(function (event, jqxhr, settings, thrownError) {
        if (parseInt(jqxhr.status) == 401 && current_path.indexOf('admin') > -1) {
            document.location.href = '/LoginAdmin';
        } else if (parseInt(jqxhr.status) == 401 && current_path.indexOf('monitor') > -1) {
            document.location.href = '/Login/?login_type=Monitors';
        } else if (parseInt(jqxhr.status) == 401 && current_path.indexOf('sponsor') > -1) {
            document.location.href = '/Login/?login_type=Sponsors';
        } else if (parseInt(jqxhr.status) == 401) {
            alert('You have been logged out. Please log in again.');
            document.location.href = '/';
        } else if (parseInt(jqxhr.status) != 503 && parseInt(jqxhr.status) != 0) {
            return displayErrorMessage("Security error, Development has been notified. \n\nState: " + jqxhr.readyState + "\nHTTP Code: " + jqxhr.status + "\nError: " + jqxhr.statusText, 'nosave');
        } 
    });  

    init();

    $('.login-menu').mouseleave(function (e) {
        e.preventDefault();
    });

    $(document.body).on('click', '#login_sponsor, #login_monitor', function (e) {
        e.preventDefault();
        var this_type = ($(this).attr('id').indexOf('monitor') > -1) ? 'monitor' : 'sponsor';
        var other_type = ($(this).attr('id').indexOf('monitor') > -1) ? 'sponsor' : 'monitor';

        var side = ($(this).attr('id').indexOf('monitor') > -1) ? 'left' : 'right';
        var other_side = ($(this).attr('id').indexOf('monitor') > -1) ? 'right' : 'left';

        $('#main_' + side).css({ 'background': 'url("/Images/' + side + '_main_dark.jpg") no-repeat center' });
        $('#main_' + other_side).css({ 'background': 'url("/Images/' + other_side + '_main.jpg") no-repeat center' });
        $('#' + this_type + '_button, #' + other_type + '_login_form').addClass('hidden');
        $('#' + this_type + '_login_form, #' + other_type + '_button').removeClass('hidden');

    });

    $(document.body).on("focus", ".datepicker", function () {
        if ($(this).attr('id') == 'ts_date' || $(this).attr('id') == 'move_date') {
            $(this).datepicker({
                maxDate: current_path.indexOf('admin') > -1 ? null : new Date, minDate: new Date(2007, 6, 12),
                beforeShowDay: function (date) {
                    if (date.getDay() == 6) {
                        return [true];
                    } else {
                        return [false];
                    }
                }
            });
        } else {
            $(".datepicker").datepicker();
        }
    });

    $(document.body).on('click', '#register_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 = '/MonitorProfile/';

        var thisValidate = validateUserName(form_values.UserName);

        if (!thisValidate.success) {
            return displayErrorMessage('Username error: ' + thisValidate.err_msg);
        }

        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: 'json',
                async: false,
                success: function (data) {
                    if (data.success) {
                        document.location.href = '/Monitors/';
                    } else {
                        return displayErrorMessage(data.err_msg);
                    }                    
                }
            });
        }
    });

    $(document.body).on('click', '[data-toggle="popover"]', function (e) {
        var e = $(this);
        e.off('hover');
        $.get(e.data('po-action'), function (d) {
            e.popover({ container: 'body', content: d, html: true, placement: 'left', trigger: 'focus' }).popover('show');
        });
    });

    $('body').on('click', function (e) {
        if ($(e.target).data('toggle') !== 'popover'
            && $(e.target).parents('[data-toggle="popover"]').length === 0
            && $(e.target).parents('.popover.in').length === 0) {
            $('[data-toggle="popover"]').popover('hide');
        }
    });

    $(document.body).on('change', '.country-name', function (e) {
        checkCountry();
    });

    $('#send_feedback').click(function (e) {
        e.preventDefault();
        var errors = [];
        var response = grecaptcha.getResponse();

        if (response.length == 0) {
            errors.push('Captcha is invalid.');
        }
        $('div.required input').each(function () {
            var $this = $(this);
            if ($this.val() == '') {
                errors.push($this.attr('id') + ' was required but not filled in.');
            }
        });

        if (errors.length > 0) {
            console.log(errors);
            return displayErrorMessage(errors.join('\n'));
        }
        else {
            $('#feedback_form').submit();
        }

    });

    $('#send_raffle').click(function (e) {
        e.preventDefault();
        var errors = [];
        var response = grecaptcha.getResponse();

        if (response.length == 0) {
            errors.push('Captcha is invalid.');
        }
        $('div.required input').each(function () {
            var $this = $(this);
            if ($this.val() == '') {
                errors.push($this.attr('id') + ' was required but not filled in.');
            }
        });

        if (errors.length > 0) {
            console.log(errors);
            return displayErrorMessage(errors.join('\n'));
        }
        else {
            $('#feedback_form').submit();
        }

    });

    $(document.body).on('click', '#register_sponsor', function (e) {
        e.preventDefault();
        var $this = $(this);

        var $form = $('#sponsor_form form');       
        var form_values = $('#sponsor_form input, #sponsor_form select, #sponsor_form textarea').serializeObject(false, '', true);

        var target = '/SponsorProfile/';

        var thisValidate = validateUserName(form_values.UserName);

        if (!thisValidate.success) {
            return displayErrorMessage('Username error: ' + thisValidate.err_msg);
        }

        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 || $('#sponsor_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: 'json',
                async: false,
                success: function (data) {
                    if (data.success) {
                        document.location.href = '/Sponsors/';
                    } else {
                        return displayErrorMessage(data.err_msg);
                    }
                }
            });
        }

    });

    if ($('#forgot_password').length > 0) {
        $('#forgot_password').click(function (e) { e.preventDefault(); document.location.href = '/LoginForgot/'; });
    }
});

function init() {

    var btn = $.fn.button.noConflict() // reverts $.fn.button to jqueryui btn	

    $.ajaxSetup({
        cache: false
    });

    if (current_path.indexOf('admin') > -1 || current_path.indexOf('sponsors') > -1 || current_path.indexOf('monitors') > -1) {


        $.ajax({
            type: 'POST', url: '/Init', dataType: 'json', async: false, success: function (data) {
                if (data.success) {
                    current_monitor_id = data.monitor_id;
                    current_sponsor_id = data.sponsor_id;
                    current_user_type_id = current_monitor_id > 0 ? current_monitor_id : current_sponsor_id;
                    current_user_name = data.full_name;
                    current_full_name = data.full_name;
                    current_monitor_level = data.status;
                    current_sponsor_status = data.status;
                    current_monitor_type = data.monitor_type;

                    if (current_path.indexOf('monitors') > -1) {
                        $('.nav-main a').each(function () {
                            var $this = $(this);
                            if (current_monitor_type.inList($this.data('permission'))) {
                                $this.removeClass('hidden');
                            }
                        });
                    }
                    loadAdmin();
                }
            }
        });

    }
    if (querystring('need_login') == 1) {
        displayErrorMessage('You are trying to access an area that requires a login.')
    }

    //if ($('.phone-mask').length > 0) {
    //    $('.phone-mask').mask('0000000000');
    //}


}

function jsLogin(data) {
    current_user_id = data.user_id;
    current_user_name = data.user_name;

}

function loadAdmin(admin_type) {
    var this_admintype = '';

    // determine admin type

    if (current_path.indexOf('admin') > -1) {
        this_admintype = 'Admin';
    } else if (current_path.indexOf('sponsors') > -1) {
        this_admintype = 'Sponsors';
        console.log(current_sponsor_status)
        if (current_sponsor_status == 'NonApproved') {
            $('.can-remove').remove();
            $('.can-disable').addClass('disabled');
        }
    } else {
        this_admintype = 'Monitors';
        if (current_monitor_level == 'm1') {
            $('.can-remove').remove();
        }
        else if (current_monitor_level == 'm2') {
            $('.can-remove').remove();
            $('.can-disable').addClass('disabled');
        }
    }  

    current_admin_type = this_admintype; 

    $('.nav-main a').unbind().click(function (e) {
        var $this = $(this);
        if ($this.attr('thisadmin') == 'LogOut') {
            window.location.href = '/LogOut/?login_type=' + this_admintype;
            return false;
        }

        $('.nav-main a').removeClass('active');
        $this.addClass('active');

        if ($this.hasClass('disabled')) {
            return displayErrorMessage('This function is disabled while your profile is under review.');
        }

        if ($this.data('toggle') != 'collapse') {
            changeAdminHeader($this.data('section'), $this.data('glyph'));
            $('#panels_load_content').html(wait_html).show().load($this.attr('thisadmin') + (this_admintype != 'Admin' ? current_user_type_id + '/' : ''), function() {
                current_admin_section = this_admintype + $this.attr('thisadmin').split('/')[2];
                resetAdmin();
                /*if ($this.data('has-paging') == true) {
					ajax_paging(0, 1, 50, $('table:first tbody tr:first').data('rowcount'), $this.data('paging-function'), $('table:first').attr('id'));
				}*/

                if (current_admin_section == 'MonitorsTimesheets' && current_project_id > 0 && $('#Project_List option[value="' + current_project_id + '"]').length > 0) {
                    console.log('yes-' + current_project_id)
                    $('#Project_List').val(current_project_id).change();
                    $("html, body").animate({ scrollTop: 0 }, "slow");
                } else {
                    current_project_id = 0;
                }
                current_count_span = $('#' + $this.attr('id') + ' span.badge');

                if ($('#panels_load_content table:first tbody tr.no-data').length == 0 && current_admin_section != 'MonitorsProjects' && $this.attr('thisadmin').indexOf('/Admin') == -1 && current_count_span.length > 0) {
                    current_count_span.text($('#panels_load_content table:first tbody tr').not('.no-records, .no-data').length);
                }
                if ($this.attr('thisadmin') == '/Admin/Monitors/') {
                    $('#new_monitors_div').html(wait_html).load('/Partial/MonitorsNew/', function(e) {
                        $('#total_results').text($('#monitors_table tbody tr').length);
                    });
                }
                if ($this.attr('thisadmin') == '/Admin/Sponsors/') {
                    $('#new_sponsors_div').html(wait_html).load('/Partial/SponsorsNew/', function(e) {
                        $('#total_results').text($('#sponsors_table tbody tr').length);
                    });
                }
                if ($this.attr('thisadmin') == '/Data/Indication/') {
                    $('#Data_TherapeuticArea').trigger('change');
                }
                if ($this.attr('thisadmin') == '/Reports/HeardAbout/') {
                    $('.heard-row[data-type="s"]').addClass('hidden');
                }
                if ($this.attr('thisadmin') == '/Reports/MonitorLocation/') {
                    $('.location-row[data-type!="r"]').addClass('hidden');
                }
                if ($this.attr('thisadmin') == '/Reports/Timesheets/') {
                    $('#timesheet_end_date').trigger('change');
                }

                if (this_admintype == 'Monitors' && $this.attr('thisadmin') == '/Monitors/Files/') {
                    upload('upload_question');
                }

                //if ($('.phone-mask').length > 0) {
                //    //$('.phone-mask').mask('0000000000');
                //}

            });
            $("html, body").animate({ scrollTop: 0 }, "slow");
        } else {
            $($this.attr('data-target')).collapse('toggle');
            e.stopPropagation();
        }
    });

    if (querystring('section') != '' && $('.nav-main a[thisadmin="/' + current_admin_type + '/' + querystring('section') + '/"]:visible').length > 0) {
        $('.nav-main a[thisadmin="/' + current_admin_type + '/' + querystring('section') + '/"]:visible').trigger('click');
    } 

    //window.scrollTo(0, 0);	
}

function changeAdminHeader(title, glyph) {
    $('#admin_title').text(title);
    if (glyph.indexOf('fa-') > -1) {
        $('#glyph').html('<i class="fa ' + glyph + '"></i>');
    }
    else {
        $('#glyph').html('<span class="glyphicon glyphicon-' + glyph + '"></span>');
    }
}
function monitorStatus(status_cookie) {
    var status_split = status_cookie.split('|');
    var status = status_split[0];
    var ready_to_submit = status_split[1];
    console.log(status_split);

    if (status == "Unapproved" && ready_to_submit == "No") {
        return "m1";
    }
    else if (status == "Unapproved" && ready_to_submit == "Yes") {
        return "m2";
    }
    else if (status == "Approved") {
        return "m3";
    }
    else {
        return "m0";
    }
}
function validateUserName(username) {
    var this_err = new ErrorMessage();
    $.ajax({
        type: 'POST',
        url: '/ValidateUserName/',
        data: JSON.stringify({ username: username }),
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        async: false,
        success: function (data) {
            if (!data.success) {
                this_err = this_err.RecordError(false, data.err_msg);
            }
        }
    });
    return this_err;
}

var ErrorMessage = function () {
    this.success = true;
    this.err_msg = '';

    this.RecordError = function (this_success, this_err_msg) {
        this.success = this_success;
        this.err_msg = this_err_msg;
        return this;
    }

    this.clear = function () {
        this.success = true;
        this.err_msg = '';
    };
};

function resetAdmin() {
    current_monitor_admin_section = '';
    current_monitor_admin_view = '';
    current_sponsor_admin_section = '';
    current_sponsor_admin_view = '';
}

function apiBuild() {
    var this_json = $('#json option:selected').data('json');

    if (this_json != '') {
        $('#results_div').addClass('hidden');
        console.log(this_json);
        //return;

        if (this_json.params) {
            var this_html = [];
            for (var i = 0; i <= this_json.params.length - 1; i++) {
                this_html.push('<div class="form-group" style="margin-right:5px"><input class="form-control form-control-param api-param" id="' + this_json.params[i].name + '" placeholder="' + this_json.params[i].name + ' (' + this_json.params[i].type + ')" title="' + this_json.params[i].name + ' (' + this_json.params[i].type + ')" data-type="' + this_json.params[i].type + '" data-required="' + (this_json.params[i].required != undefined ? this_json.params[i].required : true) + '" value="' + ($('#' + this_json.params[i].name).length == 0 ? '' : $('#' + this_json.params[i].name).val()) + '" /></div>');
            }
            $('#param_div').removeClass('hidden');
            $('#params').html(this_html.join(''));
            $('#api_test').removeClass('hidden');
        }
    }
}

function apiTest() {
    var this_json = $('#json option:selected').data('json');
    var err_msg = [];

    if (!$('#param_div').hasClass('hidden')) {
        $('.api-param').each(function () {
            var $this = $(this);
            var this_type = $this.data('type');
            var this_required = $this.data('required');
            var val = $this.val();
            if (val == '' && this_required) {
                err_msg.push($this.attr('id') + ' is required.');
            }
            switch (this_type) {
                case 'int':
                    if (val != '' && !isNumeric(val)) {
                        err_msg.push($this.attr('id') + ' is incorrect type, ' + this_type + ' is expected.');
                    }
                    break;
                case 'date':
                    if (val != '' && !IsDate(val)) {
                        err_msg.push($this.attr('id') + ' is incorrect type, ' + this_type + ' is expected.');
                    }
                    break;
                default:
                    break;
            }
            this_json[$this.attr('id')] = $this.val();
        });
    }

    if (err_msg.length > 0) {
        alert(err_msg.join('\n'));
        return false;
    }

    console.log(this_json);
    //return;

    $.ajax({
        type: 'POST',
        url: '/api/' + this_json.apicall + '/',
        data: this_json,
        dataType: 'json',
        async: false,
        success: function (data) {
            $('#results_div').removeClass('hidden');
            $('#results').html('<pre class="prettyprint lang-json"><code>' + JSON.stringify(data) + '</code></pre>');
            console.log(data);
            if (!data.success) {
                $('#endpoint').html('<i class="far fa-exclamation-circle"></i> ' + $('#json option:selected').text()).parent().parent().removeClass('alert-success').addClass('alert-danger');
            }
            else {
                $('#endpoint').html('<i class="far fa-check-circle"></i> ' + $('#json option:selected').text()).parent().parent().removeClass('alert-danger').addClass('alert-success');
            }
        }
    });
}

function trainingPopup() {
    window.open("/SiteContent/MFHTimesheets/", "training_popup", 'top=100,left=100,width=759,height=548,scrollbars=no');
}

