/*
 * New "Master" javascript file for spark - lucena
 */

var dg_appendOnloadEvent__onloadEvents = new Array();

function dg_appendOnloadEvent_appendOnloadEvent(functionName)
{
	if (!window.onload)
	{
		window.onload = functionName;
	}
	else
	{
		if (window.onload != dg_appendOnloadEvent_bindOnloadEvents)
		{
			dg_appendOnloadEvent__onloadEvents[dg_appendOnloadEvent__onloadEvents.length] 
				= window.onload;
			window.onload = dg_appendOnloadEvent_bindOnloadEvents;		
		}
		
		dg_appendOnloadEvent__onloadEvents[dg_appendOnloadEvent__onloadEvents.length] 
			= functionName;			
	}
}

function dg_appendOnloadEvent_bindOnloadEvents()
{
	for (var i = 0; i < dg_appendOnloadEvent__onloadEvents.length; i++)
	{
		dg_appendOnloadEvent__onloadEvents[i]();
	}
}

////////////////////////////////////////////////////////////////////////////////////////
// These functions are required to persist a Layout Template across multiple requests

function getUrlParams(url)
{
	var queryString = url.split('?');
	if (queryString[1] != null)
		return queryString[1].split('&');
}

function getUrlParam(url, paramName)
{
	var params = getUrlParams(url);

	if (params == null)
		return null;
	
	for (i = 0; i < params.length; i++)
	{
		var param = params[i];
		
		if (param.indexOf(paramName + '=') == 0)
		{
			return param.substr(paramName.length + 1);
		}
	}
	
	return null;
}

function getBodyFromFunction(func)
{
	func = func.toString();
	func = func.substring(func.indexOf("{") + 1, func.lastIndexOf("}"));
	return func;
}

function appendPopupKeyToLink(link)
{
	var layoutTemplateID = getUrlParam(location.href, 'LayoutTemplateID');

	if (layoutTemplateID != null)
	{
		if(link.href != null && link.href != "")
		{
			if (link.href.indexOf('?') == -1)
			{
				delim = '?';
			}
			else
			{
				delim = '&';
			}
			
			if (getUrlParam(link.href, 'PersistLayoutTemplate') == null)
			{
				link.href += delim + 'PersistLayoutTemplate=1';
				delim = '&';
			}

			if (getUrlParam(link.href, 'LayoutTemplateID') == null)
			{
				link.href += delim + 'LayoutTemplateID=' + layoutTemplateID;
			}
		}
    }
}

function delegateClickEvents()
{
	if (getUrlParam(location.href, 'PersistLayoutTemplate') != null)
	{
		var links = document.getElementsByTagName('a');

		for (var i = 0; i < links.length; i++)
		{
			if (links[i].href.indexOf('javascript') == -1)
			{
				if (!links[i].onclick)
				{
					links[i].onclick = new Function("appendPopupKeyToLink(this);");
				}
				else
				{
					currentOnClick = links[i].onclick;
					if (typeof currentOnClick == "function")
					{
						currentOnClick = getBodyFromFunction(currentOnClick);
					}
					
					links[i].onclick = new Function("appendPopupKeyToLink(this); " + currentOnClick);
				}
			}
		}
    }
}

////////////////////////////////////////////////////////////////////////////////////////

function spark_getCookie(name)
{
    var start   = document.cookie.indexOf(name + '=');
    var len     = start + name.length + 1;

    if ((!start) && (name != document.cookie.substring(0, name.length))) 
    {
        return null;
    }
    
    if (start == -1) 
    {
        return null;
    }
    
    var end = document.cookie.indexOf(';', len);
    
    if (end == -1) 
    {
        end = document.cookie.length;
    }
    
    return unescape(document.cookie.substring(len, end));
}

function spark_setCookie(name, value, expires, path, domain, secure)
{
    document.cookie = name + '=' + escape(value) 
        + ((expires) ? ';expires=' + expires.toGMTString() : '') 
        + ((path) ? ';path=' + path : '') 
        + ((domain) ? ';domain=' + domain : '') 
        + ((secure) ? ';secure' : '');
} 

function matchnetYNM4_checkWindowOpener(objectId)
{
	var lnkNoPhoto = document.getElementById(objectId);
	
	if (lnkNoPhoto != null)
	{
		if(window.top.opener != null)
		{
			window.top.opener.location.href = lnkNoPhoto.href;
			lnkNoPhoto.onclick				= matchnetYNM4_returnFalse;
			
			return false;
		}
		else
		{
			window.location.href = lnkNoPhoto.href;
		}
	}	
}

function matchnetYNM4_returnFalse()
{
	return false;
}

/* bust out of frames always */
function RemoveFrames()
{
	if (self.location != top.location) top.location = self.location;
}

/**********************************************************************************/
function launchWindow(strURL, strName, intWidth, intHeight, strProperties) 
{
	// just create a window with the given properties and don't return the handle
	// to the window. (for inline javascript: calls in hrefs)
	var w = createWindow(strURL, strName, intWidth, intHeight, strProperties);
	// make sure created window has focus. In case a popup profile was in background
	// or minimized, bring it to front.
	w.focus();
}

function createWindow(strURL, strName, intWidth, intHeight, strProperties)
{
	var mywin;
	var intVersion;
	var dummyDate = new Date(); 
	
	var strPoundURL;
	var intPoundPos;

	intVersion = navigator.appVersion.substring(0,1);
	if (strURL != "") 
	{
		intPoundPos = strURL.indexOf("#");
		if (intPoundPos != -1) {
			strPoundURL = strURL.substring(intPoundPos);
			strURL = strURL.substring(0, intPoundPos);
		}
			
		if (strURL.indexOf("?") != -1) { 
			strURL = strURL + "&rnd="
		} else {
			strURL = strURL + "?rnd="
		}
			
		strURL = strURL + dummyDate.getTime();
		
		if (strPoundURL != null)
		{
			strURL = strURL + strPoundURL;
		}
			
		strURL = Replace(strURL,"@","%40");
	}
	
	if (strProperties == "") {
		strProperties = "scrollbars=yes,resizable=yes,menubar=no,location=no,directories=no,toolbar=no";
	}
	
	strProperties = "status=yes,height=" + intHeight + ",width=" + intWidth + "," + strProperties;

	// replace all non-alphacharacters with X
	if(strName.replace)
		strName = strName.replace(/\W/g,"X");
	
	// lower case the string
	strName = strName.toLowerCase();
	
		//try to open a pop-up window
		mywin = window.open(strURL, strName, strProperties);


		// POP-BLOCKER OVERRIDE SECTION
		// try to load the link in the current window, unless this is a view profile request from IM.
		// If it is a view profile request from IM, try to show the profile in window.opener or else give up
		if(mywin==null)//i.e., pop-up blocker
		{		
			mywin = self; // set to self so we don't return null reference
			
			// We are changing the template here to show nav and header 
			// since we can't open a pop-up window
			strURL = strURL.replace("LayoutTemplateID=2", "LayoutTemplateID=1");
			strURL = strURL.replace("LayoutTemplateID=4", "LayoutTemplateID=8");
			strURL = strURL.replace("LayoutTemplateID=11", "LayoutTemplateID=1"); //Open profile in same window if popup blockers are enabled.
			
			// If the current window is an IM window, we will allow the popup blocker to notify the user that
			// the window couldn't be opened, otherwise, we load the link in the current window.
			if (window.location.href.indexOf("/upInstantCommunicator.aspx") == -1)
			{
				window.document.location = strURL;
			}
			else {
			// if this is an IM window request for a profile, check if window.opener is still open
				var IsWindowOpenerClosed = false;
				try
				{	//Attempt to access a property on the window.opener object
					//Using 'window.opener.closed' is not consistent on all browser implementations.
					var temp = window.opener.location.href;		
				}
				catch(e)
				{
					IsWindowOpenerClosed = true;
				}
				if (!IsWindowOpenerClosed) {

					//do not persist the layout template (bug: 15532) (or else all subsequent requests will have nav and header around them)
					strURL = strURL.replace("PersistLayoutTemplate=1", "")
					window.opener.location = strURL;
				}
				else {
					//do nothing. let the pop-up blocker work TODO: resource in other languages
					//alert("to view member's profile requires pop-up blocker to be disabled.");
				}
			
			}
		}
		
	// return handle to caller
	return mywin;
}

/**********************************************************************************/
function AddFriendsToHotList(strBaseForm, lngAction, lngLayoutTemplateID)
{
	var mywin;
	var i;
	var lngCount;
	var strFriendMemberIDs;
	var lngCachedAction;
	var strCachedTarget;

	strFriendMemberIDs = '';
	lngCount = 0
	for (var i=0; i<document.forms[strBaseForm].FriendMemberID.length; i++) {
		if (document.forms[strBaseForm].FriendMemberID[i].checked == true) {
			if (lngCount == 0) 
				strFriendMemberIDs = strFriendMemberIDs + document.forms[strBaseForm].FriendMemberID[i].value;
			else
				strFriendMemberIDs = strFriendMemberIDs + ',' + document.forms[strBaseForm].FriendMemberID[i].value;
			lngCount++;
		}
	}
	
	if(lngCount == 0) {
		alert("Please choose at least one member");
		return;
	}


	mywin = window.open('/blank.htm', 'friends', 'status=yes,height=525,width=750,scrollbars=yes,resizable=yes,menubar=no,location=no,directories=no,toolbar=no');
	if (mywin.opener == null) mywin.opener = self;
	mywin.focus();

	strCachedTarget = document.forms[strBaseForm].target;
	lngCachedAction = document.forms[strBaseForm].elements["a"].value;
	
	strSavedAction = document.forms[strBaseForm].action;
	document.forms[strBaseForm].action = "default.asp?LayoutTemplateID=" + lngLayoutTemplateID;
	document.forms[strBaseForm].target = mywin.name;
	document.forms[strBaseForm].elements["a"].value = lngAction;
	document.forms[strBaseForm].submit();
	
	document.forms[strBaseForm].target = strCachedTarget;
	document.forms[strBaseForm].elements["a"].value = lngCachedAction;
	document.forms[strBaseForm].action = strSavedAction;
}

/**********************************************************************************
/ The name of the OpenerFormName is hardcoded for these reasons:
/ 1) For effeciency. We don't want to pass it around the form and querystring
/ 2) The SelectMemberForm is really comming from CMemberList. Adding support for this
/		would make this code get more ugly then
/ 3) Don't want to make a global constant; it would have to be passed into this function
**********************************************************************************/
function SelectMemberToEmailFromHotlist(strFormName, lngMaxRadioButtonIndex, strErrorMsg)
{
	var strOpenerFormName = 'frmComposeEmailFull';
	var lngToMemberID;
	var blnFound = false;
	
	if (lngMaxRadioButtonIndex == 1) {
		if (document.forms[strFormName].ToMemberID.checked) {
			lngToMemberID = document.forms[strFormName].ToMemberID.value;
			blnFound = true;
		}
	} else {
		for (i = 0; i < lngMaxRadioButtonIndex; i++) {
			if (document.forms[strFormName].ToMemberID[i].checked) {
				lngToMemberID = document.forms[strFormName].ToMemberID[i].value;
				blnFound = true;
			}
		}
	}
	
	if (blnFound == false) {
		alert(strErrorMsg);
		return;
	}
	
	window.opener.document.forms[strOpenerFormName].ToMemberID.value=lngToMemberID;
	window.opener.document.forms[strOpenerFormName].submit();
	window.close();
}

