(function () {

    var AuctionVisitor = function () {

        var countdownTypes = {
            //soon: '%H:%M:%S'
            soon: '%Dd %H:%M:%S',
            default: '%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
        };
    }();


    var Visitor = function () {
        return {

            init: function () {


                var itemIds = getItemIds();


                window.vquery = {
                    visitorId: getUuidv4(),
                    followedItems: itemIds
                };

                //console.log('Visitor id: ' + window.vquery.visitorId);

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

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


            }
        }
    }();



    $(document).ready(function () {
        Visitor.init();
        AuctionVisitor.init();

 
    });

    function getUuidv4() {
        return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
            (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
        )
    }

    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'));
        })

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

        return itemIdArray;
    }

})();