// Flags to indicate whether the browser is Netscape or IE
var isNS = false;
var isIE = false;

// Flag to indicate whether the browser is Netscape 4.x
var isNS4 = false;

// Flag to indicate whether the browser is IE4 or IE6
var isIE4 = false;
var isIE6 = false;
var isIE7 = false;
// Is this Netscape or IE?
if (navigator.appName.indexOf('Netscape') != -1) {
	isNS = true;

	// Is it the dreaded Netscape 4?
	if (navigator.appVersion.indexOf('4.') != -1) {
		isNS4 = true;
	}
} else {
	isIE = true;

	// Is it IE 4?
	if (navigator.appVersion.indexOf('MSIE 4.') != -1) {
		isIE4 = true;
	}
	if (navigator.appVersion.indexOf('MSIE 6.') !=-1) {
	    isIE6 = true;
	}
	if (navigator.appVersion.indexOf('MSIE 7.') !=-1) {
		    isIE7 = true;
	}

	//alert('IE:' + isIE + ', IE4:' + isIE4 + ', NS:' + isNS + ', NS4:' + isNS4);
}


var alreadyLoaded = false;

// Function to conditionally reload the doc, to prevent NS4 from infinitely looping
function reloadDoc() {
	if (!isNS4) {
		if (isNS) {
			document.location.reload();
		} else if (alreadyLoaded == false) {
			document.location.reload();
		}
	}
}


var CallPageLoad = false;

// Determine if user is logged in.
// Returns: 0=no, 3=subscriber.
function OnPageLoad()
{
	isSession();    
    
	alreadyLoaded = true;
	
	writeIE4Menus();

	if (CallPageLoad == true)
	{
		PageLoad();
	}
	
	ChangeLogo();
	ChangeRmsLogo();
}

function OnRSPageLoad()
{
	writeRSIE4Menus();
}

/**
 * Helper function for creating DHTML divs corresponding to a NavBar, its associated menus
 * and items.  Should be called from the onLoad() handler to ensure IE4 compatability.
 */
function writeNavBarHTML(navBar) {
    
    //alert("writeNavBarHTML");
	// Write main nav bar div
	var str = '<div id="' + navBar.name + '"';
	str += ' style="position:absolute;"';
	str += '>';
	str += '<table  name="Menutable" id="Menutable" width=' + navBar.width + ' height=' + navBar.height + ' cellspacing=0 cellpadding=0 border=0>';
	str += '<tr>';

	// Write each menu heading
	for (i = 0; i < navBar.menus.length; i++) {
		curMenu = navBar.menus[i];
		str += '<td width=' + curMenu.width + ' bgcolor=' + navBar.bgcolor + ' onMouseOver="showMenu(' + navBar.name + ', ' + i + ')">';
		str += '<font color="#ffffff">';

		// Fix alignment issues - IE5 is different that the others
		if (isNS || isIE4) {
			str += '<table border=0 cellpadding=0 cellspacing=0 width=' + curMenu.width + '><tr><td>';
			str += '<img src="../images/Anchor.gif" width=' + curMenu.width + ' height=1>';
			str += '</td></tr><tr><td>';
		}

		// Write link (if applicable)
		if (curMenu.url != null) {
			str += '<a class="RMSnav" href="' + curMenu.url + '">';
		} else {
			str += '<font class="RMSnav" color="#ffffff">';
		}

		// Is this the menu heading of the current section? If so, breadcrumb
		if (i == navBar.currentSection) {
			str += '<b><font color="#ffffcc">';
		}

		// Write text
		str += curMenu.name;

		// End breadcrumb, if applicable
		if (i == navBar.currentSection) {
			str += '</font></b>';
		}

		// Finish link (if necessary)
		if (curMenu.url != null) {
			str += '</a>';
		} else {
			str += '</font>';
		}

		// Finish alignment table, if necessary
		if (isNS || isIE4) {
			str += '</td></tr></table>';
		}

		// Finish table cell
		str += '</font></td>';

	}

	str += '</tr></table></div>';

	if (isIE)
	{
		// iframe used to cover any <select> control under the menu
		str += '<iframe id="DivShim" src="javascript:false" scrolling="no" frameborder="0" style="position:absolute; visibility:hidden;"></iframe>';
	}

	// Create DIV
	var newDiv;
	var ref;
	if (!isIE4) {
		newDiv = document.createElement('div');
		newDiv.innerHTML = str;
		ref = newDiv.style;		// Create an alias for newDiv.style
		ref.position = 'absolute';
	} else {
		document.body.insertAdjacentHTML('beforeEnd', str);
		newDiv = document.all[navBar.name];
		ref = newDiv.style;
	}

	// Calculate width based on total menu widths
	var width = 0;
	for (i = 0; i < navBar.menus.length; i++) {
		curMenu = navBar.menus[i];
		width += curMenu.width;
	}

	// Attach div to document body
	if (!isIE4) {
		document.body.appendChild(newDiv);
	}

	// Set style properties
	ref.left = navBar.left;
	ref.top = navBar.top;
	ref.width = width;
	ref.height = navBar.height;
	ref.visibility = 'visible';		// inherit, visible, hidden
	ref.background = navBar.bgcolor;

	// Build menus
	for (i = 0; i < navBar.menus.length; i++) {
		writeMenuHTML(navBar.menus[i], navBar);
	}
}

/**
 * Helper function to build menu HTML.  Should be called from the onLoad()
 * handler to ensure IE4 compatability.
 */
