var popUpDivs;
agt = navigator.appVersion;

var MouseBuffer;

function pullDivToTop(divToPull)
{
    if (typeof(divToPull) == 'string')
        divToPull = $(divToPull);

    if (divToPull && divToPull.id && divToPull.style && divToPull.style.zIndex)
    {
        var popUpZIndexBase = 10000;

        // initialize array of popup divs
        if (!popUpDivs)
            popUpDivs = new Array();

        for (var i = 0; i < popUpDivs.length; i++)
        {
            // remove the div-to-pull from the popUpDivs array
            if (divToPull.id == popUpDivs[i])
                popUpDivs.splice(i, 1);

            // maintain that all divs in popUpDivs are still valid
            var divToCheck = $(popUpDivs[i]);
            if (!divToCheck)
                popUpDivs.splice(i, 1);
        }

        // insert the div-to-pull at the end of the popUpDivs array
        popUpDivs.push(divToPull.id);

        // update all popup divs' zIndex
        for (var i = 0; i < popUpDivs.length; i++)
        {
            var somePopUpDiv = $(popUpDivs[i]);
            if (somePopUpDiv)
                somePopUpDiv.style.zIndex = popUpZIndexBase + i;
        }
    }
}

function SetYouHaveAsked(message)
{
		var div = $('FriendInfo');
		if(div)
		{
			div.innerHTML = message;
		}
}

function SetYouHaveAskedSearch(buttonIndex, message)
{
	var divId = 'AddToFriendsButton_' + buttonIndex;
	var div = parent.$(divId);
	
	if(div)
	{
		div.innerHTML = "";
		div.innerHTML = message;
	}
}
function SetIsFriendText(message)
{
		var div = $('FriendInfo');
		if(div)
		{
			div.innerHTML = message;
		}
}

function SetAddToFriendsText(message)
{
		var div = $('FriendInfo');
		HideOrigFriendBar();
		if(div)
		{
			div.innerHTML = message;
		}
}

function SetAddRejectText(message)
{
		var div = $('FriendInfo');
		HideOrigFriendBar();
		if(div)
		{
			div.innerHTML = message;
		}
}

function HideOrigFriendBar()
{
		HideElement('buttonFriendAdd');
		HideElement('ProfileHeader_pnlAcceptReject');
		HideElement('ProfileHeader_pnlAddFriends');
		HideElement('ProfileHeader_pnlIsFriend');
		HideElement('ProfileHeader_pnlYouHaveAsked');
		HideElement('ProfileHeader_pnlNewRequests');
}
function HideElement(id)
{
		var hideMe = Get(id);
		if(hideMe)
			hideMe.style.display="none";	
}
function SetRemoteHeader(querystring){

		if(document.location.href.toLowerCase().indexOf("customprofile") > -1 && !PageIsLoaded)
			return;
		
		if(querystring.indexOf("podId=6") > -1)
		{
		    callToServer("/Profile/remote_bmf_handler.ashx?" + querystring);
		}
		else
		{
		    callToServer("/Profile/Remote.aspx?" + querystring);
		}
		return true;
}

function SearchFriends()
{
		var textbox = document.getElementById("txtSearch");
		if(textbox)
		{
		 
			parent.location.href = "/flirt/QuickSearch.aspx?SearchId="+textbox.value;
		}
}

function EnterSubmitSearch()
{
		if(event.keyCode == 13)
			{
				event.keyCode = null;
				document.getElementById('btnSearch').click();
			}     	
}

function ResetHeaderFriends()
{
		var encUno = Get('EncUno');
		callToServer("remoteNew.aspx?key=ProfileHeader&encUno=" + encUno.value + "&parameters=ResetFriendsCount");
}

function SignMeOut()
{	
		document.location.href='/signout.asp';
}

function showVerifyPhoneDivRSSPricingPublic()
{
		var div = Get('divVerifyPhoneConfirm');
		var divRSS = Get('RSSPricingForPublicAdd');
		if(div)
		{
			if(event)
			{
				var podNutritionDivId = event.srcElement.id;
				podNutritionDivId = podNutritionDivId.replace('lnkEditPhoneNumber','');
				var myregexp = new RegExp("RSS_PricingPublic[0-9]+_");
				if(myregexp.exec(podNutritionDivId))
				{
					setPodNutritionDiv(podNutritionDivId);
					div.style.display = 'inline';
					
					if(divRSS)
					{
						div.style.top =  (parseInt(divRSS.offsetTop)+100)+'px';
						div.style.left = (parseInt(divRSS.offsetLeft)+50)+'px';
					}
				
				setPodNutritionDivLoc('RSSPricingForPublicAdd');
				return false;
				}else
				{
					setPodNutritionDiv("");
				}
			}
		}
		return false;
}

function showVerifyPhoneDivPSB()
{	
	var div = Get('divVerifyPhoneConfirm');
	var divPSB = Get('divOptinInfoSB');
	
	if(div)
	{
		div.style.display = 'inline';
		div.style.top = (parseInt(divPSB.style.top)+100)+'px';
		div.style.left = (parseInt(divPSB.style.left)-15)+'px';
		setPodNutritionDivLoc('PodSidebar');
	}
	return false;
}

function showVerifyPhoneDivMusicVideoSA()
{	
	var div = Get('divVerifyPhoneConfirm');
	if(div)
	{
		var nDivMusicVideoSA = Get('ctl00_PopularSongs_SrchB_ctlSongNutrition_nutritionDiv');
		
		if(nDivMusicVideoSA) {
			div.style.display = 'inline';
			div.style.top =  (parseInt(nDivMusicVideoSA.style.top)+140)+'px';
			div.style.left = (parseInt(nDivMusicVideoSA.style.left)+100)+'px';
			setPodNutritionDivLoc('VideoSA');
			return;
		}
		var nDivVideoPlayer = Get('ctlSongNutrition_nutritionDiv');
		
		if(nDivVideoPlayer) {
			div.style.display = 'inline';
			div.style.top =  (parseInt(nDivVideoPlayer.offsetTop)+50)+'px';
			div.style.left = (parseInt(nDivVideoPlayer.offsetLeft)+50)+'px';
			setPodNutritionDivLoc('VideoSA');
			return false;
		}
		
		setPodNutritionDivLoc('VideoSA');
		SetDivPosition('divVerifyPhoneConfirm');
	}
	return false;
}

function showVerifyPhoneDivMusicVideoPod()
{
	var div = Get('divVerifyPhoneConfirm');
	if(div)
	{
		var newevent = event;
		if(newevent != null){
			var podNutritionDivId = newevent.srcElement.id;
			podNutritionDivId = podNutritionDivId.replace('lnkEditPhoneNumber','');
			var myregexp = new RegExp("pod[0-9]+_[0-9]+_[0-9]+_");
			
			if(myregexp.exec(podNutritionDivId)){
				setPodNutritionDiv(podNutritionDivId);
				var nutritionDivName = podNutritionDivId+"nutritionDiv";
				var nutritionDivAnchor = Get(nutritionDivName);
				
				div.style.display = 'inline';
				
				if(nutritionDivAnchor) {
					div.style.top =  (parseInt(nutritionDivAnchor.offsetTop)+75)+'px';
					div.style.left = (parseInt(nutritionDivAnchor.offsetLeft)+50)+'px';
				}
				setPodNutritionDivLoc('Pod');
				return false;
			} else {
				setPodNutritionDiv("");
			}
		}
		SetDivPosition('divVerifyPhoneConfirm');
		setPodNutritionDivLoc('Pod'); 
	}
	return false;
}

function showVerifyPhoneDivGMDirectory()
{
	var div = Get('divVerifyPhoneConfirm');
	
	if(div)
	{
		div.style.display = 'inline';
		
		var gmDirectoryDiv = Get('divOptinInfo');
		
		if(gmDirectoryDiv) {
			div.style.top =  (parseInt(gmDirectoryDiv.style.top)+100)+'px';
			div.style.left = (parseInt(gmDirectoryDiv.style.left)-40)+'px';
		}	
		setPodNutritionDivLoc('GMDirectory');
	}
	return false;
}

function deletePodNutritionInfo(location)
{
	var expiredays = 1;
	var exdate=new Date();
	exdate.setDate(exdate.getDate()-expiredays);
	if(location)
	{
		return document.cookie = "SMS.ac_podNutritionLoc==;expires="+exdate.toGMTString();
	}
	else {return document.cookie = "SMS.ac_podNutrition==;expires="+exdate.toGMTString();}
}

function getPodNutritionDiv(location)
{
		var c_name = "SMS.ac_podNutrition";
		var c_name_loc = "SMS.ac_podNutritionLoc";
	
		if (document.cookie.length>0)
		{
			if(location)
			{
				c_start=document.cookie.indexOf(c_name_loc + "=");
				if (c_start!=-1)
				{ 
					c_start=c_start + c_name_loc.length+1; 
					c_end=document.cookie.indexOf(";",c_start);
					if (c_end==-1) c_end=document.cookie.length;
					return unescape(document.cookie.substring(c_start,c_end));
				}
			}	
		}
		else
		{
			c_start=document.cookie.indexOf(c_name + "=");
			if (c_start!=-1)
			{ 
				c_start=c_start + c_name.length+1; 
				c_end=document.cookie.indexOf(";",c_start);
				if (c_end==-1) c_end=document.cookie.length;
				return unescape(document.cookie.substring(c_start,c_end));
			}
		}	
		return "";
}

function SetDivPosition(divName)
{
		if( document.getElementById(divName) ) 
		{
	
			// Get a reference to divTest and measure its width and height.
			var div = Get(divName);		
			if(div)
			{
				var divWidth = div.offsetWidth ? div.offsetWidth : div.style.width ? parseInt( div.style.width ) : 0;
				var divHeight = div.offsetHeight ? div.offsetHeight :  div.style.height ? parseInt( div.style.height ) : 0;

				// Calculating setX and setX so the div will be centered in the viewport.
				var setX = ( getViewportWidth()   - divWidth ) / 2 + getViewportScrollX();
				var setY = ( .5*window.screen.height  - divHeight ) / 2 +  getViewportScrollY();

				// If setX or setY have become smaller than 0, make them 0.
				if( setX < 0 ) setX = 0;
				if( setY < 0 ) setY = 0;

				// Position the div in the center of the page and make it visible.
				div.style.left = setX + "px";
				div.style.top = setY + "px";
			}
		}
}

getViewportWidth = function() {
	var width = 0;
	if( document.documentElement && document.documentElement.clientWidth ) {
		width = document.documentElement.clientWidth;
	}
	else if( document.body && document.body.clientWidth ) {
		width = document.body.clientWidth;
	}
	else if( window.innerWidth ) {
		width = window.innerWidth - 18;
	}
	return width;
};

getViewportHeight = function() {
  var height = 0;
  
  //ZH this seems to work for firefox and IE
  if( document.body && document.body.clientHeight ) {
    height = document.body.clientHeight;
  }
  else if( window.innerHeight ) {
    height = window.innerHeight - 18;
  }
  return height;
};

getViewportScrollX = function() {
  var scrollX = 0;
  if( document.documentElement && document.documentElement.scrollLeft ) {
    scrollX = document.documentElement.scrollLeft;
  }
  else if( document.body && document.body.scrollLeft ) {
    scrollX = document.body.scrollLeft;
  }
  else if( window.pageXOffset ) {
    scrollX = window.pageXOffset;
  }
  else if( window.scrollX ) {
    scrollX = window.scrollX;
  }
  return scrollX;
};

getViewportScrollY = function() {
  var scrollY = 0;
  if( document.documentElement && document.documentElement.scrollTop ) {
    scrollY = document.documentElement.scrollTop;
  }
  else if( document.body && document.body.scrollTop ) {
    scrollY = document.body.scrollTop;
  }
  else if( window.pageYOffset ) {
    scrollY = window.pageYOffset;
  }
  else if( window.scrollY ) {
    scrollY = window.scrollY;
  }
  return scrollY;
};

function closeVerifyPhoneDiv()
{
	var div = Get('divVerifyPhoneConfirm');
	if(div!=null)
	{
		div.style.display = 'none';
	}
}

function closeVerifyPhoneDivSMS()
{
	var div = Get('divVerifyPhoneConfirmSMS');
	if(div!=null)
	{
		div.style.display = 'none';
	}
}

function getPageSizeWithScroll(){
	if (window.innerHeight && window.scrollMaxY) 
	{
		// Firefox
		yWithScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight)
	{ 
		// all but Explorer Mac
		yWithScroll = document.body.scrollHeight;
	} else 
	{ 
		// works in Explorer 6 Strict, Mozilla (not FF) and Safari
		yWithScroll = document.body.offsetHeight;
  	}
	return yWithScroll;
}

function disablePageBehind()
{
	var div;
	if ($('frmMHP'))
    	div = Get('divDisablePageMHP');
    else
        div = Get('divDisablePage');
	if(div)
	{
		div.style.display = 'block';
		div.style.height = getPageSizeWithScroll();
		div.style.width = document.body.scrollWidth;
	}
}

function enablePageBehind()
{
	var div;
	if ($('frmMHP'))
    	div = Get('divDisablePageMHP');
    else
        div = Get('divDisablePage');
	if(div)
	{
		div.style.display = 'none';	
	}
}
//End Re-Verify Phone Functions

function removeSplashPage()
{
	var div = Get('splashPage');
	if(div)
	{
		div.style.display = 'none';	
	}
}

//function to show and hide the broadcasts link 
function HideShowBroadcasts(id)
{
		var broadcasts = Get(id);	
		if(broadcasts!=null)
		{
		broadcasts.style.visibility =  'visible';
		}
		setTimeout("Get('" + id + "').style.visibility =  'hidden'; ",2000) 
		setTimeout("Get('" + id + "').style.visibility =  'visible';", 2200);
		setTimeout("Get('" + id + "').style.visibility =  'hidden';", 2400);
		setTimeout("Get('" + id + "').style.visibility =  'visible'", 2600);    
}

var cnt = 0;
var color = new initArray("red", "blue", "green");
var interval = 1000;
function Blink(elementId) {
		var element;
		if (document.getElementById) {
			element = document.getElementById(elementId);
		}
		if(cnt == 6)
		{
			document.getElementById(elementId).style.color="black";
			clearTimeout();
			return;
		}
		element.style.color = color[x];
		(x < color.length-1) ? x++ : x = 0;
		cnt++;
		setTimeout("Blink('" + elementId + "')", interval);
}

function initArray() {
		this.length = initArray.arguments.length;
		for (var i = 0; i < this.length; i++) {
			this[i] = initArray.arguments[i];
		}
}

function launchIM()
{
		window.open("/mobilemessenger/messenger.html",null,"height=600,width=300,status=yes,toolbar=no,menubar=no,location=no,resizable=yes");
}

/******** PHOTOS *********/


var errorType;
var imgInput;
function PhotoUpload(target, photoSrc, saveBtn)
{
		var imgPrev = Get(target);
		if(!CheckImageError(photoSrc) && errorType=="InvalidFileType")
		{
			alert('Please select a valid file type');
		}
		else if(errorType=="InvalidFileSize")
		{
			alert('Please select a valid file less than 1MB');
		}
		else
		{
			imgInput = Get(photoSrc);
			imgPrev.src = imgInput.value;
			imgPrev.style.display = "inline";	
			EnableInput(saveBtn);
		}
}


function PhotoDisplay(target, photoSrc, divToClose)
{
		var imgPrev = Get(target);
		imgInput = Get(photoSrc);
		imgPrev.src = imgInput.value;
		imgPrev.style.display = "inline";	

		Element.hide(divToClose);
		hideDivPopThemesFrame();
}

function SaveImage(photoSrc, formId, path)
{
		if(!CheckImageError(photoSrc) && errorType=="InvalidFileType")
		{
			alert('Please select a valid file type');
		}
		else if(errorType=="InvalidFileSize")
		{
			alert('Please select a valid file less than 1MB');
		}
		else
		{
			PostForm(formId,'POST', path + imgInput.value);
		}
}

function PostForm(formId,method,action){
		var fEle = Get(formId);
		if(!fEle) return false;
		fEle.method = method;
		if(action)
			fEle.target='_top';
			fEle.action = action;
		
		fEle.submit();
}

function CheckImageError(photoSrc){
		imgInput = Get(photoSrc);
		if(imgInput.value == "")
			return true;
		if(!IsValidImgFile(imgInput)){
				errorType = "InvalidFileType";
				return false;
		}
		else {
			var mySize = getFileSize(imgInput.value);
			//added when file size>1MB
			if(mySize > 1048576){
			errorType = "InvalidFileSize";
				return false;			
			}
		}
		return true;
}

