bidsLogLoaded = false;
sellerLoaded = false;
descriptionEnLoaded = false;
descriptionXciteLoaded = false;
countdownActive = false;
descriptionHeight = 0;

function rgb2hex(r,g,b)
{
  return Number(r).toString(16).toUpperCase().replace(/^(.)$/,'0$1') + 
         Number(g).toString(16).toUpperCase().replace(/^(.)$/,'0$1') +
         Number(b).toString(16).toUpperCase().replace(/^(.)$/,'0$1');
}

function getHexRGBColor(color)
{
  color = color.replace(/\s/g,"");
  var aRGB = color.match(/^rgb\((\d{1,3}[%]?),(\d{1,3}[%]?),(\d{1,3}[%]?)\)$/i);

  if(aRGB)
  {
    color = '';
    for (var i=1;  i<=3; i++) color += Math.round((aRGB[i][aRGB[i].length-1]=="%"?2.55:1)*parseInt(aRGB[i])).toString(16).replace(/^(.)$/,'0$1');
  }
  else color = color.replace(/^#?([\da-f])([\da-f])([\da-f])$/i, '$1$1$2$2$3$3');
  
  return color;
}

function splitRGB(color)
{
  color = getHexRGBColor(color); 
  var matches = color.match(/^#?([\dabcdef]{2})([\dabcdef]{2})([\dabcdef]{2})$/i);
    
  if (!matches) return false;
  
  for (var i=1, rgb = new Array(3);  i<=3; i++) rgb[i-1] = parseInt(matches[i],16);
  
  return rgb;
}

function hex2rgb(hex) {
  var color = new Array();
  hex = hex.replace('#', '');
  for (var i = 0; i < 3; i++) {
    color[i] = parseInt(hex.slice(i, i + 1), 16);
  }
  return color;
}

function fade(elementId, to, attribute, finalClassName, steps, delay) {
  var obj = $(elementId);
  var source = splitRGB(obj.style[attribute]);
  if (!to) {
    to = '#FFFFFF';
  }
  if (!finalClassName) {
    finalClassName = '';
  }
  var target = splitRGB(to);
//  console.log(source, target);
  for(var i = 0; i < 3; i++) {
    source[i] += Number(((target[i] - source[i]) / steps).toFixed(0));
  }
//  console.log(source);
  obj.style[attribute] = '#' + rgb2hex(source[0], source[1], source[2]);
  steps--;
  if (steps > 0) {
	  setTimeout('fade("' + elementId + '", "' + to + '", "' + attribute + '", "' + finalClassName + '", ' + steps + ', ' + delay + ')', delay);
	} else {
	  obj.style[attribute] = '';
	  obj.className = finalClassName;
	}
} 

function switchTo(name) {
  if (descriptionHeight == 0) {
    descriptionHeight = $('divTabContentDescription').offsetHeight > 0 ? $('divTabContentDescription').offsetHeight : 200;
  }
  e = document.getElementsByTagName('td');
  for(var i in e) {
    if (e[i].id && e[i].id.indexOf('tdTab')==0) {
      e[i].className = 'tab-' + (e[i].id == ('tdTab'+name) ? 'active' : 'inactive');       
    }
  }
  
  e = document.getElementsByTagName('div');
  for(var i in e) {
    if (e[i].id && e[i].id.indexOf('divTabContent')==0) {
      e[i].style.display = e[i].id == ('divTabContent'+name) ? '' : 'none';       
    }
  }
  
  if (name == 'BidsLog') {
    if (!bidsLogLoaded) {
      loadBidsLog();
    }
  }

  if (name == 'DescriptionEn') {
    if (!descriptionEnLoaded) {
      loadDescriptionEn();
    }
  }
  
  if (name == 'DescriptionXcite') {
    if (!descriptionXciteLoaded) {
      loadDescriptionXcite();
    }
  }  
  
  if (name == 'Seller') {
    if (!sellerLoaded) {
      loadSeller();
    }
  }
}

function loadBidsLog() {
  $('spanBidsLogLoading').style.display = 'block';  
  $('spanBidsLogData').style.display = 'none';
  req = getAjax();
  if (req) {
    req.open('GET',  '/ajax/getBidsLog/'+auctionId+'.html', true);
    req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    req.onreadystatechange = function() {
      if (req.readyState == 4) {
        $('spanBidsLogData').innerHTML = req.responseText;
        $('spanBidsLogData').style.display = '';
        //try { $('spanBidsLogData').scrollIntoView(); } catch(e) {}
        $('spanBidsLogLoading').style.display = 'none';
        bidsLogLoaded = true;
        $('aReloadBidsLog').style.display = '';
        $('aLoadBidsLog').className = '';
      }
    }
    req.send(null);
  }
}

function loadDescriptionEn() {
  $('spanDescriptionEnLoading').style.display = 'block';  
  $('spanDescriptionEnData').style.display = 'none';
  $('spanDescriptionEnData').innerHTML = '<iframe border="0" frameborder="0" noresize="noresize" cellspacing="0" style="border: none; padding: 0; margin: 0; width: 100%; height: ' + (descriptionHeight + 100) + 'px" src="http://translate.google.com/translate?hl=en&u=http%3A%2F%2Finjapan.ru%2FauctionDescription%2Fshow%2F' + auctionId + '.html&sl=ja&tl=en"></iframe>';
  $('spanDescriptionEnData').style.display = '';
  $('aLoadDescriptionEn').className = '';
  $('spanDescriptionEnLoading').style.display = 'none';
  descriptionEnLoaded = true;
}

function loadDescriptionXcite() {
  $('spanDescriptionXciteLoading').style.display = 'block';  
  $('spanDescriptionXciteData').style.display = 'none';
  req = getAjax();
  if (req) {
    req.open('GET',  '/ajax/translate/'+auctionId+'.html?method=excite', true);
    req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    req.onreadystatechange = function() {
      if (req.readyState == 4) {
        $('spanDescriptionXciteData').innerHTML = req.responseText;
        $('spanDescriptionXciteData').style.display = '';
        $('spanDescriptionXciteLoading').style.display = 'none';
        descriptionXciteLoaded = true;
        $('aLoadDescriptionXcite').className = '';
      }
    }
    req.send(null);
  }
}

function updateInfo() {
  $('spanUpdateLoading').style.display = '';  
  $('spanUpdate').style.display = 'none';
  req = getAjax();
  if (req) {
    req.open('GET',  '/ajax/updateInfo/'+auctionId+'.html', true);
    req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    req.onreadystatechange = function() {
      if (req.readyState == 4) {
			  $('spanUpdateLoading').style.display = 'none';  
			  $('spanUpdate').style.display = '';
        //try {
          eval(req.responseText);
          var dirty = new Array();
          for(var i in updatedInfo) {
            if ($('spanInfo'+i)) {
              test1 = $('spanInfo'+i).innerHTML.toUpperCase().replace('CLASS=COMMENT', 'CLASS="COMMENT"');
              test2 = updatedInfo[i].toUpperCase();
	            if ( test1 != test2) {
	              dirty[i] = true;
	              $('rowInfo'+i).style.backgroundColor = '#D3F180';
	            } else {
	              $('rowInfo'+i).style.backgroundColor = '#FFE680';
	            }
	            fade('rowInfo'+i, '#FFFFFF', 'backgroundColor', $('rowInfo'+i).className, 10, 100);
	            $('spanInfo'+i).innerHTML = updatedInfo[i];
	          }             
          }
          if (!hiddenPrice && $('spanHiddenPrice')) {
            $('spanHiddenPrice').style.display = 'none';
          }
          if (dirty['Enddate'] && countdownActive) {
            $('aGetTimer').click();
          }
        //} catch(e) {}
      }
    }
    req.send(null);
  }
}

function loadSeller() {
  $('spanSellerLoading').style.display = 'block';  
  $('spanSellerData').style.display = 'none';
  req = getAjax();
  if (req) {
    req.open('GET',  '/ajax/getSellerRating/'+sellerName+'.html', true);
    req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    req.onreadystatechange = function() {
      if (req.readyState == 4) {
        $('spanSellerData').innerHTML = req.responseText;
        $('spanSellerData').style.display = '';
        //try { $('spanSellerData').scrollIntoView(); } catch(e) {}
        $('spanSellerLoading').style.display = 'none';
        sellerLoaded = true;
        //$('aReloadSeller').style.display = '';          
        $('aLoadSeller').className = '';
      }
    }
    req.send(null);
  }
}

function checkBid(bid) {
  if (bid > maxbid) {
    alert('Ставка в ¥ '+bid+' превышает вашу максимальную ставку.');
    return false;
  }
  
  if ($('quantity') && $('quantity').value == '') {
    alert('Укажите нужное количество (текущая цена лота — это цена за 1 шт.).');
    return false;
  }

  if ($('spanInfoQuantity') && $('quantity') && Number($('spanInfoQuantity').innerHTML) < Number($('quantity').value)) {
    alert('Можно купить максимум '+$('spanInfoQuantity').innerHTML+' шт. Измените количество.');
    return false;
  }      
   
  return true;
}


  this.dt = '';
  this.iscontinue = false;
  
  // call a url
  function getText(url) {
    var xmlHttpReq = getAjax();

    if (!xmlHttpReq) {
        alert('Необходим браузер с поддержкой XMLHTTP');
    return;
    }

    xmlHttpReq.onreadystatechange = function()
      {
        getReturn(xmlHttpReq);
      };

    xmlHttpReq.open("POST", url, true);
    xmlHttpReq.send('1');
    
} 
  
  //  
  
  function addZero(number) {
      return ((number < 10) ? "0" : "" ) + number;
  } 
  
  function getReturn(xmlHttpReq) {
      
   if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
    res = xmlHttpReq.responseText;
    if (isNaN(res)) {
     datevalue.innerHTML = res; 
    } else { 
     this.iscontinue = true;
     this.dt = new Date();
     var curt = new Date();
     res = 0 + res;
     this.dt.setTime(curt.getTime() + res * 1000);
     $('aGetTimer').innerHTML = 'обновить';
	   $('spanCountdown').style.display = '';
	   $('spanCountdownLoading').style.display = 'none';
     
     countdownActive = true;
     IncTime();
    }     
   }
  
  }
  
  function getTime(auctionid) {
   this.iscontinue = false;
   var url;
   //var auctionid = document.getElementById('lotnum').value;
   var datevalue = document.getElementById('datevalue');
   //var dateref = document.getElementById('dateref');  
   //dateref.innerHTML = '';
   $('spanCountdown').style.display = 'none';
   $('spanCountdownLoading').style.display = '';
   
   url = '/ajax/getCountDown/' + auctionid;
   var res = getText(url);
  } 
  
  function IncTime() {

   if (this.iscontinue) {
    var datevalue = document.getElementById('datevalue');
    //var dateref= document.getElementById('dateref');      
    var curt = new Date();
    var tempt = new Date(0,0,0,0,0,0);
    var delta = this.dt.getTime() - curt.getTime();
    
    if (delta > 0) {
     tempt.setMilliseconds(delta);
  
       var d = tempt.getDate();
     var h = tempt.getHours();
     var m = tempt.getMinutes();
     var s = tempt.getSeconds();
   
     if (delta > 86400000)
      var str = d + ' ' + (d <= 1 ? 'день' : (d >= 5 ? 'дней' : 'дня')) + ' + ' + addZero(h) + ':' + addZero(m) + ':' + addZero(s);
     else
      var str = addZero(h) + ':' + addZero(m) + ':' + addZero(s);

     if (delta <= 3600000) 
       datevalue.innerHTML = '<span style="color: red">' + str + '</span>';
     else
       datevalue.innerHTML = str;
   
     if (this.iscontinue)
      setTimeout('IncTime()', 1000);
    } else {
    this.iscontinue = false;
    datevalue.innerHTML = 'Торги завершены';
    }   
   } 
    }