idBtn = new Array();
var messZeroBid = 1;

function getTimestamp(){
	var humDate = new Date();
	return(humDate.getTime());
}

function TimeLotRefresh(){
	var TimeStart = getTimestamp();
	var Latency = 0;
	$.ajax({
		type: "GET",
		url: _url + "core/actions/arefresh.htm",
		data: "r="+Math.random(),
		success: function(htm){
			var data = new Array();
			data = htm.split('<i>');
			var ldata = new Array();
			var k=0;
			
			for(var i=0; i<data.length; i++){
				ldata = data[i].split('<br>');
				k = ldata[0];
				if($(_lotStatus[k]) != null){
					if((_lotTime[k] != null) && _lotTime[k].time>=0 && (_lotTime[k].price != ldata[2] || _lotTime[k].status != ldata[1])){
						var _a= $(_lotStatus[k]).find("#user_"+k);
						$(_a).attr("href", _url + "index.php?idd=user&user="+ldata[7]);
						$(_a).children("span").html(ldata[7]);
						//_lotTimeHost.user = ldata[7];
						
						// мигание цены сделать здесь
						$(_lotStatus[k]).find("#price_"+k+" span").html(ldata[2]);

						$(_lotStatus[k]).find("#time_"+k)
						.animate({ backgroundColor: "#d011cb" }, 800, function(){ /*alert($(this).css("background-color"))*/})
						.animate({ backgroundColor: "#09102f" }, 800, function(){ $(this).css("background-color", "transparent").css("color", "#ffd800")});


						_lotTime[k] = { "id":ldata[0], "status":ldata[1], "time":ldata[3], "price":ldata[2], "isannul":ldata[11], "user": ldata[7]};
						
						el = $(_lotStatus[k]).find("#pricest");
						if($(el).html() != null){
							$(el).html(ldata[4]);
							$(_lotStatus[k]).find("#timest").html(timeFormat(ldata[5]));
							var c;
							if(ldata[9] != "reverse") c = ldata[8]-((ldata[2]-ldata[10])/ldata[4])-ldata[2];
							else c = ldata[8]-((ldata[10]-ldata[2])/ldata[4])-ldata[2];
							if(c < 0) c=0;
							
							// мигание цены сделать здесь
							
							$(_lotStatus[k]).find("#currprice").html((ldata[2]*1).toFixed(2)+" грн");
							//$(_lotStatus[k]).find("#compens").html(c.toFixed(2)+" грн");
							//$(_lotStatus[k]).find("#ecoprice").html((ldata[8]-ldata[2]-c).toFixed(2)+" грн");
                            $(_lotStatus[k]).find("#ecoprice").html((ldata[8]-ldata[2]).toFixed(2)+" грн");
							if(_lotTime[k].status == 'start'){ 
								lotLogRefresh(_lotTime[k].id);
								autoBidRefresh(_lotTime[k].id);
							}
						}
						
					}else{                          
						if(_lotTime[k] != null) _lotTime[k].time = ldata[3];
					}
				}
			}
			/**/
			TimeLotRef=getTimestamp()- TimeStart;
		}
	});
	setTimeout("TimeLotRefresh()", lotRefreshTime);
}

function lotLogRefresh(id){
	$.ajax({
		url: _url + "core/actions/bidlogrefresh.php",
		data: "lotid="+id,
		type: "POST",
		success: function(htm){
			$("#history table").html(htm);
		}
	});
	
}

function autoBidRefresh(lot){
	$.ajax({
		url: _url + "core/actions/autoBids.php",
		data: "action=refresh&lot="+lot,
		type: "POST",
		success: function(htm){
			$("#autoHistory").html(htm);
		}
	});
}

function ChangePic(idpic, cdir){	
	temp = document.getElementById("pic"+idpic).src;
	temppic = temp.split('thumb');

	str = document.getElementById("picbig").src;
	namepic = str.split('/');
	exprPos = namepic.length-1;
					
	document.getElementById("pic"+idpic).src =  cdir+"thumb"+namepic[exprPos];
	document.getElementById("picbig").src = cdir+temppic[1];
}

