//show a lightbox that asks the user to register
function showOverlayRegister(message){
	showOverlayHelper("register", message);
}

function showOverlayUserName(message)
{
	showOverlayHelper("username", message);
}

// show a lightbox that asks the user to log in
function showOverlayLogin(message){
	var theMessage = (message) ? message : "";
	showOverlayHelper("login", theMessage);
}

// show a lightbox that displays a message to the user
function showOverlayMessage(message){
	showOverlayHelper("information", message);
}

// show a lightbox that displays a message to the user
//function showOverlayGrabIt(message){
	//showOverlayHelper("grabit", message);
//}
// helper function that is called by other lightbox functions
// dialogType: whether it is a register, login, or message dialog
// message: an optional string message to display to the user
function showOverlayHelper(action, message){
	link = document.createElement('a');
	link.href = currentBaseUrl + '/Ajax/GenericOverlay.aspx?action=' + action + "&message=" + escape(message) + "&ref=" + escape(window.location);
	link.className = "lbOn";
	var valid = new lightbox(link);
	valid.activate();
	return true;
}

// Display lightbox containing player stats widget on MyPlayer and ViewPlayer.
function showOverlayPlayerGrab(playerID){
	link = document.createElement('a');
	link.href = currentBaseUrl + '/GrabIt.aspx?t=' + playerID + '&ref=player';
	link.className = "lbOn";
	var valid = new lightbox(link);
	valid.activate();
	return true;
}

// Display lightbox containing featured video widget on Video ag page.
function showOverlayVideoGrab(videoID){
	link = document.createElement('a');
	link.href = currentBaseUrl + '/GrabIt.aspx?v=' + videoID + '&ref=video';
	link.className = "lbOn";
	var valid = new lightbox(link);
	valid.activate();
	return true;
}

// Display lightbox containing most recent video widget on Video ag page.
function showOverlayRecentVideoGrab(){
	link = document.createElement('a');
	link.href = currentBaseUrl + '/GrabIt.aspx?ref=recentvideos';
	link.className = "lbOn";
	var valid = new lightbox(link);
	valid.activate();
	return true;
}

// Display lightbox containing most recent video widget on Video ag page.
function showOverlayTopStocks(){
	link = document.createElement('a');
	link.href = currentBaseUrl + '/GrabIt.aspx?ref=topstocks';
	link.className = "lbOn";
	var valid = new lightbox(link);
	valid.activate();
	return true;
}
// Display lightbox containing most recent video widget on Video ag page.
function showOverlayStockSpotlight(ticker){
	link = document.createElement('a');
	link.href = currentBaseUrl + '/GrabIt.aspx?ticker=' + ticker + '&ref=spotlight';
	link.className = "lbOn";
	var valid = new lightbox(link);
	valid.activate();
	return true;
}

// This function governs the behavior of overlay pops.
function menus (whichMenu,whatState,PositionTop,PositionLeft,PositionRight)
{
	$(whichMenu).style.visibility = whatState;
	$(whichMenu).style.top = PositionTop;
	$(whichMenu).style.left = PositionLeft;
	$(whichMenu).style.right = PositionRight;
}

// This method will toggle on and off the pitch in the StockPicks control.
function TogglePlayerPitch(sender, pitchRowIdentifier)
{
	// Get the existing 60 second pitch row.
	var existingRow = $(pitchRowIdentifier);

	// If there is no row then add it.
	if (existingRow==null)
	{
		return false;
	}
	else
	{
		// If the existing row is off, turn it on and vice versa.
		if (existingRow.style.display=="none")
		{
			existingRow.style.display = "";

			// Change the image.
			if (sender.src.indexOf('pitch_open') != -1)
			{
				sender.src = ReplaceStr(sender.src, 'pitch_open', 'pitch_collapse');
			}
			else
			{
				sender.src = ReplaceStr(sender.src, 'pitch_multiple', 'pitch_close_multiple');
			}
		}
		else
		{
			existingRow.style.display = "none";

			// Change the image.
			if (sender.src.indexOf('pitch_collapse') != -1)
			{
				sender.src = ReplaceStr(sender.src, 'pitch_collapse', 'pitch_open');
			}
			else
			{
				sender.src = ReplaceStr(sender.src, 'pitch_close_multiple', 'pitch_multiple');
			}
		}
	}
}

// This function will get the first (closest) parent of the element with the tag name passed in.
function GetParentElementByTagName(el, tagName)
{
	var element=el;
	while(element.tagName != tagName)
	{
		element = element.parentNode;
	}
	return element;
}

function GetElementByTagNameAndId(elementId, tagName)
{
	var tags = document.getElementsByTagName(tagName);
	var i = 0;

	// Loop through all of the elements with the given tag name.
	for(i; i < tags.length; i++)
	{
		// If this is element contains the elementId then we've found it.
		if (tags[i].id.indexOf(elementId) != -1)
		{
			return tags[i];
		}
	}

	return null;
}

// String replacement function.
function ReplaceStr(orgString, findString, replString)
{
	pos = orgString.lastIndexOf(findString);
	return orgString.substr(0, pos) + replString + orgString.substr(pos + findString.length);
}

// This function will get a Random Pitch For A Given User and show it.
function GetRandomPitch(sender, token)
{
	var rand = Math.random();
	var url = currentBaseUrl + '/Ajax/GetRandomPitch.aspx';
	var pars = 't=' + token + '&ref=' + escape(currentUrl) + '&rand=' + rand;
	var callFilter = GetElementByTagNameAndId('drpPitchRuleSetFilterType', 'SELECT');

	if (callFilter !== null)
	{
		pars = pars + '&pitchruleset=' + callFilter.value;
	}

	Element.hide('divMoreBuzzFailure');
	Element.show('divBuzz');


	var mygAjax = new Ajax.Updater(
		GetElementByTagNameAndId('divCommunityChatterBox', 'DIV'),
		url,
		{
			method: 'get',
			parameters: pars,
			onFailure: showMorebuzzfailure,
			showFeedback: false // show loading box even when turned off for the page
		});
}

function showMorebuzzfailure(response)
{
	Element.show('divMoreBuzzFailure');
	Element.hide('divBuzz');

	showGenericErrorMessage(response);
}

// This function called when user clicks on the $-sign to indicate that a stock
// shown in the MyPlayer scorecard should be set or unset as a "top pick".
function SetTopPick(pickId, setAsTopPick)
{
	var url = '/Ajax/MarkTopPick.aspx';
	var pars = 'pid=' + pickId + '&tpval=' + (setAsTopPick ? 1 : 0);

	var myAjax = new Ajax.Updater(
	"topPick" + pickId,
	url,
	{
			method: 'post',
			parameters: pars,
			onFailure: showGenericErrorMessage,
			onSuccess: addWatchlistPickSuccess,
			evalScripts: true
	});
}

// This function will get a user's 60-second pitch and show it.
// If it already exists then it will just toggle the
// visibility of the row.
function GetPitch(sender, pickId, whichView)
{
	var url = currentBaseUrl + '/Ajax/GetPitchReplies.aspx';
	var pars = 'pid=' + pickId + '&ref=' + escape(currentUrl);
	var pitchRowId = pickId + whichView + 'PitchRow';

	// If we are just getting the first post then check to see if it is already there.
	if (CheckExistingPitch(pitchRowId) == true)
	{
		TogglePlayerPitch (sender, pitchRowId);
		return;
	}

	if (whichView == 'data')
	{
		url = currentBaseUrl + '/Ajax/GetPitchReplies.aspx';
	}
	else
	{
		url = currentBaseUrl + '/Ajax/GetPitchForBlogView.aspx';
	}

	var newTD = createNewTableRowAndTDForPitches(sender, pitchRowId);

	var myAjax = new Ajax.Updater(
		newTD,
		url,
		{
			method: 'get',
			parameters: pars,
			onFailure: showGetPitchFailure
		});
}

function showGetPitchFailure(response)
{
	Element.show('divShowDataPitchFailure');
	Element.show('divShowBlogPitchFailure');

	showGenericErrorMessage(response);
}

function AddFavorite(sender, playerToken, favoriteToken, whichView)
{
	var url = currentBaseUrl + '/Ajax/AddPlayerFavorite.aspx';
	var pars = 't=' + playerToken + '&ft=' + favoriteToken;
	var callback = 'showFavoritePlayerAdded';

	if (!VerifyAuthorization())
	{
		return false;
	}

	var myAjax = new Ajax.Request(
	url,
	{
		method: 'get',
		parameters: pars,
		onSuccess: function() {Element.hide(sender); Element.show('divPlayerAdded'); Element.hide('addPlayer');},
		onFailure: showFavoritePlayerAdditionFailure
	});
}

function showFavoritePlayerAdditionFailure(response)
{
	showGenericErrorMessage(response);

	Element.show('divPlayerAddedFailure');
	Element.hide('addPlayer');
}

function showGenericErrorMessage(response)
{
	var statusCode = response.status;
	// If the status is a 405 message then the user needs to log in order to perform this action
	if (statusCode == '405')
	{
		showOverlayLogin(response.statusText);
		return false;
	}
	// If the status is a 403 message then the user needs to register.
	if (statusCode == '403')
	{
		showOverlayRegister(response.statusText);
		return false;
	}
		// If the status is a 701 message then the user needs a username.
	if (statusCode == '701')
	{
		showOverlayUserName(response.statusText);
		return false;
	}
	showOverlayMessage(response.statusText);
	return false;
}

