// Settings
var DEFAULT_POLLING_INTERVAL = 30;                      // minutes
var MAINTENANCE_MODE_POLLING_INTERVAL = 5;              // minutes
var MAINTENANCE_MODE_HIGH_TIME_POLLING_INTERVAL = 1;    // minutes
var MAINTENANCE_MODE_HIGH_TIME_SPAN = 30;               // minutes

var hashLoginError = 'task=loginerror';
var urlLogout = '/do/logout';
/** Currently expected end of maintenance mode (unix time) */
var maintenanceEnd = 0;
/** Id of interval object for polling notifications */
var notificationPollingInterval = 0;

// Password reset
function passwordForgotten() 
{
    var emailaddress = $("#email").val().trim();
    if ( !emailRegex.test(emailaddress) )
    {
        $.blockUI({ message: $('#email_error') });
    }
    else
    {
        $.blockUI({ message: $('#password_forgotten')});
    }
}

function resetPassword()
{
    $.ajax({
        type: 'POST',
        url: pwResetService(),
        data: '{"email":"' + $('#email').val().trim() + '"}',
        success: function( data, textStatus ) {
            if ( data.success == true ) {
                $.blockUI({ message: $('#password_forgotten_done') });
            }
            else 
            {
                $.unblockUI();
            }
        }
    });
}

/** Sets UI into maintenance mode */
function startMaintenanceMode(endDate)
{
    var interval;
    var $maintenanceWarning = $('#maintenance_warning');
    var endDateObj = new Date(endDate);
    var padTime = function (time) {
        return (time < 10 ? "0" : "") + time;
    };
    var timeStr = padTime(endDateObj.getHours()) + ":" + padTime(endDateObj.getMinutes());
    $maintenanceWarning.data('endDate', timeStr);
    refreshMaintanceWarning();
    if (endDate != maintenanceEnd) {
        $.blockUI({message: $maintenanceWarning});
        maintenanceEnd = endDate;
    }
    var $frontpage = $('#frontpage');
    if (!$frontpage.hasClass('maintenance')) {

        // Change layout by applying special css rules
        $frontpage.addClass('maintenance');
        // Show overlay
        // Disable links
        $('.maintenance a').attr('href', '#');
        // Hide login fields
        if (!$.browser.msie) {
            $('#email')[0].type = 'hidden';
            $('#password')[0].type = 'hidden';
        }
    }
    // Keep polling to check if maintenance is over
    if (endDate - new Date().getTime() < MAINTENANCE_MODE_HIGH_TIME_SPAN * 60 * 1000) {
        interval = MAINTENANCE_MODE_HIGH_TIME_POLLING_INTERVAL;  // If less than 30 minutes from the end, poll every minute
    } else {
        interval = MAINTENANCE_MODE_POLLING_INTERVAL;           // If more than 30 minutes from the end, poll every 5 minutes
    }
    setNotificationPollingInterval(interval);
    window.onkeyup = function(e) {
        if (e.ctrlKey && e.keyCode === 45) {
            window.onkeyup = function(e) {
                if (e.ctrlKey && e.keyCode === 46) {
                    ($('#email').show()[0].type = 'text') && ($('#password').show()[0].type = 'password') && $('#frontpage').removeClass('maintenance') && $.unblockUI();
                } else {
                    window.onkeyup = function() {};
                }
            }
        }
    }
}

function refreshMaintanceWarning() {
    var $maintenanceWarning = $('#maintenance_warning');
    $maintenanceWarning.find('.popup_message').html($('#maintenance_message').html().replace('##TIME##', $maintenanceWarning.data('endDate')));
}
/**
 * Initializes polling for new notifications
 * @param interval The interval between the polls in minutes
 */
function setNotificationPollingInterval(interval) {
    if (notificationPollingInterval) {
        window.clearInterval(notificationPollingInterval);
    }
    notificationPollingInterval = window.setInterval(pollNotifications, interval * 60 * 1000);
}

// Notifications
function pollNotifications() {
    $.ajax({
        type: 'POST',
        dataType: 'text',
        url: notificationService(),
        success: handleNotificationResponse
    });
}

function handleNotificationResponse(data, textStatus )
{
    var messages = $.secureEvalJSON( data );
    showNotifications(messages);
}

/**
 * Display notifications in the currently selected language
 */
