var SnipsterAuctionUpdater = (function () {

    var that = {},
        _timeout = 30 * 60 * 1000,
        _endTime = (new Date()).getTime() + _timeout,
        _auctionIds = null,
        _box_initialized = false,
        _mode = 'list',
        _show_layer = true;

    function isActive() {
        if ((new Date()).getTime() > _endTime) {
            return false;
        }

        return true;
    }

    function setBoxPosition() {
        // Calculate a center position for the box.
        var $box = $$("#inactivity_layer .box")[0],
            left = (window.innerWidth / 2) - ($box.getWidth() / 2);

        try {
            $box.style.left = left + 'px';
        } catch (e) {
            // Must be a crappy browser.
        }
    }

    function showTimeout() {
        // In some cases the ajax calls stop but the timeout box should not be
        // displayed.
        if (!_show_layer) {
            return;
        }
        $("inactivity_layer").style.display = 'block';
        setBoxPosition();

        if (!_box_initialized) {
            // Only observe the elements once.
            $$("#inactivity_layer .close, #inactivity_layer button").each(function ($element) {
                $element.observe('click', function () {
                    window.location.reload();
                    return;
                    /*
                     * Disabled on request.
                    that.reset();
                    if (_mode === 'list') {
                        that.run();
                    } else {
                        that.run_detail();
                    }
                    */
                });
            });
            _box_initialized = true;
        }
    }

    that.run = function (auctionIds) {
        if (auctionIds !== undefined) {
            _auctionIds = auctionIds;
        }

        if (isActive()) {
            new Ajax.Request(
                '/getInfo1.php?auction_id_list=' + _auctionIds,
                {
                    method: 'POST',
                    onComplete: updateBidView
                }
            );
            window.setTimeout(function () {
                that.run();
            }, 1000);
        } else {
            showTimeout();
        }
    };

    that.run_detail = function (auctionId) {
        if (auctionId !== undefined) {
            _auctionIds = auctionId;
        }

        _mode = 'detail';

        // This looks like a lot of boilerplate, but there might be different
        // AJAX options for this type of request like additional parameters
        // or different timing.
        if (isActive()) {
            new Ajax.Request(
                '/getInfo2.php?auction_id=' + _auctionIds,
                {
                    method: 'POST',
                    onComplete: updateBidDetailView
                }
            );
            window.setTimeout(function () {
                that.run_detail();
            }, 1000);
        } else {
            showTimeout();
        }

    };

    // Reset the timeout (when user closes the popup).
    that.reset = function () {
        _endTime = (new Date()).getTime() + _timeout;
        $("inactivity_layer").style.display = 'none';
    };

    that.stop = function (no_layer) {
        if (no_layer === true) {
            _show_layer = false;
        }
        _endTime = (new Date()).getTime();
    };

    return that;
}());


var updateBidView = function(r) {
	var response = r.responseText;
	var auctionResponses = response.split(';');
	
	for(var j = 0; j < auctionResponses.length; ++j) {
		var ai = auctionResponses[j].split('|');
		updateAuction(ai);
	}
};

var updateBidDetailView = function(r) {
	var response = r.responseText;
	var ai = response.split("|");

	var aid = ai[0];
	var status = ai[1];

	updateAuction(ai);

	var history = ai[12];
	var historyItems = history.split(';');
	var placedBids = '';
	var classStr = 'first';
	for (var i = 0; i < historyItems.length; i++) {
		var hd = historyItems[i].split('::');
		if (hd.length != 5) {
			continue;
		}
		var bidTime = hd[0];
		var userId = hd[1];
		var username = hd[2];
		var price = hd[3];
		var type = hd[4];
		var icon = '';

		if(type == 3) {
			icon = '<img src="/img/icon_pb.png" title="Telefongebot" />';
		} else if(type == 2) {
			icon = '<img src="/img/icon_ba.png" title="Bietagent" />';
		} else {
			icon = '<img src="/img/icon_db.png" title="Direktgebot" />';
		}
		if(bidTime != '') {
			placedBids = [placedBids, '<dt class="', classStr, ' time_cell">', bidTime.substr(11, 5), ' Uhr</dt>',
                '<dd id="historyUser', userId, '" class="userInfo historyUser ', classStr, '" style="text-align:left;font-weight:normal; width: 112px;">', username, '</dd>',
				'<dd class="', classStr, '">&euro;&nbsp;', currency(price), '</dd>',
				'<dd class="fourth ', classStr, '">', icon, '</dd>'].join('');
		}
		classStr = '';
	}
	document.getElementById('bidHistory').innerHTML = placedBids;

    // Show user info
    $$("#bidHistory .userInfo").each(function(el) {
        el.observe('click', function() {
            var currentUserId = this.id.split('historyUser')[1];
            var currentUserName = this.firstChild.nodeValue.strip();
            showUserInfoTip(currentUserName, currentUserId, this);
        });
    });

	if (status == 2) { // Auction has ended
		SnipsterAuctionUpdater.stop(true);
	}
};

