var initialTime = new Date();
var requestResponseTime = 0;
var timeDifference = 0;
var serverTime = null;
var dstOffset = null;

$(document).ready(function () {
    setTime();
    dstOffset = getDstOffset();
    setInterval(function () {
        var time = new Date().getTime() + timeDifference;
        var date = new Date(time);
        moment.lang('de');
        var format = 'dddd, DD.MM.YYYY HH:mm:ss';
        var newDate = moment(time).zone(dstOffset).format(format);
//        var newDate = moment(time).zone(-120).format(format); // dst
//        var newDate = moment(time).zone(-60).format(format);
        $('#serverTime').html(isNaN(date.getTime()) ? "" : newDate);
    }, 500);
});

function setTime() {
    $.ajax({
        type: "GET",
        url: adb.utils.GetAPIUrl() + "ServerTime/GetServerTime",
        success: function (data) {

            requestResponseTime = new Date().getTime() - initialTime.getTime();

            serverTime = new Date(Date.parse(data.serverTime));

            timeDifference = (serverTime.getTime() - (requestResponseTime / 2)) - initialTime.getTime();
        },
        async: false
    });
}

function getDstOffset() {
    return (initialTime.dst()) ? -120 : -60;
}

Date.prototype.stdTimezoneOffset = function() {
    var jan = new Date(this.getFullYear(), 0, 1);
    var jul = new Date(this.getFullYear(), 6, 1);
    return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
};

Date.prototype.dst = function() {
    return this.getTimezoneOffset() < this.stdTimezoneOffset();
};
;
var App = App || {};

$('document').ready(function () {
    if (typeof App.FormValidatorHandler !== 'undefined') {
        var validator = new App.FormValidatorHandler();
        validator.Init();
    }

    if (typeof App.LogService !== 'undefined') {
        var logService = new App.LogService();
        $(logService.settings.logViewClass).each(function () {
            logService.initViewEvent($(this));
        });

        $(logService.settings.logClickClass).each(function () {
            logService.initClickEvent($(this));
        });
    }

    // home index carousel
    setCarouselHeight('#carousel-text');

    function setCarouselHeight(id) {
        var slideHeight = [];
        $(id + ' .item').each(function () {
            // add all slide heights to an array
            slideHeight.push($(this).height());
        });

        // find the tallest item
        max = Math.max.apply(null, slideHeight);

        // set the slide's height
        $(id + ' .carousel-text-content').each(function () {
            $(this).css('height', max + 'px');
        });
    }

    var random = Math.floor(Math.random() * $(".carousel-text-item").length);
    $(".carousel-text-item").removeClass("active");
    $(".carousel-text-item").eq(random).addClass("active");

    $('#carousel-text').carousel({
        interval: 10000
    })

    // back2top button
    $(window).scroll(function () {
        //console.log('is call scroll');
        if ($(this).scrollTop() === 0) {
            $('#adb-btn-back-to-top').fadeOut();
        } else if (isVisible($('#footer'))) {
            $('#adb-btn-back-to-top')
                .css('position', 'fixed')
                .css('bottom', '236px');
        } else {
            $('#adb-btn-back-to-top')
                .css('position', 'fixed')
                .css('bottom', '20px')
                .fadeIn();
        }
    });

    // initialize date time picker
    $('.datetimepicker').datetimepicker({
        locale: 'de'
    });

    // initialize date time picker
    $('.datetimepicker-month-year').datetimepicker({
        locale: 'de',
        viewMode: 'years',
        format: 'MM/YYYY'
    });

    if (document.cookie.indexOf('hide_adbs_stoerer=1') != -1) {
        jQuery('#adbs_stoerer').hide();
    }
    else {
        jQuery('#adbs_stoerer').prependTo('body');
        jQuery('#adbs_stoerer_close').show();
    }


}); // document.ready

function SetTac() {
    $.ajax({
        type: "POST",
        url: adb.utils.GetAPIUrl() + "Security/SetTrueTac",
        success: function (result) {
            if (result.Status === globals.servicecodes.Error) OnServerResponseError(result);
        }
    });
}

function SetPwChanged() {
    $.ajax({
        type: "POST",
        url: adb.utils.GetAPIUrl() + "Security/SetTruePwChanged",
        success: function (result) {
            if (result.Status == globals.servicecodes.Error) OnServerResponseError(result);
        }
    });
}

