/* Minification failed. Returning unminified contents.
(1334,32-33): run-time error JS1195: Expected expression: )
(1334,35-36): run-time error JS1195: Expected expression: >
(1339,14-15): run-time error JS1195: Expected expression: ,
(1340,9-10): run-time error JS1002: Syntax error: }
(1346,27-28): run-time error JS1195: Expected expression: )
(1346,29-30): run-time error JS1004: Expected ';': {
(1352,6-7): run-time error JS1195: Expected expression: )
 */
(function e(t, n, r) {
    function s(o, u) {
        if (!n[o]) {
            if (!t[o]) {
                var a = typeof require == "function" && require;
                if (!u && a) return a(o, !0);
                if (i) return i(o, !0);
                var f = new Error("Cannot find module '" + o + "'");
                throw f.code = "MODULE_NOT_FOUND", f
            }
            var l = n[o] = {
                exports: {}
            };
            t[o][0].call(l.exports, function (e) {
                var n = t[o][1][e];
                return s(n ? n : e)
            }, l, l.exports, e, t, n, r)
        }
        return n[o].exports
    }
    var i = typeof require == "function" && require;
    for (var o = 0; o < r.length; o++) s(r[o]);
    return s
})({
    // this is used on the frequently asked questions page, refactor before removing
    46: [function (require, module, exports) {
        "use strict";
        require("./utilities/customValidationMessages");
        var toggler = require("./utilities/toggler");
        toggler.init()
    }, {
        "./utilities/customValidationMessages": 47,
        "./utilities/toggler": 50,

    }],
    //data-validationmessage used in Save page
    47: [function (require, module, exports) {
        "use strict";
        var handleValidationMessages = function handleValidationMessages(form) {
            var required = [].slice.call(form.querySelectorAll("[required]"));
            var requiredWithMessage = required.filter(function (field) {
                return field.hasAttribute("data-validationmessage")
            });
            required.forEach(function (field) {
                field.oninvalid = function (e) {
                    if (!e.target.validity.valid) {
                        form.classList.add("submitted")
                    }
                }
            });
            requiredWithMessage.forEach(function (field) {
                var validationMessage = field.getAttribute("data-validationmessage");
                field.oninvalid = function (e) {
                    if (!e.target.validity.valid) {
                        e.target.setCustomValidity(validationMessage)
                    }
                };
                field.oninput = function (e) {
                    e.target.setCustomValidity("")
                }
            })
        };
        var init = function init() {
            var pageForms = document.forms;
            for (var i = 0; i < pageForms.length; i++) {
                var form = pageForms[i];
                handleValidationMessages(form)
            }
        };
        init()
    }, {}],
    //js-toggler used on Faq page
    50: [function (require, module, exports) {
        "use strict";
        var toggle = function toggle(e) {
            var $this = $(this);
            var cls = $this.data("togglerclass");
            var target = $this.data("togglertarget");

            // Do not toggle aria-pressed if aria-expanded is present. Doing so will interfere with some SR tech.
            if ($this.attr('aria-expanded') === undefined) {
                var pressed = $this.attr("aria-pressed") === "true" ? "false" : "true";
                $this.attr("aria-pressed", pressed);
            }

            $(target).toggleClass(cls);
            $this.toggleClass("toggle-on");
            e.preventDefault();
            $this.trigger("toggled", this)
        };
        exports.init = function () {
            $("body").on("click", ".js-toggler", toggle)
        }
    }, {}],
    //verify-selector used at Azure/index.cshtml
    51: [function (require, module, exports) {
        "use strict";
        $(document).ready(function () {
            function verifyDropdown() {
                var $verifyContent = $(".vrify-groupe");
                var $verifySelector = $("#verify-selector");
                $verifyContent.hide();
                $verifySelector.on("change", function (e) {
                    var $verifyTarget = $("#" + $(this).val()).show();
                    $verifyContent.not($verifyTarget).hide()
                });
            } verifyDropdown()
        })
    }, {}]
}, {}, [46]);

$(function () {
    function multiOrderedList2(aList, currentPrefix) {
        if (currentPrefix == null) {
            currentPrefix = '';
        }
        else {
            currentPrefix += ".";
        }
        aList.children('li').each(function (index, element) {
            var counter = index + 1;
            var anItem = $(element);
            var newPrefix = currentPrefix + '<ol class="noproc"><li value="' + counter + '"></li></ol>';
            anItem.prepend(newPrefix + '. ');
            //This commented block doesn't work in IE.
            //anItem.children('ol:not(.noproc)').each(function (index, childOl)
            //{
            //	multiOrderedList($(childOl), newPrefix);
            //});
            $.each(anItem.children('ol:not(.noproc)'), function (index, childOl) {
                multiOrderedList($(childOl), newPrefix);
            });
        });
    }

    function multiOrderedList(aList, currentPrefix) {
        if (currentPrefix == null) {
            currentPrefix = '';
        }
        else {
            currentPrefix += ".";
        }
        aList.children('li').each(function (index, element) {
            var counter = index + 1;
            var anItem = $(element);
            var newPrefix = currentPrefix + counter;
            anItem.prepend('<span class="multilevel-counter">' + newPrefix + '. ' + '</span>');
            //This commented block doesn't work in IE.
            //anItem.children('ol:not(.multilevel-skip)').each(function (index, childOl)
            //{
            //	multiOrderedList($(childOl), newPrefix);
            //});
            $.each(anItem.children('ol:not(.multilevel-skip)'), function (index, childOl) {
                multiOrderedList($(childOl), newPrefix);
            });
        });
    }

    $('.data-table-src.responsive:not(.js-ignore)').each(function () {
        var CurrentChain = $(this);
        var containsGroups = CurrentChain.hasClass('grouped');
        var toggleCellIndex = containsGroups ? 1 : 0;
        CurrentChain.DataTable(
            {
                bFilter: false
                , bInfo: false
                , paging: false
                , ordering: false
                //, sDom: 't'
                //, fixedHeader: true
                //, fixedColumns: true
                //, scrollX: true
                //, scrollY: '300px'
                //, scrollCollapse: true
                //, sScrollXInner: '100%'
                , createdRow: function (row, data, index) {
                    //$('td', row).attr('tabindex', 0);
                    $('td:nth(' + toggleCellIndex + ')', row).toggleClass('responsive-details-toggle fa-plus').attr('tabindex', 0).keydown(function (e) {
                        if (e.which == 13 || e.which == 32) {//Enter key pressed
                            $(e.currentTarget).click();
                            return false;
                        }
                    });

                    //  $(row).children('.details-control').attr('tabindex', 0).keydown(function (e) {
                    //    if (e.which == 13 || e.which == 32) {//Enter key pressed
                    //        $(e.currentTarget).click();
                    //    }
                    //});
                }
                , responsive: {
                    details: {
                        renderer: function (api, rowIdx, columns) {
                            var data = $.map(columns, function (col, i) {
                                return col.hidden && col.data ?
                                    '<li data-dtr-index="' + col.columnIndex + '" data-dt-row="' + col.rowIndex + '" data-dt-column="' + col.columnIndex + '">' +
                                    '<span class="dtr-title">' + col.title + (col.title ? ':' : '') + '</span> <span class="dtr-data">' + col.data + '</span>' +
                                    '</li>' :
                                    '';
                            }).join('');
                            return data ? $('<ul data-dtr-index="' + rowIdx + '"/>').append(data) : false;
                        }
                    }
                }
                , drawCallback: function (settings) {
                    if (containsGroups) {
                        var api = this.api(), rows = api.rows({ page: 'current' }).nodes(), last = null;
                        api.columns(0).visible(false);
                        api.column(0, { page: 'current' }).data().each(function (group, i) {
                            var $aRow = $(rows).eq(i);
                            if (last !== group) {
                                $aRow.before('<tr class="group-header"><td class="hidden-element"></td><td colspan="' + $aRow.children().length + '">' + group + '</td></tr>');
                                last = group;
                            }
                        });
                    }
                }
            });


    });

    // table.responsive used in contact cshtml
    $('table.responsive .dtr-data').each(function () {
        var currentInstance = $(this);

        if (currentInstance.text() == '') {
            currentInstance.closest('li').hide();
        }
    });

    //  When user clicks on a collapsable tab, set aria attributes correctly.
    $('button.m-drawer').click(function (e) {
        var $this = $(this);
        var isExpanding = $this.attr('aria-expanded') == 'true' ? 'false' : 'true';
        var isHidden = $this.attr('aria-expanded') == 'true' ? 'true' : 'false';
        $this.attr('aria-expanded', isExpanding);
        var targetSelector = $this.data('togglertarget');
        if (targetSelector !== undefined) {
            $(targetSelector).attr({
                'aria-hidden': isHidden,
                'tabindex': -1
            }).css('outline', '0')
        }
    });

});

