if (!window['UIM']) { window['UIM'] = {}; }
UIM.Fips = {};
UIM.Fips.checkLoadedTimeoutInitial = 100;
UIM.Fips.checkLoadedTimeoutUsual   = 500;
UIM.Fips.previousOnload            = null;
UIM.Fips.fieldnameUsername         = 'username';
UIM.Fips.fieldnamePassword         = 'password';
UIM.Fips.initialized               = false;
UIM.Fips.init = function() {
    if (UIM.Fips.initialized) { return; }
    UIM.Fips.previousOnload = window.onload;
    window.onload = function() {
        if (UIM.Fips.previousOnload) { UIM.Fips.previousOnload(); }
        UIM.Fips.previousOnload = null;
        UIM.Fips.run();
    };
    UIM.Fips.initialized = true;
    if (document.readyState == 'complete') { window.onload(); }
};
UIM.Fips.run = function() {
    UIM.Fips.loadFipsScript();
    UIM.Fips.prepareCheckLoaded(true);
};
UIM.Fips.loadFipsScript = function() {
    var head = document.getElementsByTagName('head')[0];
    var js   = document.createElement('script');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src',  '//fips.uimserv.net/ngvar.js');
    head.insertBefore(js, head.firstChild);
};
UIM.Fips.prepareCheckLoaded = function(initial) {
    window.setTimeout(
        UIM.Fips.checkLoaded,
        initial ? UIM.Fips.checkLoadedTimeoutInitial : UIM.Fips.checkLoadedTimeoutUsual
    );
};
UIM.Fips.checkLoaded = function() {
    if (typeof(window['UI_nguserid']) == 'undefined') {
        UIM.Fips.prepareCheckLoaded();
    } else {
        UIM.Fips.modifyLoginForms();
    }
};
UIM.Fips.modifyLoginForms = function() {
    var lfs = UIM.Fips.getLoginForms();
    for (var i=0; i<lfs.length; i++) {
        var lf = lfs[i];
        if (!lf.elements['uinguserid']) {
            UIM.Fips.appendNgUserIdField(lf);
        }
        lf.elements['uinguserid'].value = UI_nguserid;
    }
};
UIM.Fips.getLoginForms = function() {
    var lfs = [];
    for (var i=0; i<document.forms.length; i++) {
        var form = document.forms[i];
        if (form[UIM.Fips.fieldnameUsername] && form[UIM.Fips.fieldnamePassword]) {
            lfs[lfs.length] = form;
        }
    }
    return lfs;
};
UIM.Fips.appendNgUserIdField = function(form) {
    var input;
    if (document.all && !window.opera) {
        input = document.createElement('<input name="uinguserid" type="hidden"/>');
    } else {
        input = document.createElement('input');
        input.setAttribute('name', 'uinguserid');
        input.setAttribute('type', 'hidden');
    }
    form.appendChild(input);
};

UIM.Fips.init();