function writeMenuHTML(menu, navBar) {

	// Find this menu's position in menus
	menu.position = 0;
	for (menu.position = 0; menu.position < navBar.menus.length; menu.position++) {
		// If we've reached the current menu, stop
		if (navBar.menus[menu.position] == menu) {
			break;
		}
	}

	// Build DIV tag
	var str = '<div id="' + navBar.name + 'menu' + menu.position + '"';
	str += ' style="position:absolute;"';
	str += ' onMouseOver="showMenu(' + navBar.name + ', ' + menu.position + ')"';
	str += ' onMouseOut="hideMenu(' + navBar.name + ', ' + menu.position + ')"';
	str += '>';

	// Build HTML for DIV display
	str += '<table border = 0 width=' + menu.width + '>';

	// Add items to table
	for (i = 0; i < menu.items.length; i++) {
		curItem = menu.items[i];
		str += '<tr><td onMouseOver="highlightItem(' + navBar.name + ', ' + menu.position + ', ' + i + ')">';

		// Link if the url is non-null
		if (curItem.url != null) {
			str += '<a class="RMSnav" href="' + curItem.url + '">';
		} else {
			str += '<font class="RMSnav" color="#ffffff">';
		}

		// Breadcrumb if this is the current section and subsection
		if ((menu.position == navBar.currentSection) && (i == navBar.currentSubsection)) {
			str += '<font color="#ffffcc"><b>';
		}

		// Write text
		str += curItem.name;

		// finish breadcrumb, if necessary
		if ((menu.position == navBar.currentSection) && (i == navBar.currentSubsection)) {
			str += '</b></font>';
		}

		// Finish link, if necessary
		if (curItem.url != null) {
			str += '</a>';
		} else {
			str += '</font>';
		}

		// Finish table row
		str += '</td></tr>';
	}

	// End table and DIV
	str += '</table></div>';

	// Find horizontal position of this menu
	menu.left = navBar.left;
	for (i = 0; i < menu.position; i++) {
		curMenu = navBar.menus[i];
		menu.left += curMenu.width;
	}

	// Adjust so the text doesn't jump around when it's rolled over
	menu.left -= 3;

	// Assign top attribute - IE5 for some reason does not align correctly
	if (isIE && !isIE4) {
		menu.top = navBar.top - 1;
	} else {
		menu.top = navBar.top;
	}

	// Create DIV
	var newDiv;
	var ref;
	if (!isIE4) {
		newDiv = document.createElement('div');
		newDiv.innerHTML = str;
		ref = newDiv.style;		// Create an alias for newDiv.style
		ref.position = 'absolute';
	} else {
		document.body.insertAdjacentHTML('beforeEnd', str);
		newDiv = document.all[navBar.name + 'menu' + menu.position];
		ref = newDiv.style;
	}

	// Attach div to document body
	if (!isIE4) {
		document.body.appendChild(newDiv);
	}

	// Set style properties
	ref.left = menu.left;
	ref.top = menu.top;
	ref.width = menu.width;
	ref.height = menu.height;
	ref.visibility = 'hidden';		// inherit, visible, hidden
	ref.background = navBar.bgcolor;

	// Associate div with Menu object
	menu.impl = newDiv;

	// Build items
	for (j = 0; j < menu.items.length; j++) {
		writeMenuItemHTML(menu.items[j], menu, navBar);
	}

}

/**
 * Helper function to build menu item HTML, implemented as a series of
 * individual divs that are shown when their parent menu is rolled-over.
 * Should be called from the onLoad() handler to ensure IE4 compatability.
 */
function writeMenuItemHTML(item, menu, navBar) {

	// Find this item's position in the menu
	item.position = 0;
	for (item.position = 0; item.position < menu.items.length; item.position++) {
		// If we've reached the current item, stop
		if (menu.items[item.position] == item) {
			break;
		}
	}

	// Build DIV tag
	var str = '<div id="' + navBar.name + 'menu' + menu.position + 'item' + item.position + '"';
	str += ' style="position:absolute;"';
	str += ' onMouseOver="highlightItem(' + navBar.name + ', ' + menu.position + ', ' + item.position + ')"';
	str += ' onMouseOut="unhighlightItem(' + navBar.name + ', ' + menu.position + ', ' + item.position + ')"';

	// Write onClick handler if the item is linkable
	if (item.url != null) {
		str += ' onClick="document.location.href=\'' + item.url + '\'"';
	}

	// Finish div tag
	str += '>';

	// Build HTML for DIV display
	str += '<table border = 0 width=' + menu.width + '"><tr><td bgcolor="' + navBar.rocolor + '">';
	str += '<font class="RMSnav" color="#ffffff">';

	// Create link if the item is link-able
	if (item.url != null) {
		// IE4 does not like <a> tags within divs
		if (!isIE4) {
			str += '<a class="RMSnav" href="' + item.url + '">';
		} else {
			str += '<font class="RMSnav" color="#ffffff">';
		}
	}

	str += item.name;

	// End link if item is link-able
	if (item.url != null) {
		// IE4 does not like <a> tags within divs
		if (!isIE4) {
			str += '</a>';
		} else {
			str += '</font>';
		}
	}

	str += '</td></tr></table>';

	// End DIV
	str += '</div>';

	// Calculate top edge based on position in array
	item.top = menu.top + (item.position * 17);

	// Create DIV
	var newDiv;
	var ref;
	if (!isIE4) {
		newDiv = document.createElement('div');
		newDiv.innerHTML = str;
		ref = newDiv.style;		// Create an alias for newDiv.style
		ref.position = 'absolute';
	} else {
		document.body.insertAdjacentHTML('beforeEnd', str);
		newDiv = document.all[navBar.name + 'menu' + menu.position + 'item' + item.position];
		ref = newDiv.style;
	}


	// Attach div to document body
	if (!isIE4) {
		document.body.appendChild(newDiv);
	}

	// Set style properties
	ref.left = menu.left;
	ref.top = item.top;
	ref.width = menu.width;
	ref.height = 20;
	ref.visibility = 'hidden';		// inherit, visible, hidden
	ref.background = navBar.rocolor;

	// Associate div with Item object
	item.impl = newDiv;
}

// Div implementation of showMenu
function showMenuImpl(menu) {
	menu.impl.style.visibility = 'visible';

	if (isIE == false)
		return;
		
	// iframe used to cover any <select> control under the menu
	var iframe = document.getElementById('DivShim');

	if (iframe == null)
		return;

	if ((menu.name == "Storm Tracker") || (menu.name == "Services"))
	{
		var height = parseInt(menu.impl.style.height,10) - 59 + "px";
		var left   = parseInt(menu.impl.style.left,10)   - 20 + "px";
		
		iframe.style.width      = menu.impl.style.width;
		iframe.style.height     = height;
		iframe.style.top        = menu.impl.style.top;
		iframe.style.left       = menu.impl.style.left;
		iframe.style.left       = left;
		iframe.style.zIndex     = menu.impl.style.zIndex - 1;
		iframe.style.visibility = 'visible';

		// alert(iframe.style.left + "," + iframe.style.top + "," + iframe.style.width + "," + iframe.style.height + ";" + iframe.style.zIndex);
	}
}

