/* グローバル変数 */
var _bid_running = 0;

/* ヘルプ */
function show_help(div_id) {
  jQuery("div[id^='help_index_']:display").hide();
  jQuery('#' + div_id).show();
}

function toggle_help_header(div_id) {
  jQuery("div[id^='help_header_']:display").hide();
  jQuery('#' + div_id).show();
}

/* オークション */
function add_to_watchlist(auction_id) {
  new Ajax.Request('/auction/add_to_watchlist/' + auction_id, {parameters:{authenticity_token:_authenticity_token}});
  $('wlComp').show();
}

/* コイン数の更新 */
_running_bid_account_total_bids = null;
function update_bid_account_total_bids() {
  if (_running_bid_account_total_bids != ''
      && _running_bid_account_total_bids != null) {
    window.clearTimeout(_running_bid_account_total_bids);
  }
  url = '/point/show'
  new Ajax.Request(url, {
    method: "get",
    onSuccess:function(httpObj){
      if ($('bid_account_total_bids').innerHTML != httpObj.responseText) {
        $('bid_account_total_bids').innerHTML = httpObj.responseText;
        $('bid_account_total_bids').style.backgroundColor='#FFFFFF';
        new Effect.Highlight('bid_account_total_bids', {duration:1,startcolor:'#ff0000',endcolor:'#ffffff',restorecolor:'#FFFFFF'});
      }
    },
    onFailure:function(httpObj){ }
  });
  _running_bid_account_total_bids = window.setTimeout('update_bid_account_total_bids()', 10000);
}
/* 参加可能オークション数の更新 */
function update_possible_entry_count() {
  url = '/auction_limit/show'
  new Ajax.Request(url, {
    method: "get",
    onSuccess:function(httpObj){
      if ($('possible_entry_count').innerHTML != httpObj.responseText) {
        $('possible_entry_count').innerHTML = httpObj.responseText;
        $('possible_entry_count').style.backgroundColor='#FFFFFF';
        new Effect.Highlight('possible_entry_count', {duration:1,startcolor:'#ff0000',endcolor:'#ffffff',restorecolor:'#FFFFFF'});
      }
    },
    onFailure:function(httpObj){ }
  });
}

function format_raw_to_price(price) {
  currency = '<span style="font-family:Monospace;">￥</span>';
  price = new String(price);
  price = price.split(".")[0];
  while(price.match(/(\d+)(\d{3})/)){
    price = price.replace(/^(\d+)(\d{3})/, '$1,$2');
  } 
  return currency + price;
}

