jQuery(function () {
    var body = jQuery('body');
    if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
        body.addClass('mobile');
    } else {
        body.addClass('pc');
    }

    var ua = window.navigator.userAgent,
        msie = ua.indexOf ('MSIE'),
        browser = null;

    if (msie > 0) {
        browser =  parseInt (ua.substring (msie+5, ua.indexOf (".", msie )),10);
        body.addClass('ie');
        if (browser < 9) {
            IE.nthChilds();
            body.addClass('ie8');
        }
        if (browser < 10) {
            IE.hoverEffect();
            body.addClass('ie9');
        }
        if (browser >= 10) {
            body.addClass('transition');
        }
    } else {
        body.addClass('transition');
    }
    if(ua.indexOf('OPR') > -1 || ua.indexOf('OPERA') > -1) {
     	  body.addClass('opera');
    }
    var ie_image = jQuery('.ie_bg');
    getImageSize(ie_image);
    jQuery(window).resize(function() {
        getImageSize(ie_image);
    });
    
  
    var spinnerClasses = ['button.continue_dark','button.continue','a span.continue.inline','a.spinner', 'button.blue-base-button'];
    for (i = 0; i < spinnerClasses.length; i++) {
        jQuery(spinnerClasses[i]).each(function() {  
        	addBlurLoaderToButtons(this);
        });
    }

    if (jQuery('select:not(.default_select)').length > 0) {
        selectBoxes.init();
    }

    var $autocomplete = $('#autocomplete_country');
    if ($autocomplete.length > 0) {
        $autocomplete.autocomplete({
            lookup: countriesObject,
            onSelect: function (suggestion) {

            }
        });
    }

});

function addBlurLoaderToButtons(_this) {
	var btn = jQuery(_this);
    var clickhandler = _this.onclick;
    var parent = jQuery(_this).parent();
    if(!parent.hasClass('no_spinner') && !btn.hasClass('no_spinner')) {
    	
        _this.onclick = null;
        btn.click(function() {
        	Loader.init();
        });
        
        btn.click(clickhandler);
        
        if(clickhandler != null && btn.prop('tagName') !== "A"){
        	btn.click(function() {
            	Loader.stopSpinner();
            });
        }
    }
}

$(function() {
    contentAnimate.init();
    var allCalendars = jQuery('body').find('.calendar');
    var thisID = null;
    allCalendars.each(function() {
        thisID = jQuery(this).attr('id');
        CalendarEvents.defaultParams('#' + thisID);
    });
    filters.init();
    if (jQuery('body').hasClass('pc')) {
        if (jQuery('.scrollbox').length > 0) {
            jQuery('.scrollbox').enscroll({
                verticalScrolling: true
            });
        }
    }
  $(window).resize();
});

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) {
            size++;
        }
    }
    return size;
};