$(function () {
    // toggle bootstrap accordion icons
    $('#accordion, #accordionb, #accordionc').on('hidden.bs.collapse', function (e) {
        $(e.target).prev().find('.fa-chevron-down').toggleClass('fa-chevron-down fa-chevron-right')
    })

    $('#accordion, #accordionb, #accordionc').on('shown.bs.collapse', function (e) {
        $(e.target).prev().find('.fa-chevron-right').toggleClass('fa-chevron-right fa-chevron-down')
    })
});

function switchViewByUserRole(role) {
    $.ajax({
        type: "POST",
        url: "/Security/SwitchViewByUserRole?role=" + role,
        success: function(retUrl) {
            window.location.replace(retUrl);
        }
    });
}

// before 20180319 adb neu responsive Korr. vor LIVE #155934725 (35) Button Drucken:  function print(selector) ...

function adb_SetLog(text, detail) {
    $.ajax({
        type: "GET",
        url: adb.utils.GetAPIUrl() + "mainLogger/setLogInfo?bereich=" + text + '_' + detail + '_' + navigator.userAgent,
        success: function(data) {}
    });
}

function checkboxSingleSelect(checkBoxName) {
    // only allow one customer type checkbox (edit, create view)
    $("input[name = checkBoxName]:checkbox").on('click',
        function() {
            // in the handler, 'this' refers to the box clicked on
            var $box = $(this);
            if ($box.is(":checked")) {
                // disable all
                $("input[name = checkBoxName]:checkbox").removeAttr('checked');
                // the name of the box is retrieved using the .attr() method
                // as it is assumed and expected to be immutable
                var item = "input:checkbox[value='" + $box[0].value + "']";
                // recheck selected one
                $(item).prop('checked', true);

            } else {
                $box.removeAttr('checked');
            }
        });
}

// is element visible f.e. back2top button
function isVisible(elment) {
    var vpH = $(window).height(), // Viewport Height
        st = $(window).scrollTop(), // Scroll Top
        y = $(elment).offset().top;

    return y <= (vpH + st);
}

// back2top button (called from @ADBHelpers.AdbBtnBack2Top()) - behaviour
function back2Top() {
    $('body,html').animate({ scrollTop: 0 }, "easeOutSine");
}

// bootstrap 3 modal dialog scrollbar bug fix
(function($) {
    var widthBeforeModal = $(window).width();
    var widthAfterModal = 0;
    var scrollBarWidth = 0;
    $(document)
        .on( 'hidden.bs.modal', '.modal', function() {
            $('#footer').css('padding-right', '0');
            $('#adb-btn-back-to-top, #btn-tenderer-profiles-clone').css('margin-right', '0');
            //$('#banner').css('right', '30px');
            
        })
        .on( 'show.bs.modal', '.modal', function() {
            widthAfterModal = $(window).width();
            scrollBarWidth = widthBeforeModal - widthAfterModal;
            $('#footer').css('padding-right', scrollBarWidth + "px");
            $('#adb-btn-back-to-top, #btn-tenderer-profiles-clone').css('margin-right', scrollBarWidth + "px");
            //$('#banner').css('right', 30 + scrollBarWidth + "px");
        });
})(window.jQuery);
 
function BuildBootStrapAlert(_messageLevel, _message, _id) {
    

    window.scrollTo(0, 0);
    var selector = _id === undefined ? '#adb-alert' : _id;
    $(selector).empty();
    $(selector).attr( "style", "");

    $(selector).html(
        '<div class="alert-popup-message">' +
        '<div class="alert alert-' +
        _messageLevel.toLowerCase() +
        '">' +
        _message +
        '</div>' +
        '</div>'
    ).fadeOut(10000);
}

// register all bootstrap 3 tooltips
$(function () {
    $('[data-toggle="tooltip"]').tooltip()
});

// switch bootstrap tabs
 function switchBsTab(tabid){
    $('.nav-tabs a[href="#' + tabid + '"]').tab('show');
}