function calc_counter_from_time(diff) {
  if (diff > 0) {
    hours=Math.floor(diff / 3600)

    minutes=Math.floor((diff / 3600 - hours) * 60)

    seconds=Math.round((((diff / 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;
}

function place_bid(auction_id, error_div, user_id, do_request, is_detail_page) {
  if (_bid_running == 1 && ((new Date()).getTime()-_last_bid_placed)<600) {
    return;
  }

  _last_bid_placed = (new Date()).getTime();

  _bid_running = 1;
  if (user_id == undefined || user_id == null || user_id == '') {
    user_id = 0;
  }

  if (do_request == undefined || do_request == null || do_request == '') {
    do_request = 0;
  }

  if (is_detail_page == undefined || is_detail_page == null || is_detail_page == '') {
    is_detail_page = 0;
  }


  // clean error div
  el = $(error_div);
  el2 = $("error_dialog_" + auction_id);
  if (el2) {
    el2.style.display = "none";
  }
  if (el) {
    el.innerHTML = "";
  }

  url = '/bid/bid?aid=' + auction_id + '&_authenticity_token=' + encodeURIComponent(_authenticity_token);
  refreshDetails(url, 'place_bid_' + auction_id);

  window.setTimeout("update_bid_account_total_bids()", 500);
  window.setTimeout("update_possible_entry_count()", 500);
  window.setTimeout("update_savings_details(" + auction_id + ",1)", 500);

  if (is_detail_page == 1) {
    _ct_force_update = 1;
  }
}

function _eval_place_bid(auction_id, user_id, response) {
  error_div = 'bid_error_div_' + auction_id;
  _bid_running = 0;
  do_request = 1;

  if (response == "OK" || response == "") {
    if (do_request == 1) {
      if (_single_auction_verify != "" && _single_auction_verify_id == auction_id) {
        do_counter_request(auction_id, user_id, 'detail2', _single_auction_verify);
      }
    }
  } else {
    el = $(error_div);
    if (el) {
      el.innerHTML = response;
    } else {
      error_div = 'error_dialog_message';
      el = $(error_div);
      if (el) {
        el.innerHTML = response;
      }
    }
    $("error_dialog_" + auction_id).show();
    window.setTimeout("$('error_dialog_" + auction_id + "').hide()", 3000);
  }
}



function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}


var _bid_agent_running = 0;

function validade_bid_agent_input(price1, price2, num_bids) {
  if (!check_price_field(price1)) {
    price1 = 0;
  }
  if (!check_price_field(price2)) {
    return false;
  }

  if (!num_bids.match(/^[0-9]+$/)) {
    num_bids = 0;
  }

  return true;
}

function check_price_field(price) {
  if (price.match(/^[0-9]+[,.]?[0-9]*$/)) {
    return true;
  } else {
    return false;
  }
}

function update_bid_agent(auction_id) {
  if (auction_id == null || auction_id == undefined) {
    return;
  }

  if (_running_bid_agent_single == 0) {
    _running_bid_agent_single = auction_id;
  }

  if (_running_bid_agents[auction_id] != ''
      && _running_bid_agents[auction_id] != null) {
    window.clearTimeout(_running_bid_agents[auction_id]);
  }

  if (_running_bid_agent_single != auction_id) {
    return;
  }

  url = '/auto_bidder/list?aid=' + auction_id;
  new Ajax.Updater("bid_agent_ov", url);
  _bid_agent_running = 0;
  _running_bid_agents[auction_id] = window.setTimeout('update_bid_agent(' + auction_id + ')', 10000);
}


function _eval_placed_bid_agents(response) {
  div_name = 'bid_agent_ov';
  if ($(div_name)) {
    $(div_name).innerHTML = response;
  }
}

function _eval_bid_agent(response) {
  bid_agent_div = 'bid_agent_ov';
  if ($(bid_agent_div)) {
    $(bid_agent_div).innerHTML = response;
  }
}


function place_bid_agent_form(form) {
  submit = 1;
  user_id = 0;
  ed = "error_dialog_message";

  if (_bid_agent_running == 1) {
    return;
  } else {
    _bid_agent_running = 1;
  }

  if (form.aid == '') {
    alert('オークションIDが見つかりません。このページを再読み込みしてください。再読み込みしても直らない場合は運営者までお問い合わせください。');
    submit = 0;
  }
/*
  if (form.error_div != '') {
    ed = form.error_div.value;
  } else {
    ed = 'error_dialog_message';
  }
  if (form.uid == '' || form.uid == undefined || form.uid == null) {
    user_id = 0;
  } else {
    user_id = form.uid.value;
  }
*/

  if (!validade_bid_agent_input(form.bid_from.value, form.bid_to.value, form.bids.value)) {
    submit = 0;
    _bid_agent_running = 0;
    el = $('auto_bidder_error_dialog_message');
    if (el) {
      el.innerHTML = "自動入札が設定できませんでした。入力内容をご確認ください。";
      $("auto_bidder_error_dialog").show();
      window.setTimeout("$('auto_bidder_error_dialog').hide()", 3000);
    }
  }
  if (submit == 1) {
    /*if (user_id == undefined || user_id == null) {
      user_id = 0;
    }*/

    place_bid_agent(form.aid.value, form.bid_from.value, form.bid_to.value, 2, form.bids.value, ed, user_id);
    form.bid_from.value="";
    form.bid_to.value="";
    form.bids.value="";
  }
}

var _ba_from = 0;
var _ba_to = 0;
var _ba_nbp = 0;

function place_bid_agent(auction_id, from, to, type, nbp, error_div, user_id) {
  if (user_id == undefined || user_id == null) {
    user_id = 0;
  }

  _ba_from = from;
  _ba_to = to;
  _ba_nbp = nbp;

  url = '/auto_bidder/create';
  new Ajax.Request(url, {
    parameters:{_method:'put', r:Math.floor(Math.random()*10000), bids:_ba_nbp, abt:type,
      bid_from:_ba_from, bid_to:_ba_to, aid:auction_id, authenticity_token:_authenticity_token},
    onSuccess:function(httpObj){
      //alert(httpObj.responseText);
      if (httpObj.responseText != 'OK') {
        el = $('auto_bidder_error_dialog_message');
        if (el) {
          el.innerHTML = httpObj.responseText;
          $("auto_bidder_error_dialog").show();
          window.setTimeout("$('auto_bidder_error_dialog').hide()", 3000);
        }
      } else {
        $('auto_bidder').hide();
        $('auto_bidder2').show();
      }
    },
    onFailure:function(httpObj){
      el = $('auto_bidder_error_dialog_message');
      if (el) {
        el.innerHTML = httpObj.responseText;
        $("auto_bidder_error_dialog").show();
        window.setTimeout("$('auto_bidder_error_dialog').hide()", 3000);
      }
    }
  });
  window.setTimeout("update_bid_account_total_bids()", 500);
  window.setTimeout("update_possible_entry_count()", 500);
  window.setTimeout("update_bid_agent(" + auction_id + ")", 500);
}


function delete_bid_agent(agent_id, auction_id) {
   url = '/auto_bidder/delete';
   new Ajax.Request(url, {
    parameters:{_method:'delete', r:Math.floor(Math.random()*10000),
      aid:auction_id, baid:agent_id, authenticity_token:_authenticity_token},
    onSuccess:function(httpObj){
      if (httpObj.responseText != 'OK') {
        el = $('auto_bidder_error_dialog_message');
        if (el) {
          el.innerHTML = httpObj.responseText;
          $("auto_bidder_error_dialog").show();
          window.setTimeout("$('auto_bidder_error_dialog').hide()", 3000);
        }
      }
    },
    onFailure:function(httpObj){
      el = $('auto_bidder_error_dialog_message');
      if (el) {
        el.innerHTML = httpObj.responseText;
        $("auto_bidder_error_dialog").show();
        window.setTimeout("$('auto_bidder_error_dialog').hide()", 3000);
      }
    }
  });
  window.setTimeout("update_bid_account_total_bids()", 500);
  window.setTimeout("update_possible_entry_count()", 500);
  window.setTimeout("update_bid_agent(" + auction_id + ")", 500);
}


var _running_timer = new Object();
var _running_browse = new Object();
var _running_bid_agents = new Object();
var _running_bid_agent_single = 0;
var _running_bid_account = 0;

var _ct_counter_time = 0;
var _ct_counter_diff = 0;
var _ct_counter_time_plain_before = 0;
var _ct_counter_time_plain = 0;
var _ct_counter_winner_id = 0;
var _ct_counter_winner_name = '';
var _ct_counter_price = 0;
var _ct_counter_status = 0;
var _ct_counter_status_changed = 0;
var _ct_counter_last_life_update = 0;
var _ct_counter_last_update_skipped = 0;
var _ct_force_update = 0;
var _ct_max_retries = 5;
var _ct_failed_requests_inc = 0;
var _ct_counter_latency_time = 1000;
var _ct_counter_force_update_time = 20;
var _ct_counter_force_update = 0;
var _ct_time_seconds = new Object();

var _ct_first_ct_slot = 120;
var _ct_second_ct_slot = 20;

var _update_interval = 1000;
var _start_time = 0
var _cached_user_id = 0;

var _intv = '';
var _intv_index = '';
var _intv_special = '';
var _lock_ct_keys = Object();
var js_cd_speed_tics = new Object();
var _bid_history = new Array();
var _own_bid_history = new Array();
var _index_counter_prices = new Object();
var _bid_out_types = new Array();
var _wording_single_bid = '入札';
var _wording_bid_agent = '自動入札';
var _wording_bid_phone = '';
var _last_update_ct_time = 0;
var _cds_image_deleted = 0;
_bid_out_types[1] = _wording_single_bid;
_bid_out_types[2] = _wording_bid_agent;
_bid_out_types[3] = _wording_bid_agent;
_bid_out_types[4] = _wording_bid_agent;
_bid_out_types[5] = _wording_bid_agent;
_bid_out_types[6] = _wording_bid_phone;

var _default_bid_increment = 10;

var _auction_status_halted = 90;
var _auction_status_future = 30;
var _auction_status_future_wo_startdate = 31;
var _auction_status_finished = 20;
var _auction_status_paused = 10;
var _auction_status_live = 1;
var _overwrite_timeout = 1000;
var _overwrite_timeout_index = 1000;
var _overwrite_timeout_special = 1000;

var _counter_server_prefix = '/telebid-us';

var _single_auction_verify = '';
var _single_auction_verify_id = 0;
var _multi_auction_verify = '';
var _multi_auction_verify_id = '';
var _special_auction_verify = '';
var _special_auction_verify_id = '';
var _last_bid_placed = 0;

var _last_bid_key = -1;

var _counter_changed = 0

var _detail_request_running = 0;

var _last_action_div_displayed = 0;
var _auction_detail_last_update = 0;
var _index_auctions_js_last_update = 0;
var _special_auctions_js_last_update = 0;

/**
 * void auction_detail_js(int, int, int)
 *   - init counter requests on detail pages
 */
function auction_detail_js(auction_id, auction_status, start_time, user_id, verify) {
  if (user_id == undefined || user_id == null) {
    user_id = 0;
  } else {
    if (user_id != 0) {
      _cached_user_id = user_id;
    }
  }

  if (verify == undefined || verify == null) {
    verify = '';
  }

  if (_cached_user_id != 0) {
    user_id = _cached_user_id;
  }

  if (auction_status == _auction_status_finished) {
    if (_intv != '' || _intv != null) {
      window.clearInterval(_intv);
    }
    return;
  }

  /*if (auction_status != _auction_status_live) {
    return;
  }*/

  if (start_time > 0) {
    _start_time = start_time;
  }

  if (_lock_ct_keys['detail'] == undefined || _lock_ct_keys['detail'] == null) {
    _lock_ct_keys['detail'] = 0;
  }

  _do_real_counter_request = 1;
  __ct_update_period = 4000;
  if (_ct_counter_time_plain != "") {
    if (__ct_update_period > _ct_first_ct_slot) {
      __ct_update_period = 6000;
    } else if (__ct_update_period > _ct_second_ct_slot) {
      __ct_update_period = 4000;
    } else {
      __ct_update_period = 3000;
    }

    if (parseInt(_ct_counter_time_plain) <= _ct_counter_force_update_time) {
      _do_real_counter_request = 1;
      _ct_counter_force_update = 1;
    } else {
      _ct_counter_force_update = 0;
      if (parseInt(_ct_counter_time_plain) > _ct_first_ct_slot
          && ((new Date()).getTime()-_auction_detail_last_update) < 5500) {
        _do_real_counter_request = 0;
      } else if (parseInt(_ct_counter_time_plain) > _ct_second_ct_slot
        && ((new Date()).getTime()-_auction_detail_last_update)<2500) {
        _do_real_counter_request = 0;
      }

      if (_ct_counter_time_plain > 1 && _ct_failed_requests_inc < _ct_max_retries) {
        if (_ct_counter_last_life_update == 0
            || ((new Date()).getTime()-_ct_counter_last_life_update) > 600) {
          _ct_counter_time_plain--;
          _ct_counter_time = calc_counter_from_time(_ct_counter_time_plain);
          _update_interval = 950;
          _overwrite_timeout = "";
          $('countertime').innerHTML = _ct_counter_time;// + "'";
        } else {
          $('countertime').innerHTML = $('countertime').innerHTML;// + ".";
        }
      }
    }
  }

  // force update if bid was placed
  if (_ct_force_update == 1) {
    _do_real_counter_request = 1;
    _ct_force_update = 0;
  }

  // 1. get counter data
  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', verify);
    }
  } else {
    if (((new Date()).getTime()-_auction_detail_last_update)>__ct_update_period) {
       _lock_ct_keys['detail'] = 0;
    }
  }

  // 2. process auction status
  get_interval_by_status(auction_id);
  // 3. check_status_code
  check_status_code();

  // update start_time
  _start_time -= (_update_interval/1000);

  _single_auction_verify = verify;
  _single_auction_verify_id = auction_id;


  if (_overwrite_timeout != "") {
    _update_interval -= parseInt(_overwrite_timeout);
    if (_update_interval <= 250) {
      _update_interval = 1000;
    } else {
      _update_interval += 30;
    }
  }

  if (_intv != '' || _intv != null) {
    window.clearInterval(_intv);
  }
  _intv = setInterval('auction_detail_js(' + auction_id + ', ' + _ct_counter_status + ', ' + _start_time + ', ' + user_id + ', "' + verify + '")', _update_interval);
}

/**
 * void auction_index_js(int, int, int)
 *   - init counter requests on index pages
 */
function auction_index_js(auction_ids, user_id, verify) {
  if (auction_ids == '' || auction_ids == null) {
    return;
  }

  if (user_id == undefined || user_id == null) {
    user_id = 0;
  }

  if (verify == undefined || verify == null) {
    verify = '';
  }


  if (_lock_ct_keys['index'] == undefined || _lock_ct_keys['index'] == null) {
    _lock_ct_keys['index'] = 0;
  }

  if (_lock_ct_keys['index'] == 0) {
    _multi_auction_verify = verify;
    _multi_auction_verify_id = auction_ids;
    do_counter_request_index(auction_ids, user_id, 'index', verify);
    _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 (parseInt(_overwrite_timeout_index) > 500) {
    update_interval_index = _overwrite_timeout_index;
  }
  if (_intv_index != '') {
    window.clearTimeout(_intv_index);
  }

  _intv_index = setTimeout('auction_index_js("' + auction_ids + '", "' + user_id + '", "' + verify + '")', update_interval_index);
}


/**
 * void auction_index_js(int, int, int)
 *   - init counter requests on index pages
 */
function auction_special_js(special_auction_ids, user_id, verify) {
  if (special_auction_ids == '' || special_auction_ids == null) {
    return;
  }

  if (user_id == undefined || user_id == null) {
    user_id = 0;
  }

  if (verify == undefined || verify == null) {
    verify = '';
  }


  if (_lock_ct_keys['special'] == undefined || _lock_ct_keys['special'] == null) {
    _lock_ct_keys['index2'] = 0;
  }

  if (_lock_ct_keys['special'] == 0) {
    _special_auction_verify = verify;
    _special_auction_verify_id = special_auction_ids;
    do_counter_request_index(special_auction_ids, user_id, 'special', verify);
    _special_auctions_js_last_update =  (new Date()).getTime();
  } else {
    if (((new Date()).getTime()-_special_auctions_js_last_update)>3000) {
       _lock_ct_keys['special'] = 0;
    }
  }


  update_interval_special_auctions = 1000;
  if (parseInt(_overwrite_timeout_special) > 500) {
    update_interval_special_auctions = _overwrite_timeout_special;
  }
  if (_intv_special != '') {
    window.clearTimeout(_intv_special);
  }

  _intv_special = setTimeout('auction_special_js("' + special_auction_ids + '", "' + user_id + '", "' + verify + '")', update_interval_special_auctions);
}


function parse_counter_response_index(transport, plain) {
  if (plain != undefined && plain != null && plain == 1) {
    counters = transport.split('#');
  } else {
    counters = transport.responseText.split('#');
  }
  for (i = 0; i <= counters.length; i++) {
    if (counters[i] == null) continue;
    counter_data = counters[i].split(':');
    auction_id = counter_data[0];
    div_name_counter = 'counter_index_page_' + auction_id;
    div_auction_name = 'auction_index_page_' + auction_id;
    div_price_name = 'price_index_page_' + auction_id;
    div_discount_name = 'discount_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;

    counter = counter_data[1].split('|');

    
    stop_refresh = false;
    tmp_status = 0;
    for (ii = 0; ii < counter.length; ii++) {
      data = counter[ii].split('=');
      if (data[0] == 'cp') {
        if (_index_counter_prices[auction_id] != null && _index_counter_prices[auction_id] != '') {
          if (parseInt(_index_counter_prices[auction_id]) > parseInt(data[1])) {
            stop_refresh = true;
            break;
          }
        }
      } else if (data[0] == 'cs') {
        tmp_status = data[1];
      }
    }
    if (stop_refresh == true) {
      _ct_time_seconds[auction_id]--;
      if (parseInt(_ct_time_seconds[auction_id]) < 0) { _ct_time_seconds[auction_id] = 0; }
      _ct_time = calc_counter_from_time(_ct_time_seconds[auction_id]);
      Element.update($(div_name_counter), _ct_time);
      if (parseInt(_ct_time_seconds[auction_id]) <= 10 && parseInt(_ct_time_seconds[auction_id]) > 0) {
        $(div_name_counter).style.color = '#DD0000';
      } else {
        $(div_name_counter).style.color = '';
      }
      continue;
    }
    
    for (ii = 0; ii < counter.length; ii++) {
      data = counter[ii].split('=');
      if (data[0] == 'ct') {
        if (data[1] == '-') {
          _ct_time = '--:--:--';
        } else {
          _ct_time = calc_counter_from_time(data[1]);
          _ct_time_seconds[auction_id] = data[1];
        }
        if ($(div_name_counter)) {
//if (i == 0) {alert(data[1]);}
          //$(div_name_counter).innerHTML = _ct_time;
          Element.update($(div_name_counter), _ct_time);
          if (parseInt(data[1]) <= 10 && parseInt(data[1]) > 0) {
            $(div_name_counter).style.color = '#DD0000';
          } else {
            $(div_name_counter).style.color = '';
          }
        }
      } else if (data[0] == 'cs') {
        if (data[1] == _auction_status_live) {
          if ($(div_button_name)) $(div_button_name).show();
        } else if (data[1] == _auction_status_paused) {
          _cur_time = new Date();
          _cur_secs = (_cur_time.getTime()/1000);
          if (_cur_secs%4 <= 2 && $(div_name_counter)) {
            $(div_name_counter).innerHTML = '<span style="font-family:Monospace;">処理中</span>';
          }
        } else if (data[1] == _auction_status_finished) {
          if ($(div_button_name_finished)) $(div_button_name_finished).show();
          if ($(div_button_name)) $(div_button_name).hide();
          if ($(div_name_counter)) {
            $(div_name_counter).innerHTML = '<span style="font-family:Monospace;">落札済み</span>';
          }
        } else if (data[1] == _auction_status_halted) {
          if ($(div_button_name)) $(div_button_name).hide();
          $(div_name_winner).innerHTML = '---';
          if ($(div_name_counter)) {
            $(div_name_counter).innerHTML = '<span style="color:red;">中止しました</span>';
          }
        }
      } else if (data[0] == 'cw' && data[1] != '' && tmp_status != _auction_status_halted) {
        el = $(div_name_winner);
        if (el) {
          el.innerHTML = data[1];
        }
      } else if (data[0] == 'cp') {
        if ($(div_price_name)) {
          $(div_price_name).innerHTML = format_raw_to_price(data[1]);
        }
        if (_index_counter_prices[auction_id] == null
            || _index_counter_prices[auction_id] == '') {
          _index_counter_prices[auction_id] = data[1];
        } else {
          if (_index_counter_prices[auction_id] != data[1]) {
            if ($(div_auction_name)) {
              new Effect.Parallel([
                new Effect.Highlight(div_auction_name, {duration:0.6, startcolor:'#f08080'}),
                new Effect.Opacity(div_auction_name, {duration:1, from:1.0, to:1.0})]
              );
            } else {
              new Effect.Highlight(div_price_name, {duration:1,startcolor:'#ff0000', endcolor:'#FFFFFF', restorecolor:'#FFFFFF'});
              new Effect.Highlight(div_name_winner, {duration:1,startcolor:'#ff0000', endcolor:'#FFFFFF', restorecolor:'#FFFFFF'});
            }
            _index_counter_prices[auction_id] = data[1];
          }
        }
      } else if (data[0] == 'cd') {
        if($(div_discount_name)) {
          $(div_discount_name).innerHTML = data[1];
        }
      }
    }
  }
}

var mlastNow = Object();


function refreshDetails(mUpdateURL, script_id) {
  if (mlastNow[script_id] == null || mlastNow[script_id] == undefined) {
    mlastNow[script_id] = 0;
  }

  if (((new Date()).getTime()-mlastNow[script_id])<300) return;

  mlastNow[script_id] = (new Date()).getTime();
  var script = document.createElement('script');

  script.type = 'text/javascript';
  script.src = mUpdateURL + "&now="+(new Date()).getTime();
  script.id = script_id + '_refresh_js' + '4';

  // remove old script-node (if there is one..)
  el = document.getElementById(script.id);
  if (el) {
    document.getElementsByTagName('head')[0].removeChild( el );
  }

  // set new script node
  document.getElementsByTagName('head')[0].appendChild(script);
}



/**
 * void do_counter_request(int)
 *   - do counter request and call success function
 */
function do_counter_request(auction_id, user_id, lock_key, verify) {
  url = 'http://' + document.location.hostname + ':8080/counter/show/?id=' + auction_id + '&plain=1';
  if (user_id != undefined && user_id != null && user_id != 0) {
    url += '&uid=' + user_id;
  }

  if (verify != undefined && verify != null) {
    url += '&val=' + verify;
  }

  if (lock_key == undefined || lock_key == null || lock_key == 0) {
    lock_key = 0;
  }

  if (_last_bid_key > -1) {
    url += '&lbp=' + _last_bid_key;
  }
  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;
    }

  }

  ic_script = document.createElement('script');
  ic_script.type = 'text/javascript';
  ic_script.src = url + "&c=" + new Date().getTime();
  ic_script.id = '_ev_detail_8409';

  el = document.getElementById(ic_script.id);
  if (el) {
    document.getElementsByTagName('head')[0].removeChild( el );
  }
  // set new script node
  document.getElementsByTagName('head')[0].appendChild(ic_script);

}


function _ev_detail(transport, auction_id, restet_counter_time, request_user_time) {
  if (restet_counter_time != null && restet_counter_time != undefined
      && restet_counter_time != '' && restet_counter_time != 0) {
    _overwrite_timeout = (1000-restet_counter_time);
  }

  if (typeof(request_user_time) != "undefined"
      && null != request_user_time
      && parseInt(request_user_time) > 0) {
    if (((new Date()).getTime()-parseInt(request_user_time)) > _ct_counter_latency_time) {
      if (_ct_counter_force_update == 0) {
        _lock_ct_keys['detail'] = 0;
        _ct_counter_last_update_skipped = 1;
        _ct_failed_requests_inc++;
        return "";
      }
    }
  }

  _ct_counter_last_update_skipped = 0;
  _ct_failed_requests_inc = 0;

  parse_counter_response(transport, auction_id, 1);

  _lock_ct_keys['detail'] = 0;
}

function _ev_index(transport, auction_id, restet_counter_time) {
  if (restet_counter_time != null && restet_counter_time != undefined
      && restet_counter_time != '' && restet_counter_time != 0) {
    _overwrite_timeout_index = (1000-restet_counter_time);
    _overwrite_timeout_special = (1000-restet_counter_time);
  }
  parse_counter_response_index(transport, 1);
  _lock_ct_keys['index'] = 0;
  if (_lock_ct_keys['special'] != null) {
    _lock_ct_keys['special'] = 0;
  }
}

function _ev_ext(transport, auction_id, restet_counter_time) {
  if (restet_counter_time != null && restet_counter_time != undefined
      && restet_counter_time != '' && restet_counter_time != 0) {
    _overwrite_timeout_index = restet_counter_time;
    _overwrite_timeout_special = restet_counter_time;
  }

  parse_counter_response_ext(transport, auction_id);
}


function do_counter_request_index(auction_ids, user_id, lock_key, verify) {
  if (auction_ids == '' || auction_ids == null) {
    return;
  }

  url = 'http://' + document.location.hostname + ':8080/counter/?aids=' + auction_ids;
  if (user_id != undefined && user_id != null && user_id != 0) {
    url += '&uid=' + user_id;
  }
  if (verify != undefined && verify != null) {
    url += '&val=' + verify;
  }
  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;

      ic_script = document.createElement('script');
      ic_script.type = 'text/javascript';
      ic_script.src = url + "&c=" + new Date().getTime();
      ic_script.id = '_ev_index_8409';

      el = document.getElementById(ic_script.id);
      if (el) {
        document.getElementsByTagName('head')[0].removeChild( el );
      }
      // set new script node
      document.getElementsByTagName('head')[0].appendChild(ic_script);

    }
  }
}