// Remove this player as a favorite.
function RemoveFavorite(sender, playerToken, favoriteToken, whichView)
{
	var url = currentBaseUrl + '/Ajax/RemoveFavoritePlayer.aspx';
	var pars = 't=' + playerToken + '&ft=' + favoriteToken;

	if (!VerifyAuthorization())
	{
		return false;
	}
	var myAjax = new Ajax.Request(
	url,
	{
		method: 'get',
		parameters: pars,
		onFailure: showGenericErrorMessage,
		// Hide the whole row
		onSuccess: function() {Element.hide(sender.parentNode.parentNode.parentNode);}
	});
}

// This function will return true if a pitch row already exists.
function CheckExistingPitch(rowIdentifier)
{
	// Get the existing 60 second pitch row.
	var existingRow = $(rowIdentifier);

	// If there is no row then add it.
	if (existingRow==null)
	{
		return false;
	}
	else
	{
		return true;
	}
}

// This function will mark a post as "helpful"
function MarkPostAsHelpful(sender, messageId, pickId, whichView)
{
	var url = currentBaseUrl + '/Ajax/MarkPostHelpful.aspx';
	var pars = 'pid=' + pickId + '&mid=' + messageId + '&view=' + whichView + '&ref=' + escape(currentUrl);
	var pitchContainer = $('pitchView' + messageId);
	var ajaxReplacementNode;

	if (!VerifyAuthorization())
	{
		return false;
	}

	if (whichView == 'data')
	{
		ajaxReplacementNode = pickId + 'dataPitchRowPitchTD';
	}
	else
	{
		ajaxReplacementNode = pitchContainer.parentNode;
	}


	var myAjax = new Ajax.Updater(
	ajaxReplacementNode,
	url,
	{
		method: 'get',
		parameters: pars,
		onFailure: showGenericErrorMessage
	});
}

// Recommend a blog post
function RecommendBlogPost(sender, blogPostId)
{
	var url = currentBaseUrl + '/Ajax/RecommendBlogPost.aspx';
	var pars = 'bpid=' + blogPostId + '&ref=' + escape(currentUrl);
	// the ajax ID is generated from the post ID
	var ajaxReplacement = $(sender).up('.ajaxContainer');

	if (!VerifyAuthorization())
	{
		return false;
	}

	var myAjax = new Ajax.Updater(
	ajaxReplacement,
	url,
	{
		method: 'get',
		parameters: pars,
		onFailure: showGenericErrorMessage
	});
}

// This function will show all closed pitches.
function ShowAllPitches(whichView)
{
	var images = window.document.images;
	var i = 0;
	var image;

	for(i; i < images.length; i++)
	{
		image = images[i];

		if ((image.src.lastIndexOf("pitch_open") > 0 || image.src.lastIndexOf("pitch_multiple") > 0)
			&& image.name !== "" && image.id.toLowerCase().indexOf(whichView) > 0)
		{
			GetPitch(image, image.name, whichView);
		}
	}

	if (whichView == 'data')
	{
		Element.hide('showPitches');
		Element.show('collapsePitches');
	}
	else
	{
		Element.hide('showPitchesBlogView');
		Element.show('collapsePitchesBlogView');
	}
}

// This function will collapse all open pitches.
function CollapseAllPitches(whichView)
{
	var images = window.document.images;
	var i = 0;
	var image;

	for(i; i < images.length; i++)
	{
		image = images[i];

		if ((image.src.lastIndexOf("pitch_collapse" + ".gif") > 0 ||
			image.src.lastIndexOf("pitch_close_multiple" + ".gif") > 0)
			&& image.id.toLowerCase().indexOf(whichView) > 0) // Opera 7.5 attempts to download image if full name
		{
			var pitchRowId =  image.name + whichView +'PitchRow';
			TogglePlayerPitch (image, pitchRowId);
		}
	}

	if (whichView == 'data')
	{
		Element.show('showPitches');
		Element.hide('collapsePitches');
	}
	else
	{
		Element.show('showPitchesBlogView');
		Element.hide('collapsePitchesBlogView');
	}
}

// Show all commentary replies
function ExpandAllBlogPitchReplies(expandLink)
	{
		var links = $$("div#divblogViewOfPitchesCommunityPlayers a.getThread");
		var i = 0;

		for (i = 0; i < links.length; i++)
		{
			links[i].onclick(null); // Simulates clicking on the link
		}

		var expandDiv = GetElementByTagNameAndId("ExpandAll", "P");
		if (expandDiv != null)
		{
			expandDiv.style.display = "none";
		}

		var collapseDiv = GetElementByTagNameAndId("CollapseAll", "P");
		collapseDiv.style.display = "block";
	}
// Hide all Commentary replies
function HideCollapseAll()
{
	var expandDiv = GetElementByTagNameAndId("ExpandAll", "P");
	expandDiv.style.display = "block";

	var collapseDiv = GetElementByTagNameAndId("CollapseAll", "P");
	collapseDiv.style.display = "none";
}

// This method will open a new window to perform a Multi-Stock Pick.
function pickStocks(watchlistPickGroupIDValue)
{
	var input;
	var url = currentBaseUrl + '/MultiTickerEntry.aspx?';

	if(watchlistPickGroupIDValue !== null && watchlistPickGroupIDValue > 0)
	{
		input = $('txtMultipleStockPickWL');
	}
	else
	{
		input = $('txtMultipleStockPick');
	}

	// If we do not have any input then return.
	if(input.value.length < 1)
	{
		return true;
	}

	var tickerString = input.value;
	var regEx = /\s+|;+/g;
	tickerString = tickerString.replace(regEx, ',');

	var tickerArray = tickerString.split(',');
	var isFirstTicker = true;
	var i = 0;
	var height = 124;

	// loop through all of the tickers
	for(i; i < tickerArray.length; i++)
	{
		// Ignore empty strings
		if (tickerArray[i].trim().length > 0)
		{
			if (!isFirstTicker)
			{
				url += '&';
			}

			isFirstTicker = false;
			url += 'ticker=' + tickerArray[i].trim();

			//Only Add To The Height 3 Times to not overblow 600 res
			if (i <=5)
			{
				height += 134;
			}
		}
	}

	if(watchlistPickGroupIDValue !== null && watchlistPickGroupIDValue > 0)
	{
		url += '&pgid=' + watchlistPickGroupIDValue + '&wl=y';

		if (currentUrl.toLowerCase().indexOf('contest') > 0)
		{
			url += '&contest=y';
		}
	}

	var stockPickWin = window.open(url, 'PickStocks','scrollbars=yes,width=700,height=' + height + ',status=1');
	stockPickWin.focus();
}
/**
* Launches the multi-ticker Advanced Pick Utility (APU) window.
*
* Usage: showAdvancedPickUtility("GOOG,MSFT,TGT");
*
* @param {string} tickers: a comma-delimited list of tickers to be passed to the APU
* @returns void
*/
function showAdvancedPickUtility(tickers) {
    var params = $H({ 'tickers': tickers });
    var url = currentBaseUrl + '/Picks/AdvancedPickUtility.aspx?' + params.toQueryString();
    var popWin = window.open(url, 'PickStocks', 'scrollbars=yes,width=740,height=480,status=1');
    $('txtMultipleStockPick').value = '';
    popWin.focus();
}

function toggleTabsForCommunityPlayers(tabName)
{
    // Get all of the tabs
    // Using the strings that come back as tabname so we can generalize some stuff
    var tabs = {};
    tabs.sdv = GetElementByTagNameAndId('tabDataView', 'li'); // scorecard
    tabs.bgv = GetElementByTagNameAndId('tabBlogView', 'li'); // commentary
    tabs.ctv = GetElementByTagNameAndId('tabContestView', 'li'); // contests
    tabs.wlv = GetElementByTagNameAndId('tabWatchLists', 'li'); // watchlist
    tabs.mlv = GetElementByTagNameAndId('tabManageLimits', 'li'); //manage limts

    var containers = {};
    containers.sdv = GetElementByTagNameAndId("divdataViewOfPitchesCommunityPlayers", "DIV"); //scorecard
    containers.bgv = GetElementByTagNameAndId("divblogViewOfPitchesCommunityPlayers", "DIV"); //commentary
    containers.ctv = GetElementByTagNameAndId("divContestViewOfCommunityPlayers", "DIV"); //contests
    containers.wlv = GetElementByTagNameAndId("divWatchlistViewOfCommunityPlayers", "DIV"); // watchlist
    containers.mlv = document.getElementById("limitOrdersView"); // manage Limits

    // Hide containers
    for (container in containers) {
	var cnt = containers[container];
	if (cnt) {
	    $(cnt).hide();
	}
    }

    // hide some other elemnts that get treated on atab by tab basis
    var watching = $("watching");
    if (watching) {
	$(watching).hide();
    }
    var picks = $('picks');
    if (picks) {
	$(picks).show();
    }

    // Make all tabs not current
    for (tab in tabs) {
	var tb = tabs[tab];
	if (tb) {
	    $(tb).select("a.current").invoke("removeClassName", "current");
	}
    }

    // set current container and tab
    var currentContainer = containers[tabName];
    var currentTab = tabs[tabName];
    $(currentContainer).show();
    $(currentTab).down("a").addClassName("current");

    // actually do stuff
    switch(tabName) {
	case "ctv":
	    var contestDetailsDiv = $('divContestStockPicks');
	    var contestButton = $('btnPlayerGetContest');

	    if (contestDetailsDiv != null && contestButton != null) {
	    // If there is no contest data then get some.
	    if (contestDetailsDiv.innerHTML.length <= 10) {
		contestButton.click();
	    }
	}
	break;
    case "wlv":
	Element.show('watching');
	break;
    }
}