// Div implementation of hideMenu
function hideMenuImpl(menu) {
	menu.impl.style.visibility = 'hidden';

	if (isIE == false)
		return;
		
	// iframe used to cover any <select> control under the menu
	var iframe = document.getElementById('DivShim');

	if (iframe == null)
		return;

	iframe.style.visibility = 'hidden';
}

// Div implementation of highlightItem
function highlightItemImpl(item) {
	item.impl.style.visibility = 'visible';
}

// Div implementation of unhighlightItem
function unhighlightItemImpl(item) {
	item.impl.style.visibility = 'hidden';
}

/**
 * Global array of navigation bars
 */
var navBars = new Array();

/**
 * Function to generate the menu HTML from the object declarations.
 * Depends on the "abstract" writeNavBarHTML(), writeMenuHTML() and
 * writeMenuItemHTML() functions in either DivNav.asp or LayerNav.asp,
 * depending on which browser is being used.
 */
function writeMenus() 
{   
    //alert("writeMenus");
    addMenus();
	for (var i = 0; i < navBars.length; i++) 
	{	    
		writeNavBarHTML(navBars[i]);
	}
}

function writeRSMenus() 
{   
    addRSMenus();
	for (var i = 0; i < navBars.length; i++) 
	{	    
		writeNavBarHTML(navBars[i]);
	}
}

/**
 * Object definition for NavBar object. Represents a horizontal navigation
 * bar that can contain 1 or more dropdown menus.  All menus in the nav
 * bar are the same color and have the same rollover behavior.
 */
function NavBar(name, left, top, height, bgcolor, rocolor) {
	this.name = name;
	this.menus = new Array();	// Holds child menus
	this.left = left;
	this.top = top;
	this.height = height;
	this.bgcolor = bgcolor;
	this.rocolor = rocolor;

	// Breadcrumbing
	this.currentSection = -1;	// Index of section to highlight
	this.currentSubsection = -1;	// Index of subsection to highlight

	// Add to global array
	navBars[navBars.length] = this;
}

/**
 * Object definition for Menu object.  Represents a single dropdown
 * menu.  The menu heading is also a selectable item and has its
 * own div/layer and URL.
 */
function Menu(name, width, height, url) {
	this.name = name;
	this.width = width;
	this.height = height;
	this.url = url;		// Associated url of menu heading
	this.items = new Array();	// Holds menu items

	// Heading is an Item too, create it and add it to the list
	addItem(this, new Item(name, url));
}

/**
 * Object definition for Item object.  Represents a menu item in a
 * dropdown menu.
 */
function Item(name, url) {
	this.name = name;
	this.url = url;
}

/**
 * Function to add a menu to the right side of a Navigation bar
 */
function addMenu(navBar, menu) {
	navBar.menus[navBar.menus.length] = menu;
}

/**
 * Function to add a menu item to the bottom of a menu
 */
function addItem(menu, item) {
	menu.items[menu.items.length] = item;
}

/**
 * Timer for rollover operations
 */
var hideTimer;

/**
 * onMouseOver() handler to display the indicated menu
 */
function showMenu(navBar, menuId) {

	// Make sure any other menus are hidden
	hideAllMenusExcept(navBar, menuId);

	// Clear the hide timer, since we've hidden the menus manually
	clearTimeout(hideTimer);

	// Show this menu
	showMenuImpl(navBar.menus[menuId]);
}

/**
 * Function to hide the indicated menu
 */
function hideMenuImmediate(navBar, menuId) {

	// Unhighlight any associated menu item divs/layers
	unhighlightItems(navBar, menuId);

	// Hide the menu div/layer
	hideMenuImpl(navBar.menus[menuId]);
}

/**
 * onMouseOut() handler to hide the indicated menu after a half-second delay.
 * The delay is to prevent flicker, since the mouse actually leaves the menu
 * div and triggers the onMouseOut() event when the item div pops up.
 */
function hideMenu(navBar, menuId) {
	hideTimer = setTimeout("hideMenuImmediate(" + navBar.name + ", " + menuId + ")", 500);
}

/**
 * Function to hide all the menus except the indicated one immediately
 */
function hideAllMenusExcept(navBar, menuId) {

	for (var j = 0; j < navBars.length; j++) {
		curNavBar = navBars[j];

		for (var i = 0; i < curNavBar.menus.length; i++) {
			if (!((navBar == curNavBar) && (menuId == i))) {
				hideMenuImmediate(curNavBar, i);
			}
		}
	}
}

/**
 * onMouseOver() handler to highlight the indicated item
 */
function highlightItem(navBar, menuId, itemId) {

	// Hide other menu items that may be showing
	unhighlightAllItems(navBar);

	// Since the item div/layer appears on top of the menu div/layer, make sure it stays visible
	showMenu(navBar, menuId);

	// Highlight item
	var item = navBar.menus[menuId].items[itemId];
	highlightItemImpl(item);

	// Display item name in status bar (workaround for URL disappearing when mouse not over item text)
	//window.status = item.name;
}

/**
 * onMouseOut() handler to unhighlight the indicated item
 */
function unhighlightItem(navBar, menuId, itemId) {

	// Unhighlight the item
	unhighlightItemImpl(navBar.menus[menuId].items[itemId]);

	// Initiate the menu hide timeout, just in case we moused out of the menu and didn't detect it
	hideMenu(navBar, menuId);
}

/**
 * Function to unhighlight all items in the specified menu
 */
function unhighlightItems(navBar, menuId) {
	var menu = navBar.menus[menuId];
	for (k = 0; k < menu.items.length; k++) {
		unhighlightItemImpl(navBar.menus[menuId].items[k]);
	}
}

