var debug = getCookie("debug");

//  Allow this website to be accessed by www.overseassingaporean.sg only.
if (document.location.href.indexOf("www.overseassingaporean.sg") < 0
&& document.location.href.indexOf("devforum1") < 0)
{
        document.location.href = "http://www.overseassingaporean.sg";
}

//  If URL is of the form http://server/forums/index.php?http://server/..., redirect to http://server/...
if (document.location.href.indexOf("/forums/index.php?http://") >= 0)
{
	var httpPos = document.location.href.indexOf("?http://");
	httpPos = httpPos + 1;
	var redirectURL = document.location.href.substring(httpPos);
	document.location.href = redirectURL;
}

//  If URL is of the form http://server/forums/index.php?...&http://server/..., redirect to http://server/...
if (document.location.href.indexOf("/forums/index.php?") >= 0 &&
	document.location.href.indexOf("&http://") >= 0)
{
	var httpPos = document.location.href.indexOf("&http://");
	httpPos = httpPos + 1;
	var redirectURL = document.location.href.substring(httpPos);
	document.location.href = redirectURL;
}

//  Redirect to proper target after login.
var loginRedirect = getCookie("loginRedirect");
if (loginRedirect != null && loginRedirect != "" && 
	(document.location.href.indexOf("/forums/index.php?&&CODE=00") >= 0 ||
	document.location.href.indexOf("/forums/index.php?&CODE=00") >= 0 ||
	document.location.href.indexOf("/forums/index.php?&CODE=03") >= 0))
{
	deleteCookie("loginRedirect", "/", null);
	document.location.href = loginRedirect;
}

//  Redirect to proper target after logout.
var logoutRedirect = getCookie("logoutRedirect");
if (logoutRedirect != null && logoutRedirect != "")
{
	deleteCookie("logoutRedirect", "/", null);
	deleteCookie("coppa", "/", null);
	document.location.href = logoutRedirect;
}

var userID = "";
var adminStatus = "";
var md5Key = "";
var loggedIn = false;
var notLoggedInMessage1 = '\
      Already a member? <A  \
      href="https://' + getServer() + '/forums/index.php?act=Login&amp;CODE=00">Log in</A> \
';
var notLoggedInMessage2 = '\
      If not, <A  \
      href="https://' + getServer() + '/forums/index.php?act=Reg&amp;CODE=00">Sign up here</A> \
';
var loggedInMessage1 = 'Welcome ';
var loggedInMessage2 = '<span id="adminFunction" style="display:none"><a href="">Admin</a> | </span>\
<a href="https://' + getServer() + '/forums/index.php?act=UserCP&amp;CODE=01">Update profile</a> | \
<a href="javascript:logout(\'%md5Key%\')">Log out</a>';

var loginBoxPrompt = ' \
            <form id="form2" name="form2" method="post" onsubmit="return validateLogin()" action="https://' + getServer() + '/forums/index.php?act=Login&amp;CODE=01"> \
          <table width="100%" border="0" cellpadding="0" cellspacing="0"> \
            <tr> \
              <td width="41%" height="37" align="right" valign="middle"><strong>Username:&nbsp;</strong> </td> \
              <td width="59%" valign="middle"><label> \
                <input id="UserName" name="UserName" type="text" size="15" maxlength="50" style="width:120px" /> \
              </label></td> \
            </tr> \
            <tr> \
              <td align="right" valign="middle"><strong>Password:&nbsp;</strong></td> \
              <td valign="middle"><input id="PassWord" name="PassWord" type="password" size="16" maxlength="50" style="width:120px" /></td> \
            </tr> \
            <tr> \
              <td height="29" align="right">&nbsp;</td> \
              <td align="left" valign="bottom"> \
<input type="hidden" name="referer" value="' + document.location.href + '" /> \
<input type="submit" name="Submit" value="Log me in" /> \
</td> \
            </tr> \
            <tr> \
              <td height="29" align="right">&nbsp;</td> \
              <td align="left" valign="top"> \
                <a href="/forums/index.php?act=Reg&amp;CODE=00" class="loginLink"><img src="content/arrow_white.gif" width="9" height="5" border="0" />Sign Up</a><br /> \
                <a class="loginLink" href="/forums/index.php?act=Reg&amp;CODE=10"><img src="content/arrow_white.gif" width="9" height="5" border="0" />Forgot Password?</a> <br> \
                <!-- added on 20060928 --> \
                <a class="loginLink" href="/forums/index.php?act=Reg&amp;CODE=13"><img src="content/arrow_white.gif" width="9" height="5" border="0" />Forgot Username?</a></td> \
		<!-- added on 20060928 --> \
            </tr> \
          </table> \
	    </form> \
';