function createNewTableRowAndTDForPitches(sender, rowIdentifier)
{
	var firstRow = 0;
	var table = GetParentElementByTagName(sender, "TABLE");
	var index = GetParentElementByTagName(sender, "TR").sectionRowIndex + 1;
	var newRow = table.insertRow(index);

	newRow.id = rowIdentifier;
	var newTD = document.createElement("TD");

	if(table.rows[0].cells[0].colSpan > 1)
	{
		newTD.colSpan = table.rows[0].cells[0].colSpan;
	}
	else
	{
		newTD.colSpan = table.rows[0].cells.length;
	}

	// Append the new TD to the new row.
	var myTD = newRow.appendChild(newTD);
	myTD.className = "";
	myTD.id = rowIdentifier + "PitchTD";

	// Change the image.
	if (sender.src.indexOf('pitch_open') != -1)
	{
		sender.src = ReplaceStr(sender.src, "pitch_open", "pitch_collapse");
	}
	else
	{
		sender.src = ReplaceStr(sender.src, "pitch_multiple", "pitch_close_multiple");
	}

	return myTD;
}

// PV: Is this function still in use? Does not appear to be called anywhere.
function getBlogContent(sender, pickId, whichView)
{
	var url = currentBaseUrl + '/Ajax/GetPitchForBlogView.aspx';
	var pars = 'pid=' + pickId + '&ref=' + escape(currentUrl);
	var pitchRowId = pickId + whichView + 'PitchRow';

	// If we are just getting the first post then check to see if it is already there.
	if (CheckExistingPitch(pitchRowId) == true)
	{
		TogglePlayerPitch (sender, pitchRowId);
		return;
	}

	var newTD = createNewTableRowAndTDForPitches(sender, pitchRowId);

	var myAjax = new Ajax.Updater(
		newTD,
		url,
		{
			method: 'get',
			parameters: pars,
			onFailure: showGetPitchFailure
		});
}

function clickButton(e, buttonid)
{
	var bt = GetElementByTagNameAndId(buttonid, 'INPUT');

	if (typeof bt == 'object')
	{
		//Enter Key
		if (e.keyCode == 13)
		{
			bt.click();
			return false;
		}
	}
}

//Blocks any key activity other than numeric key presses
function numericOnly(e)
{
	if(e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 46)
	{
		//backspace, delete and tab keys are allowed thru
		return true;
	}

	if (navigator.appName.indexOf('Netscape') != -1)
	{
		if((e.which < 48) || (e.which > 57))
		{
			return false;
		}
		return true;
	}
	else
	{
		e = window.event;

		if((e.keyCode < 48) || (e.keyCode > 57))
		{
			return false;
		}
		return true;
	}
}

// Check that a string contains only numbers
function isNumeric(string, ignoreWhiteSpace) {
	if (string.search)
	{
		if ((ignoreWhiteSpace && string.search(/[^\d\s]/) != -1) || (!ignoreWhiteSpace && string.search(/\D/) != -1)) {
			return false;
		}
	}
	return true;
}

// Remove all spaces from a string
function removeSpaces(string) {
	var newString = '';
	for (var i = 0; i < string.length; i++)
	{
		if (string.charAt(i) != ' ') {
			newString += string.charAt(i);
		}
	}
	return newString;
}

// This function is a dynamic Ajax function that is used to get any paged list. The paging, sort, and filter
// values are passed into this function which dynamically builds a GET request url then replaces the innerHTML
// content of some DOM object with the content returned by the request.
function GetPagedList(ajaxUrl, replacementObjectId, pageNumber, filterType, sortColumn, sortType, ticker, token, playerType, pickGroupId)
{
	// Set up the query string.
	var pars = 'objid=' + escape(replacementObjectId);
	var txtPageSize;

	// Check if this is a BlogViewOfPitches transaction.
	if (ajaxUrl.indexOf('GetBlogView.aspx') > 0 )
	{
		txtPageSize = GetElementByTagNameAndId('txtBlogViewOfPitchesPageSize', 'INPUT');

	}
	// The other type is of StockPicks.  If a new type is added, don't forget to rework this.
	else
	{
		txtPageSize = GetElementByTagNameAndId('txtPageSize', 'INPUT');
	}


	// Add page number to the query string.
	if ((pageNumber.length > 0) && (pageNumber != '-1'))
	{
		pars = pars + '&pagenum=' + pageNumber;
	}

	// Add the filter query string.
	if ((filterType.length > 0) && (filterType != '-1'))
	{
		pars = pars + '&filter=' + filterType;
	}

	// Add the sort column query string.
	if ((sortColumn.length > 0) && (sortColumn != '-1'))
	{
		pars = pars + '&sortcol=' + sortColumn;
	}

	// Add the sort type query string.
	if (sortType.length > 0 && (sortType != '-1'))
	{
		pars = pars + '&sortdir=' + sortType;
	}

	// Add the ticker query string.
	if (ticker.length > 0)
	{
		pars = pars + '&ticker=' + ticker;
	}

	// Add the player type query string.
	if (playerType.length > 0 && (playerType != '-1'))
	{
		pars = pars + '&playertype=' + playerType;
	}

	// Add the token query string.
	if (token.length > 0 && (token != '-1'))
	{
		pars = pars + '&t=' + token;
	}

	// Send the page size if we have it
	if (txtPageSize != null)
	{
		pars = pars + '&pageSize=' + txtPageSize.value;
	}

	if (pickGroupId.length > 0 && pickGroupId != '-1')
	{
		pars = pars + '&pgid=' + pickGroupId;
	}

	pars = pars + '&ref=' + escape(currentUrl);

    var updateElement = $(replacementObjectId);
	var myAjax = new Ajax.Updater(
	replacementObjectId,
	ajaxUrl,
	{
		method: 'get',
		parameters: pars,
		evalScripts: true
	});
	return false;
}

function MonitorPitchCountDown(textEntry, countDownNotification, notificationContainer)
{
	var notificationObj = $(countDownNotification);
	var containerObj = $(notificationContainer);
	var showNotificationCount = 1000;
	var maxCount = 10000;

	// Only show the countdown if the user has entered more than n characters
	if (textEntry.value.length > showNotificationCount)
	{
		// If the user has entered too many characters then truncate the entry.
		if (textEntry.value.length > maxCount)
		{
			textEntry.value = textEntry.value.substring(0, 10000);
		}

		// Show the remaining character count.
		notificationObj.value = maxCount - textEntry.value.length;
	}
}

function AddReplyConfirmation(pitchId)
{
	// Get the DOM elements.
	var textEntry = $('txtPitch' + pitchId);
	var reviewData = $('review' + pitchId);

	if (!VerifyAuthorization())
	{
		return false;
	}

	if (textEntry.value.length == 0)
	{
		$('error' + pitchId).innerHTML = 'Oops! There appears to be a problem with your comment. Check to see if there is something you left out.';
		Element.show('error' + pitchId);
		return;
	}

	var myAjax = new Ajax.Request(
		currentBaseUrl + '/Ajax/ValidatePost.aspx',
		{
			method: 'post',
			parameters: 'text=' + escape($('txtPitch' + pitchId).value),
			onFailure: function(response){$('error' + pitchId).innerHTML = response.statusText; Element.show('error' + pitchId); },
			onSuccess: function(response){reviewData.innerHTML = response.responseText; Element.hide('txtPitch' + pitchId); Element.hide('btnConfirm' + pitchId); Element.hide('btnCancel' + pitchId); Element.hide('error' + pitchId); Element.show('btnEdit' + pitchId); Element.show('btnSubmit' + pitchId); Element.show('review' + pitchId);}
		});
}

function CancelAddReply(pitchId)
{
	// Hide the reply area.
	new Effect.SlideUp('replyView' + pitchId);
	Element.hide('error' + pitchId);
	Element.show('lnkReply' + pitchId);

	// Reset the entered text.
	// Get the textarea.
	var textEntry = $('txtPitch' + pitchId);
	textEntry.disabled = false;
	textEntry.value = '';
}

function EditReply(pitchId)
{
	// Get the DOM elements.
	var textEntry = $('txtPitch' + pitchId);
	var reviewData = $('review' + pitchId);

	if (!VerifyAuthorization())
	{
		return false;
	}
	reviewData.innerHTML = textEntry.value;
	// Hide and show the appropriate elements
	Element.show('txtPitch' + pitchId);
	Element.show('btnConfirm' + pitchId);
	Element.show('btnCancel' + pitchId);
	Element.hide('btnEdit' + pitchId);
	Element.hide('btnSubmit' + pitchId);
	Element.hide('review' + pitchId);
}

