setSubmitEvents();
check_autobid_settings();
setInterval("adjustValues()", 1000);

function xhr(url, callbackFunction)
{
	this.request = null;
	this.url = url;
	this.callbackFunction = callbackFunction;

	this.connect = function(url, callbackFunction) 
	{
		if (this.request == null)
		{
			try 
			{
				this.request = new XMLHttpRequest();
			} 
			catch (e) 
			{
				try 
				{
					this.request = new ActiveXObject("Msxml2.XMLHTTP");
				} 
				catch (e) 
				{
					try 
					{
						this.request = new ActiveXObject("Microsoft.XMLHTTP");
					} 
					catch (e) 
					{
						return false;
					}
				}
			}
		}

		this.request.open("GET", this.url + "&time=" + new Date().getTime(), true);
		this.request.onreadystatechange = this.callbackFunction;
		this.request.send(null);
	}

	this.response = function()
	{
		return this.request.responseText;
	}

	this.state = function()
	{
		return this.request.readyState;
	}

	this.disconnect = function()
	{
		this.request.abort();
	}

	this.connect();
}

function iframe(url, updateFunction, reloadFunction, IE)
{
	this.subDoc = null;
	this.iframe = null;
	this.url = url;
	this.id = 0;

	this.connect = function()
	{
		if (IE == true)
		{
			if (this.subDoc == null)
			{
				this.subDoc = new ActiveXObject('htmlfile');
				this.subDoc.open();
				this.subDoc.write('<html></html>');
				this.subDoc.close();

				this.subDoc.parentWindow.updateData = updateFunction;
				this.subDoc.parentWindow.reload = reloadFunction;
			}
			else
			{
				this.subDoc.removeChild(this.iframe);
				this.id += 1;
			}

			this.iframe = this.subDoc.createElement('<iframe id="iframe-' + this.id + '" src="' + 
				this.url + "&time=" + new Date().getTime() + '"></iframe>');
			this.subDoc.appendChild(this.iframe);
		}
		else
		{
			if (this.iframe != null)
				document.body.removeChild(this.iframe);

			this.iframe = document.createElement('iframe');
			this.iframe.width = 0;
			this.iframe.height = 0;
			this.iframe.vspace = 0;
			this.iframe.hspace = 0;
			this.iframe.frameborder = 0;
			this.iframe.style.visibility = "hidden";
			this.iframe.onload = prepareIFrame;
			this.iframe.src = this.url + "&time=" + new Date().getTime();
			document.body.appendChild(this.iframe);
		}
	}

	this.disconnect = function()
	{
		if (IE == true)
			this.subDdoc = null;
	}

	this.connect();
}

timeParts = {
	hours : 0,
	mins : 1,
	secs : 2
}

priceIndexes = Array(3, 6, 9, 12, 15, 18, 21, 24, 27, 30);
leaderIndexes = Array(4, 7, 10, 13, 16, 19, 22, 25, 28, 31);
typeIndexes = Array(5, 8, 11, 14, 17, 20, 23, 26, 29, 32);
u_actions = Array('a','b','f','r');

if (location.pathname.search('/en/') > -1)
	bioPath = '/en/accounts/bio/?user=';
else if (location.pathname.search('/fr/') > -1)
	bioPath = '/fr/accounts/bio/?user=';
else
	bioPath = '/en/accounts/bio/?user=';

receiverURL = "/python/receiver.py?ucriteria=";

function updateConnect() 
{
	if (onPage == false)
		return;

	ttlCount = 0;
	boundary = 0;

	var url = receiverURL + auctionStr + "u" + user_id;

	// Reusing XHR objects does not work
	if (navigator.userAgent.match("Firefox") || navigator.userAgent.match(/webkit/gi)
		|| navigator.userAgent.match("Presto"))
	{
		updateRequest = new xhr(url, updateReconnect);
		state3 = true;
	}
	else if (navigator.userAgent.match("MSIE"))
	{
		if (updateIFrame == null)
			updateIFrame = new iframe(url, updateData, prepareIFrame, true);
		else
			updateIFrame.connect();

		IFrameReload = false;
	}
	else
	{
		if (updateIFrame == null)
			updateIFrame = new iframe(url, updateData, prepareIFrame, false);
		else
			updateIFrame.connect();

		IFrameReload = false;
	}
}