/**
 * Function to unhighlight all items in the specified nav bar
 */
function unhighlightAllItems(navBar) {
	for (var i = 0; i < navBar.menus.length; i++) {
		for (var j = 0; j < navBar.menus[i].items.length; j++) {
			unhighlightItemImpl(navBar.menus[i].items[j]);
		}
	}
}

/**
 * Designates which section of the specified nav bar should be highlighted
 * and which menu item should be highlighted for breadcrumbing purposes.
 * Passing -1 for the section or itemId indicates that no section and/or item
 * should be highlighted.
 */
function setBreadCrumbing(navBar, sectionId, subsectionId) {
	navBar.currentSection = sectionId;
	navBar.currentSubsection = subsectionId;
}

// Get cookie value.
// IIS4 writes cookie in capital letters.
// IIS5 writes cookie with the actual letters specified.
// name [in] cookie name.
// key  [in] value key.
// Returns value of specified cookie or null if not found.
function getCookie(name,key) 
{
	// the entire cookie block
	var begin;
    var block  = unescape(document.cookie);
	var BLOCK  = block.toUpperCase();
    var end;
    var full;
	var KEY  = key.toUpperCase();
	var NAME = name.toUpperCase();
    var pair;
    var prefix;
    var value;

	prefix = NAME + "=";

	// isolate the named cookie
    begin = BLOCK.indexOf("; " + prefix);
 
    if (begin == -1) 
    {
        begin = BLOCK.indexOf(prefix);

        if (begin != 0) 
            return null;
    }
    else
	{
		begin += 2;
	}

	begin += prefix.length;

    end = BLOCK.indexOf(";",begin);

    if (end == -1)
        end = BLOCK.length;

	// full cookie string
	var full = block.substring(begin,end);
	var FULL = BLOCK.substring(begin,end);

	// isolate the entry
    prefix = KEY + "=";
    begin  = FULL.indexOf("&" + prefix);

    if (begin == -1) 
    {
        begin = FULL.indexOf(prefix);

        if (begin != 0) 
            return null;
    }
    else
    {
		begin += 1;
    }

    end = FULL.indexOf("&",begin + prefix.length);

    if (end == -1)
        end = FULL.length;

	// key/value pair
	pair = full.substring(begin,end);
	// alert(pair);

	// value
    value = pair.substring(prefix.length);
    // alert(value);
    
	return value;
}

// Create navigation bars
var leftNavBar = new NavBar('leftNavBar', 20, getNavBarTop(), 18, '#006699', '#666666');

// un-comment next line to reinstate right-justified rightNavBar
//var rightNavBar = new NavBar('rightNavBar', getRightNavPos(), getNavBarTop(), 18, '#666666', '#000000');

// Create menus for left navigation bar
var MainMenu = new Menu('Main Menu', 150, 60, 'javascript:Main()');
var HazardMenu = new Menu('Hazard Data', 150, 100, 'javascript:Hazard()');
var PersonalMenu = new Menu('Personal Lines', 150, 80, 'javascript:Personal()')
var CommercialMenu = new Menu('Commercial Lines', 150, 120, 'javascript:Commercial()')
var ManagementMenu = new Menu('Management', 150, 80, 'javascript:Management()')
var logoutMenu = new Menu('Logout', 150, 20, 'javascript:logout();')

var AdminMainMenu = new Menu('Main Menu',150,160,'javascript:AdminMain();')
var AdminUserProfileMenu = new Menu('User Profile Manager',150,20,'http://www.risksearch.com/Scripts/UserProfile/Admin.asp')
var AdminAccumMenu = new Menu('Accumulations',150,60,null)
var AdminDLMProfile = new Menu('DLM Profiles',150, 60, null);

var RSHomeMenu = new Menu('Home',150,10,'javascript:HomeRS()');
var RSAbountUsMenu = new Menu('About Us',150,40,null)
var RSProductsMenu = new Menu('Products',150,90,null)
var RSContactMenu = new Menu('Contacts',150, 80, null);

function addUserMenu(UserId, MenuOptions)
{
    var isHazard = false;
    var isPersonal = false;
    var isCommercial = false;
    var isManagement = false;

    //Hazard Lookups       
    if((MenuOptions & 1) == 1)
    {
        addItem(HazardMenu, new Item('New Location', 'javascript:HazardNew();'));
		isHazard = true;
	}
        
	if((MenuOptions & 2) == 2)
	{
		addItem(HazardMenu, new Item('Find Location', 'javascript:HazardFind();'));
		isHazard = true;
	}

	if((MenuOptions & 4) == 4)
	{
		addItem(HazardMenu, new Item('Delete Location', 'javascript:HazardDelete();'));
		isHazard = true;
	}
	
	if((MenuOptions & 16384) == 16384)
	{
	    addItem(HazardMenu, new Item('Multiple Locations', 'javascript:Mutliloc();'));
	    isHazard = true;
	}
		     
    // Personal Lines
	if((MenuOptions & 8) == 8)
    {
		addItem(PersonalMenu, new Item('New Account', 'javascript:PersonalNew();'));
		isPersonal = true;
	}

	if((MenuOptions & 16) == 16)
	{
		addItem(PersonalMenu, new Item('Find Account', 'javascript:PersonalFind();'));
		isPersonal = true;
	} 

	if((MenuOptions & 32) == 32)
	{
		addItem(PersonalMenu, new Item('Delete Account', 'javascript:PersonalDelete();'));  
		isPersonal = true;
	}
	
	// Commercial Lines		
	if((MenuOptions & 64) == 64)
	{
	    addItem(CommercialMenu, new Item('New Account', 'javascript:CommericalNew();'));
		isCommercial = true;
	}
		
	if((MenuOptions & 128) == 128)
	{
		addItem(CommercialMenu, new Item('Find Account', 'javascript:CommericalSearch();'));
		isCommercial = true;
	}
		
	if((MenuOptions & 256) == 256)
	{
		addItem(CommercialMenu, new Item('Delete Account', 'javascript:CommericalDelete();')); 
		isCommercial = true;
	}
	
	if((MenuOptions & 65536) == 65536)
    {
		addItem(CommercialMenu, new Item('Create Renewal', 'javascript:CommercialRenewal();'));
		isCommercial = true;
	}  
		
	if((MenuOptions & 131072) == 131072)
	{
		addItem(CommercialMenu, new Item('Find Committed Account', 'javascript:CommercailFindCommitted();'));
		isCommercial = true;
	}	
		
	// Management	
	if((MenuOptions & 524288) == 524288)
	{
	    addItem(ManagementMenu, new Item('Find Accumulations', 'javascript:FindAccum();'));
		isManagement = true;
	}
	
	if((MenuOptions & 32768) == 32768)
	{
		addItem(ManagementMenu, new Item('Find Jobs', 'javascript:FindJobs();'));
		isManagement = true;
	}

	if((MenuOptions & 262144) == 262144)
	{
		
		addItem(ManagementMenu, new Item('Find Committed Jobs', 'javascript:FindCommittedJobs();'));
		isManagement = true;
	}
	
	// Add items to Main menu
    addItem(MainMenu, new Item('Help', 'javascript:Help();'));
    
    if((MenuOptions & 4096) == 4096)
    {
        addItem(MainMenu, new Item('Change Profile', 'javascript:ChangeProfile();'));
    }
    
    if(UserId)
    addMenu(leftNavBar, MainMenu);
    
	if(isHazard == true)
	    addMenu(leftNavBar, HazardMenu);	    
	
	if(isPersonal == true)
	    addMenu(leftNavBar, PersonalMenu);	    
	
	if(isCommercial == true)
	    addMenu(leftNavBar, CommercialMenu);	   
	
	if(isManagement == true)
	    addMenu(leftNavBar, ManagementMenu);	    
	
    addMenu(leftNavBar, logoutMenu);
}

