var _lock_ct_keys = Object();
var GDS_DTL = null;
var _requested_aids = new Array();
var _auction_detail_last_update = 0;
var _index_auctions_js_last_update = 0;
var _counter_server_prefix = context;

var _intv = '';
var _intv_index = '';
var _index_counter_prices = new Object();
var _bid_history = new Array();

var _auction_status_finished = 3;
var _update_interval = 1000;
var _ct_counter_time = 0;
var _ct_counter_price = 0;
var _ct_counter_status = 0;
var _ct_counter_status_changed = 0;
var _ct_counter_winner_name = '';
var _counter_changed = 0;
var _last_bid_key = -1;

var _cached_user_id = 0;

var _request_counter_aids = true;

var nb_boxes = 3;
var boxes = new Array(new Array('live_auctions',1), new Array('future_auctions',2), new Array('ended_auctions',3), new Array('newer_auctions',4));
var ar_aids = '';
var ar_uid = '';
var ar_val = '';

/**
 * 商品详细计数
 * @param {} auction_id
 */
function auction_detail_js(auction_id,user_id) {
	if (user_id == undefined || user_id == null) {
    user_id = 0;
  } else {
    if (user_id != 0) {
      _cached_user_id = user_id;
    }
  }

  if (_cached_user_id != 0) {
    user_id = _cached_user_id;
  }

	if (_lock_ct_keys['detail'] == undefined || _lock_ct_keys['detail'] == null) {
    _lock_ct_keys['detail'] = 0;
  }
  
  _do_real_counter_request = 1;
  
  if (_lock_ct_keys['detail'] == 0) {
    //if (_do_real_counter_request == 1) {
      _auction_detail_last_update = (new Date()).getTime();
      //_lock_ct_keys['detail'] = 1;
      do_counter_request(auction_id, user_id,'detail');
    //}
  } else {
    //if (((new Date()).getTime()-_auction_detail_last_update)>__ct_update_period) {
      // _lock_ct_keys['detail'] = 0;
    //}
  }
  
  
  if (_intv != '' || _intv != null) {
    window.clearInterval(_intv);
  }
  _intv = setInterval('auction_detail_js(' + auction_id +','+ user_id+')', _update_interval);

}

function do_counter_request(auction_id,user_id,lock_key) {
  url = _counter_server_prefix + '/auction/details/' + auction_id + '.shtml?plain=1';
  
  if (lock_key == undefined || lock_key == null || lock_key == 0) {
    lock_key = 0;
  }

  if (_last_bid_key > -1) {
    url += '&lbp=' + _last_bid_key;
  }
  if (user_id != undefined && user_id != null && user_id != 0) {
    url += '&uid=' + user_id;
  }

  if (lock_key != 0) {
    if (_lock_ct_keys[lock_key] == undefined || _lock_ct_keys[lock_key] == null || _lock_ct_keys[lock_key] == 0) {
      _lock_ct_keys[lock_key] = 1;
    }
    $.getJSON(url, {t:Math.random()},function(data) {
			_ev_detail(data);
			_lock_ct_keys[lock_key] = 0;
			});
  }
}
function _ev_detail(transport) {
  auction_status = transport.cs;
  parse_counter_response(transport);
  if (auction_status == _auction_status_finished) {
    if (_intv != '' || _intv != null) {
      window.clearInterval(_intv);
    }
    return;
  }
}