function _after_ev_index() {
  _lock_ct_keys['index'] = 0;
  if (_lock_ct_keys['special'] != null) {
    _lock_ct_keys['special'] = 0;
  }
}

/**
 * void check_status_code(void)
 *   - get status code specific HTML
 */
function check_status_code() {
  if (_ct_counter_status == _auction_status_finished) {
    if ($('gebotsbutton')) {
      $('gebotsbutton').innerHTML = '<strong>オークション終了！</strong>';
    }
    if ($('auto_bidder')) {
      $('auto_bidder').innerHTML = '';
    }
    window.location.reload();
  } else if (_ct_counter_status == _auction_status_halted) {
    if ($('gebotsbutton')) {
      $('gebotsbutton').innerHTML = '<strong>オークション中止！</strong>';
    }
    if ($('auto_bidder')) {
      $('auto_bidder').innerHTML = '';
    }
    window.location.reload();
  }
}


/**
 * void get_future_auction_counter(int, int)
 *   - display future auction counter
 */
/*
function get_future_auction_counter(auction_id, start_time) {
  if (_future_counter_time > 0 && _future_counter_changed == 1) {
    start_time = _future_counter_time;
    _future_counter_changed = 0;
  }
  if (start_time < 0 || _ct_counter_status != _auction_status_future) {
    return;
  }

  time_string = calc_counter_from_time(start_time);

  $('countertime').innerHTML = time_string;

  _intv2 = setTimeout('get_future_auction_counter(' + auction_id + ', ' + --start_time + ')', 1000);
}
*/