/**********************************************************************************/
function SelectMemberToEmail(lngToMemberID)
{
	var strOpenerFormName = 'frmComposeEmailFull';

	window.opener.document.forms[strOpenerFormName].ToMemberID.value=lngToMemberID;
	window.opener.document.forms[strOpenerFormName].submit();
	window.close();
}

/**********************************************************************************/
function Split(str, strDelimiter) {
	var ary = new Array();
	var lngCurrentLoc;
	var i = 0;
	var strValue;
	var lngLength;
		
	lngCurrentLoc = str.indexOf(strDelimiter);
	while (lngCurrentLoc >= 0) 
	{
		strValue = str.substring(0, lngCurrentLoc);
		if (strValue.length > 0) 
		{
			ary[i++] = strValue
		}
		str = str.substring(lngCurrentLoc + 1, str.length);
		lngCurrentLoc = str.indexOf(strDelimiter);
	}
	if (str.length > 0) 
	{
		ary[i] = str;
	}
	return ary;
}

/**********************************************************************************/



/**********************************************************************************/
function Replace(str, substring, newstring) {
	if (str.length <= 0)
		return "";

	temp = "" + str; 

	while (temp.indexOf(substring)>-1) {
	pos = temp.indexOf(substring);
	temp = "" + (temp.substring(0, pos) + newstring + temp.substring((pos + substring.length), temp.length));
	}
	return temp;
}

/**********************************************************************************/
function ConfirmDelete(strMessage, strLocation) 
{
	if (confirm(strMessage)) {
		document.location.href = strLocation;
	}
}

/**********************************************************************************/
function CheckAll(frm)
{
	for (var i=0;i<frm.elements.length;i++)
	{
		var e = frm.elements[i];
		if (e.name != 'allbox')
			e.checked = frm.allbox.checked;
	}
}

/**********************************************************************************/
function UnCheckAllExceptOne(form_object, lngItem) {
	if (lngItem == null) {lngItem = 0};
	if (form_object[lngItem].checked == true) {
		var len = form_object.length;
		for (var i = 0; i < len; i++) {
			if (i != lngItem) {
				form_object[i].checked = false;
			}
		}
	}
}

/**********************************************************************************/
function UnCheckTop(form_object) 
{
	form_object[0].checked = false;
}


/**********************************************************************************/
/* Form Validation: Begin													      */
/**********************************************************************************/

function IsEmpty(obj, obj_type)
{
	if (obj_type == "text" || obj_type == "password" || obj_type == "textarea" || obj_type == "file")	{
		var objValue;
		
		objValue = obj.value.replace(/\s+$/,"");
		
		if (objValue.length == 0) {
			obj.focus();
			return true;
		} else {
			return false;
		}
	} else if (obj_type == "select") {
		for (i=0; i < obj.length; i++) {
			if (obj.options[i].selected) {
				if(obj.options[i].value == "") {
					obj.focus();
					return true;
				} else {
					return false;
				}
			}
			
		}
		return true;	
	} else if (obj_type == "radio" || obj_type == "checkbox") {
		if (!obj[0] && obj) {
			if (obj.checked) {
				return false;
			} else {
				obj.focus();
				return true;	
			}
		} else {
			for (i=0; i < obj.length; i++) {
				if (obj[i].checked) {
					return false;
				}
			}
			obj[0].focus();
			return true;
		}
	} else {
		return false;
	}
}

function InLengthRange(object_value, min_value, max_value)
{
	
	if (object_value == null) {
		return true;
	}

	if (min_value == null) {
		min_value = 0;
	}
	
	if (max_value == null) {
		if (object_value.length >= min_value) {
			return true;
		} else {
			return false;
		}
	}
	
	if (object_value.length >= min_value && object_value.length <= max_value) {
		return true;
	} else {
		return false;
	}

}

function InValueRange(object_value, min_value, max_value)
{
	
	if (object_value == null) {
		return true;
	}
	else {
		if (object_value == '')
			return true;
	}

	if (min_value == null) {
		min_value = 0;
	}
	
	

	if (max_value == null) {
		if (object_value >= min_value) {
			return true;
		} else {
			return false;
		}
	}
	
	if (object_value >= min_value && object_value <= max_value) {
		return true;
	} else {
		return false;
	}

}


function TestNumberRange(object_value, min_value, max_value)
{
	// check minimum
	if (min_value != null) {
		if (object_value < min_value) {
			return false;
		}
	}
		
	// check maximum
	if (max_value != null) {
		if (object_value > max_value) {
			return false;
		}
	}
	//All tests passed, so...
	return true;
}

function IsValidDate(month, day, year) {
	var blnRet;

	if (month ==  "" || day == "" || year == "") {
		return true;
	}

	day = parseInt(day)
	month = parseInt(month)
	year = parseInt(year)
	

	if( (day >= 1 && day <= 31) && 
		(month >=1 && month <= 12) && 
		(year > 0) ) {
		blnRet = true;
		switch(month) {
			case 2:
				
				if(day > 28) {
					// check for leap years
					if( ((year % 4 == 0) && (year % 100 != 0)) ||
						(year % 400 == 0) ) {
						if(day > 29) {
							blnRet =  false;
						}
					} else {
						blnRet = false;
					}
				}
				break;
			case 4:
			case 6:
			case 9:
			case 11:
				if(day > 30) {
					blnRet = false;
				}
				break;
			default:
				break;
		}
	} else {
		blnRet = false;
	}
		
	return blnRet;
}

function IsInteger(object_value)
{
    if (object_value.length == 0){
		return true;
	}

	var decimal_format = ".";
	var check_char;

    //The first character can be + -  blank or a digit.
	check_char = object_value.indexOf(decimal_format)

    //Was it a decimal?
	if (check_char < 1) {
		return IsNumeric(object_value);
	} else {
		return false;
	}
}


function IsNumeric(object_value)
{
	//Returns true if value is a number or is NULL
	//otherwise returns false	
	
	if (object_value.length == 0) {
		return true;
	}
	
	//	Returns true if value is a number defined as
	//	having an optional leading + or -.
	// 	having at most 1 decimal point.
	//	otherwise containing only the characters 0-9.
	var start_format = " .+-0123456789";
	var number_format = " .0123456789";
	var check_char;
	var decimal = false;
	var trailing_blank = false;
	var digits = false;
	
	//The first character can be + - .  blank or a digit.
	check_char = start_format.indexOf(object_value.charAt(0))
	//Was it a decimal?
	if (check_char == 1) {
		decimal = true;
	} else if (check_char < 1) {
		return false;
	}
	        
	//Remaining characters can be only . or a digit, but only one decimal.
	for (var i = 1; i < object_value.length; i++)
	{
		check_char = number_format.indexOf(object_value.charAt(i))
		if (check_char < 0) {
			return false;
		} else if (check_char == 1) {
			if (decimal) {		// Second decimal.
				return false;
			} else {
				decimal = true;
			}
		} else if (check_char == 0)	{
			if (decimal || digits) {
				trailing_blank = true;
			}
			// ignore leading blanks
		} else if (trailing_blank) {
			return false;
		} else {
			digits = true;
		}
	}	
	//All tests passed, so...
	return true
}

function IsNumberChar(ch)
{
	return (ch >= '0' && ch <= '9');
}

function IsAlphaChar(ch)
{
	return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || ( ch.charCodeAt(0) >= 0x05d0 && ch.charCodeAt(0) <= 0x05ea);
}

function IsAlphaNumeric(object_value)
{
	var i;
	var intLength, ch;
	intLength = object_value.length;
	
	for(i = 0; i < intLength; i++) 
	{
		ch = object_value.charAt(i);
		if(!(IsAlphaChar(ch) || IsNumberChar(ch))) {
			return false;
		}
	}
	return true;
}

function IsAlpha(object_value)
{
	var i;
	var intLength, ch;
	intLength = object_value.length;
	
	for(i = 0; i < intLength; i++) 
	{
		ch = object_value.charAt(i);
		if(!IsAlphaChar(ch)) {
			return false;
		}
	}
	return true;
}


function IsEmail(object_value, min_value)
{
	var i, ch, intAtCount, intDotPos, intLastDotPos;
	
	var strEmailChars = "_-@.~!#$%&*+\"'"

	var len = object_value.length;

	if (len == 0) {
		return true;
	}
	
	if (len < min_value) {
		return false;
	}
	
	intAtCount = 0;
	intDotPos = 0;
	for(i = 0; i < len; i++) {
		ch = object_value.charAt(i);
		
		if(!(	IsAlphaChar(ch) || 
				IsNumberChar(ch) ||
				strEmailChars.indexOf(ch) != -1) 
			) {
				return false;
		} else {
			if(ch == '@') {
				intAtCount++;
				if(intAtCount > 1) {
					return false;
				}
			} else if (ch == '.') {
				// don't allow consecutive .'s
				if (i - 1 == intLastDotPos) {
					return false;
				}
				intDotPos = i;
				intLastDotPos = i;
			}
		}
	}
	
	return (intDotPos > 0 && intAtCount > 0 && intDotPos < (len - 1));

}

function IsURL(object_value)
{
	var i, ch, intDotCount;
	
	var strURLChars = "~!@#$%*_+-:/.?&="
	
	var len = object_value.length;
	
	if (object_value.length == 0) {
		return true;
	}
	
	if (object_value.length < 10) {
		return false;
	}
	
	if	((object_value.indexOf("http://") == -1) &&
			(object_value.indexOf("https://") == -1) &&
			(object_value.indexOf("ftp://") == -1)) {
		return false;
	}
	
	intDotCount = 0;
	for(i = 0; i < len; i++) {
		ch = object_value.charAt(i);
		
		if(!(	IsAlphaChar(ch) || 
				IsNumberChar(ch) ||
				strURLChars.indexOf(ch) != -1) 
			) {
				return false;
		} else if(ch == '.') {
			intDotCount++;
		} 
	}
	
	return (intDotCount > 0);
	
}