function parse_counter_response(transport) {
  div_counter_name = 'countertime';

  if(transport==''){
  	return;
  }

  has_price_update = 0;
  tmp_counter = 0;

  var ct = transport.ct;
  var el = $('#'+div_counter_name);

  if(el) {
  	_ct_counter_time = ct;
      _ct_counter_time_plain = ct;
      _ct_counter_last_life_update = (new Date()).getTime();

      
    if (transport.cs == 3) {
      _ct_counter_time = '竞拍结束';
	  	if(transport['cw']) {
	  		$('#bb').html(a1);
	  	} else {
	  		$('#bb').html(a2);
	  	}
    } else {
      _ct_counter_time = calc_counter_from_time(_ct_counter_time);
    }
  	if (el && _ct_counter_time != '') {
	    el.text(_ct_counter_time);
	    if (parseInt(ct) <= 10 && parseInt(ct) > 0) {
	      el.css('color','#ff0000');
	    } else {
	    	el.css('color','');
	    }
  	} 
  }
  	_ct_counter_winner_name = transport.cw;
  el = $('#a_current_winner');
  if (_ct_counter_winner_name) {
      if (el) {
        el.text(_ct_counter_winner_name);
      }
    }
  _ct_counter_price = transport.cp;
  el = $('#a_current_price');
  if (_ct_counter_price) {
      if (el) {
        el.html(format_raw_to_price(_ct_counter_price+''));
      }
      if ($('#a_current_price2')) {
        $('#a_current_price2').html(format_raw_to_price(_ct_counter_price+''));
      }
      if (_ct_counter_price != _counter_changed) {
          if (el) {
          	el.effect("highlight", {'color': '#ff0000'}, 1500);
          }
      }
      if (_last_bid_key != -1 && !transport.pb) {
	      	var market = $('#market').attr('mp');
	      	var cha = parseFloat(market)-_ct_counter_price;
	      	if(cha > 0)
	       		$('#user_savings').html(format_raw_to_price(cha+''));
      	}
      _counter_changed = _ct_counter_price;

  }
    
  pb = transport.pb;
  el = $('#place_bids');
  if (pb) {
  	if (el) {
        el.html(format_raw_to_price(pb+''));
        $('#lbids').html(pb);
        if (_last_bid_key != -1) {
	      	var market = $('#market').attr('mp');
	      	var cha = parseFloat(market)-_ct_counter_price-parseFloat(pb);
	      	if(cha > 0)
	       		$('#user_savings').html(format_raw_to_price(cha+''));
      	}
      }
  }
  
  var cs = transport.cs;
  if (cs != _ct_counter_status) {
    _ct_counter_status_changed = 1;
  }
  _ct_counter_status = cs;

  /* display puased if needed
  if (_ct_counter_status == _auction_status_paused) {
    _cur_time = new Date();
    _cur_secs = _cur_time.getTime();
    if (_cur_time%5 <= 2) {
      $(div_counter_name).innerHTML = 'Pause';
    }
  }
   */ 
  var bh = transport.bh;
  if (bh) {
      parse_bid_history(bh, transport.aid);
  }
}

function parse_bid_history(bh, auction_id) {

  history_out = "";
  own_history_out = "";
  tmp_bh = new Array();
  tmp_own_bh = new Array();
  y = 0;
  z = 0;
  tmp_min_bid_key = 9999999;
  div_stats_all = 'bids_stats';
  div_stats_own = 'my_placed_bids';
  if (!document.getElementById(div_stats_all)) {
    return;
  }
  var _tmp_array = [];
  for (x = 0; x < bh.length; x++) {
      single_entry = bh[x];

      if (single_entry.bp > _last_bid_key) {
        _last_bid_key = single_entry.bp;
      }

      var bidder = new Object();
      bidder["bidder_name"] = single_entry.bw;
      //bidder["bid_time"] = (new Date()).getTime() + _ms_diff;
      bidder["is_bidder"] = 0;

      tmp_bh[y] = new Object();
      tmp_bh[y]["bid_key"] = single_entry.bp;
      tmp_bh[y]["user"] = single_entry.bw;
      tmp_bh[y]["type"] = single_entry.bt;
      tmp_bh[y]["price"] = format_raw_to_price(single_entry.bp+'');
      tmp_bh[y]["your_bid"] = 0;
      
      _tmp_array.push(bidder);


      y++;

      if (tmp_min_bid_key >= single_entry.bp) {
        tmp_min_bid_key = single_entry.bp;
      }

  }

  if (tmp_bh != null) {
    if (_bid_history != null && _bid_history.length > 0) {
      for (x = 0; x < _bid_history.length; x++) {
        if (y >= 10) continue;

        if (_bid_history[x]["bid_key"] < tmp_min_bid_key) {
          tmp_bh[y] = _bid_history[x];
          y++;
        }
      }
      _bid_history = tmp_bh;
    } else {
      _bid_history = tmp_bh;
    }
  }
  
  if (_bid_history != null) {
    for (x = 0; x < _bid_history.length; x++) {
      if (x >= 8) break;
      history_out += "<div class=\"beat86\">";
      history_out += "<div class=\"beat87\">" + _bid_history[x]["price"] + "</div>";
      history_out += "<div class=\"beat88\">" + _bid_history[x]["user"] + "</div>";
      history_out += "<div class=\"beat89\">" + '普通出价' + "</div>";
      history_out += "</div>";
    }
  }
  if (history_out != "") {
    $('#'+div_stats_all).html(history_out);
  }


  return;
}

/**
 * 商品列表计数
 * @param {} auction_id
 */
