/**
 * Function for locking objects
 */

// http://www.quirksmode.org/js/cookies.html
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return decodeURIComponent( c.substring(nameEQ.length,c.length) );
	}
	return null;
}

function getXmlHttpRequest()
{
	try
	{
		// Firefox, Opera 8.0+, Safari
		return new XMLHttpRequest();
	}
	catch (e)
	{
		try
		{
			// Internet Explorer
			return new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				return new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
			}
		}
	}
	return null;
}

function lockObject( id )
{
	revokeLock( id );
	var xmlHttp = getXmlHttpRequest();
	xmlHttp.open("GET", "/objects/lock/"+id, false); // synchronous request 
	xmlHttp.send(null);
	if (xmlHttp.status == 200)
	{
		if (xmlHttp.responseText == '1')
		{
			return true;
		}
		alert( xmlHttp.responseText );
	}
	return false;
}

function renewLock( id )
{
	revokeLock( id );
	var xmlHttp = getXmlHttpRequest();
	xmlHttp.open("GET", "/objects/renew/"+id, true); // synchronous request 
	xmlHttp.send(null);	
	setTimeout("renewLock("+id+")", 120000); // 2 minutes
	return true;
}

function releaseLock( id )
{
	var locks = readCookie( "lock_release" );
	if( locks === null || locks == "" )
	{
		locks = "";
	}
	else
	{
		locks += ",";
	}
	locks += id;
	document.cookie = "lock_release=" + encodeURIComponent( locks ) + "; path=/";
}

function revokeLock( id )
{
	var locks = readCookie( "lock_release" );
	if( locks !== null )
	{
		var newLocks = [];
		var lockArr = locks.split( "," );
		for( var i = 0; i < lockArr.length; i++ )
		{
			if( lockArr[i] != id )
			{
				newLocks.push( lockArr[i] ); 
			}
		}
		document.cookie = "lock_release=" + encodeURIComponent( newLocks.join( "," ) ) + "; path=/";
	}
}

function processPendingLocks()
{
	var locks = readCookie( "lock_release" );
	if( locks !== null )
	{
		var lockArr = locks.split( "," );
		for( var i = 0; i < lockArr.length; i++ )
		{
			var xmlHttp = getXmlHttpRequest();
			xmlHttp.open( "GET", "/objects/release/" + lockArr[i], true ); 
			xmlHttp.send( null );	
		}
	}
	document.cookie = "lock_release=; path=/; expires=" + ( new Date() ).toGMTString();
}

