// REQUIRES Russell.Core.js functions

var IsLoggedIn = false;
var CssEnabled = false;
AddEvent(window, 'load', AttachInitialEventListeners);

// Run all window.onload events here
function AttachInitialEventListeners()
{
	//EnableMediaTypeSelection();
	CheckIfLoggedIn();
	CheckIfCssEnabled();
    hijack_search_button();
    SetUpMultiViews();
    AttachLinkHandlers();
    RepositionFollowingButtonArea();
    expandoBox();
    EqualizeColumnHeights();
}

// Allow user to force display and print via a specific media type
function EnableMediaTypeSelection()
{
	if(window.location.search != '')
	{
		var mediaPat = /\?(&|&amp;)?media=(.+)(&|$)/i;
		var result = window.location.search.match(mediaPat);
		if (result && result.length > 2)
		{
			var mediaTgt = result[2];
			var ssMediaPattern = new RegExp('\\b(all|' +  mediaTgt + ')\\b', 'i');
			for (var i = 0; i < document.styleSheets.length; i++)
			{
				var ss = document.styleSheets[i];
				//alert(ss.href);
				var ssMedia = ss.media;
				var ssTag = (ss.ownerNode) ? ss.ownerNode : ss.owningElement;
				if (typeof ssMedia != 'string') ssMedia = ssMedia.mediaText;
				if (ssMediaPattern.test(ssMedia))
				{
					ssTag.media = 'all';
				}
				else
				{
					ssTag.media = 'none';
					ss.disabled = true;
				}
			}
		}
	}
}

// Inspect all links in order to handle special cases (such as "rel"-directed behaviors)
function AttachLinkHandlers()
{
	var pageLinks = document.links;
	for (var i = 0; i < pageLinks.length; i++)
	{
		var thisLink = pageLinks[i];
		if (thisLink.rel)
		{
			switch (thisLink.rel)
			{
				case 'UsdFeedback':
				case 'SalesFeedback':
					thisLink.onclick = OpenSalesFeedbackWindow;
					break;
				default:
					break;
			}
		}
	}
}

// Place the FollowingButtonArea under the SubNav
function RepositionFollowingButtonArea()
{
 var sn = document.getElementById('SubNav');
 var fb = document.getElementById('FollowingButtonArea');
 if (sn && fb)
 {
  fb.style.top = (sn.offsetTop + sn.offsetHeight - 142).toString() + 'px';
  AddClass(fb, 'repositioned');
 }
}