function ClkBtn(){
	if(document.getElementById("rules").checked){
		$("#register").show();
	}
	else{
		$("#register").hide();
	}
}

function addListBtn(id){
	idBtn.push(id);
}

function ViewBtn(rname,bname){
	for(i=0; i < idBtn.length; i++){
		$(idBtn[i]).hide();
	}
		
	if(document.getElementById(rname).checked){ $(bname).show(); }
		else{ $(bname).hide(); }
}

function SendForm(objname){
	 objform= document.getElementById(objname);
	 objform.submit();
}

function showMessForm(){
	$("#chBoxadd").show("slow");
	$("#showmfbutt").hide();
	
}

function hideMessForm(){
	$("#chBoxadd").hide("slow");
	$("#showmfbutt").show();
}

function addMessForm(){
	 var txt = $("#fmess").val();

	 var typ = "user";
	 if($("#rad #root").attr("checked")) typ = "root";
		else if($("#rad #system").attr("checked")) typ = "system";
	 
	$.ajax({
		type: "POST",
		url: _url + "core/actions/forum.php",
		data: "act=add&forum="+thisforum+"&fstatus="+typ+"&message="+txt
	});
	$("#fmess").val("");
	hideMessForm();
	
	_getFinfo();
}

function _getFinfo(){
	if(document.getElementById("chBox")){
		if(thisforum>0){
			$.ajax({
				url: _url + "core/actions/af.php",
				data: "forum="+thisforum,
				type: "POST",
				success: function(htm){
					$("#chBox").html(htm);
				}
			});
		}else{
			$.ajax({
				url: _url + "core/actions/f.php",
				success: function(htm){
					$("#chBox").html(htm);
				}
			});
		}
	}
}

function getForumInfo(){
	if(document.getElementById("chBox")){
		_getFinfo();
		setTimeout("getForumInfo()", 10000);
	}
}
function setLoginFocus(){
	$("#lInp").focus();
}
function linkOver(obj){
	obj.innerHTML = "Авторизуйтесь!";
}
function linkOut(obj){
	obj.innerHTML = "Сделать ставку";
}

function linkfrOut(obj){
	obj.innerHTML = "Принять участие";
}

function ChangeBtnY(id){
	$(id).css("background-image", "url(pic/price_down_bg.gif)");
}

function ChangeBtnR(id){
	$(id).css("background-image", "url(pic/price_bg.gif)");
}


function foreregist(id, st){
	if(!id) return false;
	$.ajax({
		type: "POST",
		url: _url + "core/actions/foreregist.php",
		data: "aid="+id+"&st="+st,
		success: function(msg){
			var message = '';
			switch (msg){
				case 'not_auth': message = 'Вы не авторизированы.<br />Зарегистрируйтесь или войдите в систему под своей учетной записью.'; break;
				case 'usr_limit_max' : message = "Количество участников на данном аукционе достигло максимального значения"; break;
				case 'usr_pre_reg' : message = 'Вы зарегистрировались на проведение аукциона'; $("#noreg_"+id).hide(); $("#isreg_"+id).show(); break;
				case 'is_usr_pre_reg' : message = 'Вы зарегистрированный участник аукциона'; $("#noreg_"+id).hide(); $("#isreg_"+id).show(); break;
				case 'usr_pre_reg_del' : message = 'Вы отказались от участия в аукционе'; $("#isreg_"+id).hide(); $("#noreg_"+id).show(); break;
				case 'bad_user': return false;
				case 'bad_params': return false;
				case 'tech_problems': return false;
			}
			//alert(msg);
			if(message){
				$("#messageBox").html(message);
				noteMessBoxShow();
			}
		}
	});
	return false;
}