var currencyArray = ['USD', 'LVL'];
var hamburgerAnimationInterval = null;
var contentAnimate = {
    init: function() {
        contentAnimate.setContentWidth();
        contentAnimate.filters.dropMenu();
        contentAnimate.topMenu.fadeArea();
        contentAnimate.leftMenu.changePosition();
        contentAnimate.tableEvents.showRows();
        contentAnimate.tableEvents.sortTables();
        contentAnimate.alignErrorPage();
        if (jQuery('.notification_area').length > 0) {
            jQuery('form').submit(contentAnimate.login.submit);
        }
        jQuery('.payment_form').find('form').submit(contentAnimate.login.submit);
        contentAnimate.login.init();
    },
    setContentWidth:function() {
        var wrapper        = jQuery('.wrapper'),
            content        = jQuery('.page_content'),
            menu           = jQuery('.menu'),
            left_menu      = jQuery('.leftMenu'),
            // banner         = jQuery('.banner_section_content'),
            header         = jQuery('nav'),
            footer         = jQuery('.footer_children'),
            content_area   = jQuery('.content');

        var setChildWidth = function() {
            // close infoWindow and hide button if browser window width less 1280px
            if ($(window).width() < 1280){
                if ($('#infoModal').hasClass('in')){
                    $('#infoModal').removeClass('fade');
                    $('#infoModal').modal('hide');
                }
                $('#info_window').hide();
            } else {
                if (!$('#infoModal').hasClass('fade')){
                    $('#infoModal').addClass('fade');
                }
                $('#info_window').show();
            }
            if (jQuery(window).width() < 1010) {
                // jQuery('body').addClass('small');
                menu.addClass('hidden_menu');
                if (hamburgerAnimationInterval == null) {
                    hamburgerAnimationInterval = setInterval(function () {
                        $(".hamburger").toggleClass('arrow');
                    }, 3000);
                }

                jQuery('.consultant_top .title_area').addClass('collapse_content');
                jQuery('.consultant_bottom').addClass('collapse_content');
                content.css('padding-left', '');
                // banner.css('width', '');
            } else {
                header.removeAttr('style');
                menu.removeAttr('style');
                footer.removeAttr('style');
                content_area.removeAttr('style');
                wrapper.removeAttr('style');
                jQuery('.menu_background').removeAttr('style');
                menu.removeClass('active');
                menu.removeClass('hidden_menu');
                jQuery('body').removeClass('small');
                jQuery('body').removeAttr('style');
                jQuery('.menu_activate').removeAttr('style');
                jQuery('.menu_activate').removeClass('active');
                if (hamburgerAnimationInterval != null) {
                  clearInterval(hamburgerAnimationInterval);
                  hamburgerAnimationInterval = null;
                }
                jQuery('.consultant_top .title_area').removeClass('collapse_content');
                jQuery('.consultant_bottom').removeClass('collapse_content');
            }
        };

        jQuery(window).resize(function() {
            setChildWidth();
        });
    },
    alignErrorPage: function() {
        var maxHeight = jQuery(window).height() - 360 + 'px';

        var setTableHeight = function(maxHeight) {
            jQuery('.error_page').css('height', maxHeight);
        };

        setTableHeight(maxHeight);

        jQuery(window).resize(function() {
            maxHeight = jQuery(window).height() - 360 + 'px';
            setTableHeight(maxHeight);
        });
    },
    filters: {
        dropMenu: function () {
            var ua = navigator.userAgent,
                event,
                activeElement,
                fadeItem = jQuery('.fade_area');

            event = (ua.match(/iPad/i)) ? "touchstart" : "click" ;

            jQuery('.clickDrop').bind('click', function(e){
                e.stopPropagation();
                var openMenu = jQuery(this).next('ul');
                if (openMenu.length > 0 && !(openMenu.is(':animated'))) {
                    if (!(openMenu.hasClass('ipad_ani'))) {
                        openMenu
                            .slideDown(250)
                            .addClass('ipad_ani');
                        jQuery(this).addClass('active');

                        if ((jQuery(this).parents('div.topMenu').length > 0)) {
                                fadeItem.fadeIn(300);
                        }
                        if ((jQuery(this).parents('div.btk-dropdown').length > 0)) {
                            fadeItem.fadeIn(300);
                        }
                    } else {
                        openMenu
                            .slideUp(250)
                            .removeClass('ipad_ani');
                        jQuery(this).removeClass('active');

                        if ((jQuery('body').hasClass('mobile')) && (jQuery(this).parents('div.topMenu').length > 0)) {
                            fadeItem.fadeOut(300);
                        }
                    }
                }
                return false;
            });
            jQuery('.company').find('.scrollClick').bind('click', function(e) {
                e.stopPropagation();
                var openMenu = jQuery('.dropScroll');
                if (openMenu.length > 0 && !(openMenu.is(':animated'))) {
                    if (!(openMenu.hasClass('ipad_ani'))) {
                        openMenu
                            .slideDown(250, function() {
                                setTimeout(function () {
                                    jQuery('.vertical-handle').fadeIn(250);
                                },150);
                            })
                            .addClass('ipad_ani');
                        jQuery(this).addClass('active');
                        fadeItem.fadeIn(300);
                    } else {
                        openMenu
                            .slideUp(250, function() {
                                jQuery('.vertical-handle').hide();
                            })
                            .removeClass('ipad_ani');
                        jQuery(this).removeClass('active');

                        if (jQuery('body').hasClass('mobile')) {
                            fadeItem.fadeOut(300);
                        }
                    }
                }

                return false;
            });

            var clearTopMenu = function () {
                jQuery('#message')
                    .slideUp(250)
                    .removeClass('ipad_ani')
                    .parent().find('.clickDrop')
                    .removeClass('active');

                jQuery('.btk-dropdown-content')
                    .slideUp(250)
                    .removeClass('ipad_ani')
                    .parent().find('.clickDrop')
                    .removeClass('active');

                jQuery('#preference')
                    .slideUp(250)
                    .removeClass('ipad_ani')
                    .parent().find('.clickDrop')
                    .removeClass('active');

                jQuery('.dropScroll')
                    .slideUp(250, function() {
                        jQuery('.vertical-handle').hide();
                    })
                    .removeClass('ipad_ani')
                    .parents('div.company').find('.scrollClick')
                    .removeClass('active');

                jQuery('.status').find('dd')
                    .slideUp(250)
                    .parent().parent('.status')
                    .removeClass('active');


                fadeItem.fadeOut(300);
            };

            fadeItem.on(event, function (e) {
                clearTopMenu();
            });

            jQuery('.nav_background').on(event, function(e) {
                clearTopMenu();
            });

            jQuery('.clickElement').bind('click', function() {
                clearTopMenu();
            });
            jQuery('.navigation_area').bind('click', function() {
                clearTopMenu();
            });


            jQuery('.logo').on(event, function(e) {
                clearTopMenu();
            });

            jQuery('.menu').on(event, function(e) {
                clearTopMenu();
            });

            jQuery(document).keyup(function(e) {
               if (e.keyCode == 27) {
                   clearTopMenu();
               }
            });

            jQuery('.message.clickDrop').bind('click', function () {
                jQuery('#preference')
                    .slideUp(250)
                    .removeClass('ipad_ani')
                    .parent().find('.clickDrop')
                    .removeClass('active');

                jQuery('.dropScroll')
                    .slideUp(250, function () {
                        jQuery('.vertical-handle').hide();
                    })
                    .removeClass('ipad_ani')
                    .parents('div.company').find('.scrollClick')
                    .removeClass('active');
            });

            jQuery('.scrollClick').bind('click', function () {
                jQuery('#message')
                    .slideUp(250)
                    .removeClass('ipad_ani')
                    .parent().find('.clickDrop')
                    .removeClass('active');

                jQuery('#preference')
                    .slideUp(250)
                    .removeClass('ipad_ani')
                    .parent().find('.clickDrop')
                    .removeClass('active');
            });

            jQuery('.preference.clickDrop').bind('click', function () {
                jQuery('.dropScroll')
                    .slideUp(250, function() {
                        jQuery('.vertical-handle').hide();
                    })
                    .removeClass('ipad_ani')
                    .parents('div.company').find('.scrollClick')
                    .removeClass('active');

                jQuery('#message')
                    .slideUp(250)
                    .removeClass('ipad_ani')
                    .parent().find('.clickDrop')
                    .removeClass('active');
            });
        }
    },
    topMenu: {
        fadeArea: function() {
            var fadeItem = jQuery('.fade_area'),
                hoverItem = jQuery('.fade_active'),
                body      = jQuery('body'),
                checkField = jQuery('.check_field'),
                checkBoxItem = jQuery('.checkbox_item').find('label'),
                radioItem = jQuery('.radio_items').find('label'),
                radioClick = jQuery('.radio_area').find('td label'),
                notification = jQuery('.main_notification');
            if (!(body.hasClass('mobile'))) {
                hoverItem.bind('mouseenter', function(e) {
                   fadeItem.fadeIn(300);
                });

                hoverItem.bind('mouseleave', function() {
                    if (!jQuery('.topMenu').find('a').hasClass('active')) {
                        fadeItem.stop().fadeOut(300);
                    }
                });
            }

            if ($('body').hasClass('ie8')) {

              (function($) {
                $('input[type="radio"]').each(function() {
                  if ($(this).prop('checked')) {
                    $(this).parents('td').find('label').addClass('checked');
                  }
                })

              })(jQuery);

                jQuery(document.body).on('click', '.check_field input', function() {
                    jQuery(this).parents('.check_field').toggleClass('checked');
                });
                notification.find('.continue').on('click', function() {
                    if (checkField.hasClass('checked')) {
                        notification.fadeOut(300);
                    }
                    return false;
                });
                notification.find('.continue_dark').on('click', function() {
                                    if (checkField.hasClass('checked')) {
                                        notification.fadeOut(300);
                                    }
                                    return false;
                 });


                jQuery(document.body).on('click', '.checkbox_item label', function() {
                    jQuery(this).parents('.checkbox_item').toggleClass('checked');
                });

                jQuery(document.body).on('click', '.radio_items label', function() {
                      jQuery('.radio_items').removeClass('checked');
                      jQuery(this).parents('.radio_items').addClass('checked');
                });

                jQuery(document.body).on('click', '.radio_area td label', function() {
                    radioClick.removeClass('checked');
                   jQuery(this).addClass('checked');
                });

            } else {
                notification.find('.continue').on('click', function() {
                    if (notification.find('input:checkbox').is(':checked')) {
                        notification.fadeOut(300);
                    }
                    return false;
                });
            }
        }
    },
    leftMenu: {
        changePosition: function() {
            var clickItem  = jQuery('.menu_activate'),
                menu       = jQuery('.menu'),
                body = jQuery('body');
            body.addClass("animated");

                clickItem.bind('click', function() {
                    if (!(menu.is(':animated'))) {
                        body.toggleClass('menu_collapsed');
                        var isCollapsed = body.hasClass('menu_collapsed');
                        menu.toggleClass('active', isCollapsed);
                        jQuery.cookie('menu_collapsed', isCollapsed);
                    }
                    clickItem.toggleClass('active');
                });
        }
    },
    tableEvents: {
        showRows: function() {
            var clickItem = jQuery('.slide_area').find('.arrow_area'),
                animateItems = null,
                elementID = null,
                currency_filter = jQuery('.currency_filter');

            clickItem.bind('click', function() {
                elementID = jQuery(this).data('info');
                animateItems = jQuery(this).parents('table').find('[data-hide="'+ elementID +'"]').find('.hidden_content');
                if (animateItems.length > 0 && !(animateItems.is(':animated'))) {
                    if (animateItems.parents('tr').next('tr').length > 0) {

                    } else {
                            animateItems.parents('tr').find('td:first-child').find('.hidden_content').addClass('hidden-border');
                    }
                    animateItems.slideToggle(300);
                }
               return false;
            });
        },
        sortTables: function() {
            var clickItem = jQuery('.currency_filter'),
                sortTable = null,
                activeCurrency = null,
                itemsToTop = null,
                objectLength = 0;

            clickItem.bind('click', function() {
                var tableObject = {};
                activeCurrency = (jQuery(this).data('active-currency'));
                sortTable = jQuery(this).parents('table');
                if ((jQuery.inArray(activeCurrency, currencyArray)) !== -1) {

                       sortTable.find('tr').each(function () {
                        var currency = jQuery(this).data('currency');
                           if (currency !== undefined) {
                               tableObject[currency] = {};
                           }
                       });

                    objectLength = (Object.size(tableObject));
                    if (objectLength > 1) {

                        if (jQuery(this).data('active-currency') === currencyArray[0]) {
                            jQuery(this).data('active-currency', currencyArray[1]);
                        } else {
                            jQuery(this).data('active-currency', currencyArray[0]);
                        }

                        itemsToTop = (sortTable.find('[data-currency="'+ activeCurrency +'"]'));
                        sortTable.append(itemsToTop);
                        sortTable.find('tr td:first-child').find('.hidden_content').removeClass('hidden-border');
                        itemsToTop.eq(1).find('td:first-child').find('.hidden_content').addClass('hidden-border');
                    }
                }
               return false;
            });
        }
    },
    login: {
        init: function() {
          this.showTooltip('mouseenter', '.login_info, .tooltip, .fi_order_login_info', 200);
          this.showTooltip('click', '.reminders', 30);
          this.validate();
        },
        showTooltip: function(onEvent, tooltipContainerClass, fadeInTimeout) {
            var tooltipArea = jQuery(tooltipContainerClass),
                hiddenBlock = jQuery('.hide_info'),
                closeItem = jQuery('.notification_area').find('.close'),
                ua = navigator.userAgent,
                time = null,
                event = (ua.match(/iPad/i)) ? "click" : "mouseenter";

            jQuery(document).on(onEvent, tooltipContainerClass, function() {
                hiddenBlock =  jQuery(this).find('.hide_info');
                time = setTimeout(function() {
                    hiddenBlock.fadeIn(300);
                }, fadeInTimeout)
            });

            if (event === 'click') {
                jQuery('.clickOverlay').on(event, function (e) {
                    hiddenBlock.fadeOut(300);
                });
            }

            jQuery(document).on('mouseleave', tooltipContainerClass, function() {
                clearTimeout(time);
                jQuery(this).find('.hide_info').stop().fadeOut(300);
            });

            closeItem.bind('click', function() {
                jQuery(this).parent('.notification_area').slideUp(300, function() {
                    closeItem.css('display', 'none');
                });
            });
        },
        validate : function () {
            var noerror = true;
            jQuery(this).find('[data-validate]').each(function(){
                var type = jQuery(this).data('validate');
                contentAnimate.login.validate.call(this);
                var result = contentAnimate.login.validation[type](this);
                if (!result)
                {
                    jQuery(this).parent().find('.error_area').addClass('error');
                    jQuery(this).parent().find('label').addClass('error');
                    noerror = false;
                }
                else
                {
                    jQuery(this).parent().find('.error_area').removeClass('error');
                    jQuery(this).parent().find('label').removeClass('error');
                }
            });
            return noerror;
        },
        validation : {
            text : function (element) {
                return  (/([^\s*$])/.test(element.value));
            },
            phone : function (element) {
                return /\+?\d{2,}/.test(element.value);
            },
            email : function (element) {
                return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(element.value);
            },
            number : function(element) {
                return /^[0-9]{5,}$/.test(element.value);
            },
            count_number : function(element) {
                return /^[0-9]{5,}$/.test(element.value);
            },
            date : function(element) {
                return /^[0-9]{5,}$/.test(element.value);
            }
        },
        submit : function () {
            if (jQuery('.notification_area').length > 0) {
                if (!contentAnimate.login.validate.call(this)) {
                    jQuery('.notification_area').slideDown(300, function() {
                        jQuery('.notification_area').find('.close').fadeIn(200);
                    });
                    return false;
                } else {
                    jQuery('.notification_area').slideUp(300, function() {
                        jQuery('.notification_area').find('.close').css('display', 'none');
                    });
                    return true;
                }
            } else {
                if (!contentAnimate.login.validate.call(this)) {
                    return false;
                } else {

                    return true;
                }
            }
        }
    }
};