/**
 * void get_interval_by_status(int)
 *   - check for counter status and adapt update interval
 */
function get_interval_by_status(auction_id) {

  // set interval
  if (_ct_counter_status_changed == 1
      || _ct_counter_status == _auction_status_future) {
    if (_ct_counter_status != 0) {
      if (_ct_counter_status == _auction_status_future) {
        // future auction
        _update_interval = 1000;
        if (_start_time > 0) {
          _update_interval = (_start_time*1000);
          if (_start_time < 10) {
            _update_interval = 1000;
          } else if (_update_interval > 5000 || _update_interval < 0) {
            _update_interval = 1000;
          }
        }
      } else if (_ct_counter_status == _auction_status_paused) {
        _update_interval = 2000;
      } else if (_ct_counter_status == _auction_status_live) {
        _update_interval = 1000;
      }
    }


    if (_ct_counter_status_changed == 1) {
      //alert('status changed - ' + _update_interval + ' - TODO print it');
    }

    if (_ct_counter_status == _auction_status_live
        || _ct_counter_status == _auction_status_future) {

      if (parseInt(_overwrite_timeout) > 500) {
        _update_interval = _overwrite_timeout;
      }
    }

    _ct_counter_status_changed = 0;
    //alert('status changed - ' + _update_interval);
    //auction_detail_js(auction_id, _ct_counter_status, 0);
  }
}



