var _current_winner = new Object();
var _current_price = new Object();
var _end = new Object();
var _timer = new Object();
var _refresh_interval;
var _autobid_timeout;
var _now = 0;
var stopTimer = 0;
var stopFlag = true;

function do_count_bid (exhibitId) {
    $.getJSON('/exhibit/count_bid', {
	    exhibit_id : exhibitId,
	    t          : (new Date()).getTime()
    }, function(data) {
	    if (data) {
		$('#bid_count').text(data.bid_count);
		$('#bid_price').text(data.bid_price);
		$('#discount_rate').text(data.discount_rate);
	    };
    });
}

function do_bid (exhibitId) {
    stopTimer = 0;
    $.getJSON('/exhibit/bid', {
	    exhibit_id : exhibitId,
	    t          : (new Date()).getTime()
    }, function(data) {
	    if (data.status == 1) {
		$('#nickname').text(data.nickname);
		$('#member_point').text(data.member_point);
		$('#can_bid').text(data.can_bid);
		$('#bid_count').text(data.bid_count);
		$('#bid_price').text(data.bid_price);
		$('#discount_rate').text(data.discount_rate);
	    }
	    else {
		popup(data.status);
		$('#bid_btn_'+exhibitId).removeAttr('disabled');
	    }
	    $('#bid_btn_'+exhibitId).removeClass('loading');
	    setTimeout(function () { $('#notify_'+exhibitId).html('&nbsp;') }, 2000);
	});
}
    
function do_refresh (exhibitIds) {
    stopTimer++;
    if (stopTimer > 600) {
	if (stopFlag) {
	    stopFlag = false;
	    popup('１０分間操作がなかったので更新を停止しました。');
	}
	else {
	    if (document.getElementById('dialog-box').style.display == 'none') {
		stopFlag = true;
		stopTimer = 0;
	    }
	}
    }
    else {
	$.getJSON('/json/list.js', {
		aid : exhibitIds,
		t   : (new Date()).getTime()
        }, function(data) {
		while (exhibit = data.exhibits.shift()) {
		    if (_now <= data.now) {
			$('#current_winner_'+exhibit.id).html(exhibit.current_winner ? exhibit.current_winner : '---');
			$('#current_price_'+exhibit.id).html(number_to_price(exhibit.current_price || 0));
			$('#current_price_'+exhibit.id+'_2').html(number_to_price(exhibit.current_price || 0));
			
			// 残り時間を算出
			var _time = exhibit.end - data.now;
			if (exhibit.status == 1) {
			    if (_time > 10) {
				_timer[exhibit.id] = time_to_hms(_time);
				$('#timer_'+exhibit.id).css('color','#333');
			    }
			    else if (_time > 0) {
				_timer[exhibit.id] = time_to_hms(_time);
				$('#timer_'+exhibit.id).css('color','#c00');
			    }
			    else {
				_timer[exhibit.id] = '00:00:00';
			    }
			}
			else {
			    _timer[exhibit.id] = '落札済み';
			    $('#bid_btn_'+exhibit.id).attr('disabled', 'disabled');
			    $('#bid_btn_'+exhibit.id).addClass('end');
			    //clearInterval(_refresh_interval);
			}
			
			$('#timer_'+exhibit.id).html(_timer[exhibit.id]);
			if (_current_price[exhibit.id] != exhibit.current_price) {
			    if (_current_price[exhibit.id]) {
				// 入札通知
				var price = exhibit.current_price - _current_price[exhibit.id];
				var count = price / exhibit.bid_unit;
				$('#notify_'+exhibit.id).html(count + '入札+￥' + price);
				var hoge = exhibit.id;
				setTimeout(function () { $('#notify_'+hoge).html('&nbsp;') }, 2000);
				$('#current_price_'+exhibit.id).effect("highlight", { color : "#0099ff" }, 1500);
			    }
			    _current_price[exhibit.id] = exhibit.current_price;
			}
			if (_current_winner[exhibit.id] != exhibit.current_winner) {
			    if (_current_winner[exhibit.id]) {
				$('#current_winner_'+exhibit.id).effect("highlight", { color : "#0099ff" }, 1500);
			    }
			    _current_winner[exhibit.id] = exhibit.current_winner || '--';
			}
			if (_end[exhibit.id] != exhibit.end) {
			    if (_end[exhibit.id]) {
				$('#timer_'+exhibit.id).css('color','#036');
				$('#timer_'+exhibit.id).effect("highlight", { color : "#0099ff" }, 1500);
			    }
			    _end[exhibit.id] = exhibit.end;
			}
			
			// recent bids
			if (exhibit.recent_bids) {
			    $('#recent_bids_'+exhibit.id).text('');
			    var table = $('<table cellspacing="5">');
			    $(exhibit.recent_bids).each(function () {
				    var tr =$('<tr>');
				    tr.append($('<td class="price">').text('￥'+this.price));
				    tr.append($('<td class="bidder">').text(this.bidder));
				    tr.append($('<td class="type">').text(this.type == 'manual' ? '手動' : '自動'));
				    table.append(tr);
				});
			    $('#recent_bids_'+exhibit.id).append(table);
			}
			_now = data.now;
		    }
		}
	    });
    }
}

function load_exhibit () {
    var auctionIds = new Array();
    $('.auction_item').each(function(){
	    if (id = $(this).attr('id')) {
		if (id.match(/^auction_(\d+)$/)) {
		    auctionIds.push(RegExp.$1);
		}
	    }
	});
    if (auctionIds.length) {
	_refresh_interval = setInterval("do_refresh('" + auctionIds.join(',') + "')", 1000);
    }
}

function update_autobid (key, aucId) {
    $.getJSON('/json/autobid', {
            key : key,
	    t   : (new Date()).getTime()
    }, function(data) {
	    if (data) {
		if ($('#autobid_point').text() != data.point) {
		    $('#autobid_min').text(data.min);
		    $('#autobid_max').text(data.max);
		    $('#autobid_point').text(data.point);
		    do_count_bid(aucId);
		}
		_autobid_timeout = setTimeout("update_autobid('" + key + "','" + aucId + "')", 1000);
	    }
    });
}

function number_to_price (number) {
    price = new String(number);
    price = price.split(".")[0];
    while(price.match(/(\d+)(\d{3})/)){
	price = price.replace(/^(\d+)(\d{3})/, '$1,$2');
    }
    return price;
}

function time_to_hms(time) {
    if (time > 0) {
	hours=Math.floor(time / 3600);
	minutes=Math.floor((time / 3600 - hours) * 60);
	seconds=Math.round((((time / 3600 - hours) * 60) - minutes) * 60);
    } else {
	hours = 0;
	minutes = 0;
	seconds = 0;
    }

    if (seconds == 60) {
	seconds = 0;
    }

    if (minutes < 10) {
	if (minutes < 0) {
	    minutes = 0;
	}
	minutes = '0' + minutes;
    }
    if (seconds < 10) {
	if (seconds < 0) {
	    seconds = 0;
	}
	seconds = '0' + seconds;
    }
    if (hours < 10) {
	if (hours < 0) {
	    hours = 0;
	}
	hours = '0' + hours;
    }

    return hours + ":" + minutes + ":" + seconds;
}

$(document).ready(function(){
	load_exhibit();
    });


$.fn.disableOnSubmit = function(disableList) {
    if (disableList == null) {
	var $list = 'input[type=submit],input[type=button],input[type=reset],button';
    }
    else {
	var $list = disableList;
    }
    $(this).find($list).removeAttr('disabled');
    $(this).submit(function() {
	    $(this).find($list).attr('disabled','disabled');
	});
    return this;
};