function IsValidImgFile(myInput){
		var imgNm = myInput.value;
		var exts = new Array(5);
		exts[0] = "jpg";
		exts[1] = "png";
		exts[2] = "jpeg";
		exts[3] = "gif";
		exts[4] = "bmp";
		
		var myExt;
		if(imgNm)
			myExt = getExtention(imgNm);
		else
			return true;
		if(imgNm.length > 0){
			if(myExt == "")
				return false;
			//check extensions
			for(x=0;x < exts.length;x++){
				if(exts[x] == myExt)
					return true;
			}
			return false;
		}else
			return false;
		return true;
}

function getExtention(filename){
		var dot_pos = filename.lastIndexOf('.');
		if(dot_pos == -1)
			return "";
		return filename.substr(dot_pos+1).toLowerCase();
}

function getFileSize (fileName) {
		var i = new Image();
		i.src = fileName;
		var max_wait = 2500;
		var cur_wait = 0;
		while (true) {
			if (i.fileSize>0)
				break;
			cur_wait += 10;
			wait(10);
			if (cur_wait > max_wait){
				return 2048576;		
			}
		}
		return i.fileSize;
}
function wait(delay){
		t = new Date();
		t.setTime(t.getTime()+delay); 
		while((new Date()) < t);
}
function ChangeButtonText(el,text){
		if(!(el=document.getElementById(el))) return;
		if(el)
			el.value = text;
}

function EnableInput(el){
		if(!(el=document.getElementById(el))) return;
		if(el)
			el.disabled = false;
}

function DisableInput(el){
		if(!(el=document.getElementById(el))) return;
		if(el)
			el.disabled = true;
}

function showActivationMiniReg()
{
		return showMiniReg('optin','activate');
}

// var global_minireg_type = -1;
var MR_EXIT_NULL	=-1; //-1 = null, initial val
var MR_EXIT_CLOSE	= 0; // 0 = exit via close no refresh, 
var MR_EXIT_PRESYNC = 1; // 1 = exit via presync, 
var MR_EXIT_REG04	= 2; // 2 = exit via reg04

function showVerifyMiniReg(strExit)
{
	var exitMethod;
	
		//alert(strExit + ',' + parent.global_minireg_type);
	
		hideNutritionDiv();
		
		// exit via close
		
		if(parent.global_minireg_type == null) // I will only verify IF i'm logged in
		{
			exitMethod = 'goto_reg04';
		}
		
		// exit via close minireg
		else if(parent.global_minireg_type == MR_EXIT_CLOSE) { // || (strExit == 'close_minireg' && global_minireg_type == MR_EXIT_NULL)
			//alert('exit via close');
			exitMethod = 'close_minireg';
		} 
		
		// exit via reg04
		else if((parent.global_minireg_type == MR_EXIT_REG04) || (parent.global_minireg_type == MR_EXIT_NULL && strExit == 'goto_reg04')) {
			//alert('exit via reg04');
			exitMethod = 'goto_reg04';
		} 
		
		// exit via pre-sync
		else {
			//alert('exit via presync');
			exitMethod = 'goto_presync';
		}
		
		//alert('set to NULL');
		parent.global_minireg_type = MR_EXIT_NULL;
		return getMiniRegDiv('optin','activate','verify', exitMethod);
		
}

function setPodNutritionDivLoc(location)
{
		var expiredays = 1;
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		
		if(location)
		{
			document.cookie = "SMS.ac_podNutritionLoc=" + escape(location) + ";domain=profile.fanbox.com;expires="+exdate.toGMTString() + ";path=/;";
		}
		
		//alert('set to close');
		parent.global_minireg_type = MR_EXIT_CLOSE;
		return;
}

function showVerifyPhoneDiv()
{
		var div = Get('divVerifyPhoneConfirm');
		if(div)
		{
			var newevent = event;
			if(newevent != null)
			{
				var podNutritionDivId = newevent.srcElement.id;
				podNutritionDivId = podNutritionDivId.replace('lnkEditPhoneNumber','');
				var myregexp = new RegExp("pod[0-9]+_[0-9]+_[0-9]+_");
				
				if(myregexp.exec(podNutritionDivId))
				{
					setPodNutritionDiv(podNutritionDivId);
				}
				else 
				{
					setPodNutritionDiv("");
				}
			}
			div.style.display = 'inline';
			SetDivPosition('divVerifyPhoneConfirm');
			
			//alert('set to reg04');
			parent.global_minireg_type = MR_EXIT_REG04;
		}
		return false;
}

function setPodNutritionDiv(valuePodId)
{
		var expiredays = 1;
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		
		if(valuePodId)
		{
			document.cookie = "SMS.ac_podNutrition=" + escape(valuePodId) + ";domain=profile.fanbox.com;expires="+exdate.toGMTString() + ";path=/;";
		}
		
		return false;
}

function showVerifyMicroReg()
{
	hideNutritionDiv();
	return getMiniRegDiv('introsmall','activate','verify');
}
function updatePodHeaders() { 
		var newName = getPossessive(field.getText());
		if(newName.length == 0)
			return false;	
		
		var spans = document.getElementsByClassName('displayNm', document.body);
		var s;
		
		if(spans)
			for (var i = 0; i < spans.length; i++) {
				s = spans[i].innerHTML;
				s = s.substring(s.indexOf(' '));  // strip out old name.
				spans[i].innerHTML = newName + s; 		
			}
}

function getPossessive(name) {
		if(name.length == 0)
			return name;
			
		if(name.charAt(name.length-1) != 's')
			return (name + "'s");
		else
			return (name + "'");
}

function isEmailOrPhone(str)
{
    var phonePattern = new RegExp("[0-9]{5,}");
    if (str.indexOf("@") > - 1 || phonePattern.exec(str) != null)
        return true;
    return false;
}

function setMemSrchPos()
{
    if ($('spanMemSrchState'))
    {
        if($('spanMemSrchState').style.display == 'none')
        {
            // move member search div right
            if ($('Header1_lnkMemSrch'))
                Position.clone('Header1_lnkMemSrch', 'divMemSrch', {setWidth: false, setHeight: false, offsetLeft: -290, offsetTop: 20});
	        else if ($('ctl00_Header1_lnkMemSrch'))
                Position.clone('ctl00_Header1_lnkMemSrch', 'divMemSrch', {setWidth: false, setHeight: false, offsetLeft: -290, offsetTop: 20});

            // shrink member search div's width
            if ($('divMemSrch'))
                $('divMemSrch').style.width = '410px';
        } // search without states
        else
        {
            // move member search div left
            if ($('Header1_lnkMemSrch'))
                Position.clone('Header1_lnkMemSrch', 'divMemSrch', {setWidth: false, setHeight: false, offsetLeft: -453, offsetTop: 20});
            else if ($('ctl00_Header1_lnkMemSrch'))
                Position.clone('ctl00_Header1_lnkMemSrch', 'divMemSrch', {setWidth: false, setHeight: false, offsetLeft: -453, offsetTop: 20});

            // expand member search div's width
            if ($('divMemSrch'))
                $('divMemSrch').style.width = '573px';
        } // search with states
    }
}
var memSrchInitialized;
var dfltMemSrchCtryIndx;
function toggleMemSrchDiv()
{
    var divMemSrch = $('divMemSrch');
    if (divMemSrch)
    {
        if (divMemSrch.style.display == 'none')
        {
            // initialize member search div
            if (memSrchInitialized != true)
            {
                new Ajax.Request('http://profile.fanbox.com/profile/membersearchpopup.aspx',
                                    {   method: 'get',
                                        onSuccess:  function(response)
                                                    {
                                                        if ($('divMemSrch'))
                                                        {
                                                            var newScriptTag = document.createElement('script');
                                                            newScriptTag.type = 'text/javascript';
                                                            newScriptTag.src = '/Pod_Js/memberSearchPopup.js';
                                                            var headTag = document.getElementsByTagName('head')[0];
                                                            headTag.appendChild(newScriptTag);

                                                            $('divMemSrch').innerHTML = response.responseText;

                                                            // remember default country
                                                            if ($('memSrchCtry') && $('memSrchCtry').selectedIndex)
                                                                dfltMemSrchCtryIndx = $('memSrchCtry').selectedIndex;
                                                            else
                                                                dfltMemSrchCtryIndx = 0;
                                                            // set the member search popup's position
                                                            setMemSrchPos();
                                                            // show member search div
                                                            Element.toggle('divMemSrch');
                                                        }
                                                    }
                                    } );

                memSrchInitialized = true;
            }
            else
            {
                // show member search div
                Element.toggle('divMemSrch');
            }

            // clear search box
            var inputSearchTerm = $('SearchTerm');
            if (inputSearchTerm)
                inputSearchTerm.value = '';

            // make the member search div top-most
            pullDivToTop(divMemSrch);
        } // showing member search div
        else
        {
            // reset all values
            $('memSrchSex').selectedIndex = 0;
            $('memSrchMinAge').selectedIndex = 0;
            $('memSrchMaxAge').selectedIndex = 81;
            if ($('memSrchCtry') && $('selMemSrchState') && $('memSrchCity') && $('spanMemSrchState'))
            {
                $('memSrchCtry').selectedIndex = dfltMemSrchCtryIndx;
                if($('memSrchCtry').options[dfltMemSrchCtryIndx].value == 768)
                    Element.show('spanMemSrchState');
                else
                    Element.hide('spanMemSrchState');
                $('selMemSrchState').selectedIndex = 0;
                ddAO('memSrchCity', Array("Select a City"), Array("-1"));
                $('memSrchCity').disabled = true;
            }
            setMemSrchPos();
            // hide member search div
            Element.toggle('divMemSrch');
        } // hiding member search div
    }
}
function getTermValue()
{
	var termField = document.getElementById('SearchTerm');
	if(termField)
	{
		var term = termField.value;		
		return term;
	}
}

function getKeyCode(e)
{
		var eventObj = window.event ? event : e;
		return keyCode = eventObj.charCode ? eventObj.charCode : eventObj.keyCode;
}

function executeSearch(invoker)
{
    	var target;
	    if (invoker.id == 'SearchButton')
	    {
	        var searchTerm = getTermValue();
	        if (searchTerm == "")
	            target = "http://profile.fanbox.com/ContentSearch/Default.aspx?r=3&c=89&dps=";
	        else if (isEmailOrPhone(searchTerm))
	            target = "http://profile.fanbox.com/ContentSearch/Default.aspx?r=3&c=89&amn=18&amx=99&q=" + escape(searchTerm);
	        else if (searchTerm)
		        target = "http://profile.fanbox.com/ContentSearch/?r=3&q=" + escape(searchTerm);
		}
		else if (invoker.id == 'memSrchButton' || invoker.id == 'advMemSrchLnk')
		{
	        target = getMemSrchUrl(invoker.id);
	        if (invoker.id == "memSrchButton")
	            target += "&msm=msp";
	    }
	    else
	        return;

		window.location.href = target; // open search results in same window
}

var searchTipInit = false;
var searchHasFocus = false;
var searchTipTimer;
function showSearchTipDelay()
{
	searchTipTimer = window.setTimeout("showSearchTip()", 300);
}

function showSearchTip()
{
	clearSearchTipTimer();
	var searchInput = document.getElementById('SearchTerm');
	var searchTip = document.getElementById('SearchTip');
	
	if(!searchTipInit)
	{
		if(searchTip && searchInput)
		{
			var searchTop = getPosition(searchInput, "y");
			var searchLeft = getPosition(searchInput, "x");
			
			searchTip.style.left = searchLeft - 25;
			searchTip.style.top = searchTop - 40;
		}
	}
	
	if(!searchHasFocus)
	{
		searchTip.style.visibility = "visible";
	}
}
function hideSearchTip()
{
	clearSearchTipTimer();
	var searchTip = document.getElementById('SearchTip');
	searchTip.style.visibility = "hidden";
}

function clearSearchTipTimer()
{
	if(searchTipTimer)
	{
		searchTipTimer = window.clearTimeout(searchTipTimer);
	}
}

function MoneyBalanceBlink(layerName, counter, lblvisible)
{
		if(counter>6)
		{	
			clearTimeout();
			return;
		}
		else
		{
			var bName = navigator.appName;
			var bVer = parseInt(navigator.appVersion);
			var NS4 = (bName == "Netscape" && bVer >= 4);
			var IE4 = (bName == "Microsoft Internet Explorer" && bVer >= 4);
			var NS3 = (bName == "Netscape" && bVer < 4);
			var IE3 = (bName == "Microsoft Internet Explorer" && bVer < 4);
			var blink_speed=1000;
			counter++;
			if (NS4 || IE4) 
			{
				if (navigator.appName == "Netscape") 
				{
					layerStyleRef="layer.";
					layerRef="document.layers";
					styleSwitch="";
				}
				else
				{
					layerStyleRef="layer.style.";
					layerRef="document.all";
					styleSwitch=".style";
				}
			}
			if(lblvisible)
			{
				eval(layerRef+'["'+layerName+'"]'+
				styleSwitch+'.visibility="visible"');
				setTimeout("MoneyBalanceBlink('"+layerName+"',"+counter+","+false+")",blink_speed);
			}
			else
			{
				eval(layerRef+'["'+layerName+'"]'+
				styleSwitch+'.visibility="hidden"');
				setTimeout("MoneyBalanceBlink('"+layerName+"',"+counter+","+true+")",blink_speed);
			}
		}
}

function openTopPerformersPopup(profuser)
{
    if ($('topPerformersPopupContent').innerHTML == '')
    {
        new Ajax.Updater('topPerformersPopupContent', 'http://profile.fanbox.com/Profile/topperformerspopup/default.aspx',
                            {
                                method:     'get',
                                parameters: 'u='+profuser,
                                onSuccess:  function()
                                            {                                      
                                                                                         
                                                                                             
                                                var newScriptTag = document.createElement('script');
                                                newScriptTag.type = 'text/javascript';
                                                newScriptTag.src = '/Pod_Js/topPerformers.js';
                                                var headTag = document.getElementsByTagName('head')[0];
                                                headTag.appendChild(newScriptTag);
                                                
                                                showStarsUnlock();
                                                Element.show('frameDisablePageMHP');
                                                var nS=$('mhpBackground');
                                                if(nS)nS.style.overflow='hidden';
                                                
                                                var performerParent=$('topPerformersPopupParent');
                                                var topBody=document.body;
                                                topBody.appendChild(performerParent);
                                                performerParent.style.width="100%";
                                                performerParent.style.height="100%";
                                                performerParent.style.overflow="auto";
                                                
                                                $('topPerformersPopup').style.top = '0px';
                                                $('topPerformersPopup').style.marginTop = '88px';
                                                pullDivToTop('topPerformersPopup');
                                                Element.show('topPerformersPopup');  
                                            }
                            }
                        );
    }
    else
    {
        $('closeTPAnchor').onclick = closeTopPerformersPopup;
        showStarsUnlock();
        
        Element.show('frameDisablePageMHP');
        var nS=$('mhpBackground');
        if(nS)nS.style.overflow='hidden';  
        
        var performerParent=$('topPerformersPopupParent');
        var topBody=document.body;
        topBody.appendChild(performerParent);
        performerParent.style.width="100%";
        performerParent.style.height="100%";
        performerParent.style.overflow="auto";
        
        $('topPerformersPopup').style.top = '0px';
        $('topPerformersPopup').style.marginTop = '88px';
        pullDivToTop('topPerformersPopup');
        Element.show('topPerformersPopup');
    }
}

function top100LearnHowLink() {
    Element.hide('topPerformersPopup');
    setStarDivPosition();
    var performerParent=$('topPerformersPopupParent');
    performerParent.style.height="0%";
    performerParent.style.overflow="hidden";
    var starsParent=$('starInfo').parentNode;
    starsParent.style.height="100%";
    starsParent.style.width="100%";
    starsParent.style.top="0px";
    starsParent.style.overflow="auto";
    $('starInfo').style.top="";
    $('starInfo').style.marginTop="88px";
    Element.show('starInfo');
}