function parse_counter_response_ext(transport, auction_id) {

  if (transport == undefined || transport == null) {
    return;
  }
  result_array = transport.split("|");

  div_counter_name = 'countertime';
  div_winner = 'a_current_winner';
  div_price_name = 'a_current_price';

  div_counter_name_index = 'counter_index_page_' + auction_id;
  div_price_index = 'price_index_page_' + auction_id;
  div_winner_index = 'winner_index_page_' + auction_id;


  for (i = 0; i < result_array.length; i++) {
    if ('' == result_array[i] || null == result_array[i]) {
      continue;
    }
    data = result_array[i].split("=");
    if (data.length < 2) {
      continue;
    }
    if (data[0] == 'ct' && data[1] != '') {
      _ct_counter_time = data[1];
      if (_ct_counter_time != undefined && _ct_counter_time != null && _ct_counter_time != '') {
        _ct_counter_time = calc_counter_from_time(_ct_counter_time);
      } else {
        _ct_counter_time = '';
      }
      if (_ct_counter_time != '' && _ct_counter_time != '-') {
        if ($(div_counter_name)) {
          $(div_counter_name).innerHTML = _ct_counter_time;
        } else if ($(div_counter_name_index)) {
          $(div_counter_name_index).innerHTML = _ct_counter_time;
        }
      }
    }  else if (data[0] == 'cw' && data[1] != '') {
      if ($(div_winner_index)) {
        $(div_winner_index).innerHTML = data[1];
      } else if ($(div_winner)) {
        $(div_winner).innerHTML = data[1];
      }
    }  else if (data[0] == 'cp' && data[1] != '') {
      if ($(div_price_index)) {
        $(div_price_index).innerHTML = data[1];
//        new Effect.Highlight(div_price_index, {duration:1,startcolor:'#ff0000',endcolor:'#ffffff',restorecolor:'#FFFFFF'});
      } else if ($(div_price_name)) {
        $(div_price_name).innerHTML = data[1];
//        new Effect.Highlight(div_price_name, {duration:1,startcolor:'#ff0000',endcolor:'#ffffff',restorecolor:'#FFFFFF'});
      }
    }
  }
  return;
}