var IE = {
    nthChilds: function() {
        var table   = jQuery('table'),
            topMenu = jQuery('.topMenu');

        topMenu.find('#branch').find('li:nth-child(odd)').addClass('odd');
        topMenu.find('#branch').find('li:nth-child(even)').addClass('even');

        topMenu.find('#message').find('li:nth-child(even)').addClass('even');
        topMenu.find('#message').find('li:nth-child(odd)').addClass('odd');

        topMenu.find('#preference').find('li:nth-child(odd)').addClass('odd');
        topMenu.find('#preference').find('li:nth-child(even)').addClass('even');

        table.find('tr.titles').find('th:nth-child(odd)').addClass('odd');
        table.find('tr.titles').find('th:nth-child(even)').addClass('even');
        table.find('tr.titles').find('th:last-child').addClass('last');

        jQuery('.message_inner').find('.message_filters li:nth-child(odd)').addClass('odd');
        jQuery('.message_inner').find('.message_filters li:nth-child(even)').addClass('even');
    },
    hoverEffect: function() {
       var company       = jQuery('.company'),
           messageItems  = jQuery('.message_block'),
           menu          = jQuery('.menu_item'),
           currencyArrow = jQuery('.currency_filter'),
           hideTable     = jQuery('.arrow_area');

        company.hover(
            function() {
                jQuery(this).stop().animate({
                    'borderColor': '#6eb4ef'
                },200);

                jQuery(this).find('.scrollClick span').stop().animate({
                    'backgroundColor': '#6eb4ef',
                    'right' : '0'
                },250);

                jQuery(this).find('.scrollClick strong').stop().animate({
                    'color': '#ffffff'
                },250);


            },
            function() {
                jQuery(this).stop().animate({
                    'borderColor': '#e5e5e5'
                },200);

                jQuery(this).find('.scrollClick strong').stop().animate({
                    'color': '#1c2d39'
                },250);

                jQuery(this).find('span').stop().animate({
                    'backgroundColor': '#ffffff',
                    'right' : '20px'
                },250);
            }
        );

        messageItems.hover(
            function() {
                jQuery(this).stop().animate({
                    'borderColor': '#6eb4ef'
                },200);

                jQuery(this).find('.message_item span').stop().animate({
                    'backgroundColor': '#6eb4ef',
                    //'right' : '0'
                },250);

//                jQuery(this).find('.message_item .text_block').stop().animate({
//                    'color': '#ffffff'
//                },250);

//                jQuery(this).find('.message_item .info_hint').stop().animate({
//                    'right' : '-80px'
//                },350);
            },
            function() {
                jQuery(this).stop().animate({
                    'borderColor': '#e5e5e5'
                },200);

                jQuery(this).find('.message_item .text_block').stop().animate({
                    'color': '#1c2d39'
                },250);
                jQuery(this).find('.message_item.card_request .text_block').stop().animate({
                    'color': '#FC560A'
                },250);

                jQuery(this).find('span').stop().animate({
                    'backgroundColor': '#f47920',
//                    'right' : '20px'
                },250);

//                jQuery(this).find('.message_item .info_hint').stop().animate({
//                    'right' : '20px'
//                },350);
            }
        );

        menu.hover(
            function() {
                jQuery(this).find('.clickDrop span').stop().animate({
                    'backgroundColor': '#6eb4ef',
                    'right' : '0'
                },200);
            },
            function() {
                jQuery(this).find('.clickDrop span').stop().animate({
                    'backgroundColor': '#00518e',
                    'right' : '20px'
                },200);
            }
        );

//        currencyArrow.hover(
//            function() {
//                jQuery(this).stop().animate({
//                    'backgroundColor': '#6eb4ef'
//                },200);
//            },
//            function() {
//                jQuery(this).stop().animate({
//                    'backgroundColor': '#f1f1f1'
//                },200);
//            }
//        );

//        hideTable.hover(
//            function() {
//                jQuery(this).stop().animate({
//                    'backgroundColor': '#6eb4ef'
//                },200);
//            },
//            function() {
//                jQuery(this).stop().animate({
//                    'backgroundColor': '#f1f1f1'
//                },200);
//            }
//        );

//        jQuery('.consultant_email').hover(
//            function() {
//                jQuery(this).stop().animate({
//                    'backgroundColor': '#6eb4ef'
//                },250);
//            },
//            function() {
//                jQuery(this).stop().animate({
//                    'backgroundColor': '#e5e5e5'
//                },250);
//            }
//        );
    }
}