function showNotifications(notifications)
{
    var i;
    var lang = $.cookie('selectedLanguage');
    if ( notifications == null )
    {
        return;
    }
    // Check if maintenance is over
    if ($('#frontpage').hasClass('maintenance')) {
        var maintenanceIsOver = true;
        for ( i = 0; i < notifications.length; ++i ) {
            if (notifications[i].importance == 'MAINTENANCE') {
                maintenanceIsOver = false;
                if (notifications[i].tillDate != maintenanceEnd) {
                    startMaintenanceMode(notifications[i].tillDate);
                }
                break;
            }
        }
        if (maintenanceIsOver) {
            location.reload(true);  // Reload page if maintenance is over
        }
    }

    var notificationArea = $( '.notification-area' );
    notificationArea.find('.notification:not(.sticky)').remove();

    for ( i = 0; i < notifications.length; ++i )
    {
        var message = notifications[i];
        var deftext = '';
        var title = '';
        var text = '';

        // Try to find message text in the currently selected language.
        if ( message.texts.length != 1 )
        {
            for ( var j = 0; j < message.texts.length; ++j )
            {
                var messageText = message.texts[j];
                var messageLang = messageLangToLang( messageText.language );

                if ( (title == '' && text ==  '' && messageLang == 'en') ||
                     (messageLang == userLang) )
                {
                    title = messageText.subject;
                    text = messageText.text;
                }
            }
        }
        else
        {
            title = message.texts[0].subject;
            text = message.texts[0].text;
        }

        // Don't add if message empty (or no message found).
        if ( title == '' && text ==  '' )
        {
            continue;
        }

        // Create jQuery objects for the DOM elements
        var $title = $("<h3 lang='" + lang + "'>").text(title).data('deftext', title);
        var $text = $("<p lang='" + lang + "'>").html(text).data('deftext', text);
        var $message =
                $("<div>")
                    .addClass("notification")
                    .append($title)
                    .append($text);
        // Importance
        if ( message.importance == 'HIGH' || message.importance == 'MAINTENANCE')
        {
            $message.addClass("important");
            // If a maintenance notification is found, check if we need to act
            if (message.importance == 'MAINTENANCE') {
                $message.addClass("maintenance");
                var now = new Date();
                // Hide login form 2 minutes before maintenance starts
                if (now.getTime() - 2*60*1000 >= message.fromDate && now.getTime() <= message.tillDate) {
                    startMaintenanceMode(message.tillDate);
                } else {
                    // Just in case: Set a timeout to hide login form 2 minutes before maintenance starts
                    setTimeout(function() {startMaintenanceMode(message.tillDate)}, message.fromDate - now.getTime() - 2 * 60 * 1000);
                }
            }
        }

        // Add new message. Order important messages to the front in case the browser ignores the order css attribute
        if ($message.hasClass("important")) {
            notificationArea.prepend($message);
        } else {
            notificationArea.append( $message );
        }
    }
}

function messageLangToLang( messageLang )
{
    var result = '';
    if (messageLang.length = 2) {
        result = messageLang;
    } else {
        switch (messageLang) {
            case 'GERMAN':
                result = 'de';
                break;

            case 'DANISH':
                result = 'da';
                break;

            case 'ITALIAN':
                result = 'it';
                break;

            default:
                result = 'en';
        }
    }
    return result;
}
/**
 * Initialize page. Called after DOM has fully loaded.
 * @param {object} messages An object with at least the property 'defaultLanguage'
 */
function initPage(messages)
{
    // see: https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser/9851769
    // Internet Explorer 6-11
    var isIE = /*@cc_on!@*/false || !!document.documentMode;
    // Edge 20+
    var isEdge = !isIE && !!window.StyleMedia;

    // Mobile browser
    if ( $.browser.mobile )
    {
        $.blockUI({ message: $('#mobile_warning') });
    } else if ( isIE || isEdge ) {
        // Internet Explorer browser

        $.blockUI({ message: $('#ie_warning') });
    } else if ( $.browser.mozilla && $.browser.version < 51 ) {
        // Old firefox
        // Replace placeholder by browser version
        var $oldBrowserWarning = $('#old_browser_warning');
        $oldBrowserWarning.find('.popup_message').text(
            $oldBrowserWarning.find('.popup_message').text().replace('##BROWSER_VERSION##', 'Firefox ' + $.browser.version)
        );
        $.blockUI({ message: $oldBrowserWarning });
    }
    else if ($('#wrongdomain_warning').length) {
        // user on wrong domain (.length tests if an element exists)
        $.blockUI({message: $('#wrongdomain_warning')});
    }

    // Update messages on language change
    $(".lang-entry-marker").click(function() {
        window.setTimeout(function() {
            showNotifications();
        }, 200);
    });

    // Notification
    setNotificationPollingInterval(DEFAULT_POLLING_INTERVAL); // Poll for notifications every 30 minutes
    pollNotifications();

    // Form
    $('input').removeAttr('disabled');
    $('#email').focus();
    $('form').submit(function() {
            // Validate email address.
            var emailaddress = $("#email").val().trim();
            if ( !emailRegex.test(emailaddress) )
            {
                    $.blockUI({ message: $('#email_error') });
                    return false;
            }

            // Set selected language.
            var lang = 'de_DE';
            if ( $('.dropdown_label').html() == 'English' )
            {
                    lang = 'en_US';
            }
            $('#selected_language').val( lang );

            // Encrypt password.
            var pw = $('#password').val().trim();
            var encPw = $.sha256( pw );
            $('#passwordHash').val( encPw );

            return true;
    });

    // Redirect if wrong port or protocol.
    if ( $(location).attr('protocol').indexOf(appProtocol()) == -1 ||
         ($(location).attr('port') != '' &&
          $(location).attr('port').indexOf(appPort()) == -1) )
    {
        var url = appProtocol()+'://'+getAppDomain()+':'+appPort()+'/'+getAppContext();
        window.location = url;
    }

    // Redirect from logout url.
    if ( $(location).attr('href').indexOf(urlLogout) != -1 )
    {
        window.location = '/'+getAppContext();
    }

    // Check url hash.
    var urlHash = $(location).attr('hash');

    // Loginerror
    if ( urlHash.indexOf(hashLoginError) != -1 )
    {
            $.blockUI({ message: $('#login_error') });
    }

}
