//------------------------- Site Theming Configuration ------------------------//

var siteTheme = "";
var imagePath = "/images";
var pageWidth = "100%";

var imgMenuItemOn     = new Image;
var imgMenuItemOff    = new Image;

function setTheme( szTheme )
{
	siteTheme = szTheme;
	
	if( szTheme == "mba-direct.com" )
	{
		imagePath = "/images/mbadirect";
	}

    if( szTheme == "exec-appointments.com" )
	{
		pageWidth = (window == top && screen.width > 800) ? "920": "100%";
	}
	
	if ( szTheme == "non-execs.com")
	{
	    imagePath = "/images/NED";
	    pageWidth = (window == top && screen.width > 800) ? "960": "100%";
	}
	
	imgMenuItemOn.src     = imagePath + "/menu/ItemOn.gif";
	imgMenuItemOff.src    = imagePath + "/menu/.gif";

	preload( 'helpIcon', imagePath + "/menu/helpOn.gif" );
	preload( 'accountIcon', imagePath + "/menu/accountOn.gif" );
	preload( 'searchIcon', imagePath + "/menu/searchOn.gif" );
	preload( 'printIcon', imagePath + "/menu/printerOn.gif" );
	preload( 'emailIcon', imagePath + "/menu/emailOn.gif" );
	preload( 'homeIcon', imagePath + "/menu/homeOn.gif" );
}


//------------------------- Image Rollover Effects ----------------------------//

var cache = new Object;


function preload( name,image )
{
    if (document.images)
    {
        cache[name] = new Image();
        cache[name].src = image;
    }
}

function rollover( name )
{

    if (document.images)
    {
        var x;
        eval("x = document['" + name + "']" );
        cache.image = x;
        cache.src   = x.src;
        if( typeof(cache[name]) == "object" )
            x.src = cache[name].src;
    }
}

function restore()
{
    if (document.images)
      cache.image.src = cache.src;
}


function filterKey(filter)
{
    if (!String.fromCharCode( event.keyCode ).match( filter ))
    {
        event.cancelBubble = true;
        event.returnValue=false;
    }
}

//---------------------- Menu Rollover Effects -----------------------------------//


function menuOn( Item,Image,menuID )
{
    Item.style.background = "url('" + imagePath + "/menu/" + Image + "On.gif')";
    Item.style.cursor = "pointer";
    if( menuID != '' )
        cswmShow( menuID, menuID, 'below', -2,-1 );
}

function menuOff( Item,Image,menuID )
{
    Item.style.background = "url('" + imagePath + "/menu/" + Image + ".gif')";
    if( menuID != '' )
        cswmHide();
}

function sectionMenuOn( Item,menuID )
{
    if (siteTheme == "non-execs.com")
    {
        Item.style.background = '#ede5da';
    }
    else
    {
        Item.style.background = '#E1E5E4';
    }
    Item.style.cursor = "pointer";
    if( menuID != '' )
    {
        cswmShow( menuID, menuID, 'right', -2,1 );
    }
}

function sectionMenuOff( Item,menuID )
{
    Item.style.background = '#FFFFFF';
    if( menuID != '' )
    {
        cswmHide();
    }
}


//---------------------- Button Rollover Effects ---------------------------------//

var imgButtonOn     = new Image;
var imgButtonOff    = new Image;

imgButtonOn.src     = imagePath + "/button/buttonOn.gif";
imgButtonOff.src    = imagePath + "/button/button.gif";

function buttonOn( Item )
{
    Item.style.background = "url('" + imagePath + "/button/buttonOn.gif') no-repeat";
    Item.style.cursor = "pointer";
}

function buttonOff( Item )
{
    Item.style.background = "url('" + imagePath + "/button/button.gif') no-repeat";
}



//---------------------- Table Row MouseOver Highlighting -------------------------//

function highlight_on( Row )
{
    if (siteTheme == "mba-direct.com")
    {
        Row.style.backgroundColor = "#A3A1A1";
        Row.style.cursor = "pointer";
    }
    else if (siteTheme == "non-execs.com")
    {
        Row.setAttribute("class", "dataRowHighlight");
    }
    else
    {
        Row.style.backgroundColor = "#FFFFFF";
        Row.style.cursor = "pointer";
    }
}