function updateReconnect()
{
	if (updateRequest.state() == 4) 
	{
		response = updateRequest.response();
		updateResponse = response.substr(boundary, response.length - boundary)
		processed = true;
		boundary = 0;
	}
	else if (updateRequest.state() == 3)
	{
		response = updateRequest.response();
		updateResponse = response.substr(boundary, response.length - boundary)
		processed = true;
	}
}

function disconnect(present)
{
	if (present == null)
		onPage = false;

	if (auctionStr != "")
	{
		if (updateRequest != null)
			updateRequest.disconnect();

		if (updateIFrame != null)
			updateIFrame.disconnect();
	}
}

function updateData(data)
{
	if (data.match(";"))
	{
		updateResponse += data;
		processed = true;
	}
}

function prepareIFrame()
{
	IFrameReload = true;
}

function removeFromRunningAuctions(auction_id)
{
	var auctionStrTemp = auctionStr.split("a");
	auctionStr = "a";

	for (var i = 0; i < auctionStrTemp.length; i++)
	{
		if ((auctionStrTemp[i] != auction_id) && (auctionStrTemp[i].length > 0))
			auctionStr += ("" + auctionStrTemp[i] + "a");
	}

	var bidStrTemp = bidStr.split("a");
	bidStr = "a";

	for (var i = 0; i < bidStrTemp.length; i++)
	{
		if ((bidStrTemp[i] != auction_id) && (bidStrTemp[i].length > 0))
			bidStr += ("" + bidStrTemp[i] + "a");
	}
}

function adjustValues()
{
	if (processed == true)
	{
		processed = false;
		var ret = updateResponse.split(";");

		// updates always start and end with ';'
		for (var i = 1; i < ret.length - 1; i++)
		{
			if (ret[i] == '')
				continue;

			processUpdate(ret[i]);
		}
	}

	// On page load, start background connection
	if ((updateRequest == null) && (updateIFrame == null))
	{
		updateConnect();
	}

	// Specifically for IE, to instruct that everything has been processed
	updateResponse = "";

	// Soft reload timer
	ttlCount++;
	reloadCount = 0;

	// Call timer for each running auction
	if (exists(auctionStr) && (auctionStr.length > 0))
	{
		// Chop the user section at the end
		// The previous part contains the auction ids
		temp = auctionStr.split("u");
		ids = temp[0].split("a");

		for (i = 0; i < ids.length; i++)
		{
			if (ids[i] != '')
				timer(ids[i]);
		}
	}

	// Ajax connection stopped running, reload it
	if (state3 == true)
	{
		// Change the boundary only once everything
		// has been processed
		boundary = updateRequest.response().length;

		if (updateRequest.state() == 4)
		{
			disconnect(true);
			updateConnect();
		}
	}
	else
	{
		if (IFrameReload == true)
			updateConnect();
	}

	// Soft reload
	if (ttlCount > ttl)
	{
		if (reloadCount == auctionStr.split('a').length - 2)
		{
			disconnect(true);
			updateConnect();
		}
	}
}