/**
 * void parse_counter_response(object int)
 *   - parse request from counter server and adapt html
 */
function parse_counter_response(transport, auction_id, plain) {
  if (plain != undefined && plain != null && plain == 1) {
    result_array = transport.split("|");
  } else {
    result_array = transport.responseText.split("|");
  }

  div_counter_name = 'countertime';

  has_price_update = 0;
  tmp_counter = 0;
  for (i = 0; i < result_array.length; i++) {
    tmp_data = result_array[i].split("=");
    if (tmp_data.length < 2) {
      continue;
    }
    if (tmp_data[0] == 'ct') {
      tmp_counter = tmp_data[1];
    }
    if (tmp_data[0] == 'cp') {
            if ( _ct_counter_price != null ) {
        if (_ct_counter_price == 0 || parseInt(_ct_counter_price) <= parseInt(tmp_data[1])) {
          has_price_update = 1;
        }
      }
    }
  }

//  if (has_price_update == 0 && _ct_counter_time_plain < tmp_counter
//      && _ct_counter_force_update == 0) {
  if (has_price_update == 0 && _ct_counter_force_update == 0) {
    return "";
  }

  for (i = 0; i < result_array.length; i++) {
    if ('' == result_array[i] || null == result_array[i]) {
      continue;
    }
    data = result_array[i].split("=");
    if (data.length < 2) {
      continue;
    }

/*
    if (_last_bid_key != null) {
      if (js_cd_speed_tics != undefined && js_cd_speed_tics != null) {
        _last_cs_speed_matched = 0;
        _current_speed = 20;
        for (var ii in js_cd_speed_tics) {
          if (_last_cs_speed_matched == 1) {
            //_update_counter_speed_image(ii, js_cd_speed_tics[ii], _current_speed);
            _last_cs_speed_matched = 0;
          }
          if (parseInt(_last_bid_key) >= parseInt(js_cd_speed_tics[ii])) {
            _last_cs_speed_matched = 1;
            _current_speed = ii;
          }
        }
        if (_last_cs_speed_matched == 1) {
          //_update_counter_speed_image(_current_speed, 1000, _current_speed);
          //_delete_counter_speed_image(_current_speed);
          _last_cs_speed_matched = 0;
        }
      }
    }
*/


    if (data[0] == 'ct') {
      _ct_counter_time = data[1];
      _ct_counter_diff = data[1] - _ct_counter_time_plain;
      _ct_counter_time_plain_before = _ct_counter_time_plain;
      _ct_counter_time_plain = data[1];
      _ct_counter_last_life_update = (new Date()).getTime();

      if (_ct_counter_status == _auction_status_future_wo_startdate) {
        /*_ct_counter_time = '-- : -- : -- ';*/
        _ct_counter_time = '';
      } else {
        if (_ct_counter_time == '-') {
          _ct_counter_time = '-- : -- : --';
        } else if (_ct_counter_status == _auction_status_live
                   && (_ct_counter_time == '0' || _ct_counter_time == '')) {
          _ct_counter_time = '';
        } else {
          _ct_counter_time = calc_counter_from_time(_ct_counter_time);
        }
      }

      if ($(div_counter_name) && _ct_counter_time != '') {
        $(div_counter_name).innerHTML = _ct_counter_time;
        if (parseInt(data[1]) <= 10 && parseInt(data[1]) > 0) {
          $(div_counter_name).style.color = '#DD0000';
          //$('countertime').style.textDecoration = 'blink'
          if ($('last_actions_div').style.display == 'none'
              &&  $('last_actions_div').innerHTML != '<img alt="Img_hurryup" src="http://img.yasuoku.jp/images/auction/img_hurryup.gif" />') {
            $('last_actions_div').innerHTML = '<img alt="Img_hurryup" src="http://img.yasuoku.jp/images/auction/img_hurryup.gif" />';
            $('last_actions_div').style.display = '';
          }
        } else {
          if (_last_action_div_displayed == 0) {
            $('countertime').style.color = '';
            //$('countertime').style.textDecoration = 'none';
            //$('last_actions_div').innerHTML = '';
            $('last_actions_div').style.display = 'none';
          }
        }
      } else if ($('counter_index_page_' + auction_id)) {
        $('counter_index_page_' + auction_id).innerHTML = _ct_counter_time;
      }

    } else if (data[0] == 'cw' && data[1] != '') {
      _ct_counter_winner_name = data[1];
      if ($('a_current_winner')) {
        $('a_current_winner').innerHTML = _ct_counter_winner_name;
      }
      if ($('winner_index_page_' + auction_id)) {
        $('winner_index_page_' + auction_id).innerHTML = _ct_counter_winner_name;
      }
    } else if (data[0] == 'cp') {
      _ct_counter_price = data[1];
      if ($('a_current_price')) {
        $('a_current_price').innerHTML = format_raw_to_price(_ct_counter_price);
      }
      if ($('a_current_price2')) {
        $('a_current_price2').innerHTML = format_raw_to_price(_ct_counter_price);
      }
      if ($('price_index_page_' + auction_id)) {
        $('price_index_page_' + auction_id).innerHTML = format_raw_to_price(_ct_counter_price);
      }

      if (_ct_counter_price != _counter_changed) {
        if (_last_bid_key != null && _last_bid_key != undefined
            && _last_bid_key >= 0) {
          if ($('a_current_price')) {
             $('a_current_price').style.backgroundColor='#FFFFFF';
             new Effect.Highlight('a_current_price', {duration:1,startcolor:'#ff0000',endcolor:'#ffffff',restorecolor:'#FFFFFF'});
          } else if ($('price_index_page_' + auction_id)) {
            new Effect.Highlight('price_index_page_' + auction_id, {duration:1,startcolor:'#ff0000',endcolor:'#ffffff',restorecolor:'#FFFFFF'});
          }
        } else if ($('price_index_page_' + auction_id)) {
          new Effect.Highlight('price_index_page_' + auction_id, {duration:1,startcolor:'#ff0000',endcolor:'#ffffff',restorecolor:'#FFFFFF'});
        }
      }

      if (_last_bid_key != -1) {
        // update savings
        update_savings_details(auction_id, 0);
      }
      // counter changed
      _counter_changed = _ct_counter_price;

    } else if (data[0] == 'cs') {
      if (data[1] != _ct_counter_status) {
        _ct_counter_status_changed = 1;
      }
      _ct_counter_status = data[1];

      // 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';
        }
      }
    } else if (data[0] == 'cwi') {
      _ct_counter_winner_id = data[1];
    } else if (data[0] == 'bh' && data[1] != '') {
      parse_bid_history(data[1], auction_id);
    } else if (data[0] == 'lui') {
      parse_last_update_info(data[1]);
    }
  }
  _detail_request_running = 0;
}