function highlight_off( Row, Style )
{
    if (siteTheme == "mba-direct.com")
    {
        if (Style == 'True' )
            Row.style.backgroundColor = "#f3f1f1";
        else
            Row.style.backgroundColor = "#cdaaab";
    }
    else if (siteTheme == "non-execs.com")
    {
        if (Style == 'True' )
            Row.setAttribute("class", "dataRowTrue");
        else
            Row.setAttribute("class", "dataRowFalse");
    }
    else
    {
        if (Style == 'True' )
            Row.style.backgroundColor = "#EEEEEE";
        else
            Row.style.backgroundColor = "#D6D8DF";
    }

}

function headline_on( Row )
{
    Row.style.backgroundColor = "#D5D7E4";
}

function headline_off( Row )
{
    Row.style.backgroundColor = "transparent";
}


//--------------------- InfoTip Popup Handling ------------------------------//

var tipElement = new Object;

function infoTipOn( ID )
{
	var screenX
	var screenY

	if( typeof(document.getElementById(ID)) != "object" )
		return;

	tipElement = document.getElementById(ID).style;

	if( navigator.appName.match('Microsoft') != null)
	{
		screenX = document.body.clientWidth;
		screenY = document.body.clientHeight;

		e = window.event;

		if( e.x + 300 > screenX )
			tipElement.left = parseInt( e.x-305+ document.body.scrollLeft );
		else
			tipElement.left = parseInt( e.x+5 + document.body.scrollLeft );

		if( e.y + 200 > screenY )
			tipElement.top = parseInt( e.y-115 + document.body.scrollTop );
		else
			tipElement.top = parseInt( event.y+5+ document.body.scrollTop );

		tipElement.zIndex = "50";
		tipElement.visibility = "visible";
	}
	else
	{
		screenX = window.innerWidth;
		screenY = window.innerHeight;

		tipElement.zIndex = "50";
		tipElement.visibility = "visible";
	}
}


function infoTipOff()
{
    tipElement.visibility = "hidden";
}


//----------------------------- Tab Bar Code -----------------------------------//

function clickTabItem( clickedTabName )
{
    try {

        if (clickedTabName != undefined && clickedTabName!=currentTabName)
        {
            //toggle tab work area
            var targetToShow = clickedTabName.slice(4, clickedTabName.length);
            var targetToHide = currentTabName.slice(4, currentTabName.length);

            //toggle clicked tab images
            document.all(clickedTabName).style.background="url('" + imagePath + "/menu/tabStartItem.gif')";
            document.all(currentTabName).style.background="url('" + imagePath + "/menu/tabItem.gif')";

            //disable rollover scripts on selected tab
            document.all(clickedTabName).onmouseover="";
            document.all(clickedTabName).onmouseout="";

            //enable rollover scripts on previously selected tab
            document.all(currentTabName).onmouseover= function handler(){menuOn(this,'tabItem','');};
            document.all(currentTabName).onmouseout= function handler(){menuOff(this,'tabItem','');};

            //change cursor on selected tab
            document.all(clickedTabName).style.cursor='default';
            document.all(currentTabName).style.cursor='pointer';

            document.all(targetToHide).style.display='none';
            document.all(targetToShow).style.display='block';

            //reset current tab marker
            currentTabName=clickedTabName;
            SetCookie('currentTabName', currentTabName);
        }
        return true;
    }
    catch(e)
    {
        return false;
    }
}


//--------------------- Page Navigation -------------------------------------------//

function goHistory( index )
{
    if( parent == self )
    {
        history.go( index );
    }
    else
    {
        history.back();
    }
}

function closePage()
{
    if( history.length >= 1 )
        history.go(-1);
    else
        location.href = "/";
}



//--------------------- Carriage Return Handling in Forms ------------------------//

function onReturn( Handler )
{
    if (event.keyCode == 13)
    {
        eval( Handler + "();" );
    }
}