function addAdminMenu()
{
    //Admin menu    
    addItem(AdminMainMenu, new Item('Help', 'javascript:Help();'));
    addItem(AdminMainMenu, new Item('Change Profile', 'javascript:ChangeProfile();'));
    addItem(AdminMainMenu, new Item('Export Accounts', 'javascript:Export();'));        
    addItem(AdminMainMenu, new Item('Manage Jobs', 'javascript:FindJobs();'));
    addItem(AdminMainMenu, new Item('Manage Commit Queue', 'javascript:FindCommittedJobs();'));
    addItem(AdminMainMenu, new Item('Progress Monitor', 'javascript:ProgressMonitor();'));
    addItem(AdminMainMenu, new Item('Resource Manager', 'javascript:ResourceMgr();'));
    addItem(AdminMainMenu, new Item('Technical Support', 'javascript:TechnicalSupport();'));
    
    //Accumulation menu
    addItem(AdminAccumMenu, new Item('Update Accumulations', 'javascript:UpdateAccum();'));
    addItem(AdminAccumMenu, new Item('Assign Accumulations', 'javascript:AssignAccum();'));    
    
    //Accumulation menu
    addItem(AdminDLMProfile, new Item('New Profile', 'javascript:NewDLMProfile();'));
    addItem(AdminDLMProfile, new Item('Search Profile', 'javascript:SearchDLMProfile();'));       
    
    addMenu(leftNavBar, AdminMainMenu); 
    addMenu(leftNavBar, AdminUserProfileMenu); 
    addMenu(leftNavBar, AdminAccumMenu); 
    addMenu(leftNavBar, AdminDLMProfile); 
    addMenu(leftNavBar, logoutMenu);
}

function addRiskSearchMenu()
{
    addItem(RSAbountUsMenu, new Item('Company', 'javascript:CompanyRS();'));
    addItem(RSProductsMenu, new Item('Earthquake Data', 'javascript:EQDataRS();'));
    addItem(RSProductsMenu, new Item('Hurricane Data', 'javascript:HUDataRS();'));
    addItem(RSProductsMenu, new Item('Flood Data', 'javascript:FLDataRS();'));
    addItem(RSContactMenu, new Item('Location', 'javascript:LocationRS();'));
    addItem(RSContactMenu, new Item('Sales', 'javascript:SalesRS();'));
    addItem(RSContactMenu, new Item('Customer Support', 'javascript:CustomerSupport();'));       
    
    addMenu(leftNavBar, RSHomeMenu);     
    addMenu(leftNavBar, RSProductsMenu); 
    addMenu(leftNavBar, RSContactMenu);
    addMenu(leftNavBar, RSAbountUsMenu); 
}

function addMenus()
{
    var GetMenu;
    var UserId;   
    
    if(is_Cookie("MENU_OPTIONS"))
    {
        GetMenu = Number(get_Cookie("MENU_OPTIONS"));        
    }    
    
    if(is_Cookie("USERID"))
    {
		UserId = Number(get_Cookie("USERID")); 
    }
        
    if(is_Cookie("Admin"))
    {
        IsAdmin = Number(get_Cookie("Admin.IsAdmin"));
        
        if(IsAdmin)
        {
            addAdminMenu();        
        }
        else
        {
            addUserMenu(UserId,GetMenu);    
        }
    }
    else
    {
		addMenu(leftNavBar, logoutMenu);
    }
}
    
function addRSMenus()
{
    addRiskSearchMenu();
}

/**
 * Function to calculate the proper top of the navigation bar
 */
function getNavBarTop() {

	if (isNS) {
		if (isNS4) {
			y = 50;
		} else {
			y = 58;
		}
	} else {
		if (isIE4) {
			y = 58;
		} else {
			y = 59;
		}
	}

	return y;
}

/**
 * Function to return the proper x-coordinate of the right navigation bar
 */
function getRightNavPos() {

	var state = LoggedIn();
	var count = (state > 0) ? 0 : 2;

	// We have to do this differently for Netscape vs. IE
	if (isNS) {
		x = window.innerWidth - 70 + count;

		// Need to adjust for scrollbar presence - is there a way to detect this?
	} else {
		// IE4 and IE5 do this differently
		if (isIE4) {
			x = document.body.scrollWidth - 73 + count;
		} else {
			// cell = document.getElementById('leftCol');
			// x = 90 + cell.scrollWidth;
			x = document.body.offsetWidth - 73 + count;
		}
	}

	// Don't let it overlap the left nav bar
	if (x < 590) {
		x = 590;
	}

	return x;
}