function userBidStatus(){
	$.ajax({
		url: _url + "core/actions/userbidstatus.php",
		data: "r="+Math.random(),
		type: "GET",
		success: function(htm){
			$("#urate").html(htm);
	
			if((htm*1)<=5 && messZeroBid==1){
				$("#messageBox").html("У Вас осталось "+htm+" ставок на текущем счету.");
				noteMessBoxShow();
				messZeroBid=0;
			}

			if((htm*1)>5) messZeroBid=1;
		}
	});
	setTimeout("userBidStatus()", 3000);
}

function timeFormat(time){
	var h = 0;
	var m = time%3600;
	if(time>3600) h = (time - m)/3600;
		else h = 0;
	var s = m%60;
	if(m>=60) m = (m - s)/60;
		else m = 0;
		
	if(s<=0) s = 0;
		
		h = (h<10 ? '0'+h : h);
		m = (m<10 ? '0'+m : m);
		s = (s<10 ? '0'+s : s);					
	return h+":"+m+":"+s;
}

function noteMessBoxShow(){
	$("#messageBox").fadeIn("slow");
	noteBoxTimer = setTimeout("noteMessBoxHide()", 5000);
}
function noteMessBoxHide(){
	clearTimeout(noteBoxTimer);
	$("#messageBox").html("");
	$("#messageBox").fadeOut("slow");
}

function showAutoBidForm(lot){
	$.ajax({
		url: _url + "core/actions/autoBids.php",
		data: "action=form&lot="+lot,
		type: "POST",
		success: function(htm){
			$("#autoHistory").html(htm);
		}
	});
}
function hideAutoBidForm(lot){
	$.ajax({
		url: _url + "core/actions/autoBids.php",
		data: "action=hist&lot="+lot,
		type: "POST",
		success: function(htm){
			$("#autoHistory").html(htm);
		}
	});
}

function updAutoBid(id,lot){
	var params = new Array();
	params[0] = "pricefrom=" + $("#prfr_"+id).text();
	var prt = $("#prt_"+id).text();
	prt = (prt=="max" ? "" : prt);
	params[1] = "priceto=" + prt;
	params[2] = "bidnum=" + $("#bn_"+id).text();
	params[3] = "updid="+id;
	params[4] = "action=updform";
	params[5] = "lot=" + lot;
	
	$.ajax({
		url: _url + "core/actions/autoBids.php",
		data: params.join('&'),
		type: "POST",
		success: function(htm){
			$("#autoHistory").html(htm);
		}
	});
}

function delAutoBid(id,lot){
	var params = new Array();
	params[3] = "updid="+id;
	params[4] = "action=del";
	params[5] = "lot=" + lot;
	
	$.ajax({
		url: _url + "core/actions/autoBids.php",
		data: params.join('&'),
		type: "POST",
		success: function(htm){
			$("#autoHistory").html(htm);
		}
	});
}

function in_array(what, where) {
    var r = false;
    for(var i=0; i<where.length; i++) {
        if(what == where[i]) {
            r = true;
            break;
        }
    }
    return r;
}

function updPaymentStatus(user, time){
	var params = new Array();
	params[0] = "user=" + user;
	params[1] = "time=" + time;	
	$.ajax({
		url: _url + "core/actions/checklogpay.php",
		data: params.join('&'),
		type: "POST",
		success: function(msg){
			if(msg == "ok"){
				$("#payInfo").html("Ставки начисляются в течении нескольких минут. Если Ваш счет не был пополен на оплаченную сумму обратитесь к администратору.");
			}else{
				paymentCheckingTime++;
				if(paymentCheckingTime <= 20){
					setTimeout("updPaymentStatus('"+time+"')", 30000);
				}else{
					$("#payInfo").html("Время ожидания ответа от сервера Интеркассы истекло. Обратитесь к администратору для уточнения статуса операции зачисления ставок.");
				}
			}
		}
	});
}

function Yellow(id){ 
	var obj = (typeof id == 'undefined' ? "#ubutton" : "#price_"+id);
	$(obj).css("background-image", "url(pic/price_down_bg.gif)"); 
}
function Red(id){
	var obj = (typeof id == 'undefined' ? "#ubutton" : "#price_"+id);
	$(obj).css("background-image", "url(pic/price_bg.gif)"); 
}