function auction_index_js(auction_ids) {
	if (auction_ids == '' || auction_ids == null) {
    return;
  }
  
  if(_requested_aids == '' || _requested_aids == null){
    _requested_aids = auction_ids.split(',');
  }
  
  if(_request_counter_aids == false){
   window.clearTimeout(_intv_index);
   return;    
  }
  
  if (_lock_ct_keys['index'] == undefined || _lock_ct_keys['index'] == null) {
    _lock_ct_keys['index'] = 0;
  }

  if (_lock_ct_keys['index'] == 0) {
    do_counter_request_index(auction_ids,'index');
    _index_auctions_js_last_update =  (new Date()).getTime();
  } else {
    if (((new Date()).getTime()-_index_auctions_js_last_update)>3000) {	//延迟三秒
       //_lock_ct_keys['index'] = 0;
    }
  }

  update_interval_index = 1000;

  if (_intv_index != '') {
    window.clearTimeout(_intv_index);
  }

  _intv_index = setTimeout('auction_index_js("' + auction_ids + '")', update_interval_index);
}

function do_counter_request_index(auction_ids, lock_key) {
	if (auction_ids == '' || auction_ids == null) {
		return;
	}
	url = _counter_server_prefix + '/auction/goodsStatus.shtml?t='
			+ Math.random() + '&aids=' + auction_ids;

	if (lock_key == undefined || lock_key == null || lock_key == 0) {
		lock_key = 0;
	}
	if (lock_key != 0) {
		if (_lock_ct_keys[lock_key] == undefined
				|| _lock_ct_keys[lock_key] == null
				|| _lock_ct_keys[lock_key] == 0) {
			_lock_ct_keys[lock_key] = 1;
		}

		$.getJSON(url, function(data) {
			_lock_ct_keys[lock_key] = 0;
			parse_counter_response_index(data);
			});
	}

}

function parse_counter_response_index(response){
	for (i = 0; i <= response.length; i++) {
	    if (response[i] == null) continue;
	    counter_data = response[i];
	    auction_id = counter_data['aid'];
	    div_name_counter = 'counter_index_page_' + auction_id;
	    div_price_name = 'price_index_page_' + auction_id;
	    div_name_winner = 'winner_index_page_' + auction_id;
	    div_button_name = 'button_index_page_' + auction_id;
	    div_button_name_finished = 'button_finished_index_page_' + auction_id;
	    div_button_bid = 'bb_' + auction_id;
	    var ct = counter_data['ct'];
		var el = $('#'+div_name_counter);
		if (el) {
		  if(counter_data['cs'] == 3) {
		  	_ct_time = '竞拍结束';
	          if(counter_data['cw']) {
		  		$('#'+div_button_bid).html(a1);
			  } else {
			  	$('#'+div_button_bid).html(a2);
			  }
		  } else {
		  	_ct_time = calc_counter_from_time(ct);
		  }
          el.text(_ct_time);
          if (parseInt(ct) <= 10 && parseInt(ct) > 0) {
            el.css('color','#ff0000');
          } else {
            el.css('color','');
          }
        }
        el = $('#'+div_name_winner);
        if (el) {
        	el.text(counter_data['cw']);
        }
        el = $('#'+div_price_name);
        if (el) {
        	el.html(format_raw_to_price(counter_data['cp']+''));
        }
        if (_index_counter_prices[auction_id] == null
            || _index_counter_prices[auction_id] == '') {
          _index_counter_prices[auction_id] = counter_data['cp'];
        } else if (_index_counter_prices[auction_id] != counter_data['cp']) {
        	 el.effect("highlight", {'color': '#ff0000'}, 1500);
        	_index_counter_prices[auction_id] = counter_data['cp'];
        }
        
        cs = counter_data['cs'];
        if (cs == _auction_status_finished) {
        	_requested_aids = removeAuctionFromList(auction_id, _requested_aids);
	          if(_requested_aids.length == 0) {
	            _request_counter_aids = false;
	          }
        }
	}
}
function bids(auction_id,el) {
	$.login({
				complete : function(result) {
					if (result != null && result.IsAuthenticated != null
							&& result.IsAuthenticated) {
						$.getJSON(_counter_server_prefix+'/auction/bids.shtml', {
									t : Math.random(),
									aid : auction_id
								},function(data){
									var nextEl = el.nextSibling;
									if(nextEl.style.width == '')
										nextEl.style.width="130px";
									nextEl.style.fontSize="13px";
									nextEl.style.display="none";
									var tt = '';
									var success = false;
									if(!data.h && data.p == 0){
										nextEl.innerHTML = '\u60a8\u7684\u6b22\u4e50\u8c46\u5df2\u4e0d\u8db3!';
										tt ='';
									} else if(data.lb){
										nextEl.innerHTML = '\u60a8\u4e0d\u5fc5\u8fde\u7eed\u51fa\u4ef7!';
										tt = '\u60a8\u4e0a\u6b21\u7684\u51fa\u4ef7\u4f9d\u7136\u9886\u5148\uff0c\u8bf7\u4e0d\u8981\u8fde\u7eed\u51fa\u4ef7';
									} else if(data.h){
										nextEl.innerHTML = '\u51fa\u4ef7\u6210\u529f!';
										tt = '\u672c\u6b21\u51fa\u4ef7\u5171\u82b1\u8d391\u4e2a\u6b22\u4e50\u8c46\uff0c\u4ef7\u683c\u589e\u52a00.15\u5143';
										success = true;
									} else {
										nextEl.innerHTML = '\u7ade\u62cd\u5df2\u7ed3\u675f!';
										if(data.tip) {
											nextEl.innerHTML = data.tip;
										}
										tt = '';
									}
									if(nextEl.innerHTML != '') {
										//$(nextEl).effect("highlight", {'color': '#ff0000','mode':'hide'}, 1000);
										showAuctionTip(nextEl.innerHTML,tt,success,el);
									}
								});
					}
				}
			});
}