// Make all columns equal height
function EqualizeColumnHeights()
{
	var COLUMN_SECTIONS_MAX = 50;
	var COLUMNS_PER_SECTION_MAX = 5;
	
	var columnSections = new Array();
	if (ContainsClass(document.body, 'homepage'))
	{
		var base = document.getElementById('Base');
		if (base) columnSections.push(base);
	}
	for (var j = 1; j < COLUMN_SECTIONS_MAX; j++)
	{
		var temp = document.getElementById('ColumnSection' + j.toString());
		if (temp && !ContainsClass(temp, 'columns1'))
		{
			columnSections.push(temp);
		}
		else
		{
			break;
		}
	}
	
	for (var idx = 0; idx < columnSections.length; idx++)
	{
		var maxHeight = 0;
		var cols = new Array();
		var divs, thisDiv, thisDivHeight, thisDivTopBottomPadding;
		var thisCS = columnSections[idx];
		if (thisCS.id && thisCS.id == 'Base')
		{
			// Homepage
			for (var i = 1; i < COLUMNS_PER_SECTION_MAX; i++)
			{
				var tempCol = document.getElementById('BaseColumn' + i.toString());
				if (tempCol)
				{
					divs = tempCol.getElementsByTagName('div');
					for (var j in divs)
					{
						thisDiv = divs[j];
						if (ContainsClass(thisDiv, 'body'))
						{
							cols.push(thisDiv);
							thisDivTopBottomPadding = (parseInt(GetCSSValue(thisDiv, 'padding-bottom'), 10) || 0) + (parseInt(GetCSSValue(thisDiv, 'padding-top'), 10) || 0);
							thisDivHeight = thisDiv.clientHeight - thisDivTopBottomPadding;
							if (thisDivHeight > maxHeight) maxHeight = thisDivHeight;
							break;
						}
					}
				}
				else
				{
					break;
				}
				//alert(thisCS.id + '\n' + thisDiv.className + '\n' + GetCSSValue(thisDiv, 'padding-bottom') + '\n' +parseInt(GetCSSValue(thisDiv, 'padding-bottom'), 10).toString());
			}
		}
		else
		{
			divs = thisCS.getElementsByTagName('div');
			for (var j in divs)
			{
				thisDiv = divs[j];
				if (ContainsClass(thisDiv, 'column\\d+'))
				{
					cols.push(thisDiv);
					thisDivTopBottomPadding = (parseInt(GetCSSValue(thisDiv, 'padding-bottom'), 10) || 0) + (parseInt(GetCSSValue(thisDiv, 'padding-top'), 10) || 0);
					thisDivHeight = thisDiv.clientHeight - thisDivTopBottomPadding;
					if (thisDivHeight > maxHeight) maxHeight = thisDivHeight;
				}
				//alert(thisCS.id + '\n' + thisDiv.className + '\n' + GetCSSValue(thisDiv, 'padding-bottom') + '\n' +parseInt(GetCSSValue(thisDiv, 'padding-bottom'), 10).toString());
			}
		}
		for (var x = 0; x < cols.length; x++)
		{
			cols[x].style.minHeight = maxHeight.toString() + 'px';
			/* Serve additional line to IE6 only (using conditional compilation) */
			/*@cc_on
				@if (@_jscript)
					cols[x].style.height = maxHeight.toString() + 'px';
				@end
			@*/
		}
	}
}

function expandoBox()
{
	if (!document.getElementsByTagName) { return; }
	var divs = document.getElementsByTagName("div");

	// loop through all div tags
	for (var i=0; i<divs.length; i++)
	{
		var div = divs[i];

		// find the tipBox divs
		if (/(^|\s)tipBox(\s|$)/.test(div.className))
		{
			// loop through all h3 tags in the tipBox
			var h3s = div.getElementsByTagName('h3');
			for (var j=0; j<h3s.length; j++)
			{
				var h3 = h3s[j];
				// find the title h3
				if (/(^|\s)title(\s|$)/.test(h3.className))
				{
					h3.onclick = function () {tipThisBox(this); return false;}
				}
			}
		}
	}
}

// Overwrite search box functionality (existing search function is inline in template) - eBiz 10/12/2006
function hijack_search_button()
{
	var $element;
	if ($element = document.getElementById('SitePageTop1_NavbarSearch_btnSubmit')) {
		$element.onclick = search_redirect;
	}
}
// Check if the user is logged in and store in a global variable
function CheckIfLoggedIn()
{
	IsLoggedIn = /RLinkApp/.test(document.cookie);
}

// Check if CSS is enabled
function CheckIfCssEnabled()
{
	CssEnabled = function()
	{
		var returnVal = false;
		var cookieCss = GetCookie('css');
		if (cookieCss == null)
		{
			var newDiv = document.createElement('div');
			document.body.appendChild(newDiv);
			newDiv.style.width = '20px';
			newDiv.style.padding = '10px';
			var divWidth = newDiv.offsetWidth;
			document.body.removeChild(newDiv);
			returnVal = (divWidth == 40);
			SetCookie('css', returnVal.toString());
		}
		else
		{
			returnVal = (cookieCss == 'true');
		}
		return returnVal;
	}();
}

// Open/Close Tool Tip
function tipThisBox(elem)
{
	ToggleClass(elem.parentNode,'hideTip','showTip');
}