function customDateTimeFormatter(date, locale) {
    var newDate = new Date(date);
    var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    if (typeof (window.LocalizationResources) != undefined) {
        try {
            days[0] = window.LocalizationResources['day_sun'];
            days[1] = window.LocalizationResources['day_mon'];
            days[2] = window.LocalizationResources['day_tue'];
            days[3] = window.LocalizationResources['day_wed'];
            days[4] = window.LocalizationResources['day_thu'];
            days[5] = window.LocalizationResources['day_fri'];
            days[6] = window.LocalizationResources['day_sat'];
            months[0] = window.LocalizationResources['month_jan'];
            months[1] = window.LocalizationResources['month_feb'];
            months[2] = window.LocalizationResources['month_mar'];
            months[3] = window.LocalizationResources['month_apr'];
            months[4] = window.LocalizationResources['month_may'];
            months[5] = window.LocalizationResources['month_jun'];
            months[6] = window.LocalizationResources['month_jul'];
            months[7] = window.LocalizationResources['month_aug'];
            months[8] = window.LocalizationResources['month_sep'];
            months[9] = window.LocalizationResources['month_oct'];
            months[10] = window.LocalizationResources['month_nov'];
            months[11] = window.LocalizationResources['month_dec'];
        }
        catch (e) {

        }
    }
    var hours = newDate.getHours();
    var minutes = newDate.getMinutes();
    var ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12;
    hours = hours ? hours : 12;
    minutes = minutes < 10 ? '0' + minutes : minutes;
    hours = hours < 10 ? '0' + hours : hours;
    return days[newDate.getDay()] + ', ' + newDate.getDate() + ' ' + months[newDate.getMonth()] + ' ' + newDate.getFullYear() + ' ' + hours + ':' + minutes + ' ' + ampm.toUpperCase();
}


var matchHeightRatioTimeout;
$(document).ready(function (e) { doMatchHeightResizes(); });
$(window).resize(function (e) {
    if (!!matchHeightRatioTimeout) {
        clearTimeout(matchHeightRatioTimeout);
    }
    matchHeightRatioTimeout = setTimeout(doMatchHeightResizes(), 200);
});

//data-match-height-with used in account page
function doMatchHeightResizes() {
    $('*[data-match-height-with]').each(function (i, e) {
        var targetSelector = $(e).data('match-height-with');
        var $et = $('#' + targetSelector);
        var height = $et.height();
        // Responsive elements only need to share same height if they are on the same horizontal level.
        if ($et.position().top == $(e).position().top) {
            $(e).css('min-height', height);
        } else {
            $(e).css('min-height', '');
        }
    });
}


var aspectRatioTimeout;
$(document).ready(function (e) { doAspectRatio(); });
$(window).resize(function (e) {
    if (!!aspectRatioTimeout) {
        clearTimeout(aspectRatioTimeout);
    }
    aspectRatioTimeout = setTimeout(doAspectRatio(), 200);
});

function doAspectRatio() {
    $('*[data-aspect-ratio]').each(function (i, e) {
        var ratio = $(e).attr('data-aspect-ratio');
        var parts = ratio.split(':');
        if (parts.length == 2) {
            var width = $(e).width();
            var height = width * parts[1] / parts[0];
            $(e).css('min-height', height);
            if ($(e).is("iframe")) {
                $(e).attr('height', height);
            }
        }
    });
}

/* MWF dropdown fix to apply selectRequired class to required form fields */
$(document).ready(function () {

    $(document).on('click', '.c-select button', function (e) {
        let divAriaLabel = $(e.target.parentElement).attr('data-default-aria-label');
        let labelId = $(e.target.parentElement.parentElement.parentElement).find('label').attr('id');
        let ulElement = $(e.target.nextElementSibling);

        if (labelId) {
            ulElement.attr('aria-labelledby', labelId);
        } else {
            ulElement.attr('aria-label', divAriaLabel);
        }
    });

    $(document).on('change', '.c-select select', function (e) {
        let nDisplay = $(e.target).find('[selected]').text();
        $(e.target).parent().find('button').attr('aria-label', nDisplay);
    });


    var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

    var observeFilter = { childList: true };
    var dropdownObserver = new MutationObserver(function (mutationRecords) {
        $.each(mutationRecords, function (index, mutationRecord) {
            if (mutationRecord.addedNodes.length > 0) {
                let nDisplay = $(mutationRecord.target).find('[selected]').text();

                // Prevent wacky behavior on "enter" on other inputs that are part of the same form.
                $(mutationRecord.target).find('button').first()
                    .attr('type', 'button')
                    .attr('aria-label', nDisplay);
                //$(mutationRecord.target).find('[data-default-aria-labelledby]').each(function (k, v) {
                //    $(v).find('button').attr('aria-labelledby', $(v).attr('data-default-aria-labelledby'));
                //});
            }
        });
    });

    $('.c-select').each(function () {
        dropdownObserver.observe(this, observeFilter);
        $(this).children('select').attr('tabindex', '-1');

        if ($(this).children('select').attr('required')) {
            $(this).children('select').on('change', function () {
                $(this).valid();
            });
            $(this).children('select').addClass('selectRequired');
        }
    });
});

/* add MWF select support to jquery Validate */
jQuery.validator.addMethod("selectRequired", function (val, element) {
    if (this.optional(element)) return true;
    var control = $(element).parent().children('.c-select-menu');
    var control_text = control.children('button').text();
    var val_text = $(element).children("option:selected").text();
    if (control_text.trim() != val_text.trim()) return false; // IF Control text does not match selected value, user has not changed it!
    return true;
}, function (val, element) {
    return $(element).data('validationmessage');
});
jQuery.validator.addClassRules("selectRequired", {
    selectRequired: true
});


// Custom error message validator so if you wanted to add an error message anywhere, 
// you can do so with $(elem).addClass('customErrorMessage') $(element).attr('data-error-msg', 'Your error message')
jQuery.validator.addMethod("customErrorMessage", function (val, element) {
    var msg = $(element).attr('data-error-msg');
    if (msg != null && msg != "") {
        return false;
    }
    return true;
}, function (val, element) {
    return $(element).attr('data-error-msg');
});
jQuery.validator.addClassRules('customErrorMessage', {
    customErrorMessage: true
});


// string format polyfill
if (!String.prototype.format) {
    String.prototype.format = function () {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function (match, number) {
            return typeof args[number] != 'undefined'
                ? args[number]
                : match;
        });
    };
};

var dataJsHref = {
    target: null,
    origX: -1,
    origY: -1
};

$(document).on('mousedown', '*[data-js-href]', function (e) {
    dataJsHref.origX = e.clientX;
    dataJsHref.origY = e.clientY;
    dataJsHref.target = e.target;
    if (e.button == 1) {
        if ($(e.target).closest('[data-js-href]').length > 0) {
            if ($(e.target).is(':not(button,a)')) {
                e.preventDefault();
                return false;
            }
        }
    }
});

// Enable middle click + click behavior for items within the data-js-href box.
$(document).on('mouseup', '*[data-js-href]', function (e) {
    if ($(e.target).not('a,button')) {
        if (e.target === dataJsHref.target) {
            if ((Math.max(e.clientX, dataJsHref.origX) - Math.min(e.clientX, dataJsHref.origX)) < 3) {
                if ((Math.max(e.clientY, dataJsHref.origY) - Math.min(e.clientY, dataJsHref.origY)) < 3) {
                    var elem = $(e.target).closest('[data-js-href]');
                    if (!!elem) {
                        var isMiddleClick = e.button === 1 || e.ctrlKey === true;
                        var href = $(elem).attr('data-js-href');
                        if (isMiddleClick) {
                            window.open(href)
                            e.stopPropagation();
                            return false;
                        } else {
                            window.location = href;
                            e.stopPropagation();
                        }
                    }
                }
            }
        }
    }
});;
// Account profile picture control
$(function () {
    setMSAProfilePictureControls();
});
function setMSAProfilePictureControls() {
    var defaultProfilePicture = 'https://mem.gfx.ms/me/MeControl/9.18199.0/msa_enabled.png';
    $('.profile-picture-control img').attr('src', defaultProfilePicture);
    if ($('.profile-picture-control').length > 0) { // profile pic control on page
        if ($('.msame_Header').length > 0) { // user's profile pic also on page (uhf)
            if ($('.msame_Drop_AI_picframe img').length > 0) {
                var profilePic = $('.msame_Drop_AI_picframe img').attr('src');
                if (profilePic == null || profilePic == "") profilePic = defaultProfilePicture; // Default pic
                $('.profile-picture-control img').attr('src', profilePic);
            } else {
                setTimeout(setProfilePictureControls, 2000);
            }
        }
    }
};