if (jQuery('.calendar').length > 0) {
    jQuery.datepicker.regional['ru'] = {
        currentText: 'Сегодня',
        monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь',
            'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
        monthNamesShort: ['Янв','Фев','Март','Апр','Май','Июнь',
            'Июль','Авг','Сеп','Окт','Нов','Дек'],
        dayNames: ['Воскресенье','Понедельник','Вторник','Среда','Четверг','Пятница','Суббота'],
        dayNamesShort: ['В','П','Вт','С','Ч','П','Сб'],
        dayNamesMin: ['В','П','Вт','С','Ч','П','Сб'],
        firstDay: 1
    };
}

var setLng = {
    init: function(lng) {
        jQuery.datepicker.setDefaults(jQuery.datepicker.regional[lng]);
    }
};


var CalendarEvents = {
    defaultParams: function(id) {
        jQuery.datepicker.setDefaults({
            showButtonPanel: true,
            showAnim: 'fade',
            showWeek: false,
            nextText: '',
            prevText: '',
            firstDay: 1,
            showOtherMonths: true,
            selectOtherMonths: true,
            closeText: '',
            dateFormat: 'dd.mm.yy'
        });


        jQuery(id).datepicker();
        jQuery.datepicker._gotoToday = function(id) {
            var target = jQuery(id);
            var inst = this._getInst(target[0]);
            if (this._get(inst, 'gotoCurrent') && inst.currentDay) {
                inst.selectedDay = inst.currentDay;
                inst.drawMonth = inst.selectedMonth = inst.currentMonth;
                inst.drawYear = inst.selectedYear = inst.currentYear;
            }
            else {
                var date = new Date();
                inst.selectedDay = date.getDate();
                inst.drawMonth = inst.selectedMonth = date.getMonth();
                inst.drawYear = inst.selectedYear = date.getFullYear();
                this._setDateDatepicker(target, date);
                this._selectDate(id, this._getDateDatepicker(target));
            }
            this._notifyChange(inst);
            this._adjustDate(target);
        };
    }
};