var loginBoxContent = loginBoxPrompt;

function logout(md5Key)
{
	//  Always logout to home page.
	setCookie("logoutRedirect", "/", null, "/", null, null);
	document.location.href = "/forums/index.php?act=Login&CODE=03&k=" + md5Key;
}

if (document.location.href.indexOf("calendar2.htm") < 0) {}

if (document.cookie.indexOf("coppa=") < 0)
{
	loggedIn = false;
	deleteSessionCookies();
	if (document.location.href.indexOf("mainloginrequired=y") >= 0)
	{
		setCookie("loginRedirect", document.location.href, null, "/", null, null);
		document.location.href = "/forums/index.php?act=Login&CODE=00"; //&referer=" + document.location.href;
	}
	else if (document.location.href.indexOf("act=Login&CODE=autologin&fromreg=1") >= 0 || 
		document.location.href.indexOf("act=Reg&CODE=05") >= 0)
	{
		//  If user clicked on validation link, bring user to home page after login.
		setCookie("loginRedirect", "/", null, "/", null, null);
	}
}
else
{
	loginBoxContent = "";
	loggedIn = true;
	//  Make an AJAX call to get user ID and admin status.
	loadFlip1();
}

document.write('\
<DIV id=Masthead> \
<TABLE id=Logo cellSpacing=0 cellPadding=0 width=510 border=0> \
  <TBODY> \
  <TR> \
    <TD><a href="/"><img src="/content/blank.gif" width=500 height=70 border=0></a></TD> \
  </TR></TBODY></TABLE> \
<TABLE id=Login cellSpacing=0 cellPadding=0 border=0> \
  <TBODY> \
  <TR> \
    <TD id=loginLine1 vAlign=bottom align=right> \
');

if (!loggedIn)
{
    document.write(notLoggedInMessage1);
}
else
{
    document.write('&nbsp;');
}

document.write('\
    </TD></TR> \
  <TR> \
    <TD id=loginLine2 vAlign=top align=right> \
');

if (!loggedIn)
{
    document.write(notLoggedInMessage2);
}
else
{
    document.write('&nbsp;');
}

document.write('\
    </TD></TR> \
  <TR> \
    <FORM id=form1 name=form1 action="/search/search.jsp" method=get> \
    <TD align=right> \
      <div style="visibility:hidden"><a href="http://www.opencube.com">OpenCube CSS Menu</a></div> \
      <LABEL>Search: <INPUT class=inputSearch  \
      id=query onfocus=searchTextFocus(this) \
      value="Search a keyword" name=query> <INPUT class=goButton id=Go type=submit value=Go name=Go> \
    </LABEL></TD></FORM></TR></TBODY></TABLE> \
</DIV> \
');

function getServer()
{
	return document.location.href.split("/")[2];
}

var flipReq1;

function loadFlip1()
{
	var server = document.location.href.split("/")[2];
	var url = document.location.protocol + "//" + server + "/forums/getuser.php";
	url = url + "?hash=" + Math.random();
	loadFlipDoc1(url);
}

function loadFlipDoc1(url) {
	flipReq1 = false;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest) {
    	try {
			flipReq1 = new XMLHttpRequest();
        } catch(e) {
			flipReq1 = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
       	try {
        	flipReq1 = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		flipReq1 = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		flipReq1 = false;
        	}
		}
    }
	if(flipReq1) {
		flipReq1.onreadystatechange = processFlipReqChange1;
		flipReq1.open("GET", url, true);
		flipReq1.send("");
	}
}