// On resize
window.onResizeActions = [];
$(window).ready(resizeCallback);
$(window).resize(resizeCallback);
var resizeTimeoutId = null;
function resizeCallback() {
    if (resizeTimeoutId)
        window.clearTimeout(resizeTimeoutId);
    resizeTimeoutId = window.setTimeout(window.doResizeActions, 5);
}
window.doResizeActions = function () {
    for (var rai = 0; rai < window.onResizeActions.length; rai++) {
        window.onResizeActions[rai]();
    }
};
window.onResize = function (func) {
    window.onResizeActions.push(func);
}

// Fixed navbar
$(window).ready(function () {
    var navContainer = $('#divMainContent');
    var nav = $(navContainer).find('.fixed-bar');

    if (nav.length == 0) return;

    // When the fixed starts
    var fixedNavStartOffset = 0;
    var fixedNavStartPos;

    // When the fixed stops
    var fixedNavEnd = $('.social-footer');
    var fixedNavEndOffset = 0;
    var fixedNavEndPos;

    // Measurements for position calcs
    var navHeight;
    var navPos;
    var fixedNavEndPos;
    recalculatePositions();

    window.onResize(function () {
        var navContainer = $('#divMainContent');
        var nav = $(navContainer).find('.fixed-bar');
        if (nav.length == 0) return;
        if ($(nav).css('position') == 'fixed') {
            $(window).scroll();
        }
    });

    function recalculatePositions() {
        // Start position
        fixedNavStartPos = $(navContainer).offset().top + fixedNavStartOffset;

        // End position
        fixedNavEndPos = $(fixedNavEnd).offset().top + fixedNavEndOffset;

        // Fixed nav position based on parent block elements
        navPos = $(navContainer).offset();
        navPos.left = navPos.left + parseInt($(navContainer).css('paddingLeft'), 0);

        // Nav height for end zone calc
        navheight = $(nav).outerHeight();
    }

    $(window).on('scroll', function () {
        recalculatePositions();

        if (window.innerWidth <= 768 || $(nav).hasClass('disabled')) {
            $(nav).removeClass('f-sticky');
            $(navContainer).css('padding-bottom', 0);
            $(navContainer).css('padding-top', 0);
        } else {
            if (window.innerWidth <= 768) {
                $(nav).removeClass('f-sticky');
                $(navContainer).css('padding-bottom', 0);
                $(navContainer).css('padding-top', 0);
            }
            else {
                if ($(window).scrollTop() + navheight > fixedNavEndPos) { // Nav is stuck to bottom of page
                    $(nav).removeClass('f-sticky');
                    $(nav).css('position', 'absolute');
                    $(nav).css('bottom', '0');
                    $(nav).css('left', '0');
                    $(nav).css('right', '0');
                    $(navContainer).css('padding-bottom', navheight + 'px');
                }
                else if ($(window).scrollTop() > fixedNavStartPos) { // Nav is fixed to scroll
                    $(nav).addClass('f-sticky');
                    $(nav).css('left', navPos.left);
                    $(nav).css('position', '');
                    $(nav).css('bottom', '');
                    $(navContainer).css('padding-top', navheight + 'px');
                }
                else { // Nav is in default position
                    $(nav).removeClass('f-sticky');
                    $(nav).css('left', '');
                    $(nav).css('position', '');
                    $(nav).css('bottom', '');
                    $(navContainer).css('padding-top', '0');
                }
            }
        }

    });
});


// Textarea character counter
$(function () {
    var loc_CharactersRemaining = (typeof (window.LocalizationResources) !== "undefined" && typeof (window.LocalizationResources['CharactersRemaining']) !== "undefined") ? window.LocalizationResources['CharactersRemaining'] : 'characters remaining.';

    $('textarea[data-val-length-max]').each(function (k, v) {
        var maxlength = $(this).attr('data-val-length-max');
        var name = $(v).attr('name');

        $(v).attr('aria-describedby', name + '-char-counter');
        $(v).attr('maxlength', $(v).attr('data-val-length-max'));

        var counterDiv = $('<span/>', {
            'id': name + '-char-counter',
            'class': 'char-counter c-caption-2',
            'aria-live': 'polite'
        }).append($('<span/>', {
            'id': name + '-char-count',
            'text': maxlength
        }), ' ' + loc_CharactersRemaining);
        $(v).parent('.c-textarea').append(counterDiv);
        $(v).on('change keyup paste', function (e) {
            var charsRemaining = $(e.target.parentElement).find('span > span');
            var maxlength = $(this).attr('data-val-length-max');
            if (maxlength != null) {
                var count = maxlength - $(this).val().length;
                charsRemaining.text(count);

            }
        });
        $(v).change();
    });
});

// "Read more" control
$(function () {
    window.ReadMoreControl = function () {
        var loc_readmore = (typeof (window.LocalizationResources) !== "undefined" && typeof (window.LocalizationResources['ReadMore']) !== "undefined") ? window.LocalizationResources['ReadMore'] : 'Read more';
        var loc_readless = (typeof (window.LocalizationResources) !== "undefined" && typeof (window.LocalizationResources['ReadLess']) !== "undefined") ? window.LocalizationResources['ReadLess'] : 'Read less';

        $('[data-readmore]').each(function (k, v) {
            var content = $(this).text();
            var maxLength = $(this).attr('data-readmore');
            var contentLength = content.length;
            if (contentLength > maxLength) {
                var aboveFold = content.substr(0, maxLength);
                var belowFold = content.substr(maxLength, contentLength);
                $(this).text(aboveFold).append('<span class="read-more-ellipsis">…</span><br class="read-more-break"/>');

                var hiddenContent = $('<span>').text(belowFold).hide();
                var readMoreLink = $('<a href="#" class="x-type-right c-hyperlink c-caption-1 readMoreLink" role="button" style="display:block;"></a>').text(loc_readmore);
                $(readMoreLink).click(function (e) {
                    e.preventDefault();
                    if ($(this).prev('span').is(':visible')) {
                        $(this).parent().find('.read-more-ellipsis').show();
                        $(this).parent().find('.read-more-break').show();
                        $(this).prev('span').hide();
                        $(this).text(loc_readmore);
                        if ($(this).parents('.block-item').length > 0) {
                            $(this).parents('.block-item').css('height', '');
                        }
                    } else {
                        $(this).parent().find('.read-more-ellipsis').hide();
                        $(this).parent().find('.read-more-break').hide();
                        $(this).prev('span').show();
                        $(this).text(loc_readless);
                        if ($(this).parents('.block-item').length > 0) {
                            var prevHeight = $(this).parents('.block-item').innerHeight;
                            $(this).parents('.block-item').css('height', 'auto');
                            $(this).parents('.block-item').attr('data-prevheight', prevHeight);
                        }
                    }
                });
                $(this).append(hiddenContent);
                $(this).append(readMoreLink);
            }
        });
    }
    window.ReadMoreControl();
});

//wrapBox.on('mousewheel DOMMouseScroll', function (e) {
//    console.log('I scrolled');
//})

