/* Minification failed. Returning unminified contents.
(347,9-15): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: Base64
 */
//** jQuery Scroll to Top Control script- (c) Dynamic Drive DHTML code library: http://www.dynamicdrive.com.
//** Available/ usage terms at http://www.dynamicdrive.com (March 30th, 09')
//** v1.1 (April 7th, 09'):
//** 1) Adds ability to scroll to an absolute position (from top of page) or specific element on the page instead.
//** 2) Fixes scroll animation not working in Opera. 


var scrolltotop={
	//startline: Integer. Number of pixels from top of doc scrollbar is scrolled before showing control
	//scrollto: Keyword (Integer, or "Scroll_to_Element_ID"). How far to scroll document up when control is clicked on (0=top).
	setting: {startline:100, scrollto: 0, scrollduration:1000, fadeduration:[500, 100]},
	controlHTML: '<img src="' + environment.content + '/img/up.png" style="width:51px; height:42px" alt="Scroll Up"/>', //HTML for control, which is auto wrapped in DIV w/ ID="topcontrol"
	controlattrs: {offsetx:5, offsety:5}, //offset of control relative to right/ bottom of window corner
	anchorkeyword: '#top', //Enter href value of HTML anchors on the page that should also act as "Scroll Up" links

	state: {isvisible:false, shouldvisible:false},

	scrollup:function(){
		if (!this.cssfixedsupport) //if control is positioned using JavaScript
			this.$control.css({opacity:0}) //hide control immediately after clicking it
		var dest=isNaN(this.setting.scrollto)? this.setting.scrollto : parseInt(this.setting.scrollto)
		if (typeof dest=="string" && jQuery('#'+dest).length==1) //check element set by string exists
			dest=jQuery('#'+dest).offset().top
		else
			dest=0
		this.$body.animate({scrollTop: dest}, this.setting.scrollduration);
	},

	keepfixed:function(){
		var $window=jQuery(window)
		var controlx=$window.scrollLeft() + $window.width() - this.$control.width() - this.controlattrs.offsetx
		var controly=$window.scrollTop() + $window.height() - this.$control.height() - this.controlattrs.offsety
		this.$control.css({left:controlx+'px', top:controly+'px'})
	},

	togglecontrol:function(){
		var scrolltop=jQuery(window).scrollTop()
		if (!this.cssfixedsupport)
			this.keepfixed()
		this.state.shouldvisible=(scrolltop>=this.setting.startline)? true : false
		if (this.state.shouldvisible && !this.state.isvisible){
			this.$control.stop().animate({opacity:1}, this.setting.fadeduration[0])
			this.state.isvisible=true
		}
		else if (this.state.shouldvisible==false && this.state.isvisible){
			this.$control.stop().animate({opacity:0}, this.setting.fadeduration[1])
			this.state.isvisible=false
		}
	},
	
	init:function(){
		jQuery(document).ready(function($){
			var mainobj=scrolltotop
			var iebrws=document.all
			mainobj.cssfixedsupport=!iebrws || iebrws && document.compatMode=="CSS1Compat" && window.XMLHttpRequest //not IE or IE7+ browsers in standards mode
			mainobj.$body=(window.opera)? (document.compatMode=="CSS1Compat"? $('html') : $('body')) : $('html,body')
			mainobj.$control=$('<div id="topcontrol">'+mainobj.controlHTML+'</div>')
				.css({position:mainobj.cssfixedsupport? 'fixed' : 'absolute', bottom:mainobj.controlattrs.offsety, right:mainobj.controlattrs.offsetx, opacity:0, cursor:'pointer'})
				.attr({title:'Scroll Back to Top'})
				.click(function(){mainobj.scrollup(); return false})
				.appendTo('body')
			if (document.all && !window.XMLHttpRequest && mainobj.$control.text()!='') //loose check for IE6 and below, plus whether control contains any text
				mainobj.$control.css({width:mainobj.$control.width()}) //IE6- seems to require an explicit width on a DIV containing text
			mainobj.togglecontrol()
			$('a[href="' + mainobj.anchorkeyword +'"]').click(function(){
				mainobj.scrollup()
				return false
			})
			$(window).bind('scroll resize', function(e){
				mainobj.togglecontrol()
			})
		})
	}
}

scrolltotop.init();
/*
 *  Linkify - v1.1.6
 *  Find URLs in plain text and return HTML for discovered links.
 *  https://github.com/HitSend/jQuery-linkify/
 *
 *  Made by SoapBox Innovations, Inc.
 *  Under MIT License
 */
