$(document).ready(function(){
	//if (!$.browser.msie || $.browser.version != '6.0')
	//{
		$("#user").val('E-mail:');
		$("#user").focus(function() {
			if($(this).val() == 'E-mail:') {
				$(this).val('');
			}
		});
		$("#user").blur(function() {
			if($(this).val() == '') {
				$(this).val('E-mail:');
			}
		});
	//}
	
	setTimeout('ping()', 600000);
	refresh_items(0);
	
	// ads replacement
	$("#content_banners a").hover(
		function ()
		{
			var id = $(this).attr("id");
			$("#"+id+" img").attr("src", "upload/"+id+"c.jpg");
		},
		function ()
		{
			var id = $(this).attr("id");
			$("#"+id+" img").attr("src", "upload/"+id+".jpg");
		}
	);
	
	_uacct = "UA-4257784-1";
	urchinTracker();
	
});

function ping()
{
	setTimeout('ping()', 600000);
	$.get("functions.php", { action: "ping" } );
}

//if (!$.browser.msie || $.browser.version != '6.0')
//{
	// Note: It is known that the dss_addLoadEvent function crashes Netscape
	// versions 4.02 and older. I recommend you use a more comprehensive event 
	// management script for production (aka "live") pages.
	function dss_addLoadEvent(fn) {
	  if(typeof(fn)!="function")return;
	  var tempFunc=window.onload;
	  window.onload=function() {
	    if(typeof(tempFunc)=="function")tempFunc();
	    fn();
	  }
	}
	
	// Example 2 (JS part 1)
	function changeInputType(
	  oldElm, // a reference to the input element
	  iType, // value of the type property: 'text' or 'password'
	  iValue, // the default value, set to 'password' in the demo
	  blankValue, // true if the value should be empty, false otherwise
	  noFocus) {  // set to true if the element should not be given focus
	  if(!oldElm || !oldElm.parentNode || (iType.length<4) || 
	    !document.getElementById || !document.createElement) return;
	  var newElm = document.createElement('input');
	  newElm.type = iType;
	  if(oldElm.name) newElm.name = oldElm.name;
	  if(oldElm.id) newElm.id = oldElm.id;
	  if(oldElm.className) newElm.className = oldElm.className;
	  if(oldElm.size) newElm.size = oldElm.size;
	  if(oldElm.tabIndex) newElm.tabIndex = oldElm.tabIndex;
	  if(oldElm.accessKey) newElm.accessKey = oldElm.accessKey;
	  newElm.onfocus = function(){return function(){
	    if(this.hasFocus) return;
	    var newElm = changeInputType(this,'Password',iValue,
	      (this.value.toLowerCase()==iValue.toLowerCase())?true:false);
	    if(newElm) newElm.hasFocus=true;
	  }}();
	  newElm.onblur = function(){return function(){
	    if(this.hasFocus)
	    if(this.value=='' || (this.value.toLowerCase()==iValue.toLowerCase())) {
	      changeInputType(this,'text',iValue,false,true);
	    }
	  }}();
	 // hasFocus is to prevent a loop where onfocus is triggered over and over again
	  newElm.hasFocus=false;
	  oldElm.parentNode.replaceChild(newElm,oldElm);
	  if(!blankValue) newElm.value = iValue;
	  if(!noFocus || typeof(noFocus)=='undefined') {
	    window.tempElm = newElm;
	    setTimeout("tempElm.hasFocus=true;tempElm.focus();",1);
	  }
	  return newElm;
	}
	
	// Example 2 (JS part 2)
	dss_addLoadEvent(function(){
	  // Normally I use object detection, however, in this case since I need to 
	  // detect Konqueror and Safari which don't have unique objects,
	  // I will use the user agent string to detect them. Only use this type of 
	  // detection as a last resort.
	  // I'm doing this because example 2 crashes Konqueror and Safari and 
	  // generates errors in IE5/Mac
	
	  var ua = navigator.userAgent.toLowerCase();
	  if(!((ua.indexOf('konqueror')!=-1) && (document.all || 
	    (ua.indexOf('khtml/3.4')!=-1))) && !(((ua.indexOf('safari')!=-1) && 
	    !window.print) || (document.defaultCharset && !window.print))) {
	
	      // Set the third value to the text you want to appear in the field.
	      if(document.forms[0] && document.forms[0].pass)changeInputType( document.forms[0].pass ,'text','Password:',false,true);
	  }
	});