// image upload control
// Use with the ImageUploadControl partial
$(function () {
    // crop variables
    let result = document.querySelector('.result');
    let img_result = document.querySelector('.img-result');
    let saveCrop = document.querySelector('.saveCrop');
    let cropped = document.querySelector('.cropped');
    let cancelCrop = document.querySelector('.cancelCrop');
    let cropper = '';
    let cropBtn = document.querySelector('#confirmCrop');

    if ($('#confirmCrop').length) {

        // when crop button is clicked
        cropBtn.addEventListener('click', function (e) {
            //let cropperCanvas = document.querySelector('.cropper-canvas');
            //console.log(cropperCanvas);
            let img_og = $(this).siblings('section.image-upload-control').find('.OgImg');
            // if cropped image preview exists
            if (cropBtn.dataset.uploadReady == 'true') {

                // begin upload process
                let imgBlob = dataURItoBlob(cropped.src);
                var form = $(this).parent();
                ImageUpload_progressStart(form);
                var useAjax = $('.image-upload-control input[name="ajax"]').val();
                if (useAjax != 'true') {
                    document.getElementsByName("cropFile").value = "";
                    document.getElementsByName("cropFile")[0].setAttribute("value", cropped.src);
                    ImageUpload_progressEnd(form);
                } else {
                    // Generate payload
                    var formData = new FormData();
                    formData.append("type", $(this).siblings("section.image-upload-control").find("input[name='type']").val());
                    formData.append("uniqueId", $(this).siblings("section.image-upload-control").find("input[name='uniqueId']").val());
                    formData.append("index", "0");
                    formData.append("fileUpload", imgBlob, $(this).parent().children('[type="file"]').val());
                    formData.append("__RequestVerificationToken", $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val());
                    var ident = $('.image-upload-control input[name="type"]').val() + '_' + $('.image-upload-control input[name="uniqueId"]').val() + '_' + '0';

                    // Call image upload endpoint
                    $.ajax({
                        url: '/Image/Upload',
                        data: formData,
                        type: 'POST',
                        processData: false,
                        contentType: false,
                        cache: false,
                        async: true,
                        success: function (e) {
                            if (e.success == null || e.success != true) {
                                alert('Error uploading image. Please contact support.');
                                $('#image_upload_result_' + ident).text('Unknown error uploading image. Please contact support.');

                                $(form).children('.progress-overlay').hide();
                                $(form).children('a').show();
                            } else if (e.success == false) {
                                alert(e.error);
                                $('#image_upload_result_' + ident).text(e.error);

                                $(form).children('.progress-overlay').hide();
                                $(form).children('a').show();
                            } else {
                                var newUrl = e.url; // Refresh the image with new URL, try to break cache.
                                $(form).children('img').attr('src', '');
                                if (e.url.indexOf('?') != -1) {
                                    newUrl += '&timestamp=' + Math.random();
                                }
                                else {
                                    newUrl += '?timestamp=' + Math.random();
                                }

                                $(form).children('img').attr('src', newUrl);

                                $(form).children('[name="length"]').val(e.length);

                                ImageUpload_progressEnd(form);

                                // This is for the gallery file upload. The "new" upload needs to be copied for the new index.
                                if ($(form).hasClass('new-file-upload')) {
                                    makeNewUploadForm(form);
                                }
                            }
                        },
                        error: function (e) {
                            console.log(e);
                            ImageUpload_progressEnd(form);
                            alert('Unknown error uploading image. Please contact support.');
                            $('#image_upload_result_' + ident).text('Unknown error uploading image. Please contact support.');
                        }
                    });
                }

                // replace original image with the cropped result
                img_og.attr('src', cropped.src);
                $(this).parent().find("section.image-upload-control").show();
                $(this).parent().find("section#cropUpload").hide();
                $(this).text(window.LocalizationResources['Team_Manage_CroptPhoto']);
                cropBtn.dataset.uploadReady = 'false';
            } else {
                $(this).parent().find("section.image-upload-control").hide();
                $(this).parent().find("section#cropUpload").show();
                // checks if image element is empty, if not, then init cropper with the image src.
                if (img_og.attr('src') != "") {

                    if (cropped.src) {
                        $(".cropped").attr("src", "");
                    }
                    // create new image
                    let img = document.createElement('img');
                    img.id = 'image';
                    img.src = img_og.attr('src');
                    // clean result before
                    result.innerHTML = '';
                    // append new image
                    result.appendChild(img);
                    // show save btn and options
                    saveCrop.classList.remove('hide');
                    // init cropper
                    // new requirements for images cropping and uploads
                    cropper = new Cropper(img, {
                        zoomable: false,
                        aspectRatio: 16 / 9, minWidth: 800, minHeight: 450, viewMode: 1, cropmove: function (event) {
                            var data = cropper.getData();
                            if (data.width < 200) {
                                if (typeof (event) !== 'undefined') {
                                    event.preventDefault();
                                    data.width = 200;
                                    cropper.setData(data);
                                }
                            }
                            if (data.height < 200) {
                                if (typeof (event) !== 'undefined') {
                                    event.preventDefault();
                                    data.height = 200;
                                    cropper.setData(data);
                                }
                            }
                        }
                    });

                    cropper.options.cropmove();

                    // hide upload btn
                    $(this).hide();
                }
                $(this).text(window.LocalizationResources['Team_Manage_SaveCrop']);
                cropBtn.dataset.uploadReady = 'true';
                if ($('.saveCrop').html() != window.LocalizationResources['Content_Preview_for']) {
                    $('.saveCrop').html(window.LocalizationResources['Content_Preview_for']);
                }
            }
        });

        cropBtn.addEventListener("keyup", function (event) {
            event.preventDefault();
            if (event.keyCode === 13) {
                document.getElementById("confirmCrop").click();
            }
        });

        // click "cancel" button
        if ($('.cancelCrop').length) {
            cancelCrop.addEventListener('click', function (e) {
                if (cropBtn.dataset.uploadReady == 'true') {
                    e.preventDefault();
                    // delete variables
                    $(".cropped").attr("src", "");
                    $(".result").empty();
                    $(this).parent().parent().hide();
                    $(this).parent().parent().siblings('section.image-upload-control').show();
                    $(this).parent().parent().parent().find('#confirmCrop').show();
                    $('#confirmCrop').text(window.LocalizationResources['Team_Manage_CroptPhoto']);
                    cropBtn.dataset.uploadReady = 'false';
                }
            });
        }

        // save on click
        if ($('.saveCrop').length) {
            saveCrop.addEventListener('click', function (e) {
                e.preventDefault();
                // get result to data uri

                var imgType = $(this).parent().parent().parent().find('input[type="file"]').attr('data-filetype');
                let imgSrc = cropper.getCroppedCanvas({
                    //updated photo requirements 4/2020
                    aspectRatio: 16 / 9,
                    minWidth: 800,
                    minHeight: 450,
                }).toDataURL(imgType);

                // remove hide class of img
                cropped.classList.remove('hide');
                img_result.classList.remove('hide');
                // show image cropped
                cropped.src = imgSrc;
                cancelCrop.classList.remove('hide');
                $(this).parent().parent().siblings('a#confirmCrop').show();
            });
        }
    }


    var progressAriaStart = "Your image has been uploaded.";
    if (typeof (window.LocalizationResources) !== "undefined" && typeof (window.LocalizationResources['ImageUpload_ProgressStart']) !== 'undefined' && window.LocalizationResources['ImageUpload_ProgressStart'].length > 0) {
        progressAriaStart = window.LocalizationResources['ImageUpload_ProgressStart'];
    }
    var progressAriaEnd = "Your image is being uploaded.";
    if (typeof (window.LocalizationResources) !== "undefined" && typeof (window.LocalizationResources['ImageUpload_ProgressEnd']) !== 'undefined' && window.LocalizationResources['ImageUpload_ProgressEnd'].length > 0) {
        progressAriaEnd = window.LocalizationResources['ImageUpload_ProgressEnd'];
    }

    // Hide/show progress functions
    function ImageUpload_progressStart(form) {

        $(form).children('.progress-overlay').children('.c-progress').attr('aria-label', progressAriaStart);
        $(form).children('.progress-overlay').show();
        $(form).children('a').hide();
        setTimeout(function () {
            ImageUpload_progressEnd(form);
        }, 30000);
        $(form).children('.progress-overlay').find('.c-progress').focus();
    }

    // dataURI to blob
    function dataURItoBlob(dataURI) {
        // convert base64 to raw binary data held in a string
        // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
        var byteString = atob(dataURI.split(',')[1]);

        // separate out the mime component
        var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

        // write the bytes of the string to an ArrayBuffer
        var ab = new ArrayBuffer(byteString.length);

        // create a view into the buffer
        var ia = new Uint8Array(ab);

        // set the bytes of the buffer to the correct values
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }

        // write the ArrayBuffer to a blob, and you're done
        var blob = new Blob([ab], { type: mimeString });
        return blob;
    }

    function ImageUpload_progressEnd(form) {
        $(form).children('.progress-overlay').children('.c-progress').attr('aria-label', progressAriaEnd);
        $(form).children('.progress-overlay').hide();
        $(form).children('a').show();
        if (document.activeElement == null || document.activeElement.tagName == "BODY") {
            $(form).children('a').focus();
        }
    }

    // While the image is loading, show the progress. Once loaded, hide.
    function ImageUpload_bindLoadComplete() {
        $('.image-upload-control img').each(function (k, v) { // Hide progress, show actions when image has loaded (or failed to load)
            $(this).get(0).onload = function () {
                //ImageUpload_progressEnd($(this).parent());
            };

            $(this).get(0).onerror = function () {
                //ImageUpload_progressEnd($(this).parent());
            };
        });
    }

    // anchor click event for the actions
    function ImageUpload_bindActionClick() {
        $('.image-upload-control a').off('click');
        $('.image-upload-control a').on('click', function (e) {
            e.preventDefault();
            var ident = $(this).parent().children('[name="type"]').val() + '_' + $(this).parent().children('[name="uniqueId"]').val() + '_' + $(this).parent().children('[name="index"]').val();
            var length = $(this).parent().children('[name="length"]').val();
            var replaceable = $(this).parent().children('[name="replaceable"]').val();
            var actionremove = $(this).parent().children('[name="remove"]').val();
            var useAjax = $(this).parent().children('[name="ajax"]').val();

            if (useAjax == "false") {
                // If ajax is set to false we're just holding the image to be uploaded on POST
                if (parseInt(length) > 0 && replaceable == "false") {
                    // Remove image that is set
                    $('#image_upload_' + ident).parent().remove();
                }
                else {
                    $(this).parent().children('input[type="file"]').trigger('click');
                }
            }
            else {
                // If ajax is true or unset we use the image data to upload to the image server
                /* if (parseInt(length) > 0 && actionremove)
                 {
                     // Begin delete process
                     $(this).parent().children('.progress-overlay').show();
                     $(this).parent().children('.progress-overlay').find('.c-progress').focus();
                     var formData = new FormData();
                     formData.append("type", $(this).parent().children('[name="type"]').val());
                     formData.append("uniqueId", $(this).parent().children('[name="uniqueId"]').val());
                     formData.append("index", $(this).parent().children('[name="index"]').val());
                     formData.append("__RequestVerificationToken", $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val());
 
                     $.ajax({
                         url: '/Image/DeleteImage/',
                         data: AntiForgeryHelper.Wrap(formData),
                         type: 'POST',
                         processData: false,
                         contentType: false,
                         cache: false,
                         async: true,
                         success: function (e) {
                             if (typeof (e) !== undefined && e.success == true) {
                                 $('#image_upload_' + ident).parent().remove();
                             } else {
                                 alert(e.error);
                                 $('#image_upload_result_' + ident).html(e.error);
                             }
                             ImageUpload_progressEnd($(this).parent());
                         },
                         error: function (e) {
                             ImageUpload_progressEnd($(this).parent());
                         }
                     });
                 }
                 else { */
                // Image is not uploaded or can be replaced, let user chose new file.
                $(this).parent().children('input[type="file"]').trigger('click');
                //}
            }
        });
    }

    // When file input is changed, begin upload process.
    function ImageUpload_bindInputChange() {

        $('.image-upload-control input[type="file"]').off('change');
        $('.image-upload-control input[type="file"]').on('change', function () {
            var form = $(this).parent();
            var ident = $(this).parent().children('[name="type"]').val() + '_' + $(this).parent().children('[name="uniqueId"]').val() + '_' + $(this).parent().children('[name="index"]').val();
            var inputType = $(this).parent().children('[name="type"]').val();

            if (this.files.length > 0) {
                ImageUpload_progressStart(form);
                var useAjax = $(this).parent().children('[name="ajax"]').val();
                $(form).children('input[type="file"]').attr('data-filetype', this.files[0].type);

                var isValidDimensions = true;
                var reader = new FileReader();
                reader.readAsDataURL(this.files[0]);
                reader.onload = function (e) {

                    var image = new Image();
                    image.src = e.target.result;
                    image.onload = function () {
                        var height = this.height;
                        var width = this.width;

                        if (inputType === 'TeamProfile') {
                            if (height > 10000 || width > 10000 || width < 800 || height < 450) {
                                isValidDimensions = false;
                            }

                            if (!isValidDimensions) {
                                ImageUpload_progressEnd(form);
                                $('#image_upload_result_' + ident).text(window.LocalizationResources["Team_Manage_Upload_Fail"]);
                                return;
                            }
                        }

                        if (useAjax == "false") {
                            var reader = new FileReader();
                            reader.onload = function (e) {
                                if ($(form).hasClass('new-file-upload')) {
                                    makeNewUploadForm(form);
                                }
                                $(form).children('img').attr('src', e.target.result);
                                ImageUpload_progressEnd(form);
                                $(form).children('a').text('Click to change photo');
                                $(form).children('[name="length"]').val($(form).children('[type="file"]').get(0).files[0].size);
                            };
                            reader.readAsDataURL(this.files[0]);
                            ImageUpload_progressEnd(form);
                            $('#confirmCrop').show();
                        } else {
                            var formData = new FormData();
                            formData.append("type", $(form).children('[name="type"]').val());
                            formData.append("uniqueId", $(form).children('[name="uniqueId"]').val());
                            formData.append("index", $(form).children('[name="index"]').val());
                            formData.append("fileUpload", $(form).children('[type="file"]').get(0).files[0], $(form).children('[type="file"]').val());
                            formData.append("__RequestVerificationToken", $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val());

                            // Call image upload endpoint
                            $.ajax({
                                url: '/Image/Upload',
                                data: formData,
                                type: 'POST',
                                processData: false,
                                contentType: false,
                                cache: false,
                                async: true,
                                success: function (e) {
                                    if (!e.success) {
                                        alert(e.error || 'Error uploading image. Please contact support.');
                                        $('#image_upload_result_' + ident).text(e.error || 'Unknown error uploading image. Please contact support.');
                                        $(form).children('.progress-overlay').hide();
                                        $(form).children('a').show();
                                    } else {
                                        var newUrl = e.url;
                                        newUrl += (newUrl.indexOf('?') != -1 ? '&' : '?') + 'timestamp=' + Math.random();

                                        // Update the image src
                                        $(form).children('img').attr('src', newUrl);

                                        $(form).children('[name="length"]').val(e.length);

                                        ImageUpload_progressEnd(form);

                                        if ($(form).hasClass('new-file-upload')) {
                                            makeNewUploadForm(form);
                                        }

                                        $(form).parent().find('#confirmCrop').show();
                                    }
                                },
                                error: function (e) {
                                    console.log(e);
                                    ImageUpload_progressEnd(form);
                                    alert('Unknown error uploading image. Please contact support.');
                                    $('#image_upload_result_' + ident).text('Unknown error uploading image. Please contact support.');
                                }
                            });
                        }
                    }
                }
            }
        });
    }

    function makeNewUploadForm(form) {
        var gallery = $(form).parent();
        var newForm = $(form).clone(false, false);
        var oldId = $(newForm).children('input[type="file"]').attr('id');
        var pieces = oldId.split('_');
        var newIndex = parseInt(pieces.pop()) + 1;
        var newVal = pieces.join('_') + "_" + newIndex;
        $(form).removeClass('new-file-upload');
        $(form).children('a').removeClass('glyph-add');
        $(form).children('a').addClass('glyph-remove');
        $(form).children('a').text('Click to remove photo');
        $(newForm).children('input[type="file"]').attr('id', newVal);
        $(newForm).children('input[type="file"]').val('');
        $(newForm).children('input[name="index"]').val(newIndex);
        $(newForm).children('input[name="length"]').val('0');
        $(newForm).children('img').attr('src', '/Image/' + pieces[2] + '/' + pieces[3] + '?index=' + newIndex);
        $(gallery).append(newForm);

        ImageUpload_bindLoadComplete();
        ImageUpload_bindInputChange();
        ImageUpload_bindActionClick();
    }

    ImageUpload_bindLoadComplete();
    ImageUpload_bindInputChange();
    ImageUpload_bindActionClick();

});