// Write the menu HTML to the document
// Divs must be created from the onload handler for IE4
if (!isIE) {
	writeMenus();
}

/**
 * Helper function for IE4, writes menus to the page.  Should be called from
 * the onload() handler.  All other browsers are ignored to prevent duplicate
 * elements from being created.
 */
function writeIE4Menus() {
    //alert("writeIE4Menus");
    
	if (isIE) 
	{	    
		writeMenus();
	}
	//AutoFocus();
}

function writeRSIE4Menus() 
{
	if (isIE) 
	{	    
		writeRSMenus();
	}
}

// Set the input focus to first form input (if any).
function AutoFocus()
{
var aElem;
var i;
var nCount;
var oElem;
var oForm = document.forms[0];
var oSelect;
var oSubmit;
var oText;
var sName;
var sType;

if (oForm == null)
	return;
	
aElem = oForm.elements;
if (aElem == null)
	return;

nCount = aElem.length;

for (i=0; i < nCount; i++)
{
	oElem = aElem[i];
	sName = oElem.name;
	sType = oElem.type;

	// skip wrong types
	if (sType == "hidden")
		continue;

	if (sType == "reset")
		continue;

	// last-resort types
	if (sType == "select-one")
	{
		if (sName != "NhcDataKey")
		{
			if (oSelect == null)
				oSelect = oElem;
			continue;
		}
	}

	if (sType == "submit")
	{
		if (oSubmit == null)
			oSubmit = oElem;
		continue;
	}

	if (sType == "textarea")
	{
		if (oText == null)
			oText = oElem;
		continue;
	}

	oElem.focus();
	return;
}

// use last-resort controls if present

if (oSubmit != null)
{
	oSubmit.focus();
	return;
}

if (oText != null)
{
	oText.focus();
	return;
}

if (oSelect != null)
{
	oSelect.focus();
	return;
}
}

// Append text to query string.
// q [in] existing query string.
// t [in] text to append.
// Returns query string with new text appended.
function AppendToQueryString(q,t)
{
	if ((q.length > 0) && (t.length > 0))
	{
		return q + "&" + t;
	}
	
	if (t.length > 0)
	{
		return t;
	}
	
	return q;
}

// Get local date format.
// code [in] 0=no prefix, 1=include prefix ("DFS=").
// Returns three-letter string representing the presentation order, in which:
// D = day
// M = month
// Y = year
// An example would be: MDY (month-day-year).
// This function always returns a valid date format string, or an
// empty string if the date format cannot be determined.
function DateFormat(code)
{
	var d = new Date();
	var s = "";

	d.setFullYear(1999);
	d.setMonth(11);
	d.setDate(30);

	var s1 = d.toLocaleDateString();
	var t1 = s1.replace(/,/g,"");
	var a1 = t1.split(' ');

	d.setDate(31);

	var s2 = d.toLocaleDateString();
	var t2 = s2.replace(/,/g,"");
	var a2 = t2.split(' ');

	for (i=0; i < a1.length; i++)
	{
		var v1 = a1[i];
		var v2 = a2[i];

		if (v1 == 12)
		{
			// month as number
			s = s + "M";
			continue;			
		}
		
		if (v1 == 30)
		{
			// day
			s = s + "D";
			continue;			
		}
		
		if (v1 == 1999)
		{
			// year
			s = s + "Y";
			continue;			
		}

		if (v1 == v2)
		{
			// month as word
			s = s + "M";
			continue;
		}
	}

	// result must have all three parts, in any order
	switch (s)
	{
		case "DMY": break;
		case "DYM": break;
		case "MDY": break;
		case "MYD": break;
		case "YMD": break;
		case "YDM": break;
		default   : return "";
	}

	if (code == 1)
		s = "DFS=" + s;
	
	return s;
}

// Sets hidden form fields to local values.
function LocalForm()
{
	var e;
	var f;
	var i;
	var j;

	// each form
	for (i=0; i < document.forms.length; i++)
	{
		f = document.forms[i];

		// each element
		for (j=0; j < f.elements.length; j++)
		{
			e = f.elements[j];

			// only hidden fields			
			if (e.type != 'hidden')
				continue;

			// date format string
			if (e.name == 'DFS')
			{
				e.value = DateFormat(0);
				// alert(e.value);
				continue;
			}

			// number format decimal
			if (e.name == 'NFD')
			{
				e.value = NumberFormatDecimal(0);
				// alert(e.value);
				continue;
			}

			// number format group
			if (e.name == 'NFG')
			{
				e.value = NumberFormatGroup(0);
				// alert(e.value);
				continue;
			}

			// time-zone abbreviation
			if (e.name == 'TZA')
			{
				e.value = TimeZoneAbbreviation(0);
				// alert(e.value);
				continue;
			}

			// time-zone difference
			if (e.name == 'TZD')
			{
				e.value = TimeZoneDifference(0);
				// alert(e.value);
				continue;
			}
		}
	}

	return true;
}

// Creates local query string, as follows:
// DFS=xxx&NFD=x&NFG=x&TZA=xxx&TZD=xxx
// DFS = date format string
// NFD = number format decimal
// NFG = number format group
// TZA = time zone abbreviation
// TZD = time zone difference
// Returns localize query string.
function LocalQuery()
{
	var dfs = DateFormat(1);
	var nfd = NumberFormatDecimal(1);
	var nfg = NumberFormatGroup(1);
	var str = "";
	var tza = TimeZoneAbbreviation(1);
	var tzd = TimeZoneDifference(1);

	str = AppendToQueryString(str,dfs);
	str = AppendToQueryString(str,nfd);
	str = AppendToQueryString(str,nfg);
	str = AppendToQueryString(str,tza);
	str = AppendToQueryString(str,tzd);
	
	return str;
}