!function(a,b,c){"use strict";function d(a,b){this._defaults=e,this.element=a,this.setOptions(b),this.init()}var e={tagName:"a",newLine:"\n",target:"_blank",linkClass:null,linkClasses:[],linkAttributes:null};d.prototype={constructor:d,init:function(){1===this.element.nodeType?d.linkifyNode.call(this,this.element):this.element=d.linkify.call(this,this.element.toString())},setOptions:function(a){this.settings=d.extendSettings(a,this.settings)},toString:function(){return this.element.toString()}},d.extendSettings=function(a,b){var c;b=b||{};for(c in e)b[c]||(b[c]=e[c]);for(c in a)b[c]=a[c];return b},d.linkMatch=new RegExp(["(",'\\s|[^a-zA-Z0-9.\\+_\\/"\\>\\-]|^',")(?:","(","[a-zA-Z0-9\\+_\\-]+","(?:","\\.[a-zA-Z0-9\\+_\\-]+",")*@",")?(","http:\\/\\/|https:\\/\\/|ftp:\\/\\/",")?(","(?:(?:[a-z0-9][a-z0-9_%\\-_+]*\\.)+)",")(","(?:com|ca|co|edu|gov|net|org|dev|biz|cat|int|pro|tel|mil|aero|asia|coop|info|jobs|mobi|museum|name|post|travel|local|[a-z]{2})",")(","(?::\\d{1,5})",")?(","(?:","[\\/|\\?]","(?:","[\\-a-zA-Z0-9_%#*&+=~!?,;:.\\/]*",")*",")","[\\-\\/a-zA-Z0-9_%#*&+=~]","|","\\/?",")?",")(",'[^a-zA-Z0-9\\+_\\/"\\<\\-]|$',")"].join(""),"g"),d.emailLinkMatch=/(<[a-z]+ href=\")(http:\/\/)([a-zA-Z0-9\+_\-]+(?:\.[a-zA-Z0-9\+_\-]+)*@)/g,d.linkify=function(a,b){var c,e,f,g=[];this.constructor===d&&this.settings?(e=this.settings,b&&(e=d.extendSettings(b,e))):e=d.extendSettings(b),f=e.linkClass?e.linkClass.split(/\s+/):[],f.push.apply(f,e.linkClasses),a=a.replace(/</g,"&lt;").replace(/(\s)/g,"$1$1"),g.push("$1<"+e.tagName,'href="http://$2$4$5$6$7"'),g.push('class="linkified'+(f.length>0?" "+f.join(" "):"")+'"'),e.target&&g.push('target="'+e.target+'"');for(c in e.linkAttributes)g.push([c,'="',e.linkAttributes[c].replace(/\"/g,"&quot;").replace(/\$/g,"&#36;"),'"'].join(""));return g.push(">$2$3$4$5$6$7</"+e.tagName+">$8"),a=a.replace(d.linkMatch,g.join(" ")),a=a.replace(d.emailLinkMatch,"$1mailto:$3"),a=a.replace(/(\s){2}/g,"$1"),a=a.replace(/\n/g,e.newLine)},d.linkifyNode=function(a){var b,e,f,g,h;if(a&&"object"==typeof a&&1===a.nodeType&&"a"!==a.tagName.toLowerCase()&&!/[^\s]linkified[\s$]/.test(a.className)){for(b=[],g=d._dummyElement||c.createElement("div"),e=a.firstChild,f=a.childElementCount;e;){if(3===e.nodeType){for(;g.firstChild;)g.removeChild(g.firstChild);for(g.innerHTML=d.linkify.call(this,e.textContent||e.innerText||e.nodeValue),b.push.apply(b,g.childNodes);g.firstChild;)g.removeChild(g.firstChild)}else 1===e.nodeType?b.push(d.linkifyNode(e)):b.push(e);e=e.nextSibling}for(;a.firstChild;)a.removeChild(a.firstChild);for(h=0;h<b.length;h++)a.appendChild(b[h])}return a},d._dummyElement=c.createElement("div"),a.fn.linkify=function(b){return this.each(function(){var c;(c=a.data(this,"plugin-linkify"))?(c.setOptions(b),c.init()):a.data(this,"plugin-linkify",new d(this,b))})},a.fn.linkify.Constructor=d,a(b).on("load",function(){a("[data-linkify]").each(function(){var b,c=a(this),d=c.attr("data-linkify"),e={tagName:c.attr("data-linkify-tagname"),newLine:c.attr("data-linkify-newline"),target:c.attr("data-linkify-target"),linkClass:c.attr("data-linkify-linkclass")};for(var f in e)"undefined"==typeof e[f]&&delete e[f];b="this"===d?c:c.find(d),b.linkify(e)})}),a("body").on("click",".linkified",function(){var c=a(this),d=c.attr("href"),e=/^mailto:/i.test(d),f=c.attr("target");return e?b.location.href=d:b.open(d,f),!1})}(jQuery,window,document);;
/*
Plugin: jQuery Parallax
Version 1.1.3
Author: Ian Lunn
Twitter: @IanLunn
Author URL: http://www.ianlunn.co.uk/
Plugin URL: http://www.ianlunn.co.uk/plugins/jquery-parallax/

Dual licensed under the MIT and GPL licenses:
http://www.opensource.org/licenses/mit-license.php
http://www.gnu.org/licenses/gpl.html
*/

(function( $ ){
	var $window = $(window);
	var windowHeight = $window.height();

	$window.resize(function () {
		windowHeight = $window.height();
	});

	$.fn.parallax = function(xpos, speedFactor, outerHeight) {
		var $this = $(this);
		var getHeight;
		var firstTop;
		var paddingTop = 0;
		
		//get the starting position of each element to have parallax applied to it		
		$this.each(function(){
		    firstTop = $this.offset().top;
		});

		if (outerHeight) {
			getHeight = function(jqo) {
				return jqo.outerHeight(true);
			};
		} else {
			getHeight = function(jqo) {
				return jqo.height();
			};
		}
			
		// setup defaults if arguments aren't specified
		if (arguments.length < 1 || xpos === null) xpos = "50%";
		if (arguments.length < 2 || speedFactor === null) speedFactor = 0.1;
		if (arguments.length < 3 || outerHeight === null) outerHeight = true;
		
		// function to be called whenever the window is scrolled or resized
		function update(){
			var pos = $window.scrollTop();				

			$this.each(function(){
				var $element = $(this);
				var top = $element.offset().top;
				var height = getHeight($element);

				// Check if totally above or totally below viewport
				if (top + height < pos || top > pos + windowHeight) {
					return;
				}

				$this.css('backgroundPosition', xpos + " " + Math.round((firstTop - pos) * speedFactor) + "px");
			});
		}		

		$window.bind('scroll', update).resize(update);
		update();
	};
})(jQuery);
;
/*
 * $Id: base64.js,v 2.15 2014/04/05 12:58:57 dankogai Exp dankogai $
 *
 *  Licensed under the MIT license.
 *    http://opensource.org/licenses/mit-license
 *
 *  References:
 *    http://en.wikipedia.org/wiki/Base64
 */

(function (global) {
    'use strict';
    // existing version for noConflict()
    var _Base64 = global.Base64;
    var version = "2.1.9";
    // if node.js, we use Buffer
    var buffer;
    if (typeof module !== 'undefined' && module.exports) {
        try {
            buffer = require('buffer').Buffer;
        } catch (err) { }
    }
    // constants
    var b64chars
        = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    var b64tab = function (bin) {
        var t = {};
        for (var i = 0, l = bin.length; i < l; i++) t[bin.charAt(i)] = i;
        return t;
    }(b64chars);
    var fromCharCode = String.fromCharCode;
    // encoder stuff
    var cb_utob = function (c) {
        if (c.length < 2) {
            var cc = c.charCodeAt(0);
            return cc < 0x80 ? c
                : cc < 0x800 ? (fromCharCode(0xc0 | (cc >>> 6))
                                + fromCharCode(0x80 | (cc & 0x3f)))
                : (fromCharCode(0xe0 | ((cc >>> 12) & 0x0f))
                   + fromCharCode(0x80 | ((cc >>> 6) & 0x3f))
                   + fromCharCode(0x80 | (cc & 0x3f)));
        } else {
            var cc = 0x10000
                + (c.charCodeAt(0) - 0xD800) * 0x400
                + (c.charCodeAt(1) - 0xDC00);
            return (fromCharCode(0xf0 | ((cc >>> 18) & 0x07))
                    + fromCharCode(0x80 | ((cc >>> 12) & 0x3f))
                    + fromCharCode(0x80 | ((cc >>> 6) & 0x3f))
                    + fromCharCode(0x80 | (cc & 0x3f)));
        }
    };
    var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
    var utob = function (u) {
        return u.replace(re_utob, cb_utob);
    };
    var cb_encode = function (ccc) {
        var padlen = [0, 2, 1][ccc.length % 3],
        ord = ccc.charCodeAt(0) << 16
            | ((ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8)
            | ((ccc.length > 2 ? ccc.charCodeAt(2) : 0)),
        chars = [
            b64chars.charAt(ord >>> 18),
            b64chars.charAt((ord >>> 12) & 63),
            padlen >= 2 ? '=' : b64chars.charAt((ord >>> 6) & 63),
            padlen >= 1 ? '=' : b64chars.charAt(ord & 63)
        ];
        return chars.join('');
    };
    var btoa = global.btoa ? function (b) {
        return global.btoa(b);
    } : function (b) {
        return b.replace(/[\s\S]{1,3}/g, cb_encode);
    };
    var _encode = buffer ? function (u) {
        return (u.constructor === buffer.constructor ? u : new buffer(u))
        .toString('base64')
    }
    : function (u) { return btoa(utob(u)) }
    ;
    var encode = function (u, urisafe) {
        return !urisafe
            ? _encode(String(u))
            : _encode(String(u)).replace(/[+\/]/g, function (m0) {
                return m0 == '+' ? '-' : '_';
            }).replace(/=/g, '');
    };
    var encodeURI = function (u) { return encode(u, true) };
    // decoder stuff
    var re_btou = new RegExp([
        '[\xC0-\xDF][\x80-\xBF]',
        '[\xE0-\xEF][\x80-\xBF]{2}',
        '[\xF0-\xF7][\x80-\xBF]{3}'
    ].join('|'), 'g');
    var cb_btou = function (cccc) {
        switch (cccc.length) {
            case 4:
                var cp = ((0x07 & cccc.charCodeAt(0)) << 18)
                    | ((0x3f & cccc.charCodeAt(1)) << 12)
                    | ((0x3f & cccc.charCodeAt(2)) << 6)
                    | (0x3f & cccc.charCodeAt(3)),
                offset = cp - 0x10000;
                return (fromCharCode((offset >>> 10) + 0xD800)
                        + fromCharCode((offset & 0x3FF) + 0xDC00));
            case 3:
                return fromCharCode(
                    ((0x0f & cccc.charCodeAt(0)) << 12)
                        | ((0x3f & cccc.charCodeAt(1)) << 6)
                        | (0x3f & cccc.charCodeAt(2))
                );
            default:
                return fromCharCode(
                    ((0x1f & cccc.charCodeAt(0)) << 6)
                        | (0x3f & cccc.charCodeAt(1))
                );
        }
    };
    var btou = function (b) {
        return b.replace(re_btou, cb_btou);
    };
    var cb_decode = function (cccc) {
        var len = cccc.length,
        padlen = len % 4,
        n = (len > 0 ? b64tab[cccc.charAt(0)] << 18 : 0)
            | (len > 1 ? b64tab[cccc.charAt(1)] << 12 : 0)
            | (len > 2 ? b64tab[cccc.charAt(2)] << 6 : 0)
            | (len > 3 ? b64tab[cccc.charAt(3)] : 0),
        chars = [
            fromCharCode(n >>> 16),
            fromCharCode((n >>> 8) & 0xff),
            fromCharCode(n & 0xff)
        ];
        chars.length -= [0, 0, 2, 1][padlen];
        return chars.join('');
    };
    var atob = global.atob ? function (a) {
        return global.atob(a);
    } : function (a) {
        return a.replace(/[\s\S]{1,4}/g, cb_decode);
    };
    var _decode = buffer ? function (a) {
        return (a.constructor === buffer.constructor
                ? a : new buffer(a, 'base64')).toString();
    }
    : function (a) { return btou(atob(a)) };
    var decode = function (a) {
        return _decode(
            String(a).replace(/[-_]/g, function (m0) { return m0 == '-' ? '+' : '/' })
                .replace(/[^A-Za-z0-9\+\/]/g, '')
        );
    };
    var noConflict = function () {
        var Base64 = global.Base64;
        global.Base64 = _Base64;
        return Base64;
    };
    // export Base64
    global.Base64 = {
        VERSION: version,
        atob: atob,
        btoa: btoa,
        fromBase64: decode,
        toBase64: encode,
        utob: utob,
        encode: encode,
        encodeURI: encodeURI,
        btou: btou,
        decode: decode,
        noConflict: noConflict
    };
    // if ES5 is available, make Base64.extendString() available
    if (typeof Object.defineProperty === 'function') {
        var noEnum = function (v) {
            return { value: v, enumerable: false, writable: true, configurable: true };
        };
        global.Base64.extendString = function () {
            Object.defineProperty(
                String.prototype, 'fromBase64', noEnum(function () {
                    return decode(this)
                }));
            Object.defineProperty(
                String.prototype, 'toBase64', noEnum(function (urisafe) {
                    return encode(this, urisafe)
                }));
            Object.defineProperty(
                String.prototype, 'toBase64URI', noEnum(function () {
                    return encode(this, true)
                }));
        };
    }
    // that's it!
    if (global['Meteor']) {
        Base64 = global.Base64; // for normal export in Meteor.js
    }
})(this);;
/*
 * Template Name: Unify - Responsive Bootstrap Template
 * Description: Business, Corporate, Portfolio and Blog Theme.
 * Version: 1.4
 * Author: @htmlstream
 * Website: http://htmlstream.com
*/

var App = function () {

    var sliverChecks = 0;

    function handleIEFixes() {
        //fix html5 placeholder attribute for ie7 & ie8
        if (jQuery.browser.msie
            && jQuery.browser.version.substr(0, 1) > 1 // if 11.0 or 10.0 returns 1, so ignore 1
            && jQuery.browser.version.substr(0, 1) < 9) { // ie7&ie8
            jQuery("input[placeholder], textarea[placeholder]").each(function () {
                var input = jQuery(this);

                jQuery(input).val(input.attr("placeholder"));

                jQuery(input).focus(function () {
                    if (input.val() === input.attr("placeholder")) {
                        input.val("");
                    }
                });

                jQuery(input).blur(function () {
                    if (input.val() === "" || input.val() === input.attr("placeholder")) {
                        input.val(input.attr("placeholder"));
                    }
                });
            });
        }
    }

    function handleBootstrap() {
        
        /*Tooltips*/
        jQuery(".tooltips").tooltip();
        jQuery(".tooltips-show").tooltip("show");      
        jQuery(".tooltips-hide").tooltip("hide");       
        jQuery(".tooltips-toggle").tooltip("toggle");       
        jQuery(".tooltips-destroy").tooltip("destroy");       

        /*Popovers*/
        jQuery(".popovers").popover();
        jQuery(".popovers-show").popover("show");
        jQuery(".popovers-hide").popover("hide");
        jQuery(".popovers-toggle").popover("toggle");
        jQuery(".popovers-destroy").popover("destroy");
    }

    function handleSearch() {    
        jQuery(".search").click(function () {
            if(jQuery(".search-btn").hasClass("fa-search")){
                jQuery(".search-open").fadeIn(500);
                jQuery(".search-btn").removeClass("fa-search");
                jQuery(".search-btn").addClass("fa-times");
            } else {
                jQuery(".search-open").fadeOut(500);
                jQuery(".search-btn").addClass("fa-search");
                jQuery(".search-btn").removeClass("fa-times");
            }   
        }); 
    }

    function handleToggle() {
        jQuery(".list-toggle").on("click", function() {
            jQuery(this).toggleClass("active");
        });
    }

    function handleHeader() {
         jQuery(window).scroll(function() {
            if (jQuery(window).scrollTop()>100){
                jQuery(".header-fixed .header").addClass("header-fixed-shrink");
            }
            else {
                jQuery(".header-fixed .header").removeClass("header-fixed-shrink");
            }
        });
    }

    return {
        init: function () {
            handleBootstrap();
            handleIEFixes();
            handleSearch();
            handleToggle();
            handleHeader();
        },

        initParallaxBg: function () {
            jQuery(".parallaxBg").parallax("50%", 0.2);
            jQuery(".parallaxBg1").parallax("50%", 0.4);
        },

        initCustom: function () {
            
            // find and execute all registered custom init functions (see the Content/js/custom directory)
            for (var item in window){
                if (window.hasOwnProperty(item) && typeof window[item] === 'function' && item.substr(0, 15) === 'initApplication') {
                    window[item].call(this);
                }
            };
            

        }
    };
}();


;

function initApplicationContactFormValidation() {

    $("#contactForm").validate({
        rules: {
            email: {
                required: true,
                email: true
            },
            phone: {
                minlength: 10,
                numeric: true
            },
            question: {
                minlength: 10,
                required: true
            }
        },
        highlight: function (element) {
            $(element).closest(".form-group").removeClass("has-success").addClass("has-warning");
        },
        success: function (element) {
            element.text("").addClass("valid").closest(".form-group").removeClass("has-warning").addClass("has-success");
        }
    });
};

function initApplicationEmployeeTeamTab() {

    var chart = {};
    var nodeCount = 0;

    function extractNodes(record, parentId, peerCount) {
        // default values
        var node = {
            "Guid": record.Guid,
            "OktaId": record.OktaId,
            "EmployeeId": record.EmployeeId,
            "CommonName": record.FullName,
            "LastName": record.LastName,
            "Title": record.Title,
            "Division": record.Division,
            "Peers": 0,
            "Children": 0
        };

        // populate parent node id
        if (record.hasOwnProperty("Manager") && record.Manager != null && record.Manager.hasOwnProperty("OktaId")) {
            node.Parent = record.Manager.OktaId;
            extractNodes(record.Manager);
        } else if (typeof parentId != "undefined") {
            node.Parent = parentId;
        } else {
            node.Parent = 0;
        }

        // populate the child and peer counts
        node.Children = record.DirectReports.length;
        if (typeof peerCount != "undefined") {
            node.Peers = peerCount;
        }

        // if the record does not exist add it
        // do not move before the manager block above
        // manager is added first (recursive call)
        if (record.OktaId in chart === false) {
            node.Sort = nodeCount;
            chart[record.OktaId] = node;
            nodeCount++;
        }

        // populate direct reports
        if (record.hasOwnProperty("DirectReports") && typeof record.DirectReports == "object") {
            for (var x = 0; x < record.DirectReports.length; x++) {
                record.DirectReports[x].Division = formatDivision(record.DirectReports[x].Division);
                extractNodes(record.DirectReports[x], record.OktaId, record.DirectReports.length);
            }
        }

    };

    function formatDivision(division) {
        var formattedDivision = division;
        if (division != null) {
            var namePieces = division.split('>');
            if (namePieces.length > 1) {
                var secondToLast = namePieces[namePieces.length - 2];
                var last = namePieces[namePieces.length - 1];
                formattedDivision = secondToLast + ' > ' + last;
            }
        }
        else {
            formattedDivision = division;
        }
        return formattedDivision;
    }

    // when the employee team tab is shown
    function formatTitle(title) {

        if (title == null || title == '') {
            title = 'Title Unknown';
        }
        title = title.replace(/(^| )PUB($| )/, '$1PUBLIC$2');
        title = title.replace(/(^| )SER($| )/, '$1SERVICE$2');
        title = title.replace(/(^| )EX(?:EC|)($| )/, '$1EXECUTIVE$2');
        title = title.replace(/(^| )OFF($| )/, '$1OFFICER$2');
        title = title.replace(/(^| )TEC(?:H|)($| )/, '$1TECHNOLOGY$2');
        title = title.replace(/(^| )SPEC($| )/, '$1SPECIALIST$2');
        title = title.replace(/(^| )MGR($| )/, '$1MANAGER$2');
        title = title.replace(/(^| )ACCT($| )/, '$1ACCOUNT$2');
        title = title.replace(/(^| )ASST($| )/, '$1ASSISTANT$2');
        title = title.replace(/(^| )ATT($| )/, '$1ATTORNEY$2');
        title = title.replace(/(^| )ADMIN($| )/, '$1ADMINISTRATOR$2');
        

        return title;
    }

    function extractSortedArray(target) {
        var tempArray = [];
        for (var property in target) {
            if (target.hasOwnProperty(property)) {
                tempArray.push(target[property]);
            }
        }
        tempArray.sort(function (a, b) {
            return (a.Sort - b.Sort);
        });
        return tempArray;
    }

    $("a[href='#employee-team']").on('shown.bs.tab', function () {

        // if this is the first time the employee tab has been shown
        if ($('#employee-team').data('populated') !== true) {

            var request = {
                "OktaId": $('#employee-team').data('oktaid')
            };
            // fetch the employee's reporting structure
            $.post(window.environment.url + "employee/teaminformation", request, function (response) {
                if (response.hasOwnProperty("Success") && response.Success === true) {
                    extractNodes(response.Data);
                    var nodes = extractSortedArray(chart);
                    
                    var employee = "";
                    var lastManager = null;
                    $('div.team-chart').html("");

                    for (var i = 0; i < nodes.length;i++) {

                        var node = nodes[i];

                        // contractors usually do not have a title
                        node.Title = formatTitle(node.Title);

                        // selected employee is green, others are blue
                        var buttonColor = (node.OktaId === request.OktaId) ? "btn-u" : "btn-u-blue";
                        
                        if (lastManager != null && lastManager !== node.Parent) {
                            employee += '</div></div></div><div class="team-arrow"></div>';
                        }

                        if (employee === "" || lastManager !== node.Parent) {
                            employee += '<div class="panel panel-dark-blue panel-flush">';
                        }

                        if (lastManager !== node.Parent) {
                            var panelHeading = '';
                            if (node.Parent in chart) {
                                var manager = chart[node.Parent];
                                panelHeading += '<i class="fa fa-arrow-up"></i> Reports to ' + manager.CommonName;
                            } else if (node.Title != null && node.Division != null && node.Peers === 0) {
                                panelHeading += '<i class="fa fa-university"></i> ' + node.Division + ' - ' + node.Title;
                            } else if (node.Title != null) {
                                panelHeading += '<i class="fa fa-university"></i> ' + node.Title;
                            } else if (node.Division != null) {
                                panelHeading += '<i class="fa fa-university"></i> ' + node.Division;
                            }
                            if (panelHeading !== '') {
                                employee += '<div class="panel-heading"><h3 class="panel-title">' + panelHeading + '</h3></div>';
                            }
                            employee += '<div class="panel-body"><div class="row">';
                        }

                        if (node.Division == null) {
                            node.Division = 'Division Not Available';
                        }

                        // prepare the button link and container
                        var url = window.environment.url + 'employee/details?OktaId=' + node.OktaId;
                        if (node.Peers === 0) {
                            employee += '<div class="col-md-12">';
                        } else if (node.Peers === 2) {
                            employee += '<div class="col-md-6 col-sm-6 col-xs-12">';
                        } else {
                            employee += '<div class="col-md-6 col-sm-6 col-xs-12">';
                        }

                        // build the button
                        employee += '<a href="' + url + '"';
                        employee += ' class="btn btn-block btn-u ' + buttonColor + '"';
                        employee += ' title="' + node.CommonName + '">';
                        employee += '<i class="fa fa-4x fa-user pull-left"></i>';
                        employee += '<strong>' + node.CommonName + '</strong>';
                        employee += '<span class="employee-division">' + node.Division + '</span>';
                        employee += '<span class="employee-title">' + node.Title + '</a></span>';
                        employee += '</div>';

                        lastManager = node.Parent;
                    }

                    $('div.team-chart').append(employee);
                }
            }, "json");

            $('#employee-team').data('populated', true);
        }
    });
}

;
/**
Wire your buttons, modals, etc, here.
**/
function initApplicationEvents() {

    $('.get-modal').on('click', function (e) {
        e.preventDefault();
        $.ajax({
            cache: false,
            type: "GET",
            url: $(this).attr("href"),
            success: function (data) {
                $("#modal-content").html(data);
                $("#modal").modal("show");
            }
        });
    });
    
};

// format as phone number
if (!String.prototype.FormatPhone) {
    String.prototype.FormatPhone = function () {
        var string = "" + this;

        string = string
            .replace('+1', '')
            .replace(/[^\d]/g, '');

        if (string.length > 10) {
            string = string.replace(/(\d{3})(\d{3})(\d{4})(\d{1})/, '($1) $2-$3 x $4');
        }
        else {
            string = string.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
        }

        return string;
    }
}
;

// init all captchas on the page (divs with captcha class)

function initApplicationReCaptcha() {

    jQuery('.captcha').each(function () {
        var id = jQuery(this).attr('id');
        var form = jQuery(this).parents('form');
        var widget = null;
        if (id !== '') {
            // initialize the widget
            widget = grecaptcha.render(id, {
                'sitekey': '6LeodQsTAAAAANOYDowD6vwOqWayy5pSpfO5wKdn',
                'theme': 'light'
            });
            // require captcha completion to submit
            jQuery(form).on('submit', function (e) {
                var response = grecaptcha.getResponse(widget);
                if (typeof response === 'undefined' || response === false || response === '') {
                    e.preventDefault();
                    e.stopPropagation();
                    if (false === jQuery('#' + id).parent().hasClass('captcha-invalid')) {
                        jQuery('#' + id).parent().addClass('captcha-invalid');
                    }
                }
            });
        }
    });
};;

function initApplicationSpamProtection() {
    
    jQuery('.m-lock').each(function () {      
        var value = jQuery(this).data('value');
        var label = jQuery(this).data('label');
        if (typeof value !== 'undefined' && value !== false && value !== '') {
            var actual = Base64.decode(value);
            if (typeof label === 'undefined' || label === false || label === '') {
                label = actual;
            }
            $(this).text(label).attr('href', 'mailto:' + actual);
        }
    });
    jQuery('.p-lock').each(function () {
        var value = jQuery(this).data('value');
        if (typeof value !== 'undefined' && value !== false && value !== '') {
            var actual = Base64.decode(value);
            $(this).text(actual.FormatPhone()).attr('href', 'tel:' + actual);
        }
    });

};
/**
* Tab Compactor manages tab overflow in bootstrap.
*/
var tabCompactorScheduler = null;

function initApplicationTabCompactor() {

    // setup handles
    tabCompactorScheduler = null;
    var tabs = $('.tab-compactor');
    var overflow = $(tabs).find('li.tab-compactor-overflow ul');
    var dropdown = $(tabs).find('li.tab-compactor-overflow > a');

    // remove active flag on all active links in the overflow
    $(dropdown).unbind().on('click', function () {
        $(this).parent().find('.active').removeClass('active');
    });

    // bind a click event to the overflow links to set active and then trigger a recheck of overflow
    $(tabs).find('li.tab-compactor-overflow ul').unbind().on('click', 'a', function () {
        
        $(this).addClass('active');
        $(overflow).children('li').insertBefore(tabs.children('li:last-child'));
        setTimeout(initApplicationTabCompactor, 1);
    });

    var tabsHeight = tabs.innerHeight();
    $(overflow).parent().show();

    // if the tabs break onto a new line
    var count;
    var children;
    if (tabsHeight >= 50) {
        while (tabsHeight > 50) {
            children = tabs.children('li:not(:last-child):not(.active)');
            if (children.length < 1) {
                children = tabs.children('li:not(:last-child)');
            }
             count = children.length;
            $(children[count - 1]).prependTo(overflow);
            var width = $(overflow).parent().width()-2;
            $(overflow).parent().css('margin-right', width + 'px');
            tabsHeight = tabs.innerHeight();
        }
    } else {
        // tabs do not break onto a new line, expand until all are shown or until they do break lines
        var collapsed = $(overflow).children('li');
        var passes = 0;
        count = $(collapsed).length;
        while (passes <= 20 && tabsHeight < 50 && count > 0) {

            if (tabs.children('li:last-child').not('active').length > 0) {
                $(collapsed[0]).insertBefore(tabs.children('li:last-child').not('active'));
            } else {
                $(collapsed[0]).insertBefore(tabs.children('li:last-child'));
            }

            tabsHeight = tabs.innerHeight();
            count = $(collapsed).length;
            passes++;
        }
        if (count < 1) {
            $(overflow).parent('li').hide();
        }
        if (tabsHeight > 50) { 
            initApplicationTabCompactor();
        }
    }

    // setup the overflow container and labels
    children = tabs.children('li:not(:last-child)');
    if (children.length < 1) {
        var newLabel = $(tabs).find('li.active').html() + ' <i class="fa fa-bars"></i>';

        $(tabs).find('li.tab-compactor-overflow > a').data('altered', true).html(newLabel);
        $(tabs).find('li.tab-compactor-overflow').addClass('pull-right').css('margin-right', '0px');
    } else {
        $(tabs).find('li.tab-compactor-overflow').removeClass('pull-right');
        $(tabs).find('li.tab-compactor-overflow > a').data('altered', false).html('More <i class="fa fa-bars"></i>');
    }

    // sort any shown tabs into their original display order
    $('.tab-compactor > li').sort(function (a, b) {
        return $(a).attr('data-sort') - $(b).attr('data-sort');
    }).appendTo('.tab-compactor');
    
}

// on window resize, trigger the compactor
$(window).on('resize', function () {
    if (tabCompactorScheduler !== null) {
        clearTimeout(tabCompactorScheduler);
    }
    setTimeout(initApplicationTabCompactor,250);
});;
/**
* Place custom UI/UX adjustments here.
*/
function initApplicationUX() {

    // make each col the same height as their parent row div
    $('.col-height-fix').each(function () {
        var parentHeight = $(this).parent().innerHeight();
        $(this).parent().css('position', 'relative');
        $(this).css('min-height', parentHeight + 'px');
    });
    
    $('.btn-sticky-bottom').each(function () {
        var parentHeight = $(this).parent().innerHeight();
        var top = $(this).position().top;
        var margin = (parentHeight - top) - $(this).outerHeight();
        $(this).css('margin-top', margin + 'px');
    });

    $('#orgJump').on('change', function (e) {
        e.preventDefault();
        var target = $(this).val();
        switchAccordian(target);
    });

    $('a.orgShortcut').on('click', function (e) {
        e.preventDefault();
        var target = $(this).attr('href');
        switchAccordian(target);
    });

}

function switchAccordian(target, allowScroll) {

    if (allowScroll === undefined) {
        allowScroll = true;
    }
    if (target !== '') {
        if (allowScroll === true) {
            window.location.hash = target;
        }
        $('.panel-collapse.in').each(function () {
            $(this).removeClass("in").addClass("collapse");
            $(this).prev('.panel-heading').find('i.indicator').removeClass("fa-chevron-down").addClass("fa-chevron-up");
        });
        $(target).removeClass("collapse").addClass("in");
        $(target).prev('.panel-heading').find('i.indicator').removeClass("fa-chevron-up").addClass("fa-chevron-down");
        if (allowScroll === true) {
            $(window).scrollTo(target, 0, { "offset": -200 });
        }
    } else {
        $('.panel-collapse.collapse').each(function () {
            $(this).removeClass("collapse").addClass("in");
            $(this).prev('.panel-heading').find('i.indicator').removeClass("fa-chevron-up").addClass("fa-chevron-down");
        });
        window.location.hash = null;
    }
}

function toggleAccordianIndicator(e) {
    var target = e;
    if (e.hasOwnProperty("target")) {
        target = e.target;
    }
    if ($(target).hasClass("in") === true) {
        $(target).prev('.panel-heading').find('i.indicator').removeClass("fa-chevron-up").addClass("fa-chevron-down");
    } else {
        $(target).prev('.panel-heading').find('i.indicator').removeClass("fa-chevron-down").addClass("fa-chevron-up");
    }
        
}
$('.with-indicator').on('hidden.bs.collapse', toggleAccordianIndicator);
$('.with-indicator').on('shown.bs.collapse', toggleAccordianIndicator);

;