function IsValidExtension(object_value, extensions)
{
	// ---------------Examples----------------
	// extensions -->   "jpeg, gif, zip"
	// object_value --> "chaka.zip"
	// ---------------------------------------

	var i, ch, intDotCount;
	var test_extension = "";
	var obj_extension = "";
	var len = object_value.length;

	if ((object_value == "") || (extensions == ""))
		return true;
		 
	// --------------------------------------------------
	// First get the extension of the object value
	// --------------------------------------------------
	for (i = len; i > 0; i--) {
		ch = object_value.charAt(i);
		if (ch == '.') {
			intDotCount = i;
			break;
		}
	}	
	
	for (i = (intDotCount + 1); i < len; i++) {
		obj_extension = obj_extension + object_value.charAt(i);
	}

	if (obj_extension.length == 0)
		return false;

	// --------------------------------------------------
	// Then, we compare that string to every extension we passed in
	// --------------------------------------------------

	extensions = extensions.toLowerCase();
	obj_extension = obj_extension.toLowerCase();

	len = extensions.length;
	test_extension = "";

	for (i = 0; i <= len; i++) {

		ch = extensions.charAt(i);

		if ((ch == ',') || (ch == ' ') || (i == len)) {
			if (test_extension.length == 0)
				continue;			
			if (test_extension == obj_extension)
				return true;
			test_extension = "";
		}
		else {
			test_extension = test_extension + ch;
		}
	}
	return false;
}

function LimitInput(field, countfield, maxlimit) 
{
	if (field.value.length > maxlimit) // if too long...trim it!
	{
		field.value = field.value.substring(0, maxlimit);
	}
	// otherwise, update 'characters left' counter
	else
	{
		if (countfield != null) 
			countfield.value = maxlimit - field.value.length;
	}
}
	
function IsCreditCard(object_value) {
  // Encoding only works on cards with less than 19 digits
  if (object_value.length > 19)
    return (false);
    
	// Use regular express to check credit card format
	var reg = /^3[4,7]\d{13}|3[0,6,8]\d{12}|((4\d{3})|(5[1-5]\d{2})|(6011)|(35\d{2}))\d{12}$/;
	if (reg.test(object_value) == false) 
	{
		return (false);
	 }
	// User Mod 10 
  sum = 0; mul = 1; l = object_value.length;
  for (i = 0; i < l; i++) {
    digit = object_value.substring(l - i - 1, l - i);
    tproduct = parseInt(digit ,10) * mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }

  if ((sum % 10) == 0)
    return (true);
  else
    return (false);

} // END FUNCTION isCreditCard()

/**********************************************************************************/
/* Form Validation: End															  */
/**********************************************************************************/

/**********************************************************************************/
/*	START - FORM OPTIONS (check or uncheck)										  */
/**********************************************************************************/
function UnCheckAllExceptThis(form_object, lngItem) {
	if (lngItem == null) {lngItem = 0};
	if (form_object[lngItem].checked == true) {
		var len = form_object.length;
		for (var i = 0; i < len; i++) {
			if (i != lngItem) {
				form_object[i].checked = false;
			}
		}
	}
}

/**********************************************************************************/
function UnCheckThis(form_object, lngItem) 
{
	form_object[lngItem].checked = false;
	var len = form_object.length;
	var uncheckedAll = true;
	for (var i = 0; i < len; i++){
		if (form_object[i].checked == true){
			uncheckedAll = false;
		}
	}
	if (uncheckedAll == true){
		form_object[0].checked = true;
	}
}

/**********************************************************************************/
/*	END - FORM OPTIONS (check or uncheck)										  */
/**********************************************************************************/

function AddPageToFavorites(strTitle)
{
	if (document.all) {
		if(strTitle.length == 0)
		{
			strTitle = document.title;
		}
		
		window.external.AddFavorite(document.location.href, strTitle);
	}
}


function addBookmark() 
{
	if (window.sidebar) 
	{
		window.sidebar.addPanel(document.title, document.location.href,"");
	} 
	else if(document.all) 
	{
		window.external.AddFavorite( document.location.href, document.title);
	} 
	else if( window.opera && window.print )
	{
	return true;
	}
} 


function SwitchImg(strSourceImgName, strNewImage) 
{ 
	if(document.images[strSourceImgName]) 
	{
		document.images[strSourceImgName].src = strNewImage;
		/*if (aryPhotos)
		{
			for (var j=0;j<aryPhotos.length;j++)
			{
				if (aryPhotos[j].toLowerCase() == strNewImage.toLowerCase())
					i = j;
			}
		}*/
	}
} 

function UpdateText(strTagName, strText)
{
	if(document.all[strTagName])
	{
		if(document.all[strTagName].innerHTML) 
		{
			document.all[strTagName].innerHTML = strText;
		}
	}
}

function onUnload()
{
	var i = window.screenTop; // close is always a big number
	if ( i > 9000 )
	{
		if ( typeof(popUnderLink) != "undefined" )
		{
			window.open(popUnderLink,"popwin","height=580,width=730,location=0,menubar=0,resizable=1,status=0,titlebar=0");
		}
	}
	else
	{
		// a window refresh
	}
} 

function ResetOnUnloadEvent()
{
	window.onunload=null;
}

function PopupInit()
{
    if (typeof(popupInitValues) != "undefined")
    {
        if (popupInitValues.length == 5)

        {
			launchWindow(popupInitValues[0], popupInitValues[1], popupInitValues[2], popupInitValues[3], popupInitValues[4]);
        }
    }
}

function PopInInit()
{
    if (typeof(popInInitValues) != "undefined" && popInInitValues.length == 1)
    {
        window.location = popInInitValues[0];
    }
}

// This function specifically for exit popups.  It will call PopupInit only if the window has been closed.
function ExitPopupInit()
{
	var i = window.screenTop; // Close is always a big number.
	if ( i > 9000 )
	{
		PopupInit();
	}
	else
	{
		// A window refresh.  Do nothing.
	}
}

/**********************************************************************************/
/*	BEGIN - PLUGIN DETECTION             										  */
/**********************************************************************************/

function detectPlugin(strName) {
  var agt=navigator.userAgent.toLowerCase();
  var ie  = (agt.indexOf("msie") != -1);
  var ns  = (navigator.appName.indexOf("Netscape") != -1);
  var win = ((agt.indexOf("win")!=-1) || (agt.indexOf("32bit")!=-1));
  var mac = (agt.indexOf("mac")!=-1);
  var pluginlist = "";

  if (ie && win) {	
    pluginlist = detectIE("Adobe.SVGCtl","SVG Viewer") 
                + detectIE("SWCtl.SWCtl.1","Shockwave Director") 
                + detectIE("ShockwaveFlash.ShockwaveFlash.1","Shockwave Flash") 
                + detectIE("rmocx.RealPlayer G2 Control.1","RealPlayer") 
                + detectIE("QuickTimeCheckObject.QuickTimeCheck.1","QuickTime") 
                + detectIE("MediaPlayer.MediaPlayer.1","Windows Media Player") 
                + detectIE("PDF.PdfCtrl.5","Acrobat Reader"); }
  if (ns || !win) {
  		nse = ""; 
  		for (var i=0;i<navigator.mimeTypes.length;i++) {
  		  nse += navigator.mimeTypes[i].type.toLowerCase();
  		}
  		pluginlist = detectNS("image/svg-xml","SVG Viewer") 
  		            + detectNS("application/x-director","Shockwave Director") 
  		            + detectNS("application/x-shockwave-flash","Shockwave Flash") 
  		            + detectNS("audio/x-pn-realaudio-plugin","RealPlayer") 
  		            + detectNS("video/quicktime","QuickTime") 
  		            + detectNS("application/x-mplayer2","Windows Media Player") 
  		            + detectNS("application/pdf","Acrobat Reader");
  }
  pluginlist += navigator.javaEnabled() ? "Java," : "";
  if (pluginlist.length > 0) pluginlist = pluginlist.substring(0,pluginlist.length-1);
  
  return pluginlist.indexOf(strName) != -1;
}
function detectNS(ClassID,name) { 
  n = ""; 
  if (nse.indexOf(ClassID) != -1) {
    if (navigator.mimeTypes[ClassID].enabledPlugin != null) { 
      n = name+","; 
    }
  }  
  return n; 
}

function detectIE(ClassID,name) { 
  result = false; 
  document.write('<SCRIPT LANGUAGE=VBScript>\n on error resume next \n result = IsObject(CreateObject("' + ClassID + '"))</' + 'SCRIPT>\n'); 
  if (result) {
    return name+','; 
  } else {
    return ''; 
  }
}  

/**********************************************************************************/
/*	END - PLUGIN DETECTION             										      */
/**********************************************************************************/
function stripWhiteSpace(txtField)
{
	if(txtField.value) {
		if(txtField.value.length > 0) {
			txtField.value = Replace(txtField.value, " ", "");
		}
	}
}

/**********************************************************************************/
/*	Open link in parent window.  If parnet window is closed
/*  then resize popup to height and width 
/**********************************************************************************/
function OpenLinkInParentWindow(href, width, height)
{
	var Parent = window.opener; 

	//alert("hehehe");
	///alert(href);

	var blnParentExists = false;
	
	var sType = typeof(Parent);

	if(sType.toLowerCase() != 'undefined')
	{
		blnParentExists = true;
		
	}

	if (blnParentExists)
	{
		Parent.location = href;
		window.close(); 	
	}
	else
	{
		window.resizeTo(width, height);
		window.location = href;
	}
}

/********************************************************************************/
/*  FUNCTION to check CSS Navigation Elements
/********************************************************************************/
function init()
{
	cssjsmenu('navbar');
	//cssjsmenu('navBarTop'); not in use anywhere
	initOnlineChecker(false);//start checking IMs (on most pages that use standard template - false means don't ignore time limit)
}

/********************************************************************************/
/*  FUNCTION to switch StyleSheets
/********************************************************************************/
//Enables the appropriate style sheet for the current font size
//NOTE: this causes the page to re-render
function setActiveStyleSheet(title)
{
	var i, a, main;
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++)
	{
		if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title"))
		{
			a.disabled = true;
			if(a.getAttribute("title") == title) a.disabled = false;
		}
	}
	
	//setFontSizer(title);
}

//highlights the 'A' on the font sizer that corresponds to the current font size
/*function setFontSizer(title)
{
	var today		= new Date();
	var expires		= new Date(today.getTime() + (365 * 86400000));  //number of ms in a day
	var smallNode	= document.getElementById('fontSmall');
	var mediumNode	= document.getElementById('fontMedium');
	var largeNode	= document.getElementById('fontLarge');
    
	if (smallNode != null && mediumNode != null && largeNode != null)
	{
		switch (title)
		{
			case 'medium' :
				smallNode.className		= 'fontBoxSmall';
				mediumNode.className	= 'fontBoxMediumOn';
				largeNode.className		= 'fontBoxLarge';
				break;
			case 'large' :
				smallNode.className		= 'fontBoxSmall';
				mediumNode.className	= 'fontBoxMedium';
				largeNode.className		= 'fontBoxLargeOn';
				break;
			default :
				smallNode.className		= 'fontBoxSmallOn';
				mediumNode.className	= 'fontBoxMedium';
				largeNode.className		= 'fontBoxLarge';
		}
	}
	spark_setCookie('mn_styleSheetPref', title, expires, '/');  
}*/