// Get local number format decimal point character.
// code [in] 0=no prefix, 1=include prefix ("NFD=").
// Returns decimal character, or an empty string if not available.
function NumberFormatDecimal(code)
{
	var n = new Number(1.23);
	var s = n.toLocaleString();
	var t = (s.length == 4) ? s.substring(1,2) : "";
	
	if ((code == 1) && (t.length > 0))
		t = "NFD=" + t;
		
	return t;
}

// Get local number format grouping character..
// code [in] 0=no prefix, 1=include prefix ("NFG=").
// Returns grouping character, or an empty string if not available.
function NumberFormatGroup(code)
{
	var n = new Number(1234.56);
	var s = n.toLocaleString();
	var t = (s.length == 8) ? s.substring(1,2) : "";

	if ((code == 1) && (t.length > 0))
		t = "NFG=" + t;

	return t;
}

// Get local time zone abbreviation.
// code [in] 0=no prefix, 1=include prefix ("TZA=").
// Returns time zone abbreviation, or an empty string if not available.
function TimeZoneAbbreviation(code)
{
	var d = new Date();
	var t = d.toTimeString();
	var i = t.lastIndexOf(' ');
	var s = (i < 0) ? "" : t.substr(i+1);
	
	if ((code == 1) && (s.length > 0))
		s = "TZA=" + s;

	return s;
}

// Get number of hours local time zone is different from GMT.
// code [in] 0=no prefix, 1=include prefix ("TZD=").
// Returns difference value as a string.
function TimeZoneDifference(code)
{
	var d = new Date();
	var h = d.getTimezoneOffset() / 60;
	var s = (code == 0) ? h.toString() : "TZD=" + h.toString();
	return s;
}

var isCheckedOnce = 0
// Appends local values to url, then navigates to that page.
function LaunchWithLocal(url)
{
	if(isCheckedOnce ==0 && isIE7)
	{
		isCheckedOnce = 1;
		setTimeout("enableCheck()", "100");
		return;
	}
	if(document.getElementById("DXMajorAccount1"))
	{
		var initDone = document.forms["MATInternal"].elements["matInitDone"].value;
		var canSave = document.forms["frm2"].elements["@RMSWF_CANSAVE@"].value;

		if (initDone == "true" && canSave == "1")
		{
			var canUnload = DXMajorAccount1.MATCanUnloadNow();
			//Condition added because the onbeforeunload is getting fired more than ones
			if (canUnload == false)
			{
				var answer = confirm("Are you sure you want to navigate away from this page?\n\nUnsaved data will be lost.\n\nTo avoid having to reenter data you should save\nbefore navigating to another page.\n\nPress OK to continue, or Cancel to stay on the current page.")
				if (!answer)
				{
					isCheckedOnce = 0;
					return;
				}
			}
		}
	}
	//var loc = url + "?" + LocalQuery();
	try
	{
		var loc = url;
		document.location = loc;
	}
	catch(error)
	{
	}
}

function enableCheck()
{
   isCheckedOnce = 0;
}

function LaunchNewWindow(url, windowName)
{
    window.open(url, windowName);
}

