// JavaScript Document

// Add self to onLoad handler
addLoadHandler(function(){ menuLoad(); });

function menuLoad() {
	// Look for an appropriate div to load into
	// if that doesn't exist then load nothing
	sObjref = "navcontainerlogin";
	if(document.getElementById){ 
		var obj = document.getElementById(sObjref);
			if (obj != null) {
				sMemberMenu = getMembersMenu();
				// If the menu is empty, then leave the login
				if (sMembersMenu != "") {
					obj.innerHTML = sMembersMenu
				}
			}
	}
}


function BaseURL(sRelPath) {
	// Get the root of this website
	// and append the relative path that is supplied
	return ("http://www.acorn.net.au/" + sRelPath + "");
}

function getMembersMenu() {
	// Automatically log in if appropriate
	CheckAutoLogin();
	bLoggedIn = IsLoggedIn();
	dLastCheckTime = "TODO";
	var sMenuURL = BaseURL("membersonly") + "/inc_navbar_ex.cfm";
	// Is the information out of date?
	if ( bLoggedIn ) {
		if (true) { // (dLastCheckTime - now() > 5min) ) {
			// Update any dynamic information (new messages etc)
			// if we can
			// Get a fresh copy from the Server
			sMembersMenu = GetURL(sMenuURL);
		} else {
			// Use the existing information that is in the Cookie (as it is not very old)
			sMembersMenu = GetCookie("membersmenu");
		}
	} else {
		// Not logged in, and cannot auto login
		// TODO could use a cached version of the menu here also
		sMembersMenu = GetURL(sMenuURL);
	}
	// Strip out extra characters
	// Helps reduce the size of the cookie, and possibly helps with making it valid data to go into a cookie
	sMembersMenu = sMembersMenu.replace(/\r|\n|\r\n|\t/g, ""); // Remove line feeds and tabs
	sMembersMenu = sMembersMenu.replace(/  /g, "");	// Double spaces, not single as we want spaces between real words

	// Now 	store the menu in a cookie for next time
	SetCookie("membersmenu",sMembersMenu);
	// and return the membersMenu
	//return "<textarea rows=60 cols=60>test " + sMenuURL + " GetCookie2 = " + sMembersMenu + "</textarea>";
	//sRet = "";
	//sRet = "<plaintext>" + sMembersMenu + "</plaintext>";	
	//sRet = sRet + "<plaintext>" + GetCookie("membersmenu") + "</plaintext>";	
	//alert(sRet);
	return GetCookie("membersmenu")
}


function CheckAutoLogin() {
	if (!IsLoggedIn()) {
		//if appropriate
		// attempt to login, if autologin is set
		if (GetCookie("ACORN_PHPBB2AUTOLOGINKEY") != null) {
			sResult = GetURL(BaseURL() + "forums/groupcp.php");
			// Now we are logged in and cookies should be set
			// New message count cookies should now be up to date
			// All done, return with no result 
		} else {
			sResult = "No Auto Login Key Found";
		}
	} else {
		sResult = "Already Logged in";
	}
	// Nothing to return
	// All done here
	// debug in sResult if you like
	//alert(sResult);
}

function IsLoggedIn() {
	// Based on Cookies
	// acorn_phpbb2autologinkey
	return (GetCookie("ACORN_PHPBB2AUTOLOGINKEY") != null )
}

function GetURL(sURL) {
	var sReturn = "";
	// A Blocking request
	document.body.style.cursor='wait';
	var httpRequest;
	if (window.XMLHttpRequest) {
		httpRequest = new XMLHttpRequest();
		httpRequest.open('GET', sURL, false);
		httpRequest.send(null);
	}
	else if (window.ActiveXObject) {
	   httpRequest = new ActiveXObject('Msxml2.XMLHTTP');
		httpRequest.open('GET', sURL, false);
		httpRequest.send();
	}

	if (httpRequest.statusText == "OK") {
		sReturn = httpRequest.responseText;
	} else {
		sReturn = httpRequest.statusText + sURL;
	}
  /*  The following fields can be used:
   objHTTP.status;
   objHTTP.statusText;
   objHTTP.responseText;
   objHTTP.responseXML;
   objHTTP.responseXML.nodeName;
  */
	document.body.style.cursor='auto';
	return sReturn;
}

/**
 * Read the JavaScript cookies tutorial at:
 *   http://www.netspade.com/articles/javascript/cookies.xml
 */

/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
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" : "");
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function GetCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function DeleteCookie(name, path, domain)
{
    if (getCookie(name))
    {
        document.cookie = name + "=" + 
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}