var countriesObject = ["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Antigua &amp; Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia &amp; Herzegovina","Botswana","Brazil","British Virgin Islands","Brunei","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Cape Verde","Cayman Islands","Chad","Chile","China","Colombia","Congo","Cook Islands","Costa Rica","Cote D Ivoire","Croatia","Cruise Ship","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Estonia","Ethiopia","Falkland Islands","Faroe Islands","Fiji","Finland","France","French Polynesia","French West Indies","Gabon","Gambia","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guam","Guatemala","Guernsey","Guinea","Guinea Bissau","Guyana","Haiti","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Isle of Man","Israel","Italy","Jamaica","Japan","Jersey","Jordan","Kazakhstan","Kenya","Kuwait","Kyrgyz Republic","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macau","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Mauritania","Mauritius","Mexico","Moldova","Monaco","Mongolia","Montenegro","Montserrat","Morocco","Mozambique","Namibia","Nepal","Netherlands","Netherlands Antilles","New Caledonia","New Zealand","Nicaragua","Niger","Nigeria","Norway","Oman","Pakistan","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Puerto Rico","Qatar","Reunion","Romania","Russia","Rwanda","Saint Pierre &amp; Miquelon","Samoa","San Marino","Satellite","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","South Africa","South Korea","Spain","Sri Lanka","St Kitts &amp; Nevis","St Lucia","St Vincent","St. Lucia","Sudan","Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor L'Este","Togo","Tonga","Trinidad &amp; Tobago","Tunisia","Turkey","Turkmenistan","Turks &amp; Caicos","Uganda","Ukraine","United Arab Emirates","United Kingdom","Uruguay","Uzbekistan","Venezuela","Vietnam","Virgin Islands (US)","Yemen","Zambia","Zimbabwe"];




function getImageSize(images) {
    if (images.length === 0) {
        return;
    }
    var getLength = images.length;
    var i = 0;
    var parent = images.parent();
    var mode;
    mode = Math.max;

    do {
        var width = images.eq(i).width();
        var height = images.eq(i).height();

        if (width === 0 || height === 0) {
            return;
        }

        var parentWidth = parseInt((parent.width()), 10);
        var parentHeight = parseInt((parent.height()), 10);

        var widthRatio = parentWidth / width;
        var heightRatio = parentHeight / height;

        var ratio = mode(widthRatio, heightRatio);

        var newWidth = parseInt((ratio * width), 10);
        var newHeight = parseInt((ratio * height), 10);

        images[i].style.width = newWidth + 'px';
        images[i].style.height = newHeight + 'px';
        images[i].style.marginLeft = ((parentWidth - newWidth) / 2) + 'px';
        images[i].style.marginTop = ((parentHeight - newHeight) / 2) + 'px';

        i++;
    } while (--getLength);
}