var _lui_running = '';
var bid_increment;
var time_increment;
function parse_last_update_info(lui) {
  lui_data = lui.split('#');
  lui_out = '';
  lui_bids = 0;
  lui_div = 'last_actions_div';
  if (null == bid_increment || undefined == bid_increment) {
    bid_increment = _default_bid_increment;
  }
  if (lui_data.length == 2) {
    if (lui_data[0] != null && lui_data[0] != undefined) {
      if (lui_data[0] != 0) {
        lui_out += lui_data[0] + ' ';
        lui_out += _wording_single_bid;
        lui_bids += parseInt(lui_data[0]);
      }
    }
    if (lui_data[1] != null && lui_data[1] != undefined) {
      if (lui_data[1] != 0) {
        if (lui_out != '') lui_out += ' ＆ ';
        lui_out += lui_data[1] + ' ';
        lui_out += _wording_bid_agent;
        lui_bids += parseInt(lui_data[1]);
      }
    }
    lui_out += "<br />";
    lui_out += '+' + format_raw_to_price(parseInt(bid_increment)*parseInt(lui_bids));
/*
    if (_ct_counter_time_plain_before <= time_increment + 1) {
      lui_out += calc_counter_from_time(_ct_counter_diff);
    } else {
      lui_out += calc_counter_from_time(time_increment*(parseInt(lui_data[0])+parseInt(lui_data[1])));
    }
*/
  }

  if (lui_out != "") {
    el = $(lui_div);
    if (el) {
      if (_lui_running) {
        window.clearTimeout(_lui_running);
      }
      el.innerHTML = lui_out;
      _last_action_div_displayed = 1;
      new Effect.BlindDown(el);
      _lui_running = window.setTimeout('new Effect.BlindUp(\'' + lui_div + '\', {duration:1}); _last_action_div_displayed = 0',4500);
    }
  }
}

