var millisecs_per_hour = 60 * 60 * 1000;

var tim_cookie_name = "tim_cookie";
var tim_cookie_user;
var tim_cookie_subuser;
var tim_cookie_password;
var tim_cookie_access;

function getCookie( name ) {

	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) return null;
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );

}

function setCookie( name, value, expires, path, domain, secure ) {

	document.cookie = name + "=" + escape( value ) + 
			( ( expires ) ? ";expires=" + expires.toGMTString() : "" ) +
			( ( path ) ? ";path=" + path : "" ) +
			( ( domain ) ? ";domain=" + domain : "" ) +
			( ( secure ) ? ";secure" : "" );
	var temp_cookie = getCookie( name );
	if ( !temp_cookie || temp_cookie != value ) return false;
	return true;

}

function deleteCookie( name, path, domain ) {

	var today = new Date();
	var expire_date = new Date( today.getTime() - ( 48 * millisecs_per_hour ) );  // 2 days ago
	if ( getCookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "" ) +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=" + expire_date.toGMTString();

}

function setTimCookie( user, subuser, password, access, expire_hours ) {

	var today = new Date();
	var expire_date = new Date( today.getTime() + expire_hours * millisecs_per_hour );

	var tim_cookie = user + ':' + subuser + ':' + password + ':' + access + ':';

	if ( !setCookie( tim_cookie_name, tim_cookie, expire_date, '/' ) ) return false;
	return true;

}

function getTimCookie() {

	var tim_cookie = getCookie( tim_cookie_name );
	if ( !tim_cookie ) return false;

	//separate out the user, subuser, password and access_allowed
	var first_colon = tim_cookie.indexOf( ':' );
	var second_colon = tim_cookie.indexOf( ':', first_colon + 1 );
	var third_colon = tim_cookie.indexOf( ':', second_colon + 1 );
	var fourth_colon = tim_cookie.indexOf( ':', third_colon + 1 );

	//alert('first_colon = '+ first_colon + ' second colon= ' + second_colon + ' third colon=' + third_colon + 'fourth_colon =' + fourth_colon );

	tim_cookie_user = tim_cookie.substring( 0, first_colon );
	tim_cookie_subuser = tim_cookie.substring( first_colon + 1, second_colon );
	tim_cookie_password = tim_cookie.substring( second_colon + 1, third_colon );
	tim_cookie_access = tim_cookie.substring( third_colon + 1, fourth_colon );

	//alert('user = ' + tim_cookie_user + ' subuser = ' + tim_cookie_subuser + ' passwd = ' + tim_cookie_password + ' access =' + tim_cookie_access);

	return true;

}