/* Get pitch. Display types:
	0 = BuzzBox
	1 = Commentary
	2 = TopBullBear */
function GetPitchThread(pickId, pitchId, displayType)
{
	var url = currentBaseUrl + '/Ajax/GetPitchThread.aspx';
	var pars = 'pid=' + pickId + '&displayType=' + displayType + '&ref=' + escape(currentUrl);
	var myAjax = new Ajax.Updater(
		'pickCommentary' + pickId,
		url,
		{
			method: 'get',
			parameters: pars,
			onFailure: showGetPitchFailure,
			onSuccess: function(){ if (displayType == 2) {hidePitch(pickId);}}
		});
}

function AddWatchlistPick(ticker)
{
	// Make sure the user is registered and logged in.
	if(!VerifyAuthorization())
	{
		return false;
	}
	var url = currentBaseUrl + '/Ajax/AddWatchlistPick.aspx';
	var pars ='ticker=' + ticker;
	var myAjax = new Ajax.Request(
	url,
	{
			method: 'post',
			parameters: pars,
			onFailure: showGenericErrorMessage,
			onSuccess: addWatchlistPickSuccess
	});
}

function addWatchlistPickSuccess()
{
	var successMessage = $('watchListSuccess');
	successMessage.style.display='block';
}

function AddPitch(pickId, pitchId, pitchAuthorToken, tickerSymbol)
{
	var url = currentBaseUrl + '/Ajax/AddPitch.aspx';

	// Make sure the user is registered and logged in.
	if(!VerifyAuthorization())
	{
		return false;
	}
	var post = 'pid=' + pickId + '&ref=' + escape(currentUrl);
	post = post + '&pitchText=' + escape($('txtPitch' + pitchId).value);
	post = post + '&pitchauthortoken=' + escape(pitchAuthorToken);
	post = post + '&ticker=' + escape(tickerSymbol);

	var myAjax = new Ajax.Updater(
		'pickCommentary' + pickId,
		url,
		{
			method: 'post',
			postBody: post,
			onFailure: showGenericErrorMessage
		});
}

function ViewMorePitch(pitchId)
{
	var blockquote = $('quote' + pitchId);
	var hiddenPitch = $('hiddenpitchView' + pitchId);

	if (blockquote != null && hiddenPitch != null)
	{
		blockquote.innerHTML = hiddenPitch.innerHTML;
	}
}

function GetContest(token)
{
	var url = currentBaseUrl + '/Ajax/GetContestDetail.aspx';
	var contestDropDown = GetElementByTagNameAndId('drpPlayerContests', 'SELECT');
	var pars = 'pgid=' + contestDropDown.value + '&t=' + token + '&ref=' + escape(currentUrl);
	if (contestDropDown.value == '-1')
	{
		return;
	}
	var myAjax = new Ajax.Updater(
		'divContestStockPicks',
		url,
		{
			method: 'get',
			parameters: pars,
			onFailure: showGenericErrorMessage
		});
}

function getWatchlistPicks(watchlistPickGroupID, token)
{
	// If there is no watchlist then create it.
	if (watchlistPickGroupID < 0 && !isWatchlistCreated)
	{
		CreateWatchList();
		isWatchlistCreated = true;
		return;
	}
	//Check to see whether the div is already populated for that Player's Commentary Blogs
	//if not, then make the Ajax call, otherwise data is already on the UI, do not make ajax call.
	if(GetElementByTagNameAndId('divWatchlistViewOfCommunityPlayers', 'DIV') != null)
	{
		if (GetElementByTagNameAndId('divWatchlistViewOfCommunityPlayers', 'DIV').innerHTML.length > 1)
		{
			return;
		}

		GetPagedList(currentBaseUrl + '/Ajax/GetStockPicks.aspx', 'divWatchlistViewOfCommunityPlayers', '0', '0', '22', '1', '', token, '6', watchlistPickGroupID);
	}
}

function getTickerPlayerPicks(tickerSymbol)
{
	//Check to see whether the div is already populated for that Ticker's Members Picks
	//if not, then make the Ajax call, otherwise data is already on the UI, do not make ajax call.
	if ($('divdataViewOfPitchesCommunityPlayers').innerHTML.length > 1)
	{
		return;
	}

	GetPagedList(currentBaseUrl + '/Ajax/GetStockPicks.aspx', 'divdataViewOfPitchesCommunityPlayers', '0', '1', '22', '1', tickerSymbol, '', '6', '0');
}

function getBlogCommentaryView(userToken)
{
	//Check to see whether the div is already populated for that Player's Commentary Blogs
	//if not, then make the Ajax call, otherwise data is already on the UI, do not make ajax call.
	if($('divblogViewOfPitchesCommunityPlayers') != null)
	{
		if ($('divblogViewOfPitchesCommunityPlayers').innerHTML.length > 1)
		{
			return;
		}

		GetPagedList(currentBaseUrl + '/Ajax/GetBlogView.aspx?', 'divblogViewOfPitchesCommunityPlayers', '0', '3', '22', '1', '', userToken, '0', '0');
	}
}

function getLimits(params) {
    // Bypassing GetPagedList because it's a mess
    var container = $("limitOrdersView");
    var url = "/ajax/limitorders/getlimitorders.aspx";
    if (!!container) {
	doPagedUpdate(
	    {"success":container},
	    url
	);
    }
}

function doPagedUpdate(updateTarget, url, params, options) {
    	var defaultParams = {
	    "pageSize": 20,
	    "pageIndex": 1,
	    "filter": 1,
	    "sortcol":22,
	    "sortdir":1
	};
	var defaultOptions = {
	    method:'get',
	    evalScripts: true
	};

    params = Object.extend(defaultParams, params || {});
    options = Object.extend(defaultOptions, options || {});
    options.parameters = params;

    var ajax = new Ajax.Updater(
	updateTarget,
	url,
	options
    );
}

//gets a contest name from a dropdownlists selected item and changes the contest name hypelink's href & text on UI.
function UpdateUIContestNameAndHrefValue()
{
	var contestDropDown = GetElementByTagNameAndId('drpPlayerContests', 'SELECT');
	var pickGroupID = contestDropDown.value;
	var selIndex = contestDropDown.selectedIndex;
	var selectedContestName = contestDropDown.options[selIndex].text;
	var ancContestLink = GetElementByTagNameAndId('contestLink', 'A');
	ancContestLink.href = currentBaseUrl + '/contest/' + pickGroupID + '/index.aspx';
	ancContestLink.innerHTML = selectedContestName;
	return;
}

//Pre-selects a dropdown list's item based on its option's Value
//objListName: the select list name
//itemToSelectValue: is the Value of the item to be selected
function presetSelectListItemByValue(itemToSelectValue, objListName)
{
	var dropList = GetElementByTagNameAndId(objListName, 'select');
	// Loop through all the items
	for (iLoop = 0; iLoop< dropList.options.length; iLoop++)
	{
		// NOTE: To MATCH BY Value Field use foll:
		if (dropList.options[iLoop].value == itemToSelectValue)
		{
			// Item is found. Set its selected property, and exit the loop
			dropList.options[iLoop].selected = true;
			break;
		}
	}
}

function collapseBuzzBox() {
	new Effect.SlideUp('divCommunityChatterBox',
			   {
			       beforeStart: function(){
				   Element.hide(GetElementByTagNameAndId('divCloseBuzzBoxLink', 'div'));

			       },
			       afterFinish: function() {
				   Element.show(GetElementByTagNameAndId('divOpenBuzzBoxLink', 'div'));				   
			       }
			   });
}

function expandBuzzBox() {
	new Effect.SlideDown('divCommunityChatterBox',
			     {
				 beforeStart:function() {
				     Element.hide(GetElementByTagNameAndId('divOpenBuzzBoxLink', 'div'));
				 },
				 afterFinish:function() {
				     Element.show(GetElementByTagNameAndId('divCloseBuzzBoxLink', 'div'));
				 }
			     });
}

//This function is used by the Ajax calls for the "Top Tens" page
function getTopTenStatsData(sender, statsMajorType, statsMinorType)
{
	//Ajax calls for Stats page.
	var url = currentBaseUrl + '/Ajax/GetStatsPageData.aspx';
	var whichView = $('currentViewType');
	var pars = 'statsmajor=' + statsMajorType;
	var currentMajorView = $('currentMajorView');
	var currentMinorView = $('currentMinorView');

	// Add secondary stats type if present
	if(statsMinorType)
	{
	 pars = pars + '&statsminor=' + statsMinorType;
	}

	// Add the view mode.
	if (whichView != null)
	{
		pars = pars + "&ViewMode=" + whichView.value;
	}

	var myAjax = new Ajax.Updater(
		'divTopStocksTickerStats',
		url,
		{
			method: 'get',
			parameters: pars,
			evalScripts: true
		});

	currentMajorView.value = statsMajorType;
	currentMinorView.value = statsMinorType;
}