var selectBoxes = {
    init: function() {
        var select = jQuery('select:not(.default_select)');

        select.selectBox({
            mobile: true,
            menuSpeed: 200,
            menuTransition: 'fade',
            keepInViewport: true
        });

        select.each(function() {
           if (jQuery(this).find('option').length <= 0) {
               jQuery(this).selectBox('disable');
           }
        });
    }
};

var filters = {
    init: function() {
        this.elementClicks();
        jQuery('.note_area').on('click', '.note_close', function() {
            jQuery(this).fadeOut(200);
            jQuery(this).parents('.note_info').slideUp(350);
            return false;
        });

        jQuery('.main_notification').on('click', '.logout_close', function() {
           jQuery(this).parents('.main_notification').fadeOut(300);
            return false;
        });

        jQuery('.message_section').on('click', '.status dt', function() {

            if (!(jQuery(this).parents('.status').find('dd').is(':animated'))) {
                jQuery(this).parents('.status').find('dd').slideToggle(300);
                if (jQuery(this).parents('.status').hasClass('active')) {
                    jQuery(this).parents('.status').removeClass('active');
                    jQuery('.fade_area').fadeOut(300);
                } else {
                    jQuery(this).parents('.status').addClass('active');
                    jQuery('.fade_area').fadeIn(300);
                }
            }

        });

//        jQuery(document).on('mousedown', function (event) {
//            console.log(event.which);
//            if (1 === event.which) {
//                jQuery('.status').find('dd').slideUp(300);
//            }
//        });
    },
    elementClicks: function() {
        var closeClick = jQuery('.content_section').find('.arrow_area.close'),
            parentAction = null,
            activeCalendar = null,
            startItem = null,
            endItem = null,
            action = null,
            calendarClick = jQuery('.calendar_buttons');

        closeClick.on('click', function() {
            jQuery(this).parents('.content_section');
        });

        calendarClick.find('li span').on('click', function() {
            parentAction = jQuery(this).parents('.calendar_buttons').data('active');
            activeCalendar = jQuery('body').find('[data-calendar="'+ parentAction +'"]');
            action = jQuery(this).data('action');
            startItem = activeCalendar.find('.calendar.start');
            endItem =  activeCalendar.find('.calendar.end');

            if (jQuery(this).hasClass('button_ico')) {
                if (jQuery(this).hasClass('active')){
                    calendarClick.find('li span').removeClass('active');
                    jQuery(startItem).datepicker('setDate', '');
                    jQuery(endItem).datepicker('setDate', '');
                    return;
                } else {
                    calendarClick.find('li span').removeClass('active');
                    jQuery(this).parents('li').find('span').addClass('active');
                }
            } else {
                if (jQuery(this).hasClass('active')){
                    if (jQuery(this).parent().find('span.button_ico').hasClass('active')){
                        calendarClick.find('li span').removeClass('active');
                        jQuery(this).addClass('active');
                    } else {
                        calendarClick.find('li span').removeClass('active');
                        jQuery(startItem).datepicker('setDate', '');
                        jQuery(endItem).datepicker('setDate', '');
                        return;
                    }
                } else {
                    calendarClick.find('li span').removeClass('active');
                    jQuery(this).addClass('active');
                }
           }

            switch(action) {
                case 'now' :
                    jQuery(startItem).datepicker('setDate', Date.today());
                    jQuery(endItem).datepicker('setDate', Date.today());
                    break;

                case 'last_day' :
                    jQuery(startItem).datepicker('setDate', (1).days().ago());
                    jQuery(endItem).datepicker('setDate', Date.today());
                    break;

                case 'yesterday'  :
                    jQuery(startItem).datepicker('setDate', (1).days().ago());
                    jQuery(endItem).datepicker('setDate', (1).days().ago());
                    break;

                case 'this_week'  :
                	if(Date.today().is().monday()) {
                		jQuery(startItem).datepicker('setDate', Date.today());
                	} else {
	                    jQuery(startItem).datepicker('setDate', Date.parse('last monday'));
                	}
                    jQuery(endItem).datepicker('setDate', Date.today());
                    break;

                case 'last_week'  :
                	if(Date.today().is().monday()) {
	                    jQuery(startItem).datepicker('setDate', Date.today().add({days: -7}));
                	} else {
	                    jQuery(startItem).datepicker('setDate', Date.parse('last monday').add({days: -7}));
                	}
                    jQuery(endItem).datepicker('setDate', Date.today());
                    break;

                case 'past_week'  :
                	if(Date.today().is().monday()) {
	                    jQuery(startItem).datepicker('setDate', Date.today().add({days: -7}));
	                    jQuery(endItem).datepicker('setDate', Date.parse('last sunday'));
                	} else {
	                    jQuery(startItem).datepicker('setDate', Date.parse('last monday').add({days: -7}));
	                    if(Date.today().is().sunday()) {
	                    	jQuery(endItem).datepicker('setDate', Date.today());
	                    } else {
	                    	jQuery(endItem).datepicker('setDate', Date.parse('last sunday'));
	                    }
                	}
                    break;

                case 'this_month' :
                    jQuery(startItem).datepicker('setDate', Date.today().moveToFirstDayOfMonth());
                    jQuery(endItem).datepicker('setDate', Date.today());
                    break;

                case 'last_month' :
                    jQuery(startItem).datepicker('setDate', Date.today().add({months: -1}).moveToFirstDayOfMonth());
                    jQuery(endItem).datepicker('setDate', Date.today());
                    break;

                case 'past_month' :
                    jQuery(startItem).datepicker('setDate', Date.today().add({months: -1}).moveToFirstDayOfMonth());
                    jQuery(endItem).datepicker('setDate', Date.today().add({months: -1}).moveToLastDayOfMonth());
                    break;
            }

        });
    }
};