//------------------------ Async Callback -----------------------------------------//

function loadAsyncList(pageToLoad, insertElement, dummyLoadElement)
{
    xmlhttp=null;
    xmlhttp = new XMLHttpRequest();

    if (window.ActiveXObject)
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
     }
    if (xmlhttp!=null)
    {
        //declare inline function because we can't call a JScript event handler with arguments directly
        xmlhttp.onreadystatechange = function() {
            state_Change(insertElement, dummyLoadElement);
        };
         xmlhttp.open("GET",pageToLoad,true);
         xmlhttp.send(null);
     }
    else
    {
        alert("Your browser does not support XMLHTTP.");
    }
}

function state_Change(insertElement, dummyLoadElement)
{
    if (xmlhttp.readyState==4)
    {
        if (xmlhttp.status==200)
        {
            var y = document.getElementById(dummyLoadElement);
            var x = document.getElementById(insertElement);

            x.insertAdjacentHTML("afterBegin", xmlhttp.responseText);
            x.removeChild(y);
        }
        else
        {
            alert("Problem retrieving XML data");
        }
    }
}


//---------------------------- Executive/Client Signin ----------------------------//


function ExecSignIn()
{
	if( document.main.email.value == "" )
	{
		alert("Enter your email address");
		document.main.email.focus();
		return;
	}

	if( document.main.password.value == "" )
	{
		alert("Enter your password");
		document.main.password.focus();
		return;
	}
	document.main.submit();
}

function ClientSignIn()
{
	if( document.main.account.value == "" )
	{
		alert("Enter your account number");
		document.main.account.focus();
		return;
	}

	if( document.main.password.value == "" )
	{
		alert("Enter your password");
		document.main.password.focus();
		return;
	}
	document.main.submit();
}

function ExecutiveForgotPassword()
{
	location.href= "/executive/forgotPassword.asp?email=" + document.main.email.value + "&checkpoint=1";
}

function ClientForgotPassword()
{
	location.href= "/client/forgotPassword.asp?email=" + document.main.account.value + "&checkpoint=1";
}


//---------------------------- Popup Window Functions ----------------------------//


function help( Topic )
{
    location.href = '/help/default.asp?topic=' + Topic;
}

function messagePopup( msgName )
{
    openWin('/help/popup.asp?message=' + msgName,'message',480,180,"center");
}

function openWin( sSource, sName, iWidth, iHeight, sPosition )
{
    var xOffset = 0, yOffset = 0;
    var sFeatures = "";
    var noFrame   = false;
    var newWindow;

    // Check to see if 'noFrame' is specified in the position

    if( sPosition.slice(0,7) == "noFrame" )
    {
        noFrame = true;
        sPosition = sPosition.slice(8);
    }

    // Work out how big the screen is

    if (document.all)
        var xMax = screen.width, yMax = screen.height;
    else if (document.layers)
        var xMax = window.outerWidth, yMax = window.outerHeight;
        else
        var xMax = 800, yMax=600;

    // Work out the window positioning

    if (sPosition == "bottomLeft")
    {
        xOffset = 0;
        yOffset = (yMax - iHeight) - 60;
    }
    else if (sPosition == "topRight")
    {
        xOffset = (xMax - iWidth) - 8;
        yOffset = 0;
    }
    else if ( sPosition.match("[0123456789*]+:[0123456789*]+") )
    {
        xOffset = sPosition.substring( 0, sPosition.indexOf(":",0))
        yOffset = sPosition.substring( xOffset.length+1,sPosition.length );

        if( xOffset == "*" ) xOffset = (xMax - iWidth)/2;
        if( yOffset == "*" ) yOffset = (yMax - iHeight)/2;
    }
    else //center
    {
        xOffset = (xMax - iWidth)/2;
        yOffset = (yMax - iHeight)/2;
    }

    // Set the features of the window

    sFeatures = "width=" + iWidth + ",height=" + iHeight + ",scrollbars=yes";

    if (xOffset > 0 || yOffset > 0)
    {
        sFeatures = sFeatures + ",left=" + xOffset + ",top=" + yOffset;
        sFeatures = sFeatures + ",screenX="+ xOffset + ",screenY=" + yOffset;
    }

    // Open the new window with the calculated attributes

    if (noFrame)
    {
        sFeatures = "fullscreen," + sFeatures;
        newWindow = window.open( sSource, sName, sFeatures);
        newWindow.blur();
        window.focus();
        newWindow.resizeTo(iWidth,iHeight);
        newWindow.moveTo(xOffset,yOffset);
    }
    else
    {
        newWindow = window.open( sSource,sName,sFeatures );

        if (newWindow.opener == null)
        {
            newWindow.opener = self;
        }
    }

    newWindow.focus();
}