/********************************************************************************/
/*  FUNCTION to show / hide divs like in FAQ section
/ added elementType for showing/hiding non-block elements
/********************************************************************************/
function showHideDiv(sDivId,hDivId,elementType)
{
  if (elementType = "span") {
  	var sDiv = document.getElementById(sDivId);
  	var hDiv = document.getElementById(hDivId);
  	
  	sDiv.className = "showSpan";
  	hDiv.className = "hideSpan";
  }

  else {
  	var sDiv = document.getElementById(sDivId);
  	var hDiv = document.getElementById(hDivId);
  	
  	sDiv.className = "show";
  	hDiv.className = "hide";
  }
}

function changeClassStyle(changeThisDivId, changeToThisClass){
	document.getElementById(changeThisDivId).className=changeToThisClass;
}

function changeDivBgImage(changeThisDivBgImage,changeThisDivBgImagePath){
	bgImagePath = "url(" + changeThisDivBgImagePath + ")";
	document.getElementById(changeThisDivBgImage).style.backgroundImage=bgImagePath;
}

function swapState(object, strDiv, strSelect, strDeselect, strHideDiv, strShowDiv, strHide, strShow)
{
    var hotlist = document.getElementById(strDiv);
    var hotlistSelectText   = document.getElementById(strSelect);
    var hotlistDeselectText = document.getElementById(strDeselect);

    if (object.checked)
    {
        hotlist.className = strHideDiv;
        hotlistSelectText.className = strHide;
        hotlistDeselectText.className = strShow; 
    }
    else
    {
        hotlist.className = strShowDiv;
        hotlistSelectText.className = strShow;
        hotlistDeselectText.className = strHide;
    }
    
}


/********************************************************************************/
/*  FUNCTION to handle mouseovers of mini profile.  Also handles voting.  Legacy code.  -wel
/********************************************************************************/

function YNMMouseOver(sender, parentClientID, type)
{
	
	if ((document.forms[window.document.forms[0].name].elements[parentClientID + "_YNMVoteStatus"].value & type) != type)
	{
		YNMSwap(sender);
	}
}

function YNMMouseOut(sender, parentClientID, type)
{
	if ((document.forms[window.document.forms[0].name].elements[parentClientID + "_YNMVoteStatus"].value & type) != type)
	{
		YNMSwap(sender);
	}
	
}

function YNMSwap(img)
{
	var imageOffIndex = img.src.indexOf('off.gif');
	var imageOnIndex = img.src.indexOf('on.gif');
	
	img.src = (imageOffIndex == -1) 
		? (img.src.substr(0, imageOnIndex) + 'off.gif')
		: (img.src.substr(0, imageOffIndex) + 'on.gif'); 
}

function SetYNMImage(img, highlight, type, parentClientID)
{
	var imageOffIndex = img.src.indexOf('off.gif');
	var imageOnIndex = img.src.indexOf('on.gif');
	
	if (highlight)
	{
		if ((document.forms[window.document.forms[0].name].elements[parentClientID + "_YNMVoteStatus"].value & type) == type)
		{
			return;
		}
		else
		{
			if (imageOnIndex != -1)
			{
				img.src = img.src.substr(0, imageOnIndex) + 'on.gif'
			}
			else
			{
				img.src = img.src.substr(0, imageOffIndex) + 'on.gif'
			}
		}
	}
	else
	{
		if (imageOffIndex != -1)
		{
			img.src = img.src.substr(0, imageOffIndex) + 'off.gif'
		}
		else
		{
			img.src = img.src.substr(0, imageOnIndex) + 'off.gif'
		}		
	}
}

function SetBothSaidYes(parentClientID, visibility)
{
	var divBothSaidYes = document.getElementById(parentClientID + "_divBothSaidYes");
	var imgBothSaidYes = document.getElementById(parentClientID + "_imgBothSaidYes");

	if (divBothSaidYes != null)
		divBothSaidYes.style.visibility = visibility;
	if (imgBothSaidYes != null)
		imgBothSaidYes.style.visibility = visibility;
}

function ShowMutualYes(divMutualYesID, divVoteButtonsID)
{
	// This function is used by the YNMVoteBarSmall object to hide the YNM buttons and show the MutualYes icon
	var divMutualYes = document.getElementById(divMutualYesID);
	var divVoteButtons = document.getElementById(divVoteButtonsID);

	if (divMutualYes != null)
		divMutualYes.style.display = "block";
	if (divVoteButtons != null)
		divVoteButtons.style.display = "none";

}

//This function gets called only when voting from ViewProfile.
function ProfileYNMVote(type, encryptedParams)
{
	if (ConfirmYNMVote(HeaderYNMVoteBarID, type))
	{
		SaveYNMVote(type, encryptedParams);
		ProcessYNMVote(HeaderYNMVoteBarID, type, encryptedParams);
		ProcessYNMVote(FooterYNMVoteBarID, type, encryptedParams);
	}
}


function YNMVote(parentClientID, type, encryptedParams)
{
	if (ConfirmYNMVote(parentClientID, type))
	{
		SaveYNMVote(type, encryptedParams);	
		ProcessYNMVote(parentClientID, type, encryptedParams);
	}
}

//If necessary, displays a prompt to confirm that the user wants to change his/her YNM vote.
function ConfirmYNMVote(parentClientID, type)
{
	var currentStatus = document.forms[window.document.forms[0].name].elements[parentClientID + "_YNMVoteStatus"];
	var process = true;
	
	//only the three least significant bits are used to indicate whether you have voted for this member
	//the more significant bits indicate whether they have voted for you, so ignore them
	currentVote = currentStatus.value & 7;
	
	//Type =				1 for yes, 2 for no, 3 for maybe
	//but currentVote =		1 for yes, 2 for no, 4 for maybe
	//so typeStatusMask is a value we can compare to currentStatus
	var typeStatusMask = type;	
	if (type == "3")
		typeStatusMask = 4;
		
	var hasVote = (currentVote > 0);
	
	// bypass confirmation on existing selection and no previous selection
	if(hasVote && currentVote != typeStatusMask)
	{
		//18106 for FireFox: can't getElementByID because form elements only had name property - not ID
		process = confirm(document.forms[0].elements['js_ynmConfirmText'].value);
	}
	
	return process;
}

//Updates the images and the hidden form input to reflect the new YNM vote.
function ProcessYNMVote(parentClientID, type)
{
	var currentStatus = document.forms[window.document.forms[0].name].elements[parentClientID + "_YNMVoteStatus"];

	switch (type)
	{
		case "1":
			SetYNMImage(document.getElementById(parentClientID + "_ImageYes"), true, type, parentClientID);
			SetYNMImage(document.getElementById(parentClientID + "_ImageMaybe"), false, type, parentClientID);
			SetYNMImage(document.getElementById(parentClientID + "_ImageNo"), false, type, parentClientID);
			if ((currentStatus.value & 2) == 2)
			{
				currentStatus.value = currentStatus.value ^ 2;
			}
			if ((currentStatus.value & 4) == 4)
			{
				currentStatus.value = currentStatus.value ^ 4;
			}
			currentStatus.value = currentStatus.value | 1;
			
			//If the other user has clicked yes, display the "you both clicked yes" icon:
			if ((currentStatus.value & 8) == 8)
				SetBothSaidYes(parentClientID, "visible");
			
			break;

		case "2":
			SetYNMImage(document.getElementById(parentClientID + "_ImageYes"), false, type, parentClientID);
			SetYNMImage(document.getElementById(parentClientID + "_ImageMaybe"), false, type, parentClientID);
			SetYNMImage(document.getElementById(parentClientID + "_ImageNo"), true, type, parentClientID);
			if ((currentStatus.value & 1) == 1)
			{
				currentStatus.value = currentStatus.value ^ 1;
			}
			if ((currentStatus.value & 4) == 4)
			{
				currentStatus.value = currentStatus.value ^ 4;
			}
			currentStatus.value = currentStatus.value | 2;
			
			//Hide the "you both clicked yes" icon:
			SetBothSaidYes(parentClientID, "hidden");
			break;			

		case "3":
			SetYNMImage(document.getElementById(parentClientID + "_ImageYes"), false, type, parentClientID);
			SetYNMImage(document.getElementById(parentClientID + "_ImageMaybe"), true, type, parentClientID);
			SetYNMImage(document.getElementById(parentClientID + "_ImageNo"), false, type, parentClientID);
			if ((currentStatus.value & 1) == 1)
			{
				currentStatus.value = currentStatus.value ^ 1;
			}
			if ((currentStatus.value & 2) == 2)
			{
				currentStatus.value = currentStatus.value ^ 2;
			}
			currentStatus.value = currentStatus.value | 4;
			
			//Hide the "you both clicked yes" icon:
			SetBothSaidYes(parentClientID, "hidden");
			break;
	}
}

//Saves the YNM vote to the DB
function SaveYNMVote(type, encryptedParams)
{
	if(window.frames["FrameYNMVote"] != null)
	{
		window.frames["FrameYNMVote"].location.href = "/Applications/MemberProfile/AttractionBarSave.aspx?YNMLT=" + type + "&ynmp=" + encryptedParams;	
	}
}

function GoToNextIfHaveVoted(destinationUrl, message)
{
	var str;
	var index;
	var currentName;
	var currentValue;
	
	for (var i = 0; i < document.forms[window.document.forms[0].name].elements.length; i++)
    {
		currentName = document.forms[window.document.forms[0].name].elements[i].name;
		index = currentName.indexOf("YNMVoteStatus");
		if(index != -1)
		{
			currentValue = document.forms[window.document.forms[0].name].elements[i].value;
			break;
		}
    }
    
    if(index == -1)
    {
	}
    else
    {
		// ensure there is a vote value and that the vote value pertains to the member's votes
		if(currentValue > 0 && currentValue != 8 && currentValue != 16 && currentValue != 32)
		{
			// vote has been cast already
			window.location = destinationUrl;
			return;
		}
    }
    
    alert(message);

	return;
}

/********************************************************************************/
/*  FUNCTION to format link for deleting a hot list member.  taken from legacy site.
/********************************************************************************/
function UnListHotList(byMember, toMember, strMsg, strConfirmation)
{
	if(confirm(strMsg))
	{
		window.location="/Applications/HotList/View.aspx?a=delete&MemberID="+byMember+"&ToMemberID="+toMember+"&FromMemberID="+byMember+"&rc="+strConfirmation;
	}
	else{}
}