// image view control
$(function () {
    $('.image-view-gallery .image-upload-control').slice(4).hide();
    $('.image-view-gallery-see-more').click(function (e) {
        e.stopImmediatePropagation();
        $(this).parent().children('.image-upload-control').show();
        $(this).hide();
        return false;
    });
    $('.image-view-gallery .image-upload-control').click(function () {
        $(this).toggleClass('lightbox');
    });
});

// Register/GetStarted buttons
function Subscription_RegisteredOrNot(SubID) {
    // returns true or false
    var hiddenVal = $("#" + SubID).val();
    var openComps = $("#comp_" + SubID).val();

    if (typeof (openComps) == "undefined") openComps = "false";
    if (typeof (hiddenVal) == "undefined") hiddenVal = "false";

    if (hiddenVal != undefined) {
        hiddenVal = hiddenVal.toString().toLowerCase();
        openComps = openComps.toString().toLowerCase();

        $('div[id^="' + SubID + '_"]').hide();

        var showSubID = SubID + "_" + hiddenVal;

        // redirect "get started" to FAQ page if the user is signed in and registered, but with no active competition
        if (hiddenVal == "true" && openComps == "false") {
            try {
                $("#" + showSubID + " a").attr("href", "/account/manage");
            } catch (e) { }
        }

        if ($("#" + showSubID).length > 0) {
            $("#" + showSubID).show();
        }
        else {
            $('div[id^="' + SubID + '_"]').first().show();
        }
    }
}