function LaunchWithLocal2(url)
{
	try
	{
		var loc = url;
		document.location = loc;
	}
	catch(error)
	{
	}
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

// Get cookie value.
// name [in] cookie name to base.
// Returns value, or null if not found.
function GetCookie(name) 
{
	var base = name.toUpperCase() + "=";
	var head;
    var copy;
	var real = document.cookie;
	var t1;
	var t2;
    var tail = -1;
    var value;

	if (real == null)
		return null;
		
    copy = real.toUpperCase();
	head = copy.indexOf("; " + base);

	if (head > 0)
	{
		head += 2;
	}

	if (head == -1)
	{
		head = copy.indexOf("=" + base);
		if (head > 0)
			head += 1;
	}

	if (head == -1)
	{
		head = copy.indexOf("&" + base);
		if (head > 0)
			head += 1;
	}

	if (head == -1) 
	{
		head = copy.indexOf(base);
		if (head != 0) 
			return null;
	} 
	  
	t1 = copy.indexOf(";", head);
	t2 = copy.indexOf("&", head);

	if (t1 > -1)
		tail = t1;
	
	if (t2 > -1)
	{
		if ((tail == -1) || (t2 < tail))
			tail = t2;
	}	

	if (tail == -1)
		tail = copy.length;

	value = unescape(real.substring(head + base.length,tail));

	return value;
}

function logout()
{
    LaunchWithLocal("http://www.risksearch.com/Scripts/Logout.asp");
}

function GoToDefault()
{
}
function Commercial()
{}
function Personal()
{}
function Hazard()
{}
function Management()
{}

function CommericalNew()
{
    LaunchWithLocal("http://www.risksearch.com/Scripts/MajorAccount.asp?RMSWF_DISPID=1");
}

function CommericalSearch()
{   
   
   LaunchWithLocal("http://www.risksearch.com/ConfigurableSearch/SearchComm.aspx?RMSWF_SEARCH=1")
}

function CommericalDelete()
{
    LaunchWithLocal("http://www.risksearch.com/ConfigurableSearch/DeleteComm.aspx?RMSWF_SEARCH=4");
}

function CommercialRenewal()
{
    LaunchWithLocal("http://www.risksearch.com/ConfigurableSearch/SearchComm.aspx?RMSWF_SEARCH=2");
}

function CommercailFindCommitted()
{
    LaunchWithLocal("http://www.risksearch.com/ConfigurableSearch/SearchComm.aspx?RMSWF_SEARCH=3");
}

function HazardNew()
{
    LaunchWithLocal("http://www.risksearch.com/Scripts/Location.asp?RMSWF_DISPID=1");
}

function HazardFind()
{
    LaunchWithLocal("http://www.risksearch.com/ConfigurableSearch/SearchProp.aspx?RMSWF_SEARCH=1");
}

function HazardDelete()
{
    LaunchWithLocal("http://www.risksearch.com/ConfigurableSearch/DeleteProp.aspx?RMSWF_SEARCH=2");
}

function Mutliloc()
{
    LaunchWithLocal("http://www.risksearch.com/Scripts/Location.asp?RMSWF_DISPID=12");
}

function PersonalNew()
{
    LaunchWithLocal("http://www.risksearch.com/Scripts/personalAccount.asp?RMSWF_DISPID=1");
}

function PersonalFind()
{
    LaunchWithLocal("http://www.risksearch.com/ConfigurableSearch/SearchPers.aspx?RMSWF_SEARCH=1");
}

function PersonalDelete()
{
    LaunchWithLocal("http://www.risksearch.com/ConfigurableSearch/DeletePers.aspx?RMSWF_SEARCH=2");
}

function FindAccum()
{
    LaunchWithLocal("http://www.risksearch.com/accumulation/find_accum.html");
}

function ChangeProfile()
{
    LaunchWithLocal("http://www.risksearch.com/Scripts/userProfile/userInfo.asp");
}

function FindJobs()
{
    LaunchWithLocal("http://www.risksearch.com/Scripts/findjob.asp");
}

function FindCommittedJobs()
{
    LaunchWithLocal("http://www.risksearch.com/Scripts/findcommittedjob.asp");
}

function RmsHome()
{
	if(Number(get_Cookie("RMSService")) == 2)
	{
		LaunchNewWindow("http://www.rms.com", "");
	}
}

function Help()
{
	if(Number(get_Cookie("RMSService")) == 2)
	{
		LaunchNewWindow("http://www.risksearch.com/Scripts/onhelp.asp?RMSWF_HLPID=26", "");
	}
	else
	{
		LaunchNewWindow("http://www.risksearch.com/Scripts/onhelp.asp?RMSWF_HLPID=2", "");
	}
}

function Main()
{
	if(Number(get_Cookie("RMSService")) == 1)
	{
		LaunchWithLocal("http://www.risksearch.com/Scripts/menu.asp");
	}
}

function AdminMain()
{
    LaunchWithLocal("http://www.risksearch.com/Scripts/Administrator.asp");
}

function NewDLMProfile()
{
    LaunchWithLocal("http://www.risksearch.com/DLMProfiles/CreateDLMProfile.aspx");
}

function SearchDLMProfile()
{
    LaunchWithLocal("http://www.risksearch.com/DLMProfiles/SearchDLMProfiles.aspx");
}

function UpdateAccum()
{
    LaunchWithLocal("http://www.risksearch.com/Scripts/AdminAccum/RenameAccumSearch.asp");
}

function AssignAccum()
{
    LaunchWithLocal("http://www.risksearch.com/Scripts/AdminAccum/AssignAccumSearch.asp");
}

function ProgressMonitor()
{
    LaunchWithLocal("http://www.risksearch.com/Progress/WebJobsMonitorInput.aspx");
}

function ResourceMgr()
{
    LaunchWithLocal("http://www.risksearch.com/Scripts/ResourceConfigMgr.asp");
}

function TechnicalSupport()
{
    LaunchWithLocal("http://www.risksearch.com/Scripts/SupportPage.asp");
}

function ChangeLogo()
{		
	if(Number(get_Cookie("RMSService")) == 1)
	{
		if(document.layers)
		{
			document.images["Logo"].src="http://www.risksearch.com/images/RB_logo.jpg";
		}
		else if (document.all)
		{
			document["Logo"].src="http://www.risksearch.com/images/RB_logo.jpg";
		}
	}
	else
	{
	    if(Number(get_Cookie("RMSService")) == 2)
	    {
		    if(document.layers)
		    {
			    document.images["Logo"].src="http://www.risksearch.com/RiskSearch/images/RiskSearch.jpg";
		    }
		    else if (document.all)
		    {
			    document["Logo"].src="http://www.risksearch.com/RiskSearch/images/RiskSearch.jpg";
		    }
	    }
	}
}

function ChangeRmsLogo()
{
	if(Number(get_Cookie("RMSService")) == 2)
	{
		if(document.layers && document.getElementById("LogoRms"))
		{			
			document.images["LogoRms"].src="http://www.risksearch.com/images/RMSlogo.gif";
		}
		else if (document.all && document.getElementById("LogoRms"))
		{
			document["LogoRms"].src="http://www.risksearch.com/images/RMSlogo.gif";
		}
	}
}

function Export()
{
    LaunchWithLocal("http://www.risksearch.com/Export/SelectDbToExport.aspx");
}

function Export2()
{
    LaunchWithLocal2("http://www.risksearch.com/Export/SelectDbToExport.aspx");
}

function PersonalDelete2()
{
    LaunchWithLocal2("http://www.risksearch.com/ConfigurableSearch/DeletePers.aspx?RMSWF_SEARCH=2");
}

function HazardDelete2()
{
    LaunchWithLocal2("http://www.risksearch.com/ConfigurableSearch/DeleteProp.aspx?RMSWF_SEARCH=2");
}

function CommericalDelete2()
{
    LaunchWithLocal2("http://www.risksearch.com/ConfigurableSearch/DeleteComm.aspx?RMSWF_SEARCH=4");
}

//Risk Search Menus
function CompanyRS()
{
    LaunchWithLocal("http://www.rms.com");
}

function EQDataRS()
{
    LaunchWithLocal("http://www.risksearch.com/RiskSearch/Products/Earthquake_Data.htm");
}

function HUDataRS()
{
    LaunchWithLocal("http://www.risksearch.com/RiskSearch/Products/Hurricane_Data.htm");
}

function FLDataRS()
{
    LaunchWithLocal("http://www.risksearch.com/RiskSearch/Products/Flood_Data.htm");
}

function LocationRS()
{
    LaunchWithLocal("http://www.rms.com/AboutRMS/Offices");
}

function CustomerSupport()
{
    LaunchWithLocal("http://www.risksearch.com/RiskSearch/Customer_Support.htm");
}

function HomeRS()
{
    LaunchWithLocal("http://www.risksearch.com/RiskSearch.html");
}

function SalesRS()
{
    LaunchWithLocal("http://www.risksearch.com/RiskSearch/Sales.htm");
}

function HomeRms()
{
	LaunchNewWindow("http://www.rms.com", "");
}