// Private method to open IM pop-up window
// This method should not be called from outside. The purpose of the strDestinationMemberId
// parameter is simply to create a unique browser window name.
// Use LaunchNewIMConversation or JoinIMConversation instead
function launchImWindow(strURL, strDestinationMemberId)
{
	//set width and height amd properties of browser window
	var intWidth = 468;
	var intHeight = 560;
	var uniquewindowname = "IM" + strDestinationMemberId;
	var strProperties = "height=" + intHeight + ",width=" + intWidth + "," + "status=yes, Resizable=no,scrollbars=no,status=no";

	//check to see if IM window is already open
	//(this is a javascript trick to return a reference by target name without specifying URL - it opens about:blank)
	var imWindowHandle = window.open("",uniquewindowname,strProperties);
	//handle permission denied errors by closing window first, then re-opening (16725)
	var imWindowLocationIsDeniedBecauseOutsideDomain = false;
	try 
	{
		if (imWindowHandle)
		{
			//try and get the location of the IM window. This will raise a permission denied security error
			//if the open window is on another domain (security built-in to browser)
			var imWindowLocationTemp = imWindowHandle.location.href;
		}
	}
	catch(e) 
	{
		//alert("IM window already open, but on another domain. This causes a security error: " + e.message);
		imWindowLocationIsDeniedBecauseOutsideDomain = true;
		//closes window then re-opens it, thereby avoiding permission denied error (and erasing any ongoing conversations)
		imWindowHandle.close();
		imWindowHandle = window.open(strURL,uniquewindowname,strProperties);
	}
	//only continue if no security problems with IM window outside current domain
	if (!imWindowLocationIsDeniedBecauseOutsideDomain 
		&& imWindowHandle
		&& imWindowHandle.location.href.indexOf(strURL) >= 0
		&& !imWindowHandle.closed){
	
		//if it exists, and the URL is the IM URL, simply bring window into focus
		//without refreshing (so as not to lose any ongoing IM conversation text)
		imWindowHandle.focus();
	}
	else {
		if (imWindowHandle) {
		imWindowHandle.location.href = strURL;
		imWindowHandle.focus(); //bring into focus for good measure, although may be unncessary
		}
		else {
			//probably a pop-up blocker... do nothing :( TODO: resource in other languages
			//alert("use of Instant Messenger requires pop-up blocker to be disabled.");
		}
	}
	
	//did not use launchWindow function because that would always refresh the page (and thereby
	//potentially cause the loss of any ongoing instant message text conversation
	// launchWindow(strURL , uniquewindowname , width , height , strproperties);
}

// Launches new Instant Messenger window from Whos online 
// and search pages (replaces former LaunchDotNetIMByMemberID)
// strDestinationMemberId is the member ID of the user that the user wants to initiate a conversation with
function LaunchNewIMConversation(strDestinationMemberId) {


	//append ID of destination member ID
   var url = GetInstantMessengerPath() + '?DestinationMemberID=' + strDestinationMemberId;
   launchImWindow(url,strDestinationMemberId);
   
}

// Launches Instant Messenger window from a user choosing
// "Yes" to join an IM initiated by other user (see ImYes)
// Requires the conversation ID of the conversation user wishes to join
// and the member id of the user that the user is accepting a conversation with
function JoinIMConversation(strDestinationMemberId, strConversationKey) {

   var url = GetInstantMessengerPath() + '?DestinationMemberID=' + strDestinationMemberId
		+ '&ConversationKey=' + strConversationKey;
		launchImWindow(url,strDestinationMemberId);
}


// Gets the path to the aspx page that hosts the Instant Messenger application
function GetInstantMessengerPath() {

	// if the location.hostname is a production site and does NOT include the 'www' prefix, we need to add it.
	// Userplane DHTML (Hebrew version will not function correctly without the host prefix. 
	// (this is as of 8/23/05 bug 14968)
	var urlPrefix = '';
	
	if ('cupid.co.il' == location.hostname.toLowerCase())
	{
		urlPrefix = 'http://www.cupid.co.il';
	}
	if ('jdate.co.il' == location.hostname.toLowerCase())
	{
		urlPrefix = 'http://www.jdate.co.il';
	}
	// link to IM should not be to secure site - remove https
	if (location.href.indexOf('https') > -1)
	{
		urlPrefix = "http://" + location.hostname;
	}

   return urlPrefix + '/Applications/InstantMessenger/upInstantCommunicator.aspx'
 
}

// Loops through the validators on the page and focuses on the first failed control
function ClientValidateAndFocus()
{
	var x;
	
	// Run the page validation then evaluate the validators
	Page_ClientValidate();
	
	for(x in Page_Validators)
	{
		if(!Page_Validators[x].isvalid)
		{
			badControl = document.getElementById(Page_Validators[x].controltovalidate);
			
			if(badControl != null)
				badControl.focus();
			break;
		}
	}
}

function CaseInsensitiveCompareValidatorEvaluateIsValid(val)
{
	var valueToValidate = ValidatorTrim(ValidatorGetValue(val.controltovalidate));
	var valueToCompare = ValidatorTrim(ValidatorGetValue(val.controltocompare));
	
	if( valueToValidate != null && valueToCompare != null )
	{
		if( valueToValidate.toLowerCase() == valueToCompare.toLowerCase() )
		{
			return true;
		}
	}
	
	return false;
}

function MultiValidatorEvaluateIsValid(val)
{	
	try
	{
		var valueToValidate =
				ValidatorTrim(ValidatorGetValue(val.controltovalidate));
				
		var controlToValidate = document.forms[window.document.forms[0].name].elements[val.controltovalidate];
		
		if ( val.isRequired == 'False' && valueToValidate.length == 0 )
			return true;
			
		if ( val.isRequired == 'True') 
		{
			if (controlToValidate.type == 'checkbox')
			{
				if (!controlToValidate.checked)
				{
					val.innerText = '';
					val.innerHTML = val.requiredErrorMessage;
					
					MultiValitorSetControlFocus(val.controltovalidate);
					
					return false;
				}
				else
				{	// Valid checkbox, exit validation script.
					return true;
				}
			}
			
			if ( valueToValidate.length == 0 )
			{
				val.innerText = val.requiredErrorMessage;
				
				if ( val.showPopup == 'True' )
				{
					alert(val.innerText);
				}
				else
				{
					if (val.appendToErrorMessage.length != 0)
					{
						val.innerText = '';
						val.innerHTML = val.requiredErrorMessage;
						val.innerHTML += val.appendToErrorMessage;
					}
				}				

				MultiValitorSetControlFocus(val.controltovalidate);
				
				return false;
			}
		}
		
		if ( val.maxLength != '0' )
		{
			if (valueToValidate.length > parseInt(val.maxLength, 10)) 
			{
				val.innerText = val.maximumLengthErrorMessage;
				
				if ( val.showPopup == 'True' )
				{
					alert(val.innerText);
				}
				else
				{
					if (val.appendToErrorMessage.length != 0)
					{
						val.innerText = '';
						val.innerHTML = val.maximumLengthErrorMessage;
						val.innerHTML += val.appendToErrorMessage;
					}
				}

				MultiValitorSetControlFocus(val.controltovalidate);

				return false;
			}
		}
		
		if ( val.minLength != '0' )
		{
			if ( valueToValidate.length < parseInt(val.minLength, 10 ))
			{
				val.innerText = val.minimumLengthErrorMessage;
				
				if ( val.showPopup == 'True' )
				{
					alert(val.innerText);
				}
				else
				{
					if (val.appendToErrorMessage.length != 0)
					{
						val.innerText = '';
						val.innerHTML = val.minimumLengthErrorMessage;
						val.innerHTML += val.appendToErrorMessage;
					}
				}

				MultiValitorSetControlFocus(val.controltovalidate);

				return false;
			}
		}
		
		if ( val.minVal != '0' )
		{
			if ( valueToValidate < parseInt(val.minVal, 10 ))
			{
				val.innerText = val.minValErrorMessage;
				
				if ( val.showPopup == 'True' )
				{
					alert(val.innerText);
				}
				else
				{
					if (val.appendToErrorMessage.length != 0)
					{
						val.innerText = '';
						val.innerHTML = val.minValErrorMessage;
						val.innerHTML += val.appendToErrorMessage;
					}
				}

				MultiValitorSetControlFocus(val.controltovalidate);

				return false;
			}
		}
		
		if ( val.maxVal != '0' )
		{
			if ( valueToValidate > parseInt(val.maxVal, 10 ))
			{
				val.innerText = val.maxValErrorMessage;
				
				if ( val.showPopup == 'True' )
				{
					alert(val.innerText);
				}
				else
				{
					if (val.appendToErrorMessage.length != 0)
					{
						val.innerText = '';
						val.innerHTML = val.maxValErrorMessage;
						val.innerHTML += val.appendToErrorMessage;
					}
				}

				MultiValitorSetControlFocus(val.controltovalidate);

				return false;
			}
		}		

		if ( val.requiredTypeRegEx.length > 0 )
		{
					
			if (valueToValidate == "")
				return true;        
				
			var rx = new RegExp(val.requiredTypeRegEx);
			var matches = rx.exec(valueToValidate);
			if ( !  (matches != null && valueToValidate == matches[0]) )
			{
				val.innerText = val.requiredTypeErrorMessage;
				
				if ( val.showPopup == 'True' )
				{
					alert(val.innerText);
				}
				else
				{
					if (val.appendToErrorMessage.length != 0)
					{
						val.innerText = '';
						val.innerHTML = val.requiredTypeErrorMessage;
						val.innerHTML += val.appendToErrorMessage;
					}
				}

				MultiValitorSetControlFocus(val.controltovalidate);

				return false;
			}
		}
	}
	catch(Ex)
	{
	}
	
	return true;
}

var isValidationFocusSet = false;
function MultiValitorSetControlFocus(controlToValidate)
{
	if (! isValidationFocusSet)
	{
		document.forms[window.document.forms[0].name].elements[controlToValidate].focus();
		isValidationFocusSet = true;
	}
}


var onListMenu = false

///The function that governs Add2List control (adding to Hotlist)
///Note: onblur in Safari will only work on INPUT, TEXTAREA and SELECT elements.
function ToggleDisplay(element, Visible)
{
	var menu = document.getElementById('smenu' + element);
	
	if(Visible == false)
	{
		if(onListMenu == false)
		{
			menu.style.display = 'none';
		}
	}
	else
	{
		menu.style.display = 'block';
	}
}

function setHighlight(Over)
{
	onListMenu = Over;
}

function ChangeImage(ImageName, NewImage, Directory)
{
if (document.images)
        {
        if (String (Directory) != "undefined")
                document[ImageName].src = Directory + "/" + NewImage;
        else
                document[ImageName].src = "images/" + NewImage;
        }
        
}