function closePing()
{
    var app = navigator.appVersion;
    Element.hide('PingDivPopup');
	var curtain = $("frameDisablePageMHP");
	if(curtain)
	{
		Element.hide(curtain);
	}
    if(app.indexOf('MSIE 6.0') != -1)
    { 
	var contentContainer = $("frmMHP");
        contentContainer.style.height="";
        contentContainer.style.width="";
        contentContainer.style.overflow="";
        contentContainer.style.position = "";
        contentContainer.style.zIndex = "";
        contentContainer.style.left = "";
        contentContainer.style.top = "";
        contentContainer.style.marginRight = "";

        window.document.documentElement.style.overflowX = "";
        window.document.documentElement.style.overflowY = "";
        document.body.style.overflowY = "";
        document.body.style.overflowX = "";
    }
}


function RenderPing()
{
    var htmlEle = window.document.documentElement;
    var newOffSetWidth;
    var oldOffSetWidth = $("frmMHP").offsetWidth;
    var app = navigator.appVersion;
   new Ajax.Updater('PingDivPopup', 'http://profile.fanbox.com/Profile/PingDivPopup/PingPopup.aspx',
                                        {
                                            onSuccess:  function()
                                            {
                                                $('PingDivPopup').style.display = "block";

                                                if(app.indexOf('MSIE 6.0') != -1)
                                                {
                                                    htmlEle.scrollTop = "0";
                                                    htmlEle.style.bottom = "0px";
                                                    htmlEle.style.overflowX = "hidden";
                                                    htmlEle.style.overflowY = "hidden";   
                                                    
                                                    document.body.style.overflowY = "scroll";
                                                    document.body.style.overflowX = "hidden";   
                                                    
                                                    $("frmMHP").style.position = "absolute";
                                                    $("frmMHP").style.zIndex = "1";
                                                    $("frmMHP").style.left = "0px";
                                                    $("frmMHP").style.top = "0px";
                                                    newOffSetWidth = $("frmMHP").offsetWidth;
                                                    marginScrollBar = (newOffSetWidth - oldOffSetWidth)/2;
                                                    $("frmMHP").style.marginRight = marginScrollBar + "px";
                                                    
                                                    
                                                    $('PingDivPopup').style.position = 'absolute';
                                                    $('PingDivPopup').style.left="50%";
                                                    $('PingDivPopup').style.top="50%";
                                                    $('PingDivPopup').style.marginLeft = "-" + (parseInt($('PingDivPopup').style.width)/2) + "px";
                                                    $('PingDivPopup').style.marginTop = "-" + (parseInt($('PingDivPopup').style.height)/2) + "px";                                     
                                                 
                                                    var curtain = $("frameDisablePageMHP");
	                                                curtain.style.position = "absolute";
	                                                curtain.style.zIndex = 1;
	                                                curtain.style.top = curtain.style.left = "0px";
	                                                curtain.style.width = curtain.style.height = "100%";

	                                                curtain.style.backgroundColor = "#000";
	                                                curtain.style.color = "#FFF";
	                                                curtain.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=0)";
	                                                curtain.style.opacity = "0";     
	                                                curtain.style.display = "block";                       
                                                }
                                                else
                                                {
                                                    $('PingDivPopup').style.position = 'fixed';
                                                    $('PingDivPopup').style.left="50%";
                                                    $('PingDivPopup').style.top="50%";
                                                    $('PingDivPopup').style.marginLeft = "-" + (parseInt($('PingDivPopup').style.width)/2) + "px";
                                                    $('PingDivPopup').style.marginTop = "-" + (parseInt($('PingDivPopup').style.height)/2) + "px";
                                                }
                                            }
                                         }
                                   );

}

function sendPing(p)
{
    var newOffSetWidth;
    var oldOffSetWidth = $("frmMHP").offsetWidth;
    var app = navigator.appVersion;
    new Ajax.Updater('PingDivPopup', 'http://profile.fanbox.com/Profile/PingDivPopup/Remote_Ping.ashx',
                                        {
                                            parameters: 'p='+p,
                                            evalScripts: true, 
                                            onComplete:function()
                                            {
                                                if(app.indexOf('MSIE 6.0') != -1)
                                                {
                                                    newOffSetWidth = $("frmMHP").offsetWidth;
                                                    marginScrollBar = (newOffSetWidth - oldOffSetWidth);
                                                    $("frmMHP").style.marginRight = marginScrollBar + "px";
                                         }
                                            }
                                        });      
}                                                       

function HeaderDD(action)
{
    var div = $('dddiv');
    var menu = $(action);
    var pos = Position.cumulativeOffset(menu);
    div.style.left = pos[0] + "px";
    div.style.top = pos[1] + 22 + "px";
    menu.style.backgroundColor = "#9B9B9B";
    new Ajax.Updater('dddiv', 'http://profile.fanbox.com/Header/Remote.ashx',  {method: 'get',  parameters: 'action='+action,
    onSuccess: function()
    {
        Element.show('dddiv');
        if(navigator.userAgent.toLowerCase().indexOf('msie') != -1)
        {
            document.body.attachEvent('onmousedown', HideHeaderDD);
            div.attachEvent('onmousedown', stopBubble);
            stopBubble();
        }
        else
        {
            document.body.addEventListener('mousedown', HideHeaderDD, false);
            div.addEventListener('mousedown', stopBubble, false);
        }
    }});
}

function HideHeaderDD()
{
    Element.hide('dddiv');
    $('idd').style.backgroundColor = "#000";
    $('fdd').style.backgroundColor = "#000";
    if(navigator.userAgent.toLowerCase().indexOf('msie') != -1)
    {
        document.body.detachEvent('onmousedown', HideHeaderDD);
        $('dddiv').detachEvent('onmousedown', stopBubble);
    }
    else
    {
        document.body.removeEventListener('mousedown', HideHeaderDD, false);
        $('dddiv').removeEventListener('mousedown', stopBubble, false);
    }
}

function stopBubble(arg)
{
    if(navigator.userAgent.toLowerCase().indexOf('msie') != -1)
        window.event.cancelBubble = true;
    else
        arg.stopPropagation();
}
    
    function searchMHPTxtKeypress(e)
    {
        var knum;
        if (window.event) //IE
            knum = e.keyCode;
        else if (e.which) //NS/FFox/Opera
            knum = e.which;
        if (knum == 13 || knum == 3)
        {
            onMHPSubmitSearch();
            return false;
         } // if enter key pressed, submit search
         else
             return true;
    } // forwards an enter key keypress event to a button element "el"
    
    function onMHPSubmitSearch()
    {
        var c;
        profUser = "";
        var c;
        
        var qsInput = $("searchField");
        if(qsInput)
        {
            // hide all error messages that may be showing
            var errHate = $("SearchErrHate");
            if(errHate)
                errHate.hide();
            var errBlank = $("SearchErrBlank");
            if(errBlank)
                errBlank.hide();
            var errMarkup = $("SearchErrMarkup");
            if(errMarkup)
                errMarkup.hide();

            // strip the leading and trailing white space characters in the query string
            var qs = qsInput.value.replace(/^\s+|\s+$/g, "");
            // replace strings of white space characters with single spaces
            qs = qs.replace(/\s{2,}/g, " ");
            // encode special characters

            if(qs)
            {
                if(!hasMarkup(qs))
                {
                    if (getCookie("sc"))
                        c = getCookie("sc");
                    
                    if(encodeURIComponent)
                        qs = encodeURIComponent(qs);
                    else
                        qs = escape(qs);
                    if(c != null)
                        window.location = "http://profile.fanbox.com/ContentSearch/?q="+qs+"&c="+c+"&u="+profUser+"&po=1";
                    // searching in some category
                    else
                    {   
                        window.location = "http://profile.fanbox.com/ContentSearch/?q="+qs+"&c=89" + "&u="+profUser+"&po=1";
                    } // searching in all categories
                }  // forward query string to adult/hate filter
                else if (errMarkup)
                {
                    errMarkup.show();
                } // show error message for queries containing markups
            }
            else if (errBlank)
            {
                errBlank.show();
            } // show error message for blank query
        }
    }
    
    function expandUpload()
    {
        if($('arrow_down').style.display == "none")
        {
            $('uploadText').style.paddingBottom = "7px";
            Element.hide($('arrow_right'));
            Element.show($('arrow_down'));
            Element.show($('upApps'));
        }
        else
        {
            $('uploadText').style.paddingBottom = "0px";
            Element.show($('arrow_right'));
            Element.hide($('arrow_down'));
            Element.hide($('upApps'));
        }
    }
    
    function showSearchDropDown()
    {
        if ($('searchdropdown').style.display == "none")
            Element.show($('searchdropdown'));
        else
            Element.hide($('searchdropdown'));
    }
    
    
    function openDevSite()
    {
        if(window.top != window)
        {
            var mdIFrame = document.createElement("iframe");
            mdIFrame.src = "http://www.fanbox.com/socnet/AppDevelopers.html";
            mdIFrame.style.display = "none";
            var container = document.body;
            container.appendChild(mdIFrame);
        }
    }
    
    
    function RenderMHPBroadcast(displaynm)
    {
       new Ajax.Updater('PingDivPopup', 'http://profile.fanbox.com/Profile/Remote_Broadcast.aspx?mode=show&displaynm='+displaynm,
                                            {
                                                method: 'get',
                                                onSuccess:  displayPingPopupDiv
                                             }
                                       );

    }
    
    function displayReportDiv(src, userno)
    {
        new Ajax.Updater('PingDivPopup', 'http://profile.fanbox.com/Profile/Remote_Report.aspx?mode=show&src='+src+'&uno='+userno+'&rsn=0',{method: 'get',onSuccess:  displayPingPopupDiv});
    }
    
    function reportUser(src, userno)
    {
        var comboBox = $('reportDivSelectBox'); 
        if( !!comboBox)
        {
            new Ajax.Updater('PingDivPopup', 'http://profile.fanbox.com/Profile/Remote_Report.aspx?mode=report&src='+src+'&uno='+userno+'&rsn='+comboBox.options[comboBox.selectedIndex].value,{method: 'get',onSuccess:  displayPingPopupDiv});
        }
    }
    
    function displayPingPopupDiv()
    {
        var htmlEle = window.document.documentElement;
        var newOffSetWidth;
	var contentContainer = $("frmMHP");
	var dialog = $('PingDivPopup');
        var oldOffSetWidth = contentContainer.offsetWidth;
        var app = navigator.appVersion;
        dialog.style.display = "block";

        if(app.indexOf('MSIE 6.0') != -1)
        {
            htmlEle.scrollTop = "0";
            htmlEle.style.bottom = "0px";
            htmlEle.style.overflowX = "hidden";
            htmlEle.style.overflowY = "hidden";

            document.body.style.overflowY = "scroll";
		/* On the photo page, setting the overflow to 'visible' instead of 'hidden' keeps the content displayed. */
            document.body.style.overflowX = "visible";

            contentContainer.style.position = "absolute";
            contentContainer.style.zIndex = "1";
            contentContainer.style.left = "0px";
            contentContainer.style.top = "0px";
            newOffSetWidth = contentContainer.offsetWidth;
            marginScrollBar = (newOffSetWidth - oldOffSetWidth)/2;
            contentContainer.style.marginRight = marginScrollBar + "px";


            dialog.style.position = 'absolute';
            dialog.style.left="50%";
            dialog.style.top="50%";
            dialog.style.marginLeft = "-" + (parseInt(dialog.style.width)/2) + "px";
            dialog.style.marginTop = "-" + (parseInt(dialog.style.height)/2) + "px";

            var curtain = $("frameDisablePageMHP");
            curtain.style.position = "absolute";
            curtain.style.zIndex = 1;
            curtain.style.top = curtain.style.left = "0px";
            curtain.style.width = curtain.style.height = "100%";

            curtain.style.backgroundColor = "#000";
            curtain.style.color = "#FFF";
            curtain.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=0)";
            curtain.style.opacity = "0";
            curtain.style.display = "block";
        }
        else
        {
            dialog.style.position = 'fixed';
            dialog.style.left="50%";
            dialog.style.top="50%";
            dialog.style.marginLeft = "-" + (parseInt(dialog.style.width)/2) + "px";
            dialog.style.marginTop = "-" + (parseInt(dialog.style.height)/2) + "px";
        }
    }

function HideDiv(divName)
{
	var div = $(divName);
	if(div)
		Element.hide(div);
		
	var myIFrame = $('ifFixMePublic');	
	if (myIFrame)
	 	Element.hide(myIFrame);
	 	
	var myIFrame2 = $('ifFixMe');	
	if (myIFrame2)
	 	Element.hide(myIFrame2);
	 	
	var myIFrame3 = $('ifFixMe3');	
	if (myIFrame3)
	 	Element.hide(myIFrame3);
}

function MHPSearchDD(action)
{
    var div = $('sdd');
    var menu = $(action);
    var pos = Position.cumulativeOffset(menu);
    

        div.style.left = pos[0] + "px";
        div.style.top = pos[1] + 17 + "px";

        new Ajax.Updater('sdd', 'http://profile.fanbox.com/Header/Remote.ashx',  {method: 'get',  parameters: 'action='+action,
        onSuccess: function()
        {
            Element.show('sdd');
            if(navigator.userAgent.toLowerCase().indexOf('msie') != -1)
            {
                document.body.attachEvent('onmousedown', HideMHPSearchDD);
                div.attachEvent('onmousedown', stopBubble);
                stopBubble();
            }
            else
            {
                document.body.addEventListener('mousedown', HideMHPSearchDD, false);
                div.addEventListener('mousedown', stopBubble, false);
            }
        }});
}

function HideMHPSearchDD()
{
    Element.hide('sdd');
    
    if(navigator.userAgent.toLowerCase().indexOf('msie') != -1)
    {
        document.body.detachEvent('onmousedown', HideMHPSearchDD);
        $('sdd').detachEvent('onmousedown', stopBubble);
    }
    else
    {
        document.body.removeEventListener('mousedown', HideMHPSearchDD, false);
        $('sdd').removeEventListener('mousedown', stopBubble, false);
    }
}

    function setMHPCatLnk(c)
    {
    	var today = new Date();
    	var exp   = new Date(today.getTime()+1*24*60*60*1000);
        $('searchFieldType').value = c;
        setCookie("sc", c, exp, "/","profile.fanbox.com","");
        HideMHPSearchDD();
		new Ajax.Updater('siDD','http://profile.fanbox.com/Header/Remote.ashx',{method:'get',parameters:'action=siDDH' + '&c=' + c});
    }
    
    function HidePingDivPopup()
    {
        Element.hide($("PingDivPopup"));
    }
    
    function appsCheckMD()
    {
        if(window.top != window)
        {
            var mdIFrame = document.createElement("iframe");
            mdIFrame.src = "http://www.fanbox.com/socnet/OpenApps.html";
            mdIFrame.style.display = "none";
            var container = document.body;
            container.appendChild(mdIFrame);
        }
        else
        {
            window.location = "http://profile.fanbox.com/gmdirectory/controls/mhpwidgetsdirectoryload.aspx";
        }
    }
    var dragLock=0;


var hovTimer;

function HideFriendsPic()
{
    cancelHoverDiv();
    var pic = Get('divPopPic1');
	var picIframe = Get("ifFix2")
    if(!pic)
        return;
	if(picIframe)
		picIframe.style.display = 'none';
    DestroyDiv(pic);
	
	if(document.onmousemove)
	    document.onmousemove=MouseBuffer;
    MouseBuffer=null;
}

function hoverDiv(userNo, host)
{
    cancelHoverDiv();
        if(dragLock)
            return true;
            
        var hostName;    
        if(host.id)
            hostName = host.id;
        else
            hostName = host;
            
    hovTimer = window.setTimeout("openHoverDiv('"+userNo+"','"+hostName+"')",500);
}

function cancelHoverDiv(){
    if(hovTimer)
        window.clearTimeout(hovTimer);
}