var allowedFileExtensions = ".doc, .xls, .pdf, .rar, .xml, .zip, .bmp, .jpeg, .jpg, .png, .txt, .csv," +
    ".dta, .dtn, .onlb, .onlv, .docx, .xlsx, .odt, .ods, .dwf, .dwg, .dxf, .d81, .d82, .d83, .d84, .d85," +
    ".d86, .d88, .d89, .P81, .P83, .P84, .P85, .X80, .X81, .X82, .X83, .X84, .X85, .X86, .X87, .X89, .X83Z, "+
    ".X84Z, .X86ZR, .X86ZE, .X31, .X52, .X93, .X94, .X96, .X97, .shx, .ctb";

// number formatter (requires jquery)
(function ($) {
    $.fn.numberFormatter = function () {
        this.each(function (i) {
            $(this).change(function (e) {
                var positive = true;
                if (isNaN(parseFloat(this.value))) return;
                if (parseFloat(this.value) < 0)
                    positive = false;
                this.value = this.value.replace(/[^\,\d]/g, ""); // remove dot of thousend seperator
                this.value = this.value.replace(",", "."); // replace comma with dot

                if (!positive)
                    this.value = this.value * -1;

                this.value = parseFloat(this.value).toFixed(2); // round

                this.value = this.value.replace(".", ","); // show dot as comma

            });
        });
        return this;
    }
})(jQuery);

// format number for display in input text boxes
(function ($) {
    $.fn.numberFormatter = function () {
        this.each(function (i) {
            $(this).change(function (e) {

                var positive = true;

                if (isNaN(parseFloat(this.value))) return;

                if (parseFloat(this.value) < 0)
                    positive = false;

                this.value = this.value.replace(/[^\,\d]/g, ""); // remove dot of thousend seperator
                this.value = this.value.replace(",", "."); // replace comma with dot

                if (!positive)
                    this.value = this.value * -1;

                this.value = parseFloat(this.value).toFixed(2); // round

                this.value = this.value.replace(".", ","); // replace dot with comma

            });
        });
        return this;
    }
})(jQuery);

// format number for calculating
function FormatNumber(val) {
    if ((val !== null && val !== 0)) {

        if (isNaN(parseFloat(val))) return;

        val = (val.indexOf(",") === -1) ? val : val.replace(/[^\,\-\d]/g, ""); // remove dot of thousend seperator
        val = val.replace(',', '.'); // replace comma with dot

        return parseFloat(val);

    }
    else {
        return 0;
    }
}

function createDesktopNotification(title, msg, icon) {
    if (!("Notification" in window)) {
        // alert("This browser does not support desktop notification");
        return;
    }

    var options = {
        title: title,
        body: msg,
        icon: icon,
        dir : "auto"
    };

    if (Notification.permission === "granted") {
        var notification = new Notification(title,options);
    }
    else if (Notification.permission !== 'denied') {
        Notification.requestPermission(function (permission) {
            if (!('permission' in Notification)) {
                Notification.permission = permission;
            }

            if (permission === "granted") {
                var notification = new Notification(msg,options);
            }
        });
    }
}


function SubmitFormSelection() {
    var radios = document.getElementsByName('selectedForm'),
        value = '';
    for (var i = radios.length; i--;) {
        if (radios[i].checked) {
            value = radios[i].value;
            break;
        }
    }
    window.location.href = '/PrincipalArea/TenderInput' + value + '/CoverSheet'
}

$(function () {
    $('#61, #8, #62, #63, #32').change(function () {
        if ($('#61').is(':checked')
            || $('#8').is(':checked')
            || $('#62').is(':checked')
            || $('#63').is(':checked')
            || $('#32').is(':checked')) {
            $('#weiter_button').attr('disabled', false);
        } else {
            $('#weiter_button').attr('disabled', true);
        }
    });
});

$(function () {
    //----- OPEN
    $(function () {
        var popupTriggers = $('[data-popup-open]');

        popupTriggers.on('click', function (e) {
            var targeted_popup_class = $(this).attr('data-popup-open');
            $('[data-popup="' + targeted_popup_class + '"]').toggle(350);

            e.preventDefault();
        });

        popupTriggers.each(function () {
            var targeted_popup_class = $(this).attr('data-popup-open');
            $('[data-popup="' + targeted_popup_class + '"]').fadeIn(350);
        });
    });

    //----- CLOSE
    $('[data-popup-close]').on('click', function (e) {
        var targeted_popup_class = jQuery(this).attr('data-popup-close');
        $('[data-popup="' + targeted_popup_class + '"]').fadeOut(350);

        e.preventDefault();

    });
});;