/// This method checks if the Enter key was pressed, and if it was, fires the click 
/// event for the given button object. This method is called from the onkeydown
/// event on textboxes where you want the enter key to submit the form or fire
/// validation. This method expects to receive a button object, NOT a string id or name.
/// (You can apparently pass an object to this method by calling the name of 
/// button object directly, but only if the object is inside a <form> tag
/// in FireFox (IE is more forgiving)). Also, IE recognizes the event.KeyCode
/// property while FF and others do not. Likewise, IE does NOT recognize the
/// event.which property, hence you must use browser detection techniques 
/// before checking if the Enter key was pressed.
function setAutoSubmitButton(btn, event)
{
	// accounts for IE
	if (document.all)
	{
		if (event.keyCode == 13)
		{
			event.returnValue=false;
			event.cancel = true;
			btn.click();
		}
	}
	// accounts for FF and NN
	else if (window.sidebar) 
	{
		if(event.which == 13)
		{
			event.returnValue=false;
			event.cancel = true;
			btn.click();
		}	
	}
	// accounts for others 
	// 18285 - use a string to represent the id of a button object (not the object) itself when using getElementById
	else if(document.getElementById(btn.id))
	{
		if (event.which == 13)
		{
			event.returnValue=false;
			event.cancel = true;
			btn.click();
		}	
	}
	// accounts for others
	else if(document.layers)
	{
		if(event.which == 13)
		{
			event.returnValue=false;
			event.cancel = true;
			btn.click();
		}		
	}
}


function readKey(e) 
{
	//window.status = e.keyCode;
	//alert(e.keyCode);
}
//document.onkeypress = readKey;


/********************************************************************************/
/*  FUNCTION to float div over content
/********************************************************************************/
 function MM_findObj(n, d) { //v4.01
 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
 d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
 if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
 for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
 if(!x && d.getElementById) x=d.getElementById(n); return x;
 }

 function MM_showHideLayers() { //v6.0
 var i,p,v,obj,args=MM_showHideLayers.arguments;
 for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
 if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
 obj.visibility=v;}
 }
 
 
function QueryString(qs) 
{
	if(qs.length > 1) 
	{
		this.qs = qs.substring(1, qs.length);
	}
	else 
	{
		this.qs = null;
	}

	this.keyValuePairs = new Array();
	
	if(qs) 
	{
		for(var i=0; i < this.qs.split("&").length; i++) 
		{
			this.keyValuePairs[i] = this.qs.split("&")[i];
		}
	}
	
	this.getKeyValuePairs = function() 
	{ 
		return this.keyValuePairs; 
	}
	
	this.getValue = function(keyvalue) 
	{
		for(var i=0; i < this.keyValuePairs.length; i++) 
		{
			if(this.keyValuePairs[i].split("=")[0] == keyvalue)
			{
				return this.keyValuePairs[i].split("=")[1];
			}
		}
		return false;
	}
	
	this.getLength = function() 
	{ 
		return this.keyValuePairs.length; 
	} 
	
	// removes a querystring parameter ("&key=value" turns to "" and "?key=value" turnes to "?")
	this.RemoveQueryKey = function(queryKey, location) 
	{
		for(var i=0; i < this.keyValuePairs.length; i++) 
		{
			if(this.keyValuePairs[i].split("=")[0] == queryKey)
			{
				var retval;
				retval = location.toString().replace("&" + queryKey + "=" + this.getValue(queryKey), "");
				retval = retval.toString().replace("?" + queryKey + "=" + this.getValue(queryKey), "?");
				return retval;
			}
		}
		return false;
	}
	
	this.ReplaceQueryKey = function(queryKey, replaceValue, location) 
	{
		for(var i=0; i < this.keyValuePairs.length; i++) 
		{
			if(this.keyValuePairs[i].split("=")[0] == queryKey)
			{
				var retval;
				retval = location.toString().replace("&" + queryKey + "=" + this.getValue(queryKey), "&" + queryKey + "=" + replaceValue);
				retval = retval.toString().replace("?" + queryKey + "=" + this.getValue(queryKey), "?" + queryKey + "=" + replaceValue);
				return retval;
			}
		}
		return false;
	}
}
	
function RemoveRC(startRow)
{
	var page = new QueryString(window.location.search);
	var rc = page.getValue("rc");
	var newUrl = page.RemoveQueryKey("rc", window.location.toString());
	newUrl = page.ReplaceQueryKey("StartRow", startRow, newUrl);
	if(rc != false)
	{
		window.location.replace(newUrl);
	}
}

//
// This is where the file formerly called dg_dhtmlNotifier.js has been appended to this one - lucena
//

var dg_dhtmlNotifier_CONST_ALERT_WIDTH       = 165;
var dg_dhtmlNotifier_CONST_DIRECTION_LEFT    = 'left';
var dg_dhtmlNotifier_CONST_DIRECTION_RIGHT   = 'right';
var dg_dhtmlNotifier_CONST_DIRECTION_UP      = 'up';
var dg_dhtmlNotifier_CONST_ALERT_HEIGHT      = 97;
var dg_dhtmlNotifier_CONST_VISIBLE_LEFT      = -10; //Original value was 5.						20070406 modified by RB  
var dg_dhtmlNotifier_CONST_INVISIBLE_LEFT    = dg_dhtmlNotifier_CONST_VISIBLE_LEFT - dg_dhtmlNotifier_CONST_ALERT_WIDTH;
var dg_dhtmlNotifier_CONST_TOP_POSITION      = -25;
var dg_dhtmlNotifier_CONST_MAJOR_STEP_PIXELS = 6; 
var dg_dhtmlNotifier_CONST_MINOR_STEP_PIXELS = 1;
var dg_dhtmlNotifier_CONST_STEP_TIME         = 20;

var dg_dhtmlNotifier__transInEffect          = false;    

// Holder of active IMs, array of { alertId:text, visible:bool, html:string }
var dg_IMAlerts = new Array();

function dg_IMFromChild(fromChildList)
{
    dg_IMLoad(fromChildList);
    dg_dhtmlNotifier_setStartingPositions(); 
    dg_dhtmlNotifier_displayIMAlerts();
    dg_dhtmlNotifier_removeOldIMAlerts(fromChildList);

}

//This function removes any old IM alerts that are no longer valid due to initiator closing window, or timeout 16615
function dg_dhtmlNotifier_removeOldIMAlerts(newAlerts) {

	if (typeof(newAlerts) == 'undefined' || !newAlerts || !newAlerts.length)
	{
		//remove ALL current alerts
		for (var i = 0; i < dg_IMAlerts.length; i++) 
		{
			//dg_dhtmlNotifier_deleteIMAlert(dg_IMAlerts[i].alertId);
			dg_dhtmlNotifier_moveNode(dg_IMAlerts[i].alertId, dg_dhtmlNotifier_CONST_INVISIBLE_LEFT, 'left');
		}
	}
	else {
		//loop through existing alerts on page if any
		for (var i = 0; i < dg_IMAlerts.length; i++) 
		{
			//if not in the "new" alert list, then remove this alert
			if (dg_IMIsOld(dg_IMAlerts[i].alertId,newAlerts))
			{
				//dg_dhtmlNotifier_deleteIMAlert(dg_IMAlerts[i].alertId);
				dg_dhtmlNotifier_moveNode(dg_IMAlerts[i].alertId, dg_dhtmlNotifier_CONST_INVISIBLE_LEFT, 'left');
			}
		}
	}
    
}

//Returns true if dhtml alert is no longer in the "new" alert list that arrived from middle tier
function dg_IMIsOld(alertId, newAlerts)
{
	//loop through all "new" alerts
	for (var i = 0; i < newAlerts.length; i++) 
	{
		if (newAlerts[i].alertId == alertId) {
			//keep this alert around - because it's in the alert list from the middle tier
			return false;
		}
	}
	return true
}

// Method for when user selects "Yes" to accepting an Instant Message conversation
// initiated by another user
// strDestinationMemberId is the id of the member to which the user is accepting
// a conversation
function IMYes(strDestinationMemberId, conversationInvitationKey)
{
   var alertId = 'alertId_' + strDestinationMemberId;
   //make the notifier go away (don't know why or how this code works, but passing in 'left' is the key)
   dg_dhtmlNotifier_moveNode(alertId, dg_dhtmlNotifier_CONST_INVISIBLE_LEFT, 'left');

	//open up IM window and accept conversation invitation
	JoinIMConversation(strDestinationMemberId, conversationInvitationKey);
	
	removeInvitation(conversationInvitationKey,false);//make AJAX call to accept (isRejection false)
}

// Method for when user selects "No" to accepting an Instant Message conversation
// invitation initiated by another user.
// strDestinationMemberId is the id of the member to which the user is rejecting
// a conversation 
function IMNo(strDestinationMemberId, conversationInvitationKey)
{
	var alertId = 'alertId_' + strDestinationMemberId;
	
	//make the notifier go away (don't know why or how this code works, but passing in 'left' is the key)
	dg_dhtmlNotifier_moveNode(alertId, dg_dhtmlNotifier_CONST_INVISIBLE_LEFT, 'left');
	
	removeInvitation(conversationInvitationKey,true);//make AJAX call to reject (isRejection true)
	//send a rejection message to the sender (call IFRAME with cmd.swf file)
	var url = GetInstantMessengerPath() + '?DestinationMemberID=' + strDestinationMemberId
		+ '&ConversationKey=' + conversationInvitationKey
		+ '&RejectIM=true';
	var r=null; r=window.frm_rejectim; if (r !=null) r.location.replace(url);

	
}

function dg_IMLoad(newAlerts)
{    
    var domIMAlerts = document.getElementById('IMAlerts');
    
	var newHTML = "";

	if (typeof(newAlerts) == 'undefined' || !newAlerts || !newAlerts.length)
		return;

	for (var i = 0; i < newAlerts.length; i++) 
	{
		var xna = newAlerts[i];
		if (dg_IMIsNew(xna.alertId)) 
		{
			dg_IMAlerts.push(xna);
			if(xna.html != null)
			{
				newHTML += xna.html;
			}
		}
	}
    
    if (domIMAlerts != null && newHTML != null)
	{
		domIMAlerts.innerHTML += newHTML;
	}
}

function dg_IMIsNew(alertId)
{
    if (alertId == null) return false;
	for (var i = 0; i < dg_IMAlerts.length; i++) {
	  if (dg_IMAlerts[i].alertId == alertId)
		return false;
	}
    return true;
}


