/**
Core script to handle the entire theme and core functions
**/




initSocket = window.initWs;

var itemIds = getItemIds();
window.uquery.followedItems = itemIds;


var socket = io.connect(socket_url, {
    reconnect: true,
    transports: ['websocket', 'polling'],
    path: '/socketio',
    query: window.uquery
});

socket.on('user.newNotification', function (data) {
    incrementNotificationCounter();
});

socket.on('user.updateItems', function (data) {
    updateVisitorWidgetItems(data);
});


var Layout = function () {

    var layoutImgPath = 'layouts/layout3/img/';

    var layoutCssPath = 'layouts/layout3/css/';

    var resBreakpointMd = App.getResponsiveBreakpoint('md');

    //* BEGIN:CORE HANDLERS *//
    // this function handles responsive layout on screen size resize or mobile device rotate.

    // Handles header
    var handleHeader = function () {        
        // handle search box expand/collapse        
        $('.page-header').on('click', '.search-form', function (e) {
            $(this).addClass("open");
            $(this).find('.form-control').focus();

            $('.page-header .search-form .form-control').on('blur', function (e) {
                $(this).closest('.search-form').removeClass("open");
                $(this).unbind("blur");
            });
        });

        // handle hor menu search form on enter press
        $('.page-header').on('keypress', '.hor-menu .search-form .form-control', function (e) {
            if (e.which == 13) {
                $(this).closest('.search-form').submit();
                return false;
            }
        });

        // handle header search button click
        $('.page-header').on('mousedown', '.search-form.open .submit', function (e) {
            e.preventDefault();
            e.stopPropagation();
            $(this).closest('.search-form').submit();
        });

        // handle scrolling to top on responsive menu toggler click when header is fixed for mobile view
        $('body').on('click', '.page-header-top-fixed .page-header-top .menu-toggler', function(){
            App.scrollTop();
        });     
    };

    // Handles main menu
    var handleMainMenu = function () {

        // handle menu toggler icon click
        $(".page-header .menu-toggler").on("click", function(event) {
            if (App.getViewPort().width < resBreakpointMd) {
                var menu = $(".page-header .page-header-menu");
                if (menu.is(":visible")) {
                    menu.slideUp(300);
                } else {  
                    menu.slideDown(300);
                }

                if ($('body').hasClass('page-header-top-fixed')) {
                    App.scrollTop();
                }
            }
        });

        // handle sub dropdown menu click for mobile devices only
        $(".hor-menu .menu-dropdown > a, .hor-menu .dropdown-submenu > a").on("click", function(e) {  
            if (App.getViewPort().width < resBreakpointMd) {
                if ($(this).next().hasClass('dropdown-menu')) {
                    e.stopPropagation();
                    if ($(this).parent().hasClass("opened")) {
                        $(this).parent().removeClass("opened");
                    } else {
                        $(this).parent().addClass("opened");
                    }
                }
            }
        });

        // close main menu on final link click for mobile mode
        $(".hor-menu li > a").on("click", function(e) {
            if (App.getViewPort().width < resBreakpointMd) {
                if (!$(this).parent('li').hasClass('classic-menu-dropdown') && !$(this).parent('li').hasClass('mega-menu-dropdown')
                    && !$(this).parent('li').hasClass('dropdown-submenu')) {
                    $(".page-header .page-header-menu").slideUp(300);
                     App.scrollTop();
                }
            }
        });

        // hold mega menu content open on click/tap. 
        $(document).on('click', '.mega-menu-dropdown .dropdown-menu, .classic-menu-dropdown .dropdown-menu', function (e) {
            e.stopPropagation();
        });

        // handle fixed mega menu(minimized) 
        $(window).scroll(function() {                
            var offset = 75;
            if ($('body').hasClass('page-header-menu-fixed')) {
                if ($(window).scrollTop() > offset){
                    $(".page-header-menu").addClass("fixed");
                } else {
                    $(".page-header-menu").removeClass("fixed");  
                }
            }

            if ($('body').hasClass('page-header-top-fixed')) {
                if ($(window).scrollTop() > offset){
                    $(".page-header-top").addClass("fixed");
                } else {
                    $(".page-header-top").removeClass("fixed");  
                }
            }
        });
    };

    // Handle sidebar menu links
    var handleMainMenuActiveLink = function(mode, el, $state) {
        var url = encodeURI(location.hash).toLowerCase();    

        var menu = $('.hor-menu');

        if (mode === 'click' || mode === 'set') {
            el = $(el);
        } else if (mode === 'match') {
            menu.find("li > a").each(function() {
                var state = $(this).attr('ui-sref');
                if ($state && state) {
                    if ($state.is(state)) {
                        el = $(this);
                        return;
                    }
                } else {
                    var path = $(this).attr('href');
                    if (path) {
                        // url match condition         
                        path = path.toLowerCase();
                        if (path.length > 1 && url.substr(1, path.length - 1) == path.substr(1)) {
                            el = $(this);
                            return;
                        }
                    }
                }
            });
        }

        if (!el || el.size() == 0) {
            return;
        }

        if (el.attr('href') == 'javascript:;' ||
            el.attr('ui-sref') == 'javascript:;' ||
            el.attr('href') == '#' ||
            el.attr('ui-sref') == '#'
            ) {
            return;
        }      

        // disable active states
        menu.find('li.active').removeClass('active');
        menu.find('li > a > .selected').remove();
        menu.find('li.open').removeClass('open');

        el.parents('li').each(function () {
            $(this).addClass('active');

            if ($(this).parent('ul.navbar-nav').size() === 1) {
                $(this).find('> a').append('<span class="selected"></span>');
            }
        });
    };

    // Handles main menu on window resize
    var handleMainMenuOnResize = function() {
        // handle hover dropdown menu for desktop devices only
        var width = App.getViewPort().width;
        var menu = $(".page-header-menu");
            
        if (width >= resBreakpointMd) { 
            $(".page-header-menu").css("display", "block");
        } else if (width < resBreakpointMd) {
            $(".page-header-menu").css("display", "none"); 
        } 
    };

    var handleContentHeight = function() {
        if ($('body').height() < App.getViewPort().height) {            
            height = App.getViewPort().height -
                $('.page-header').outerHeight() - 
                ($('.page-container').outerHeight() - $('.page-content').outerHeight()) -
                $('.page-prefooter').outerHeight() - 
                $('.page-footer').outerHeight();

            $('.page-content').css('min-height', height);
        }
    };

    // Handles the go to top button at the footer
    var handleGoTop = function () {
        var offset = 100;
        var duration = 500;

        if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {  // ios supported
            $(window).bind("touchend touchcancel touchleave", function(e){
               if ($(this).scrollTop() > offset) {
                    $('.scroll-to-top').fadeIn(duration);
                } else {
                    $('.scroll-to-top').fadeOut(duration);
                }
            });
        } else {  // general 
            $(window).scroll(function() {
                if ($(this).scrollTop() > offset) {
                    $('.scroll-to-top').fadeIn(duration);
                } else {
                    $('.scroll-to-top').fadeOut(duration);
                }
            });
        }
        
        $('.scroll-to-top').click(function(e) {
            e.preventDefault();
            $('html, body').animate({scrollTop: 0}, duration);
            return false;
        });
    };

    //* END:CORE HANDLERS *//

    return {
        
        // Main init methods to initialize the layout
        // IMPORTANT!!!: Do not modify the core handlers call order.

        initHeader: function($state) {
            handleHeader(); // handles horizontal menu    
            handleMainMenu(); // handles menu toggle for mobile
            App.addResizeHandler(handleMainMenuOnResize); // handle main menu on window resize


        },

        initContent: function() {
            handleContentHeight(); // handles content height 
        },

        initFooter: function() {
            handleGoTop(); //handles scroll to top functionality in the footer
        },

        init: function () {            
            this.initHeader();
            this.initContent();
            this.initFooter();
        },

        setMainMenuActiveLink: function(mode, el) {
            handleMainMenuActiveLink(mode, el);
        },

        setAngularJsMainMenuActiveLink: function(mode, el, $state) {
            handleMainMenuActiveLink(mode, el, $state);
        },

        closeMainMenu: function() {
            $('.hor-menu').find('li.open').removeClass('open');

            if (App.getViewPort().width < resBreakpointMd && $('.page-header-menu').is(":visible")) { // close the menu on mobile view while laoding a page 
                $('.page-header .menu-toggler').click();
            }
        },

        getLayoutImgPath: function() {
            return App.getAssetsPath() + layoutImgPath;
        },

        getLayoutCssPath: function() {
            return App.getAssetsPath() + layoutCssPath;
        }
    };

}();