function processUpdate(updateStr)
{
	// Field 0: action
	// Field 1: auction_id
	var subRet = updateStr.split("+");

	// Update an auction
	if (contains(u_actions, subRet[0]))
	{
		var leaderNode;

		// Server never mentions m or not
		if (auctionStr.match("m" + subRet[1] + "a"))
		{
			if (subRet[0] == 'f')
				removeFromRunningAuctions("m" + subRet[1])

			document.getElementById("mtime").firstChild.nodeValue = gettext(subRet[2]);

			for (j = 0; j < 10; j++)
			{
				if (subRet[priceIndexes[j]] != "")
					subRet[priceIndexes[j]] = "$ " + subRet[priceIndexes[j]];
			}

			if (document.getElementById("mprice").firstChild.nodeValue != subRet[3])
			{
				document.getElementById("mprice").firstChild.nodeValue = subRet[3];

				if (subRet[0] != 'r')
					$("#mprice").animate({backgroundColor:"violet"},200).animate({backgroundColor:"white"},600);
			}

			if (subRet[3] == '')
				document.getElementById("mprice").firstChild.nodeValue = '$ 0.00';

			for (j = 0; j < 10; j++)
			{
				leaderNode = document.getElementById("mleader" + (j + 1)).firstChild;
				leaderNode.firstChild.nodeValue = subRet[leaderIndexes[j]];
				leaderNode.setAttribute('href', bioPath + subRet[leaderIndexes[j]]);

				document.getElementById("mprice" + (j + 1)).firstChild.nodeValue = 
					subRet[priceIndexes[j]];
				if (subRet[typeIndexes[j]] == "u")
					document.getElementById("mtype" + (j + 1)).firstChild.nodeValue = 
						"Manual";
				else if ((subRet[typeIndexes[j]] == "a") || (subRet[typeIndexes[j]] == "d"))
					document.getElementById("mtype" + (j + 1)).firstChild.nodeValue = 
						"SpaceBidder";
			}
			check_autobid_settings();
		}
		else if (auctionStr.match("a" + subRet[1] + "a"))
		{
			if (subRet[0] == 'f')
				removeFromRunningAuctions(subRet[1])

			if (subRet[0] == 'v')
			{
				removeFromRunningAuctions(subRet[1])
				subRet[2] = "Price too low";
			}

			document.getElementById("time-" + subRet[1]).firstChild.nodeValue = gettext(subRet[2]);
			document.getElementById("leader-" + subRet[1]).firstChild.nodeValue = subRet[4];

			// Only run this if the value changed
			if (document.getElementById("price-" + subRet[1]).firstChild.nodeValue != "$ " + subRet[3])
			{
				document.getElementById("price-" + subRet[1]).firstChild.nodeValue = "$ " + subRet[3];
				if (subRet[0] != 'r')
					$("#price-" + subRet[1]).animate({backgroundColor:"violet"},200).animate({backgroundColor:"white"},600);
			}

			if (subRet[3] == '')
				document.getElementById("price-" + subRet[1]).firstChild.nodeValue = "$ 0.00";
		}
	}
	// Update the autobid
	else if (subRet[0] == "z")
	{
		if (auctionStr.match("am" + subRet[1] + "a"))
		{
			autobidNode = document.getElementById("autobidAmount");

			if (autobidNode != null)
				autobidNode.firstChild.nodeValue = subRet[subRet.length - 1];
		}
	}
}

function timer(auction_id)
{
	if (auction_id.substr(0, 1) != "m")
		var time = document.getElementById("time-" + auction_id).firstChild.nodeValue;
	else
		var time = document.getElementById("mtime").firstChild.nodeValue;

	 if ((time != "Soon") && (time > "00:00:01"))
	 {
		var timeElems = time.split(":");

		for (i = 0; i < 3; i++)
		{
			if (timeElems[i].substr(0, 1) != "0")
				timeElems[i] = parseInt(timeElems[i], 10);
			else
			{
				timeElems[i] = timeElems[i].substr(1, 1);
				timeElems[i] = parseInt(timeElems[i], 10);
			}
		}

		if (timeElems[timeParts.secs] == 0)
		{
			timeElems[timeParts.secs] = 59;
			if (timeElems[timeParts.mins] == 0)
			{
				timeElems[timeParts.mins] = 59;
				timeElems[timeParts.hours] -= 1;
			}
			else
				timeElems[timeParts.mins]--;
		}
		else
			timeElems[timeParts.secs]--;

		for (i = 0; i < 3; i++)
		{
			if (timeElems[i] < 10)
				timeElems[i] = "0" + timeElems[i];
			else
				timeElems[i] = "" + timeElems[i];
		}

		time = timeElems.join(":");

		if (auction_id.substr(0, 1) != "m")
		{
			document.getElementById("time-" + auction_id).firstChild.nodeValue = time;

			if (time > ("00:00:" + reloadThreshold))
				reloadCount++;
			
			if (time < "00:00:10")
			{
				document.getElementById("time-" + auction_id).style.color = "#ff0000";
			} else 
			{
				document.getElementById("time-" + auction_id).style.color = "#000";
			}
		}
		else {
			document.getElementById("mtime").firstChild.nodeValue = time;
		
			if (time > ("00:00:" + reloadThreshold))
				reloadCount++;
	
			if (time <= "00:00:10")
			{
				document.getElementById("mtime").style.color = "#ff0000";
			} else 
			{
				document.getElementById("mtime").style.color = "#000";
			}	
		}
 	}
}