//}

function refresh_items(counter)
{
	//var quick_time = new Date();
	//var quick_time = quick_time.getTime();
	if (counter == 1)
	{
		/*$.ajax({
			async: false,
		  url: "tooted_timing.php",
		  success: function(data){
		  	//var quick_time2 = new Date();
		  	//var quick_time2 = quick_time2.getTime();
		  	//var time_difference = quick_time2 - quick_time;
		  	//alert(time_difference);
		    //var timing = 1000 - (time_difference) + 50 - (1000 * parseFloat(data));
		    var timing = 1000 - (1000 * parseFloat(data));
		    //alert("algne: "+data+"uus: "+timing);
		    setTimeout('refresh_items('+counter+')', timing);
		  }
		});
		//alert(timing);*/
		
		setTimeout('refresh_items('+counter+')', 1000);
	}
	else
	{
		if (counter == 10) counter = 0;
		setTimeout('refresh_items('+counter+')', 1000);
	}
	get_items();
}
function get_items()
{
	var items = $("#id_list").text();
	var get_options = '';
	if (items == '')
	{
		//if ($.browser.msie && $.browser.version == '6.0') return;
		var get_item = "time.php";
	}
	else
	{
		if ($("#choosexml").text() == "big")
		{
			var get_item = "tooted_big.php";
			get_options = 'special='+items;
		}
		else var get_item = "tooted.php";
	}
	//if ($.browser.msie)
	//{
		var quick_time = new Date();
		var quick_time = quick_time.getTime();
		if (get_options != '') get_options += "&";
		get_options += quick_time;
		//alert(get_options);
	//}
	//alert(get_options);
	var id = $("#id").text();
	var self_best = "Hetkel juhid";
	var self_winner = "Palju &otilde;nne v&otilde;idu puhul!";
	
	
	/*
a	response
b	auction_item
c	item
d	status
e	price
f	time
g	current
h	liider
i	osal
j	winner
k	statustext
l	measurement
m	current_time
n	current_time_small
	*/
	//var countertest = counter % 2;
	//if (countertest == 0)
	//{
		$.ajax({
			async: true,
			type: "GET",
		  url: get_item,
		  processData: false,
		  data: get_options,
		  error: function(XMLHttpRequest, textStatus, errorThrown)
		  {
		  	//alert("error: request: "+XMLHttpRequest+"; status: "+textStatus+"; error: "+errorThrown+";");
		  },
		  success: function(xml)
			{
				//alert("success");
				var timing = parseFloat($("n", xml).text());
				timing = 1000 - (1000 * timing);
				setTimeout('create_ctime_master()', timing);
				$("b", xml).each(function(id)
				{
					itemid = $("c", this).text();
					if ($("d", this).text() != '')
					{
						if ($("d", this).text() != '')$("#item"+itemid+"status").text($("d", this).text());
						if ($("d", this).text() == 'r') $("#item"+itemid+"activate").hide('slow');
						if ($("d", this).text() == 'r') $("#item"+itemid+"osale").attr("src", "files/bid.png");
						if ($("d", this).text() == 's')
						{
							if ($("k", this).text() != '')
							{
								$("#item"+itemid+"activate").text($("k", this).text());
								$("#item"+itemid+"activate").show('slow');
							}
						}
					}
					if ($("e", this).text() != '')
					{
						$("#item"+itemid+"price_num").text($("e", this).text());
						if (parseFloat($("e", this).text()) >= 1000) $("#pricetext"+itemid).text('');
					}
					if ($("f", this).text() != '')
					{
						$("#item"+itemid+"time_num").text($("f", this).text());
						//var time_vars = itemid+", "+$("f", this).text();
						//if ($("f", this).text() > -4) setTimeout('create_ctime('+time_vars+')', timing);
						//$("#item"+itemid+" .time_left_num").html(ctime($("f", this).text()));
					}
					if ($("g", this).text() != '') $("#item"+itemid+"current").text($("g", this).text());
					if ($("h", this).text() != '')
					{
						if ($("h", this).text() == $("#item"+itemid+"liider_id").text())
						{
							$("#item"+itemid+"current").text(self_best);
						}
					}
					if ($("i", this).text() != '') $("#item"+itemid+"product_osal").html($("i", this).text());
					if ($("j", this).text() != '')
					{
						$("#item"+itemid+"buyer").text('Ostja');
						$("#item"+itemid+"time_left").html('');
						$("#item"+itemid+"time_left_num").html($("j", this).text());
						$("#item"+itemid+"osale").attr("src", "files/bid2.png");
						$("#item"+itemid+" .toode_link").attr("href", "?5,"+itemid);
					}
				});
				if ($("m", xml).text() != '') setTimeout('create_clock("'+$("m", xml).text()+'")', timing);
			}
		});
	//}
	
	/*$(".auction_items").each(function(id)
	{
		if ($(".status", this).text() == "running")
		{
			$(".time_num", this).text($(".time_num", this).text() - 1);
			$(".item_info_time", this).html(ctime($(".time_num", this).text()));
		}
	});*/
}