// format polyfill
String.prototype.format = String.prototype.format = function () {
    var s = this,
        i = arguments.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return s;
};

// startsWith polyfill
if (!String.prototype.startsWith) {
    String.prototype.startsWith = function (searchString, position) {
        position = position || 0;
        return this.substr(position, searchString.length) === searchString;
    };
}


// endsWith polyfill
if (!String.prototype.endsWith) {
    String.prototype.endsWith = function (search, this_len) {
        if (this_len === undefined || this_len > this.length) {
            this_len = this.length;
        }
        return this.substring(this_len - search.length, this_len) === search;
    };
}

// includes polyfill
if (!Array.prototype.includes) {
    Object.defineProperty(Array.prototype, 'includes', {
        value: function (searchElement, fromIndex) {
            if (this == null) {
                throw new TypeError('"this" is null or not defined');
            }
            // 1. Let O be ? ToObject(this value).
            var o = Object(this);
            // 2. Let len be ? ToLength(? Get(O, "length")).
            var len = o.length >>> 0;
            // 3. If len is 0, return false.
            if (len === 0) {
                return false;
            }
            // 4. Let n be ? ToInteger(fromIndex).
            //    (If fromIndex is undefined, this step produces the value 0.)
            var n = fromIndex | 0;
            // 5. If n ≥ 0, then
            //  a. Let k be n.
            // 6. Else n < 0,
            //  a. Let k be len + n.
            //  b. If k < 0, let k be 0.
            var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
            function sameValueZero(x, y) {
                return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
            }
            // 7. Repeat, while k < len
            while (k < len) {
                // a. Let elementK be the result of ? Get(O, ! ToString(k)).
                // b. If SameValueZero(searchElement, elementK) is true, return true.
                if (sameValueZero(o[k], searchElement)) {
                    return true;
                }
                // c. Increase k by 1. 
                k++;
            }
            // 8. Return false
            return false;
        }
    });
}

// nodelist foreach polyfill
if (window.NodeList && !NodeList.prototype.forEach) {
    NodeList.prototype.forEach = function (callback, thisArg) {
        thisArg = thisArg || window;
        for (var i = 0; i < this.length; i++) {
            callback.call(thisArg, this[i], i, this);
        }
    };
}

// jquery case insensitive contains
jQuery.expr[':'].ContainsCaseIns = function (a, i, m) {
    return jQuery(a).text().toUpperCase()
        .indexOf(m[3].toUpperCase()) >= 0;
};


// random func
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}



// drag-n-drop file upload
if ($('body').children('.overlay-disabled').length == 0) {
    $('body').append('<div class="overlay-disabled" style="display:none;"></div>');
}

var dragging = 0;
$('body').on('drag dragstart dragend dragover dragenter dragleave drop', function (e) {
    e.preventDefault();
    e.stopPropagation();
    return false;
})
    .on('dragenter', function (e) {
        dragging++;
        if ($('.icWebFileUpload:visible').length === 1) {
            $('.icWebFileUpload').addClass('overlay-highlight');
            $('.overlay-disabled').show();
        }

        e.preventDefault();
        e.stopPropagation();
        return false;
    })
    .on('dragleave', function (e) {
        dragging--;
        if (dragging == 0) {
            window.setTimeout(() => {
                if ($('.icWebFileUpload:visible').length === 1) {
                    $('.icWebFileUpload').removeClass('overlay-highlight');
                    $('.overlay-disabled').hide();
                }
            }, 50);
        }

        e.preventDefault();
        e.stopPropagation();
        return false;
    })
    .on('drop', function () {
        dragging = 0;
        if ($('.icWebFileUpload:visible').length === 1) {
            $('.icWebFileUpload').removeClass('overlay-highlight');
            $('.overlay-disabled').hide();
        }
    });

var fileUploadDrag = 0;
$('.icWebFileUpload').on('dragenter', function () {
    fileUploadDrag++;
    $(this).addClass('file-dragover');
    console.log('dragenter ' + fileUploadDrag);
});

$('.icWebFileUpload').on('dragleave', function () {
    fileUploadDrag--;
    if (fileUploadDrag == 0) {
        $(this).removeClass('file-dragover');
    }
    console.log('dragleave ' + fileUploadDrag);

});

$('.icWebFileUpload').on('drop', function (e) {
    $(this).removeClass('file-dragover');
    var droppedFile = false;
    if (typeof e != 'undefined' && e.originalEvent != null && e.originalEvent.dataTransfer != null && e.originalEvent.dataTransfer.files.length > 0) {
        droppedFile = e.originalEvent.dataTransfer.files[0];
    }

    if (droppedFile) {
        var index = $(this).find('input[type="file"]').attr('data-index');
        var options = $(this).find('input[type="file"]').attr('accept');
        var maxSize = $(this).find('input[type="file"]').attr('data-maxSize');
        var compId = $(this).find('input[type="file"]').attr('data-compId');
        var teamId = $(this).find('input[type="file"]').attr('data-teamId') || 0;
        var userProfileId = $(this).find('input[type="file"]').attr('data-userProfileId') || 0;
        var userCompId = $(this).find('input[type="file"]').attr('data-userCompId') || 0;
        var subAttrId = $(this).find('input[type="file"]').attr('data-subAttrId');
        var altName = $(this).find('input[type="file"]').attr('data-altName');

        var studentLabel = null;
        var num = parseInt(teamId, 10);
        if (isNaN(num)) { // If teamID isn't a number, set to -1, and use studentLabel
            studentLabel = teamId;
            teamId = -1;
        }

        if (ClientValidateAjaxFile(droppedFile, 'fileUpload_' + index, options, maxSize, 'divStatusMessage_' + index)) {
            StartAjaxFileBatchUpload(droppedFile,
                'fileUpload_' + index,
                'uploaded_file_name_' + index,
                'fileHolder_' + index,
                4194304,
                3,
                'file_progress_' + index,
                'divStatusMessage_' + index,
                'hidSavedFilePath_' + index,
                'btnUpload_' + index,
                'btnCancel_' + index,
                compId,
                teamId,
                userProfileId,
                userCompId,
                studentLabel,
                subAttrId,
                index,
                altName,
                validFileUpload
            );
        }
    }
});

$('.icWebFileUpload button[name="btnSelect"]').click(function () {
    $(this).parent().children('input[type="file"]').click();
});

$('.icWebFileUpload input[type="file"]').change(function () {
    if ($(this)[0].files.length > 0) {
        var file = $(this)[0].files[0];
        var index = $(this).attr('data-index');
        var options = $(this).attr('accept');
        var maxSize = $(this).attr('data-maxSize');
        var compId = $(this).attr('data-compId');
        var teamId = $(this).attr('data-teamId');
        var userCompId = $(this).attr('data-userCompId');
        var userProfileId = $(this).attr('data-userProfileId');
        var subAttrId = $(this).attr('data-subAttrId');
        var altName = $(this).attr('data-altName');

        if (userProfileId == "") userProfileId = 0;
        if (teamId == "") teamId = 0;

        var studentLabel = null;
        var num = parseInt(teamId, 10);
        if (isNaN(num)) { // If teamID isn't a number, set to -1, and use studentLabel
            studentLabel = teamId;
            teamId = -1;
        }

        if (ClientValidateAjaxFile(file, 'fileUpload_' + index, options, maxSize, 'divStatusMessage_' + index)) {
            StartAjaxFileBatchUpload(file,
                'fileUpload_' + index,
                'uploaded_file_name_' + index,
                'fileHolder_' + index,
                4194304,
                3,
                'file_progress_' + index,
                'divStatusMessage_' + index,
                'hidSavedFilePath_' + index,
                'btnUpload_' + index,
                'btnCancel_' + index,
                compId,
                teamId,
                userProfileId,
                userCompId,
                studentLabel,
                subAttrId,
                index,
                altName,
                validFileUpload
            );
        }
    }
});