//Get a player's Favorites
function getFavoritesData(replacementDiv, view, token)
{
	var url= currentBaseUrl + '/Ajax/GetFavorites.aspx';
	var updateElement = $(replacementDiv);

	if (updateElement.innerHTML.length >= 10)
	{
		//return;
	}

	var pars = 't=' + token + '&favv=' + view;

	var myAjax = new Ajax.Updater(
		replacementDiv,
		url,
		{
		    method:'post',
		    parameters: pars,
		    evalScripts: true
		});
}

//Get a player's Sector choices
function getSectorData(replacementDiv, token, userName, filter)
{
	var url= currentBaseUrl + '/Ajax/GetSectorGraph.aspx';
	var div= $(replacementDiv);

	if (div.innerHTML.length >= 10)
	{
		//return;
	}

	//Show "Loading ..." graphic
	Fool.Util.showLoading(replacementDiv);

	var pars = "";

	pars = addToQueryString(pars, "t", token);
	pars = addToQueryString(pars, "name", userName);
	pars = addToQueryString(pars, "filter", filter);

	var myAjax = new Ajax.Updater(
		div,
		url,
		{
				method:'post',
				parameters: pars,
				onFailure: showGenericErrorMessage,
				evalScripts: false
		}
	);

	$(replacementDiv).style.height = "auto";
}

function addToQueryString(queryString, newKey, newValue)
{
	var newQueryString = queryString;

	if (newValue.length > 0)
	{

		if (newQueryString.length > 0)
		{
			newQueryString += "&";
		}

		newQueryString += newKey + '=' + newValue;
	}

	return newQueryString;
}

//This function will be used by the Ajax calls for the regular update of
//Felton master page's S&P values. Make a HTTP request every 2 minutes
//After completion change the div's color for a moment.
function getSAndPIndexDataAjax()
{
	var url = currentBaseUrl + '/Ajax/GetSAndPIndexData.aspx';
	new Ajax.PeriodicalUpdater('divSPValue', url, {asynchronous:true, frequency:120, onSuccess: changeDivColorForTimeDelay});
}

//Change the S&P div's color when an Ajax call updates the S&P value
function changeDivColorForTimeDelay()
{
	GetElementByTagNameAndId('divSPValue', 'div').style.backgroundColor = "lightgreen";
	//called to change back the Div's color after 1/2 second
	waitForChangingDivColor(500);
}

//Wait before changing the Div's background color
function waitForChangingDivColor(delay)
{
	string="changeDivColorBack("+delay+");";
	setTimeout(string,delay);
}

function changeDivColorBack(delay)
{
	GetElementByTagNameAndId('divSPValue', 'div').style.backgroundColor = "transparent";
}

//Makes the Ajax call to take the User to a valid displayable page on the grid in context
//this dynamic call is created in the AjaxHelper class
function validateAndJumpToPageNumber(pageNumbercontrol, maxPages, ajaxUrl, replacementObjectId, filterType, sortColumn, sortType, ticker, token, playerType, pickGroupId)
{
	if(isNaN(pageNumbercontrol.value))
	{
		displayErrorMessageAndSetFocus("Please enter a valid integer page number", pageNumbercontrol);
		return;
	}

	if(pageNumbercontrol.value == '')
	{
		displayErrorMessageAndSetFocus("Please enter a page number", pageNumbercontrol);
		return;
	}

	if(parseInt(pageNumbercontrol.value)  > maxPages)
	{
		displayErrorMessageAndSetFocus("Page number exceeds the " + maxPages + " available pages. Please enter a valid page number.", pageNumbercontrol);
		return;
	}

	if(parseInt(pageNumbercontrol.value) < 1)
	{
		displayErrorMessageAndSetFocus("Page numbers start with 1.", pageNumbercontrol);
		return;
	}

	if(parseInt(pageNumbercontrol.value) <= maxPages)
	{
		var validPageNumber = pageNumbercontrol.value - 1;
		var stringPageNum = validPageNumber + '';

		//Make the Actual call to the Ajax control to get the result.
		GetPagedList(ajaxUrl, replacementObjectId, stringPageNum, filterType, sortColumn, sortType, ticker, token, playerType, pickGroupId);
	}
}

//Makes the page postback to the changed Url based on the user input for a particular page number.
//this dynamic call is created in the DataGridHelper class
function validateAndJumpToPageNumberByUrl(pageNumbercontrol, maxPages, postbackUrl)
{
	if(isNaN(pageNumbercontrol.value))
	{
		displayErrorMessageAndSetFocus("Please enter a valid integer page number", pageNumbercontrol);
		return;
	}

	if(pageNumbercontrol.value == '')
	{
		displayErrorMessageAndSetFocus("Please enter a page number", pageNumbercontrol);
		return;
	}

	if(parseInt(pageNumbercontrol.value)  > maxPages)
	{
		displayErrorMessageAndSetFocus("Page number exceeds the " + maxPages + " available pages. Please enter a valid page number.", pageNumbercontrol);
		return;
	}

	if(parseInt(pageNumbercontrol.value) < 1)
	{
		displayErrorMessageAndSetFocus("Page numbers start with 1.", pageNumbercontrol);
		return;
	}

	if(parseInt(pageNumbercontrol.value) <= maxPages)
	{
		var validPageNumber = pageNumbercontrol.value - 1;
		var stringPageNum = validPageNumber + '';

		//Append pagenum to url
		postbackUrl += '&pagenum=' + validPageNumber;

		//Make the Actual call to the postedPage to get the result with the new Url.
		window.location = "" + postbackUrl + "";
	}
}

//Displays an error message and sets focus to that textcontrol and clears its content
function displayErrorMessageAndSetFocus(errorMsg, textControl)
{
	alert(errorMsg);
	textControl.value = '';
	textControl.focus();
}

function VerifyAuthorization()
{
	if (!isRegistered)
	{
		showOverlayRegister("");
		return false;
	}
	else if (!isUserNameCreated)
	{
		showOverlayUserName("");
		return false;
	}
	else if (!isLoggedIn)
	{
		showOverlayLogin("");
		return false;
	}
	return true;
}

function showPlayerTab(tabName, link, favoritesTabName)
{
	var quickStatsTab = $('liQuickStatsTab');
	var profileTab = $('liProfileTab');
	var favoritesTab = $$('li.liFavoritesTab').last();
	if (favoritesTabName)
	{
		favoritesTab = $(favoritesTabName);
	}
	var bestWorstTab = $('liBestWorstTab');
	var sectorsTab = $('liSectorTab');

	// Hide all the divs then we'll show one of them later.
	Element.hide('divQuickStatsMain');
	Element.hide('divProfileMain');
	Element.hide('divFavoritesMain');
	Element.hide('divBestWorstMain');
	Element.hide('divSectorsMain');

	// Set all links style's to disabled, then we'll enable one later
	quickStatsTab.getElementsByTagName("a")[0].className = "";
	profileTab.getElementsByTagName("a")[0].className = "";

	if (favoritesTab != null)
	{
		favoritesTab.getElementsByTagName("a")[0].className = "";
	}
	bestWorstTab.getElementsByTagName("a")[0].className = "";
	sectorsTab.getElementsByTagName("a")[0].className = "";

	switch(tabName)
	{
		case "qs":
			quickStatsTab.getElementsByTagName("a")[0].className = "current";
			Element.show('divQuickStatsMain');
			break;
		case "pr":
			profileTab.getElementsByTagName("a")[0].className = "current";
			Element.show('divProfileMain');
			break;
		case "fv":
			favoritesTab.getElementsByTagName("a")[0].className = "current";
			Element.show('divFavoritesMain');
			break;
		case "bw":
			bestWorstTab.getElementsByTagName("a")[0].className = "current";
			Element.show('divBestWorstMain');
			break;
		case "sc":
			sectorsTab.getElementsByTagName("a")[0].className = "current";
			Element.show('divSectorsMain');
			break;
	}

	// IE apparently needs a prod to do "something" to redraw the page
	// otherwise the components of the buzzbox get out of position.
	if($("divCommunityChatterBox")) {
		$("divCommunityChatterBox").style.zoom = "100%";
	}
}

// Mainpage buzzbox/video toggling.
function showMainpagePromoTab(tabName, link)
{
	var videoTab = $('liVideoTab');
	var buzzboxTab = $('liBuzzboxTab');

	// Hide all the divs then show one later.
	Element.hide('videoPitch');
	Element.hide('divCommunityChatterBox');

	// Set link styles to disabled, then call one later.
	videoTab.getElementsByTagName("a")[0].className = "";
	buzzboxTab.getElementsByTagName("a")[0].className = "";

	switch(tabName)
	{
		case "vp":
			videoTab.getElementsByTagName("a")[0].className = "current";
			Element.show('videoPitch');
			break;
		case "bb":
			buzzboxTab.getElementsByTagName("a")[0].className = "current";
			Element.show('divCommunityChatterBox');
			break;
	}
}

// Contest Stats.
function showContestStatsTab(tabName, link)
{
	var keyStatsTab = $('liKeyStatsTab');
	var bestWorstTab = $('liBestWorstTab');

	// Hide all the divs then show one later.
	Element.hide('divKeyStats');
	Element.hide('divBestWorst');

	// Set link styles to disabled, then call one later.
	keyStatsTab.getElementsByTagName("a")[0].className = "";
	bestWorstTab.getElementsByTagName("a")[0].className = "";

	switch(tabName)
	{
		case "ks":
			keyStatsTab.getElementsByTagName("a")[0].className = "current";
			Element.show('divKeyStats');
			break;
		case "bw":
			bestWorstTab.getElementsByTagName("a")[0].className = "current";
			Element.show('divBestWorst');
			break;
	}
}