function processFlipReqChange1() {
    try {
    // only if req shows "loaded"
    if (flipReq1.readyState == 4) {
        // only if "OK"
        if (flipReq1.status == 200) {
            // Show counter values.
	    var responseText = flipReq1.responseText;
	    var re = /\r/g;
	    responseText = responseText.replace(re, "");
	    responseList = responseText.split("|");
	    userID = responseList[0];
            adminStatus = responseList[1];
            md5Key = responseList[2];
            var group = responseList[3];

            //  If the user has not been validated, log him out.
            if (group == "1")
            {
                alert("Your account has not been validated. Please check your email for instructions.");
                logout(md5Key);
		return;
            }

	    var loginLine1 = document.getElementById("loginLine1");
	    var loginLine2 = document.getElementById("loginLine2");
	    var loginBox = document.getElementById("loginBox");
	    if (userID != "Guest")
	    {
		//  Logged in.
	    	re = /%md5Key%/g;
	    	loggedInMessage2 = loggedInMessage2.replace(re, md5Key);
	    	if (loginLine1) loginLine1.innerHTML = loggedInMessage1 + userID + 
			'<img width=1 height=1 src="/calendar/account.php?action=loginProcess&from=myDatesLogin&sessionRandomSeed=' +
			getCookie("session_id") + '">';
	    	if (loginLine2) loginLine2.innerHTML = loggedInMessage2;  //  TODO: Handle admin status.
		//if (loginBox) loginBox.innerHTML = "<div align=center>Welcome " + userID + "</div>";

		//  If browsing calendar and not logged in to calendar, log in to calendar.
		if (document.location.href.indexOf("calendarloginrequired=y") >= 0 &&
			(getCookie("calendarmyDates") == null || getCookie("calendarmyDates") == ""))
		{
			if (document.location.href.indexOf("/calendar/calendar.php") < 0)
			{
				setCookie("calendarRedirect", document.location.href, null, "/", null, null);
			}
			document.location.href = "/calendar/account.php?action=loginProcess&from=myDatesLogin&sessionRandomSeed=" +
				getCookie("session_id");
		}

		//  If in calendar page and logged in calendar and calendarRedirect cookie is set,
		//  go to the calendarRedirect.
		var calendarRedirect = getCookie("calendarRedirect");
		if (document.location.href.indexOf("/calendar/calendar.php") >= 0 &&
			(calendarRedirect != null && calendarRedirect != "") && 
			(getCookie("calendarmyDates") != null && getCookie("calendarmyDates") != ""))
		{
			deleteCookie("calendarRedirect", "/", null);
			document.location.href = calendarRedirect;
		}

		//  Get PM.
		if (document.getElementById("homepage")) loadFlip2();
	    }
	    else
	    {
		//  Not logged in.
		deleteSessionCookies();
	    	if (loginLine1) loginLine1.innerHTML = notLoggedInMessage1 + "&nbsp;";
	    	if (loginLine2) loginLine2.innerHTML = notLoggedInMessage2;
		if (loginBox) { loginBox.innerHTML = loginBoxPrompt; loginBoxContent = loginBoxPrompt; }
		if (document.location.href.indexOf("mainloginrequired=y") >= 0)
		{
			setCookie("loginRedirect", document.location.href, null, "/", null, null);
			document.location.href = "/forums/index.php?act=Login&CODE=00";
		}
	    }
        } 
        else 
        {
        }
    }
    } catch(e) {}
}

var flipReq2;

function loadFlip2()
{
	var server = document.location.href.split("/")[2];
	var url = document.location.protocol + "//" + server + "/forums/index.php?s=&act=buddy&xml=1&tab=pms";
	url = url + "&hash=" + Math.random();
	loadFlipDoc2(url);
}

