/* Minification failed. Returning unminified contents.
(1523,74-75): run-time error JS1195: Expected expression: >
(1523,106-107): run-time error JS1004: Expected ';': )
(1529,5-6): run-time error JS1002: Syntax error: }
(1531,40-41): run-time error JS1195: Expected expression: )
(1531,42-43): run-time error JS1004: Expected ';': {
(1545,78-79): run-time error JS1195: Expected expression: >
(1545,110-111): run-time error JS1004: Expected ';': )
(1549,10-11): run-time error JS1004: Expected ';': )
(1552,33-34): run-time error JS1195: Expected expression: )
(1552,35-36): run-time error JS1004: Expected ';': {
(1595,56-57): run-time error JS1195: Expected expression: >
(1595,88-89): run-time error JS1004: Expected ';': )
(1596,5-6): run-time error JS1002: Syntax error: }
(1598,51-52): run-time error JS1004: Expected ';': {
(1770,41-42): run-time error JS1195: Expected expression: >
(1770,117-118): run-time error JS1004: Expected ';': )
(1771,9-13): run-time error JS1034: Unmatched 'else'; no 'if' defined: else
(1775,40-41): run-time error JS1195: Expected expression: )
(1775,42-43): run-time error JS1004: Expected ';': {
(1795,62-63): run-time error JS1195: Expected expression: >
(1795,94-95): run-time error JS1004: Expected ';': )
(1795,117-125): run-time error JS1197: Too many errors. The file might not be a JavaScript file: minMonth
(1794,31-42): run-time error JS1301: End of file encountered before function is properly closed: function ()
(1795,205-206): run-time error JS1004: Expected ';': )
(1795,206-207): run-time error JS1197: Too many errors. The file might not be a JavaScript file: ;
(1777,13-113): run-time error JS1018: 'return' statement outside of function: return _this.valuesGEL[_this.valuesGEL.length - 1].Flow / _this.values[_this.values.length - 1].Flow
(1603,9-65): run-time error JS1018: 'return' statement outside of function: return number.toFixed(fixed).toString().replace("-", "")
 */

var gridFloatBreakpoint = 1200;
var gridLgMin = 1200;

function debounce (func, threshold, execAsap) {
    var timeout;

    return function debounced () {
        var obj = this, args = arguments;
        function delayed () {
            if (!execAsap)
                func.apply(obj, args);
            timeout = null;
        };

        if (timeout)
            clearTimeout(timeout);
        else if (execAsap)
            func.apply(obj, args);

        timeout = setTimeout(delayed, threshold || 100);
    };
};

$.fn.extend({
    animateCss: function (animationName, callback) {
        var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
        this.addClass('animated ' + animationName).one(
            animationEnd, function(){
                $(this).removeClass('animated ' + animationName);
                if(typeof(callback) === 'function'){
                    callback.call(this);
                }
            });
        return this;
    }
});

jQuery.fn.slickResponsive = function(slickOptions) {
    var $o = $(this[0]);
    var slickInitFn = function(){
        $o.slick(slickOptions);
    };
    slickInitFn();
    $(window).on('resize orientationchange', debounce(function() {
        $o.slick('unslick');
        slickInitFn();
        $o.slick('resize');
    }, 200));
    return this;
};

/*
function showNextCurrency(){
    if($("body").hasClass('offcanvas-stop-scrolling')){
        return;//causes flickering when offcanvas menu is open
    }
    var $active = $('.splash-calculator-currency-box.active');
    var $next = $active.next('.splash-calculator-currency-box');
    if(!$next.length){
        //start again
        $next = $active.parent().find('.splash-calculator-currency-box:first-child');
    }
    $active.addClass('deactivating');
    $active.find('>*').animateCss('flipInY', function(){
        $active.removeClass('active deactivating');
    });
    $next.addClass('activating');
    $next.find('>*').animateCss('flipInY', function(){
        $next.removeClass('activating').addClass('active');
    });
};
*/
function showNextCurrency(){
    if($("body").hasClass('offcanvas-stop-scrolling')){
        return;//causes flickering when offcanvas menu is open
    }
    var $active = $('.header-calculator-currency-box.active');
    var $next = $active.next('.header-calculator-currency-box');
    if(!$next.length){
        //start again
        $next = $active.parent().find('.header-calculator-currency-box:first-child');
    }
    $active.addClass('deactivating');
    $active.find('>*').animateCss('flipInY', function(){
        $active.removeClass('active deactivating');
    });
    $next.addClass('activating');
    $next.find('>*').animateCss('flipInY', function(){
        $next.removeClass('activating').addClass('active');
    });
}

function trunk8ultimate(selector, lines, callback){
    setTimeout(function(){
        $(selector).trunk8({ lines: lines });
        if(typeof(callback) !== 'undefined'){
            callback.call(window);
        }
    }, 0);
    $(window).on('resize orientationchange', function() {
        setTimeout(function(){
            $(selector).trunk8({ lines: lines });
            if(typeof(callback) !== 'undefined'){
                callback.call(window);
            }
        }, 0);
    });
};


function openOffcanvas(){
    $(".navbar-offcanvas").addClass("in navbar-offcanvas-transform");
    $(".navbar-toggle").addClass("is-open");
    $("html").addClass("html-noscroll");
    $("body").addClass("offcanvas-stop-scrolling");
    $('.header__search').addClass('expanded');
    //also pause the slider, otherwise it will get very large
    $('.home-slider').slick('slickPause');
};
function closeOffcanvas() {
    setTimeout(function () {
        $('.header__search').removeClass('expanded');
        $(".navbar-offcanvas").removeClass("in navbar-offcanvas-transform");
        $(".navbar-toggle").removeClass("is-open");
        $("html").removeClass("html-noscroll");
        $("body").removeClass("offcanvas-stop-scrolling");
        //also unpause the slider
        $('.home-slider').slick('slickPlay');
        
    }, 0);
};
function isOffcanvasOpen(){
    return $(".navbar-offcanvas").hasClass("in");
}
function toggleOffcanvas(){
    isOffcanvasOpen() ? closeOffcanvas() : openOffcanvas();
}
/*$(".navbar-offcanvas").click(function(e){
    if($(e.currentTarget).is($(e.target))){
        closeOffcanvas();
    }
});*/
$(".navbar-offcanvas-close-btn").click(function(e){
    closeOffcanvas();
});



function openUbermenu(){
    $('.uber-menu').addClass('in');
    $('body').addClass('uber-menu-open');
};
function closeUbermenu(){
    $('.uber-menu').removeClass('in');
    $('body').removeClass('uber-menu-open');
};
function toggleUbermenu(){
    if($('.uber-menu').hasClass('in')){
        closeUbermenu();
    } else {
        openUbermenu();
    }
};



function customDropdown() {
    $('.js-select-trigger').on('click', function(e) {console.log(5);
        e.preventDefault();
        if($(this).parents('.select-wrapper').hasClass('open')){
            var jsp = $(this).parents('.select-wrapper').find('.select-results').data('jsp');
            if(jsp){
                jsp.destroy();
            }
            $(this).parents('.select-wrapper').removeClass('open');
            $(this).siblings('.js-select-results').stop().slideToggle(200);
        } else {
            $(this).parents('.select-wrapper').addClass('open');
            $(this).siblings('.js-select-results').stop().slideToggle(200);
        }
    });
    $("body").on('click', function(e){
        var $parSelectWrapper = $(e.target).parents('.select-wrapper');
        $('.select-wrapper').each(function(i, sw){
            //don't close select-wrappers that are parenting the clicked element
            if($parSelectWrapper.length > 0 && $parSelectWrapper[0].isSameNode(sw)){
                return;
            }
            //only run this [auto-closing] code on opened select wrappers
            if($(sw).hasClass('open')){
                var jsp = $(sw).find('.select-results').data('jsp');
                if(jsp){
                    jsp.destroy();
                }
                $(sw).find('.js-select-results').hide();
                $(sw).removeClass('open');
            }
        });
    });
};

$('.js-dropdown-trigger').on('click', function () {
    var _trigger = $(this);
    var _results = $(this).siblings('.js-dropdown-results');
    _trigger.parent().toggleClass('open');
    _results.stop().slideToggle();
    $('.js-dropdown-trigger').not(_trigger).parent().removeClass('open');
    $('.js-dropdown-results').not(_results).slideUp();
    return false;
});


window.initCustomRangeSliders = function(){
    $(".custom-range-slider:not(.initialized)").each(function(i, tws_cont){
        $(tws_cont).addClass('initialized');
        $('<div class="custom-range-slider-in"></div>').appendTo($(tws_cont));
        var sliderDiv = $(tws_cont).find(".custom-range-slider-in")[0];
        var $input = $(tws_cont).find(".custom-range-slider-value");
        //
        var config = {
            'min': 0, 'max': 100, 'start': 3, 'step': 1, 'prefix': '', 'suffix': '',
            'display' : false, 'two-way-display' : false, 'tooltips' : true
        };
        var configAttrs = {
            'start': parseInt($input.val() || config['start']),
            'min': parseInt($(tws_cont).attr("data-min") || config['min']),
            'max': parseInt($(tws_cont).attr("data-max") || config['max']),
            'step': parseInt($(tws_cont).attr("data-step") || config['step']),
            'prefix': $(tws_cont).attr("data-prefix") || config['prefix'],
            'suffix': $(tws_cont).attr("data-suffix") || config['suffix'],
            'display': $(tws_cont).attr("data-display") || config['display'],
            'two-way-display': $(tws_cont).attr("data-two-way-display") || config['two-way-display'],
            'tooltips': ($(tws_cont).attr("data-tooltips") || config['tooltips'].toString()) == 'true'
        };
        //take the defaults config object and fill with found values from data attributes
        for(var icn in Object.keys(config)){
            var configName = Object.keys(config)[icn];
            var configAttr = configAttrs[configName];
            if('undefined' !== typeof(configAttr) && '' !== configAttr){
                config[configName] = configAttr;
            }
        }
        //
        var starsByValueFormatter = wNumb({
            edit: function(x){
                return x + " " + "*".repeat(x);
            }
        });
        //
        var slider = noUiSlider.create(sliderDiv, {
	    start: [config["start"]],
            step: config["step"],
            tooltips: [ config['tooltips'] /*starsByValueFormatter*/ ],
	    connect: [ true, false ],
	    range: {
	        'min': config["min"],
	        'max': config["max"]
	    }
        });
        //events: start/end/update/set
        slider.on('update', function(){
	    var value = slider.get();
            $input.val(value);
            if(config['display']){
                if(config['suffix']){
                    $(config['display']).html('<span>' + value + '</span><span>' + config['suffix'] + '</span>');
                } else {
                    $(config['display']).text(value);
                }
            }
            if(config['two-way-display']){
                $(config['two-way-display']).val(value);
            }
        });
        if(config['two-way-display']){
            $(config['two-way-display']).keyup(function(){
                slider.set($(config['two-way-display']).val());
            });
        }
    });
};


window.initCustomDatepickers = function(){
    $('.input-group.date').each(function(i, dateInputGroup){
        var $dateInputGroup = $(dateInputGroup);
        var dateOptions = {
            format: 'dd.mm.yyyy',
            maxViewMode: 2,
            // todayBtn: "linked",
            clearBtn: false,
            language: "en",
            multidate: false,
            autoclose: true,
            todayHighlight: true,
            orientation: 'bottom',
            showOnFocus: false
        };
        if($dateInputGroup.parents('search-bar').length > 0){
            dateOptions.startDate = new Date();
        }
        if($dateInputGroup.hasClass('birthdate')){
            dateOptions.startView = 'century';
            dateOptions.endDate = '-18y';
        }
        //clear date value that's clearly a null date converted to string
        if($dateInputGroup.find('input').val() == '01.01.0001' || $dateInputGroup.find('input').val() == '01.01.0001 00:00:00'){
            $dateInputGroup.find('input').val('');
        }
        $dateInputGroup.datepicker(dateOptions);
        var visible = false;
        $dateInputGroup.click(function(){
            if(visible){
                $dateInputGroup.datepicker('hide');
                visible = false;
            } else {
                $dateInputGroup.datepicker('show');
                visible = true;
            }
        });
    });
};



function decideTableResponsive($able){
    var $ableParent = $able.parent();
    var jsp = $able.data('jsp');
    //make it display:block to measure content and avail. area width
    var hadAbleBlockClass = $able.hasClass('able-block');
    $able.addClass('able-block');
    //width of content
    var wContent = $able.find("tr:first-child").children().get().reduce(function(wSum, td){ return wSum + $(td).outerWidth(true); }, 0);
    //width of usable area for table
    var wAble = $able.parent().width();
    //restore .able-block class
    //if(!hadAbleBlockClass){ $able.removeClass('able-block'); }
    $able.removeClass('able-block');
    //initialize and only if contents dont fit
    //disabled the [only if responsive] check
    //$(window).width() < 768 &&
    if(wContent > wAble){
        //mobile screens
        //make it responsive (if not already)
        $ableParent.find(".able").addClass('able-block');
        // IMPORTANT: currently DISABLE jScrollPane, using only native scrollbars
        /*if('undefined' === typeof(jsp)){
            $able.jScrollPane({
                horizontalDragMinWidth: 106,
                horizontalDragMaxWidth : 120
            });
            jsp = $able.data('jsp');
        }
        jsp.reinitialise();*/
    } else {
        //screens where content fits the available width
        //if it has scrollpane, remove it
        if('undefined' !== typeof(jsp)){
            //jsp.getContentPane();
            jsp.destroy();
        }
        $ableParent.find(".able").removeClass('able-block');
    }
};

function enableCustomFonts(){
    $('body').addClass('fonts-loaded');
}

// var fonts = {
//     'ge' : { 'default' : 'DejaVu Sans', 'caps' : 'BPG Banner Caps'},
//     'en' : { 'default' : 'DejaVu Sans', 'caps' : 'DejaVu Sans'},
//     'ru' : { 'default' : 'DejaVu Sans', 'caps' : 'DejaVu Sans'}
// };
// var activeFont = $('body').hasClass('ge') ? 'ge'
//     : $('body').hasClass('en') ? 'en' : 'ru';
// var defaultFace = new FontFaceObserver(fonts[activeFont]['default']);
// var capsFace = new FontFaceObserver(fonts[activeFont]['caps']);

// Promise.all([defaultFace.load(null, 6000), capsFace.load(null, 6000)])
//     .then(function () {
//         enableCustomFonts();
//     });




window.is_ie = function(){

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");
    // If Internet Explorer, return version number
    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)){
        //alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
        return true;
    }
    else {
        return false;//other browser
    }

    return false;
};
window.is_edge = function(){
    return (navigator.userAgent.indexOf("Edge")) > -1;
};
window.is_firefox = function(){
    return (navigator.userAgent.indexOf("Firefox")) > -1;
};
window.is_safari = function(){
    return /constructor/i.test(window.HTMLElement);
};
window.is_iphone = function(){
    return (navigator.userAgent.indexOf("iPhone")) > -1;
};
window.is_android = function(){
    return (navigator.userAgent.toLowerCase().indexOf("android")) > -1;
};