var Loader = {
	saveIsPressed:false,
    addToCreatedPaymentListPressed:false,
    specialLoaderStop:false,
	saveAndSendIsPressed:false,
    sendAllPressed:false,
    timerIdInitForPmtsToSaveActionAfter : null,
    spinner : null,
    init: function() {
    	var opts = {
                lines: 9, // The number of lines to draw
                length: 2, // The length of each line
                width: 2, // The line thickness
                radius: 4, // The radius of the inner circle
                corners: 1, // Corner roundness (0..1)
                rotate: 0, // The rotation offset
                direction: 1, // 1: clockwise, -1: counterclockwise
                color: '#000', // #rgb or #rrggbb or array of colors
                speed: 1.3, // Rounds per second
                trail: 21, // Afterglow percentage
                shadow: false, // Whether to render a shadow
                hwaccel: true, // Whether to use hardware acceleration
                className: 'spinner', // The CSS class to assign to th.e spinner
                zIndex: 2e9, // The z-index (defaults to 2000000000)
                top: 'auto', // Top position relative to parent in px
                left: 'auto' // Left position relative to parent in px
            };         
        var target = document.getElementById('loader');       
    	jQuery('#loader').fadeIn(300);
        Loader.spinner = new Spinner(opts).spin(target);
    },
    initForPmtsToSaveActionAfter: function() {
    	var opts = {
                lines: 9, // The number of lines to draw
                length: 2, // The length of each line
                width: 2, // The line thickness
                radius: 4, // The radius of the inner circle
                corners: 1, // Corner roundness (0..1)
                rotate: 0, // The rotation offset
                direction: 1, // 1: clockwise, -1: counterclockwise
                color: '#000', // #rgb or #rrggbb or array of colors
                speed: 1.3, // Rounds per second
                trail: 21, // Afterglow percentage
                shadow: false, // Whether to render a shadow
                hwaccel: true, // Whether to use hardware acceleration
                className: 'spinner', // The CSS class to assign to th.e spinner
                zIndex: 2e9, // The z-index (defaults to 2000000000)
                top: 'auto', // Top position relative to parent in px
                left: 'auto' // Left position relative to parent in px
            };   
        Loader.specialLoaderStop = true;
        var target = document.getElementById('loader');
        Loader.timerIdInitForPmtsToSaveActionAfter = setTimeout( function () {
        	jQuery('#loader').fadeIn(300);
            Loader.spinner = new Spinner(opts).spin(target);
        },150);
            
    }
    ,stopSpinner: function() {
                clearTimeout(Loader.timerIdInitForPmtsToSaveActionAfter);
                Loader.timerIdInitForPmtsToSaveActionAfter = null;
                try {
                    Loader.spinner.stop();
                }catch(e){
                    // do nothing
                }
	            jQuery('#loader').fadeOut(300); 
	            Loader.specialLoaderStop = false;
	            pressSaveInPmt(Loader.saveIsPressed);
                pressAddToCreatedPaymentList(Loader.addToCreatedPaymentListPressed);
                pressSaveAndSendInPmt(Loader.saveAndSendIsPressed);
                pressSendAll(Loader.sendAllPressed);
    }
};

function pressSaveInPmt(isPressed) {
	if(isPressed) {
    	Loader.saveIsPressed = false;  
		jQuery('.save-hook').click(); 
	}
}

function pressAddToCreatedPaymentList(isPressed) {
    if(isPressed) {
        Loader.addToCreatedPaymentListPressed = false;
        jQuery('.addToCreatedPaymentList-hook').click();
    }
}

function pressSendAll(isPressed) {
    if(isPressed) {
        Loader.sendAllPressed = false;
        jQuery('.sendAll-hook').click();
    }
}
function pressSaveAndSendInPmt(isPressed) {
	if(isPressed) {
		Loader.saveAndSendIsPressed = false;  
		jQuery('.saveAndSend-hook').click(); 
	}
}

function renewUI() {
    renewSelectBox('select', 'refresh');
    if (jQuery.isFunction(jQuery.fn.initCalendarDates)) {
        initCalendarDates();
    }
}

function showLoaderAndRenewUI(data) {
    if (data.status === 'begin') {
        Loader.init();
    } else {
        if (data.status === 'success') {
            renewUI();
        }
        Loader.stopSpinner();
    }
}

function showLoaderAndCallback(data, callback) {
    if (data.status === 'begin') {
        Loader.init();
    } else {
        if (data.status === 'success') {
            callback();
        }
        Loader.stopSpinner();
    }
}

function renewSelectBox(className, event) {
    jQuery(className).each(function() {
        var select = jQuery(this);
        if(!select.hasClass('default_select')) {
            var value = select.selectBox('value');
            if (event === 'refresh') {
	            select.selectBox('destroy');
	        }

	        select.selectBox({
	            mobile: true,
	            menuSpeed: 200,
	            menuTransition: 'fade',
	            keepInViewport: true
	        });

	        select.each(function() {
	            if (jQuery(this).find('option').length <= 0) {
	                jQuery(this).selectBox('disable');
	            }
	        });
            select.selectBox('value', value);
        }
    });
    
}

function renewCalendar(className) {
    var thisID = null;
    jQuery(className).each(function () {
        jQuery(this).datepicker('destroy');
        thisID = jQuery(this).attr('id');
        CalendarEvents.defaultParams('#' + thisID);
    });
}