var updateAuction = function(ai) {
	//  0 = Auction ID
	//  1 = Status
	//  2 = Formatted countdown
	//  3 = Countdown
	//  4 = Bids
	//  5 = Price
	//  6 = User ID (0 if not applicable)
	//  7 = User name (empty string if not applicable)
	//  8 = Activity index
	//  9 = Active?
	// 10 = Pending
	// 11 = Highest bidder?
	// (12 = History)

	var aid = ai[0];
	var status = ai[1];
	var countdownFormatted = ai[2];
	var countdown = ai[3];
	var nBids = ai[4];
	var price = ai[5];
	var userId = ai[6];
	var username = ai[7];
	var activity = ai[8];
	var active = ai[9];
	var pendingBids = ai[10];
	var isHighestBidder = ai[11];
	
	// Update bid count
	if (nBids != '') {
		updateCurrentBidCount(aid, nBids);
	}
	// Display countdown
	$('cd'+aid).update(countdownFormatted);
	if (countdownFormatted == 'CHECK' || countdownFormatted == 'PAUSE') {
		document.getElementById('cd'+aid).className='countdown';
	} else {
		if (0 < countdown && countdown <= 10 && countdown % 2 === 0) {
			document.getElementById('cd'+aid).className='countdown active';
		} else {
			document.getElementById('cd'+aid).className='countdown';
		}
	}
	// Price
	if (price != '') {
		$('cp'+aid).update('&euro;&nbsp;'+price.replace(/\./g, ','));
	}
	// Username
	if (username != '') {
		$('cu'+aid).update(username);
        if(userId) {
            $('cu'+aid).stopObserving('click')
                .observe('click', function() {
                    var username = this.firstChild.nodeValue.strip();
                    var curUID = userId;
                    showUserInfoTip(username, curUID, this);
                });
        }
        if (isHighestBidder > 0) {
        	if (!$('cu'+aid).hasClassName('me')) {
                $('cu'+aid).addClassName('me');
        	}
        } else if ($('cu'+aid).hasClassName('me')) {
            $('cu'+aid).removeClassName('me');
        }
	}
	// Activity index
	updateActivityIndex(aid, activity, active);
	// Pending bids (if existing)
	if ($('cob'+aid)) {
		if(pendingBids != '' && pendingBids > 0) {
			$('cob'+aid).update(pendingBids+(pendingBids==1?' offenes Gebot':' offene Gebote'));
		} else {
		  $('cob'+aid).update('');
		}
	}

	if (status == 2) { // Auction has ended
		if (typeof(isRunning) != 'undefined') { // We're on the details page
			if (!isRunning) { // Auction has ended before
				return;
			} else { // Auction has just ended
				$('auctionStatus').update('Auktion beendet');
				$('endOfAuction').update('Auktionsende');
				var d = new Date();
				$('auctionEndDate').update(twoDigits(d.getDate())+'.'+twoDigits(d.getMonth())+'.'+d.getFullYear()+', '+twoDigits(d.getHours())+':'+twoDigits(d.getMinutes())+' Uhr');
				$('phoneInfoRunning').hide();
				$('phoneInfoSold').show();
				$('phoneFootnote').hide();
				$('auctionSetBidCountEnabled').hide();
				$('auctionSetBidCountDisabled').show();
				// Winner popup
				if (isHighestBidder > 0) {
					$('winnerPopup').show();
				}
				isRunning = false;
			}
		}
		// Replace bid button (spotlight/box/list/details) if existing
		var but = $('but'+aid);
		if (but && but.src.indexOf('_sold') < 0) { // Button is active
			but.src = but.src.replace(/\-trans.png/, '_sold-trans.png');
			if (but.getStyle('width') == '89px' && but.getStyle('height') == '26px') {
				but.setStyle({width: '90px', height:'63px'});
			}
		} else { // Otherwise there is nothing more to do
			return;
		}
		// Replace product image (spotlight/details) if existing
		var ab = $('auctionBox'+aid);
		if (ab) {
			var bgimgStyle = ab.getStyle('background-image');
			if (bgimgStyle.indexOf('_sold') < 0) { // No sold stamp yet
				ab.setStyle({
					backgroundImage:bgimgStyle.replace(/\.png/, '_sold.png')
				});
			}
		}
		// Replace product image (box) if existing
		var aimg = $('auctionImage'+aid);
		if (aimg) {
			var aimgSrc = aimg.src;
			if (aimgSrc.indexOf('_sold') < 0) { // No sold stamp yet
				aimg.src = aimgSrc.replace(/\.gif/, '_sold.gif');
			}
		}
		// Hide phone info at the bottom (spotlight/box)
		var phoneInfo = $('phoneInfo'+aid);
		if (phoneInfo && phoneInfo.visible()) {
			phoneInfo.hide();
		}
	}
};