function parse_bid_history(bh, auction_id) {
  bh_data = bh.split('#');
  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 = 'stats_test';
  div_stats_own = 'my_placed_bids';
  if (!document.getElementById(div_stats_all)) {
    return;
  }

  if (bh_data.length == 1 && bh_data[0] == "none") {
    _last_bid_key = 0;
    return;
  }

  for (x = 0; x < bh_data.length; x++) {
    if (null != bh_data[x]) {
      single_entry = bh_data[x].split(':');

      if (null == single_entry || single_entry.length == 0) {
        continue;
      }

      if (single_entry[0] == null || single_entry[0] == "") {
        continue;
      }

      if (parseInt(single_entry[0]) > parseInt(_last_bid_key)) {
        _last_bid_key = single_entry[0];
      }

      tmp_bh[y] = new Object();
      tmp_bh[y]["bid_key"] = parseInt(single_entry[0]);
      tmp_bh[y]["user"] = single_entry[1];
      tmp_bh[y]["type"] = single_entry[2];
      tmp_bh[y]["price"] = format_raw_to_price(single_entry[3]);
      tmp_bh[y]["your_bid"] = 0;
      if (undefined != single_entry[4]) {
        tmp_bh[y]["your_bid"] = single_entry[4];
      }
      if (tmp_bh[y]["your_bid"] == 1) {
        tmp_bh[y]["user"] = "<b>" + tmp_bh[y]["user"] + "</b>";
        tmp_own_bh[z] = tmp_bh[y];
        z++;
      }
      y++;

      if (single_entry[0] != "" && tmp_min_bid_key >= single_entry[0]) {
        tmp_min_bid_key = parseInt(single_entry[0]);
      }
    }
  }

  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) {
    history_out += '<table width="180" border="0" cellspacing="0" cellpadding="0">';
    history_out += '<tr> ' +
                   '  <td width="50"></td>' +
                   '  <td width="70"></TD>' +
                   '  <td width="60"></TD>' +
                   '</tr>';

    for (x = 0; x < _bid_history.length; x++) {
      if (_bid_out_types[_bid_history[x]["type"]] != null) {
        _type = _bid_out_types[_bid_history[x]["type"]];
      } else {
        _type = 'n/a';
      }
      history_out += "<tr>";
      history_out += "<td align=\"left\">" + _bid_history[x]["price"] + "</td>";
      history_out += "<td>" + _bid_history[x]["user"] + "</td>";
      history_out += "<td>" + _type + "</td>";
      history_out += "</tr>";
    }
    history_out += '</table>';
  }

  if (history_out != "") {
    $(div_stats_all).innerHTML = history_out;
  }

  return;
}

var _last_savings_update = 0;
function update_savings_details(auction_id, force_update) {
  if (auction_id == undefined || auction_id == null) {
    return;
  }

  if(force_update  == undefined || force_update == 0){
    if (((new Date()).getTime()-_last_savings_update)<15000) {
      return;
    }
  }

  _last_savings_update = (new Date()).getTime();

  url = '/auction/savings/' + auction_id;
  new Ajax.Request(url, {method:'get',
    onSuccess: function(transport) { parse_savings_detail(transport); } });
}


function parse_savings_detail(transport) {
  result_array = transport.responseText.split("|");
  div_name_own_bids = 'a_placed_bids';
  div_name_own_bid_price = 'a_placed_bid_price';
  div_name_savings = 'user_savings';
  div_name_saving_rate = 'user_saving_rate';
  if (result_array.length == 4) {
    el = $(div_name_own_bids);
    el2 = $(div_name_own_bid_price);
    el3 = $(div_name_savings);
    el4 = $(div_name_saving_rate);
    if (el) { el.innerHTML = result_array[0]; }
    if (el2) { el2.innerHTML = result_array[1]; }
    if (el3) { el3.innerHTML = result_array[2]; }
    if (el4) { el4.innerHTML = result_array[3]; }
  } else if (result_array.length == 2) {
    el3 = $(div_name_savings);
    el4 = $(div_name_saving_rate);
    if (el3) { el3.innerHTML = result_array[0]; }
    if (el4) { el4.innerHTML = result_array[1]; }
  }
}