function favorite(auction_id, user_id)
{
	var favRequest; 

	favoriteReply = function()
	{
		if (favRequest.state() == 4) {
			favResponse = favRequest.response();
			if (favResponse == "added")
			{
				text = "Remove";
			}
			else if (favResponse == "removed")
			{
				text = "Add to";
			}
			document.getElementById("watch-" + auction_id).firstChild.nodeValue = text;
		}

	}

	favRequest = new xhr("/favorite.php?auction_id=" + auction_id + "&user_id=" + user_id + "&salt=" 
			+ salt +  "&time=" + new Date().getTime(), favoriteReply);
}

function bid(auction_id, user_id)
{
	if (user_id == -1)
		return 0;

	if (bidStr.match("a" + auction_id + "a") == null)
		return 0;

	auction_id = "" + auction_id;
	if (auction_id.substr(0, 1) == "m")
		auction_id = auction_id.substr(1,auction_id.length);

	var bidRequest;

	bidReply = function()
	{
		if (bidRequest.state() == 4) {
			bidResponse = bidRequest.response();
			if (bidResponse != "0")
			{
				var bidAmount = document.getElementById("bidAmount").firstChild.nodeValue;
				bidAmount = parseInt(bidAmount, 10);
				spent = parseInt(bidResponse, 10);
				bidAmount -= spent;

				document.getElementById("bidAmount").firstChild.nodeValue = bidAmount;
			}
		}
	}

	bidRequest = new xhr("/python/generator.py?auction_id=" + auction_id + "&user_id=" + user_id + "&salt=" + salt, bidReply);
}

function check_autobid_settings()
{
	fNodes = document.getElementsByName('unset_autobid');

	if (fNodes.length > 0)
	{
		var current_price = document.getElementById("mprice").firstChild.nodeValue;
		current_price = parseFloat(current_price.substr(2, current_price.length));

		var bid_to = document.getElementById("bid_to").firstChild.nodeValue;
		bid_to = parseFloat(bid_to.substr(2, bid_to.length));

		var bid_from = document.getElementById("bid_from").firstChild.nodeValue;
		bid_from = parseFloat(bid_from.substr(2, bid_from.length));

		if (current_price > bid_to)
			document.getElementById("bid_to").style.color = "#ff0000";

		if (current_price < bid_from)
			document.getElementById("bid_from").style.color = "#0000ff";
		else
			document.getElementById("bid_from").style.color = "#000000";
	}
}

function addInputSubmitEvent(form, input)
{
	input.onkeydown = function(e) 
	{
		e = e || window.event;
		if (e.keyCode == 13) 
		{
			form.submit();
			return false;
		}
	};
}

function setSubmitEvents() 
{
	var forms = document.getElementsByTagName('form');

	for (var i = 0; i < forms.length; i++) 
	{
		var inputs = forms[i].getElementsByTagName('input');

		for (var j = 0; j < inputs.length; j++)
			addInputSubmitEvent(forms[i], inputs[j]);
	}
}

function contains(a, obj) 
{
	for (var i = 0; i < a.length; i++)
	{
		if (a[i] == obj)
			return true;
	}
	return false;
}

function handleError(description, pagename, lineno)
{
	var errorStr = description + ", in page " + pagename + ", on line " + lineno;
	var expiration = new Date();
	// Add 30 days to today's date
	expiration.setDate(expiration.getDate() + 30);
	document.cookie = 'lastError=' + errorStr + '; expires=' + expiration.toUTCString() + '; path=/;';
}

function exists(a)
{
	if (typeof(a) == 'undefined')
		return false;
	else
		return true;
}

window.onerror = handleError;
window.onunload = disconnect;
window.onload = function() {
	onPage = true;
}