$(document).ready(function(){

    if(window.is_ie()){
        $("body").addClass("browser-ie");
    }
    if(window.is_edge()){
        $("body").addClass("browser-edge");
    }
    if(window.is_android()){
        $("body").addClass("browser-android");
    }
    if(window.is_firefox()){
        $("body").addClass("browser-firefox");
    }
    if(window.is_safari()){
        $("body").addClass("browser-safari");
    }
    if(window.is_iphone()){
        $("body").addClass("browser-safari browser-iphone");
    }

    $("[data-animate-on][data-animate-with]").each(function(i, el){
        var eventName = $(el).attr('data-animate-on');
        var animationName = $(el).attr('data-animate-with');
        $(el).on(eventName, function(){ $(el).animateCss(animationName); });
    });

    $('.header__search').click(function(e){
        var that = this;
        if($(window).width() >= gridFloatBreakpoint){
            $(this).addClass('expanded');
        } else {
            //fix android keyboard-triggered resize on search input focus
            if(window.is_android()){
                //if search button was clicked, submit form
                if($(e.target).parents('.header__search-btn').length){
                    $(that).submit();
                    return;
                }
                //don't close when clicking inside input
                if($(that).hasClass('expanded') && $(e.target).hasClass('header__search-input')){
                    return false;
                }
                //will toggle expanded class on this too
                toggleOffcanvas();
                //
                e.preventDefault();
                e.stopImmediatePropagation();
                e.stopPropagation();
                return false;
            }
            if(!$(that).hasClass('expanded')){
                toggleOffcanvas();
            }
            /*
            //when search is open and clicking on search input, dont toggle it or menu
            if($(this).hasClass('expanded')
               && $(e.target).hasClass('header__search-input')){
                //in this case, disable bubbling event so that offcanvas doesn't close
                e.preventDefault();
                e.stopPropagation();
            } else {
                if($('.navbar-toggle').hasClass('is-open')){
                    closeOffcanvas();
                } else {
                    openOffcanvas();
                    //prevent bubbling event so that offcanvas stays open
                    e.preventDefault();
                    e.stopPropagation();
                }
                $(this).toggleClass('expanded');
            }
            */
        }
    });
    $('.header__search-close').click(function(e){
        if($(window).width() >= gridFloatBreakpoint){
            $('.header__search').removeClass('expanded');
            //prevent triggering expanded class adder handler on .header__search
            e.stopPropagation();
        } else {
            //will also remove expanded class
            closeOffcanvas();
            /*
            on mobile, navbar-toggle will also trigger search open/close*/
            if($('.navbar-toggle').hasClass('is-open')){
                setTimeout(function(){
                    closeOffcanvas();
                    $('.header__search').removeClass('expanded');
                }, 0);
                //prevent bubbling event to make sure that offcanvas closes
                e.preventDefault();
                e.stopPropagation();
            }
        }
    });
    $('body').on('click', function(e){
        if(!$(e.target).hasClass('header__search') && !$(e.target).parents('.header__search').length){
            //on mobile, also don't close when menu is open
            if($(window).width() >= gridFloatBreakpoint){
                $('.header__search').removeClass('expanded');
            } else {
                /*
                //since search and menu are synchronised,..
                //..only hide menu when clicking outside search AND .navbar-toggle
                if(!$(e.target).hasClass('navbar-toggle')){
                    $('.header__search').removeClass('expanded');
                }*/
            }
        }
    });
    //on mobile, open/close search and menu simultaneously
    $(".navbar-toggle").on('click', function(){
        if($(window).width() < gridFloatBreakpoint){
            toggleOffcanvas();
        }
    });

    //var enableNavbarExpandOnRootItemClick = false;
    //on mobile, expand subitems but only on arrow click
    var navbarExpandOnRootItemClickMin = 1;//768;
    navbarExpandOnRootItemClickMax = gridFloatBreakpoint - 1;
    $('.navbar-nav>li>a .navbar-subitems-expand').click(function(e){
        var $li = $(this).parents('li');
        if(true){//if(enableNavbarExpandOnRootItemClick){
            //on first click on root lvl item, expand submenu; on second click, open root lvl link
            //also check for touch? otherwise, on devices w/ mouse but screen<lg requires two clicks
            //if($(window).width() < gridLgMin){//gridFloatBreakpoint
            if(navbarExpandOnRootItemClickMin <= $(window).width() && $(window).width() <= navbarExpandOnRootItemClickMax){//gridFloatBreakpoint
                if($li.hasClass('expanded')){
                    $li.removeClass('expanded');
                    e.stopPropagation();
                    return false;
                } else {
                    //remove expanded class from other items
                    $('.navbar-nav>li').removeClass('expanded');
                    //add expanded class to this item
                    $li.addClass('expanded');
                    e.stopPropagation();
                    return false;
                }
            } else {
                //on big screens, do nothing; just follow the link on click; submenu opens on hover
                return true;
            }
        }
    });

    $('.navbar-nav>li').mouseenter(function(){
        $(this).siblings().addClass('disable-hover');
    }).mouseleave(function(){
        $(this).siblings().removeClass('disable-hover');
    });

    
    $('.header__navbar-toggle-affix').click(function(){
        $(this).toggleClass('expanded');
        // $('.header__navbar-container-wrapper').toggleClass('expanded');
        // this toggle now toggles left main menu instead of .navbar
        toggleUbermenu();
    });
    $(".uber-menu-close").click(function(e){
        closeUbermenu();
    });
    $(".uber-menu").click(function(e){
        //when clicking on the translucent area above the page content
        if(e.target == e.currentTarget){
            closeUbermenu();
        }
    });
    // expand on BOTH title and arrow
    $('.uber-menu nav ul.nav>li>a,.uber-menu-subitems-expand').click(function(e){
        var $li = $(this).parents('li');
        if(!$li.hasClass('expanded')){
            //if expanding this submenu, then remove expanded class from other items
            $li.siblings().removeClass('expanded');
        }
        $li.toggleClass('expanded');
        //jScrollPane
        setTimeout(function(){ $li.find('>ul').jScrollPane(); }, 200);
        //
        e.stopPropagation();
        return false;
    });
    $(window).on('resize orientationchange', debounce(function() {
        if($(window).width() < gridFloatBreakpoint){
            closeUbermenu();
        }
    }, 200));

    // [code that collapses offcanvas menu on body.click] disables <a> tag links,..
    // .. so restore the links on them
    $('.fixed-sidebar a, .header__strip-ibank-link, .header__top-menu a')
        .click(function(e){
            if($(window).width() < gridFloatBreakpoint){
                document.location.href = $(this).attr('href');
            }
        });
    /*$('.fixed-sidebar *').click(function(e){
        if(!$('.fixed-sidebar').hasClass('expanded')){
            $('.fixed-sidebar').addClass('expanded');
            e.stopPropagation();
            return false;
        }
    });
    $('body').on('click', function(e){
        if(!$(e.target).hasClass('fixed-sidebar') && !$(e.target).parents('.fixed-sidebar').length){
            $('.fixed-sidebar').removeClass('expanded');
        }
    });*/
    

    $('.home-slider').slickResponsive({
        dots: true,
        infinite: true,
        speed: 800,
        slidesToShow: 1,
        centerMode: false,
        vertical: false,
        verticalSwiping: false,
        arrows: false,
        autoplay: true,
        fade: true,
        autoplaySpeed: 8000
    });
    trunk8ultimate('.home-slide-desc', 3);

    function fixHomeDotsPos(){
        $('.home-slider .slick-dots').css('right', (($(window).width() - 1200)/2) + 'px');
    }
    setTimeout(function(){ fixHomeDotsPos(); }, 0);
    setTimeout(function(){ fixHomeDotsPos(); }, 100);
    setTimeout(function(){ fixHomeDotsPos(); }, 300);
    setTimeout(function(){ fixHomeDotsPos(); }, 500);
    $(window).on('resize orientationchange', debounce(function(){
        setTimeout(function(){ fixHomeDotsPos(); }, 0);
        setTimeout(function(){ fixHomeDotsPos(); }, 100);
        setTimeout(function(){ fixHomeDotsPos(); }, 300);
        setTimeout(function(){ fixHomeDotsPos(); }, 500);
    }));

    $('.home-icon-slider').slickResponsive({
        slidesToShow: 6,
        dots: false,
        infinite: false,
        speed: 300,
        centerMode: false,
        arrows: true,
        responsive: [
            {
                breakpoint: 1200,
                settings: {
                    slidesToShow: 4,
                    dots: false,
                    infinite: false,
                    speed: 300,
                    centerMode: false,
                    arrows: true
                }
            }, 
            {
                breakpoint: 768,
                settings: {
                    slidesToShow: 2,
                    dots: false,
                    infinite: false,
                    speed: 300,
                    centerMode: false,
                    arrows: true
                }
            }
        ]
    });
    

    $('.footer__menu').slickResponsive({
        responsive: [
            {
                breakpoint: 100000,
                settings: 'unslick'
            },
            {
                breakpoint: 1200,
                settings: {
                    dots: false,
                    infinite: false,
                    speed: 300,
                    slidesToShow: 3,
                    centerMode: false,
                    vertical: false,
                    verticalSwiping: false,
                    arrows: true,
                    autoplay: false,
                    autoplaySpeed: 8000,
                    fade: false
                }
            },
            {
                breakpoint: 768,
                settings: {
                    dots: false,
                    infinite: false,
                    speed: 300,
                    slidesToShow: 1,
                    centerMode: false,
                    vertical: false,
                    verticalSwiping: false,
                    arrows: true,
                    autoplay: false,
                    autoplaySpeed: 8000,
                    fade: false
                }
            }
        ]
    });

    //spinning effect on submit buttons
    $('.inner-content [type="submit"]').click(function(){
        $(this).addClass('spinning');
    });

    // video player slider used on remote banking details page
    $('.inner-slider').slickResponsive({
        dots: true,
        infinite: true,
        speed: 800,
        slidesToShow: 1,
        centerMode: false,
        vertical: false,
        verticalSwiping: false,
        arrows: true,
        autoplay: false,
        fade: false,
        autoplaySpeed: 8000
    });
    trunk8ultimate('.inner-slide-title', 1);


    
    // image slider used on social project details page
    $('.inner-img-slider').slickResponsive({
        dots: false,
        infinite: false,
        speed: 800,
        slidesToShow: 1,
        centerMode: false,
        vertical: false,
        verticalSwiping: false,
        arrows: true,
        autoplay: false,
        fade: false,
        autoplaySpeed: 8000
    });



    


    $('.inner-4col-slider').slickResponsive({
        slidesToShow: 4,
        slidesToScroll: 4,
        dots: false,
        infinite: false,
        speed: 300,
        centerMode: false,
        arrows: true,
        responsive: [
            {
                breakpoint: 1200,
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 2,
                    dots: false,
                    infinite: false,
                    speed: 300,
                    centerMode: false,
                    arrows: true
                }
            }, 
            {
                breakpoint: 768,
                settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1,
                    dots: false,
                    infinite: false,
                    speed: 300,
                    centerMode: false,
                    arrows: false// true
                }
            }
        ]
    });

    
    
    
    customDropdown();


    //initCustomRangeSliders();

    initCustomDatepickers();


    //trunk8ultimate('.item-arrowed .item-desc', 4);
    trunk8ultimate('.item-title', 2);
    //trunk8ultimate('.item-desc', 4);
    

    $('.tab-switcher').each(function(i, el){
        var $sw = $(el);
        $sw.find('.tab-switcher-link').click(function(){
            $sw.find('.tab-switcher-tab').hide();
            var $tab = $($(this).attr("href"));
            $tab.show();
        });
        $sw.find('.tab-switcher-link.active').click();
    });


    var enableAsideExpandOnRootClick = false;
    $('.inner-aside>nav>ul>li>a').click(function(e){
        if(enableAsideExpandOnRootClick){
            var $li = $(this).parent();
            if(!$li.hasClass('active')){
                $('.inner-aside>nav>ul>li').removeClass('active');
                $li.addClass('active');
                e.stopPropagation();
                return false;
            }
        }
    });

    $('.inner-aside').click(function(e){
        //responsive click
        if($(window).width() < 1200){// 768
            if($(e.target).parent('.inner-aside>nav>ul>li.active').length){
                //clicking on the active menu, so toggle expand
                if($(this).hasClass('expanded-xs')){
                    $(this).removeClass('expanded-xs');
                    //reset (hide) submenus
                    $(this).find('li ul').hide();
                } else {
                    $(this).addClass('expanded-xs');
                    $(this).find('li ul').show();
                }
                e.preventDefault();
                return false;
            } else if($(e.target).parent('.inner-aside>nav>ul>li').length){
                var $thisUl = $(e.target).parent('li').find('ul');
                var wasThisUlVis = $thisUl.is(':visible');
                //clicking on non-active root-item, so hide other submenus
                $(e.target).parents('.inner-aside').find('>nav>ul>li>ul').hide();
                //toggle this menu
                wasThisUlVis ? $thisUl.hide() : $thisUl.show();
                //e.preventDefault();
                //return false;
            } else {
                //clicking a submenu, so follow it
            }
        }
    });

    fixItemExpandedWidthPos = function($item){
        var rowWidth = $item.parents('.row').outerWidth(true);
        var rowLeft = $('.expandable-items-row').offset().left;
        var $expandedContent = $item.find('.item-expanded-content');
        //reset left position to measure difference
        $expandedContent.css('left', '0px');
        var contentLeft = $expandedContent.offset().left;
        $expandedContent
            .css('width',rowWidth+'px')
            .css('left','-'+(contentLeft-rowLeft-15)+'px');
    };
    $('.item-expandable .item-expand-btn').click(function(){
        var $item = $(this).parents('.item');
        var hadClass = $item.hasClass('expanded');
        $('.item-expandable').removeClass('expanded');
        if(!hadClass){ $item.toggleClass('expanded'); }
        fixItemExpandedWidthPos($item);
		
		return false;
    });
    $(window).on('resize orientationchange', debounce(function() {
        $('.item-expandable').each(function(i, el){
            var $item = $(el);
            fixItemExpandedWidthPos($item);
        });
    }));


    $('.able').each(function(i, able){
        decideTableResponsive($(able));
    });
    $(window).on('resize orientationchange', debounce(function() {
        $('.able').each(function(i, able){
            decideTableResponsive($(able));
        });
    }, 200));
    $("[data-fancybox]").click(function(){
        setTimeout(function(){
            $('.fancybox-popup-content .able').each(function(i, able){
                decideTableResponsive($(able));
            });
        }, 500);
    });

    /*$(".item-compare-btn").click(function(){
        $(this).toggleClass('active');
        if($(".item-compare-btn.active").length > 0){
            $('.fixed-compare-btn-wrapper').show();
        } else {
            $('.fixed-compare-btn-wrapper').hide();
        }
    });*/

    $('.select-wrapper .select-trigger').click(function(){
        var that = this;
        setTimeout(function(){
            if($(that).parents('.select-wrapper').hasClass('open')){
                var jsp = $(that).parents('.select-wrapper').find('.select-results').data('jsp');
                if(jsp){
                  //2nd or more open - reinitialize jScrollPane, items may have changed
                    jsp.reinitialise();
                } else {
                    //first time dropdown open - initialize jScrollpane
                    $(that).parents('.select-wrapper')
                        .find('.select-results')
                        .jScrollPane();
                }
            }
        }, 300);
    });

    $('.fixed-compare-show-btn').click(function(){
        $('.inner-compared-items').show();
        var jsp = $('.inner-compared-items').data('jsp');
        if(jsp){ jsp.destroy(); }
        $('.inner-compared-items').jScrollPane();
        $(window).scrollTop($('.inner-compared-items').offset().top - 95);
    });
    $(window).on('resize orientationchange', debounce(function() {
        var jsp = $('.inner-compared-items').data('jsp');
        if(jsp){ jsp.destroy(); }
        $('.inner-compared-items').jScrollPane();
    }, 200));

    $('.fixed-compare-hide-btn').click(function(){
        $('.inner-compared-items').hide();
        $('.item-compare-btn:not(.active)').click();
    });

    //enable .able component on all content tables for dynamic content width detection
    //..on resize
    $(".inner-content table").not(".inner-compared-items table").addClass('able');

    //only on homepage
    $("body.homepage").each(function(){
        setInterval(showNextCurrency, 5000);
    });
    
});
;
function RegisterApplicationFormSocialEvent(appFormId, eventAction) {
    debugger;
    RegisterApplicationFormSocialEvent_RegisterFbqEvent(appFormId, eventAction);
    RegisterApplicationFormSocialEvent_RegisterGaEvent(appFormId, eventAction);
    RegisterApplicationFormSocialEvent_SetEventUrl(appFormId, eventAction);
}
function RegisterApplicationFormSocialEvent_RegisterFbqEvent(appFormId, eventAction) {
    try {
        (window.fbq || function () { })('trackCustom', appFormId + '-Submitted', {});
    } catch (err) {
        console.error(err);
    }
}
function RegisterApplicationFormSocialEvent_RegisterGaEvent(appFormId, eventAction) {
    try {
        ga('send', 'event', 'application-form', eventAction, appFormId);
    } catch (err) {
        console.error(err);
    }
}
function RegisterApplicationFormSocialEvent_SetEventUrl(appFormId, eventAction) {
    window.location.href = '#' + eventAction;
    var ga = (window.ga || function () { });

    setTimeout(function () {
        try {
            ga('set', 'page', window.location.href.substr(window.location.origin.length));
            ga('send', 'pageview');
        } catch (err) {
            console.error(err);
        }
    });
}
function ProductPageApplicationFormButton_RegisterGaEvent(uCid) {
    debugger;
    try {
        ga('send', 'event', 'product-page', uCid, "");
    } catch (err) {
        console.error(err);
    }
};
/**
 * Bunch of useful filters for angularJS(with no external dependencies!)
 * @version v0.5.17 - 2017-09-22 * @link https://github.com/a8m/angular-filter
 * @author Ariel Mashraki <ariel@mashraki.co.il>
 * @license MIT License, http://www.opensource.org/licenses/MIT
 */!function(a,b,c){"use strict";function d(a){return E(a)?a:Object.keys(a).map(function(b){return a[b]})}function e(a){return null===a}function f(a,b){var d=Object.keys(a);return d.map(function(d){return b[d]!==c&&b[d]==a[d]}).indexOf(!1)==-1}function g(a,b){function c(a,b,c){for(var d=0;b+d<=a.length;){if(a.charAt(b+d)==c)return d;d++}return-1}for(var d=0,e=0;e<=b.length;e++){var f=c(a,d,b.charAt(e));if(f==-1)return!1;d+=f+1}return!0}function h(a,b,c){var d=0;return a.filter(function(a){var e=y(c)?d<b&&c(a):d<b;return d=e?d+1:d,e})}function i(a,b){return Math.round(a*Math.pow(10,b))/Math.pow(10,b)}function j(a,b,c){b=b||[];var d=Object.keys(a);return d.forEach(function(d){if(D(a[d])&&!E(a[d])){var e=c?c+"."+d:c;j(a[d],b,e||d)}else{var f=c?c+"."+d:d;b.push(f)}}),b}function k(a){return a&&a.$evalAsync&&a.$watch}function l(){return function(a,b){return a>b}}function m(){return function(a,b){return a>=b}}function n(){return function(a,b){return a<b}}function o(){return function(a,b){return a<=b}}function p(){return function(a,b){return a==b}}function q(){return function(a,b){return a!=b}}function r(){return function(a,b){return a===b}}function s(){return function(a,b){return a!==b}}function t(a){return function(b,c){return b=D(b)?d(b):b,!(!E(b)||z(c))&&b.some(function(b){return B(c)&&D(b)||A(c)?a(c)(b):b===c})}}function u(a,b){return b=b||0,b>=a.length?a:E(a[b])?u(a.slice(0,b).concat(a[b],a.slice(b+1)),b):u(a,b+1)}function v(a){return function(b,c){function e(a,b){return!z(b)&&a.some(function(a){return I(a,b)})}if(b=D(b)?d(b):b,!E(b))return b;var f=[],g=a(c);return z(c)?b.filter(function(a,b,c){return c.indexOf(a)===b}):b.filter(function(a){var b=g(a);return!e(f,b)&&(f.push(b),!0)})}}function w(a,b,c){return b?a+c+w(a,--b,c):a}function x(){return function(a){return B(a)?a.split(" ").map(function(a){return a.charAt(0).toUpperCase()+a.substring(1)}).join(" "):a}}var y=b.isDefined,z=b.isUndefined,A=b.isFunction,B=b.isString,C=b.isNumber,D=b.isObject,E=b.isArray,F=b.forEach,G=b.extend,H=b.copy,I=b.equals;String.prototype.contains||(String.prototype.contains=function(){return String.prototype.indexOf.apply(this,arguments)!==-1}),b.module("a8m.angular",[]).filter("isUndefined",function(){return function(a){return b.isUndefined(a)}}).filter("isDefined",function(){return function(a){return b.isDefined(a)}}).filter("isFunction",function(){return function(a){return b.isFunction(a)}}).filter("isString",function(){return function(a){return b.isString(a)}}).filter("isNumber",function(){return function(a){return b.isNumber(a)}}).filter("isArray",function(){return function(a){return b.isArray(a)}}).filter("isObject",function(){return function(a){return b.isObject(a)}}).filter("isEqual",function(){return function(a,c){return b.equals(a,c)}}),b.module("a8m.conditions",[]).filter({isGreaterThan:l,">":l,isGreaterThanOrEqualTo:m,">=":m,isLessThan:n,"<":n,isLessThanOrEqualTo:o,"<=":o,isEqualTo:p,"==":p,isNotEqualTo:q,"!=":q,isIdenticalTo:r,"===":r,isNotIdenticalTo:s,"!==":s}),b.module("a8m.is-null",[]).filter("isNull",function(){return function(a){return e(a)}}),b.module("a8m.after-where",[]).filter("afterWhere",function(){return function(a,b){if(a=D(a)?d(a):a,!E(a)||z(b))return a;var c=a.map(function(a){return f(b,a)}).indexOf(!0);return a.slice(c===-1?0:c)}}),b.module("a8m.after",[]).filter("after",function(){return function(a,b){return a=D(a)?d(a):a,E(a)?a.slice(b):a}}),b.module("a8m.before-where",[]).filter("beforeWhere",function(){return function(a,b){if(a=D(a)?d(a):a,!E(a)||z(b))return a;var c=a.map(function(a){return f(b,a)}).indexOf(!0);return a.slice(0,c===-1?a.length:++c)}}),b.module("a8m.before",[]).filter("before",function(){return function(a,b){return a=D(a)?d(a):a,E(a)?a.slice(0,b?--b:b):a}}),b.module("a8m.chunk-by",["a8m.filter-watcher"]).filter("chunkBy",["filterWatcher",function(a){return function(b,c,d){function e(a,b){for(var c=[];a--;)c[a]=b;return c}function f(a,b,c){return E(a)?a.map(function(a,d,f){return d*=b,a=f.slice(d,d+b),!z(c)&&a.length<b?a.concat(e(b-a.length,c)):a}).slice(0,Math.ceil(a.length/b)):a}return a.isMemoized("chunkBy",arguments)||a.memoize("chunkBy",arguments,this,f(b,c,d))}}]),b.module("a8m.concat",[]).filter("concat",[function(){return function(a,b){if(z(b))return a;if(E(a))return D(b)?a.concat(d(b)):a.concat(b);if(D(a)){var c=d(a);return D(b)?c.concat(d(b)):c.concat(b)}return a}}]),b.module("a8m.contains",[]).filter({contains:["$parse",t],some:["$parse",t]}),b.module("a8m.count-by",[]).filter("countBy",["$parse",function(a){return function(b,c){var e,f={},g=a(c);return b=D(b)?d(b):b,!E(b)||z(c)?b:(b.forEach(function(a){e=g(a),f[e]||(f[e]=0),f[e]++}),f)}}]),b.module("a8m.defaults",[]).filter("defaults",["$parse",function(a){return function(b,c){if(b=D(b)?d(b):b,!E(b)||!D(c))return b;var e=j(c);return b.forEach(function(b){e.forEach(function(d){var e=a(d),f=e.assign;z(e(b))&&f(b,e(c))})}),b}}]),b.module("a8m.every",[]).filter("every",["$parse",function(a){return function(b,c){return b=D(b)?d(b):b,!(E(b)&&!z(c))||b.every(function(b){return D(b)||A(c)?a(c)(b):b===c})}}]),b.module("a8m.filter-by",[]).filter("filterBy",["$parse",function(a){return function(b,e,f,g){var h;return f=B(f)||C(f)?String(f).toLowerCase():c,b=D(b)?d(b):b,!E(b)||z(f)?b:b.filter(function(b){return e.some(function(c){if(~c.indexOf("+")){var d=c.replace(/\s+/g,"").split("+");h=d.map(function(c){return a(c)(b)}).join(" ")}else h=a(c)(b);return!(!B(h)&&!C(h))&&(h=String(h).toLowerCase(),g?h===f:h.contains(f))})})}}]),b.module("a8m.first",[]).filter("first",["$parse",function(a){return function(b){var e,f,g;return b=D(b)?d(b):b,E(b)?(g=Array.prototype.slice.call(arguments,1),e=C(g[0])?g[0]:1,f=C(g[0])?C(g[1])?c:g[1]:g[0],g.length?h(b,e,f?a(f):f):b[0]):b}}]),b.module("a8m.flatten",[]).filter("flatten",function(){return function(a,b){return b=b||!1,a=D(a)?d(a):a,E(a)?b?[].concat.apply([],a):u(a,0):a}}),b.module("a8m.fuzzy-by",[]).filter("fuzzyBy",["$parse",function(a){return function(b,c,e,f){var h,i,j=f||!1;return b=D(b)?d(b):b,!E(b)||z(c)||z(e)?b:(i=a(c),b.filter(function(a){return h=i(a),!!B(h)&&(h=j?h:h.toLowerCase(),e=j?e:e.toLowerCase(),g(h,e)!==!1)}))}}]),b.module("a8m.fuzzy",[]).filter("fuzzy",function(){return function(a,b,c){function e(a,b){var c,d,e=Object.keys(a);return 0<e.filter(function(e){return c=a[e],!!d||!!B(c)&&(c=f?c:c.toLowerCase(),d=g(c,b)!==!1)}).length}var f=c||!1;return a=D(a)?d(a):a,!E(a)||z(b)?a:(b=f?b:b.toLowerCase(),a.filter(function(a){return B(a)?(a=f?a:a.toLowerCase(),g(a,b)!==!1):!!D(a)&&e(a,b)}))}}),b.module("a8m.group-by",["a8m.filter-watcher"]).filter("groupBy",["$parse","filterWatcher",function(a,b){return function(c,d){function e(a,b){var c,d={};return F(a,function(a){c=b(a),d[c]||(d[c]=[]),d[c].push(a)}),d}return!D(c)||z(d)?c:b.isMemoized("groupBy",arguments)||b.memoize("groupBy",arguments,this,e(c,a(d)))}}]),b.module("a8m.is-empty",[]).filter("isEmpty",function(){return function(a){return D(a)?!d(a).length:!a.length}}),b.module("a8m.join",[]).filter("join",function(){return function(a,b){return z(a)||!E(a)?a:(z(b)&&(b=" "),a.join(b))}}),b.module("a8m.last",[]).filter("last",["$parse",function(a){return function(b){var e,f,g,i=H(b);return i=D(i)?d(i):i,E(i)?(g=Array.prototype.slice.call(arguments,1),e=C(g[0])?g[0]:1,f=C(g[0])?C(g[1])?c:g[1]:g[0],g.length?h(i.reverse(),e,f?a(f):f).reverse():i[i.length-1]):i}}]),b.module("a8m.map",[]).filter("map",["$parse",function(a){return function(b,c){return b=D(b)?d(b):b,!E(b)||z(c)?b:b.map(function(b){return a(c)(b)})}}]),b.module("a8m.omit",[]).filter("omit",["$parse",function(a){return function(b,c){return b=D(b)?d(b):b,!E(b)||z(c)?b:b.filter(function(b){return!a(c)(b)})}}]),b.module("a8m.pick",[]).filter("pick",["$parse",function(a){return function(b,c){return b=D(b)?d(b):b,!E(b)||z(c)?b:b.filter(function(b){return a(c)(b)})}}]),b.module("a8m.range",[]).filter("range",function(){return function(a,b,c,d,e){c=c||0,d=d||1;for(var f=0;f<parseInt(b);f++){var g=c+f*d;a.push(A(e)?e(g):g)}return a}}),b.module("a8m.remove-with",[]).filter("removeWith",function(){return function(a,b){return z(b)?a:(a=D(a)?d(a):a,a.filter(function(a){return!f(b,a)}))}}),b.module("a8m.remove",[]).filter("remove",function(){return function(a){a=D(a)?d(a):a;var b=Array.prototype.slice.call(arguments,1);return E(a)?a.filter(function(a){return!b.some(function(b){return I(b,a)})}):a}}),b.module("a8m.reverse",[]).filter("reverse",[function(){return function(a){return a=D(a)?d(a):a,B(a)?a.split("").reverse().join(""):E(a)?a.slice().reverse():a}}]),b.module("a8m.search-field",[]).filter("searchField",["$parse",function(a){return function(b){var c,e;b=D(b)?d(b):b;var f=Array.prototype.slice.call(arguments,1);return E(b)&&f.length?b.map(function(b){return e=f.map(function(d){return(c=a(d))(b)}).join(" "),G(b,{searchField:e})}):b}}]),b.module("a8m.to-array",[]).filter("toArray",function(){return function(a,b){return D(a)?b?Object.keys(a).map(function(b){return G(a[b],{$key:b})}):d(a):a}}),b.module("a8m.unique",[]).filter({unique:["$parse",v],uniq:["$parse",v]}),b.module("a8m.where",[]).filter("where",function(){return function(a,b){return z(b)?a:(a=D(a)?d(a):a,a.filter(function(a){return f(b,a)}))}}),b.module("a8m.xor",[]).filter("xor",["$parse",function(a){return function(b,c,e){function f(b,c){var d=a(e);return c.some(function(a){return e?I(d(a),d(b)):I(a,b)})}return e=e||!1,b=D(b)?d(b):b,c=D(c)?d(c):c,E(b)&&E(c)?b.concat(c).filter(function(a){return!(f(a,b)&&f(a,c))}):b}}]),b.module("a8m.math.abs",[]).filter("abs",function(){return function(a){return Math.abs(a)}}),b.module("a8m.math.byteFmt",[]).filter("byteFmt",function(){var a=[{str:"B",val:1024}];return["KB","MB","GB","TB","PB","EB","ZB","YB"].forEach(function(b,c){a.push({str:b,val:1024*a[c].val})}),function(b,c){if(C(c)&&isFinite(c)&&c%1===0&&c>=0&&C(b)&&isFinite(b)){for(var d=0;d<a.length-1&&b>=a[d].val;)d++;return b/=d>0?a[d-1].val:1,i(b,c)+" "+a[d].str}return"NaN"}}),b.module("a8m.math.degrees",[]).filter("degrees",function(){return function(a,b){if(C(b)&&isFinite(b)&&b%1===0&&b>=0&&C(a)&&isFinite(a)){var c=180*a/Math.PI;return Math.round(c*Math.pow(10,b))/Math.pow(10,b)}return"NaN"}}),b.module("a8m.math.kbFmt",[]).filter("kbFmt",function(){var a=[{str:"KB",val:1024}];return["MB","GB","TB","PB","EB","ZB","YB"].forEach(function(b,c){a.push({str:b,val:1024*a[c].val})}),function(b,c){if(C(c)&&isFinite(c)&&c%1===0&&c>=0&&C(b)&&isFinite(b)){for(var d=0;d<a.length-1&&b>=a[d].val;)d++;return b/=d>0?a[d-1].val:1,i(b,c)+" "+a[d].str}return"NaN"}}),b.module("a8m.math.max",[]).filter("max",["$parse",function(a){function b(b,c){var d=b.map(function(b){return a(c)(b)});return d.indexOf(Math.max.apply(Math,d))}return function(a,c){return E(a)?z(c)?Math.max.apply(Math,a):a[b(a,c)]:a}}]),b.module("a8m.math.min",[]).filter("min",["$parse",function(a){function b(b,c){var d=b.map(function(b){return a(c)(b)});return d.indexOf(Math.min.apply(Math,d))}return function(a,c){return E(a)?z(c)?Math.min.apply(Math,a):a[b(a,c)]:a}}]),b.module("a8m.math.percent",[]).filter("percent",function(){return function(a,b,c){var d=B(a)?Number(a):a;return b=b||100,c=c||!1,!C(d)||isNaN(d)?a:c?Math.round(d/b*100):d/b*100}}),b.module("a8m.math.radians",[]).filter("radians",function(){return function(a,b){if(C(b)&&isFinite(b)&&b%1===0&&b>=0&&C(a)&&isFinite(a)){var c=3.14159265359*a/180;return Math.round(c*Math.pow(10,b))/Math.pow(10,b)}return"NaN"}}),b.module("a8m.math.radix",[]).filter("radix",function(){return function(a,b){var c=/^[2-9]$|^[1-2]\d$|^3[0-6]$/;return C(a)&&c.test(b)?a.toString(b).toUpperCase():a}}),b.module("a8m.math.shortFmt",[]).filter("shortFmt",function(){return function(a,b){return C(b)&&isFinite(b)&&b%1===0&&b>=0&&C(a)&&isFinite(a)?a<1e3?""+a:a<1e6?i(a/1e3,b)+" K":a<1e9?i(a/1e6,b)+" M":i(a/1e9,b)+" B":"NaN"}}),b.module("a8m.math.sum",[]).filter("sum",function(){return function(a,b){return E(a)?a.reduce(function(a,b){return a+b},b||0):a}}),b.module("a8m.ends-with",[]).filter("endsWith",function(){return function(a,b,c){var d,e=c||!1;return!B(a)||z(b)?a:(a=e?a:a.toLowerCase(),d=a.length-b.length,a.indexOf(e?b:b.toLowerCase(),d)!==-1)}}),b.module("a8m.latinize",[]).filter("latinize",[function(){function a(a){return a.replace(/[^\u0000-\u007E]/g,function(a){return c[a]||a})}for(var b=[{base:"A",letters:"AⒶＡÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄȺⱯ"},{base:"AA",letters:"Ꜳ"},{base:"AE",letters:"ÆǼǢ"},{base:"AO",letters:"Ꜵ"},{base:"AU",letters:"Ꜷ"},{base:"AV",letters:"ꜸꜺ"},{base:"AY",letters:"Ꜽ"},{base:"B",letters:"BⒷＢḂḄḆɃƂƁ"},{base:"C",letters:"CⒸＣĆĈĊČÇḈƇȻꜾ"},{base:"D",letters:"DⒹＤḊĎḌḐḒḎĐƋƊƉꝹ"},{base:"DZ",letters:"ǱǄ"},{base:"Dz",letters:"ǲǅ"},{base:"E",letters:"EⒺＥÈÉÊỀẾỄỂẼĒḔḖĔĖËẺĚȄȆẸỆȨḜĘḘḚƐƎ"},{base:"F",letters:"FⒻＦḞƑꝻ"},{base:"G",letters:"GⒼＧǴĜḠĞĠǦĢǤƓꞠꝽꝾ"},{base:"H",letters:"HⒽＨĤḢḦȞḤḨḪĦⱧⱵꞍ"},{base:"I",letters:"IⒾＩÌÍÎĨĪĬİÏḮỈǏȈȊỊĮḬƗ"},{base:"J",letters:"JⒿＪĴɈ"},{base:"K",letters:"KⓀＫḰǨḲĶḴƘⱩꝀꝂꝄꞢ"},{base:"L",letters:"LⓁＬĿĹĽḶḸĻḼḺŁȽⱢⱠꝈꝆꞀ"},{base:"LJ",letters:"Ǉ"},{base:"Lj",letters:"ǈ"},{base:"M",letters:"MⓂＭḾṀṂⱮƜ"},{base:"N",letters:"NⓃＮǸŃÑṄŇṆŅṊṈȠƝꞐꞤ"},{base:"NJ",letters:"Ǌ"},{base:"Nj",letters:"ǋ"},{base:"O",letters:"OⓄＯÒÓÔỒỐỖỔÕṌȬṎŌṐṒŎȮȰÖȪỎŐǑȌȎƠỜỚỠỞỢỌỘǪǬØǾƆƟꝊꝌ"},{base:"OI",letters:"Ƣ"},{base:"OO",letters:"Ꝏ"},{base:"OU",letters:"Ȣ"},{base:"OE",letters:"Œ"},{base:"oe",letters:"œ"},{base:"P",letters:"PⓅＰṔṖƤⱣꝐꝒꝔ"},{base:"Q",letters:"QⓆＱꝖꝘɊ"},{base:"R",letters:"RⓇＲŔṘŘȐȒṚṜŖṞɌⱤꝚꞦꞂ"},{base:"S",letters:"SⓈＳẞŚṤŜṠŠṦṢṨȘŞⱾꞨꞄ"},{base:"T",letters:"TⓉＴṪŤṬȚŢṰṮŦƬƮȾꞆ"},{base:"TZ",letters:"Ꜩ"},{base:"U",letters:"UⓊＵÙÚÛŨṸŪṺŬÜǛǗǕǙỦŮŰǓȔȖƯỪỨỮỬỰỤṲŲṶṴɄ"},{base:"V",letters:"VⓋＶṼṾƲꝞɅ"},{base:"VY",letters:"Ꝡ"},{base:"W",letters:"WⓌＷẀẂŴẆẄẈⱲ"},{base:"X",letters:"XⓍＸẊẌ"},{base:"Y",letters:"YⓎＹỲÝŶỸȲẎŸỶỴƳɎỾ"},{base:"Z",letters:"ZⓏＺŹẐŻŽẒẔƵȤⱿⱫꝢ"},{base:"a",letters:"aⓐａẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁąⱥɐ"},{base:"aa",letters:"ꜳ"},{base:"ae",letters:"æǽǣ"},{base:"ao",letters:"ꜵ"},{base:"au",letters:"ꜷ"},{base:"av",letters:"ꜹꜻ"},{base:"ay",letters:"ꜽ"},{base:"b",letters:"bⓑｂḃḅḇƀƃɓ"},{base:"c",letters:"cⓒｃćĉċčçḉƈȼꜿↄ"},{base:"d",letters:"dⓓｄḋďḍḑḓḏđƌɖɗꝺ"},{base:"dz",letters:"ǳǆ"},{base:"e",letters:"eⓔｅèéêềếễểẽēḕḗĕėëẻěȅȇẹệȩḝęḙḛɇɛǝ"},{base:"f",letters:"fⓕｆḟƒꝼ"},{base:"g",letters:"gⓖｇǵĝḡğġǧģǥɠꞡᵹꝿ"},{base:"h",letters:"hⓗｈĥḣḧȟḥḩḫẖħⱨⱶɥ"},{base:"hv",letters:"ƕ"},{base:"i",letters:"iⓘｉìíîĩīĭïḯỉǐȉȋịįḭɨı"},{base:"j",letters:"jⓙｊĵǰɉ"},{base:"k",letters:"kⓚｋḱǩḳķḵƙⱪꝁꝃꝅꞣ"},{base:"l",letters:"lⓛｌŀĺľḷḹļḽḻſłƚɫⱡꝉꞁꝇ"},{base:"lj",letters:"ǉ"},{base:"m",letters:"mⓜｍḿṁṃɱɯ"},{base:"n",letters:"nⓝｎǹńñṅňṇņṋṉƞɲŉꞑꞥ"},{base:"nj",letters:"ǌ"},{base:"o",letters:"oⓞｏòóôồốỗổõṍȭṏōṑṓŏȯȱöȫỏőǒȍȏơờớỡởợọộǫǭøǿɔꝋꝍɵ"},{base:"oi",letters:"ƣ"},{base:"ou",letters:"ȣ"},{base:"oo",letters:"ꝏ"},{base:"p",letters:"pⓟｐṕṗƥᵽꝑꝓꝕ"},{base:"q",letters:"qⓠｑɋꝗꝙ"},{base:"r",letters:"rⓡｒŕṙřȑȓṛṝŗṟɍɽꝛꞧꞃ"},{base:"s",letters:"sⓢｓßśṥŝṡšṧṣṩșşȿꞩꞅẛ"},{base:"t",letters:"tⓣｔṫẗťṭțţṱṯŧƭʈⱦꞇ"},{base:"tz",letters:"ꜩ"},{base:"u",letters:"uⓤｕùúûũṹūṻŭüǜǘǖǚủůűǔȕȗưừứữửựụṳųṷṵʉ"},{base:"v",letters:"vⓥｖṽṿʋꝟʌ"},{base:"vy",letters:"ꝡ"},{base:"w",letters:"wⓦｗẁẃŵẇẅẘẉⱳ"},{base:"x",letters:"xⓧｘẋẍ"},{base:"y",letters:"yⓨｙỳýŷỹȳẏÿỷẙỵƴɏỿ"},{base:"z",letters:"zⓩｚźẑżžẓẕƶȥɀⱬꝣ"}],c={},d=0;d<b.length;d++)for(var e=b[d].letters.split(""),f=0;f<e.length;f++)c[e[f]]=b[d].base;return function(b){return B(b)?a(b):b}}]),b.module("a8m.ltrim",[]).filter("ltrim",function(){return function(a,b){var c=b||"\\s";return B(a)?a.replace(new RegExp("^"+c+"+"),""):a}}),b.module("a8m.match",[]).filter("match",function(){return function(a,b,c){var d=new RegExp(b,c);return B(a)?a.match(d):null}}),b.module("a8m.phoneUS",[]).filter("phoneUS",function(){return function(a){return a+="","("+a.slice(0,3)+") "+a.slice(3,6)+"-"+a.slice(6)}}),b.module("a8m.repeat",[]).filter("repeat",[function(){return function(a,b,c){var d=~~b;return B(a)&&d?w(a,--b,c||""):a}}]),b.module("a8m.rtrim",[]).filter("rtrim",function(){return function(a,b){var c=b||"\\s";return B(a)?a.replace(new RegExp(c+"+$"),""):a}}),b.module("a8m.slugify",[]).filter("slugify",[function(){return function(a,b){var c=z(b)?"-":b;return B(a)?a.toLowerCase().replace(/\s+/g,c):a}}]),b.module("a8m.split",[]).filter("split",function(){function a(a){return a.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}return function(b,c,d){var f,g,h,i;return z(b)||!B(b)?null:(z(c)&&(c=""),isNaN(d)&&(d=0),f=new RegExp(a(c),"g"),g=b.match(f),e(g)||d>=g.length?[b]:0===d?b.split(c):(h=b.split(c),i=h.splice(0,d+1),h.unshift(i.join(c)),h))}}),b.module("a8m.starts-with",[]).filter("startsWith",function(){return function(a,b,c){var d=c||!1;return!B(a)||z(b)?a:(a=d?a:a.toLowerCase(),!a.indexOf(d?b:b.toLowerCase()))}}),b.module("a8m.stringular",[]).filter("stringular",function(){return function(a){var b=Array.prototype.slice.call(arguments,1);return a.replace(/{(\d+)}/g,function(a,c){return z(b[c])?a:b[c]})}}),b.module("a8m.strip-tags",[]).filter("stripTags",function(){return function(a){return B(a)?a.replace(/<\S[^><]*>/g,""):a}}),b.module("a8m.test",[]).filter("test",function(){return function(a,b,c){var d=new RegExp(b,c);return B(a)?d.test(a):a}}),b.module("a8m.trim",[]).filter("trim",function(){return function(a,b){var c=b||"\\s";return B(a)?a.replace(new RegExp("^"+c+"+|"+c+"+$","g"),""):a}}),b.module("a8m.truncate",[]).filter("truncate",function(){return function(a,b,c,d){return b=z(b)?a.length:b,d=d||!1,c=c||"",!B(a)||a.length<=b?a:a.substring(0,d?a.indexOf(" ",b)===-1?a.length:a.indexOf(" ",b):b)+c}}),b.module("a8m.ucfirst",[]).filter({ucfirst:x,titleize:x}),b.module("a8m.uri-component-encode",[]).filter("uriComponentEncode",["$window",function(a){return function(b){return B(b)?a.encodeURIComponent(b):b}}]),b.module("a8m.uri-encode",[]).filter("uriEncode",["$window",function(a){return function(b){return B(b)?a.encodeURI(b):b}}]),b.module("a8m.wrap",[]).filter("wrap",function(){return function(a,b,c){return B(a)&&y(b)?[b,a,c||b].join(""):a}}),b.module("a8m.filter-watcher",[]).provider("filterWatcher",function(){this.$get=["$window","$rootScope",function(a,b){function c(b,c){function d(){var b=[];return function(c,d){if(D(d)&&!e(d)){if(~b.indexOf(d))return"[Circular]";b.push(d)}return a==d?"$WINDOW":a.document==d?"$DOCUMENT":k(d)?"$SCOPE":d}}return[b,JSON.stringify(c,d())].join("#").replace(/"/g,"")}function d(a){var b=a.targetScope.$id;F(l[b],function(a){delete j[a]}),delete l[b]}function f(){m(function(){b.$$phase||(j={})},2e3)}function g(a,b){var c=a.$id;return z(l[c])&&(a.$on("$destroy",d),l[c]=[]),l[c].push(b)}function h(a,b){var d=c(a,b);return j[d]}function i(a,b,d,e){var h=c(a,b);return j[h]=e,k(d)?g(d,h):f(),e}var j={},l={},m=a.setTimeout;return{isMemoized:h,memoize:i}}]}),b.module("angular.filter",["a8m.ucfirst","a8m.uri-encode","a8m.uri-component-encode","a8m.slugify","a8m.latinize","a8m.strip-tags","a8m.stringular","a8m.truncate","a8m.starts-with","a8m.ends-with","a8m.wrap","a8m.trim","a8m.ltrim","a8m.rtrim","a8m.repeat","a8m.test","a8m.match","a8m.split","a8m.phoneUS","a8m.to-array","a8m.concat","a8m.contains","a8m.unique","a8m.is-empty","a8m.after","a8m.after-where","a8m.before","a8m.before-where","a8m.defaults","a8m.where","a8m.reverse","a8m.remove","a8m.remove-with","a8m.group-by","a8m.count-by","a8m.chunk-by","a8m.search-field","a8m.fuzzy-by","a8m.fuzzy","a8m.omit","a8m.pick","a8m.every","a8m.filter-by","a8m.xor","a8m.map","a8m.first","a8m.last","a8m.flatten","a8m.join","a8m.range","a8m.math.max","a8m.math.min","a8m.math.abs","a8m.math.percent","a8m.math.radix","a8m.math.sum","a8m.math.degrees","a8m.math.radians","a8m.math.byteFmt","a8m.math.kbFmt","a8m.math.shortFmt","a8m.angular","a8m.conditions","a8m.is-null","a8m.filter-watcher"])}(window,window.angular);;
var app = angular.module('vtb-app', ['angular.filter'])
;
app.controller('askAQuestionController', ['$scope', '$http', function ($scope, $http) {
    var _this = this;
    _this.$scope = $scope;
    $scope._this = _this;

    _this.isSubmitted = false;
    _this.showForm = true;
    _this.sendingData = false;
    _this.message = "";

    _this.data = {
        fullName: null,
        email: null,
        question: null,
        subject: null,
        phone: null,
        captcha: null
    };

    _this.send = function (languageId) {
        _this.isSubmitted = true;
        var validate = true;
        for (var key in _this.data) {
            if (_this.data[key] == null || !_this.data[key].length) {
                validate = false;
            }
        }

        if (validate) {
            _this.sendingData = true;
            $http.post('~/api/askaquestion/send',
                {
                    fullName: _this.data.fullName,
                    email: _this.data.email,
                    subject: _this.data.subject,
                    phone: _this.data.phone,
                    question: _this.data.question,
                    captcha: _this.data.captcha,
                    languageId: languageId
                }).then(function successCallback(response) {
                    if (response.data.success) {
                        _this.showForm = false;
                    }
                    _this.message = response.data.message;
                }).catch(function (e) {

                }).finally(function (e) {
                    _this.sendingData = false;
                    $('.captcha').attr('src', $('.captcha').attr('src') + '1');
                });
        }
    }
}]);
;
app.controller('businessLoanCalculatorController', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
    var _this = this;
    _this.$scope = $scope;
    $scope._this = _this;

    _this.currencies = window.currencies;

    _this.selectedcurrency = null;

    _this.selectedInterest = null;
    _this.selectedAmount = null;
    _this.selectedMonth = null;
    _this.monthlyPayment = 0;

    _this.monthlyPaymentsSum = 0;
    _this.monthlyPercentsSum = 0;

    _this.schedule = {
        monthlyPayments: []
    };
   
    _this.init = function () {
        _this.selectedcurrency = _this.currencies[0];

        _this.selectedInterest = _this.selectedcurrency.minInterest;
        _this.selectedAmount = _this.selectedcurrency.minAmount;
        _this.selectedMonth = _this.selectedcurrency.minMonth;

        _this.calculate();
        $(window).trigger('resize');
    }
    _this.changeType = function () {
        $timeout(function () {
            _this.selectedInterest = _this.selectedcurrency.minInterest;
            _this.selectedAmount = _this.selectedcurrency.minAmount;
            _this.selectedMonth = _this.selectedcurrency.minMonth;
            _this.calculate();
        });
    }

    _this.calculate = function () {
        $timeout(function () {
            _this.monthlyPayment = _this.formatNumber(_this.calcuatePmt(_this.selectedInterest, _this.selectedMonth, _this.selectedAmount));
            _this.createSchedule();
        });

    }

    _this.calcuatePmt = function (apr, term, loan) {
        apr = apr / 1200;
        var amount = apr * -loan * Math.pow((1 + apr), term) / (1 - Math.pow((1 + apr), term));
        return amount;
    }

    _this.createSchedule = function () {
        _this.schedule.monthlyPayments = [];
        var balance = _this.selectedAmount;
        var percent = 0;
        var percentsSum = 0;

        for (var i = 1; i < _this.selectedMonth + 1; i++) {

           
                percent = ((balance * (_this.selectedInterest / 100)) / 12);

                balance -= ((_this.calcuatePmt(_this.selectedInterest, _this.selectedMonth, _this.selectedAmount)) - percent);

                percentsSum += percent;

                _this.monthlyPaymentsSum = _this.formatNumber(i * _this.monthlyPayment);
                _this.schedule.monthlyPayments.push({
                    "month": i,
                    "monthly": _this.monthlyPayment,
                    "loan": _this.formatNumber(((_this.calcuatePmt(_this.selectedInterest, _this.selectedMonth, _this.selectedAmount)) - percent)),
                    "percent": _this.formatNumber(percent),
                    "balance": _this.formatNumber(balance) 
                });
          

        }

        _this.monthlyPercentsSum = _this.formatNumber(percentsSum)
    }

    _this.formatNumber = function (number) {
        return number.toFixed(4).toString().slice(0, -2).replace("-", "");
    }

}]);
;
app.controller('contactController', ['$scope', '$http', function ($scope, $http) {
    var _this = this;
    _this.$scope = $scope;
    $scope._this = _this;

    _this.IsSubmitted = false;
    _this.ShowForm = true;
    _this.SendingData = false;
    _this.Message = "";

    _this.Data = {
        FullName: null,
        Email: null,
        Question: null,
        Captcha: null
    };

    _this.Send = function (languageId) {
        _this.IsSubmitted = true;
        var validate = true;
        for (var key in _this.Data) {
            if (_this.Data[key] == null || !_this.Data[key].length) {
                validate = false;
            }
        }

        if (validate) {
            _this.SendingData = true;
            $http.post('~/api/contact/send',
                {
                    FullName: _this.Data.FullName,
                    Email: _this.Data.Email,
                    Question: _this.Data.Question,
                    Captcha: _this.Data.Captcha,
                    languageId: languageId
                }).then(function successCallback(response) {
                    if (response.data.success) {
                        _this.ShowForm = false;
                    }
                    _this.Message = response.data.message;
                }).catch(function (e) {

                }).finally(function (e) {
                    _this.SendingData = false;
                    $('.captcha').attr('src', $('.captcha').attr('src') + '1');
                });
        }
    }
}]);
;
app.controller('currencyConverterController', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
    var _this = this;
    _this.$scope = $scope;
    $scope._this = _this;

    var rates = window.rates;
    var names = window.names;

    _this.currencyNames = names;

    _this.currencyHistoryNames = window.historyNames;
    _this.currencyHistory = null;

    _this.fromCurrency = names[0];
    _this.toCurrency = names[1];
    _this.amount = 100;
    _this.sum = 0;


    _this.selectedDate = window.dateNow;
    _this.selectedCurrency = _this.currencyHistoryNames[0];
    _this.SendingData = false;
    _this.init = function () {
        _this.calculate();
        _this.get();
    }
    _this.calculate = function () {
        $timeout(function () {
            _this.sum = 0;
            var buy = _this.alternativeFind(rates, function findCurrency(e) {
                return e.fromCurrency === _this.fromCurrency.title && e.toCurrency === _this.toCurrency.title;
            });
            if (buy != null) {
                buy = buy.buy;
                _this.sum = _this.amount * buy;
            }
            var sell = _this.alternativeFind(rates, function findCurrency(e) {
                return e.toCurrency === _this.fromCurrency.title && e.fromCurrency === _this.toCurrency.title;
            });
            if (sell != null) {
                sell = sell.sell;
                _this.sum = _this.amount / sell;
            }
        });
    }

    _this.get = function () {
        var validate = true;
        if (_this.selectedDate == null || _this.selectedCurrency == null) {
            validate = false;
        }

        if (validate) {
            $http.post(window.apiUrl + '?Date=' + _this.selectedDate + '&CurrencyName=' + _this.selectedCurrency.title).then(function (e) {
                _this.currencyHistory = e.data.list;
            }).catch(function (e) {
            }).finally(function () {
            });
        }
    }

    _this.clear = function () {
        _this.selectedDate = window.dateNow;
        _this.selectedCurrency = _this.currencyHistoryNames[0];
        _this.get();
    }


    _this.alternativeFind = function (arr, callback) {
        for (var i = 0; i < arr.length; i++) {
            var match = callback(arr[i]);
            if (match) {
                return arr[i];
                break;
            }
        }
    }
}]);
;
app.controller('depositCalculatorController', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
    var _this = this;
    _this.$scope = $scope;
    $scope._this = _this;


    _this.types = window.types;
    _this.selectedType = null;
    _this.selectedCurrency = null;

    _this.selectedSettings = null;
    _this.selectedAmount = null;
    _this.selectedMonth = null;
    _this.sum = 0;

    _this.minMonth = 1000;
    _this.maxMonth = 0;

    _this.interest = 0;

    _this.init = function () {
        _this.selectedType = _this.types[0];
        _this.selectedCurrency = _this.selectedType.currencies[0];


        _this.setMonth();

        _this.calculate();
        $(window).trigger('resize');

        $timeout(function () {
            if (window.depositCalcInitTypeId > 0) {
                //var requestedInitialType = _this.types.find(function (elem) { return elem.id == window.depositCalcInitTypeId });

                var requestedInitialType = _this.alternativeFind(_this.types, function (elem) { return elem.id == window.depositCalcInitTypeId });

                if (requestedInitialType != null) {
                    _this.selectedType = requestedInitialType;
                    _this.changeType();
                }
            }
        });
    }
    _this.changeType = function () {
        $timeout(function () {
            _this.selectedCurrency = _this.selectedType.currencies[0];
            _this.changeInterest();
            _this.setMonth();
        });
    }

    _this.calculate = function () {
        $timeout(function () {
            if (_this.selectedType.id == 3) {
                _this.calculateKidsDeposit();
            } else {
                //_this.sum = ((_this.selectedAmount * _this.interest / 365 * (_this.selectedMonth * 30)) / 100).toFixed(2);
                _this.calculateDeposit();
            }
        }, 100);
    }

    _this.changeInterest = function () {
        $timeout(function () {
            for (var i = 0; i < _this.selectedSettings.length; i++) {
                if (_this.selectedSettings[i].minMonth <= _this.selectedMonth && _this.selectedSettings[i].maxMonth >= _this.selectedMonth) {
                    _this.interest = _this.selectedSettings[i].interest;

                    _this.calculate();
                }
            }
        }, 100);
    }

    _this.setMonth = function () {
        $timeout(function () {
            _this.selectedSettings = _this.selectedCurrency.settings;
            _this.minMonth = 1000;
            _this.maxMonth = 0;
            for (var i = 0; i < _this.selectedSettings.length; i++) {
                if (_this.selectedSettings[i].minMonth < _this.minMonth) {
                    _this.minMonth = _this.selectedSettings[i].minMonth;
                }
                if (_this.selectedSettings[i].maxMonth > _this.maxMonth) {
                    _this.maxMonth = _this.selectedSettings[i].maxMonth;
                }
            }
            _this.changeInterest();
        });
    }

    _this.calculateDeposit = function () {

        if (_this.selectedMonth >= 12) {
            var index = 1;
            var percent = 0;
            var monthes = _this.selectedMonth;
            var sumpercent = 0;
            var monthesleft = 0;
            var days = 0;
            var dayCountInCurrentYear = 365;
            //if (_this.selectedMonth > 12 && _this.selectedMonth < 24) {
            //    dayCountInCurrentYear = 360;
            //    
            //} else {
            //    dayCountInCurrentYear = 365;
            //}
            for (var i = 0; i < _this.selectedMonth; i++) {
                if (index == 1) {

                    if (monthes < 12) { monthesleft = 12 - monthes; days = 0; dayCountInCurrentYear = 360; }
                   if (_this.selectedMonth > 12 && _this.selectedMonth < 24) {
                       dayCountInCurrentYear = 360;
                       
                   }
                    percent = ((((parseFloat(_this.selectedAmount)) * parseFloat(_this.interest) / 365) * (dayCountInCurrentYear - (monthesleft * 30) - days)) / 100);
                    sumpercent += percent;
                    monthes = monthes - 12;
                }
                if (index < 12) {
                    index++;
                } else {
                    index = 1;
                }
            }

            _this.sum = sumpercent.toFixed(2);
        } else {
            _this.sum = ((_this.selectedAmount * _this.interest / 365 * (_this.selectedMonth * 30)) / 100).toFixed(2);
        }
        //$timeout(function () {
        //    _this.sum = ((_this.selectedAmount * _this.interest / 365 * (_this.selectedMonth * 30)) / 100).toFixed(2);
        //}, 100);
    }

    _this.calculateKidsDeposit = function () {

        var index = 1;
        var percent = 0;
        var monthes = _this.selectedMonth;
        var sumpercent = 0;
        var monthesleft = 0;
        var days = 0;

        for (var i = 0; i < _this.selectedMonth; i++) {
            if (index == 1) {
                percent = ((((parseFloat(_this.selectedAmount) + sumpercent) * parseFloat(_this.interest) / 365) * (365 - (monthesleft * 30) - days)) / 100);
                sumpercent += percent;
                monthes = monthes - 12;
                if (monthes < 12) { monthesleft = 12 - monthes; days = 5; }
            }
            if (index < 12) {
                index++;
            } else {
                index = 1;
            }
        }

        _this.sum = sumpercent.toFixed(2);
        //$timeout(function () {
        //    _this.sum = ((_this.selectedAmount * _this.interest / 365 * (_this.selectedMonth * 30)) / 100).toFixed(2);
        //}, 100);
    }

    _this.alternativeFind = function (arr, callback) {
        for (var i = 0; i < arr.length; i++) {
            var match = callback(arr[i]);
            if (match) {
                return arr[i];
                break;
            }
        }
    }
}]);
;
app.controller('newDepositCalculatorController', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
    var _this = this;
    _this.$scope = $scope;
    $scope._this = _this;



    _this.entityTypes = window.entityTypes;

    //_this.types = window.types;
    _this.selectedEntityType = null;
    _this.selectedType = null;
    _this.selectedCurrency = null;

    _this.selectedSettings = null;
    _this.selectedAmount = null;
    _this.selectedMonth = null;
    _this.sum = 0;
    _this.XIRR = 0;

    _this.minMonth = 1000;
    _this.maxMonth = 0;

    _this.interest = 0;

    _this.needStaticCalculation = false;

    _this.schedule = {
        monthlyBenefits: []
    };
    _this.scheduleGEL = {
        monthlyBenefits: []
    };

    _this.init = function () {
        _this.selectedEntityType = _this.entityTypes[0];
        _this.selectedType = _this.selectedEntityType.types[0];

        _this.selectedCurrency = _this.selectedType.currencies.filter(s => s.title.toLowerCase() != 'gel')[0];

        _this.setMonth();

        _this.calculate();
        $(window).trigger('resize');
    }

    _this.changeEntityType = function () {
        $timeout(function () {
            _this.needStaticCalculation = false;
            _this.selectedType = _this.selectedEntityType.types[0];
            if (_this.selectedEntityType.id == 4) {
                _this.needStaticCalculation = true;
                _this.selectedMonth = 1;
            }
            _this.changeType();
        });
    }

    _this.changeType = function () {
        $timeout(function () {
            _this.selectedCurrency = _this.selectedType.currencies.filter(s => s.title.toLowerCase() != 'gel')[0];

            _this.changeInterest();
            _this.setMonth();
        });
    }

    _this.calculate = function () {
        $timeout(function () {

            _this.calculateDeposit();
        }, 100);
    }

    _this.changeInterest = function () {
        $timeout(function () {
            for (var i = 0; i < _this.selectedSettings.length; i++) {
                if (_this.selectedSettings[i].minMonth <= parseInt(_this.selectedMonth) && _this.selectedSettings[i].maxMonth >= parseInt(_this.selectedMonth)) {
                    _this.interest = _this.selectedSettings[i].interest;

                    _this.calculate();
                }
            }
        }, 100);
    }

    _this.setMonth = function () {
        $timeout(function () {
            _this.selectedSettings = _this.selectedCurrency.settings;
            _this.minMonth = 1000;
            _this.maxMonth = 0;
            for (var i = 0; i < _this.selectedSettings.length; i++) {
                if (_this.selectedSettings[i].minMonth < _this.minMonth) {
                    _this.minMonth = _this.selectedSettings[i].minMonth;
                }
                if (_this.selectedSettings[i].maxMonth > _this.maxMonth) {
                    _this.maxMonth = _this.selectedSettings[i].maxMonth;
                }
            }
            _this.changeInterest();
        });
    }

    _this.calculateDeposit = function () {
        $timeout(function () {
            _this.createSchedule();
        });
    }

    _this.getCurrenciesForSelect = function () {
        return _this.selectedType.currencies.filter(s => s.title.toLowerCase() != 'gel');
    }

    _this.formatNumber = function (number, fixed) {
        if (!fixed) {
            fixed = 2;
        }
        number = parseFloat(number);
        return number.toFixed(fixed).toString().replace("-", "");
    }

    _this.getNextBenefittDate = function (index, monthCount, prevDt) {
        if (index <= monthCount) {
            var benefitDate = new Date(prevDt);
            benefitDate.setMonth(prevDt.getMonth() + 1);
            return benefitDate;
        }
    }

    _this.createSchedule = function () {
        _this.schedule.monthlyBenefits = [];

        _this.values = [];
        _this.dates = [];

        var balance = 0;

        balance = _this.formatNumber(_this.selectedAmount);

        sum = 0;

        _this.dates[0] = new Date();
        _this.dates[0].setDate(_this.dates[0].getDate() + 1);
        _this.dates[0].setHours(0, 0, 0, 0);


        _this.values.push({
            "Date": _this.dates[0],
            "Flow": -1 * balance
        });

        if (_this.selectedType.isMonthly) {
            for (var i = 0; i < parseInt(_this.selectedMonth) + 1; i++) {
                if (i == 0) {
                    _this.schedule.monthlyBenefits.push({
                        "benefitDate": _this.dates[i],
                        "month": i,
                        "benefit": _this.formatNumber(balance),
                    });
                } else {
                    var nextBenefitDt = _this.getNextBenefittDate(i, parseInt(_this.selectedMonth), _this.dates[i - 1]);
                    _this.dates[i] = new Date(nextBenefitDt.getFullYear(), nextBenefitDt.getMonth(), nextBenefitDt.getDate());
                    var totalDays = _this.daysBetweenTwoDate(_this.dates[i], _this.dates[i - 1]);
                    var benefit = (balance * _this.formatNumber(_this.interest) / 100) / 365 * totalDays;
                    _this.schedule.monthlyBenefits.push({
                        "benefitDate": nextBenefitDt,
                        "month": i,
                        "benefit": i == parseInt(_this.selectedMonth) ? _this.formatNumber(parseFloat(benefit) + parseFloat(balance)) : _this.formatNumber(benefit),
                    });

                    sum += parseFloat(benefit);

                    _this.values.push({
                        "Date": nextBenefitDt,
                        "Flow": (i == parseInt(_this.selectedMonth) ? parseFloat(benefit) + parseFloat(balance) : (benefit))
                    });
                }
            }
        } else {
            _this.schedule.monthlyBenefits.push({
                "benefitDate": _this.dates[0],
                "month": 0,
                "benefit": _this.formatNumber(balance),
            });

            if (_this.needStaticCalculation) {
                _this.dates[1] = new Date();
                //_this.dates[1] = new Date(_this.dates[1].setMonth(_this.dates[1].getMonth() + parseInt(_this.selectedMonth)));
                _this.dates[1] = new Date(_this.dates[1].setDate(_this.dates[1].getDate() + 36));
                _this.dates[1].setHours(0, 0, 0, 0);
            } else {
                _this.dates[1] = new Date();
                _this.dates[1] = new Date(_this.dates[1].setMonth(_this.dates[1].getMonth() + parseInt(_this.selectedMonth)));
                _this.dates[1] = new Date(_this.dates[1].setDate(_this.dates[1].getDate() + 1));
                _this.dates[1].setHours(0, 0, 0, 0);
            }
            var totalDays = _this.daysBetweenTwoDate(_this.dates[1], _this.dates[0]);
            var benefit = (balance * _this.formatNumber(_this.interest) / 100) / 365 * totalDays;
            _this.schedule.monthlyBenefits.push({
                "benefitDate": _this.dates[1],
                "month": 1,
                "benefit": _this.formatNumber(benefit),
            });
            sum = parseFloat(benefit);
            _this.values.push({
                "Date": _this.dates[1],
                "Flow": parseFloat(benefit) + parseFloat(balance)
            });
        }



        _this.sum = _this.formatNumber(sum);
        _this.XIRR = _this.formatNumber(_this.calculateXIRR(_this.values) * 100, 3);

        _this.createScheduleForGEL();
    }

    _this.calculateXIRR = function (values, guess) {
        if (!guess) guess = 0.1;
        var x1 = 0.0;
        var x2 = guess;
        var f1 = _this.XNPV(x1, values);
        var f2 = _this.XNPV(x2, values);

        for (var i = 0; i < 100; i++) {
            if ((f1 * f2) < 0.0) break;
            if (Math.abs(f1) < Math.abs(f2)) {
                f1 = _this.XNPV(x1 += 1.6 * (x1 - x2), values);
            }
            else {
                f2 = _this.XNPV(x2 += 1.6 * (x2 - x1), values);
            }
        };

        if ((f1 * f2) > 0.0) return null;

        var f = _this.XNPV(x1, values);
        if (f < 0.0) {
            var rtb = x1;
            var dx = x2 - x1;
        }
        else {
            var rtb = x2;
            var dx = x1 - x2;
        };

        for (var i = 0; i < 100; i++) {
            dx *= 0.5;
            var x_mid = rtb + dx;
            var f_mid = _this.XNPV(x_mid, values);
            if (f_mid <= 0.0) rtb = x_mid;
            if ((Math.abs(f_mid) < 1.0e-6) || (Math.abs(dx) < 1.0e-6)) return x_mid;
        };

        return null;
    }

    _this.XNPV = function (rate, values) {
        var xnpv = 0.0;
        var firstDate = new Date(values[0].Date);
        for (var key in values) {
            var tmp = values[key];
            var value = tmp.Flow;
            var date = new Date(tmp.Date);
            xnpv += value / Math.pow(1 + rate, _this.daysBetweenTwoDate(firstDate, date) / 365);
        };
        return xnpv;
    }

    _this.daysBetweenTwoDate = function (firstDate, secondDate) {
        var firstDate = new Date(firstDate);
        var secondDate = new Date(secondDate);

        var oneDay = 1000 * 60 * 60 * 24

        return (firstDate - secondDate) / (1000 * 3600 * 24);;
    }

    _this.getSumAmount = function () {
        return _this.formatNumber(parseFloat(_this.selectedAmount) + parseFloat(_this.sum));
    }

    _this.getCurrencyRate = function () {
        if (_this.showDepositInGel())
            return window.rates.find(f => f.fromCurrency.toLowerCase() == _this.selectedCurrency.title.toLowerCase()).buy;
        else
            return 1;
    }

    _this.getBreakEvenRate = function () {
        if (_this.values != null && _this.valuesGEL != null) {
            return _this.valuesGEL[_this.valuesGEL.length - 1].Flow / _this.values[_this.values.length - 1].Flow;
        }
    }

    //GEL
    _this.getSumAmountInGel = function () {
        return _this.formatNumber(parseFloat(_this.getDepositInGel()) + parseFloat(_this.sumGEL));
    }

    _this.getDepositInGel = function () {
        return _this.formatNumber(_this.selectedAmount * _this.getCurrencyRate());
    }

    _this.showDepositInGel = function () {
        return _this.selectedCurrency.title.toLowerCase() != 'gel';
    }

    _this.GetInterestForGel = function () {
        var settings = _this.selectedType.currencies.find(s => s.title.toLowerCase() == 'gel').settings.find(c => c.minMonth <= parseInt(_this.selectedMonth) && c.maxMonth >= parseInt(_this.selectedMonth));
        if (settings != null) {
            return settings.interest;
        }
    }


    _this.createScheduleForGEL = function () {
        _this.scheduleGEL.monthlyBenefits = [];

        _this.valuesGEL = [];
        _this.datesGEL = [];

        var balance = 0;

        balance = _this.formatNumber(_this.getDepositInGel());

        sum = 0;

        _this.datesGEL[0] = new Date();
        _this.datesGEL[0].setDate(_this.datesGEL[0].getDate() + 1);
        _this.datesGEL[0].setHours(0, 0, 0, 0);


        _this.valuesGEL.push({
            "Date": _this.datesGEL[0],
            "Flow": -1 * balance
        });

        if (_this.selectedType.isMonthly) {
            for (var i = 0; i < parseInt(_this.selectedMonth) + 1; i++) {
                if (i == 0) {
                    _this.scheduleGEL.monthlyBenefits.push({
                        "benefitDate": _this.datesGEL[i],
                        "month": i,
                        "benefit": _this.formatNumber(balance),
                    });
                } else {
                    var nextBenefitDt = _this.getNextBenefittDate(i, parseInt(_this.selectedMonth), _this.datesGEL[i - 1]);
                    _this.datesGEL[i] = new Date(nextBenefitDt.getFullYear(), nextBenefitDt.getMonth(), nextBenefitDt.getDate());
                    var totalDays = _this.daysBetweenTwoDate(_this.datesGEL[i], _this.datesGEL[i - 1]);
                    var benefit = (balance * _this.formatNumber(_this.GetInterestForGel()) / 100) / 365 * totalDays;
                    _this.scheduleGEL.monthlyBenefits.push({
                        "benefitDate": nextBenefitDt,
                        "month": i,
                        "benefit": i == parseInt(_this.selectedMonth) ? _this.formatNumber(parseFloat(benefit) + parseFloat(balance)) : _this.formatNumber(benefit),
                    });

                    sum += parseFloat(benefit);

                    _this.valuesGEL.push({
                        "Date": nextBenefitDt,
                        "Flow": (i == parseInt(_this.selectedMonth) ? parseFloat(benefit) + parseFloat(balance) : (benefit))
                    });
                }
            }
        } else {
            _this.scheduleGEL.monthlyBenefits.push({
                "benefitDate": _this.datesGEL[0],
                "month": 0,
                "benefit": _this.formatNumber(balance),
            });

            if (_this.needStaticCalculation) {
                _this.datesGEL[1] = new Date();
                //_this.datesGEL[1] = new Date(_this.datesGEL[1].setMonth(_this.datesGEL[1].getMonth() + parseInt(_this.selectedMonth)));
                _this.datesGEL[1] = new Date(_this.datesGEL[1].setDate(_this.datesGEL[1].getDate() + 36));
                _this.datesGEL[1].setHours(0, 0, 0, 0);
            } else {
                _this.datesGEL[1] = new Date();
                _this.datesGEL[1] = new Date(_this.datesGEL[1].setMonth(_this.datesGEL[1].getMonth() + parseInt(_this.selectedMonth)));
                _this.datesGEL[1] = new Date(_this.datesGEL[1].setDate(_this.datesGEL[1].getDate() + 1));
                _this.datesGEL[1].setHours(0, 0, 0, 0);
            }



            var totalDays = _this.daysBetweenTwoDate(_this.datesGEL[1], _this.datesGEL[0]);
            var benefit = (balance * _this.formatNumber(_this.GetInterestForGel()) / 100) / 365 * totalDays;
            _this.scheduleGEL.monthlyBenefits.push({
                "benefitDate": _this.datesGEL[1],
                "month": 1,
                "benefit": _this.formatNumber(benefit),
            });
            sum = parseFloat(benefit);
            _this.valuesGEL.push({
                "Date": _this.datesGEL[1],
                "Flow": parseFloat(benefit) + parseFloat(balance)
            });
        }



        _this.sumGEL = _this.formatNumber(sum);
        _this.XIRRGEL = _this.formatNumber(_this.calculateXIRR(_this.valuesGEL) * 100, 3);
    }
}]);
;
app.controller('effectiveCalculatorController', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
    var _this = this;
    _this.$scope = $scope;
    $scope._this = _this;

    _this.types = window.loanTypes;
    _this.selectedType = null;
    _this.selectedSettings = null;

    _this.selectednaprFee = 0;
    _this.monthlyPayment = 0;
    _this.selectedCarPrice = 0;
    _this.MinParticipationAmount = 0;
    _this.MaxParticipationAmount = 1;
    _this.otherMonthlyPaymentsSum = 0;
    _this.currentAcountCommisionSum = 0;
    _this.selectedLifeinsurance = 0;
    _this.selectedAutoInsurancePercent = 0;
    _this.selectedLoanServiceCommision = 0;
    _this.selectedServicFeeSum = 0;
    _this.naprFeeSum = 0;
    _this.differenceBetweenPrices = 0;

    _this.showInstallmentChilds = false;
    _this.calculatedLoanAmount = 0;

    _this.selectedParticipationAmount = 0;
    _this.monthlyPaymentSum = 0;

    _this.mortgageCancellationFeeSum = 0;
    _this.mortgageFastCreditFeeSum = 0;

    _this.monthlyPaymentForOneMonth = 0;
    _this.autoDealCommission = 0;

    _this.currencyRate = 1;

    _this.dates = [];
    _this.values = [];

    _this.schedule = {
        monthlyPayments: []
    };

    _this.init = function () {

        _this.selectedType = _this.types[0];
        $timeout(function () {
            if (window.loanCalcInitTypeId > 0) {
                var requestedInitialType = _this.types.find(function (elem) { return elem.id == window.loanCalcInitTypeId });
                if (requestedInitialType != null) {
                    _this.selectedType = requestedInitialType;
                }
            }
        });
        _this.selectedSubType = _this.selectedType.types[0];
        _this.selectedSettings = _this.selectedSubType.settings[0];
        _this.setRangesDefault();
        _this.selectedcurrency = _this.selectedSettings;

        _this.setMinAndMax();

        _this.calculate();
        _this.changeType();
        $(window).trigger('resize');
    }

    _this.changeType = function () {
        $timeout(function () {
            _this.setZero();
            _this.selectedSubType = _this.selectedType.types[0];
            _this.selectedSettings = _this.selectedSubType.settings[0];
            _this.selectedCarPrice = _this.selectedSettings.carPriceValue;

            _this.selectedcurrency = _this.selectedSettings;
            _this.selectedAmount = _this.selectedSettings.minAmount;
            _this.calculateCustomerLoan();


            if (parseFloat(_this.selectedSettings.minAmount) >= parseFloat(_this.selectedSettings.maxAmount)) {
                _this.selectedSettings.maxAmount = parseFloat(_this.selectedSettings.minAmount) + 1;
            }
            _this.setRangesDefault();

            if (_this.selectedType.id == 1) {
                _this.selectedLifeinsurance = true;
            }
            if (_this.selectedType.id == 4 && _this.selectedType.types.length > 1) {
                _this.showInstallmentChilds = true;
            }
            else if (_this.selectedType.id == 2 || _this.selectedType.id == 3) //auto
            {
                _this.selectedAutoInsurancePercent = true;
            }
            else if (_this.selectedType.id == 5 || _this.selectedType.id == 6) //mortgage
            {
                _this.selectedRealEstateInsurance = true;
            }

            _this.setParticipationMinAmount();

            _this.calculate();
        });
    }

    _this.setParticipationMinAmount = function () {
        $timeout(function () {

            if (_this.selectedMonthlyExpense.length <= 0) {
                _this.selectedMonthlyExpense = 0;
            }
            if (_this.selectedOtherExpense.length <= 0) {
                _this.selectedOtherExpense = 0;
            }

            if (_this.selectedParticipationAmount.length <= 0) {
                _this.selectedParticipationAmount = 0;
            }

            if (_this.selectedType.id == 4) //express
            {
                if (_this.selectedProductAmount.length <= 0 || parseFloat(_this.selectedProductAmount) < (parseFloat(_this.minAmount))) {
                    _this.selectedProductAmount = _this.minAmount;
                }
                if (_this.differenceBetweenPrices.length <= 0) {
                    _this.differenceBetweenPrices = 0;
                }
            }
            if (_this.selectedType.id == 2 || _this.selectedType.id == 3) //auto
            {
                if (_this.selectedCarPrice.length <= 0) {
                    _this.selectedCarPrice = _this.minAmount;
                }
            } else
                if (_this.selectedType.id == 5) //mortgage
                {
                    if (_this.selectedMortgagePrice.length <= 0) {
                        _this.selectedMortgagePrice = _this.minAmount;
                    }
                    if (parseFloat(_this.selectedMortgagePrice) < (parseFloat(_this.minAmount))) {
                        _this.selectedMortgagePrice = _this.formatNumber(parseFloat(_this.minAmount));
                    }
                }
            _this.updateParticipationAmount();
        })
    }

    _this.updateParticipationAmount = function () {

        $timeout(function () {

            if (_this.selectedType.id == 2 || _this.selectedType.id == 3) //auto
            {
                var min = _this.selectedCarPrice * parseFloat(_this.selectedSettings.participationPercent);
                var max = _this.selectedCarPrice - parseFloat(_this.selectedSettings.minAmount);
            }
            else if (_this.selectedType.id == 4) //express
            {
                if (parseFloat(_this.selectedParticipationAmount) > parseFloat(_this.selectedProductAmount)) {

                    _this.selectedParticipationAmount = _this.selectedProductAmount;
                }
                _this.calculatedLoanAmount = _this.selectedProductAmount - _this.selectedParticipationAmount;

                if (parseFloat(_this.calculatedLoanAmount) > parseFloat(_this.selectedSettings.maxAmount)) {
                    _this.calculatedLoanAmount = parseFloat(_this.selectedSettings.maxAmount);
                    _this.selectedParticipationAmount = parseFloat(_this.selectedProductAmount) - parseFloat(_this.selectedSettings.maxAmount);
                }
            }
            else if (_this.selectedType.id == 5) //Mortgage
            {
                if (parseFloat(_this.selectedParticipationAmount) > parseFloat(_this.selectedMortgagePrice)) {

                    _this.selectedParticipationAmount = _this.selectedMortgagePrice;
                }
                _this.calculatedLoanAmount = _this.selectedMortgagePrice - _this.selectedParticipationAmount;
            }

            _this.calculate();
        })
    }

    _this.changeAmount = function () {
        $timeout(function () {
            _this.MinParticipationAmount = 0;
            _this.MaxParticipationAmount = _this.formatNumber(parseFloat(_this.selectedAmount) - parseFloat(_this.selectedSettings.minAmount));
            if (parseFloat(_this.MaxParticipationAmount) <= parseFloat(_this.MinParticipationAmount)) {
                _this.MaxParticipationAmount = parseFloat(_this.MinParticipationAmount) + 1;
            }
        });
    }

    _this.changeCurrency = function () {
        $timeout(function () {
            _this.setZero();
            _this.setRangesDefault();

            _this.calculate();
            // _this.calculateCustomerLoan();
        });
    }

    _this.setZero = function () {
        $timeout(function () {
            _this.minAmount = 0;
            _this.maxAmount = 1;
            _this.minInterest = 0;
            _this.maxInterest = 1;
            _this.minMonth = 0;
            _this.maxMonth = 1;
            _this.minServicFee = 0;
            _this.maxServicFee = 1;
            _this.minPaymentFee = 0;
            _this.maxPaymentFee = 1;
            _this.minCurrentAcountCommision = 0;
            _this.maxCurrentAcountCommision = 1;
            _this.minLoanServiceCommision = 0;
            _this.maxLoanServiceCommision = 1;
        })
    }

    _this.setMinAndMax = function () {
        $timeout(function () {
            _this.minAmount = _this.formatNumber(parseFloat(_this.selectedSettings.minAmount) / parseFloat(_this.currencyRate));
            _this.maxAmount = _this.formatNumber(parseFloat(_this.selectedSettings.maxAmount) / parseFloat(_this.currencyRate));
            _this.minInterest = _this.selectedSettings.minInterest;
            _this.maxInterest = _this.selectedSettings.maxInterest;
            _this.minMonth = _this.selectedSettings.minMonth;
            _this.maxMonth = _this.selectedSettings.maxMonth;
            _this.minServicFee = _this.selectedSettings.minServicFee;
            _this.maxServicFee = _this.selectedSettings.maxServicFee;
            _this.minPaymentFee = _this.selectedSettings.minPaymentFee;
            _this.maxPaymentFee = _this.selectedSettings.maxPaymentFee;
            _this.minCurrentAcountCommision = _this.selectedSettings.minCurrentAcountCommision;
            _this.maxCurrentAcountCommision = _this.selectedSettings.maxCurrentAcountCommision;
            _this.minLoanServiceCommision = _this.selectedSettings.minLoanServiceCommision;
            _this.maxLoanServiceCommision = _this.selectedSettings.maxLoanServiceCommision;
        })
    }

    _this.setRangesDefault = function () {
        $timeout(function () {
            _this.setMinAndMax();
            var currnetSelectedType = _this.selectedType;
            _this.selectedType = _this.types[0];
            _this.selectedSettings = _this.selectedcurrency;

            _this.selectedType = currnetSelectedType;
            if (_this.selectedcurrency.title == 'USD') {
                _this.currencyRate = parseFloat(window.usdRate);
            }
            else if (_this.selectedcurrency.title == 'EUR') {
                _this.currencyRate = parseFloat(window.eurRate);
            }
            else {
                _this.currencyRate = 1;
            }
            //if (_this.selectedType.id == 5 || _this.selectedType.id == 6) {
            _this.minAmount = _this.formatNumber(parseFloat(_this.selectedSettings.minAmount) / parseFloat(_this.currencyRate));
            _this.maxAmount = _this.formatNumber(parseFloat(_this.selectedSettings.maxAmount) / parseFloat(_this.currencyRate));
            //}
            _this.selectedInterest = _this.selectedSettings.minInterest;
            _this.selectedCurrentAcountCommision = _this.selectedSettings.minCurrentAcountCommision;
            _this.selectedLoanServiceCommision = _this.selectedSettings.minLoanServiceCommision;
            _this.selectedAmount = _this.minAmount;
            _this.selectedMonth = _this.selectedSettings.minMonth;
            _this.selectedMonthlyExpense = 0;
            _this.selectedOtherExpense = 0;
            _this.selectedServicFee = _this.selectedSettings.minServicFee;
            _this.selectedCarPrice = _this.formatNumber(parseFloat(_this.selectedSettings.carPriceValue) / parseFloat(_this.currencyRate));

            _this.selectedMortgagePrice = _this.formatNumber(parseFloat(_this.minAmount));
            _this.selectedProductAmount = _this.minAmount;
            _this.selectedParticipationAmount = 0;
        })
    }

    _this.calculate = function () {
        $timeout(function () {
            if (_this.selectedType.id == 1) //customer
            {
                _this.calculateCustomerLoan();
            }
            else if (_this.selectedType.id == 2 || _this.selectedType.id == 3) //auto
            {
                _this.calculateAutoLoan();
            }
            else if (_this.selectedType.id == 4) //express
            {
                _this.calculateExpressInstallment();
            }
            else if (_this.selectedType.id == 5 || _this.selectedType.id == 6) //mortgage
            {
                _this.calculateMortgageLoan();
            }
            else if (_this.selectedType.id == 7) //general
            {
                _this.calculateGeneralLoan();
            }
        });
    }

    _this.calculateCustomerLoan = function () {
        $timeout(function () {
            var percent = parseFloat(_this.selectedInterest);
            if (_this.selectedLifeinsurance) {
                percent = parseFloat(_this.selectedInterest) + parseFloat(_this.selectedcurrency.lifeinsurance);
            }
            _this.monthlyPayment = _this.formatNumber(_this.calcuatePmt(percent, _this.selectedMonth, _this.selectedAmount) + parseFloat(_this.selectedMonthlyExpense) + parseFloat(_this.selectedCurrentAcountCommision));
            _this.selectedServicFeeSum = _this.formatNumber(parseFloat(_this.selectedAmount) * parseFloat(_this.selectedServicFee) / 100);

            _this.createSchedule();

        })
    }

    _this.calculateAutoLoan = function () {
        $timeout(function () {
            var percent = parseFloat(_this.selectedInterest);
            _this.calculatedLoanAmount = _this.formatNumber((parseFloat(_this.selectedCarPrice) - parseFloat(_this.selectedParticipationAmount)));
            _this.autoDealCommission = _this.calculatedLoanAmount * 0.1 / 100;

            if (parseFloat(_this.autoDealCommission) < parseFloat(_this.selectedcurrency.autoDealCommission)) {
                _this.autoDealCommission = _this.selectedcurrency.autoDealCommission;
            }
            if (_this.selectedAutoInsurancePercent) {
                percent = parseFloat(_this.selectedInterest);// + _this.selectedcurrency.autoInsurance;
            }
            if (_this.selectedType.id == 2) {
                _this.calculatedLoanAmountWithComissions = _this.formatNumber(((parseFloat(_this.calculatedLoanAmount)) + parseFloat(_this.selectedcurrency.miaFee) + parseFloat(_this.autoDealCommission)) / ((100 - parseFloat(_this.selectedServicFee)) / 100));

            } else if (_this.selectedType.id == 3) {
                _this.calculatedLoanAmountWithComissions = _this.formatNumber(((parseFloat(_this.calculatedLoanAmount)) + parseFloat(_this.selectedcurrency.miaFee)) / ((100 - parseFloat(_this.selectedServicFee)) / 100));
            }
            _this.monthlyPayment = _this.formatNumber(_this.calcuatePmt(percent, _this.selectedMonth, _this.calculatedLoanAmountWithComissions) + parseFloat(_this.selectedCurrentAcountCommision));
            _this.createSchedule();

        })
    }

    _this.calculateMortgageLoan = function () {
        $timeout(function () {
            var percent = parseFloat(_this.selectedInterest);
            //if (_this.selectedLifeinsurance) {
            //    percent = parseFloat(_this.selectedInterest) + _this.selectedcurrency.lifeinsurance;
            //}
            if (_this.selectedRealEstateInsurance) {
                percent = percent + _this.selectedcurrency.realEstateInsurance;
            }
            //if (_this.selectedMortgageCancellationFee) {
            _this.mortgageCancellationFeeSum = _this.formatNumber(parseFloat(_this.selectedRealEstateCount) * (parseFloat(_this.selectedcurrency.mortgageCancellationFee)));
            //}
            _this.mortgageFastCreditFeeSum = _this.formatNumber(parseFloat(_this.selectedRealEstateCount) * parseFloat(_this.selectedSettings.mortgageFastCreditFee));
            if (_this.selectedType.id == 5) {
                _this.calculatedLoanAmount = _this.formatNumber(((_this.selectedMortgagePrice - _this.selectedParticipationAmount) * 100) / (100 - (_this.selectedServicFee)));//+ (_this.selectedMortgagePrice * _this.selectedServicFee / 100);

            } else {
                _this.calculatedLoanAmount = _this.formatNumber(_this.selectedAmount);

            }
            _this.monthlyPayment = _this.formatNumber(_this.calcuatePmt(percent, _this.selectedMonth, _this.calculatedLoanAmount) + (parseFloat(_this.selectedCurrentAcountCommision) / parseFloat(_this.currencyRate)) + (parseFloat(_this.selectedMonthlyExpense) / parseFloat(_this.currencyRate)));

            //_this.monthlyPayment = _this.calcuatePmt(percent / 12, _this.selectedMonth, _this.calculatedLoanAmount) + parseFloat(_this.selectedCurrentAcountCommision) + IF(I2 = $F$5; $F$12; 0)+$F$16;

            _this.naprFeeSum = _this.formatNumber(_this.selectedRealEstateCount * _this.selectedcurrency.naprFee);
            _this.selectedServicFeeSum = _this.formatNumber(parseFloat(_this.selectedAmount) * parseFloat(_this.selectedServicFee) / 100);
            _this.createSchedule();
        })
    }

    _this.calculateExpressInstallment = function () {
        $timeout(function () {
            _this.calculatedLoanAmount = _this.selectedProductAmount - _this.selectedParticipationAmount;

            _this.selectedServicFeeSum = _this.formatNumber(parseFloat(_this.selectedAmount) * parseFloat(_this.selectedServicFee) / 100);

            _this.monthlyPayment = _this.formatNumber(_this.calcuatePmt(_this.selectedInterest, _this.selectedMonth, (_this.selectedAmount)));
            _this.monthlyPayment = parseFloat(_this.monthlyPayment) + parseFloat(_this.selectedCurrentAcountCommision) + parseFloat(_this.selectedLoanServiceCommision)
            _this.createSchedule();

        })
    }

    _this.calcuatePmt = function (apr, term, loan) {
        if (apr <= 0) {
            return loan / term;
        }
        apr = apr / 1200;

        var amount = apr * -loan * Math.pow((1 + apr), term) / (1 - Math.pow((1 + apr), term));

        return parseFloat(amount);
    }

    _this.formatNumber = function (number) {
        number = parseFloat(number);
        return number.toFixed(2).toString().replace("-", "");
    }

    _this.createSchedule = function () {
        _this.schedule.monthlyPayments = [];
        _this.values = [];
        _this.dates = [];
        var balance = 0;
        var percent = 0;
        var percentsSum = 0;
        var monthlyPaymentSum = 0;
        var monthlyPaymentsSum = 0;

        if (_this.selectedType.id == 2) {
            _this.selectedAmount = _this.formatNumber(((parseFloat(_this.calculatedLoanAmount)) + parseFloat(_this.selectedcurrency.miaFee) + parseFloat(_this.autoDealCommission)) / ((100 - parseFloat(_this.selectedServicFee)) / 100));
        }
        else if (_this.selectedType.id == 3) {
            _this.selectedAmount = _this.formatNumber(((parseFloat(_this.calculatedLoanAmount)) + parseFloat(_this.selectedcurrency.miaFee)) / ((100 - parseFloat(_this.selectedServicFee)) / 100));
        }
        else if (_this.selectedType.id == 4) {
            _this.selectedAmount = (_this.calculatedLoanAmount * (_this.selectedServicFee / 100) + _this.calculatedLoanAmount);
        }
        else if (_this.selectedType.id == 5 || _this.selectedType.id == 6) {
            _this.selectedAmount = (_this.calculatedLoanAmount);
        }


        balance = _this.selectedAmount;

        _this.dates[0] = new Date();


        if (_this.selectedType.id == 1) {//customer
            _this.values.push({
                "Date": new Date(),
                "Flow": -1 * (_this.selectedAmount - (parseFloat(_this.selectedServicFee / 100)) * _this.selectedAmount - ((_this.selectedAmount - (parseFloat(_this.selectedServicFee / 100)) * _this.selectedAmount)) * parseFloat(_this.selectedPaymentFeePecent / 100)) + parseFloat(_this.selectedOtherExpense)
            });
        }
        else if (_this.selectedType.id == 2) {// auto
            _this.values.push({
                "Date": new Date(),
                "Flow": -1 * parseFloat(_this.formatNumber(((_this.selectedAmount - (_this.selectedAmount * (parseFloat(_this.selectedServicFee) / 100)) - parseFloat(_this.selectedcurrency.miaFee) - parseFloat(_this.autoDealCommission))))) + parseFloat(_this.selectedOtherExpense)
            });
        }
        else if (_this.selectedType.id == 3) {// auto
            _this.values.push({
                "Date": new Date(),
                "Flow": -1 * ((_this.selectedAmount - _this.selectedAmount * (parseFloat(_this.selectedServicFee) / 100) - parseFloat(_this.selectedcurrency.miaFee))) + parseFloat(_this.selectedOtherExpense)
            });
        }
        else if (_this.selectedType.id == 4) {//express installment
            _this.values.push({
                "Date": new Date(),
                "Flow": -1 * (_this.selectedAmount - (_this.calculatedLoanAmount) * (_this.selectedServicFee / 100) - _this.differenceBetweenPrices) + parseFloat(_this.selectedOtherExpense)
            });
        }
        else if (_this.selectedType.id == 5 || _this.selectedType.id == 6) {//mortgage
            _this.values.push({
                "Date": new Date(),
                "Flow": -1 * (_this.calculatedLoanAmount - (_this.selectedServicFee / 100) * _this.calculatedLoanAmount - ((parseFloat(_this.naprFeeSum) / parseFloat(_this.currencyRate)) + (parseFloat(_this.mortgageFastCreditFeeSum) / parseFloat(_this.currencyRate))) - ((_this.calculatedLoanAmount - (_this.selectedServicFee / 100) * _this.calculatedLoanAmount)) * parseFloat(_this.selectedPaymentFeePecent / 100)) + (parseFloat(_this.selectedOtherExpense) / parseFloat(_this.currencyRate))
                //"Flow": -1 * (_this.selectedAmount - (_this.calculatedLoanAmount) * (_this.selectedServicFee / 100) - _this.differenceBetweenPrices) + parseFloat(_this.selectedOtherExpense)
            });
        }
        else {
            _this.values.push({
                "Date": new Date(),
                "Flow": -1 * (_this.selectedAmount - (_this.calculatedLoanAmount - _this.selectedParticipationAmount) * (_this.selectedServicFee / 100) - _this.differenceBetweenPrices)
            });
        }

        //_this.values.push({
        //    "Date": new Date(),
        //    //"Flow": -1 * parseFloat(_this.selectedAmount - ((_this.selectedServicFee / 100) * _this.selectedAmount) - (_this.selectednaprFee + 0) - ((_this.selectedAmount - (_this.selectedServicFee / 100) * _this.selectedAmount)) * 0.2 / 100)
        //    "Flow": -1 * (_this.selectedAmount - (_this.calculatedLoanAmount - _this.selectedParticipationAmount) * (_this.selectedServicFee / 100) - _this.differenceBetweenPrices)
        //});



        for (var i = 1; i < _this.selectedMonth + 1; i++) {

            percent = ((balance * (_this.selectedInterest / 100)) / 12);
            percentsSum += percent;

            balance -= ((_this.calcuatePmt(_this.selectedInterest, _this.selectedMonth, _this.selectedAmount)) - percent);

            var nextPaymentDt = _this.getNextPaymentDate(i, _this.selectedMonth, _this.dates[i - 1]);

            _this.dates[i] = new Date(nextPaymentDt.getFullYear(), nextPaymentDt.getMonth(), nextPaymentDt.getDate());


            if (_this.selectedType.id == 1) {
                _this.monthlyPaymentForOneMonth = monthlyPaymentSum = parseFloat(_this.monthlyPayment);
            }
            else if (_this.selectedType.id == 2 || _this.selectedType.id == 3) {

                //var autoPerncet = 0;
                //if (_this.selectedRealEstateInsurance) {
                //    autoPerncet = _this.selectedcurrency.realEstateInsurance;
                //}
                //var autoInsurance = Math.pow((1 - 0.1), parseInt(i / 12)) * _this.selectedCarPrice * (autoPerncet / 100) / 365 * _this.daysBetweenTwoDate(_this.dates[i - 1], _this.dates[i]);

                //_this.selectedAmount = _this.formatNumber(_this.selectedCarPrice - _this.selectedParticipationAmount);

                var monthlyInsuranceAmount = 0;

                if (i > 6) {
                    if (_this.selectedAutoInsurancePercent) {
                        monthlyInsuranceAmount = (parseFloat(_this.selectedCarPrice) * (parseFloat(_this.selectedcurrency.autoInsurance) / 100)) / 12;
                    }
                }
                _this.monthlyPaymentForOneMonth = monthlyPaymentSum = parseFloat(_this.monthlyPayment) + parseFloat(_this.selectedMonthlyExpense) + parseFloat(monthlyInsuranceAmount);

            }
            else if (_this.selectedType.id == 4) {
                _this.monthlyPaymentForOneMonth = monthlyPaymentSum = parseFloat(_this.monthlyPayment) + parseFloat(_this.selectedMonthlyExpense);
            }
            else if (_this.selectedType.id == 5 || _this.selectedType.id == 6) {
                _this.monthlyPaymentForOneMonth = monthlyPaymentSum = parseFloat(_this.monthlyPayment);
                if (i == _this.selectedMonth) {
                    monthlyPaymentSum = parseFloat(_this.monthlyPayment) + (parseFloat(_this.mortgageCancellationFeeSum) / parseFloat(_this.currencyRate))

                }
            }
            else {
                _this.monthlyPaymentForOneMonth = monthlyPaymentSum = parseFloat(_this.monthlyPayment) + parseFloat(_this.selectedCurrentAcountCommision);
            }

            _this.monthlyPaymentForOneMonth = _this.formatNumber(_this.monthlyPaymentForOneMonth);

            monthlyPaymentsSum = monthlyPaymentSum;

            _this.schedule.monthlyPayments.push({
                "paymentDate": nextPaymentDt,
                "month": i,
                "monthly": _this.formatNumber(parseFloat(_this.monthlyPayment)),
                "loan": _this.formatNumber(((_this.calcuatePmt(_this.selectedInterest, _this.selectedMonth, _this.selectedAmount)) - percent)),
                "percent": _this.formatNumber(percent),
                "balance": _this.formatNumber(balance),
                "autoInsurance": _this.formatNumber(parseFloat(monthlyInsuranceAmount)),
                "monthlyPaymentSum": _this.formatNumber(monthlyPaymentSum),
                "lifeIns": _this.selectedLifeinsurance ? _this.formatNumber(parseFloat(balance) * (_this.selectedcurrency.lifeinsurance / 100) / 365 * _this.daysBetweenTwoDate(_this.dates[i - 1], _this.dates[i])) : 0,
                "realEstInst": _this.selectedRealEstateInsurance ? _this.formatNumber(parseFloat(balance) * (_this.selectedcurrency.realEstateInsurance / 100) / 365 * _this.daysBetweenTwoDate(_this.dates[i - 1], _this.dates[i])) : 0
            });


            _this.values.push({
                "Date": nextPaymentDt,
                "Flow": parseFloat(monthlyPaymentsSum)
            });


        }
        _this.monthlyPaymentsSum = _this.formatNumber(monthlyPaymentsSum /*+ (_this.selectedCurrentAcountCommision * _this.selectedMonth)*/);
        _this.otherMonthlyPaymentsSum = _this.formatNumber((_this.selectedMonthlyExpense * _this.selectedMonth));
        _this.currentAcountCommisionSum = _this.formatNumber(_this.selectedCurrentAcountCommision * _this.selectedMonth);
        _this.monthlyPercentsSum = _this.formatNumber(percentsSum);
        _this.XIRR = _this.formatNumber(_this.calculateXIRR(_this.values) * 100);

    }

    _this.daysBetweenTwoDate = function (firstDate, secondDate) {
        var firstDate = new Date(firstDate);
        var secondDate = new Date(secondDate);

        var oneDay = 1000 * 60 * 60 * 24

        return Math.ceil((secondDate.getTime() - firstDate.getTime()) / (oneDay));
    }

    _this.calculateXIRR = function (values, guess) {
        if (!guess) guess = 0.1;

        for (var i = 1; i < values.length; i++) {
            values[i].Date.setDate(1);
            values[i].Date.setMonth(values[i].Date.getMonth() + 1);
            values[i].Date.setDate(values[i].Date.getDate() - 1)
        }



        var x1 = 0.0;
        var x2 = guess;
        var f1 = _this.XNPV(x1, values);
        var f2 = _this.XNPV(x2, values);

        for (var i = 0; i < 100; i++) {
            if ((f1 * f2) < 0.0) break;
            if (Math.abs(f1) < Math.abs(f2)) {
                f1 = _this.XNPV(x1 += 1.6 * (x1 - x2), values);
            }
            else {
                f2 = _this.XNPV(x2 += 1.6 * (x2 - x1), values);
            }
        };

        if ((f1 * f2) > 0.0) return null;

        var f = _this.XNPV(x1, values);
        if (f < 0.0) {
            var rtb = x1;
            var dx = x2 - x1;
        }
        else {
            var rtb = x2;
            var dx = x1 - x2;
        };

        for (var i = 0; i < 100; i++) {
            dx *= 0.5;
            var x_mid = rtb + dx;
            var f_mid = _this.XNPV(x_mid, values);
            if (f_mid <= 0.0) rtb = x_mid;
            if ((Math.abs(f_mid) < 1.0e-6) || (Math.abs(dx) < 1.0e-6)) return x_mid;
        };

        return null;
    }

    _this.XNPV = function (rate, values) {
        var xnpv = 0.0;
        var firstDate = new Date(values[0].Date);
        for (var key in values) {
            var tmp = values[key];
            var value = tmp.Flow;
            var date = new Date(tmp.Date);
            xnpv += value / Math.pow(1 + rate, _this.daysBetweenTwoDate(firstDate, date) / 365);
        };
        return xnpv;
    }

    _this.getNextPaymentDate = function (index, monthCount, prevDt) {
        if (index <= monthCount) {
            var paymentDate = new Date(prevDt);

            paymentDate.setMonth(prevDt.getMonth() + 1);
            return paymentDate;
        }
    }

    _this.calculateGeneralLoan = function () {
        $timeout(function () {
            var percent = parseFloat(_this.selectedInterest);

            _this.monthlyPayment = _this.formatNumber(_this.calcuatePmt(percent, _this.selectedMonth, _this.selectedAmount));
            _this.createSchedule();

        })
    }
}]);
;
app.controller('feedbackController', ['$scope', '$http', function ($scope, $http) {
    var _this = this;
    _this.$scope = $scope;
    $scope._this = _this;

    _this.isSubmited = false;
    _this.sendingData = false;
    _this.showForm = true;
    _this.message = null;


    _this.feedbackComplainTypes = null;
    _this.feedbackProducts = null;
    _this.feedbackTypes = null;


    _this.data = {
        feedbackType: null,
        feedbackProduct: null,
        feedbackComplainType: null,

        fullName: null,
        idNumber: null,
        phoneNumber: null,
        address: null,
        email: null,
        otherComplainText: null,
        otherProductText: null,
        message: null,
        agreeChecked: null,
        captcha: null
    }

    _this.init = function () {
        _this.feedbackComplainTypes = window.feedbackComplainTypes;
        _this.feedbackProducts = window.feedbackProducts;
        _this.feedbackTypes = window.feedbackTypes;
    }

    _this.send = function (languageId) {
        _this.isSubmited = true;

        if (!_this.data.agreeChecked) {
            return;
        }

        if (_this.data.feedbackType == null || _this.data.feedbackProduct == null || _this.data.feedbackComplainType == null) {
            return;
        }

        if (!_this.data.fullName || !_this.data.idNumber || !_this.data.phoneNumber || !_this.data.address
            || !_this.data.email || !_this.data.message || !_this.data.captcha) {
            return;
        }

        if (_this.isOtherComplainTypeSelected() && !_this.data.otherComplainText) { return; }
        if (_this.isOtherProductSelected() && !_this.data.otherProductText) { return; }

        _this.sendingData = true;
        $http.post('~/api/feedback/send',
            {
                feedbackType: _this.data.feedbackType.title,
                feedbackProduct: _this.data.feedbackProduct.title,
                feedbackComplainType: _this.data.feedbackComplainType.title,
                fullName: _this.data.fullName,
                idNumber: _this.data.idNumber,
                phoneNumber: _this.data.phoneNumber,
                address: _this.data.address,
                email: _this.data.email,
                otherComplainText: _this.data.otherComplainText,
                otherProductText: _this.data.otherProductText,
                message: _this.data.message,
                captcha: _this.data.captcha,
                languageId: languageId
            }).then(function successCallback(response) {
                if (response.data.success) {
                    _this.showForm = false;
                }
                _this.message = response.data.message;
            }).catch(function (e) {

            }).finally(function (e) {
                _this.sendingData = false;
                $('.captcha').attr('src', $('.captcha').attr('src') + '1');
            });
    }

    _this.isOtherComplainTypeSelected = function () {
        return _this.feedbackComplainTypes[_this.feedbackComplainTypes.length - 1].title == (_this.data.feedbackComplainType || {}).title;
    }

    _this.isOtherProductSelected = function () {
        return _this.feedbackProducts[_this.feedbackProducts.length - 1].title == (_this.data.feedbackProduct || {}).title;
    }
}]);
;
app.controller('itemsCompareController', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
    var _this = this;
    _this.$scope = $scope;
    $scope._this = _this;

    _this.showCompareTable = false;

    _this.data = {
        items: null
    };

    _this.init = function () {
        _this.data.items = window.items;

    }

    _this.isAnyItemChosen = function () {

        for (var i = 0; i < _this.data.items.length; i++) {
            if (_this.data.items[i].isChosen) {
                return true;
            }
        }

        return false;
    }

    _this.chooseItem = function (item) {
        item.isChosen = true;

    }

    _this.compareItems = function () {
        _this.showCompareTable = true;
    }

    _this.clearItems = function () {
        for (var i = 0; i < _this.data.items.length; i++) {
            _this.data.items[i].isChosen = false;
        }
    }

    $scope.$watch('_this.data.items', function () {
        if (!_this.isAnyItemChosen()) {
            _this.showCompareTable = false;
        }

        $timeout(function () {
            $(".item-details .item-title").equalHeights();
            $(".inner-compared-item-title").equalHeights();
            $(".item-line").equalHeights({ useOuterHeight: true })
        })
       

    }, true);
}]);
;
app.controller('loanCalculatorController', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
    var _this = this;
    _this.$scope = $scope;
    $scope._this = _this;

    _this.currencies = window.names;
    _this.types = window.types;
    _this.selectedType = null;
    _this.selectedSettings = null;

    _this.selectedInterest = null;
    _this.selectedAmount = null;
    _this.selectedMonth = null;

    _this.monthlyPayment = 0;

    _this.monthlyPaymentsSum = 0;
    _this.monthlyPercentsSum = 0;

    _this.schedule = {
        monthlyPayments: []
    };


    _this.init = function () {
        _this.selectedType = _this.types[0];
        _this.selectedSettings = _this.selectedType.settings[0];
        _this.calculate();

        $(window).trigger('resize');

        $timeout(function () {
            if (window.loanCalcInitTypeId > 0) {
                var requestedInitialType = _this.types.find(function (elem) { return elem.id == window.loanCalcInitTypeId });
                if (requestedInitialType != null) {
                    _this.selectedType = requestedInitialType;
                    _this.changeType();
                }
            }
        });
    }
    _this.changeType = function () {
        $timeout(function () {
            _this.selectedSettings = _this.selectedType.settings[0];
            _this.selectedInterest = _this.selectedSettings.minInterest;
            _this.selectedAmount = _this.selectedSettings.minAmount;
            _this.selectedMonth = _this.selectedSettings.minMonth;
            _this.calculate();
        });
    }

    _this.changeCurrency = function () {
        $timeout(function () {
            _this.selectedInterest = _this.selectedSettings.minInterest;
            _this.selectedAmount = _this.selectedSettings.minAmount;
            _this.selectedMonth = _this.selectedSettings.minMonth;
            _this.calculate();
        });
    }


    _this.calculate = function () {
        $timeout(function () {
            _this.monthlyPayment = _this.formatNumber(_this.calcuatePmt(_this.selectedInterest, _this.selectedMonth, _this.selectedAmount));
            _this.createSchedule();
        }, 100);
    }
    _this.calcuatePmt = function (apr, term, loan) {
        apr = apr / 1200;
        var amount = apr * -loan * Math.pow((1 + apr), term) / (1 - Math.pow((1 + apr), term));
        return amount;
    }

    _this.createSchedule = function () {
        _this.schedule.monthlyPayments = [];
        var balance = _this.selectedAmount;
        var percent = 0;
        var percentsSum = 0;

        for (var i = 1; i < _this.selectedMonth + 1; i++) {


            percent = ((balance * (_this.selectedInterest / 100)) / 12);

            balance -= ((_this.calcuatePmt(_this.selectedInterest, _this.selectedMonth, _this.selectedAmount)) - percent);

            percentsSum += percent;

            _this.monthlyPaymentsSum = _this.formatNumber(i * _this.monthlyPayment);
            _this.schedule.monthlyPayments.push({
                "month": i,
                "monthly": _this.monthlyPayment,
                "loan": _this.formatNumber(((_this.calcuatePmt(_this.selectedInterest, _this.selectedMonth, _this.selectedAmount)) - percent)),
                "percent": _this.formatNumber(percent),
                "balance": _this.formatNumber(balance)
            });


        }

        _this.monthlyPercentsSum = _this.formatNumber(percentsSum)
    }

    _this.formatNumber = function (number) {
        return number.toFixed(4).toString().slice(0, -2);
    }

}]);
;
app.controller('goldCalculatorController', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
    var _this = this;
    _this.$scope = $scope;
    $scope._this = _this;

    _this.finenesses = window.finenesses;
    _this.selectedFineness = null;
    _this.weight = 0;
    _this.loanAmount = 0;

    _this.changeFineness = function () {
        $timeout(function () {
            _this.calculate();
        });
    }

    _this.calculate = function () {
        _this.loanAmount = _this.formatNumber(_this.selectedFineness.priceInGel * _this.weight);
    }

    _this.formatNumber = function (number) {
        return number.toFixed(4).toString().slice(0, -2);
    }

}]);
;
app.controller('partnerDeveloperLoanController', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
    var _this = this;
    _this.$scope = $scope;
    $scope._this = _this;

    _this.showCompareTable = false;

    _this.cities = null;
    _this.selectedCity = null;

    _this.districts = null;
    _this.selectedDistrict = null;

    _this.companies = null;
    _this.selectedCompany = null;

    _this.minAmount = null;
    _this.maxAmount = null;
    _this.amounts = [];

    _this.showFilterButton = false;

    _this.selectedPrice = null;

    _this.data = {
        items: null
    };

    _this.init = function () {
        _this.data.items = window.items;
        _this.cities = window.cities;
        _this.companies = window.companies;
        _this.data.items.forEach(function (item) {
            _this.amounts.push(item.monthlyPayment);
        })
        _this.minAmount = Math.min.apply(null, _this.amounts);
        _this.maxAmount = Math.max.apply(null, _this.amounts);
        if (_this.minAmount == _this.maxAmount) {
            _this.maxAmount += 1;
        }
        _this.selectedPrice = _this.maxAmount;
        $(window).trigger('resize');
    }

    _this.isAnyItemChosen = function () {

        for (var i = 0; i < _this.data.items.length; i++) {
            if (_this.data.items[i].isChosen) {
                return true;
            }
        }

        return false;
    }

    _this.chooseItem = function (item) {
        item.isChosen = true;

    }

    _this.compareItems = function () {
        _this.showCompareTable = true;
    }

    _this.clearItems = function () {
        for (var i = 0; i < _this.data.items.length; i++) {
            _this.data.items[i].isChosen = false;
        }
    }

    _this.changeCity = function () {
        $timeout(function () {
            _this.districts = _this.selectedCity.districts;
            _this.selectedDistrict = null;
            _this.filter();
        })
    }

    _this.changeCompany = function () {
        $timeout(function () {
            _this.filter();

        })
    }

    _this.filterWithPrice = function () {
        $timeout(function () {
            _this.filter();

        })
    }

    _this.filterCompanies = function (items) {
       
        _this.companies = [];
        $timeout(function () {

            for (var i = 0; i < items.length; i++) {
                var currentItem = items[i];
                if (!!currentItem.visible) {
                    var exist = false;

                    _this.companies.forEach(function (item) {
                        if (item.id == currentItem.company.id) {
                            exist = true;
                        }
                    });


                    if (!exist) {
                        _this.companies.push(currentItem.company);
                    }
                }
            }
        })
    }

    _this.filter = function () {
        $timeout(function () {
            if (_this.selectedCity != null || _this.selectedDistrict != null || _this.selectedCompany != null || _this.selectedPrice != _this.maxAmount) {

                _this.showFilterButton = true;
            }

            for (var i = 0; i < _this.data.items.length; i++) {
                var currentItem = _this.data.items[i];

                currentItem.visible = true;

                if (_this.selectedDistrict != null) {
                    if (currentItem.district.title != _this.selectedDistrict.title) {
                        currentItem.visible = false;
                    }
                }
                else if (_this.selectedCity != null) {
                    if (currentItem.district.city != _this.selectedCity.title) {
                        currentItem.visible = false;
                    }
                }

                if (currentItem.monthlyPayment > _this.selectedPrice) {
                    currentItem.visible = false;
                }

                if (_this.selectedCompany != null && currentItem.company.id != _this.selectedCompany.id) {
                    currentItem.visible = false;
                }

            }
        })

        _this.filterCompanies(_this.data.items);
    }

    _this.getVisibleCount = function (items) {
        var count = 0;
        for (var i = 0; i < items.length; i++) {
            if (!!items[i].visible) { count++; }
        }

        return count;
    }
    _this.clearFilter = function (items) {
        _this.selectedCity = null;
        _this.selectedDistrict = null;
        _this.selectedCompany = null;
        _this.selectedPrice = _this.maxAmount;
        _this.filter();
        _this.showFilterButton = false;
    }
    $scope.$watch('_this.data.items', function () {
        if (!_this.isAnyItemChosen()) {
            _this.showCompareTable = false;
        }
        $timeout(function () { $(".item-details .item-title").equalHeights(); })
    }, true);

}]);
;
app.directive('bindHtml', function () {
    return {
        restrict: 'A',
        link: function ($scope, $elem, $attrs, modelCtrl) {
            var setHtmlValue = function () {
                var htmlText = $attrs.bindHtml || "";
                $($elem).html(htmlText);

                //$($elem).html($($elem).text());
            }

            setHtmlValue();
           

            $attrs.$observe('bindHtml', function () {
                setHtmlValue();
            });
        }
    };
});
;
app.directive('vtbCompare', function () {
    return {
        restrict: 'E',
        replace: true,
        template: '<div data-ng-show="showCompareTable()">\
                    <div class="inner-compared-items" style="display: block;">\
                    <table>\
                        <tr>\
                            <td>\
                                <div class="inner-compared-item-img"></div>\
                            </td>\
                            <td data-ng-repeat="item in items"\
                                data-ng-if="item.isChosen">\
                                <div class="inner-compared-item-img" style="background-image: url({{item.imageUrl}});"></div>\
                            </td>\
                           </tr>\
                        <tr>\
                            <td></td>\
                            <td data-ng-repeat="item in items"\
                                data-ng-if="item.isChosen">\
                                <div class="inner-compared-item-title">{{item.title}}</div>\
                            </td>\
                        </tr>\
                        <tr>\
                            <td></td>\
                            <td data-ng-repeat="item in items"\
                                data-ng-if="item.isChosen">\
                                <button type="button" class="box box-md box-outline box-outline-blue sm two-state-hover caps"\
                                        data-ng-click="item.isChosen = false">\
                                    <i class="i-x-slim-blue default-state m-r-5"></i>\
                                    <i class="i-x-slim-white hover-state m-r-5"></i>\
                                   {{deletePhrase()}}\
                                </button>\
                            </td>\
                        </tr>\
                        <tr data-ng-repeat="c in getCharacteristics() track by $index"\
                             data-ng-if="isFieldVisible(c)">\
                            <td>{{c.title}}</td>\
                            <td data-ng-repeat="item in getIndexCharacteristics($index) track by $index">{{item}}</td>\
                        </tr>\
                    </table>\
                </div>\
            </div>',
        scope: {
            items: '=',
            showCompareTable: '&',
            deletePhrase: '&'
        },
        controller: ['$scope', '$timeout', function ($scope, $timeout) {
            var _this = this;

            $scope.getCharacteristics = function () {
                if (!$scope.items.length) { return []; }
                return $scope.items[0].characteristics;
            }

            $scope.isFieldVisible = function (character) {
                var visible = false;
                
                for (var i = 0; i < $scope.items.length; i++) {
                    var item = $scope.items[i];
                    for (var c = 0; c < item.characteristics.length; c++) {
                        var singleCharacter = item.characteristics[c];
                        if (singleCharacter.id == character.id && !!singleCharacter.value) {
                            visible = true;
                        }
                    }
                }

                return visible;
            }

            $scope.getIndexCharacteristics = function (index) {
                var values = [];

                for (var i = 0; i < $scope.items.length; i++) {
                    if ($scope.items[i].isChosen) {
                        values.push($scope.items[i].characteristics[index].value);
                    }
                }

                return values;
            }

            $scope.$watch('items', function () {
                if (!$scope.showCompareTable()) { return; }
                $timeout(function () {
                    $scope.setJsp();
                }, 200)
            }, true);

            $scope.$watch('showCompareTable()', function () {
                if (!$scope.showCompareTable()) {
                    $scope.destroyJsp();
                    return;
                }
                $timeout(function () {
                    $scope.setJsp();
                }, 200)
            })
        }],
        link: function ($scope, $elem, $attr) {
            $scope.$elem = $elem;

            $scope.$jspElem = $($scope.$elem).find('.inner-compared-items');

            $scope.setJsp = function () {
                var jsp = $($scope.$jspElem).data('jsp');
                if (jsp) { jsp.destroy(); }
                $($scope.$jspElem).jScrollPane();
                $(window).scrollTop($($scope.$jspElem).offset().top - 95);
                setTimeout(function () { $(window).trigger('resize'); }, 400);
            }

            $scope.destroyJsp = function () {
                var jsp = $($scope.$jspElem).data('jsp');
                if (jsp) { jsp.destroy(); }
            }

        }
    }
});;
app.directive('currencySelect', function () {
    return {
        restrict: 'E',
        replace: true,
        template: '<div class="select-wrapper {{class}}">\
                        <a href="" class="select-trigger ng-js-select-trigger  js-select-trigger-ng"><span><i class="flag-icon flag-icon-default flag-icon-{{getPlaceholder() | limitTo : 2 | lowercase}}"></i>{{getPlaceholder()}}</span></a>\
                        <div class="select-results js-select-results">\
         <div class="select-results-one-big-item">\
                            <a href=""\
                               data-ng-repeat="n in items()"\
                               data-ng-click="selectItem(n)">\
                                <i class="flag-icon flag-icon-default flag-icon-{{n.title | limitTo : 2 | lowercase}}"></i>\
                                {{n.title}}\
                            </a>\
         </div>\
                        </div>\
                    </div>',
        scope: {
            items: '&',
            placeholder: '&',
            ngModel: '=',
            change: '&',
            class: '@',
            calculate: "&"
        },
        controller: ['$scope', function ($scope) {
            var _this = this;

            $scope.getPlaceholder = function () {
                if ($scope.ngModel == null) { return $scope.placeholder(); }

                return $scope.ngModel.title;
            }

            $scope.selectItem = function (item) {
                $scope.ngModel = item;
                $($scope.$elem).trigger('click');
                $scope.change();
                //$scope.calculate();
            }

        }],
        link: function ($scope, $elem, $attr) {
            $scope.$elem = $elem;
            
            var $selectTrigger = $($elem).find('.js-select-trigger-ng');
            $selectTrigger.on('click', function (e) {
                console.log(5);
                e.preventDefault();
                if ($(this).parents('.select-wrapper').hasClass('open')) {
                    var jsp = $(this).parents('.select-wrapper').find('.select-results').data('jsp');
                    if (jsp) {
                        jsp.destroy();
                    }
                    $(this).parents('.select-wrapper').removeClass('open');
                    $(this).siblings('.js-select-results').stop().slideToggle(200);
                } else {
                    $(this).parents('.select-wrapper').addClass('open');
                    $(this).siblings('.js-select-results').stop().slideToggle(200);
                }
            });
            $("body").on('click', function (e) {
                var $parSelectWrapper = $(e.target).parents('.select-wrapper');
                $('.select-wrapper').each(function (i, sw) {
                    //don't close select-wrappers that are parenting the clicked element
                    if ($parSelectWrapper.length > 0 && $parSelectWrapper[0].isSameNode(sw)) {
                        return;
                    }
                    //only run this [auto-closing] code on opened select wrappers
                    if ($(sw).hasClass('open')) {
                        var jsp = $(sw).find('.select-results').data('jsp');
                        if (jsp) {
                            jsp.destroy();
                        }
                        $(sw).find('.js-select-results').hide();
                        $(sw).removeClass('open');
                    }
                });
            });
            //$selectTrigger.on('click', function () {
            //    $selectTrigger.siblings('.js-select-results').stop().slideToggle(200);

            //    $selectTrigger.parents('.select-wrapper').toggleClass('open');

            //    setTimeout(function () {
            //        if ($selectTrigger.parents('.select-wrapper').hasClass('open')) {

            //            var jsp = $selectTrigger.parents('.select-wrapper').find('.select-results').data('jsp');
            //            if (!jsp) {
            //                $selectTrigger.parents('.select-wrapper').find('.select-results').jScrollPane();
            //            } 
            //        }
            //    }, 300);
            //});
        }
    }
});;
app.directive('onlyDigits', function () {
    return {
        require: 'ngModel',
        restrict: 'A',
        link: function (scope, element, attr, ctrl) {
            function inputValue(val) {
                if (val) {
                    var digits = val.replace(/[^0-9.]/g, '');
                    if (digits.length == 1 && digits == ".") {
                        digits = "";
                    }
                    if (digits.split('.').length > 2) {
                        var lastIndex = digits.lastIndexOf('.');
                        digits = digits.slice(0, lastIndex) + digits.slice(lastIndex + 1);
                    }
                    if (digits.split('.').length > 1 && digits.split('.')[1].length > 2) {
                        digits = digits.split('.')[0] + '.' + digits.split('.')[1].substring(0, 2);
                    }
                    if (digits !== val) {
                        ctrl.$setViewValue(digits);
                        ctrl.$render();
                    }
                    return parseFloat(digits);
                }
                return undefined;
            }
            ctrl.$parsers.push(inputValue);
        }
    };
});;
app.directive('priceSlider', function () {
    return {
        restrict: 'E',
        replace: true,
        template: '<div class="inner-filter">\
                        <label for=""> {{title}}</label>\
                        <div class="inner-filter-rangeslider-limits">\
                            <div class="caps">{{min}} <span class="gel"></span></div>\
                            <div class="caps">{{max}} <span class="gel"></span></div>\
                        </div>\
                        <div class="custom-range-slider" data-min="{{min}}" data-max="{{max}}">\
                            <input type="hidden" class="custom-range-slider-value" value="{{max}}" />\
                        </div>\
                    </div>',
        scope: {
            min: '<',
            max: '<',
            ngModel: '=',
            change: "&",
            title: "@",
        },
        controller: ['$scope', '$timeout', function ($scope, $timeout) {
            $scope.callChange = function () {
                $timeout(function () {
                    $scope.change();
                });
            };

            $scope.$watch('min', function () {
                $scope.$sliderElem.find('.custom-range-slider-in')[0].noUiSlider.updateOptions({
                    range: {
                        'min': parseFloat($scope.min),
                        'max': parseFloat($scope.max)
                    },
                    start: $scope.min
                });
            });
            $scope.$watch('max', function () {
                $scope.$sliderElem.find('.custom-range-slider-in')[0].noUiSlider.updateOptions({
                    range: {
                        'min': parseFloat($scope.min),
                        'max': parseFloat($scope.max)
                    },
                    start: $scope.max
                });
            });
        }],
        link: function ($scope, $elem, $attr) {

            $scope.$elem = $elem;
            $scope.$sliderElem = $($scope.$elem).find('.custom-range-slider');

            $scope.$suffix = $($scope.$elem).find('.js-suffix');


            $scope.$sliderElem.addClass('initialized');
            $('<div class="custom-range-slider-in"></div>').appendTo($scope.$sliderElem);
            var sliderDiv = $scope.$sliderElem.find(".custom-range-slider-in")[0];
            var $input = $scope.$sliderElem.find(".custom-range-slider-value");
            //
            $input.val($scope.min);
            var config = {
                'min': 0, 'max': 100, 'start': 3, 'step': 0.01, 'prefix': '', 'suffix': '',
                'display': false, 'two-way-display': false, 'tooltips': true
            };
            var configAttrs = {
                'start': parseFloat($scope.max || config['start']),
                'min': parseFloat($scope.min || config['min']),
                'max': parseFloat($scope.max || config['max']),
                'step': parseFloat(config['step']),
                'prefix': $scope.$sliderElem.attr("data-prefix") || config['prefix'],
                'suffix': $scope.$sliderElem.attr("data-suffix") || config['suffix'],
                'display': $scope.$sliderElem.attr("data-display") || config['display'],
                'two-way-display':  config['two-way-display'],
                'tooltips': ($scope.$sliderElem.attr("data-tooltips") || config['tooltips'].toString()) == 'true'
            };
            //take the defaults config object and fill with found values from data attributes
            for (var icn in Object.keys(config)) {
                var configName = Object.keys(config)[icn];
                var configAttr = configAttrs[configName];
                if ('undefined' !== typeof (configAttr) && '' !== configAttr) {
                    config[configName] = configAttr;
                }
            }
            //
            var starsByValueFormatter = wNumb({
                edit: function (x) {
                    return x + " " + "*".repeat(x);
                }
            });
            //
            var slider = noUiSlider.create(sliderDiv, {
                start: [config["start"]],
                step: config["step"],
                tooltips: [config['tooltips'] /*starsByValueFormatter*/],
                connect: [true, false],
                range: {
                    'min': config["min"],
                    'max': config["max"]
                }
            });
            //events: start/end/update/set
            slider.on('update', function () {
                var value = slider.get();

                $scope.ngModel = value;

                if (config['display']) {
                    if (config['suffix']) {
                        $(config['display']).html('<span>' + value + '</span><span>' + config['suffix'] + '</span>');
                    } else {
                        $(config['display']).text(value);
                    }
                }
                if (config['two-way-display']) {
                    $(config['two-way-display']).val(value);
                }

                $scope.callChange();
            });
            if (config['two-way-display']) {
                $(config['two-way-display']).keyup(function () {
                    slider.set($(config['two-way-display']).val());
                });
            }

        }
    }
});;
app.directive('rangeSlider', ['$timeout', function ($timeout) {
    return {
        restrict: 'E',
        replace: true,
        template: '<div class="inner-filter">\
                     <label for="">{{title}}</label>\
                     <div data-ng-show="min != max">\
                       <div class="rangeslider-display">\
                           <input type="text" id="{{id}}" value="{{getFormattedAmount()}}" data-ng-blur="updateFromInput()" data-ng-keypress="$event.keyCode == 13 ? updateFromInput() : null"/>\
                           <span class="js-suffix"></span>\
                       </div>\
                       <div class="inner-filter-rangeslider-limits">\
                           <div class="caps js-min-suffix" style="height: 22px;"></div>\
                           <div class="caps js-max-suffix" style="height: 22px;"></div>\
                       </div>\
                       <div class="custom-range-slider" \
                            data-min="{{min}}" \
                            data-max="{{max}}" \
                            data-suffix="{{suffix}}" \
                            data-two-way-display="#{{id}}" \
                            data-tooltips="false">\
                           <input type="hidden" class="custom-range-slider-value" value="{{min}}" />\
                       </div>\
                     </div>\
                     <div class="rangeslider-display"  data-ng-show="min == max">\
                         <input type="text" value="{{min}}" disabled />\
                         <span class="js-suffix"></span>\
                     </div>\
                   </div>',
        scope: {
            min: '<',
            max: '<',
            ngModel: '=',
            id: '@',
            calculate: "&",
            change: "&",
            title: "@",
            suffix: "@",
            step: "@",
            type: "@"
        },
        controller: ['$scope', '$timeout', '$filter', function ($scope, $timeout, $filter) {
            $scope.setSuffixes = function () {
                $($scope.$elem).find('.js-suffix').html($scope.suffix);
                $($scope.$elem).find('.js-min-suffix').html($scope.getFormattedValue($scope.min) + '&nbsp;' + $scope.suffix);
                $($scope.$elem).find('.js-max-suffix').html($scope.getFormattedValue($scope.max) + '&nbsp;' + $scope.suffix);
            }
            $scope.updateFromInput = function () {
                $timeout(function () {
                    if ($scope.$sliderElem) {

                        //var value = $('#' + $scope.id).val().replace(/,/g, '.');
                        var value = $('#' + $scope.id).val().replace(/,/g, '');
                        $scope.$sliderElem.find('.custom-range-slider-in')[0].noUiSlider.set(value);
                        $scope.callChange();
                        $scope.callCalculate();
                    }
                });
            }

            $scope.getFormattedValue = function (val) {
                return $filter('currency')(val, "");
            }

            $scope.getFormattedAmount = function () {
                return $scope.getFormattedValue($scope.ngModel);
            }
            $scope.callCalculate = function () {

                $scope.calculate();

            }
            $scope.callChange = function () {

                $scope.change();

            }
            $scope.$watchGroup('suffix', function () {
                $scope.setSuffixes();
            });
            $scope.$watch('suffix', function () {
                $scope.setSuffixes();
            });

            $scope.$watch('min', function () {
                if ($scope.$sliderElem) {
                    if ($scope.min != $scope.max) {

                        if (!$scope.$sliderElem.hasClass('initialized')) {
                            $scope.setNoUiSlider();
                        }

                        $scope.$sliderElem.find('.custom-range-slider-in')[0].noUiSlider.updateOptions({
                            range: {
                                'min': parseFloat($scope.min),
                                'max': parseFloat($scope.max)
                            },
                            start: parseFloat($scope.min)
                        });
                        $scope.setSuffixes();
                    }

                    if ($scope.$sliderElem.hasClass('initialized')) {
                        $scope.$sliderElem.find('.custom-range-slider-in')[0].noUiSlider.set(parseFloat($scope.min));
                    }


                }
            });
            $scope.$watch('max', function () {
                if ($scope.$sliderElem) {
                    if ($scope.min != $scope.max) {
                        if (!$scope.$sliderElem.hasClass('initialized')) {
                            $scope.setNoUiSlider();
                        }

                        $scope.$sliderElem.find('.custom-range-slider-in')[0].noUiSlider.updateOptions({
                            range: {
                                'min': parseFloat($scope.min),
                                'max': parseFloat($scope.max)
                            },
                            start: parseFloat($scope.min)
                        });
                        $scope.setSuffixes();
                    }
                    if ($scope.$sliderElem.hasClass('initialized')) {
                        $scope.$sliderElem.find('.custom-range-slider-in')[0].noUiSlider.set(parseFloat($scope.min));
                    }
                }
            });

            $scope.callChange();
            $scope.callCalculate();
        }],
        link: function ($scope, $elem, $attr) {
            $scope.$elem = $elem;
            $scope.setSuffixes();

            $scope.$sliderElem = $($scope.$elem).find('.custom-range-slider');

            $scope.setNoUiSlider = function () {
                $scope.$sliderElem.addClass('initialized');
                $('<div class="custom-range-slider-in"></div>').appendTo($scope.$sliderElem);
                var sliderDiv = $scope.$sliderElem.find(".custom-range-slider-in")[0];
                var $input = $scope.$sliderElem.find(".custom-range-slider-value");
                //
                $input.val($scope.min);
                var config = {
                    'min': 0, 'max': 100, 'start': 0, 'step': 1, 'prefix': '', 'suffix': '',
                    'display': false, 'two-way-display': false, 'tooltips': true
                };
                var configAttrs = {
                    'start': parseFloat($scope.min || config['start']),
                    'min': parseFloat($scope.min || config['min']),
                    'max': parseFloat($scope.max || config['max']),
                    'step': parseFloat($scope.step || config['step']),
                    'prefix': $scope.$sliderElem.attr("data-prefix") || config['prefix'],
                    'suffix': $scope.$sliderElem.attr("data-suffix") || config['suffix'],
                    'display': $scope.$sliderElem.attr("data-display") || config['display'],
                    'two-way-display': '#' + $scope.id || config['two-way-display'],
                    'tooltips': ($scope.$sliderElem.attr("data-tooltips") || config['tooltips'].toString()) == 'true'
                };

                //take the defaults config object and fill with found values from data attributes
                for (var icn in Object.keys(config)) {
                    var configName = Object.keys(config)[icn];
                    var configAttr = configAttrs[configName];
                    if ('undefined' !== typeof (configAttr) && '' !== configAttr) {
                        config[configName] = configAttr;
                    }
                }
                //
                var starsByValueFormatter = wNumb({
                    edit: function (x) {
                        return x + " " + "*".repeat(x);
                    }
                });
                //

                var slider = noUiSlider.create(sliderDiv, {
                    start: [config["start"]],
                    step: config["step"],
                    tooltips: [config['tooltips'] /*starsByValueFormatter*/],
                    connect: [true, false],
                    range: {
                        'min': config["min"],
                        'max': config["max"]
                    }
                });

                var updateValue = function () {
                    var value = slider.get();
                    if ($scope.min == $scope.max) {
                        value = $scope.min;
                    }
                    $scope.ngModel = value;

                    if (config['display']) {
                        if (config['suffix']) {
                            $(config['display']).html('<span>' + $scope.getFormattedAmount() + '</span><span>' + config['suffix'] + '</span>');
                        } else {
                            $(config['display']).text($scope.getFormattedAmount());
                        }
                    }
                    if (config['two-way-display']) {
                        $(config['two-way-display']).val($scope.getFormattedAmount());
                    }

                    $timeout(function () {
                        $scope.callChange();
                        $scope.callCalculate();
                    });
                }


                //events: start/end/update/set
                slider.on('update', function (e) {
                    updateValue();
                });
                //events: start/end/update/set
                slider.on('change', function () {
                    updateValue();
                });

                if (config['two-way-display']) {
                    $(config['two-way-display']).keyup(function () {
                        //slider.set($(config['two-way-display']).val());
                    });
                }
            }

            if ($scope.min != $scope.max) {
                $scope.setNoUiSlider();
            }
        }
    }
}]);;
app.directive('vtbSelect', function () {
    return {
        restrict: 'E',
        replace: true,
        template: '<div class="select-wrapper"\
                            data-ng-class="{\'has-error\' : hasError()}">\
                        <a href="" class="select-trigger js-select-trigger-ng"><span>{{getPlaceholder()}}</span></a>\
                        <div class="select-results js-select-results">\
                            <div class="select-results-one-big-item">\
                                <a href="" data-ng-repeat="i in items()"\
                                       data-ng-click="selectItem(i)"><span>{{i.title}}</span></a>\
                            </div>\
                        </div>\
                    </div>',
        scope: {
            items: '&',
            placeholder: '&',
            ngModel: '=',
            change: '&',
            hasError: '&'
        },
        controller: ['$scope', function ($scope) {
            var _this = this;

            $scope.getPlaceholder = function () {
                if ($scope.ngModel == null) { return $scope.placeholder(); }

                return $scope.ngModel.title;
            }

            $scope.selectItem = function (item) {
                $scope.ngModel = item;
                $($scope.$elem).trigger('click');
                $scope.change();
            }

        }],
        link: function ($scope, $elem, $attr) {
            $scope.$elem = $elem;

            var $selectTrigger = $($elem).find('.js-select-trigger-ng');


            $selectTrigger.on('click', function (e) {
                console.log(5);
                e.preventDefault();
                if ($(this).parents('.select-wrapper').hasClass('open')) {
                    var jsp = $(this).parents('.select-wrapper').find('.select-results').data('jsp');
                    if (jsp) {
                        jsp.destroy();
                    }
                    $(this).parents('.select-wrapper').removeClass('open');
                    $(this).siblings('.js-select-results').stop().slideToggle(200);
                } else {
                    $(this).parents('.select-wrapper').addClass('open');
                    $(this).siblings('.js-select-results').stop().slideToggle(200);
                }
            });
            $("body").on('click', function (e) {
                var $parSelectWrapper = $(e.target).parents('.select-wrapper');
                $('.select-wrapper').each(function (i, sw) {
                    //don't close select-wrappers that are parenting the clicked element
                    if ($parSelectWrapper.length > 0 && $parSelectWrapper[0].isSameNode(sw)) {
                        return;
                    }
                    //only run this [auto-closing] code on opened select wrappers
                    if ($(sw).hasClass('open')) {
                        var jsp = $(sw).find('.select-results').data('jsp');
                        if (jsp) {
                            jsp.destroy();
                        }
                        $(sw).find('.js-select-results').hide();
                        $(sw).removeClass('open');
                    }
                });
            });

            //$selectTrigger.on('click', function () {
            //    $selectTrigger.siblings('.js-select-results').stop().slideToggle(200);

            //    $selectTrigger.parents('.select-wrapper').toggleClass('open');

            //    //setTimeout(function () {
            //    //    if ($selectTrigger.parents('.select-wrapper').hasClass('open')) {
            //    //        var $sel = $selectTrigger.parents('.select-wrapper').find('.select-results');
            //    //        var $tempWrapper = $sel.clone();
            //    //        var $items = $tempWrapper.children('a');
            //    //        //console.log('found ' + $items.length + ' items');
            //    //        //$sel.remove();
            //    //        //console.log($tempWrapper.children('a').length);
            //    //        var jsp = $sel.data('jsp');
            //    //        if (jsp) {
            //    //            //2nd or more open - reinitialize jScrollPane, items may have changed
            //    //            //$items.appendTo($tempWrapper);//first, remove from DOM context (to ensure that jsp destroy doesn't remove items)
            //    //            jsp.destroy();//clear the data('jsp')
            //    //            $sel.empty();//ensure it's empty - including .jspContainer
            //    //            //console.log($tempWrapper);
            //    //            $tempWrapper.children('a').appendTo($sel);//return items to list
            //    //            //next line will reinitialise jScrollPane manually
            //    //        }
            //    //        //first time (or dynamically changed items) dropdown open - initialize jScrollpane
            //    //        $sel.jScrollPane();

            //    //    }
            //    //}, 300);
            //});

        }
    }
});;
app.controller('becomeClient', ['$scope', '$http', function ($scope, $http) {
    var _this = this;
    _this.$scope = $scope;
    $scope._this = _this;

    _this.isSubmitted = false;
    _this.showForm = true;
    _this.sendingData = false;
    _this.message = "";
    _this.branches = window.becomeClientBranches;

    _this.data = {
        fullName: null,
        email: null,
        phone: null,
        selectedBranch: null,
        //captcha: null
    };

    _this.send = function (languageId) {
        _this.isSubmitted = true;
        var validate = true;

        if (_this.data.fullName == null || !_this.data.fullName.length ||
            _this.data.email == null || !_this.data.email.length ||
            _this.data.phone == null || !_this.data.phone.length || _this.data.selectedBranch == null)
        //|| _this.data.captcha == null || !_this.data.captcha.length)
        {
            validate = false;
        }

        if (validate) {
            _this.sendingData = true;
            $http.post('~/api/BecomeAClient/send',
                {
                    fullName: _this.data.fullName,
                    email: _this.data.email,
                    phone: _this.data.phone,
                    branch: _this.data.selectedBranch.title,
                    //captcha: _this.data.captcha,
                    languageId: languageId
                }).then(function successCallback(response) {
                    if (response.data.success) {
                        _this.showForm = false;
                    }
                    _this.message = response.data.message;
                }).catch(function (e) {

                }).finally(function (e) {
                    _this.sendingData = false;
                    //$('.captcha').attr('src', $('.captcha').attr('src') + '1');
                });
        }
    }
}]);
;
app.controller('cyberSecurityController', ['$scope', '$http', function ($scope, $http) {
    var _this = this;
    _this.$scope = $scope;
    $scope._this = _this;

    _this.isSubmited = false;
    _this.sendingData = false;
    _this.showForm = true;
    _this.message = null;
    _this.fileMessage = null;

    _this.incidentTypes = null;

    _this.data = {
        incidentType: null,

        fullName: null,
        phoneNumber: null,
        email: null,
        description: null,
        agreeChecked: null,
        captcha: null,
        files: []
    }

    _this.init = function () {
        _this.incidentTypes = window.cyberSecurityIncidentTypes;
    }

    _this.send = function (languageId) {
        _this.isSubmited = true;

        //if (!_this.data.agreeChecked) {
        //    return;
        //}
        if (_this.data.incidentType == null) {
            return;
        }

        if (_this.data.files == null || _this.data.files.length == 0) {
            return;
        }

        for (var i in _this.data.files) {
            if (window.allowedFileTypes.indexOf(_this.data.files[i].name.split(".").pop()) < 0) {
                _this.fileMessage = window.invalidFileTypePhrase + ' ' + _this.data.files[i].name.split(".").pop();
                return;
            }
        }

        if (!_this.data.fullName || !_this.data.phoneNumber || !_this.data.email || !_this.data.description || !_this.data.captcha) {
            return;
        }
        _this.fileMessage = null;
        _this.message = null;
        _this.sendingData = true;


        var data = new FormData();
        data.append("incidentType", _this.data.incidentType.title);
        data.append("fullName", _this.data.fullName);
        data.append("phoneNumber", _this.data.phoneNumber);
        data.append("email", _this.data.email);
        data.append("description", _this.data.description);
        //data.append("files", _this.data.files);
        data.append("captcha", _this.data.captcha);
        data.append("languageId", languageId);

        for (var i in _this.data.files) {
            data.append("files", _this.data.files[i]);
        }


        var headerData = {
            headers: {
                'Content-Type': undefined
            }
        };



        $http.post('~/api/cybersecurityform/send', data, headerData)
            .then(function successCallback(response) {
                if (response.data.success) {
                    _this.showForm = false;
                }
                _this.message = response.data.message;
            }).catch(function (e) {

            }).finally(function (e) {
                _this.sendingData = false;
                $('.captcha').attr('src', $('.captcha').attr('src') + '1');
            });
    }

    _this.attachFile = function (e) {
        _this.data.files.push(e.files[0]);
        $scope.$apply();
        e.value = null;
    }
    _this.removeAttachement = function (index) {
        _this.data.files.splice(index, 1);
    }
}]);
;