// Mainpage Featured Members toggling.
function showFeaturedPlayersTab(tabName, link)
{
	var mainStreetTab = $('liMainStreetTab');
	var wallStreetTab = $('liWallStreetTab');

	// Hide all the divs then show one later.
	Element.hide('divPlayerSpotlightMainStreet');
	Element.hide('divPlayerSpotlightWallStreet');

	// Set link styles to disabled, then call one later.
	mainStreetTab.getElementsByTagName("a")[0].className = "";
	wallStreetTab.getElementsByTagName("a")[0].className = "";

	switch(tabName)
	{
		case "mst":
			mainStreetTab.getElementsByTagName("a")[0].className = "current";
			Element.show('divPlayerSpotlightMainStreet');
			break;
		case "wst":
			wallStreetTab.getElementsByTagName("a")[0].className = "current";
			Element.show('divPlayerSpotlightWallStreet');
			break;
	}
}

// Mainpage Featured Stocks toggling.
function showFeaturedStocksTab(tabName, link)
{
	var bullTab = $('liBullTab');
	var bearTab = $('liBearTab');

	// Hide all the divs then show one later.
	Element.hide('divStockSpotlightBull');
	Element.hide('divStockSpotlightBear');

	// Set link styles to disabled, then call one later.
	bullTab.getElementsByTagName("a")[0].className = "";
	bearTab.getElementsByTagName("a")[0].className = "";

	switch(tabName)
	{
		case "slbl":
			bullTab.getElementsByTagName("a")[0].className = "current";
			Element.show('divStockSpotlightBull');
			break;
		case "slbr":
			bearTab.getElementsByTagName("a")[0].className = "current";
			Element.show('divStockSpotlightBear');
			break;
	}
}

function PickStock(ticker, action, replacementObjectId)
{
	var ajaxUrl = currentBaseUrl + "/Ajax/PickStock.aspx";
	var pars = "a=" + action + "&ticker=" + ticker;
	var pitchTextbox;
	var callDropDown;
	var durationDropDown;
	var pitchData;

	// Make sure the user is registered and logged in.
	if (!VerifyAuthorization())
	{
		return false;
	}

	// If the action is a confirmation then get the appropriate data.
	switch (action)
	{
		case "pick":
		case "cancel":
			pitchTextbox = GetElementByTagNameAndId('hdnPitch', 'INPUT');
			callDropDown = GetElementByTagNameAndId('hdnCall', 'INPUT');
			durationDropDown = GetElementByTagNameAndId('hdnDuration', 'INPUT');
			break;
		case "confirm":
			pitchTextbox = GetElementByTagNameAndId('txtRatingDescription', 'TEXTAREA');
			callDropDown = GetElementByTagNameAndId('drpRating', 'SELECT');
			durationDropDown = GetElementByTagNameAndId('drpWeeks', 'SELECT');
			break;
	}

	if (pitchTextbox != null)
	{
		// Condition the data before passing to ajax.
		pitchData = pitchTextbox.value.replace(new RegExp( "\\n", "g" ), "<br />");
		pitchData = encodeURIComponent(pitchData);

		pars += "&pitchtext=" + pitchData;
	}

	if (callDropDown != null)
	{
		pars += "&call=" + callDropDown.value;
	}

	if (durationDropDown != null)
	{
		pars += "&duration=" + durationDropDown.value;
	}

	var myAjax = new Ajax.Updater(
	{ 'success': GetElementByTagNameAndId(replacementObjectId, 'DIV') },
	ajaxUrl,
	{
	    method: 'post',
	    parameters: pars,
	    onFailure: showGenericErrorMessage
	});
}

function CancelPick(pickId, action, ticker, replacementObjectId)
{
	var ajaxUrl = currentBaseUrl + "/Ajax/CancelPick.aspx";
	var pars = "a=" + action + "&pid=" + pickId + "&ticker=" + ticker;

	// Make sure the user is registered and logged in.
	if (!VerifyAuthorization())
	{
		return false;
	}

	var myAjax = new Ajax.Updater(
	GetElementByTagNameAndId(replacementObjectId, 'DIV'),
	ajaxUrl,
	{
		method: 'get',
		parameters: pars,
		onFailure: showGenericErrorMessage
	});
}
function CreateWatchList()
{
	var myAjax = new Ajax.Updater(
	'divCreateWatchList',
	currentBaseUrl + '/Ajax/CreateWatchList.aspx',
	{
		method: 'get',
		evalScripts: true,
		onFailure: showGenericErrorMessage
	});
}

// Function to resize inline frame. Originally for IDC tabs on ticker.aspx.
// Must be called by page that is loaded into the inline frame when it detects onload event.
function resizeIFrame(iFrameId) {
	var oIFrame = $(iFrameId);
	var oIFrameDoc = oIFrame.contentWindow ? oIFrame.contentWindow.document : oIFrame.contentDocument;
	var iHeight;

	if(oIFrameDoc){
		// First set iframe height smaller than any conceivable content or content size will be reported as frame size.
		oIFrame.style.height = "25px";

		// Get dimensions of content
		if(document.documentElement && document.compatMode && document.compatMode=="CSS1Compat") {
			iHeight = oIFrameDoc.documentElement.scrollHeight;
		}
		else if(document.body) {
			iHeight = oIFrameDoc.body.scrollHeight;
		}

		// Set dimensions of inline frame
		if(iHeight) {
			oIFrame.style.height = (iHeight + 1) + "px";
		}
	}
}

//-----------------------------------------------------------------------------
// Called on page load
function initializePromos(){
	// alert("initializePromos()");

	// Start automatic sequencing
	var sIntervalId = window.setInterval(function(){viewNextPromo("mainTopPromo");}, 7000);

	// Assign onclick handlers to the tabs. Don't assume there are four tabs.
	var aTabLinks = $$("div#tabsTopPromo li a");
	var sListItemId;
	for(var i=0; i<aTabLinks.length; i++) {
		sListItemId = aTabLinks[i].parentNode.id;
		//console.info("sListItemId: " + sListItemId + ", IntervalId: " + sIntervalId);
		Event.observe(aTabLinks[i], "click", viewPromo.bind(window, sListItemId, sIntervalId));  // Could not get .bindAsEventListener to work - the event was passed but not the other arguments.
	}

}

// Function called when user clicks on promo tab; jumps immediately to selected promo.
function viewPromo(sListItemId, sIntervalId) {

	// alert("viewPromo(sListItemId: " + sListItemId + "\nsIntervalId: " + sIntervalId + ")");

	// Kill auto-sequencing
	window.clearInterval(sIntervalId);

	// Reset links
	var aTabLinks = $$("div#tabsTopPromo li a");
	for(var i=0; i<aTabLinks.length; i++) {
		aTabLinks[i].className = "";
	}
	$(sListItemId).getElementsByTagName("a")[0].className = "current";

	//Reset promotion
	var sNewPromoId = sListItemId.replace(/^li/, "div");
	var aChildren = $(sNewPromoId).parentNode.childNodes;
	for(var j=0; j < aChildren.length; j++) {
		if(aChildren[j].nodeType == 1 && aChildren[j].tagName.toLowerCase() == "div") {
			aChildren[j].style.display = "none";
		}
	}
	//alert("sNewPromoId: " + sNewPromoId);
	$(sNewPromoId).style.display = "block";
	setOpacity($(sNewPromoId), 1.0);
}

// Function to smoothly transition to next promo and associated tab
function viewNextPromo(sContainerID) {
	var iTime = 7000; //milliseconds
	var iCurrent = 0;
    var container = $(sContainerID) || false;
        if (container) {
	// Get DIV children of mainTopPromo
	    var aChildren = $(sContainerID).childNodes;
	    var aPromos = [];
	    for(var i=0; i < aChildren.length; i++) {
		if(aChildren[i].nodeType == 1 && aChildren[i].tagName.toLowerCase() == "div") {
		    aPromos.push(aChildren[i]);
		}
	    }
	    
	    // Determine which one is currently visible
	    for(var j=0; j<aPromos.length; j++) {
		//alert("i: , display: "+ getStyle(aPromos[i], "display"));
		if(getStyle(aPromos[j], "display") == "block") {
		    iCurrent = j;
		    break;
		}
	    }
	    var iNext = (iCurrent + 1) % aPromos.length;
	    
	    // Get ID of current and next promo. Will use to change tabs
	    var sCurrentPromoId = aPromos[iCurrent].id;
	    var sNextPromoId    = aPromos[iNext].id;
	    
	    // Change the promo. Have to wait momentarily for first one to fade before calling second to appear.
	    Effect.Fade(sCurrentPromoId);
	    window.setTimeout("Effect.Appear('" + sNextPromoId + "')", 1000);

	    // Change the tab - assumes IDs of divs and list items match e.g. divTP2 and liTP2.
	    var oCurrentLink = $(sCurrentPromoId.replace(/^div/, "li")).getElementsByTagName("a")[0];
	    var oNextLink = $(sNextPromoId.replace(/div/, "li")).getElementsByTagName("a")[0];
	    oCurrentLink.className = "";
	    window.setTimeout(function(){oNextLink.className = "current";}, 1000);
	}
}

