(function(){
	var Auction = function() {

		var doms = {
			bidHistory: $('.bid-history-table'),
			lastBidder: $('.item-details .lastBidder'),
			currentPrice: $('.currentPrice'),
			currentBidPrice: $('.currentBidPrice'),
			placebidModal: $('#placebid-modal'),
			buyItNowModal: $('#buyitnow-modal'),
			buyItNowBtn: $('.buy-now-btn'),
			myBuyItNowPrice: $('.myBuyItNowPrice'),
			placebidModalOkBtn: $('.placebid-ok-btn'),
			placebidModalCancelBtn: $('.placebid-cancel-btn'),
			buyItNowModalOkBtn: $('.buyitnow-ok-btn'),
			buyItNowModalCancelBtn: $('.buyitnow-cancel-btn'),
			setBidButlerBtn: $('.setBidButlerBtn'),
			bitButlerInput: $('input[name=bitButlerInput]'),
			bidButlerCurrently: $('.bidButlerCurrently'),
			endsAt: $('.endsAt')
		},
		aid = window.aid, initSocket = window.initWs;



		var initWebsocket = function(){
            if( window.io == undefined || io == undefined ) return;
            
            //var socket = io.connect('http://ausante.green:9090', { reconnect: true, transports: ['websocket', 'polling'], path: '/socketio', query: window.squery });
            var socket = io.connect(socket_url, { reconnect: true, transports: ['websocket', 'polling'], path: '/socketio', query: window.squery });

            socket.on('auction.newBid', function( data ) {
                //console.log(data);
                var newBids = data.newBids;

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

				if( newBids && newBids.length > 0 ) {
					var lastBidder = newBids[ newBids.length - 1 ];

					if( doms.bidHistory.find('tbody tr').length == 10 ) {
						doms.bidHistory.find('tbody tr').slice( -newBids.length ).remove();
					}

					for( var i = 0; i < newBids.length; i++ ) {
						doms.bidHistory.find('tbody').prepend('<tr class="flash"><td>' + newBids[i].username + '</td><td>$' + parseFloat(newBids[i].price).toFixed(2) + '</td><td>' + ((newBids[i].type == 1) ? 'Normal' : ((newBids[i].type == 2) ? 'Bid Butler' : 'Buy It Now') ) + '</td><td data-custom-event="utc-offset-update">' + newBids[i].created_at_format + '</td></tr>');

						//If autobid, decrement the font-end's remaining autobid count value
						if(data.is_butler !== undefined && data.is_butler == 1)
						{
							if(act_page_user_id == newBids[i].user_id)
							{
                                var act_cont = doms.bidButlerCurrently.find('.value').text();
                                act_cont = act_cont.replace('(', '').replace(')', '');
                                var cont_array = act_cont.split(' ');

                                var act_one_bid = parseInt(cont_array[1]) / parseInt(cont_array[0]);
								var new_bid_count = parseInt(cont_array[1]) - act_one_bid;
                                var act_value = parseInt(cont_array[0]) - 1;

                                if(act_value >= 0) doms.bidButlerCurrently.find('.value').text(act_value + ' (' + new_bid_count + ' bids)');
							}
						}
					}

					doms.lastBidder.find('.value').text( lastBidder.username );
					doms.currentPrice.find('.value').text('$'  + parseFloat(data.item.current_price).toFixed(2) );
					//doms.currentBidPrice.find('.value').text( parseFloat(data.item.current_price).toFixed(2) );
					doms.endsAt.find('.value').attr('data-ts', data.item.ends_at_ts * 1000 ).removeClass('highlight');

                    custom_updateUTCs();

					AuctionCommon.initCountdowns();
				}
            });

            socket.on('auction.ended', function( data ) {
               location.reload();
            });

        };

	    return {

	    	init: function() {
	    		if( initSocket )
	    			initWebsocket();

				$('.item-images a').on('click', function(e) {
					e.preventDefault();
					var images = [];

					$('.item-images a').each(function() {
						images.push({
			                href: $(this).attr('href'),
			                title: $(this).attr('title')
			            });
					});

					blueimp.Gallery(images, {
			            container: '#blueimp-gallery',
			            carousel: true,
			            event: e
			        });
				});

				$.fn.modal.defaults.spinner = $.fn.modalmanager.defaults.spinner = 
		        '<div class="loading-spinner" style="width: 200px; margin-left: -100px;">' +
		            '<div class="progress progress-striped active">' +
		                '<div class="progress-bar" style="width: 100%;"></div>' +
		            '</div>' +
		        '</div>';

				$('.place-bid-btn').on('click', function(e) {
					/*$('body').modalmanager('loading');
					doms.placebidModal.modal();*/
					var self = $(this);

					self.addClass('disabled').prop('disabled', 'disabled');

					App.ajax({
						url: window.placeBidUrl,
						data: {
							id: aid
						}
					}, function( d ) {
						self.removeClass('disabled').prop('disabled', false);
						//doms.placebidModal.modal('hide');
					}, function() {
						self.removeClass('disabled').prop('disabled', false);
					});
				});

				doms.placebidModalOkBtn.on('click', function(e) {
					App.ajax({
						url: window.placeBidUrl,
						data: {
							id: aid
						}
					}, function( d ) {
						doms.placebidModal.modal('hide');
					});
				});
				doms.placebidModalCancelBtn.on('click', function(e) {
					doms.placebidModal.modal('hide');
				});

				doms.buyItNowBtn.on('click', function(e) {
					$('body').modalmanager('loading');

					App.ajax({
						url: window.buyPriceUrl,
						data: {
							id: aid
						}
					}, function(data) {
						var bp = parseFloat(data.data.buyItNowPrice).toFixed(2),
							pb = parseFloat(data.data.prevBids).toFixed(2),
							rp = bp - pb;

						doms.myBuyItNowPrice.find('.value').text( '$' + rp );
						doms.buyItNowModal.modal();
					});
				});
				doms.buyItNowModalOkBtn.on('click', function(e) {
					App.ajax({
						url: window.buyItNowUrl,
						data: {
							id: aid
						}
					}, function( d ) {
						doms.buyItNowModal.modal('hide');
					});
				});
				doms.buyItNowModalCancelBtn.on('click', function(e) {
					doms.buyItNowModal.modal('hide');
				});

				doms.setBidButlerBtn.on('click', function(e) {
					e.preventDefault();

					var val = doms.bitButlerInput.val().trim();

					if( val && val !== '' && !isNaN(parseInt(val)) ) {
						App.ajax({
							url: window.bidButlerUrl,
							data: {
								id: aid,
								counter: val
							}
						}, function( data ) {
							if( data && data.data && data.data.result ) {
								doms.bidButlerCurrently.find('.value').text( data.data.counter + ' (' + data.data.counter * data.data.multiplier + ' bids)' );
								doms.bidButlerCurrently.removeClass('hidden');
							}
						});
					}
				});

                $('.btn-clear').on('click', function(e) {
                    e.preventDefault();

                    var act_val = parseInt(doms.bidButlerCurrently.find('.value').text().split(' ')[0]);

                    console.log(act_val);

                    if( act_val && act_val !== '' && !isNaN(parseInt(act_val)) ) {
                        App.ajax({
                            url: window.clearButlerUrl,
                            data: {
                                id: aid,
                                counter: act_val
                            }
                        }, function( data ) {
                            if( data && data.data && data.data.result ) {
                                doms.bidButlerCurrently.find('.value').text( data.data.counter + ' (' + data.data.counter * data.data.multiplier + ' bids)' );
                                doms.bidButlerCurrently.addClass('hidden');
                            }
                        });
                    }

                });
	        }
	    };
  	}();

	$(document).ready(function() {
        Auction.init();

        custom_updateUTCs();

		/*
        var start_time = $('#item_start_time').text();
        var end_time = $('#item_end_time').text();
        //custom_getClientUTCTime(start_time)
        $('#item_start_time').text(custom_getClientUTCTime(start_time));
        $('#item_end_time').text(custom_getClientUTCTime(end_time));
        */
	});

})();