function hidedisplay_boxes(div_box_id,url){
  for (box in boxes){
    var el = $('#'+boxes[box][0]);
    if (el) {
			if (boxes[box][0] == div_box_id) {
				if(el.html() == '') {
					get_browse_page(div_box_id, url);
				}
				el.css('display','block');
			} else {
				el.css('display','none');
				el.html("");
			}
		}
	}

  if($('#live_auctions')){
    if($('#live_auctions').css('display') == "none" && $('#newer_auctions').css('display') == "none"){
      window.clearTimeout(_intv_index);
    } else {
      if(ar_aids != '')
      	auction_index_js(ar_aids);
    }
  }
}

/**utils**/
function calc_counter_from_time(time_length){
	var hour = time_length/3600|0;
	var min = (time_length%3600)/60|0;
	var sec = (time_length%3600)%60;
	if(hour<10){
		hour = "0"+hour;
	}
	if(min<10){
		min = "0"+min;
	}
	if(sec<10){
		sec = "0"+sec;
	}
	return hour+":"+min+":"+sec;
}

function highlight(id,content) {
	$('span').hide();
	$('span').text(content);
	$('span').fadeIn("slow"); 
}
function get_browse_page(div_name, url) {
	var el = $("#"+div_name);
	var html = '<div style="text-align:center;border:#ccc solid 1px;width: 100px;margin: auto;height:20px;">' +
			'<img src="'+_counter_server_prefix+'/images/ck.gif"/>正在加载...</div>';
	el.html(html);
	if(div_name == 'newer_auctions') {
		$('#last').text('新手竞拍区商品');
	} else {
		$('#last').text('竞拍商品');
	}
	el.load(url,{t:Math.random()}); 
}

function format_raw_to_price(price){
	currency = "￥";
	if(/[^0-9\.]/.test(price)) return "invalid value";
	price=price.replace(/^(\d*)$/,"$1.");
	price=(price+"00").replace(/(\d*\.\d\d)\d*/,"$1");
	price=price.replace(".",",");
	var re=/(\d)(\d{3},)/;
	while(re.test(price))
	        price=price.replace(re,"$1,$2");
	price=price.replace(/,(\d\d)$/,".$1");
	return currency+price.replace(/^\./,"0.");
}

function timeDiff(time) {
	var date = new Date().g;
}
function mycarousel_initCallback(carousel) {
	$("#mycarousel li").mouseover(function() {
				$("#MainImage img")[0].src = this.getElementsByTagName("img")[0].name;
				$(this).siblings().each(function() {
							this.getElementsByTagName("img")[0].className = "";
						})
				this.getElementsByTagName("img")[0].className = "curr";

			})
};

function removeAuctionFromList(aid, list) {
  var _tmpArray = [];

  for (var i=0; i<list.length; i++) {
  
    if( list[i] == aid){
      continue;
    }

    _tmpArray.push(list[i]);
  }
  return _tmpArray;
}
var a1 = '<input type="button" class="beat174" name="button" id="button" value="已售出" />';
var a2 = '<input type="button" class="beat174" name="button" id="button" value="未售出" />';