var AuctionVisitor = function() {

    var countdownTypes = {
        soon: '%Dd %H:%M:%S'
    };

    var initCountdowns = function() {
        $('.ends-at').each(function(item) {
            var elem = $(this);
            //console.log(elem);
            if( elem.attr('data-ended') != 1 ) {
                //console.log(elem.attr('data-ts'));
                elem.countdown(elem.attr('data-ts'), function(event) {
                    if( event.offset.elapsed || event.offset.totalSeconds === 0 ) {
                        var _parent = $(this).parents('.auction-item');

                        if( _parent.length > 0 )
                            _parent.fadeOut(300).remove();

                        $(this).attr('data-ended', 1).html('Ended');
                    } else {
                        if( event.offset.totalSeconds <= (5 * 60) && !$(this).hasClass('highlight') )
                            $(this).addClass('highlight');

                        $(this).html(
                            event.strftime( countdownTypes[ elem.data('type') ] )
                        );
                    }
                });

            }
        });
    };

    return {

        init: function() {
            initCountdowns();
        },
        initCountdowns: initCountdowns
    };
}();

    jQuery(document).ready(function() {   
        Layout.init(); // init metronic core componets

        AuctionVisitor.init();

    });

function custom_getUTCTime(utc_shift_hour)
{
    var d = new Date();
    var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
    var nd = new Date(utc + (3600000*utc_shift_hour));
    //console.log(nd.toLocaleString());
    return nd;
}