$('.icWebFileUpload .file_replace').click(function (e) {
    e.preventDefault();
    $(this).parents('.icWebFileUpload').find('input[type="file"]').click();
});

$('.icWebFileUpload .file_delete').click(function (e) {
    e.preventDefault();

    var fileInput = $(this).parents('.icWebFileUpload').find('input[type="file"]');
    var index = $(fileInput).attr('data-index');

    if (!confirm("Are you sure you want to delete this file?")) {
        return;
    }

    // Reset to default state
    $(fileInput).attr('data-uploaded', 'false');
    $('#uploaded_file_name_' + index).val('');
    $('#hidSavedFilePath_' + index).val('');
    $('#divStatusMessage_' + index).text('');
    $('#model_attribute_index_' + index).find('.file').hide();
    $('#model_attribute_index_' + index).find('.select').show();
    $('[name="[' + index + '].FileIsUploaded"]').val('false');

    // Grab the new submission detail DTO (empty, going to wipe out the db)
    var data = $(this).parents('[data-subAttrId]').clone();
    var i = 0;
    var processed = []; // rename from whatever id to [0]
    $(data).find('input').each(function () {
        var name = $(this).attr('name');
        if (typeof name != 'undefined' && name != null) {
            var oldId = "[" + name.substr(1, name.indexOf("]") - 1) + "]";
            var newId = "[" + i + "]";
            if (!processed.includes(oldId)) {
                $(data).find('input[name^="' + oldId + '"]').each(function () { $(this).attr('name', $(this).attr('name').replace(oldId, newId)); });
                i++;
                processed.push(newId);
            }
        }
    });

    // Post update to sub dto
    var newForm = $('<form/>').append(data);
    var dataToSend = newForm.serializeArray();
    dataToSend.push({ "name": "isSubmit", "value": "false" });
    dataToSend.push({ "name": "__RequestVerificationToken", "value": AntiForgeryHelper.Token().value });
    $.ajax({
        type: 'POST',
        url: 'Submission/RemoteSave',
        data: AntiForgeryHelper.Wrap(dataToSend),
        async: true,
        cache: false,
        traditional: true,
        success: function (data) {
        },
        error: function (data) {
            //console.log('error' + data);
        }
    });
});

/* slide picker control */
$('.SlidePicker').find('input[type="text"]').on('input change', function () {
    var container = $(this).closest('.SlidePicker');
    var slide = $(this).parent().find('input[type="range"]');
    var output = $(this).parent().children('.output');
    if (output.length > 0) {
        var val = $(this).val();
        if (isNaN(val)) {
            $(this).val('');
            val = '';
        }

        var min = $(slide).attr('min');
        var max = $(slide).attr('max');

        var width = $(slide).width();
        var newPoint = ((val - max) / max - min) + 1;

        var offset = $(output).width() * newPoint * -1;

        if (newPoint < 0) newPoint = 0;
        if (newPoint > 1) newPoint = 1;

        newPoint = newPoint * width;

        if (val != "") {
            output.text(val);
            output.css('font-size', '25px');
        } else {
            output.text('unset');
            output.css('font-size', '11px');
        }
        output.css('left', newPoint + 'px');
        output.css('margin-left', offset + 'px');
    }
}).trigger('change');

$('.SlidePicker').find('input[type="range"]').on('input change', function () {
    var input = $(this).parent().parent().children('input[type="text"]');
    if (input.length > 0) {
        $(input).val($(this).val()).trigger('change');
    }
});

window.onResize(function () {
    $('.SlidePicker').find('input[type="text"]').trigger('change');
});

/* new MWF version, fix onchanged */
if (typeof (mwfAutoInit) != "undefined") {
    var mwfAutoInit_Select_onSelectionChanged = mwfAutoInit.Select.prototype.onSelectionChanged;
    mwfAutoInit.Select.prototype.onSelectionChanged = (function (e) {
        mwfAutoInit_Select_onSelectionChanged.apply(this, arguments);
        $(this.select).val(e.id);
        $(this.select).trigger('change');
        return true;
    });
}