function dg_dhtmlNotifier_displayIMAlerts()
{
    if (dg_IMAlerts == null 
        || dg_dhtmlNotifier_CONST_VISIBLE_LEFT == null 
        || dg_dhtmlNotifier_CONST_DIRECTION_RIGHT == null 
        || dg_dhtmlNotifier__transInEffect == null)
    {
        return;
    }
    
    for (var i = 0; i < dg_IMAlerts.length; i++) {
		var xna = dg_IMAlerts[i];
        var element = document.getElementById(xna.alertId);

        if (element != null)
        {
            var currentLeft = parseInt(element.style.left.replace(/px/, ''), 10);

            if (currentLeft != dg_dhtmlNotifier_CONST_VISIBLE_LEFT)
            {
                if (!dg_dhtmlNotifier__transInEffect)
                {
                    dg_dhtmlNotifier_moveNode(xna.alertId, 
						dg_dhtmlNotifier_CONST_VISIBLE_LEFT, 
                        dg_dhtmlNotifier_CONST_DIRECTION_RIGHT);
                }
                else
                {
                    setTimeout('dg_dhtmlNotifier_displayIMAlerts()', 1000);
                    break;
                }
            }
        }
    }
}

function dg_dhtmlNotifier_setStartingPositions()
{
    if (dg_dhtmlNotifier_CONST_TOP_POSITION == null 
        || dg_IMAlerts == null 
        || dg_dhtmlNotifier_CONST_ALERT_WIDTH == null 
        || dg_dhtmlNotifier_CONST_ALERT_HEIGHT == null)
    {
        return;
    }
    
    var startTop = dg_dhtmlNotifier_CONST_TOP_POSITION;
    
    for (var i = 0; i < dg_IMAlerts.length; i++)
    {
		var xna = dg_IMAlerts[i];
        var element = document.getElementById(xna.alertId);
        
        if (element != null)
        {
            if (!xna.visible)
            {
                element.style.position  = 'absolute';
                element.style.top       = startTop + 'px';
				element.style.left = dg_dhtmlNotifier_CONST_INVISIBLE_LEFT + 'px';
            }

            startTop += dg_dhtmlNotifier_CONST_ALERT_HEIGHT;
        }
    }
}

function dg_dhtmlNotifier_setNodeVisibility(nodeId, visible)
{
    if (nodeId == null || visible == null || dg_IMAlerts == null)
        return;
    
    for (var i = 0; i < dg_IMAlerts.length; i++) {
		var xna = dg_IMAlerts[i];
        if (nodeId == xna.alertId) {
            xna.visible = visible;
            break;
        }
    }
}

function dg_dhtmlNotifier_moveNode(nodeId, to, direction)
{
    if (nodeId == null || to == null || direction == null 
        || dg_dhtmlNotifier__transInEffect == null 
        || dg_dhtmlNotifier_CONST_DIRECTION_RIGHT == null
        || dg_dhtmlNotifier_CONST_DIRECTION_LEFT == null 
        || dg_dhtmlNotifier_CONST_DIRECTION_UP == null
        || dg_dhtmlNotifier_CONST_STEP_TIME == null)
    {
        return;
    }
    
    var element = document.getElementById(nodeId);
    
    if (element != null)
    {
        var currentLeft = null; 
        var currentTop  = null;
        var axis        = null;

        try
        {
			// This cause the alert box go too far right.
            //to = parseInt(to, 10);
            if(direction==dg_dhtmlNotifier_CONST_DIRECTION_LEFT)
              { to = -10;}
			else
				{to = parseInt(to, 10);}
        }
        catch (NumberFormatException)
        {
            return;
        }            

        switch (direction)
        {
            case dg_dhtmlNotifier_CONST_DIRECTION_RIGHT :
            case dg_dhtmlNotifier_CONST_DIRECTION_LEFT :
                axis = parseInt(element.style.left.replace(/px/, ''), 10);
                break;
            case dg_dhtmlNotifier_CONST_DIRECTION_UP :
                axis = parseInt(element.style.top.replace(/px/, ''), 10);
                break;
        }

        if (axis != to)
        {
            dg_dhtmlNotifier__transInEffect = true;

            switch (direction)
            {
                case dg_dhtmlNotifier_CONST_DIRECTION_RIGHT :
                case dg_dhtmlNotifier_CONST_DIRECTION_LEFT :
                    axis = dg_dhtmlNotifier_determineStepPixels(axis, to,
                        direction) + 'px';
                    element.style.left = axis;
                    break;
                case dg_dhtmlNotifier_CONST_DIRECTION_UP :
                    axis = dg_dhtmlNotifier_determineStepPixels(axis, to,
                        direction) + 'px';
                    element.style.top = axis;
                    break;
            }

            var call = "dg_dhtmlNotifier_moveNode('" + nodeId + "', '" + to 
                + "', '" + direction + "')";

                setTimeout(call, dg_dhtmlNotifier_CONST_STEP_TIME);
        }
        else
        {
            if (direction == dg_dhtmlNotifier_CONST_DIRECTION_LEFT)
            {
                dg_dhtmlNotifier_deleteIMAlert(nodeId);
            }
            else if (direction == dg_dhtmlNotifier_CONST_DIRECTION_RIGHT)
            {
                dg_dhtmlNotifier_setNodeVisibility(nodeId, true);
            }

            dg_dhtmlNotifier__transInEffect = false;
        }
    }
}

function dg_dhtmlNotifier_determineStepPixels(currentPosition, to, direction)
{
    if (currentPosition == null || to == null || direction == null
        || dg_dhtmlNotifier_CONST_DIRECTION_RIGHT == null 
        || dg_dhtmlNotifier_CONST_MAJOR_STEP_PIXELS == null
        || dg_dhtmlNotifier_CONST_MINOR_STEP_PIXELS == null 
        || dg_dhtmlNotifier_CONST_DIRECTION_LEFT == null
        || dg_dhtmlNotifier_CONST_DIRECTION_UP == null)
    {
        return;
    }
    
    var absMinorStep = Math.abs(dg_dhtmlNotifier_CONST_MINOR_STEP_PIXELS);
    var absMajorStep = Math.abs(dg_dhtmlNotifier_CONST_MAJOR_STEP_PIXELS);
    
    try
    {
        switch (direction)
        {
            case dg_dhtmlNotifier_CONST_DIRECTION_RIGHT :
                currentPosition 
                    += (Math.abs(currentPosition - to) % absMajorStep != 0)
                    ? dg_dhtmlNotifier_CONST_MINOR_STEP_PIXELS
                    : dg_dhtmlNotifier_CONST_MAJOR_STEP_PIXELS; 
                break;
            case dg_dhtmlNotifier_CONST_DIRECTION_LEFT :
                currentPosition 
                    -= ((currentPosition + to) 
                        % dg_dhtmlNotifier_CONST_MAJOR_STEP_PIXELS == 0)
                    ? dg_dhtmlNotifier_CONST_MAJOR_STEP_PIXELS
                    : dg_dhtmlNotifier_CONST_MINOR_STEP_PIXELS;
                break;
            case dg_dhtmlNotifier_CONST_DIRECTION_UP :
                currentPosition 
                    -= (Math.abs(dg_dhtmlNotifier_CONST_MAJOR_STEP_PIXELS) 
                        % (currentPosition - to) == 0)
                    ? Math.abs(dg_dhtmlNotifier_CONST_MINOR_STEP_PIXELS)
                    : Math.abs(dg_dhtmlNotifier_CONST_MAJOR_STEP_PIXELS);
                break;
        }
    }
    catch (NumberFormatException)
    {
        return;
    }

    return currentPosition;
}

function dg_dhtmlNotifier_deleteIMAlert(nodeId)
{
    if (nodeId == null || dg_IMAlerts == null)
    {
        return;
    }
    
    if (dg_dhtmlNotifier__transInEffect)
    {
        var call = "dg_dhtmlNotifier_deleteIMAlert('" + nodeId + "')";

        setTimeout(call, 30);

        return;
    }
    
    var alertsToMoveUp  = new Array();
    var IMAlerts        = document.getElementById('IMAlerts');

    if (IMAlerts != null)
    {
        var nodeList = IMAlerts.getElementsByTagName('DIV');
        
        for (var i = 0; i < dg_IMAlerts.length; i++)
        {
			var xna = dg_IMAlerts[i];
            if (xna.alertId == nodeId)
            {
                for (var j = 0; j < nodeList.length; j++)
                {
                    if (nodeList[j].id == xna.alertId)
                    {
                        for (var k = j + 1; k < nodeList.length; k++)
                        {
                            if (nodeList[k].id.indexOf('alertId') != -1)
                            {
                                alertsToMoveUp.push(nodeList[k].id);    
                            }
                        }

                        break;
                    }
                }
                
                dg_IMAlerts[i] = dg_IMAlerts[dg_IMAlerts.length - 1];
                dg_IMAlerts.pop(); 
                
                var node = document.getElementById(nodeId);
				IMAlerts.removeChild(node);               

                break;
            }
        }

        dg_dhtmlNotifier_moveAlertsUp(alertsToMoveUp);
    }
}

function dg_dhtmlNotifier_moveAlertsUp(alertsToMoveUp)
{
    if (alertsToMoveUp == null || dg_dhtmlNotifier_CONST_ALERT_HEIGHT == null 
        || dg_dhtmlNotifier_CONST_DIRECTION_UP == null)
    {
        return;
    }
    
    for (var i = 0; i < alertsToMoveUp.length; i++)
    {
        var element = document.getElementById(alertsToMoveUp[i]);

        if (element != null)
        {
            var currentTop  = parseInt(element.style.top.replace(/px/, ''), 10);
            var newTop      = currentTop - dg_dhtmlNotifier_CONST_ALERT_HEIGHT;
            
            dg_dhtmlNotifier_moveNode(alertsToMoveUp[i], newTop, 
                dg_dhtmlNotifier_CONST_DIRECTION_UP);
        }
    }
}
/***************************************************************
NEW CheckIM Implementation Using AJAX
****************************************************************/

//global variables
var isAjaxEnabled = false;//whether or not to use Ajax to make async calls or not. Turn off for testing potential bugs 18114. False means use IFRAMES.
var isAjaxVerboseMode = false;//like debug mode. Turns alerts on and forces execution of remote javascript which would otherwise be fire and forget.
var isOnlineTimeLimitReached = false;//when true, checking invitations and updating MOL should stop (assuming ignoreOnlineTimeLimit is false)
var req1 = null; var req2=null; var req3=null; //1: check invitations 2: update mol 3: sessionkeepalive (4th is remove invitations, but uses new req variable every request)
var timerOnlineTimeout; var interval1; var interval2; var interval3; var countdownTimer1 = null; //integers used for timers
var IgnoreOnlineTimeLimit = false;//certain pages, such as chat, need to ignore the on-line time limit
//initialize the online checker functions. Called once onload on pages that have menu in init() and in chat. Else called manually by clicking hyperlinks.
function initOnlineChecker(ignoreOnlineTimeLimit) 
{
	IgnoreOnlineTimeLimit = ignoreOnlineTimeLimit;
    if (pageIncludesIMNotifier())
    {	clearTimeout(timerOnlineTimeout);clearInterval(interval1);clearInterval(interval2);clearInterval(interval3);
		isOnlineTimeLimitReached = false;//set to false because we're initializing
		//certain pages, like chat, need to ignore online IM checking limit. Otherwise set the time limit
		if (!ignoreOnlineTimeLimit) timerOnlineTimeout = setTimeout(OnlineTimeLimitReached,3600000); //check for invitations/updateMOL for max of 60 minutes (3600000 milliseconds)
		setIMStatusOnline();//show UI indication of being online
		checkForInvitations();//check for invitations on load of page
		updateMembersOnline();//add to members on-line on load of page
		interval1 = setInterval("if (!isOnlineTimeLimitReached) checkForInvitations();",15000); //continue checking for invitations every 15 seconds until max limit reached. (change to 15000)
		interval2 = setInterval("if (!isOnlineTimeLimitReached) updateMembersOnline()",100000); //continue adding to members online every 100 seconds (100000 milliseconds) until max limit reached.
    }
    var statusLoggedInElement = document.getElementById("statusLoggedIn");
    if (statusLoggedInElement != null) 
    {
		if (statusLoggedInElement.style.display == '')
		{
			//set session keep alive regardless of whether we're checking IM (i.e., even for hidden members) but only for logged in users
			interval3 = setInterval("sessionKeepAlive()",300000); //keep member session alive every 5 minutes (300000) milliseconds, forever, with no limit (note: session is different than Members Online)
		}
	}
}