// Activate the RDS Calculator
function RedirectToRDS()
{
 var rdsUrl = '/RDS/HomePage.aspx';
 var RDS_Window = window.open(rdsUrl, 'RDS_Window','width=780,height=800,scrollbars=1,resizable=1,address=no');
 if (RDS_Window != null)
 {
  RDS_Window.focus();
 }
 else
 {
  window.location.href = rdsUrl;
 }
 return false;
}

// Enable search keywords
function search_redirect()
{
	var $array = new Array();
	//ADD NEW SEARCH TERMS AND DESTINATIONS HERE (case insensitive)
	$array['somefakesearch'] = '/Privacy_Notice.aspx';
	$array['!rmap'] = '/Russell_University/Practice_Management/Tools/Rmap.aspx';
	$array['@rmap'] = '/Russell_University/Practice_Management/Tools/Rmap.aspx';
	$array['#rmap'] = '/Russell_University/Practice_Management/Tools/Rmap.aspx';
	$array['*rmap'] = '/Russell_University/Practice_Management/Tools/Rmap.aspx';
	$array['?rmap'] = '/Russell_University/Practice_Management/Tools/Rmap.aspx';
	$array['gormap'] = '/Russell_University/Practice_Management/Tools/Rmap.aspx';
	$array['gotormap'] = '/Russell_University/Practice_Management/Tools/Rmap.aspx';
	$array['go2rmap'] = '/Russell_University/Practice_Management/Tools/Rmap.aspx';
	$array['=rmap'] = '/Russell_University/Practice_Management/Tools/Rmap.aspx';
	$array['equalrmap'] = '/Russell_University/Practice_Management/Tools/Rmap.aspx';
	$array['equalsrmap'] = '/Russell_University/Practice_Management/Tools/Rmap.aspx';
	$array['ageworkshops'] = '/Common/keywords/age_workshops.aspx';
	$array['fpa'] = '/Research_Commentary/Conferences/FPA_Retreat_2007.aspx';
	$array['globalinvesting'] = '/Research_Commentary/Capital_Markets_Insight/Global_Investing.aspx';
	$array['dain'] = '/Research_Commentary/Conferences/Dain_Conference_2007.aspx';

	//DO NOT EDIT BELOW THIS LINE
	var searchText = document.getElementById('SitePageTop1_NavbarSearch_txtSearchString').value;
	var $str = searchText.toLowerCase();
	$str = $str.replace(/\s/g,'');
	if( typeof($array[$str]) != 'undefined' )
	{
		window.location = $array[$str] + '?DCMP=ILC-KW-' + escape($str.replace(/[!,@,#,\*,\?,\=]/g,'')) + '&searchText=' + escape(searchText);
		return false;
	}
	else 
	{
		ShowAlert();
	}
}


//--------------------------------------------------------------------------------------------
// PopUp a USD Feedback Form Window 
//--------------------------------------------------------------------------------------------
// eBiz 11/30/2007

// Used only as wrapper to OpenSalesFeedbackWindow function, so that we can return null, which is required for the {href="javascript:SalesFeedback();"} link
function SalesFeedback()
{
	OpenSalesFeedbackWindow();
}
function OpenSalesFeedbackWindow()
{
	return OpenPopUp('/SA_View/ContactForm/Contact.aspx', 450, 450, 'SalesFeedbackWindow', 'menubar=0,resizable=1,toolbar=0,location=0,status=0,dependent=1');
}
function OpenHelpingAdvisorsWindow()
{
	return OpenPopUp('http://www.Russell.com/Helping-Advisors/', 1020, 650, 'helpingAdvisorsWindow', 'location=1,menubar=1,scrollbars=1,status=1,titlebar=1,toolbar=1,resizable=1,directories=1');
}

// Multi-purpose function to open popup windows. Can be used to simplify the many stand-alone functions currently implemented.
function OpenNewWindow(thisUrl, windowWidth, windowHeight, windowName, options)
{
    if (options == null) options = '';
    if (windowName == null) windowName = 'RussellLinkWindow';
	// Record non-trackable pages to HBX (100 character max on url for HBX's custom recording)
	if(!/\.(html?|aspx?)(\?|$)/i.test(thisUrl))
	{
		// HBX
		_hbDownload(thisUrl.toLowerCase());
		hbx_custom_record(thisUrl.toLowerCase().match(/.{1,100}$/)[0]);
		// Omniture
		if (/function/i.test(typeof(customEventRecord)))
		{
			customEventRecord(windowName, 'd', thisUrl);
		}
	}

    var params = new Object();
	var opts = options.toLowerCase().split(',');
	for (var i in opts)
	{
		var pair = opts[i].split('=');
		params[pair[0]] = pair[1];
	}
	if ((windowWidth && !isNaN(windowWidth)) || (params['width'] && !isNaN(params['width'])))
	{
		var screenWidth = screen.availWidth;
		if (!windowWidth || isNaN(windowWidth)) windowWidth = params['width'];
		if (windowWidth > screenWidth) windowWidth = screenWidth;
		params['width'] = params['outerWidth'] = windowWidth;
		if (params['left'] == null) params['left'] = parseInt((screenWidth - windowWidth) / 2);
	}
	if ((windowHeight && !isNaN(windowHeight)) || (params['height'] && !isNaN(params['height'])))
	{
		var screenHeight = screen.availHeight;
		if (!windowHeight || isNaN(windowHeight)) windowHeight = params['height'];
		if (windowHeight > screenHeight) windowHeight = screenHeight;
		params['height'] = params['outerHeight'] = windowHeight;
		if (params['top'] == null) params['top'] = parseInt((screenHeight - windowHeight) / 3);
	}
	var allOptions = '';
	for (var key in params)
	{
		allOptions += key + '=' + params[key] + ',';
	}
	allOptions = allOptions.replace(/,$/, '');
	//alert('options:\n' + allOptions);
	var win = window.open(thisUrl, windowName, allOptions);
	win.focus();
	return win;
}
function OpenPopUp(thisUrl, windowWidth, windowHeight, windowName, options)
{
	return OpenNewWindow(thisUrl, windowWidth, windowHeight, windowName, options) == null;
}
function OpenBarePopUp(thisUrl, windowWidth, windowHeight, windowName)
{
	return OpenPopUp(thisUrl, windowWidth, windowHeight, windowName, 'scrollbars=1,directories=0,menubar=0,status=0,toolbar=0,resizable=1');
}

// MultiView
function MultiView_Manager()
{
	this.Classname = 'multiView';
	this.Trigger_Classname_Suffix = '_trigger';
	this.SelectedView_Classname = 'selected';
	this.EnhancedView_Classname = 'enhancedView';
	this.SelectedView_HiddenClassname_Suffix = '_hidden';
	this.PutSelectedViewClassnameOnParent = false;
	this.AllowViewCollapse = false;
	this.ScopingElement = document;
	this.MultiViews = new Array();
	this.urlRegex = new RegExp('^' + document.location.toString().replace(document.location.hash, '').replace('?', '\\?') + '#(.+)');
	this.CssMedia = 'screen,projection,tv';
	return this;
}
MultiView_Manager.prototype.Initialize = function ()
{
	var divs = this.ScopingElement.getElementsByTagName('div');
	for (var i = divs.length-1; i >= 0; i--)
	{
		var thisDiv = divs[i];
		if (ContainsClass(thisDiv, this.Classname))
		{
			var newMV = new MultiView(this, thisDiv);
			if (newMV)
			{
				this.MultiViews.push(newMV);
			}
		}
	}
	for (var mvIndex = 0; mvIndex < this.MultiViews.length; mvIndex++)
	{
		var thisMV = this.MultiViews[mvIndex].Init();
	}
	var pageHash = document.location.hash;
	if (pageHash)
	{
		pageTarget = document.getElementById(pageHash.replace(/^#/, ''));
		if (pageTarget && pageTarget.multiViewTrigger)
		{
			pageTarget.multiViewTrigger.MultiView.SelectView.call(pageTarget.multiViewTrigger.Link);
			window.scrollTo(0,0);
		}
	}
	if (this.MultiViews.length > 0) this.RenderCSS();

isReady = true;

}
MultiView_Manager.prototype.RenderCSS = function ()
{
	var returnVal = false;
	var SS = null;
	var x = 0;
	var isFound = false;
	var cssNode = document.createElement('style');
	cssNode.id = 'MultiViewStylesheet';
	cssNode.type = 'text/css';
	cssNode.media = this.CssMedia;
	cssNode.title = 'MultiView Stylesheet';
	document.getElementsByTagName("head")[0].appendChild(cssNode);
	for (x = document.styleSheets.length - 1; x >= 0; x--)
	{
		if (document.styleSheets[x].title == cssNode.title)
		{
			cssNode.removeAttribute('title');
			isFound = true;
			break;
		}
	}
	if (isFound)
	{
		for (var j = 0; j < this.MultiViews.length; j++)
		{
			var thisMV = this.MultiViews[j];
			//InsertCssRule(document.styleSheets[x], '#' + thisMV.ContainerElement.id + ' .' + thisMV.HiddenElementsClassname, 'display: none;');
			for (var k in thisMV.Views)
			{
				InsertCssRule(document.styleSheets[x], '#' + k, 'display: none;');
				InsertCssRule(document.styleSheets[x], 'body.' + k + ' #' + k, 'display: ' + thisMV.Views[k][0].Trigger.TargetDefaultDisplay + ';');
				InsertCssRule(document.styleSheets[x], 'body.' + k + ' .' + k + thisMV.Manager.SelectedView_HiddenClassname_Suffix, 'display: none;');
			}
		}
		document.styleSheets[x].disabled = false;
		returnVal = true;
	}
	return returnVal;
}
function InsertCssRule(objStylesheet, strSelector, strDeclarations)
{
	if (objStylesheet.insertRule)
	{
		objStylesheet.insertRule(strSelector + ' {' + strDeclarations + '}', objStylesheet.cssRules.length);
		returnVal = true;
	}
	else if (objStylesheet.addRule)
	{
		objStylesheet.addRule(strSelector, strDeclarations, objStylesheet.rules.length);
		returnVal = true;
	}
}
function MultiView(manager, containerElem)
{
	this.Manager = manager;
	this.ContainerElement = containerElem;
	if (!this.ContainerElement.id || this.ContainerElement.id == '')
	{
		alert('no id!');
		return;
	}
	this.TriggerClassname = this.ContainerElement.id + this.Manager.Trigger_Classname_Suffix;
	this.HiddenElementsClassname = this.ContainerElement.id + this.Manager.SelectedView_HiddenClassname_Suffix;
	this.Views = new Object();
	this.CurrentView = null;
	this.AvailableClasses = '';
	return this;
}
MultiView.prototype.Init = function()
{
	// Populate Views and AvailableClasses
	var tgtToView = null;
	var atags = document.getElementsByTagName('a');
	for (var i = 0; i < atags.length; i++)
	{
		var thisA = atags[i];
		if (thisA.href && ContainsClass(thisA, this.TriggerClassname))
		{
			var matches = thisA.href.match(this.Manager.urlRegex);
			if (matches && matches.length > 1)
			{
				var tgt = document.getElementById(matches[1]);
				if (tgt)
				{
					var newTrigger = new MultiViewTrigger(this, thisA, tgt);
					if (!this.Views[matches[1]])
					{
						this.Views[matches[1]] = [tgt, new Array()];
					}
					this.Views[matches[1]][1].push(newTrigger);
					this.AvailableClasses += matches[1] + '|'
					if (ContainsClass(newTrigger.ClassTarget, this.Manager.SelectedView_Classname))
					{
						tgtToView = tgt;
						RemoveClass(newTrigger.ClassTarget, this.Manager.SelectedView_Classname)
					}
				}
			}
		}
	}
	this.AvailableClasses = this.AvailableClasses.replace(/\|$/, '');
	AddClass(this.ContainerElement, this.Manager.EnhancedView_Classname);
	if (tgtToView)
	{
		// Safari/Chrome lose reference to link here
		this.SelectView.call(tgtToView.Trigger.Link);
	}
}
MultiView.prototype.SelectView = function(e)
{
	var returnValue = false;
	try
	{
		var self = this;
		if (!self.Trigger && window.event && window.event.srcElement) self = window.event.srcElement;
		if ('a' != self.nodeName.toLowerCase()) self = GetAncestorElement(self, 'a');
		if (self == null) return returnValue;
		var thisMV = self.Trigger.MultiView;
		if (thisMV.CurrentView)
		{
			var triggerArr = thisMV.Views[thisMV.CurrentView.Trigger.Target.id][1];
			for (var i = 0; i < triggerArr.length; i++)
			{
				RemoveClass(triggerArr[i].ClassTarget, thisMV.Manager.SelectedView_Classname);
			}
			RemoveClass(document.body, thisMV.CurrentView.id);
		}
		if (thisMV.Manager.AllowViewCollapse && thisMV.CurrentView === self.Trigger.Target)
		{
			thisMV.CurrentView = null;
		}
		else
		{
			thisMV.CurrentView = self.Trigger.Target;
			var triggerArr2 = thisMV.Views[self.Trigger.Target.id][1];
			for (var j = 0; j < triggerArr2.length; j++)
			{
				AddClass(triggerArr2[j].ClassTarget, thisMV.Manager.SelectedView_Classname);
			}
			AddClass(document.body, thisMV.CurrentView.id);
			// Bubble up
			var parent = thisMV.CurrentView.parentNode;
			while (parent.nodeName.toLowerCase() != 'body' && !parent.multiViewTrigger)
			{
				parent = parent.parentNode;
			}
			if (parent.nodeName.toLowerCase() != 'body')
			{
//if (isReady) alert('Current:\n' + self.innerHTML + '\n' + thisMV.ContainerElement.id + '\n\nParent:\n' + parent.multiViewTrigger.Link.innerHTML + '\n' + parent.multiViewTrigger.MultiView.ContainerElement.id + '\n\n' + parent.nodeName.toLowerCase() + (parent.id ? '#' + parent.id : '') + (parent.className ? '.' + parent.className : ''));
				if (document.body.click)
				{
					parent.multiViewTrigger.Link.click();
				}
				else
				{
					parent.multiViewTrigger.MultiView.SelectView.call(parent.multiViewTrigger.Link);
				}
			}
		}
		returnValue = true;
	}
	catch (err)
	{
		alert('Error detected in MultiView code:\n\n' + err.name + ':\n' + err.message);
		returnValue = false;
	}
	finally
	{
		if (returnValue)
		{
			if (window.event)
			{
				window.event.returnValue = !returnValue;
			}
			else if (e)
			{
				e.preventDefault();
			}
		}
		return returnValue;
	}
}
function MultiViewTrigger(parentMultiView, aTag, targetElem)
{
	this.MultiView = parentMultiView;
	this.Link = aTag;
	this.Target = targetElem;
	this.Link.Trigger = this.Target.Trigger = this;
	targetElem.multiViewTrigger = this;
	AddEvent(this.Link, 'click', this.MultiView.SelectView);
	this.TargetID = this.Target.id;
	this.TargetDefaultDisplay = GetCSSValue(targetElem, 'display');
	this.ClassTarget = this.MultiView.Manager.PutSelectedViewClassnameOnParent ? this.Link.parentNode : this.Link;
	return this;
}
var MVM;
function SetUpMultiViews()
{
	MVM = new MultiView_Manager();
	MVM.PutSelectedViewClassnameOnParent = true;
	MVM.Initialize();
}



var isReady = false;