function loadFlipDoc2(url) {
	flipReq2 = false;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest) {
    	try {
			flipReq2 = new XMLHttpRequest();
        } catch(e) {
			flipReq2 = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
       	try {
        	flipReq2 = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		flipReq2 = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		flipReq2 = false;
        	}
		}
    }
	if(flipReq2) {
		flipReq2.onreadystatechange = processFlipReqChange2;
		flipReq2.open("GET", url, true);
		flipReq2.send("");
	}
}

function processFlipReqChange2() {
    try {
    // only if req shows "loaded"
    if (flipReq2.readyState == 4) {
        // only if "OK"
        if (flipReq2.status == 200) {
            // Show counter values.
	    var responseText = flipReq2.responseText;
	    var loginBox = document.getElementById("loginBox");
	    if (loginBox)
	    {
	    		var re = /<a /g;
	    		responseText = responseText.replace(re, "<a style='color:white' ");
			re = /<div class='taboff'>/g;
	    		responseText = responseText.replace(re, "<div style='display:none'>");
			re = /Recent PMs/g;
	    		responseText = responseText.replace(re, "");
			re = /style_images\/redemption/g;
	    		responseText = responseText.replace(re, "/content");	    		

			if (responseText.indexOf("Inbox") < 0)
			{
				// deleted on 20070611  - start 
				/*
				responseText = "<br/><br/><div align=center><b>Your account has not been validated.<br/><br/>Please check your email for instructions.</b></div>";
				*/
				// deleted on 20070611  - end
				
				// added on 20070611  - start 
				if (responseText.indexOf("New Posts") < 0 ) {
					responseText = "<br/><br/><div align=center><b>Your account has not been validated.<br/><br/>Please check your email for instructions.</b></div>";				
				} else {
					responseText = "<br/><br/><div align=center><b>Your mailbox is<br/>not available.<br/></b></div>";
				}
				// added on 20070611  - end 
			}
			else if (responseText.indexOf("/content/") < 0)
			{
				re = /Go to Inbox/g;
	    			responseText = responseText.replace(re, "You have no personal messages.<br/><br/>Go to Inbox");
			}
			else
			{
				responseText = "<div align=center><b>Your personal messages:</b></div>" + responseText;
			}
			
			
			
			loginBox.innerHTML = responseText;
			loginBoxContent = responseText;
	    }
	    else
	    {
	    }
        } 
        else 
        {
        }
    }
    } catch(e) {}
}

function deleteSessionCookies()
{
////if (debug=="1") prompt("",document.cookie);////
	if (getCookie("member_id")) setCookie("member_id", "0", null, "/", null, null);
	if (getCookie("calendarmember_id")) setCookie("calendarmember_id", "0", null, "/", null, null);
	if (getCookie("calendarpass_hash")) deleteCookie("calendarpass_hash", "/", null);
	if (getCookie("calendarmyDates")) deleteCookie("calendarmyDates", "/", null);
}

/*
   name - name of the cookie
   value - value of the cookie
   [expires] - expiration date of the cookie
     (defaults to end of current session)
   [path] - path for which the cookie is valid
     (defaults to path of calling document)
   [domain] - domain for which the cookie is valid
     (defaults to domain of calling document)
   [secure] - Boolean value indicating if the cookie transmission requires
     a secure transmission
   * an argument defaults when it is assigned null as a placeholder
   * a null placeholder is not required for trailing omitted arguments
*/

function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}


/*
  name - name of the desired cookie
  return 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));
}


/*
   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)
   path and domain default if assigned null or omitted if no explicit
     argument proceeds
*/

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";
  }
}

    function searchTextFocus(searchBox)
    {
        if (searchBox.value == "Search a keyword")
        {
            searchBox.value = "";
        }
    }    

function locationjump(para)
{
	//  Used by PM box.
	document.location.href = "/forums/index.php?" + para;
}

function validateLogin()
{
	if (document.getElementById("UserName").value.length == 0 || 
		document.getElementById("PassWord").value.length == 0)
	{
		alert("Please enter your name and password before continuing");
		return false;
	}
	return true;
}