function SetCookie(sName, sValue)
{
  date = new Date();
  document.cookie = sName + "=" + escape(sValue); // + "; expires=" + date.toGMTString();
}

function GetCookie(sName)
{
  // cookies are separated by semicolons
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    // a name/value pair (a crumb) is separated by an equal sign
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0])
      return unescape(aCrumb[1]);
  }

  // a cookie with the requested name does not exist
  return null;
}

function DelCookie(sName)
{
  document.cookie = sName + "=" + escape(sValue) + "; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}

//------------------- Validate Email Address for Correct Syntax ------------------//

function validateEmail(strEmail)
{
    var reg1str = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
    var reg2str = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
    var reg1    = new RegExp(reg1str);
    var reg2    = new RegExp(reg2str);
    var reg3    = new RegExp("\s");

    return (!reg1.test(strEmail) && reg2.test(strEmail) && (strEmail.indexOf(" ")<0)) ;
}


//------------------------ Miscellaneous -----------------------------------------//

function printDoc()
{
   if (window.print)
   {
        if ( top.window != window )
        {
            top.frames[1].window.focus();
        }

        window.print();
   }
   else
   {
       alert('Your browser doesn\'t support printing from this link. Use ctrl-p instead.')
   }
}

function parentElementName(element, parentTag)
{
    var parent = element;
    while (parent.tagName!=parentTag)
    {
        var parent = parent.parentElement;
    }
    return parent.name
}

function parentElementID(element, parentTag)
{
    var parent = element;
    while (parent.tagName!=parentTag)
    {
        var parent = parent.parentElement;
    }
    return parent.id
}

function trimString(string)
{
    return string.replace(/^\s+|\s+$/g, '');
}


// Functions to retrieve webpage of given url
function httpRequest(url){
    var pageRequest = false //variable to hold ajax object
    /*@cc_on
       @if (@_jscript_version >= 5)
          try {
          pageRequest = new ActiveXObject("Msxml2.XMLHTTP")
          }
          catch (e){
             try {
             pageRequest = new ActiveXObject("Microsoft.XMLHTTP")
             }
             catch (e2){
             pageRequest = false
             }
          }
       @end
    @*/

    if (!pageRequest && typeof XMLHttpRequest != 'undefined')
       pageRequest = new XMLHttpRequest();

    if (pageRequest)
    { //if pageRequest is not false
        pageRequest.open('GET', url, false); //get page synchronously 
        pageRequest.send(null);
        embedpage(pageRequest);
    }
}

// Helper method of HttpRequest
function embedpage(request)
{
    //if viewing page offline or the document was successfully retrieved online (status code=200)
    if (window.location.href.indexOf("http")==-1 || request.status==200)
    {
        // IE failed to recognise AJAX object here, but the code will still work anyway.
        // Catch whatever error throwed by IE and let the code continue on.
        try 
        {
            document.write(request.responseText);
        }
        catch (err) {}
    }
}

// Resize height of iframe tag
// Note: this function is not being used, and seems not working atm.
function resizeIframe() {
    var height = document.documentElement.clientHeight;
    //height -= document.getElementById('frame').offsetTop;
    
    // not sure how to get this dynamically
    //height -= 0; /* whatever you set your body bottom margin/padding to be */
    
    document.getElementById('frame').style.height = height +"px";
    alert(height);
};