// The getStyle function in prototype.js is failing in IE
function getStyle(element, prop) {
  if (typeof element == 'string') {
		element = document.getElementById(element);
	}

	if (element.style[prop]) {
		// inline style property
		return element.style[prop];
	}
	else if (element.currentStyle) {
		// external stylesheet for Explorer
		return element.currentStyle[prop];
	}
	else if (document.defaultView && document.defaultView.getComputedStyle) {
		// external stylesheet for Mozilla and Safari 1.3+
		prop = prop.replace(/([A-Z])/g, "-$1");
		prop = prop.toLowerCase();
		return document.defaultView.getComputedStyle(element, null).getPropertyValue(prop);
	}
	else {
		return null;
	}
}

function setOpacity(div, val) {
  if (div.filters) {  //For IE
    val *= 100;
    try {
      div.filters.item("DXImageTransform.Microsoft.Alpha").opacity = val;
    } catch (e) {
      // If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
      div.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+val+')';
    }
  } else {
    div.style.opacity = val;
    div.style.MozOpacity = val;  //This is for older Mozilla Browsers
  }
}
//-----------------------------------------------------------------------------
// GrabIt widget is breaking blogs page
function SWFFormFix() {
	var objects = document.getElementsByTagName("object");
	if (objects.length == 0) {
		return true;
	}
		for(i=0;i<objects.length;i++){
			// here's all the objects on the page, now lets find the flash objects
				if(objects[i].data.indexOf("clearspring") != -1) {
					// this is a clearspring flash movie, apply the fix
					window[objects[i].id] = objects[i];
				}
	}
	var out = '';
	return true;
}

//-----------------------------------------------------------------------------
// CAPS alias old command to new counterpart
Fool.createWidget = Fool.Widgets.create;

//TODO: which one is right this one or Caps.Widgets.rangeSliders in foolsliders.js
Fool.Widgets.rangeSliders = function(options) {
	// Requires Scriptaculous; fail silently if unavailable
	if (typeof Scriptaculous == 'undefined') {
		return;
	}

	var handle1 = $(options.handle1) || $('handle1');
	var handle2 = $(options.handle2) || $('handle2');
	var meter1 = $(options.meter1) || $('meter1');
	var meter2 = $(options.meter2) || $('meter2');
	var track = $(options.track) || $('track');
	var min = options.min || 0;
	var max = options.max || 100;
	var offset = options.offset || 0;
	var callback = options.callback || function() { return; };

	meter1.innerHTML = min.toFixed(0);
	meter2.innerHTML = max.toFixed(0);

	var minHandle = new Control.Slider(handle1, track, {
		range: $R(min, max),
		onSlide: function(e) {
			if (parseInt(handle1.style.left) < parseInt(handle2.style.left) - offset) {
				meter1.innerHTML = e.toFixed(0);
			} else {
				handle1.style.left = parseInt(handle2.style.left) - offset + 'px';
			}
			},
		onChange: callback
		});
	var maxHandle = new Control.Slider(handle2, track, {
		range: $R(min, max),
		sliderValue: max,
		onSlide: function(e) {
			if (parseInt(handle1.style.left) < parseInt(handle2.style.left) - offset) {
				meter2.innerHTML = e.toFixed(0);
				}
			else {
				handle2.style.left = parseInt(handle1.style.left) - 0 + offset + 'px';
				}
			},
		onChange: callback
		});
	Event.stopObserving(minHandle.track, "mousedown", minHandle.eventMouseDown);
	Event.stopObserving(maxHandle.track, "mousedown", maxHandle.eventMouseDown);
};


/*******************************************************************************
=CAPS
*******************************************************************************/
var Caps = window.Caps || {};

/*******************************************************************************
=QUOTE
*******************************************************************************/
Caps.Quote = {
    getQuoteUri : "/common/ajax/caps/json/Quote.ashx",
    getQuote : function(symbol, onSuccess, onFailure) {
        if(Caps.Quote.cache[symbol]) {
            if(onSuccess) {
                onSuccess(Caps.Quote.cache[symbol]);
                return;
            }
        }

        var request = new Ajax.Request(
            this.getQuoteUri,
			{
			    method: 'get',
			    showFeedback: false,
			    parameters: 's=' + symbol,
			    onSuccess: function(transport) {
				if(onSuccess) {
				    var quote = eval("(" + transport.responseText + ")");
				    Caps.Quote.cache[symbol] = quote;
				    onSuccess(quote);
				}
                },
                onFailure: function(transport) {
                    if (onFailure) { onFailure(transport);}
                }
            }
        );
    },
    cache: {}
};


/*******************************************************************************
=SEARCH
*******************************************************************************/

Caps.Search = {
	prepare: function() {
	    var searchForm = $("capsSearchForm");
	    if (searchForm) {
		var searchInput = searchForm.select("input[name='q']")[0];
		var queryParams = location.search.toQueryParams();
		var query = (!!queryParams.q) ? queryParams.q : "";

		// If q is the same as the value of teh form don't activate Usmf.Search
		if(searchInput.getValue() !== query) {
		    Usmf.Search.prepare(searchForm);
		}
	    }
	}
};

/*******************************************************************************
=TICKER
*******************************************************************************/
Caps.Ticker = {
	Format:{
		comstock: function(Ticker) {
			// Format ticker to Comstock friendly format should probably be moved to JSON handler
			// Uppercase it
			var ticker = Ticker.toUpperCase();

			// Rule #1:  Remove .PK or .OB
			var tickerEnd = ticker.substring(ticker.length -3, ticker.length);
			if (tickerEnd == ".PK" || tickerEnd == ".OB") {
				ticker = ticker.slice(0, ticker.length-3);
			}
			// Rule #2: Convert "-" to "."
			if (ticker.match(/-/)) {
				ticker = ticker.replace(/-/, ".");
			}
			// Rule #3: Map reserved words
			if (ticker.match(/\^/)) {
				switch (ticker) {
					case "^DJI":
						ticker = "DJI";
						break;
					case "^IXIC":
						ticker = "COMP";
						break;
					case "^GSPC":
						ticker = "INX";
						break;
					case "^RUT":
						ticker = "IUX";
						break;
				}
			}
				return ticker;
		}
	},
	dto: function(quote){
        this.CompanyName = quote.Name;
		this.Ticker = quote.Ticker;
        this.CurrentPrice = "$" + quote.LastTrade.toFixed(2);

        // Stars URL bits.
		//var starsBaseUrl = "http://g.fool.com/art/ratings/";
        var starsUrl = [
			"http://g.fool.com/art/ratings/foolcaps_none.gif",
			"http://g.fool.com/art/ratings/foolcaps_one.gif",
			"http://g.fool.com/art/ratings/foolcaps_two.gif",
			"http://g.fool.com/art/ratings/foolcaps_three.gif",
			"http://g.fool.com/art/ratings/foolcaps_four.gif",
			"http://g.fool.com/art/ratings/foolcaps_five.gif"
		];
		// Deal with some potential bad data. !! casts to boolean
		var stars = (!!quote.NumberOfStars) ? quote.NumberOfStars : 0;
		stars = (stars > 5) ? 5 : stars;

		//set the image url
        this.StarsImgUrl = starsUrl[stars];
		var changePrefix = "";

        // Format the DailyChange
        if(quote.PricePercentChange > 0)
        {
            this.ChangeClass = "up";
			changePrefix = "+";
        }
        else if(quote.PricePercentChange < 0)
        {
            this.ChangeClass = "down";
        }
        else
        {
            this.ChangeClass = "";
        }

        this.DailyPercentChange = changePrefix + quote.PricePercentChange.toFixed(2) + "%";
		this.DailyPriceChange = changePrefix + quote.PriceChange.toFixed(2);

        // Format the Timestamp.
        var MM = quote.LastTradeTime.getMonth() + 1;
        var dd = quote.LastTradeTime.getDate();
        var yyyy = quote.LastTradeTime.getFullYear();
        var hh = (quote.LastTradeTime.getHours() > 12) ? (quote.LastTradeTime.getHours() - 12) : quote.LastTradeTime.getHours();
        var mm = (quote.LastTradeTime.getMinutes() < 10) ? ("0" + quote.LastTradeTime.getMinutes()) : quote.LastTradeTime.getMinutes();
        var tt = (quote.LastTradeTime.getHours() > 12) ? "PM" : "AM";
        this.Timestamp = MM + "/" + dd + "/" + yyyy + " " + hh + ":" + mm + " " + tt;

		this.ChartUrl = "http://www.motleyfool.idmanagedsolutions.com/charts/minichart.chart?SYMBOL_US=" + Caps.Ticker.Format.comstock(this.Ticker) + "&amp;ID_BENCH1=SPY";

        return this;
    }
};