function openHoverDiv(userNo, hostName)
{
    new Ajax.Updater('divPopPic1', 'http://profile.fanbox.com/Profile/hoverDiv.ashx?userNo='+userNo+'&hostName='+hostName,
                                            {
                                               method : "Get",
                                               onComplete : function(){     var pic = Get('divPopPic1');
                                                                            pic.style.position = 'absolute';	
                                                                            pic.style.width = 'auto';
                                                                            pic.style.height = 'auto';
                                                                            pic.style.visibility = 'visible';}
                                            });
        
    }
    
    function HideFriendsPic()
    {
            cancelHoverDiv();
            var pic = Get('divPopPic1');
		    var picIframe = Get("ifFix2")
            if(!pic)
                return;
            pic.style.left=0;	
		    pic.style.top= 0;
		    if(picIframe)
			    picIframe.style.display = 'none';
            DestroyDiv(pic);

            document.onmousemove=MouseBuffer;
            MouseBuffer=null;
    }
    
    function xlaALSrequest_mm(){
        var w = 640, h = 480;
        if (document.all || document.layers) {
            w = screen.availWidth;
            h = screen.availHeight;
        }
        var leftPos = (w-520)/2, topPos = (h-360)/2;
        xlaALSwindow=window.open("http://livechat.sms.ac/UserPreChat.aspx?ref=http%3a%2f%2fwww.sms.ac%2fcontactus%2fhelp.aspx&d=1&u=&bypass=","ALSRoom","toolbar=0,location=0,status=0,menubar=0,scrollbars=1,resizable=1,width=520,height=360,top=" + topPos + ",left=" + leftPos);
        if (xlaALSwindow != null) {
            xlaALSwindow.focus();
        }
    }
    
    function CheckMDSignIn(destinationURL)
    {
	    if(!(destinationURL))
	    {
		    destinationURL = window.location.href;
	    }
        if(window.top != window)
        {
            var mdIFrame = document.createElement("iframe");
            mdIFrame.src = "http://www.fanbox.com/socnet/SignIn.html?destinationURL=" + encodeURIComponent(destinationURL);
            mdIFrame.style.display = "none";
            var container = document.body;
            container.appendChild(mdIFrame);
        }
        else
            window.location.href = "http://profile.fanbox.com/login/login.aspx";
    }
    
function CheckMDLogout(link)
{
	if(window.top !== window)
	{
		link.target = "_top";
		try
		{
			window.top.LogOut();
		}
		catch(problem)
		{
			try
			{
				window.document.domain = "fanbox.com";
				window.top.LogOut();
			}
			catch(problem)
			{
				link.href = "http://www.fanbox.com/socnet/Logout.aspx";
				return true;
			}
		}
		link.href = "http://www.fanbox.com/socnet/Logout.aspx?HTTPStatusCode=204";
	}
	return true;
}



var PageTimer = {
	"_placeholderSessions" : {},
	"_sessionGroups" : [],
	"_instance" : Math.floor(Math.random() * 100),
	"_cookiesSent" : 0,
	"_restored" : false,
	"_implicitBackgroundTimerKind" : 0,
	"_publicationTimer" : 0,
	"_getSessionGroup" : PageTimer_GetSessionGroup,
	"_removeSessionGroupKind" : PageTimer_RemoveSessionGroupKind,
	"_removeSessionGroupByIndex" : PageTimer_RemoveSessionGroupByIndex,
	"_publishSession" : PageTimer_PublishSession,
	"_completeSession" : PageTimer_CompleteSession,
	"_cookieAllowed" : PageTimer_CookieAllowed,
	"_sendCookies" : PageTimer_SendCookies,

	/** Defines a placeholder session for an upcoming window with the specified statistic, recording the current time.  (kind) */
	"AddPlaceholderSession" : PageTimer_AddPlaceholderSession,
	/** Removes a placeholder session for an upcoming window with the specified statistic.  (kind) */
	"RemovePlaceholderSession" : PageTimer_RemovePlaceholderSession,
	/** Matches the specified window to the earliest placeholder session by the specified statistic, or sets the statistic for a session.  The previous statistic is published.  The current time is recorded for the server reply.  (ownerWindow, kind, label) */
	"ConnectToSession" : PageTimer_ConnectToSession,
	/** Defines a session for the specified window.  (ownerWindow, label) */
	"AddSession" : PageTimer_AddSession,
	/** Resets a session and publishes the previous statistic, if needed.  If this is applied to the current window, it is expected that the current page is being unloaded, and timing starts for an upcoming unspecified session that is started on the next page.  This is primarily intended for use in the profile window.  (ownerWindow) */
	"ResetSession" : PageTimer_ResetSession,
	/** Defines named progress counters.  This function can be safely called once per session.  To add additional counters to an ongoing session, use 'ExchangeProgressCounters'.  (ownerWindow, counterList) */
	"DefineProgressCounters" : PageTimer_DefineProgressCounters,
	/** Defines named progress counters for a given Activity Kind.  (ownerWindow, counterList, activityKind) */
	"DefineProgressCountersForActivityKind" : PageTimer_DefineProgressCountersForActivityKind,
	/** Marks a progress counter as fulfilled.  If all of the progress counters of that name are fulfilled, this has no effect.  When all progress counters are fulfilled, the statistic is published.  (ownerWindow, counter) */
	"FulfillProgressCounter" : PageTimer_FulfillProgressCounter,
	/** Cancels all instances of a progress counter.  When all progress counters are fulfilled, the statistic is published.  (ownerWindow, counter) */
	"CancelProgressCounter" : PageTimer_CancelProgressCounter,
	/** Simultaneously fulfills the specified original progress counter and defines the named progress counters.  If the original progress counter was not found, the new progress counters are not added.  (ownerWindow, originalCounter, newCounterList) */
	"ExchangeProgressCounters" : PageTimer_ExchangeProgressCounters,
	/** Creates a derivative session within the same window that runs concurrently with the entire window's session.  The derivative session receives the request time of the original session.  To control the request time, use a placeholder session on the current window instead using 'AddPlaceholderSession'.  (ownerWindow, kind) */
	"SplitSession" : PageTimer_SplitSession,
	/** Resets a session without publishing the previous statistic.  (ownerWindow) */
	"CancelSession" : PageTimer_CancelSession,
	/** Removes a session for the specified window.  (ownerWindow) */
	"RemoveSession" : PageTimer_RemoveSession,
	/** Declares the kind of statistic to assume when a background timer does not specify the statistic kind to record.  (kind) */
	"SetImplicitBackgroundTimerKind" : PageTimer_SetImplicitBackgroundTimerKind,
	/** Changes current activity Kind.  (ownerWindow, kind) */
	"ChangeCurrentSession" : PageTimer_ChangeCurrentSession
};

/** Defines a placeholder session for an upcoming window with the specified statistic, recording the current time. */
function PageTimer_AddPlaceholderSession(kind)
{
	var placeholderSession = {
		"_progress" : 0,
		"_published" : null,

		"Kind" : kind,
		"Window" : null,
		"Label" : null,
		"RequestTime" : new Date(),
		"ReplyTime" : null,
		"CompletionTime" : null,
		"ProgressCounters" : {},
		"LastProgressCounter" : null
		};

	/* Add the placeholder session to the queue. */
	var newEntry = {"Value" : placeholderSession, "Next" : null};
	var placeholderSessionQueue = this._placeholderSessions[kind];
	if(!!placeholderSessionQueue)
	{
		var endEntry = placeholderSessionQueue.Last;
		if(!!endEntry)
		{
			endEntry.Next = newEntry;
			placeholderSessionQueue.Last = newEntry;
		}
		else
		{
			placeholderSessionQueue.First = placeholderSessionQueue.Last = newEntry;
		}
	}
	else
	{
		this._placeholderSessions[kind] = {"First" : newEntry, "Last" : newEntry};
	}
	return true;
}

