(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;


		$('.btn-offer').tooltip();
        $('.btn-clear').tooltip();

		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.mquery });

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

                var parent_tr;

                $('tr.text-center').each(function(item) {
                    var elem = $(this);
                    //console.log(elem.attr('data-id'));
                    items_array.push(elem.attr('data-id'));
                    if(elem.attr('data-id') == data.item.id){
                        parent_tr = elem;
					}
                });

				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 element_butlers = parent_tr.find('.td-butlers');
                                var act_count = parseInt(element_butlers.text());


                                if(act_count > 0) element_butlers.text(act_count - 1);

                                var bids_left = parseInt($('#bids-left').text().replace(/,/g, ""));
                                //console.log(bids_left);
                                if(bids_left > 0) {
                                    bids_left = bids_left - 1;
                                    $('#bids-left').text(bids_left.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
                                    flashElementColorOnce($('#bids-left'));
                                }

                                flashElementColorOnce(element_butlers);

                                /*var act_cont = doms.bidButlerCurrently.find('.value').text();
                                var 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)');
							}
						}
					}

                    var element_time_left = parent_tr.find('.ends-at');
                    element_time_left.find('.value').attr('data-ts', data.item.ends_at_ts * 1000 ).removeClass('highlight');

                    var element_current_price = parent_tr.find('.td-price');
                    element_current_price.text('$'  + parseFloat(data.item.current_price).toFixed(2) );


                    /*
					//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();

                    flashElementColorOnce(element_time_left);
                    flashElementColorOnce(element_current_price);
				}
            });

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

				$('.btn-offer').on('click', function(e) {
					e.preventDefault();
					var tr_element = $(this).parents('tr');
					var item_id = tr_element.attr('data-id');
					var val = tr_element.find('.input-offer').val();

                    tr_element.find('.input-offer').val(1);

					var act_counter = tr_element.find('.td-butlers');

					//console.log(val);
					//console.log($(this).parent().parent().attr('data-id'));
					//var val = doms.bitButlerInput.val().trim();


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

                                flashElementColorOnce(act_counter);

							}
						});
					}

				});


                $('.btn-clear').on('click', function(e) {
                    e.preventDefault();
                    var tr_element = $(this).parents('tr');
                    var item_id = tr_element.attr('data-id');
                    //var val = tr_element.find('.input-offer').val();

                    tr_element.find('.input-offer').val(1);

                    var act_counter = tr_element.find('.td-butlers');

                    var act_val = parseInt(act_counter.text());


                    //console.log(act_val);

                    //console.log(val);
                    //console.log($(this).parent().parent().attr('data-id'));
                    //var val = doms.bitButlerInput.val().trim();


                    if( act_val && act_val !== '' && !isNaN(parseInt(act_val)) ) {
                        App.ajax({
                            url: window.clearButlerUrl,
                            data: {
                                id: item_id,
                                counter: act_val
                            }
                        }, function( data ) {
                            if( data && data.data && data.data.result ) {
                                act_counter.text( data.data.counter);
                                //act_counter.text( data.data.counter + ' (' + data.data.counter * data.data.multiplier + ' bids)' );
                                act_counter.removeClass('hidden');

                                flashElementColorOnce(act_counter);

                                /*var bids_left = parseInt($('#bids-left').text().replace(/,/g, ""));
                                //console.log(bids_left);
                                if(bids_left > 0) {
                                    bids_left = bids_left + act_counter;
                                    $('#bids-left').text(bids_left.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
                                }
								*/

                            }
                        });
                    }

                });
	        }
	    };
  	}();

	$(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));
        */
	});

})();