function g(nodeId)
{
   return document.getElementById(nodeId);
}
function getPos(obj){
	this.Left=0;
	this.Top=0;
	this.Height=obj.offsetHeight;
	this.Width=obj.offsetWidth;
	var tempObj=obj;
	while (tempObj.tagName.toLowerCase()!="body" && tempObj.tagName.toLowerCase()!="html"){
		this.Left+=tempObj.offsetLeft;
		this.Top+=tempObj.offsetTop;
		tempObj=tempObj.offsetParent;
	}
}
function showCate() {
	var objPos=new getPos(g('oo'));
	var styleStr ="left:"+(objPos.Left-1)+"px;"+"top:"+(objPos.Top)+"px;position:absolute;";
	g('cate').style.cssText=styleStr;
	g('cate').style.display='block';
	}
function hideOption() {
	g('cate').style.display='none';
}

function showAuctionTip(t,tx,s,btn) {
	var but = 'k_54.gif';
	if(s) but = 'k_52.gif';
	var seconds =2;
	if(t.indexOf('\u4e0d\u8db3')!=-1){
		seconds =5;
		tx = '<a target="_blank" href="'+_counter_server_prefix+'/manage/person/buy_bid_beans">>> 立即充值欢乐豆 <<</a>';
	}
	var html = '<div class="beat200"><div class="beat201"><div class="beat202">操作提示</div><div class="beat203 Tip_Close">' +
			'<img src="'+_counter_server_prefix+'/images/auction/k_51.gif"/></div></div><div class="beat204"><div class="beat205">' +
			'<img src="'+_counter_server_prefix+'/images/auction/'+but+'" width="25" height="25" /></div><div class="beat206">'+t+'</div></div>' +
			'<div class="beat207">'+tx+'</div><div class="beat208"><div class="beat209 Tip_Close">' +
			'<input type="button" class="beat210" name="button" id="button" value="知道了"/></div>' +
			'<div class="beat211"><span id="timer_5">'+seconds+'</span>秒后自动关闭</div> </div></div>';
	$('#poptip').html(html);
	var objPos=new getPos(btn);
	var selfY=objPos.Top+objPos.Height;
	var bodyW=document.documentElement.clientWidth+document.documentElement.scrollLeft;
	var bodyH=document.documentElement.clientHeight+document.documentElement.scrollTop;
	if(bodyH-selfY<169){
		selfY = objPos.Top-169;
	}
	showTip2('#poptip');
	$("#c02tip").css({top:parseInt(selfY)+"px",left:parseInt(objPos.Left-(294-objPos.Width)/2) +"px"});
}

function showAuctionFTip(id,btn) {
	var but = 'k_54.gif';
	var tx = $('#futureTime'+id).html();
	var html = '<div class="beat200"><div class="beat201"><div class="beat202">操作提示</div><div class="beat203 Tip_Close">' +
			'<img src="'+_counter_server_prefix+'/images/auction/k_51.gif"/></div></div><div class="beat204"><div class="beat205">' +
			'<img src="'+_counter_server_prefix+'/images/auction/'+but+'" width="25" height="25" /></div><div class="beat206">'+'离开始竞拍还有'+'</div></div>' +
			'<div class="beat207">'+tx+'</div><div class="beat208"><div class="beat209 Tip_Close">' +
			'<input type="button" class="beat210" name="button" id="button" value="知道了"/></div>' +
			'<div class="beat211"><span id="timer_5">2</span>秒后自动关闭</div> </div></div>';
	$('#poptip').html(html);
	var objPos=new getPos(btn);
	showTip2('#poptip');
	$("#c02tip").css({top:parseInt(objPos.Top+objPos.Height)+"px",left:parseInt(objPos.Left-(294-objPos.Width)/2) +"px"});
}

function refreshIndexFuture(s) {
	if(s != null && s != undefined && s != '') {
	var a = s.split(',');
	var tmp = '';
	for(var i = 0;i<a.length-1;i++){
		var b =a[i];
		var c = b.split('/');
		var el = $('#futureTime'+c[0]);
		var diff = c[1]-1;
		if(diff <=0) {
			window.location.reload();
		}
		el.html(calc_counter_from_time(diff));
		tmp += c[0]+'/'+diff+',';
	}
	s = tmp;
	setTimeout('refreshIndexFuture("' + s + '")', 1000);
	}
}