/** Removes a placeholder session for an upcoming window with the specified statistic. */
function PageTimer_RemovePlaceholderSession(kind)
{
	var placeholderSessionQueue = this._placeholderSessions[kind];
	if(!!placeholderSessionQueue)
	{
		if(!!placeholderSessionQueue.First)
		{
			if((placeholderSessionQueue.First = placeholderSessionQueue.First.Next) === null);
			{
				placeholderSessionQueue.Last = null;
			}
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}

/** Retrieves the session group corresponding to the specified window. */
function PageTimer_GetSessionGroup(ownerWindow)
{
	var sessionGroup = null;
	/* Search the sessions. */
	for(var sessionGroupIndex = 0;  sessionGroupIndex < this._sessionGroups.length;  sessionGroupIndex++)
	{
		sessionGroup = this._sessionGroups[sessionGroupIndex];
		/* Remove sessions that are closed, but are still recorded. */
		while(true)
		{
			try
			{
				if(sessionGroup.Window.closed)
				{
					this._removeSessionGroupByIndex(sessionGroupIndex);
				}
				else
				{
					break;
				}
			}
			catch(Problem)
			{
				sessionGroupIndex++;
			}
			if(sessionGroupIndex >= this._sessionGroups.length)
			{
				return null;
			}
			sessionGroup = this._sessionGroups[sessionGroupIndex];
		}
		try
		{
			if(sessionGroup.Window.document === ownerWindow.document)
			{
				break;
			}
		}
		catch(Problem)
		{
		}
		sessionGroup = null;
	}
	return sessionGroup;
}

/** Matches the specified window to the earliest placeholder session by the specified statistic, or sets the statistic for a session.  The previous statistic is published.  The current time is recorded for the server reply. */
function PageTimer_ConnectToSession(ownerWindow, kind, label)
{
	label = label || null;
	var sessionGroup;
	var sessionKindsToPreserve = {};

	if(!(this._restored))
	{
		this._restored = true;
		var currentCookie = window.document.cookie;

		/* Retrieve the last time a session was accepted.  If a URL containing request timing information is stored in history, ignore it if it is reused. */
		var recentTime;
		var searchIndex = currentCookie.indexOf("PageTimer_Recent=");
		if(searchIndex !== -1)
		{
			recentTime = new Date(parseInt(decodeURIComponent(currentCookie.substr(searchIndex + 17)), 10));
		}
		else
		{
			recentTime = new Date(0);
		}
		var requestTime;

		/* Applying the window.location.hash format of restoring an ongoing session in the top-level window using Internet Explorer with Flash movies on the page causes this portion of the URL to be appended to the title bar.  If this occurs, use window.location.search instead. */
		var locationHint = window.location.hash;
		searchIndex = locationHint.indexOf("PageTimer_Request=");
		if((searchIndex !== -1) && ((requestTime = new Date(parseInt(decodeURIComponent(locationHint.substr(searchIndex + 18)), 10))) >= recentTime))
		{
			this.AddSession(ownerWindow, label);
			sessionGroup = this._getSessionGroup(ownerWindow);
			sessionGroup.Sessions[0].RequestTime = requestTime;
		}
		else
		{
			locationHint = window.location.search;
			var searchIndex = locationHint.indexOf("PageTimer_Request=");
			if((searchIndex !== -1) && ((requestTime = new Date(parseInt(decodeURIComponent(locationHint.substr(searchIndex + 18)), 10))) >= recentTime))
			{
				this.AddSession(ownerWindow, label);
				sessionGroup = this._getSessionGroup(ownerWindow);
				sessionGroup.Sessions[0].RequestTime = requestTime;
			}
			else
			{
				searchIndex = currentCookie.indexOf("PageTimer=");
				if(searchIndex !== -1)
				{
					savedSessionText = currentCookie.substr(searchIndex);
					searchIndex = savedSessionText.indexOf(";")
					if(searchIndex !== -1)
					{
						savedSessionText = savedSessionText.substring(0, searchIndex);
					}
					this._cookiesSent = parseInt(savedSessionText.substr(savedSessionText.indexOf("_Sent:") + 6), 10);
					this.AddSession(ownerWindow, label);
					sessionGroup = this._getSessionGroup(ownerWindow);
					sessionGroup.Sessions[0].RequestTime = new Date(parseInt(savedSessionText.substr(savedSessionText.indexOf("_Request:") + 9), 10));
					window.document.cookie = "PageTimer=; expires=Thu, 31-Dec-1970 08:00:00 GMT; path=/";
				}
				else
				{
					sessionGroup = this._getSessionGroup(ownerWindow);
				}
			}
		}
		/* Restore a background timer. */
		var backgroundCookieHeading = "PageTimer_Background_" + kind + "=";
		searchIndex = currentCookie.indexOf(backgroundCookieHeading);
		if(searchIndex === -1)
		{
			backgroundCookieHeading = "PageTimer_Background=";
			searchIndex = currentCookie.indexOf(backgroundCookieHeading);
		}
		if(searchIndex !== -1)
		{
			window.document.cookie = backgroundCookieHeading + "; expires=Thu, 31-Dec-1970 08:00:00 GMT; path=/";

			var cookieText = currentCookie.substr(searchIndex + backgroundCookieHeading.length);
			searchIndex = cookieText.indexOf(";");
			if(searchIndex !== -1)
			{
				cookieText = cookieText.substring(0, searchIndex);
			}
			searchIndex = cookieText.indexOf("|");
			var backgroundKind;
			if(searchIndex === -1)
			{
				backgroundKind = this._implicitBackgroundTimerKind;
			}
			else
			{
				backgroundKind = parseInt(cookieText, 10);
			}
			this.SplitSession(ownerWindow, backgroundKind);
			sessionGroup = this._getSessionGroup(ownerWindow);
			sessionGroup.Sessions[backgroundKind].RequestTime = new Date(parseInt(cookieText.substr(searchIndex + 1), 10));
			var originalBaseKind = sessionGroup.BaseKind;
			var originalCurrentKind = sessionGroup.CurrentKind;
			sessionGroup.BaseKind = -1;
			this.ConnectToSession(ownerWindow, backgroundKind, label);
			this.DefineProgressCounters(ownerWindow, ["_published_" + kind]);
			sessionGroup.BaseKind = originalBaseKind;
			sessionGroup.CurrentKind = originalCurrentKind;
			sessionKindsToPreserve[backgroundKind] = true;
		}
		window.document.cookie = "PageTimer_Recent=" + ((new Date()).getTime()) + "; path=/";
	}
	else
	{
		sessionGroup = this._getSessionGroup(ownerWindow);
	}
	var session = null;
	if(!!sessionGroup)
	{
		if(sessionGroup.BaseKind === 0)
		{
			var previousSession = sessionGroup.Sessions[kind];
			if(!!previousSession)
			{
				if(previousSession._published === false)
				{
					this._completeSession(previousSession, sessionGroup);
				}
				sessionGroup.Sessions[kind] = null;
			}
			session = sessionGroup.Sessions[0];
			sessionGroup.Sessions[kind] = session;
			sessionGroup.BaseKind = kind;
			this._removeSessionGroupKind(sessionGroup, 0);
			sessionGroup.Sessions[0] = null;
			sessionGroup.CurrentKind = kind;
			sessionGroup.Kinds.push(kind);
		}
		else
		{
			session = sessionGroup.Sessions[kind];
		}
	}
	if(!(session))
	{
		/* Search the placeholder sessions. */
		var placeholderSessionQueue = this._placeholderSessions[kind];
		if(!!placeholderSessionQueue)
		{
			var sessionEntry = placeholderSessionQueue.First;
			if(!!sessionEntry)
			{
				/* Upgrade the placeholder session to a standard session. */
				if((placeholderSessionQueue.First = sessionEntry.Next) === null)
				{
					placeholderSessionQueue.Last = null;
				}
				session = sessionEntry.Value;
				session.Window = ownerWindow;

				if(!(sessionGroup))
				{
					sessionGroup = {
						"Window" : ownerWindow,
						"BaseKind" : kind,
						"CurrentKind" : kind,
						"Kinds" : [kind],
						"Sessions" : {}
						};
					sessionGroup.Sessions[kind] = session;
					this._sessionGroups.push(sessionGroup);
				}
				else
				{
					if(!(sessionGroup.Sessions[kind]))
					{
						sessionGroup.Kinds.push(kind);
					}
					sessionGroup.Sessions[kind] = session;
					sessionGroup.CurrentKind = kind;
				}
			}
		}
	}

	/* If there are no matches, create a new session. */
	if(!(session))
	{
		session = {
			"_progress" : 0,
			"_published" : false,

			"Kind" : kind,
			"Window" : ownerWindow,
			"Label" : label,
			"RequestTime" : null,
			"ReplyTime" : new Date(),
			"CompletionTime" : null,
			"ProgressCounters" : {},
			"LastProgressCounter" : null
			};

		if(!(sessionGroup))
		{
			sessionGroup = {
				"Window" : ownerWindow,
				"BaseKind" : kind,
				"CurrentKind" : kind,
				"Kinds" : [kind],
				"Sessions" : {}
				};
			sessionGroup.Sessions[kind] = session;
			this._sessionGroups.push(sessionGroup);
		}
		else
		{
			if(!(sessionGroup.Sessions[kind]))
			{
				sessionGroup.Kinds.push(kind);
			}
			sessionGroup.Sessions[kind] = session;
			sessionGroup.CurrentKind = kind;
		}
	}
	else
	{
		/* Reset the session with an unspecified request time. */
		if(session._published === false)
		{
			this._completeSession(session, sessionGroup);
		}
		if(session._published !== null)
		{
			session.RequestTime = null;
		}
		session._published = false;
		session.Kind = kind;
		session.Label = label;
		session.ReplyTime = new Date();
		session.CompletionTime = null;
		session.ProgressCounters = {};
		session.LastProgressCounter = null;
		session._progress = 0;
	}

	if(kind === sessionGroup.BaseKind)
	{
		sessionKindsToPreserve[kind] = true;
		var newKinds = [];
		for(var kindIndex = 0;  kindIndex < sessionGroup.Kinds.length;  kindIndex++)
		{
			var kindCursor = sessionGroup.Kinds[kindIndex];
			if(sessionKindsToPreserve[kindCursor] !== true)
			{
				var sessionCursor = sessionGroup.Sessions[kindCursor];
				if(sessionCursor._published === false)
				{
					this._completeSession(sessionCursor, sessionGroup);
				}
				sessionGroup.Sessions[kindCursor] = null;
			}
			else
			{
				newKinds.push(kindCursor);
			}
		}
		sessionGroup.Kinds = newKinds;
		sessionGroup.CurrentKind = sessionGroup.BaseKind;
	}
}

/** Defines a session for the specified window. */
function PageTimer_AddSession(ownerWindow, label)
{
	label = label || null;

	var sessionGroup = this._getSessionGroup(ownerWindow);
	if(!(sessionGroup))
	{
		var session = {
			"_progress" : 0,
			"_published" : null,

			"Kind" : null,
			"Window" : ownerWindow,
			"Label" : label,
			"RequestTime" : new Date(),
			"ReplyTime" : null,
			"CompletionTime" : null,
			"ProgressCounters" : {},
			"LastProgressCounter" : null
			};

		sessionGroup = {
			"Window" : ownerWindow,
			"BaseKind" : 0,
			"CurrentKind" : 0,
			"Kinds" : [0],
			"Sessions" : {}
			};
		sessionGroup.Sessions[0] = session;

		this._sessionGroups.push(sessionGroup);
	}
}

/** Resets a session and publishes the previous statistic, if needed. */
function PageTimer_ResetSession(ownerWindow)
{
	var currentTime = new Date();
	var sessionGroup = this._getSessionGroup(ownerWindow);
	if(!!sessionGroup)
	{
		for(var kindIndex = sessionGroup.Kinds.length - 1;  kindIndex >= 0;  kindIndex--)
		{
			var kind = sessionGroup.Kinds[kindIndex];
			var session = sessionGroup.Sessions[kind];
			if(!!session)
			{
				/* Reset the session. */
				if(session._published === false)
				{
					this._completeSession(session, sessionGroup);
				}
			}
		}
		var session = sessionGroup.Sessions[sessionGroup.BaseKind];
		if(!!session)
		{
			var originalKind = session.Kind;
			session._published = null;
			session.Kind = 0;
			session.Label = null;
			session.RequestTime = currentTime;
			session.ReplyTime = null;
			session.CompletionTime = null;
			session.ProgressCounters = {};
			session.LastProgressCounter = null;
			session._progress = 0;
			this._removeSessionGroupKind(sessionGroup, originalKind);
			sessionGroup.Sessions[0] = session;
			sessionGroup.BaseKind = 0;
			sessionGroup.Sessions[originalKind] = null;
			sessionGroup.Kinds.push(0);
		}
	}
	try
	{
		if(ownerWindow.document === window.document)
		{
			if(this._cookieAllowed())
			{
				window.document.cookie = "PageTimer=_Sent:" + this._cookiesSent + "_Request:" + currentTime.getTime() + "; path=/";
			}
		}
	}
	catch(Problem)
	{
	}
}

/** Defines named progress counters. */
function PageTimer_DefineProgressCounters(ownerWindow, counterList)
{
	var sessionGroup = this._getSessionGroup(ownerWindow);
	if(!!sessionGroup)
	{
		var session = sessionGroup.Sessions[sessionGroup.CurrentKind];
		if(!!session)
		{
			for(var counterIndex = 0;  counterIndex < counterList.length;  counterIndex++)
			{
				var counter = counterList[counterIndex];
				if(!!session.ProgressCounters[counter])
				{
					session.ProgressCounters[counter]++;
				}
				else
				{
					session.ProgressCounters[counter] = 1;
				}
				session._progress--;
			}
		}
	}
}

/** Defines named progress counters for a specified activity kind. */
function PageTimer_DefineProgressCountersForActivityKind(ownerWindow, counterList, activityKind)
{
	var sessionGroup = this._getSessionGroup(ownerWindow);
	if(!!sessionGroup)
	{
		var session = sessionGroup.Sessions[activityKind];
		if(!!session)
		{
			for(var counterIndex = 0;  counterIndex < counterList.length;  counterIndex++)
			{
				var counter = counterList[counterIndex];
				if(!!session.ProgressCounters[counter])
				{
					session.ProgressCounters[counter]++;
				}
				else
				{
					session.ProgressCounters[counter] = 1;
				}
				session._progress--;
			}
		}
	}
}

/** Marks a progress counter as fulfilled.  If all of the progress counters of that name are fulfilled, this has no effect.  When all progress counters are fulfilled, the statistic is published. */
function PageTimer_FulfillProgressCounter(ownerWindow, counter)
{
	var sessionGroup = this._getSessionGroup(ownerWindow);
	var setAnyKind = false;
	if(!!sessionGroup)
	{
		var session = sessionGroup.Sessions[sessionGroup.CurrentKind];
		if(!!session)
		{
			if(!!session.ProgressCounters[counter])
			{
				session.ProgressCounters[counter]--;
				session._progress++;
				session.LastProgressCounter = counter;
				setAnyKind = true;
				if(session._progress === 0)
				{
					session.CompletionTime = new Date();
					if(session._published === false)
					{
						this._completeSession(session, sessionGroup);
					}
				}
			}
		}

		for(var kindIndex = sessionGroup.Kinds.length - 1;  kindIndex >= 0;  kindIndex--)
		{
			var kind = sessionGroup.Kinds[kindIndex];
			if (kind != sessionGroup.CurrentKind)
			{
			    var session = sessionGroup.Sessions[kind];
			    if(!!session)
			    {
				    if(!!session.ProgressCounters[counter])
				    {
					    session.ProgressCounters[counter]--;
					    session._progress++;
					    session.LastProgressCounter = counter;
					    if(session._progress === 0)
					    {
						    session.CompletionTime = new Date();
						    if(session._published === false)
						    {
							    this._completeSession(session, sessionGroup);
						    }
					    }
					    if (!setAnyKind)
					    {
					        sessionGroup.CurrentKind = kind;
					    }
				        setAnyKind = true;
				    }
			    }
			}
		}
	}
	return setAnyKind;
}

/** Cancels all instances of a progress counter.  When all progress counters are fulfilled, the statistic is published. */
function PageTimer_CancelProgressCounter(ownerWindow, counter)
{
	var sessionGroup = this._getSessionGroup(ownerWindow);
	if(!!sessionGroup)
	{
		var session = sessionGroup.Sessions[sessionGroup.CurrentKind];
		if(!!session)
		{
			if(!!session.ProgressCounters[counter])
			{
				var quantity = session.ProgressCounters[counter];
				session.ProgressCounters[counter] = 0;
				session._progress += quantity;
				session.LastProgressCounter = counter;
				if(session._progress === 0)
				{
					session.CompletionTime = new Date();
					if(session._published === false)
					{
						this._completeSession(session, sessionGroup);
					}
				}
				return true;
			}
		}

		for(var kindIndex = sessionGroup.Kinds.length - 1;  kindIndex >= 0;  kindIndex--)
		{
			var kind = sessionGroup.Kinds[kindIndex];
			var session = sessionGroup.Sessions[kind];
			if(!!session)
			{
				if(!!session.ProgressCounters[counter])
				{
					var quantity = session.ProgressCounters[counter];
					session.ProgressCounters[counter] = 0;
					session._progress += quantity;
					session.LastProgressCounter = counter;
					if(session._progress === 0)
					{
						session.CompletionTime = new Date();
						if(session._published === false)
						{
							this._completeSession(session, sessionGroup);
						}
					}
					sessionGroup.CurrentKind = kind;
					return true;
				}
			}
		}
	}
	return false;
}

/** Simultaneously fulfills the specified original progress counter and defines the named progress counters. */
function PageTimer_ExchangeProgressCounters(ownerWindow, originalCounter, newCounterList)
{
	if(newCounterList.length !== 0)
	{
		var sessionGroup = this._getSessionGroup(ownerWindow);
		if(!!sessionGroup)
		{
			var sessionFound = false;
			var session = sessionGroup.Sessions[sessionGroup.CurrentKind];
			if(!!session)
			{
				if(!!session.ProgressCounters[originalCounter])
				{
					session.ProgressCounters[originalCounter]--;
					session._progress++;
					session.LastProgressCounter = originalCounter;
					sessionFound = true;
				}
			}
			if(!(sessionFound))
			{
				for(var kindIndex = sessionGroup.Kinds.length - 1;  kindIndex >= 0;  kindIndex--)
				{
					var kind = sessionGroup.Kinds[kindIndex];
					var session = sessionGroup.Sessions[kind];
					if(!!session)
					{
						if(!!session.ProgressCounters[originalCounter])
						{
							session.ProgressCounters[originalCounter]--;
							session._progress++;
							session.LastProgressCounter = originalCounter;
							sessionFound = true;
							sessionGroup.CurrentKind = kind;
							break;
						}
					}
				}
			}
			if(sessionFound)
			{
				return this.DefineProgressCounters(ownerWindow, newCounterList);
			}
		}
		return false;
	}
	else
	{
		return this.FulfillProgressCounter(ownerWindow, originalCounter);
	}
}

/** Creates a derivative session within the same window that runs concurrently with the entire window's session.  The derivative session receives the request time of the original session.  To control the request time, use a placeholder session on the current window instead. */
function PageTimer_SplitSession(ownerWindow, kind)
{
	var sessionGroup = this._getSessionGroup(ownerWindow);
	if(!!sessionGroup)
	{
		if(!(sessionGroup.Sessions[kind]))
		{
			var requestTime;
			var baseSession;
			if((sessionGroup.BaseKind !== 0) && !!(baseSession = sessionGroup.Sessions[sessionGroup.BaseKind]))
			{
				requestTime = baseSession.RequestTime;
				if(requestTime === null)
				{
					requestTime = baseSession.ReplyTime;
				}
			}
			else
			{
				requestTime = new Date();
			}
			sessionGroup.Kinds.push(kind);
			sessionGroup.Sessions[kind] = {
				"_progress" : 0,
				"_published" : null,

				"Kind" : null,
				"Window" : ownerWindow,
				"Label" : null,
				"RequestTime" : requestTime,
				"ReplyTime" : null,
				"CompletionTime" : null,
				"ProgressCounters" : {},
				"LastProgressCounter" : null
				};
			sessionGroup.CurrentKind = kind;
		}
	}
}

/** Resets a session without publishing the previous statistic. */
function PageTimer_CancelSession(ownerWindow)
{
	var sessionGroup = this._getSessionGroup(ownerWindow);
	if(!!sessionGroup)
	{
		var session = sessionGroup.Sessions[sessionGroup.CurrentKind];
		if(!!session)
		{
			session._published = null;
			session.Kind = null;
			session.Label = null;
			session.RequestTime = new Date();
			session.ReplyTime = null;
			session.CompletionTime = null;
			session.ProgressCounters = {};
			session.LastProgressCounter = null;
			session._progress = 0;
		}
	}
}

/** Removes a session for the specified window. */
function PageTimer_RemoveSession(ownerWindow)
{
	var sessionGroup = null;
	/* Search the sessions. */
	for(var sessionGroupIndex = 0;  sessionGroupIndex < this._sessionGroups.length;  sessionGroupIndex++)
	{
		sessionGroup = this._sessionGroups[sessionGroupIndex];
		/* Remove sessions that are closed, but are still recorded. */
		while(true)
		{
			try
			{
				if(sessionGroup.Window.closed)
				{
					this._removeSessionGroupByIndex(sessionGroupIndex);
				}
				else
				{
					break;
				}
			}
			catch(Problem)
			{
				sessionGroupIndex++;
			}
			if(sessionGroupIndex >= this._sessionGroups.length)
			{
				return null;
			}
			sessionGroup = this._sessionGroups[sessionGroupIndex];
		}
		if(sessionGroup.Window.document === ownerWindow.document)
		{
			this._removeSessionGroupByIndex(sessionGroupIndex);
			sessionGroup = null;
			return true;
		}
		sessionGroup = null;
	}
	return false;
}

/** Removes a kind from the session group. */
function PageTimer_RemoveSessionGroupKind(sessionGroup, kind)
{
	var kinds = sessionGroup.Kinds;
	for(var kindIndex = 0;  kindIndex < kinds.length;  kindIndex++)
	{
		if(kinds[kindIndex] === kind)
		{
			kinds[kindIndex] = kinds[kinds.length - 1];
			kinds.pop();
			if(sessionGroup.CurrentKind === kind)
			{
				sessionGroup.CurrentKind = sessionGroup.BaseKind;
			}
			return true;
		}
	}
	return false;
}

/** Removes a session at the specified index, replacing it with a session with a higher index, if available. */
function PageTimer_RemoveSessionGroupByIndex(sessionGroupIndex)
{
	var sessionGroup = this._sessionGroups[sessionGroupIndex];
	for(var kindIndex = sessionGroup.Kinds.length - 1;  kindIndex >= 0;  kindIndex--)
	{
		var session = sessionGroup.Sessions[sessionGroup.Kinds[kindIndex]];
		if(session._published === false)
		{
			this._completeSession(session, sessionGroup);
		}
		session = null;
	}
	this._sessionGroups[sessionGroupIndex] = this._sessionGroups[this._sessionGroups.length - 1];
	this._sessionGroups.pop();
	return true;
}

/** Declares the kind of statistic to assume when a background timer does not specify the statistic kind to record. */
function PageTimer_SetImplicitBackgroundTimerKind(kind)
{
	this._implicitBackgroundTimerKind = kind;
}

/** Sends the statistic and notifies background timers transparently. */
function PageTimer_CompleteSession(session, sessionGroup)
{
	this._publishSession(session);
	session._published = true;
	/* Notify one background timer. */
	this.FulfillProgressCounter(session.Window, "_published_" + session.Kind);
}

/** Sends the statistic by adding a cookie. */
function PageTimer_PublishSession(session)
{
	if(!(this._cookieAllowed()))
	{
		return;
	}
	var originTiming = 0;
	if(!!session.RequestTime)
	{
		originTiming = session.RequestTime.getTime();
	}
	else if(!!session.ReplyTime)
	{
		originTiming = session.ReplyTime.getTime();
	}
	if(originTiming !== 0)
	{
		var cookieValue = "kind=" + encodeURIComponent(session.Kind);
		if(!!session.RequestTime)
		{
			cookieValue += "&request=" + encodeURIComponent(session.RequestTime.getTime() - originTiming);
		}
		if(!!session.ReplyTime)
		{
			cookieValue += "&reply=" + encodeURIComponent(session.ReplyTime.getTime() - originTiming);
		}
		if(!!session.CompletionTime)
		{
			cookieValue += "&completion=" + encodeURIComponent(session.CompletionTime.getTime() - originTiming);
		}
		if(!!session.LastProgressCounter)
		{
			cookieValue += "&lastCounter=" + encodeURIComponent(session.LastProgressCounter);
		}
		if(!!session.Label)
		{
			cookieValue += "&label=" + encodeURIComponent(session.Label);
		}
		switch(window.navigator.onLine)
		{
			case true:
				cookieValue += "&online=1";
				break;
			case false:
				cookieValue += "&online=0";
				break;
		}
		var clientCapabilities = window.document.getElementById("ClientCaps");
		if(clientCapabilities === null)
		{
			clientCapabilities = window.document.createElement("LINK");
			clientCapabilities.id = "ClientCaps";
			window.document.getElementsByTagName("HEAD")[0].appendChild(clientCapabilities);
			try
			{
				clientCapabilities.style.behavior = "url(\"#default#clientCaps\")";
			}
			catch(Problem)
			{
			}
		}
		try
		{
			var connectionType = clientCapabilities.connectionType;
			if(!!connectionType)
			{
				cookieValue += "&connection=" + encodeURIComponent(connectionType);
			}
		}
		catch(Problem)
		{
		}
	}
	var expires = new Date();
	expires.setMinutes(expires.getMinutes() + 30);
	window.document.cookie = "loadingTime" + this._instance + "_" + (this._cookiesSent++) + "=" + encodeURIComponent(cookieValue) + "; path=/; expires=" + expires.toUTCString();
	if(this._publicationTimer !== 0)
	{
		window.clearTimeout(this._publicationTimer);
	}
	this._publicationTimer = window.setTimeout(PageTimerCallback_SendCookies, 5000);
}

/** Issues a request that sends statistic cookies.  Use this as a callback function when the calling context is not preserved. */
function PageTimerCallback_SendCookies()
{
	PageTimer._sendCookies();
}

/** Issues a request that sends statistic cookies. */
function PageTimer_SendCookies()
{
	if(window.document.cookie.indexOf("loadingTime") !== -1)
	{
		if(this._publicationTimer !== 0)
		{
			window.clearTimeout(this._publicationTimer);
			this._publicationTimer = 0;
		}
		var beacon = window.document.createElement("SCRIPT");
		beacon.type = "text/javascript";
		beacon.defer = true;
		beacon.src = "Remote.aspx?HTTPStatus=204";
		window.document.getElementsByTagName("HEAD")[0].appendChild(beacon);
	}
}

/** Decides if it is safe to add a cookie. */
function PageTimer_CookieAllowed()
{
	var currentCookies = window.document.cookie;
	/* Do not record statistics if an opt-out cookie exists. */
	if(currentCookies.indexOf("ID=OPT_OUT") !== -1)
	{
		return false;
	}
	/* Verify that adding a statistic cookie will not eliminate an older cookie. */
	var availableCookieCount = 14;
	for(var cookieSeparatorIndex = 0;  cookieSeparatorIndex !== -1;  cookieSeparatorIndex = currentCookies.indexOf(";", cookieSeparatorIndex + 1))
	{
		availableCookieCount--;
	}
	return (availableCookieCount > 0);
}

function PageTimer_ChangeCurrentSession(ownerWindow, kind)
{
	var sessionGroup = this._getSessionGroup(ownerWindow);
	if(!!sessionGroup)
	{
		if(!!(sessionGroup.Sessions[kind]))
		{
			sessionGroup.CurrentKind = kind;
		}
	}
}



var ie6 = false;
var ie7 = false;
var ff = false;
if(window.navigator.appName.match('Netscape'))
{
	ff = true;
}
else
{
	window.navigator.appVersion.match('MSIE.*?([0-9])');
	if(RegExp.$1 <= 6)
	{
		ie6 = true;
	}
	else
	{
		ie7 = true;
	}
}

function resizeHoverFriendPicWON(img, maxSize, hostNm){
    if (ie6) 
        return resizeHoverFriendPicWON_ie6(img, maxSize, hostNm);
    else 
        if (ff) 
            return resizeHoverFriendPicWON_ns(img, maxSize, hostNm);
        else 
            return resizeHoverFriendPicWON_ie7(img, maxSize, hostNm);
}

function HideFriendsPicWON(){
    cancelHoverDivWON();
    var pic = Get('divPopPic1');
    var picIframe = Get("ifFix2")
    if (!pic) 
        return;
    if (ff || ie6) {
        pic.style.left = 0;
        pic.style.top = 0;
    }
    if (picIframe) 
        picIframe.style.display = 'none';
    DestroyDiv(pic);
    try{
 		if(document.onmousemove)
	    	document.onmousemove=MouseBuffer;
		}
	catch(err){}
    MouseBuffer = null;
}

function hoverDivWON(userNo, host, backIfrm){
    if (backIfrm == null) {
        backIfrm = "false";
    }
    cancelHoverDiv();
    if (dragLock) 
        return true;
    
    var hostName;
    if (host.id) 
        hostName = host.id;
    else 
        hostName = host;
    
    hovTimer = window.setTimeout("openHoverDivWON('" + userNo + "','" + hostName + "', '" + backIfrm + "')", 500);
}

function cancelHoverDivWON(){
    if (hovTimer) 
        window.clearTimeout(hovTimer);
}

function openHoverDivWON(userNo, hostName, backIfrm){
	if (backIfrm == null) {
		backIfrm = "false";
	}
	new Ajax.Updater('divPopPic1', 'http://profile.fanbox.com/Profile/hoverDivWON.ashx?userNo=' + userNo + '&hostName=' + hostName + '&ifrm=' + backIfrm, {
		method: "Get",
		onComplete: function(){
			var pic = Get('divPopPic1');
			pic.style.position = 'absolute';
			pic.style.width = 'auto';
			pic.style.height = 'auto';
			pic.style.visibility = 'visible';
		}
	}
	);
}
function hideResizeHover(){
	Element.hide($('divPopPic1'));
	if (ff) {
		document.body.removeEventListener('mousedown', hideResizeHover, false);
		document.removeEventListener('keydown', hideResizeHover, false);
		window.removeEventListener('scroll', hideResizeHover, false);
	}
	else {
		document.body.detachEvent('onmousedown', hideResizeHover);
		document.detachEvent('onkeydown', hideKPH);
		document.body.detachEvent('onmousewheel', hideResizeHover);
	}
}

function hideKPH(e){
	var knum;
	
	if (window.event) 
		knum = event.keyCode;
	else 
		knum = e.which;
	
	if ((knum == 37) || (knum == 38) || (knum == 39) || (knum == 40)) {
		Element.hide($('divPopPic1'));
		if (ff) {
			document.body.removeEventListener('mousedown', hideResizeHover, false);
			document.removeEventListener('keydown', hideKPH, false);
			document.body.removeEventListener('mousewheel', hideResizeHover, false);
		}
		else {
			document.body.detachEvent('onmousedown', hideResizeHover);
			document.detachEvent('onkeydown', hideKPH);
			document.body.detachEvent('onmousewheel', hideResizeHover);
		}
		
	}
}


function resizeHoverFriendPicWON_ns(img, maxSize, hostNm){
	//make sure any changes here are reflected in Pod_Js\HeaderFunc.js ie6/ie7/ff versions and jslib\[0123]\Init.js
	if (img) {
		var tmpImg = new Image();
		tmpImg.src = img.src;
		img.style.visibility = "visible";
		tmpImg.width > tmpImg.height ? img.width = maxSize : img.height = maxSize;
		img.className = 'Border_black';
		var pic = $('divPopPic1');
		var host = $(hostNm);
		pic.style.position = "fixed";
		var picIframe = $("ifFix2")
		if (pic) {
			document.body.addEventListener('mousedown', hideResizeHover, false);
			document.addEventListener('keydown', hideKPH, false);
			window.addEventListener('scroll', hideResizeHover, false);
			pic.style.width = "138px";
			var oldWidth = tmpImg.width;
			var oldHeight = tmpImg.height;
			var newWidth = img.width;
			var newHeight = img.height;
			var pos = Position.cumulativeOffset(host);
			var totalScrollTop = 0;
			var totalScrollLeft = 0;
			for (var cursor = host; cursor != null; cursor = cursor.parentNode) {
				totalScrollTop += cursor.scrollTop || 0;
				totalScrollLeft += cursor.scrollLeft || 0;
			}
			pic.style.display = "none";
			pic.style.left = "-500px";
			pic.style.top = "-500px";
			pic.style.display = "block";
			var picsLeft = pos[0] - totalScrollLeft + "px";
			if (pos[1] - totalScrollTop < 230) {
				var picsTop = pos[1] + host.clientHeight - totalScrollTop + 7 + "px";
			}
			else {
				var picsTop = pos[1] - pic.clientHeight - totalScrollTop + 4 + "px";
			}
			pic.style.display = "none";
			pic.style.left = picsLeft;
			pic.style.top = picsTop;
			pic.style.display = "block";
			if (picIframe) {
				if (pic.offsetHeight) {
					picIframe.style.height = (parseInt(pic.offsetHeight));
					picIframe.style.width = (parseInt(pic.offsetWidth));
				}
				else 
					if (pic.style.pixelHeight) {
						picIframe.style.height = (parseInt(pic.style.pixelHeight));
						picIframe.style.width = (parseInt(pic.style.pixelWidth));
					}
				picIframe.style.left = pic.style.left;
				pic.style.top = (parseInt(pic.style.top) + 5);
				picIframe.style.top = pic.style.top
				picIframe.style.display = pic.style.display;
			}
		}
	}
}

function resizeHoverFriendPicWON_ie7(img, maxSize, hostNm){
	//make sure any changes here are reflected in Pod_Js\HeaderFunc.js ie6/ie7/ff versions and jslib\[0123]\Init.js
	if (img) {
		var tmpImg = new Image();
		tmpImg.src = img.src;
		img.style.visibility = "visible";
		tmpImg.width > tmpImg.height ? img.width = maxSize : img.height = maxSize;
		img.className = 'Border_black';
		var pic = Get('divPopPic1');
		pic.style.position = "fixed";
		var host = Get(hostNm);
		var picIframe = Get("ifFix2");
		
		document.body.attachEvent('onmousedown', hideResizeHover);
		document.attachEvent('onkeydown', hideKPH);
		document.body.attachEvent('onmousewheel', hideResizeHover);
		
		if (pic) {
			pic.style.display = "block";
			pic.style.width = "138px";
			var oldWidth = tmpImg.width;
			var oldHeight = tmpImg.height;
			var newWidth = img.width;
			var newHeight = img.height;
			var pos = Position.cumulativeOffset(host);
			
			
			var totalScrollTop = 0;
			var totalScrollLeft = 0;
			
			for (var cursor = host; cursor != null; cursor = cursor.parentNode) {
				totalScrollTop += cursor.scrollTop || 0;
				totalScrollLeft += cursor.scrollLeft || 0;
			}
			pic.style.left = pos[0] - totalScrollLeft + "px";
			var spaceAbove = pos[1] - totalScrollTop;
			if (spaceAbove < 230) {
				pic.style.top = pos[1] + host.clientHeight - totalScrollTop + 7 + "px";
			}
			else {
				pic.style.top = pos[1] - pic.clientHeight - totalScrollTop + 4 + "px";
			}
			
			if (picIframe) {
				if (pic.offsetHeight) {
					picIframe.style.height = (parseInt(pic.offsetHeight));
					picIframe.style.width = (parseInt(pic.offsetWidth));
				}
				else 
					if (pic.style.pixelHeight) {
						picIframe.style.height = (parseInt(pic.style.pixelHeight));
						picIframe.style.width = (parseInt(pic.style.pixelWidth));
					}
				picIframe.style.left = pic.style.left;
				pic.style.top = (parseInt(pic.style.top) + 5);
				picIframe.style.top = pic.style.top
				picIframe.style.display = pic.style.display;
			}
		}
	}
}

function resizeHoverFriendPicWON_ie6(img, maxSize, hostNm){
	//make sure any changes here are reflected in Pod_Js\HeaderFunc.js ie6/ie7/ff versions and jslib\[0123]\Init.js
	if (img) {
		var tmpImg = new Image();
		tmpImg.src = img.src;
		img.style.visibility = "visible";
		tmpImg.width > tmpImg.height ? img.width = maxSize : img.height = maxSize;
		img.className = 'Border_black';
		var pic = Get('divPopPic1');
		var host = Get(hostNm);
		var picIframe = Get("ifFix2")
		if (pic) {
			pic.style.display = "block";
			pic.style.width = "138px";
			
			document.body.attachEvent('onmousedown', hideResizeHover);
			document.attachEvent('onkeydown', hideKPH);
			document.body.attachEvent('onmousewheel', hideResizeHover);
			
			var oldWidth = tmpImg.width;
			var oldHeight = tmpImg.height;
			var newWidth = img.width;
			var newHeight = img.height;
			var pos = Position.cumulativeOffset(host);
			
			pic.style.left = pos[0] + "px";
			if (pos[1] - document.documentElement.scrollTop < 230) {
				pic.style.top = pos[1] + host.clientHeight + 7 + "px";
			}
			else {
				pic.style.top = pos[1] - pic.clientHeight + 4 + "px";
			}
			
			if (picIframe) {
				if (pic.offsetHeight) {
					picIframe.style.height = (parseInt(pic.offsetHeight));
					picIframe.style.width = (parseInt(pic.offsetWidth));
				}
				else 
					if (pic.style.pixelHeight) {
						picIframe.style.height = (parseInt(pic.style.pixelHeight));
						picIframe.style.width = (parseInt(pic.style.pixelWidth));
					}
				picIframe.style.left = pic.style.left;
				pic.style.top = (parseInt(pic.style.top) + 5);
				picIframe.style.top = pic.style.top
				picIframe.style.display = pic.style.display;
			}
		}
	}
}

/* NewCustomProfile personalizes portions of the header at runtime. */
function PersonalizeHeaderHTML(profUser){
	new Ajax.Request("http://profile.fanbox.com/Profile/Remote_Header.ashx?u=" + encodeURIComponent(profUser) + "&mode=header" + ( /* Trial widget display status. */(window.location.search.match(/\b(sp=\d+)\b/) != null) ? ("&" + RegExp.$1) : ("")), {
		onSuccess: function(Reply){
			var Pairs = Reply.responseText.split("&");
			var Placeholders = ["ProfileReturnLinkPlaceholder", "FriendCountPlaceholder", "HeaderHotNowInterests", "FriendshipStatusPlaceholder", "PresencePlaceholder", "MoneyPlaceholder", "BroadcastSummaryPlaceholder", "realTrialPodDiv", "PhotosPlaceHolder", "OnlineStatusPlaceholder", "ShufflePlaceHolder", "WhosOnlinePhotoPlaceHolder"];
			/* For more information, see encodePublicPersonalizedParameters() and encodePrivatePersonalizedParameters() in \WebProfile\Apps\profile.fanbox.com\Profile\Remote_Header.ashx.cs . */
			var Parameters = ["p", "f", "i", "s", "a", "m", "b", "n", "ph", "o", "sh", "op"];
			var ParameterValues = {};
			
			for (var i = 0; i < Pairs.length; i++) {
				var Binding = Pairs[i].split("=");
				if (Binding.length == 2) {
					ParameterValues[Binding[0]] = decodeURIComponent(Binding[1]);
				}
			}
			for (var i = 0; i < Placeholders.length; i++) {
				var Cursor = $(Placeholders[i]);
				if (Cursor != null) {
					var CursorContent = ParameterValues[Parameters[i]];
					if (CursorContent != undefined) {
						Cursor.innerHTML = CursorContent;
					}
				}
			}
			TidyProfileStatus();
			TidyHeaderInterestsPanel();
			var ScriptText = ParameterValues["x"];
			if ((ScriptText !== undefined) && (ScriptText.length != 0)) {
				var ScriptElement = window.document.createElement("SCRIPT");
				ScriptElement.type = "text/javascript";
				ScriptElement.text = ScriptText;
				window.document.body.appendChild(ScriptElement);
			}
		}
	});
}

function TidyProfileStatus()
{
	var profileViewer = window.document.getElementById("ProfileNameViewer");
	if(profileViewer !== null)
	{
		profileViewer.style.position='absolute';
		profileViewer.style.left='-500px';
		profileViewer.style.top='-500px';
		profileViewer.style.display='inline-block';

		var onlineWidth;
		var onlinePlaceholder = window.document.getElementById("OnlineStatusPlaceholder");
		if(onlinePlaceholder.firstChild !== null)
		{
			onlinePlaceholder.style.display = "inline-block";
			/* 10 pixels from the margin between the button and status. */
			onlineWidth = onlinePlaceholder.offsetWidth + 10;
		}
		else
		{
			onlineWidth = 0;
		}
		var divider = window.document.getElementById("ProfileHeaderDivider");
		/* 10 pixels from the margin between the divider and name; 1 pixel unaccounted for. */
		var profileViewerWidth = window.document.getElementById("ProfileHeaderContainer").offsetWidth - (10 + divider.offsetLeft - window.document.getElementById("FanCountLink").offsetLeft) - onlineWidth - 1;
		profileViewer.style.width = profileViewerWidth.toString() + "px";
		var profileStatusOverview = window.document.getElementById("ProfileStatusOverview");
		var profileStatus = window.document.getElementById("ProfileStatus");

		if(profileStatusOverview.style.display !== "none")
		{
			var caption = profileStatus.firstChild;
			for(var ellipses = profileStatus.lastChild;  ellipses !== caption;  ellipses = profileStatus.lastChild)
			{
				profileStatus.removeChild(ellipses);
			}
			var rawStatus = caption.data;
			profileStatus.setAttribute("rawStatus", rawStatus);

			var profileName = window.document.getElementById("ProfileName");
			var profileWrapper = window.document.getElementById("ProfileNameWrapper");

			if(TruncateDisplayTextHeightPrepared(profileWrapper, 39, caption, PrepareProfileStatusSuffix, FinalizeProfileStatusSuffix, rawStatus) !== null)
			{
				TruncateDisplayTextWidthPrepared(profileWrapper, profileViewerWidth+2, caption, PrepareTruncationNoOp, FinalizeProfileStatusSuffix, rawStatus);
			}
			else
			{
				TruncateDisplayTextWidthPrepared(profileWrapper, profileViewerWidth+2, caption, PrepareProfileStatusSuffix, FinalizeProfileStatusSuffix, rawStatus);
			}
		}
		else
		{
			profileStatus.setAttribute("rawStatus", "");
		}
		profileViewer.style.display='inline-block';
		profileViewer.style.position='';
	}
}

function PrepareProfileStatusSuffix(container, shortenerTextNode, details)
{
	var profileStatusOverview = window.document.getElementById("ProfileStatusOverview");
	profileStatusOverview.style.display = "inline";
	var ellipses = window.document.createElement("SPAN");
	ellipses.appendChild(window.document.createTextNode("... (more)"));
	shortenerTextNode.parentNode.appendChild(ellipses);
	ellipses.title = window.document.getElementById("ProfileName").firstChild.data + " " + details;
	return ellipses;
}

function FinalizeProfileStatusSuffix(container, shortenerTextNode, originalText, truncationStillNeeded, details)
{
	return details;
}

function TidyHeaderInterestsPanel()
{
	var hotNowSection = window.document.getElementById("HeaderHotNowSection");
	if(hotNowSection !== null)
	{
		var hotNowInterests = window.document.getElementById("HeaderHotNowInterests");
		if(hotNowInterests.firstChild !== null)
		{
			hotNowSection.style.display = "block";
			var offsetCutoff = NaN;
			for(var interestLink = hotNowInterests.firstChild;  interestLink !== null;  interestLink = interestLink.nextSibling)
			{
				if(interestLink.nodeType === 1)
				{
					if(isNaN(offsetCutoff))
					{
						offsetCutoff = interestLink.offsetLeft + 400;
					}
					var linkID = interestLink.id;
					var interestID = linkID.substr(linkID.indexOf("_") + 1);
					var match = window.document.getElementById("OwnerInterest_" + interestID);
					if(match !== null)
					{
						var container = match.parentNode;
						var nextProperty;
						if(match.previousSibling === null)
						{
							nextProperty = "nextSibling";
						}
						else
						{
							nextProperty = "previousSibling";
						}
						do
						{
							var nextElement = match[nextProperty];
							container.removeChild(match);
							match = nextElement;
						} while ((match !== null) && (match.nodeType !== 1));
					}
					if(interestLink.offsetLeft + interestLink.offsetWidth > offsetCutoff)
					{
						var lastElement = interestLink.previousSibling;
						for(var cursor = hotNowInterests.lastChild;  cursor !== lastElement;  cursor = hotNowInterests.lastChild)
						{
							hotNowInterests.removeChild(cursor);
						}
						if(lastElement !== null)
						{
							hotNowInterests.removeChild(lastElement);
						}
						break;
					}
				}
			}
		}
		var ownerInterests = window.document.getElementById("HeaderOwnerInterests");
		
		ownerInterests.style.lineHeight = '20px';

		var expansionLink = ownerInterests.lastChild;
		var lastLineFirstChild = null;
		var rollValues = 5;
		var rollRange = rollValues - 1;
		var currentRoll = Math.floor(Math.random() * rollValues);
		var linkCursor = null;
		for(linkCursor = ownerInterests.firstChild;  linkCursor !== null;  linkCursor = linkCursor.nextSibling)
		{
			if((linkCursor.nodeType === 1) && (linkCursor !== expansionLink))
			{
				currentRoll = (currentRoll + Math.floor(Math.random() * rollRange) + 1) % rollValues;
				linkCursor.className = "headerinterest_" + currentRoll.toString();
			}
		}

		for (linkCursor = expansionLink.previousSibling; ownerInterests.offsetHeight > 50; linkCursor = expansionLink.previousSibling)
		{
			ownerInterests.removeChild(linkCursor);
		}
		if (!!expansionLink.previousSibling && expansionLink.previousSibling.nodeType !== 1)
		{
			ownerInterests.removeChild(expansionLink.previousSibling);
		}
		
		ownerInterests.style.lineHeight='';
	}
}

/*

Truncation functions:

TruncateDisplayTextWidth(container, widthMaximum, shortenerTextNode)
TruncateDisplayTextHeight(container, heightMaximum, shortenerTextNode)
TruncateDisplayTextWidthPrepared(container, widthMaximum, shortenerTextNode, preparationFunction, finalizationFunction, details)
TruncateDisplayTextHeightPrepared(container, heightMaximum, shortenerTextNode, preparationFunction, finalizationFunction, details)



Word-wrapping functions:

WordBreakDisplayTextWidth(container, widthMaximum, textNode)



Combined functions:

FitDisplayTextToBlock(container, widthMaximum, heightMaximum, textNode)
FitDisplayTextToBlockPrepared(container, widthMaximum, heightMaximum, textNode, rangedPreparationFunction, rangedFinalizationFunction, details)



Preparation functions (for use in "prepared" functions):

PrepareTruncationTextSuffix(container, shortenerTextNode, details)
PrepareTruncationElementSuffix(container, shortenerTextNode, details)
RangedPrepareTruncationTextSuffix(container, firstShortenerTextNode, lastShortenerTextNode, details)
RangedPrepareTruncationElementSuffix(container, firstShortenerTextNode, lastShortenerTextNode, details)



Finalization functions (for use in "prepared" functions):

FinalizeTruncationSuffixTooltip(container, shortenerTextNode, originalText, truncationStillNeeded, details)
FinalizeTruncationSuffix(container, shortenerTextNode, originalText, truncationStillNeeded, details)
RangedFinalizeTruncationSuffixTooltip(container, firstShortenerTextNode, lastShortenerTextNode, originalText, truncationStillNeeded, details)
RangedFinalizeTruncationSuffix(container, firstShortenerTextNode, lastShortenerTextNode, originalText, truncationStillNeeded, details)



Computation functions:

ComputeDisplayTextLineHeight(oneLineElement, twoLineElement, lineCount)

*/



/* Adjusts the text in 'shortenerTextNode' so that the width of 'container' is within the specified amount.  If text is truncated, the 'TextNode' is enclosed in a new element with its 'title' attribute set to the original text and the new element is returned.  Otherwise, this function returns 'null'. */
function TruncateDisplayTextWidth(container, widthMaximum, shortenerTextNode)
{
	if(TruncationIsNeeded(container, "offsetWidth", widthMaximum))
	{
		var suffixNode = PrepareTruncationTextSuffix(container, shortenerTextNode, "...");
		var originalText = TruncateDisplayTextInternalEx(container, "offsetWidth", widthMaximum, shortenerTextNode);
		var truncationStillNeeded = TruncationIsNeeded(container, "offsetWidth", widthMaximum);
		return FinalizeTruncationSuffixTooltip(container, shortenerTextNode, originalText, truncationStillNeeded, suffixNode);
	}
	else
	{
		return null;
	}
}

/* Adjusts the text in 'shortenerTextNode' so that the height of 'container' is within the specified amount.  If text is truncated, the 'TextNode' is enclosed in a new element with its 'title' attribute set to the original text and the new element is returned.  Otherwise, this function returns 'null'. */
function TruncateDisplayTextHeight(container, heightMaximum, shortenerTextNode)
{
	if(TruncationIsNeeded(container, "offsetHeight", heightMaximum))
	{
		var suffixNode = PrepareTruncationTextSuffix(container, shortenerTextNode, "...");
		var originalText = TruncateDisplayTextInternalEx(container, "offsetHeight", heightMaximum, shortenerTextNode);
		var truncationStillNeeded = TruncationIsNeeded(container, "offsetHeight", heightMaximum);
		return FinalizeTruncationSuffixTooltip(container, shortenerTextNode, originalText, truncationStillNeeded, suffixNode);
	}
	else
	{
		return null;
	}
}

/* Adjusts the text in 'shortenerTextNode' so that the width of 'container' is within the specified amount.  If truncation is needed, 'preparationFunction' is called with the parameters ('container', 'shortenerTextNode', 'originalText', 'details'), then after truncation, 'finalizationFunction' is called with the parameters ('container', 'shortenerTextNode', 'originalText', 'truncationStillNeeded', (the return value of 'preparationFunction')), and its result is returned.  Otherwise, this function returns 'null'. */
function TruncateDisplayTextWidthPrepared(container, widthMaximum, shortenerTextNode, preparationFunction, finalizationFunction, details)
{
	if(TruncationIsNeeded(container, "offsetWidth", widthMaximum))
	{
		details = preparationFunction(container, shortenerTextNode, details);
		var originalText = TruncateDisplayTextInternalEx(container, "offsetWidth", widthMaximum, shortenerTextNode);
		var truncationStillNeeded = TruncationIsNeeded(container, "offsetWidth", widthMaximum);
		return finalizationFunction(container, shortenerTextNode, originalText, truncationStillNeeded, details);
	}
	else
	{
		return null;
	}
}

/* Adjusts the text in 'shortenerTextNode' so that the height of 'container' is within the specified amount.  If truncation is needed, 'preparationFunction' is called with the parameters ('container', 'shortenerTextNode', 'originalText', 'details'), then after truncation, 'finalizationFunction' is called with the parameters ('container', 'shortenerTextNode', 'originalText', 'truncationStillNeeded', (the return value of 'preparationFunction')), and its result is returned.  Otherwise, this function returns 'null'. */
function TruncateDisplayTextHeightPrepared(container, heightMaximum, shortenerTextNode, preparationFunction, finalizationFunction, details)
{
	if(TruncationIsNeeded(container, "offsetHeight", heightMaximum))
	{
		details = preparationFunction(container, shortenerTextNode, details);
		var originalText = TruncateDisplayTextInternalEx(container, "offsetHeight", heightMaximum, shortenerTextNode);
		var truncationStillNeeded = TruncationIsNeeded(container, "offsetHeight", heightMaximum);
		return finalizationFunction(container, shortenerTextNode, originalText, truncationStillNeeded, details);
	}
	else
	{
		return null;
	}
}

/* Adds the suffix to the truncated text.  This is a 'truncationFunction'. */
function AddTruncationSuffix(container, shortenerTextNode, originalText, details)
{
	var suffix = details;
	var textCurrentLength = shortenerTextNode.length;
	var suffixLength = suffix.length;
	if(textCurrentLength > suffixLength)
	{
		shortenerTextNode.replaceData(textCurrentLength - suffixLength, suffixLength, suffix);
	}
	return container;
}

/* Adds the suffix to the truncated text and creates a tooltip with the original text.  This is a 'truncationFunction'. */
function AddTruncationSuffixAndDisplayTextTooltip(container, shortenerTextNode, originalText, details)
{
	var suffix = details;
	var textCurrentLength = shortenerTextNode.length;
	var shortenerParent = shortenerTextNode.parentNode;
	var shortenerNeighbor = shortenerTextNode.nextSibling;
	var wrapper = window.document.createElement("SPAN");
	wrapper.title = originalText;
	wrapper.appendChild(shortenerTextNode);
	shortenerParent.insertBefore(wrapper, shortenerNeighbor);
	var suffixLength = suffix.length;
	if(textCurrentLength > suffixLength)
	{
		shortenerTextNode.replaceData(textCurrentLength - suffixLength, suffixLength, suffix);
	}
	return wrapper;
}

/* Creates a tooltip with the original text and returns the wrapper element containing the tooltip.  This is a 'truncationFunction'. */
function AddDisplayTextTooltip(container, shortenerTextNode, originalText, details)
{
	var suffixNode = details;
	suffixNode.parentNode.removeChild(suffixNode);
	var shortenerParent = shortenerTextNode.parentNode;
	var shortenerNeighbor = shortenerTextNode.nextSibling;
	var wrapper = window.document.createElement("SPAN");
	wrapper.title = originalText;
	wrapper.appendChild(shortenerTextNode);
	wrapper.appendChild(suffixNode);
	shortenerParent.insertBefore(wrapper, shortenerNeighbor);
	return wrapper;
}

/* Inserts the provided text as a suffix in anticipation of truncation.  This is a 'preparationFunction'. */
function PrepareTruncationTextSuffix(container, shortenerTextNode, details)
{
	var suffixTextNode = window.document.createTextNode(details);
	shortenerTextNode.parentNode.insertBefore(suffixTextNode, shortenerTextNode.nextSibling);
	return suffixTextNode;
}
/* Inserts the provided text as a suffix in anticipation of truncation.  This is a 'rangedPreparationFunction'. */
function RangedPrepareTruncationTextSuffix(container, firstShortenerTextNode, lastShortenerTextNode, details)
{
	var suffixTextNode = window.document.createTextNode(details);
	lastShortenerTextNode.parentNode.insertBefore(suffixTextNode, lastShortenerTextNode.nextSibling);
	return suffixTextNode;
}
/* Inserts the provided element as a suffix in anticipation of truncation.  This is a 'preparationFunction'. */
function PrepareTruncationElementSuffix(container, shortenerTextNode, details)
{
	var suffixElement = details;
	shortenerTextNode.parentNode.insertBefore(suffixElement, shortenerTextNode.nextSibling);
	return suffixElement;
}
/* Inserts the provided element as a suffix in anticipation of truncation.  This is a 'rangedPreparationFunction'. */
function RangedPrepareTruncationElementSuffix(container, firstShortenerTextNode, lastShortenerTextNode, details)
{
	var suffixElement = details;
	lastShortenerTextNode.parentNode.insertBefore(suffixElement, lastShortenerTextNode.nextSibling);
	return suffixElement;
}
/* Applies no changes in anticipation of truncation.  This is a 'preparationFunction'. */
function PrepareTruncationNoOp(container, shortenerTextNode, details)
{
	return details;
}
/* If truncation occurred, adds a tooltip with the original text.  This is a 'finalizationFunction'. */
function FinalizeTruncationSuffixTooltip(container, shortenerTextNode, originalText, truncationStillNeeded, details)
{
	var suffixNode = details;
	if(originalText !== null)
	{
		var wrapper = AddDisplayTextTooltip(container, shortenerTextNode, originalText, suffixNode);
		if(truncationStillNeeded)
		{
			suffixNode.parentNode.removeChild(suffixNode);
		}
		return wrapper;
	}
	else
	{
		return null;
	}
}
/* If truncation occurred, adds a tooltip with the original text.  This is a 'rangedFinalizationFunction'. */
function RangedFinalizeTruncationSuffixTooltip(container, firstShortenerTextNode, lastShortenerTextNode, originalText, truncationStillNeeded, details)
{
	var suffixNode = details;
	if(originalText !== null)
	{
		suffixNode.parentNode.removeChild(suffixNode);
		var shortenerParent = lastShortenerTextNode.parentNode;
		var shortenerNeighbor = lastShortenerTextNode.nextSibling;
		var wrapper = window.document.createElement("SPAN");
		wrapper.title = originalText;
		var nextCursor;
		for(var shortenerCursor = firstShortenerTextNode;  shortenerCursor !== shortenerNeighbor;  shortenerCursor = nextCursor)
		{
			nextCursor = shortenerCursor.nextSibling;
			wrapper.appendChild(shortenerCursor);
		}
		wrapper.appendChild(suffixNode);
		shortenerParent.insertBefore(wrapper, shortenerNeighbor);

		if(truncationStillNeeded)
		{
			suffixNode.parentNode.removeChild(suffixNode);
		}
		return wrapper;
	}
	else
	{
		return null;
	}
}
/* If truncation occurred, decides if the suffix can fit.  This is a 'finalizationFunction'. */
function FinalizeTruncationSuffix(container, shortenerTextNode, originalText, truncationStillNeeded, details)
{
	var suffixNode = details;
	if(originalText !== null)
	{
		if(truncationStillNeeded)
		{
			suffixNode.parentNode.removeChild(suffixNode);
		}
		return container;
	}
	else
	{
		return null;
	}
}
/* If truncation occurred, decides if the suffix can fit.  This is a 'rangedFinalizationFunction'. */
function RangedFinalizeTruncationSuffix(container, firstShortenerTextNode, lastShortenerTextNode, originalText, truncationStillNeeded, details)
{
	var suffixNode = details;
	if(originalText !== null)
	{
		if(truncationStillNeeded)
		{
			suffixNode.parentNode.removeChild(suffixNode);
		}
		return container;
	}
	else
	{
		return null;
	}
}

/* Decides if the specified property of 'container' is within the specified amount. */
function TruncationIsNeeded(container, dimensionProperty, dimensionMaximum)
{
	var currentDimension = container[dimensionProperty];
	return (currentDimension > dimensionMaximum);
}

/* For internal use.  Adjusts the text in 'shortenerTextNode' so that the specified property of 'container' is within the specified amount.  If text is truncated, the original text is returned.  Otherwise, this function returns 'null'. */
function TruncateDisplayTextInternalEx(container, dimensionProperty, dimensionMaximum, shortenerTextNode)
{
	var originalText = shortenerTextNode.data;
	var originalTextLength = originalText.length;
	if(originalTextLength === 0)
	{
		return null;
	}
	var textCurrentLength = originalTextLength;
	/* Record the range of previously-tried lengths. */
	var textLowLength = 0;
	var textHighLength = textCurrentLength;
	while(true)
	{
		var currentDimension = container[dimensionProperty];
		var dimensionDifference = currentDimension - dimensionMaximum;
		if(dimensionDifference > 0)
		{
			textHighLength = textCurrentLength;
		}
		else
		{
			textLowLength = textCurrentLength;
		}
		var candidateTextLengthDifference;
		/* Decide if the range can be narrowed. */
		if(textHighLength - textLowLength > 1)
		{
			var dimensionDifferenceRatio = dimensionMaximum / currentDimension;
			var candidateTextLength = Math.floor(textCurrentLength * dimensionDifferenceRatio);
			candidateTextLengthDifference = textCurrentLength - candidateTextLength;

			/* Ensure at least one unit of change. */
			if(candidateTextLengthDifference === 0)
			{
				if(dimensionDifferenceRatio > 0)
				{
					candidateTextLength++;
					candidateTextLengthDifference = -1;
				}
				else
				{
					candidateTextLength--;
					candidateTextLengthDifference = 1;
				}
			}
			/* Clamp the length to within the range of our previous attempts. */
			if(candidateTextLength >= textHighLength)
			{
				candidateTextLength = textHighLength - 1;
				candidateTextLengthDifference = textCurrentLength - candidateTextLength;
			}
			else if(candidateTextLength <= textLowLength)
			{
				candidateTextLength = textLowLength + 1;
				candidateTextLengthDifference = textCurrentLength - candidateTextLength;
			}
			if(candidateTextLengthDifference > 0)
			{
				shortenerTextNode.deleteData(candidateTextLength, candidateTextLengthDifference);
			}
			else
			{
				shortenerTextNode.appendData(originalText.substr(textCurrentLength, -candidateTextLengthDifference));
			}
			textCurrentLength = candidateTextLength;
		}
		else
		{
			/* Trim to the last accepted length. */
			if(textCurrentLength !== textLowLength)
			{
				candidateTextLengthDifference = textCurrentLength - textLowLength;
				if(candidateTextLengthDifference > 0)
				{
					shortenerTextNode.deleteData(textLowLength, candidateTextLengthDifference);
				}
				else
				{
					shortenerTextNode.appendData(originalText.substr(textCurrentLength, -candidateTextLengthDifference));
				}
				textCurrentLength = textLowLength;
			}
			break;
		}
	}
	if(originalTextLength !== textCurrentLength)
	{
		return originalText;
	}
	else
	{
		return null;
	}
}

/* Estimates the height, in pixels, of an element containing the specified number of lines of text based on two specimen elements containing one and two lines of text. */
function ComputeDisplayTextLineHeight(oneLineElement, twoLineElement, lineCount)
{
	var oneLineElementHeight = oneLineElement.offsetHeight;
	var twoLineElementHeight = twoLineElement.offsetHeight;
	var lineHeight = twoLineElementHeight - oneLineElementHeight;
	var fixedHeight = oneLineElementHeight - lineHeight;
	return fixedHeight + (lineHeight * lineCount);
}

/* Breaks long words in the provided 'TextNode' to fit within a line of the specified width, simulating the Cascading Style Sheets property 'word-wrap'. */
function WordBreakDisplayTextWidth(container, widthMaximum, textNode)
{
	var text = textNode.data;
	var offsets = FindWordBreakOffsetsWidthInternal(container, widthMaximum, textNode);

	if(offsets.length !== 0)
	{
		var lastOffset = 0;
		var currentTextNode = textNode;
		var textNodeParent = textNode.parentNode;
		for(var offsetIndex = 0;  offsetIndex < offsets.length;  offsetIndex++)
		{
			var offset = offsets[offsetIndex];
			var difference = offset - lastOffset;
			var newTextNode = currentTextNode.splitText(difference);
			var nextNode = currentTextNode.nextSibling;
			textNodeParent.insertBefore(window.document.createElement("WBR"), nextNode);
			textNodeParent.insertBefore(newTextNode, nextNode);
			currentTextNode = newTextNode;
			lastOffset = offset;
		}
	}
}

/* For internal use.  Builds a list of indices in the specified 'TextNode' where word breaks should be inserted to fit within lines of the specified width. */
function FindWordBreakOffsetsWidthInternal(container, widthMaximum, textNode)
{
	/* Internet Explorer may need a wrapper when interacting with nearby floated elements. */
	var wrapper = window.document.createElement("DIV");
	var duplicateContainer = container.cloneNode(false);
	var duplicateTextNode = window.document.createTextNode("");
	duplicateContainer.appendChild(duplicateTextNode);
	duplicateContainer.style.overflow = "visible";
	duplicateContainer.style.position = "absolute";
	duplicateContainer.style.left = "-999px";
	duplicateContainer.style.top = "-999px";
	duplicateContainer.style.display = "block";
	duplicateContainer.style.whiteSpace = "nowrap";
	duplicateContainer.style.width = "auto";
	duplicateContainer.style.wordWrap = "normal";
	container.parentNode.insertBefore(wrapper, container);
	wrapper.appendChild(duplicateContainer);

	var text = textNode.data;
	var lastBreakIndex = 0;
	var offsets = [];
	for(var breakIndex = text.indexOf(" ", lastBreakIndex); breakIndex !== -1;  breakIndex = text.indexOf(" ", lastBreakIndex))
	{
		var word = text.substring(lastBreakIndex, breakIndex);
		AppendWordBreakOffsetsWidthInternal(duplicateContainer, widthMaximum, duplicateTextNode, word, lastBreakIndex, offsets);
		lastBreakIndex = breakIndex + 1;
	}
	var lastWord = text.substr(lastBreakIndex);
	AppendWordBreakOffsetsWidthInternal(duplicateContainer, widthMaximum, duplicateTextNode, lastWord, lastBreakIndex, offsets);

	wrapper.parentNode.removeChild(wrapper);

	return offsets;
}

/* For internal use.  Calculates indices in the specified word where breaks can be inserted to fit within lines of the specified width. */
function AppendWordBreakOffsetsWidthInternal(container, widthMaximum, textNode, word, offsetAdjustment, offsets)
{
	textNode.data = word;
	for(var wordIndex = 0;  (TruncateDisplayTextInternalEx(container, "offsetWidth", widthMaximum, textNode) !== null);  )
	{
		var breakThreshold = textNode.data.length;
		offsets.push(breakThreshold + wordIndex + offsetAdjustment);
		wordIndex += breakThreshold;
		textNode.data = word.substr(wordIndex);
	}
}

/* Breaks long words in the provided 'TextNode' to fit within a line of the specified width, simulating the Cascading Style Sheets property 'word-wrap', and adjusts the text so that the height of 'container' is within the specified amount.  If text is truncated, the 'TextNode' is enclosed in a new element with its 'title' attribute set to the original text and the new element is returned.  Otherwise, this function returns 'null'. */
function FitDisplayTextToBlock(container, widthMaximum, heightMaximum, textNode)
{
	return FitDisplayTextToBlockPrepared(container, widthMaximum, heightMaximum, textNode, RangedPrepareTruncationTextSuffix, RangedFinalizeTruncationSuffixTooltip, "...");
}

/* Breaks long words in the provided 'TextNode' to fit within a line of the specified width, simulating the Cascading Style Sheets property 'word-wrap', and adjusts the text so that the height of 'container' is within the specified amount.  If truncation is needed, 'rangedPreparationFunction' is called with the parameters ('container', 'firstShortenerTextNode', 'lastShortenerTextNode', 'originalText', 'details'), then after truncation, 'rangedFinalizationFunction' is called with the parameters ('container', 'firstShortenerTextNode', 'lastShortenerTextNode', 'originalText', 'truncationStillNeeded', (the return value of 'rangedPreparationFunction')), and its result is returned.  Otherwise, this function returns 'null'. */
function FitDisplayTextToBlockPrepared(container, widthMaximum, heightMaximum, textNode, rangedPreparationFunction, rangedFinalizationFunction, details)
{
	var originalText = textNode.data;
	var offsets = FindWordBreakOffsetsWidthInternal(container, widthMaximum, textNode);

	if(offsets.length !== 0)
	{
		textNode.data = "";

		var lastOffset = 0;
		var currentTextNode = textNode;
		var textNodeParent = textNode.parentNode;
		for(var offsetIndex = 0;  offsetIndex < offsets.length;  offsetIndex++)
		{
			var offset = offsets[offsetIndex];
			currentTextNode.data = originalText.substring(lastOffset, offset);
			if(TruncationIsNeeded(container, "offsetHeight", heightMaximum))
			{
				return FitDisplayTextToBlockPreparedFitLastLineInternal(container, widthMaximum, heightMaximum, originalText, textNode, currentTextNode, textNodeParent, lastOffset, rangedPreparationFunction, rangedFinalizationFunction, details);
			}
			var nextNode = currentTextNode.nextSibling;
			textNodeParent.insertBefore(window.document.createElement("WBR"), nextNode);
			var newTextNode = window.document.createTextNode("");
			textNodeParent.insertBefore(newTextNode, nextNode);
			currentTextNode = newTextNode;
			lastOffset = offset;
		}
		currentTextNode.data = originalText.substr(lastOffset);
		if(TruncationIsNeeded(container, "offsetHeight", heightMaximum))
		{
			return FitDisplayTextToBlockPreparedFitLastLineInternal(container, widthMaximum, heightMaximum, originalText, textNode, currentTextNode, textNodeParent, lastOffset, rangedPreparationFunction, rangedFinalizationFunction, details);
		}
		else
		{
			return null;
		}
	}
	else
	{
		var detailsShim = {
			"PreparationFunction" : rangedPreparationFunction,
			"FinalizationFunction" : rangedFinalizationFunction,
			"Details" : details
		};
		return TruncateDisplayTextHeightPrepared(container, heightMaximum, textNode, PrepareFromRangedFunctionInternal, FinalizeFromRangedFunctionInternal, detailsShim);
	}
}

/* For internal use.  Fits the final line within the specified dimensions, assuming that there are previously-wrapped lines. */
function FitDisplayTextToBlockPreparedFitLastLineInternal(container, widthMaximum, heightMaximum, originalText, textNode, currentTextNode, textNodeParent, lastOffset, rangedPreparationFunction, rangedFinalizationFunction, details)
{
	details = rangedPreparationFunction(container, textNode, currentTextNode, details);
	TruncateDisplayTextInternalEx(container, "offsetHeight", heightMaximum, currentTextNode);
	if(currentTextNode.data.length === 0)
	{
		/* There is no room for a new line.  Backtrack and truncate the previous line. */
		var cursor = currentTextNode.previousSibling;
		if(cursor !== null)
		{
			/* Find the last line of text. */
			for(;  cursor !== null;  cursor = cursor.previousSibling)
			{
				if(cursor.nodeType === 3)
				{
					break;
				}
			}
			/* Remove intervening elements. */
			for(var eraser = cursor.nextSibling;  eraser !== currentTextNode;  eraser = cursor.nextSibling)
			{
				textNodeParent.removeChild(eraser);
			}
			/* Remove the new line of text that didn't fit. */
			textNodeParent.removeChild(currentTextNode);
			/* Restore the remaining text. */
			cursor.appendData(originalText.substr(lastOffset));
			TruncateDisplayTextInternalEx(container, "offsetWidth", widthMaximum, cursor);
			var truncationStillNeeded = TruncationIsNeeded(container, "offsetWidth", widthMaximum);
			return rangedFinalizationFunction(container, textNode, cursor, originalText, truncationStillNeeded, details);
		}
		else
		{
			/* No lines of text remain. */
			return rangedFinalizationFunction(container, textNode, textNode, originalText, false, details);
		}
	}
	else
	{
		return rangedFinalizationFunction(container, textNode, currentTextNode, originalText, false, details);
	}
}

/* For internal use.  Calls a 'rangedPreparationFunction' as if it were a 'preparationFunction'.  This is a 'preparationFunction'. */
function PrepareFromRangedFunctionInternal(container, shortenerTextNode, details)
{
	return {
		"FinalizationFunction" : details.FinalizationFunction,
		"Details" : details.PreparationFunction(container, shortenerTextNode, shortenerTextNode, details.Details)
	};
}

/* For internal use.  Calls a 'rangedFinalizationFunction' as if it were a 'preparationFunction'.  This is a 'finalizationFunction'. */
function FinalizeFromRangedFunctionInternal(container, shortenerTextNode, originalText, truncationStillNeeded, details)
{
	return details.FinalizationFunction(container, shortenerTextNode, shortenerTextNode, originalText, truncationStillNeeded, details.Details);
}

/* Hyphenates long words in the provided 'TextNode'. */
function HyphenateDisplayText(textNode)
{
	var text = textNode.data;
	var lastBreakIndex = 0;
	var offsets = [];
	for(var breakIndex = text.indexOf(" ", lastBreakIndex); breakIndex !== -1;  breakIndex = text.indexOf(" ", lastBreakIndex))
	{
		var word = text.substring(lastBreakIndex, breakIndex);
		AppendWordHyphenationOffsetsInternal(word, lastBreakIndex, offsets);
		lastBreakIndex = breakIndex + 1;
	}
	var lastWord = text.substr(lastBreakIndex);
	AppendWordHyphenationOffsetsInternal(lastWord, lastBreakIndex, offsets);
	if(offsets.length !== 0)
	{
		for(var offsetIndex = 0;  offsetIndex < offsets.length;  offsetIndex++)
		{
			var offset = offsets[offsetIndex];
			textNode.insertData(offset + offsetIndex, "\u00AD");
		}
	}
}

/* For internal use.  Calculates indexes in the specified word where hyphens can be inserted. */
function AppendWordHyphenationOffsetsInternal(word, offsetAdjustment, offsets)
{
	var hyphenationThreshold = 12;
	var breakCount = Math.floor((word.length - 1) / hyphenationThreshold);
	for(var breakIndex = 1;  breakIndex <= breakCount;  breakIndex++)
	{
		offsets.push(hyphenationThreshold * breakIndex + offsetAdjustment);
	}
}

function ViewInboxFromMHP()
{
	setTimeout(
		function()
		{
			var mdIFrame = $("uurl_create_ifrm");
			if (mdIFrame == null){
				var mdIFrame=document.createElement("iframe");
				mdIFrame.style.display="none";
				var container=document.body;
				container.appendChild(mdIFrame);
			}
			mdIFrame.src="http://www.fanbox.com/socnet/LaunchViewInboxFromMHP.html";
		},
		500);
	return false;	
}

var blogIframe;
function LaunchPBlog(pblogid, link, page, src, postID)
{
	try
	{
		top.LaunchPBlog(pblogid, pblogid, link, page, 1, '', src, false, false, '', postID)
	}
	catch (e)
	{
		if (!blogIframe)
		{
			blogIframe = document.createElement('iframe');
			blogIframe.src = 'about:blank';
			blogIframe.style.position = 'absolute';
			blogIframe.left = '-10px';
			blogIframe.top = '-10px';
			blogIframe.style.width = '1px';
			blogIframe.style.height = '1px';
			document.body.appendChild(blogIframe);
		}
		blogIframe.src = 'http://www.fanbox.com/socnet/LaunchPblog.html?pbid=' + pblogid + '&pageid=' + page + '&lkid=' + link + '&src=' + src + '&postId=' + postID;
	}
}

function HeaderInterestClick(tagName, interestID)
{
	new Ajax.Request("/Profile/PBlogTagStatHandler.ashx",
		{
		method: 'post',
		parameters: "tagname=" + encodeURIComponent(tagName) + "&interestid=" + encodeURIComponent(interestID.toString()) + "&source=Profile%20Header"
		}
	);
	PageTimer.ResetSession(window);
}