/*******************************************************************************
=HOVERS
*******************************************************************************/
Caps.Hover = {
	cache: {},
	Templates: {
		ticker: new Template("<h4>#{CompanyName} <span>(#{Ticker})</span></h4><div class='capsRating'>CAPS Rating: <img class='imgRatings' alt='CAPS Rating' src='#{StarsImgUrl}'/></div><div class='tickerPerformance'> #{CurrentPrice} <span class='performance #{ChangeClass}'>#{DailyPriceChange} (#{DailyPercentChange})</span></div><div class='divChart'><a href='/Ticker/#{Ticker}.aspx'><div style='background-image:url(#{ChartUrl})' class='ssChart'></div></a></div><div class='timestamp'>#{Timestamp}</div>")
	},
	attach: function(container) { // Global hover attaching.  All hover atatch methods go in here
		this.Ticker.attach(container);
		this.Tooltip.attach(container);
	}
};

/*******************************************************************************
=HOVER.TICKER
*******************************************************************************/
Caps.Hover.Ticker = {
	attach: function(container){
		var self = this; // Maintain object scope
		//TODO 1.6: replace with $().select
		if ($(container) && $(container).id) {
			$$('#' + $(container).id + ' span.ticker a').each(function(obj){
				self.handler(obj);
			});
		}

	},
	/* This function is probably more complicated then it needs to be but I couldn't
 	* find any other way to lazy load the hovers with our current hover system.
 	* Also if someone has a better name for it -PW
 	*/
	handler: function(el){
		var symbol = (el.firstChild) ? el.firstChild.nodeValue : null;
		var delay = null; // Global delay variable which which holds the initial timeout
		var delayTime = 500;


		/* this runs after a succesful quote request */
		var successCallback = function(quote){
			var hoverDto = new Caps.Ticker.dto(quote);
			var markup = Caps.Hover.Templates.ticker.evaluate(hoverDto);
			/* create the widget */
			var hover = Fool.Widgets.create(
			"Hover",
			{
				trigger: el,
				content: markup,
				theme: "v1",
				isVisible: false,
				isExclusive: true,
				showDelay: delayTime
			});

			/* detach the initial processes which fetched the quotes
			 * and give control over to the widget.
			 */
			Event.stopObserving(el, "mouseover", initialLoad);
			Event.stopObserving(el, "mouseout", clearInitialLoad);
			// show the hover
			hover.show();

			// add this hover instance to the cache
			if (el.id) {
				Caps.Hover.cache[el.id] = true;
			}
		};
		/* initial callbacks that get attached to the mouseover/mouseout events*/
		var initialLoad = function(){
			// Call the quote service with a slight delay
			// so that casual mouseovers don't trigger it
			delay = setTimeout(function(){
				Caps.Quote.getQuote(symbol, successCallback);
			}, delayTime);
		};
		var clearInitialLoad = function(){
			// Kill the timout so that calls don't keep going
			clearTimeout(delay);
			setTimeout(function(){
				// Check for any hovers and hide them so they don't get stuck
				if (Fool.Widgets.instances("Hover")) {
					Fool.Widgets.hideAll("Hover");
				}
			}, delayTime);
		};
		/* These initial callbacks allow us to lazy load the hovers
		 * once the hovers are created they are destroyed and the events are handed to the widget
	 	*/
		if (!!symbol) {
			Event.observe(el, "mouseout", clearInitialLoad);
			Event.observe(el, "mouseover", initialLoad);
		}
	}
};

/*******************************************************************************
=HOVER.TOOLTIP
*******************************************************************************/
Caps.Hover.Tooltip = {
	attach: function(container){
		var self = this; // Maintain object scope
		//TODO 1.6: replace with $().select, until then check for id's before hand
		if ($(container) && $(container).id) {
			$$('#' + $(container).id + ' .infoTip').each(function(obj){
				self.handler(obj);
			});
		}
	},
	handler: function(obj) {
		//Does it have a title
		if (obj.getAttribute("title")) {
			//create the widget
			var tooltip = Fool.Widgets.create("Hover", {
				trigger: obj,
				content: obj.title,
				theme: "infotip",
				isExclusive: true,
				showDelay:300
			});
			// Remove the title
			obj.removeAttribute("title");
			// .net inserts some bogus alts
			if (obj.getAttribute("alt")) { obj.removeAttribute("alt"); }

			//remove alt and title attributes from nested images to remove
			// system native tooltips
			var childImgs = $A(obj.getElementsByTagName("img"));
			childImgs.each(function(el){
				if (el.getAttribute('title')) { el.removeAttribute('title'); }
				if (el.getAttribute('alt')) { el.removeAttribute('alt'); }
			});
		}
	}
};
// create the new theme
Fool.Widgets.Hover.themes.infotip = {
  className : "infotip",
  template : "<div class='layout'>" + "<div class='content'></div></div>",
  layout : function (hover, orientation, box) {
		var left = (/e$/.test(orientation)) ? box.left + box.width : box.left - hover.width();
		var top = (/^s/.test(orientation)) ? box.top + box.height : box.top - box.height;
    hover.left(left);
    hover.top(top);
  }
};
/*******************************************************************************
=AJAX
*******************************************************************************/
Caps.Ajax = {
	Global: {
		showFeedback: false,
		onCreate: function(obj){
			var doFeedback = this.showFeedback;
			if(!Object.isUndefined(obj.options.showFeedback)) {
				doFeedback = obj.options.showFeedback;
			}
			if (doFeedback) {
			    Element.show('systemWorking');
			    document.body.setStyle({cursor:"wait"});
			}
		},
		onComplete: function(obj, transport, json){
			if (Ajax.activeRequestCount === 0) {
			    Element.hide('systemWorking');
			    document.body.setStyle({cursor:""});
			    // Attach hovers to any Ajax.updater calls
			    if (obj.container && obj.container.success) {
				Caps.Hover.attach(obj.container.success);
			    }
			}
		},
		onFailure: function(){
		    alert('Sorry. There was an error processing your request.');
		    Element.hide('systemWorking');
		    document.body.style.cursor = 'default';
		}
	}
};

/*******************************************************************************
=FOLLOWBLOGPOST
*******************************************************************************/
Caps.Ajax.Follow = {
	prepare: function() {
		$$("a.setFollow").each(function(link){
			Event.observe(link, 'click', function(evt){
				Caps.Ajax.Follow.toggle(link);
				Event.stop(evt);
			});
		});
	},
	toggle: function(link) {
		var request = new Ajax.Request(
	            "/ajax/UpdateFavoriteBlogPost.aspx",
		    {
	                method: 'post',
	                parameters: link.search,
	                onSuccess: function(transport) {
	                    Caps.Ajax.Follow.updateLink(link, transport.responseText);
	                },
			on403: function() {
			    VerifyAuthorization();
			}
	            }
	       	);
	},
	updateLink: function(link, csv) {
		if (!csv || !link) { return;}
		var classAddOn = "Follow";

		var values = csv.split(",");
		var text = values[0].strip();
		var action = values[1].strip();
		var params = $H(link.search.toQueryParams());

		link.removeClassName(params.get('actiontype').toLowerCase() + classAddOn);
		link.addClassName(action.toLowerCase() + classAddOn);
		params.set("actiontype", action);
		link.search = '?' + params.toQueryString();
		link.update(text);
	}
};
/*******************************************************************************
=LOGIN
*******************************************************************************/

Caps.Ajax.Login = {
	prepare: function() {
		$$('a.requireLogin').each(function(link){
			Event.observe(link, 'click', function(evt){
			    VerifyAuthorization();
			    Event.stop(evt);
			});
		});
	}
};

/*******************************************************************************
=Picks
*******************************************************************************/
Caps.Ajax.Picks = {
    changeStatus: function(obj, params) {
	var btn = obj;
	btn.disabled = true;
	var url = "/ajax/picks/getmyscorecard.aspx";
	var container = "divdataViewOfPitchesCommunityPlayers";
	params.objid = container;
	Caps.Ajax.Picks.btnDisable($(container).select("input"));
	doPagedUpdate(
	    { "success": container },
	    url,
	    params,
	    {
		method:'post'
	    }
	);
    },
    btnDisable: function(collection) {
	collection.each(function(btn){
	    btn.disabled = true;
	    btn.addClassName("disabled");
	});
    }
};

/*******************************************************************************
=ONDOMREADY
*******************************************************************************/
Event.onDOMReady(function() {
		// register the Ajax handlers
		Ajax.Responders.register(Caps.Ajax.Global);
		//Attach hover events
		Caps.Hover.attach("capsWrapper");
		//Prepare Search
		//Caps.Search.prepare(); //- This is now called in /controls/search/CapsSearchbar.ascx
		//Bind PostFollow tags
		Caps.Ajax.Follow.prepare();
		// Bind login required links
		Caps.Ajax.Login.prepare();

		/* Page specific stuff */
		if (currentUrl && currentUrl.toLowerCase().lastIndexOf('index.aspx') > -1) {
			Caps.Ajax.Global.showFeedback = false;
		}
		if(navigator.appName.toLowerCase() == "microsoft internet explorer" &&
			(
				window.location.href.indexOf("ViewPost.aspx") > -1 ||
				window.location.href.indexOf("ViewBlog.aspx") > -1
			)) {
			SWFFormFix();
		}

});

var sweetTitles = false; // turn off any left over checking for sweetTitles
