String.prototype.trim = function ()
{
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

String.prototype.filter = function(legal)
{
	var i;
	var ret = "";
	for (i=0;i<this.length;i++)
	{
		if (legal.indexOf(this.substr(i, 1)) >= 0)
		{
			ret += this.substr(i, 1);
		}
	}
	return ret;
}

// Return random element of an array.
Array.prototype.rand = function()
{
	return this[Math.floor(Math.random()*this.length)];
}

// Return value in array appearing
// after value 'current'.  If current
// not found or last in array, first value
// in array is returned.
Array.prototype.after = function(current)
{
	var i;
	var found = false;
	var ret = this[0];
	for (i=0;i<this.length;i++)
	{
		if (found)
		{
			ret = this[i];
			break;
		}
		if (this[i] == current)
		{
			found = true;
		}
	}
	return ret;
}

function tick()
{
	if (seconds < 2)
	{
		clearInterval(turntimer);
		$('span#timer').html('<a href=\"'+document.location+'\">next turn is ready!</a>');
		document.title = 'Other World (next turn ready)';
	} else {
		seconds--;
		var min = Math.floor(seconds/60);
		var sec = seconds%60;
		if (sec < 10)
		{
			sec = "0"+sec;
		}
		$('span#timer').html(min+':'+sec);
		document.title = 'Other World ('+min+':'+sec+' until turn)';
	}
		
}

// Grey screen and open AJAX pop-up
function popWin(url)
{
	$('body').append('<div class="mask"></div><div class="popwin" id="popwin">loading...</div>');
	$('div#popwin').load(url);
}

function popClose()
{
	$('div.mask').remove();
	$('div.popwin').remove();
}

function prep()
{
	// Initialize turn countdown.
	if ($('span#timer').length > 0)
	{
		turntimer = setInterval('tick()', 1000);
	}
}

gear_ID = 0;
gear_target = false;
function gearOut()
{
	gear_ID = 0;
	gear_target = false;
	$('div#floaty').hide();
}

function gearOver(new_gear_ID, target)
{
	gear_target = target;
	gear_ID = new_gear_ID;
	$.post("gear_detail.php", { gear_ID:new_gear_ID },
		function(data)
		{
			if (gear_ID != 0)
			{
				var floaty = $('div#floaty');
				floaty.html(data);
				var offset = $(gear_target).offset();
				floaty.css('top', offset.top+30);
				floaty.css('left', offset.left);
				floaty.show();
			}
		});
}

function addFriend(character_ID)
{
	popWin('addfriend.php?character_ID='+character_ID+'&next='+escape(document.location));
}