var setTableSort = function() {
    var tableToSort = jQuery('#sortable');
    if (tableToSort.length > 0) {
        if (jQuery('body').hasClass('ie8')) {
            tableToSort.sortable({
                helper: 'clone',
                refreshPositions: true,
                opacity: 0.5,
                placeholder: 'placeholder',
                toArray: true,
                appendTo: document.body
            });
        } else {
            tableToSort.sortable({
                helper: 'clone',
                refreshPositions: true,
                opacity: 0.5,
                placeholder: 'placeholder',
                toArray: true,
                appendTo: document.body,
                scroll: false
            });
        }
        tableToSort.disableSelection();

        var setTableWidth  = function(tableToSort) {

            if (tableToSort.length > 0) {
                tableToSort.find('td').each(function(){
                    jQuery(this).css('width', jQuery(this).outerWidth(true));
                });
            }
        };
        setTableWidth(tableToSort);

        jQuery(window).resize(function(){
            setTableWidth(tableToSort);
        });
    }
};


function logoutPage() {
    var logout_count = 10;
    try{
        logout_count = jQuery('.logout_timer_count').find('.timer_number').text();
    }catch(er ){
    }
    jQuery('.logout_timer_count').find('.timer_number').html(logout_count);

    var logoutInterval = setInterval(function() {
        logout_count--;
        jQuery('.logout_timer_count').find('.timer_number').html(logout_count);
        if (logout_count == 0) {
            clearInterval(logoutInterval);
            document.location.href="/x/login";
        }
    },1000);

    jQuery(document).on('click', '.logout_close_button', function() {
//       clearInterval(logoutInterval);
//       var ww = window.open(window.location, '_self');
//       ww.close();
       return false;
    });
}


jQuery(function () {
    var tableToSort = jQuery('#sortable');
        if (tableToSort.length > 0) {
            if (jQuery('body').hasClass('ie8')) {
                tableToSort.sortable({
                    helper: 'clone',
                    refreshPositions: true,
                    opacity: 0.5,
                    placeholder: 'placeholder',
                    toArray: true,
                    appendTo: document.body
                });
            } else {
                tableToSort.sortable({
                    helper: 'clone',
                    refreshPositions: true,
                    opacity: 0.5,
                    placeholder: 'placeholder',
                    toArray: true,
                    appendTo: document.body,
                    scroll: false
                });
            }
         tableToSort.disableSelection();

        var setTableWidth  = function(tableToSort) {

            if (tableToSort.length > 0) {
                tableToSort.find('td').each(function(){
                   jQuery(this).css('width', jQuery(this).outerWidth(true));
                });
            }
        };
        setTableWidth(tableToSort);

        jQuery(window).resize(function(){
            setTableWidth(tableToSort);
        });
    }


    jQuery(document).on('selectstart dragstart mousedown keydown keyup mouseup', '.readonly', function(event) {
        if (event.keyCode === 9) {

        } else {
            event.preventDefault();
            event.stopPropagation();
        }
    });

    if (jQuery('.logout_timer_count').length > 0) {
        logoutPage();
    }
});
document.addEventListener('DOMContentLoaded', function() {
    $('[data-open-click]').click(function() {
        var thisCheck = $(this);
        if ( thisCheck.is(':checked') ) {
            var pos = $(this).attr('data-open-click');
            $('[data-open-line="' + pos + '"]').css('display', 'block');
            $('[data-open-line="' + pos + '"]').removeClass('hidden');
            $('[data-open-stuff="' + pos + '"]').addClass('show');
        } else {
            var pos = $(this).attr('data-open-click');
            $('[data-open-line="' + pos + '"]').addClass('hidden');
            $('[data-open-stuff="' + pos + '"]').removeClass('show');
            
        }
    });
});

var ajaxAction = {
	    state : false,
	    load  : false,
	    init: function() {
	       jQuery(document).on('click', 'a.ajax_animate', function  () {

	           var direction = jQuery(this).data('page');

	           if (!ajaxAction.state) {
	                ajaxAction.getPageContent(this.href);
	           }
	           ajaxAction.state = true;
	           return false;
	       });

	        jQuery(window).on('popstate', function() {
	            var location  = history.location || document.location,
	                direction = jQuery('.main_content').data('content');


	            if (ajaxAction.load) {
	                (history.state !== null && history.state !== undefined) ?
	                    ajaxAction.getPageContent(location) :
	                    ajaxAction.getPageContent(location);
	            }
	            ajaxAction.load = true;
	        });
	    },
	    getPageContent : function(page) {
	        var timeToStart = null,
	            timeHold    = null,
	            showedContent = $('.main_content');
	        Loader.init();
	        
	        jQuery.ajax ({
	            url: page,
	            type: 'get',
	            dataType: 'html',
	            success : function(html) {	            	
	                setTimeout( function () {
	                    Loader.stopSpinner();
	                },1500);
	            },
	            complete: function() {
	                if (timeToStart) {
	                    clearTimeout(timeToStart);
	                }
	                if (timeHold) {
	                    clearTimeout(timeToStart);
	                }

	                timeToStart =  setTimeout(function() {
                      timeHold = setTimeout(function() {
                            showedContent.remove();
                            ajaxAction.state = false;
                        },550);
	                },10);

	                
	            }
	        });
	    },
	 
	};

jQuery(function () {
    ajaxAction.init();  
});



function showBoDialog(params) {
    var $notificationContent = $('.notification_content');
    if ($notificationContent.length) {
        return ;
    }
    $(params['id']).dialog({
        show: true,
        dialogClass: "bo-dialog",
        resizable: false,
        height: "auto",
        width: 560,
        modal: true,
        open: function(event, ui) {
            $(event.target).dialog('widget')
                .css({ position: 'fixed' })
                .position({ my: 'center', at: 'center', of: window });
        }
    });
    $(window).resize(function() {
        $(".ui-dialog-content:visible").each(function () {
            $( this ).dialog("option","position",$(this).dialog("option","position"));
        });
    });
}

function hideBoDialog() {
    $('.bo-dialog-main').dialog('close');
}

function showCardActivationDialog(data) {
    if (data.status === 'success') {
        showBoDialog({id:'#card-activation-dialog'});
    }
}