// teams collaboration join now component
function TeamsCollabOptInPartial() {
    if ($('#teams-collab-opt-in').length > 0) {
        var loc_click_here_to_continue = (typeof (window.LocalizationResources['teams_collab_click_here_to_continue']) !== "undefined") ? window.LocalizationResources['teams_collab_click_here_to_continue'] : 'Click here to continue Teams Collaboration registration';
        var loc_generic_error = (typeof (window.LocalizationResources['GenericError']) !== "undefined") ? window.LocalizationResources['GenericError'] : 'There was an error. Please retry.';

        $('#TeamsCollabOptInPrivacyNoticeRead').on('change', function () {
            if ($('#TeamsCollabOptInPrivacyNoticeRead').is(':checked')) {
                $('#teams-collab-opt-in').addClass('f-purple');
                $('#teams-collab-opt-in').removeClass('f-clear');
                $('#teams-collab-opt-in').removeAttr('disabled');
            } else {
                $('#teams-collab-opt-in').removeClass('f-purple');
                $('#teams-collab-opt-in').addClass('f-clear');
                $('#teams-collab-opt-in').attr('disabled', 'disabled');
            }
        });
        $('#teams-collab-opt-in').on('click', function (e) {
            e.preventDefault();
            if ($('#TeamsCollabOptInPrivacyNoticeRead').is(':checked')) {
                $(this).removeClass('f-purple');
                $(this).addClass('f-clear');
                $(this).prop('disabled', 'disabled');
                $('.teams-collaboration-block-item').find('.c-progress').show();
                var returnUrl = null;
                if (window.location.pathname.toLowerCase().includes("/search")) {
                    returnUrl = window.location.pathname + window.location.search + window.location.hash;
                }
                $.post('/Account/TeamsCollaborationOptIn', AntiForgeryHelper.Wrap({ optin: true, returnUrl: returnUrl }), function (s) {
                    if (typeof (s) == "object") {
                        if (typeof (s.Data) == "string" && s.Data.startsWith("http")) {
                            window.location.href = s.Data;

                            setTimeout(function () {
                                $('.teams-collaboration-block-item').append('<a href="' + s.Data + '" class="c-hyperlink"> ' + loc_click_here_to_continue + '</a>');
                            }, 4000);
                        } else if (typeof (s.Data) == "boolean") {
                            if (s.Data == true) {
                                if ($('#userregionProfile').length > 0) {
                                    $.get('/account/GetUserProfileRegion', function (s) {
                                        $('#userregionProfile').html(s);
                                    });
                                }
                                if ($('#GetTeamsCollaborationRequests').length > 0) {
                                    $.get('/account/GetTeamsCollaborationRequests', function (s) {
                                        $('#GetTeamsCollaborationRequests').html(s);
                                    })
                                }
                                if (document.location.pathname.toLowerCase().includes("/search/")) {
                                    document.location.reload();
                                }
                            } else {
                                $('.teams-collaboration-block-item').append(loc_generic_error);
                            }
                        }
                    } else {
                        $('.teams-collaboration-block-item').append(loc_generic_error);
                    }

                    // Center-screen popup window script
                    //var newWindow;
                    //if (s != "true" || s.startsWith("http")) {
                    //    var w = 400;
                    //    var h = 500;
                    //    var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
                    //    var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
                    //    var systemZoom = width / window.screen.availWidth;
                    //    var left = (width - w) / 2 / systemZoom;
                    //    var top = (height - h) / 2 / systemZoom;

                    //    newWindow = window.open(s, "Imagine Cup Teams Collaboration Opt-In", 'scrollbars=yes, width=' + w / systemZoom + ', height=' + h / systemZoom + ', top=' + top + ', left=' + left + ', location=no, menubar=no, resizable=no, toolbar=no');

                    //    try {
                    //        newWindow.focus();
                    //    } catch (e) {
                    //        $('.teams-collaboration-block-item').append('<a href="' + s + '" class="c-hyperlink">Click here to continue Teams Collaboration registration</a>');
                    //    }
                    //}

                    //var timer = setInterval(function () {
                    //    if (typeof (newWindow) == 'undefined' || newWindow.closed) {
                    //        $.get('@Url.Action("GetUserProfileRegion", "Account")', function (s) {
                    //            $('#userregionProfile').html(s);
                    //        });
                    //        clearTimeout(timer);
                    //    }
                    //}, 1000)
                });
            }
        });
    }
}
$(function () {
    TeamsCollabOptInPartial();
});;
$(function () {
    var loc_dialogShow = (typeof (window.LocalizationResources) !== "undefined" && typeof (window.LocalizationResources['SupportBot_Show_Aria']) !== "undefined") ? window.LocalizationResources['SupportBot_Show_Aria'] : 'Click or press enter to show the support bot dialog';
    var loc_dialogHide = (typeof (window.LocalizationResources) !== "undefined" && typeof (window.LocalizationResources['SupportBot_Hide_Aria']) !== "undefined") ? window.LocalizationResources['SupportBot_Hide_Aria'] : 'Click or press enter to hide the support bot dialog';
    var loc_NetworkError = (typeof (window.LocalizationResources) !== "undefined" && typeof(window.LocalizationResources['NetworkError']) !== "undefined") ? window.LocalizationResources['NetworkError'] : 'A network error occurred. Please email support.';
    var loc_youSaid = (typeof(window.LocalizationResources) !== "undefined" && typeof (window.LocalizationResources['SupportBot_Aria_YouSaid']) !== "undefined") ? window.LocalizationResources['SupportBot_Aria_YouSaid'] : 'You said...';
    var queryTemplate = $('<div class="query" tabindex="0" role="alertdialog">');
    var typingIndicatorTemplate = $('<div class="typing-indicator"><span></span><span></span><span></span></div>');

    if ($('.SupportChatBot').length > 0) {
        var culture = $('.SupportChatBot').attr('data-locale');

        // Bind controls
        $('.SupportChatBot input[type="text"]').on('keyup', function (e) {
            if (e.keyCode == 13) {
                SubmitQuery();
            }
        });

        $('.SupportChatBot button').on('click', function () {
            SubmitQuery();
        });

        $(document).ready(function () {
            // remove re-add previous messages for aria-live to update properly
            var log = $('.SupportChatBot .responses').html().trim();
            $('.SupportChatBot .responses').html('');
            $('.SupportChatBot .responses').append(log);

            // Tab focus capture
            tabFocusCapture();

            // Script for when focus goes behind the fixed chat window
            $('body').on('focusin', function (e) {
                if (typeof(e.target) == 'undefined' || e.target == null) return;
                if ($(e.target).hasClass('SupportChatBot') || $(e.target).parents('.SupportChatBot').length > 0) return;

                var targetPos = e.target.getBoundingClientRect();
                var chatbotPos = document.querySelector('.SupportChatBot').getBoundingClientRect();

                var overlap = !(targetPos.right < chatbotPos.left ||
                                targetPos.left > chatbotPos.right ||
                                targetPos.bottom < chatbotPos.top ||
                                targetPos.top > chatbotPos.bottom);

                if (overlap) {
                    var moveTop = chatbotPos.bottom - targetPos.top;
                    window.scrollTo(0, window.scrollY + moveTop);
                }
            });


            
            if ($('.SupportChatBot').parent('.fixed-bottom-right').length > 0) {
                var initialBottom = $('.SupportChatBot').css('bottom');

                window.onResize(function () {
                    $(window).scroll();
                });

                $(window).on('resize', function () {
                    $(window).scroll();
                });

                $(window).on('scroll', function () {
                    if ($('.SupportChatBot').parent('.fixed-bottom-right').length > 0) {
                        var height = $('.SupportChatBot .top').outerHeight();

                        // End position
                        var endPos = $('.social-footer').offset().top;
                        var scrollBottom = $(window).scrollTop() + $(window).height();

                        if (scrollBottom > endPos) { // Nav is stuck to bottom of page
                            $('.SupportChatBot').css('position', 'absolute');
                            $('.SupportChatBot').css('bottom', '10px');
                        } else {
                            $('.SupportChatBot').css('position', 'fixed');
                            $('.SupportChatBot').css('bottom', initialBottom);
                        }
                    }
                });
            }
        });

        function tabFocusCapture() {
            var focusable = $('.SupportChatBot').find('a:not([tabindex="-1"]), button:not([tabindex="-1"]), input:not([tabindex="-1"]), [tabindex]:not([tabindex="-1"])');
            var firstFocusable = $(focusable).first().get(0);
            var lastFocusable = $(focusable).last().get(0);
            $('.SupportChatBot').off('keydown');

            if (firstFocusable == lastFocusable) return;
            $('.SupportChatBot').on('keydown', function (e) {
                if (e.key === 'Tab' || e.keyCode === 9) {
                    if (e.shiftKey) {
                        if (document.activeElement == firstFocusable) {
                            lastFocusable.focus();
                            e.preventDefault();
                        }
                    } else {
                        if (document.activeElement == lastFocusable) {
                            firstFocusable.focus();
                            e.preventDefault();
                        }
                    }
                }
            });
        }

        // Logic for querying
        function SubmitQuery() {
            var query = $('.SupportChatBot input[type="text"]').val().trim();
            var session = $('.SupportChatBot .responses').children().first().attr('data-session') || "-1";
            if (query.length > 0) {
                $('.SupportChatBot input[type="text"]').val('');
                var userQueryBox = $(queryTemplate).clone(false, false).text(query);
                $(userQueryBox).prepend('<div class="screen-reader-text">You said...</div>');
                $('.SupportChatBot .responses').append(userQueryBox);
                $('.SupportChatBot .responses').append($(typingIndicatorTemplate).clone(false, false));
                $.ajax({
                    type: 'POST',
                    url: "/" + culture + "/Support/ChatbotQuery",
                    dataType: "html",
                    async: true,
                    cache: false,
                    data: AntiForgeryHelper.Wrap({ query: query, session: session }),
                    success: function (response, xhr, details) {
                        if (response.replace(/\s/g, '').toLowerCase().startsWith('<!doctype') || response.replace(/\s/g, '').toLowerCase().startsWith('<html')) {
                            error();
                        } else {
                            $('.SupportChatBot .typing-indicator').remove();
                            $('.SupportChatBot .responses').append(response);
                        }
                    },
                    error: function (xhr, status, errThrow) {
                        error();
                    }
                });
            }
        }

        function error() {
            $('.SupportChatBot .typing-indicator').remove();
            $('.SupportChatBot .responses').append($('<div class="error">' + loc_NetworkError + '</div>'));
        }

        $('.SupportChatBot .responses').bind('DOMSubtreeModified', function (e) {
            $('.SupportChatBot .responses').scrollTop(function () { return this.scrollHeight; });
        });

        $('.SupportChatBot .hide-show-btn').bind('click', function () {
            if ($('.SupportChatBot .top .hide-show-btn').hasClass('glyph-chevron-down')) {
                hideChatBot();
            } else {
                showChatBot();
            }
        });

        if (window.innerWidth <= 767) {
            hideChatBot();
        }

        function hideChatBot() {
            $('.SupportChatBot .top .hide-show-btn').removeClass('glyph-chevron-down');
            $('.SupportChatBot .top .hide-show-btn').addClass('glyph-chevron-up');
            $('.SupportChatBot .top .hide-show-btn').attr('aria-label', loc_dialogShow);
            $('.SupportChatBot').attr('tabindex', '-1');
            $('.SupportChatBot .controls').find('a,button,input').attr('tabindex', '-1');
            $('.SupportChatBot .responses').find('a').attr('tabindex', '-1');
            $('.SupportChatBot .responses .response').attr('tabindex', '-1');
            $('.SupportChatBot .responses .query').attr('tabindex', '-1');
            $('.SupportChatBot').animate({ 'height': '65px' }, 500);
            $('.SupportChatBot').animate({ 'width': '100px' }, 500);
            tabFocusCapture();
        }

        function showChatBot() {
            $('.SupportChatBot .top .hide-show-btn').removeClass('glyph-chevron-up');
            $('.SupportChatBot .top .hide-show-btn').addClass('glyph-chevron-down');
            $('.SupportChatBot .top .hide-show-btn').attr('aria-label', loc_dialogHide);
            $('.SupportChatBot').attr('tabindex', '0');
            $('.SupportChatBot .controls').find('a,button,input').attr('tabindex', '0');
            $('.SupportChatBot .responses').find('a').attr('tabindex', '0');
            $('.SupportChatBot .responses .response').attr('tabindex', '0');
            $('.SupportChatBot .responses .query').attr('tabindex', '0');
            $('.SupportChatBot').animate({ 'width': '300px' }, 500);
            $('.SupportChatBot').animate({ 'height': '400px' }, 500);
            tabFocusCapture();
        }
    };
});;