function ask_offer(item_id)
{
	var tel_num = $("#telnum").text();
	var new_content = '';
	if (tel_num == '') new_content = '<p onclick="hide_alerts()">Selle teenuse kasutamiseks pead olema sisselogitud kasutaja</p>';
	else
	{
		new_content = '<p>Teenus eemaldab &uuml;he osalemiskorra sinu kontolt</p><p style="margin-top: 5px; margin-bottom: 5px;"><span class="clickable" onclick="send_offer('+item_id+')">N&otilde;ustun</span>&nbsp;&nbsp;&nbsp;<span class="clickable" onclick="hide_alerts()">Keeldun</span></p>';
	}
	$("#alerts p").html(new_content);
	$("#alerts").show("fast");
	if (tel_num == '') setTimeout('$("#alerts").hide("fast");', 3000);
}

function send_offer(item_id)
{
	$("#alerts").hide("fast");
	$.get("osale.php", {id: item_id }, function(data)
	{
		if ($("text", data).text() != '')
		{
			$("#alerts p").html($("text", data).text());
			$("#alerts").show("fast");
		}
		setTimeout('$("#alerts").hide("fast");', 5000);
		if ($("pakkumine", data).text() != '')$("#item"+item_id+"liider_id").text($("pakkumine", data).text());
		if ($("credit", data).text() != '')
		{
			$('#item_curok').text($('credit', data).text());
		}
	});
}

function hide_alerts()
{
	$("#alerts").hide("fast");
}

function create_ctime_master()
{
	$(".auction_item").each(function(id)
	{
		var itemid = $(this).attr("id").substr(4);
		var time = $("#item"+itemid+"time_num").text();
		create_ctime(itemid, time);
	});
}

function create_ctime(itemid, time)
{
	if (time > -5)
	{
	var time_str = ctime(time);
	$("#item"+itemid+"time_left_num").html(time_str);
		if(time < 0)
		{
			if (time <= -3)
			{
				$("#item"+itemid+"buyer").text('Buyer');
				$("#item"+itemid+"osale").attr("src", "files/bid2.png");
			}
			else{
				$("#item"+itemid+"time_left").html('');
			}
		}
	}
}

function create_clock(time)
{
	$("#server_time").text(time);
}

function ctime(time)
{
	var color1 = 't1';
	var color2 = 't2';
	var color3 = 't3';
	var time1 = 30;
	var time2 = 10;
	
	var result = '';
	var color = '';
	if (time < time1) {
		if (time < time2) {
			color = color3;
			if (time < 0) {
				if (time <= -3) {
					result = 'Sold!';
					return result;
				}
				else{
					result = '<span class="'+color+'">Checking</span>';
					return result;
				}

			}
		}
		else color = color2;
	}
	else color = color1;
	
	var minut = Math.floor(time/60);
	var sekund = time-minut*60;
	
	if (minut < 10) minut = '0'+minut;
	if (time < 1) sekund = '0';
	if (sekund < 10) sekund = '0'+sekund;
	
	result = result+'<span class="'+color+'">';
	result = result+minut+':'+sekund;
	result = result+'</span';
	return result;
}

function change_img (id, num)
{
	if (num == 0) num = "";
	$(".product_img #big_pic").attr("src", "upload/tood"+num+"e"+id+".jpg");
}