//Remote "AJAX" Methods or alternate methods using IFRAME
function checkForInvitations() {
	var url = "/Applications/API/CheckForInvitations.aspx?random="+randomNumber();
	if(isAjaxEnabled)
	{
		show('lblCheckingInvitations');showCountDownToNextCheckForInvitations(15);executeRemoteJavascript(url,req1);
	}
	else
	{
		loadGetInvitations();
	}
}
function updateMembersOnline() {
	var url = "/Applications/API/UpdateMembersOnline.aspx?random="+randomNumber();
	if(isAjaxEnabled) 
	{
		executeFireAndForgetUrl(url,req2);
	}
	else 
	{
		var fmol=null; fmol=window.frm_updateMOL; if (fmol !=null) fmol.location.replace(url);
	}
}
function sessionKeepAlive() {
	var url = "/Applications/API/SessionKeepAlive.aspx?random="+randomNumber();
	if(isAjaxEnabled) 
	{
		executeRemoteJavascript(url,req3);
	}
	else 
	{
		var fmol=null; fmol=window.frm_sessionKeepAlive; if (fmol !=null) fmol.location.replace(url);
	}
}

function removeInvitation(conversationKey,isRejection) {
	var url = "/Applications/API/RemoveInvitation.aspx?&ConversationInvitationKey=" + conversationKey + "&IMReject="+isRejection;
	if(isAjaxEnabled) 
	{
		//passes null xhr object so it will create a new one for every click on yes or no. Uses fire and forget because we don't do anything with the response.
		executeFireAndForgetUrl(url,null);
	}
	else 
	{
		var r=null; r=window.frm_removeim; if (r !=null) r.location.replace(url);
	}
}


//CallBack Methods - you won't find calls to these here... They come from the output of ASPX pages
//called by result of checkForInvitations - loads GetInvitations page in IFRAME named frm_checkim
function loadGetInvitations(){var cim=null; cim=window.frm_checkim; if (cim !=null) cim.location.replace("/Applications/InstantMessenger/CheckIM.aspx?random=" + randomNumber());hide('lblCheckingInvitations')}
function noInvitationsFound(){hide('lblCheckingInvitations');dg_dhtmlNotifier_removeOldIMAlerts();}
//callback from checkForInvitations.aspx or sessionKeepAlive.aspx- if user logs out of another window, checking for IMs will fail. We want to show user they are logged out and if we're on a page where online time limit is ignored, force a reload of the current page (such as on chat page) because user would otherwise never know they couldn't receive IM's. Also, if user has logged out of second window, clear the sessionKeepAlive interval which would be in vain anyway.
function notLoggedIn(){isOnlineTimeLimitReached=true;show('statusLoggedOut');hide('statusLoggedIn');clearInterval(interval3);hide('divIMOffline');hide('divIMOnline');show('divMembersOnline');if(IgnoreOnlineTimeLimit)parent.location.reload(parent.location.href)};

//called when online time limit reached
function OnlineTimeLimitReached(){if (isAjaxVerboseMode)alert('online time limit reached');isOnlineTimeLimitReached=true;setIMStatusOffline();}

//UI Methods
function show(elementId) {var elem = null; elem = document.getElementById(elementId);if (elem==null) return; elem.style.display=""};//shows a given element if it can find it
function hide(elementId) {var elem = null; elem = document.getElementById(elementId);if (elem==null) return; elem.style.display="none"};//hides a given element if it can find it
function toggle(elementId){var elem = null; elem = document.getElementById(elementId);if (elem==null) return; elem.style.display = elem.style.display == "none" ? "":"none";} //This is the quintessential toggle display of given element
function randomNumber() {return Math.floor( Math.random() * 100000000000 );}//for defeating caching

//show UI indication of being online. Not in use as of 16766 however.
function setIMStatusOnline() {show('divIMOnline');hide('divIMOffline');show('divMembersOnline');}
//show UI indication of being disconnected (but still logged in)
function setIMStatusOffline() {show('divIMOffline');hide('divIMOnline');hide('divMembersOnline');}

//Returns true/false. Currently, determine if check invitations process should happen by checking if IFRAME exists.
//TODO: in the future, will have to have another type of check when IFRAME goes away.
function pageIncludesIMNotifier() {cim=null; cim=window.frm_checkim; return (cim !=null);}

//shows how many seconds left until next check for invitations. Not in use as of 16766 however.
function showCountDownToNextCheckForInvitations(i)
{ 
	if (i == 15) {clearTimeout(countdownTimer1)};
	if (i == 0) return;
	var lblCheckingInvitationsCounter = null;lblCheckingInvitationsCounter = document.getElementById('lblCheckingInvitationsCounter');if(lblCheckingInvitationsCounter == null) return;
	lblCheckingInvitationsCounter.innerHTML=i;//next check in i seconds
	i = i - 1;countdownTimer1 = setTimeout("showCountDownToNextCheckForInvitations(" + i + ")",1000);
}

/****************************************************************
XMLHttpRequest Utility Functions
*****************************************************************/

//returns xmlhttp object if it can, if not an xmlhttprequest object, or null
function getXHR(){var C=null;try{C=new ActiveXObject("Msxml2.XMLHTTP")}catch(e){try{C=new ActiveXObject("Microsoft.XMLHTTP")}catch(sc){C=null}}if(!C&&typeof XMLHttpRequest!="undefined"){C=new XMLHttpRequest()}return C}

//calls remote page, executes the javascript returned (using eval). url is the page requested (with or without query string) and xhr is the XMLHttpRequest object to use.
function executeRemoteJavascript(url,xhr)
{
    if(xhr&&xhr.readyState!=0)
    {
    xhr.abort();
    }
    xhr=getXHR();
    if(xhr){
        xhr.open("GET",url,true);
        xhr.onreadystatechange=function()
        {
            if(xhr.readyState==4&&xhr.responseText&&xhr.status=='200')
            {
                if(xhr.responseText.charAt(0)=="<")
                {
                    if (isAjaxVerboseMode)alert('Error returned from server:' + xhr.responseText);
                }
                else
                {
                 eval(xhr.responseText)
                }
                xhr = null;
            }
        };
        xhr.send(null);
    }
}

//calls remote page url with given xhr object and ignores response. If in AjaxVerboseMode (aka debug mode) calls executeRemoteJavascript instead.
function executeFireAndForgetUrl(url,xhr)
{
    if (isAjaxVerboseMode) 
    {
        executeRemoteJavascript(url,xhr)
    }
    else {
        if(xhr&&xhr.readyState!=0)
        {
        xhr.abort();
        }
        xhr=getXHR();
        if(xhr){
            xhr.open("GET",url,true);
            xhr.onreadystatechange=function()
            {
				if (xhr.readyState==2)
				{
					xhr.abort();
					xhr = null;
				}
            };
            xhr.send(null);
        }
    }
}

// TT#19377
function activatePageObjects()
{
	try
	{
		theObjects = document.getElementsByTagName("object");

		for (var i = 0; i < theObjects.length; i++) 
		{
			theObjects[i].outerHTML = theObjects[i].outerHTML;
		}
	}
	catch(err)
	{
	}
}

// FOR MEMBER SUSPENSION THROUGH FREE TEXT APPROVAL 
function validateSuspendReasons(divSuspendID, cblSuspendID, btnSuspendID, btnSuspendName)
{
	var suspensionReasonSelected = false;
	var el = document.getElementById(divSuspendID);

    // Show the checkbox list of suspension reasons	            
    if (el.className == 'suspendReasonsHide')
    {
        el.className = 'suspendReasonsShow';
    }
    else
    {
	    var group = document.getElementById(cblSuspendID);
        var col = group.getElementsByTagName('INPUT');                   
        var i = 0;
        
        for (i=0; i<col.length; i++)
        {
            if (col.item(i).checked)
            {
                suspensionReasonSelected = true;
            }                                        
        }                
    }

    if (!suspensionReasonSelected)
    {
        alert('Please select at least one suspension reason.');                            
    }
    else
    {
        var btnSuspend = document.getElementById(sb);
        btnSuspend.value = 'Please wait...';
        btnSuspend.disabled = true;
        __doPostBack(btnSuspendName, '');        
    }

    return suspensionReasonSelected;         
}

function textboxMultilineMaxNumber(txt,maxLen)
{
    try
    {
        if (txt.value.length > (maxLen-1))
        {
            alert('Maximum characters allowed is ' + maxLen.toString());
            return false;
        }
    }
    catch(e)
    {
    
    }
}

// Keep user from entering more than maxLength characters
function doKeypress(control){

    maxLength = control.attributes["maxLength"].value;
    value = control.value;
     if(maxLength && value.length > maxLength-1){
          alert('too long');
          event.returnValue = false;
          maxLength = parseInt(maxLength);
     }
}
// Cancel default behavior
function doBeforePaste(control){

    maxLength = control.attributes["maxLength"].value;
     if(maxLength)
     {
          event.returnValue = false;
     }
}
// Cancel default behavior and create a new paste routine
function doPaste(control){

    maxLength = control.attributes["maxLength"].value;
    value = control.value;
     if(maxLength){
          event.returnValue = false;
          maxLength = parseInt(maxLength);
          var oTR = control.document.selection.createRange();
          var iInsertLength = maxLength - value.length + oTR.text.length;
          var sData = window.clipboardData.getData("Text").substr(0,iInsertLength);
          oTR.text = sData;
     }
}


// For popup help divs
function ShowPopupDiv(id){
	document.getElementById(id).style.display='block';
}

function HidePopupDiv(id){
	document.getElementById(id).style.display='none';
}