function custom_getClientUTCTime(server_offset, server_time, plus_offset_sec, only_increment)
{

    server_time = server_time.replace(/\./g, '/');

    var return_value = '';
    if(only_increment !== undefined && only_increment == true) {
        var server_d = new Date(Date.parse(server_time));
        //console.log(server_d);
        if (plus_offset_sec !== undefined && plus_offset_sec != 0) {
            server_d.setSeconds(server_d.getSeconds() + plus_offset_sec);
            var plus_offset = server_d.getTime();
            //console.log(plus_offset);
            return_value = new Date(plus_offset);
        }
        else{
            return_value = server_d;
        }
    }
    else {
        var local_d = new Date();

        var server_d = new Date(Date.parse(server_time));
        //console.log(server_d);
        if (plus_offset_sec !== undefined && plus_offset_sec != 0) {
            server_d.setSeconds(server_d.getSeconds() + plus_offset_sec);
        }

        var utc = server_d.getTime() + ((server_offset * (-60)) * 60000);

        var nd = new Date(utc + (3600000 * (local_d.getTimezoneOffset() / -60)));

        return_value = nd;
    }

    return_value = return_value.getFullYear() + "." + ("0"+(return_value.getMonth()+1)).slice(-2) + '.' + ("0" + return_value.getDate()).slice(-2) + " " + ("0" + return_value.getHours()).slice(-2) + ":" + ("0" + return_value.getMinutes()).slice(-2) + ":" + ("0" + return_value.getSeconds()).slice(-2);
    return return_value;
}

function custom_updateUTCs()
{
    $("[data-custom-event=utc-offset-update]").each(function(/*index*/) {
        var act_value = $(this).text();
        //console.log(index + ' :' + act_value);
        $(this).text(custom_getClientUTCTime(8, act_value, 0, false));
        $(this).removeAttr("data-custom-event");
    });

    $("[data-custom-event=utc-offset-increment]").each(function(/*index*/) {
        var act_value = $(this).text();
        //console.log('only inc');
        //console.log(index + ' :' + act_value);
        $(this).text(custom_getClientUTCTime(8, act_value, 10, true));
    });

    $("[data-custom-event=utc-offset-update-increment]").each(function(/*index*/) {
        var act_value = $(this).text();
        //console.log(index + ' :' + act_value);
        $(this).text(custom_getClientUTCTime(8, act_value, 10, false));
        $(this).attr("data-custom-event", "utc-offset-increment");
    });
}

function incrementNotificationCounter()
{
    console.log('Incrementing notifs...');
    var act_value = $('#notification_counter').text();
    var act_class = $('#notification_counter').attr('class');
    $('#notification_counter').text(parseInt(act_value) + 1);
    if(act_class == 'badge badge-default hidden'){
        $('#notification_counter').attr('class', 'badge badge-default');
    }
}

function flashElementOnce (element)
{
    element.addClass('flash-once flash-transition');
    setTimeout(function(){
        element.removeClass('flash-once');
    }, 1300);
}

function flashElementColorOnce (element)
{
    element.addClass('flash-color-once flash-color-transition');
    setTimeout(function(){
        element.removeClass('flash-color-once');
    }, 3300);
}


function updateVisitorWidgetItems(data)
{
    //console.log('Updating items attributes...');
    //console.log(data);
    var newBids = data.newBids;
    var item = data.item;

    if( data.ended ) {
        location.reload();
    }

    if( newBids && newBids.length > 0 ) {
        $('.single-auction-item').each(function(){
            var elem = $(this);
            //console.log(elem.attr('data-item-id'));
            if( elem.attr('data-item-id') == item.id) {
                var act_ts = elem.find('.value ends-at').attr('data-ts');
                elem.find('.value').attr('data-ts', item.ends_at_ts * 1000);
                elem.find('.price').text('$' + parseFloat(item.current_price).toFixed(2));
                AuctionVisitor.init();
            }
        });
    }
}

function getItemIds()
{
    var itemIdArray = [];

    $("#ending-soon-container .single-auction-item").each(function(){
        itemIdArray.push($(this).data('item-id'));
    });

    $("#auction-items-container .single-auction-item").each(function(){
        itemIdArray.push($(this).data('item-id'));
    });

    if(itemIdArray.length == 0) {

        $(".single-auction-item").each(function () {
            itemIdArray.push($(this).data('item-id'));
        });
    }

    return Array.from(new Set(itemIdArray));
}
