

function saveDefaultReferer() {
	
	//alert('saveDefaultReferer');
	
	var referer = document.referrer.toLowerCase();
	
	if (typeof currentPageManagerClass == 'undefined') {
		// nothing we can do - some parameters are missing
		return;
	}
		
	// see if referer saving should be done in the current page
	var shouldCheckReferer = false;
	for (var i=0; i<pageManagersWhereDefaultSaveCookieIsManipulated.length; i++) {
		var pageManagerName = pageManagersWhereDefaultSaveCookieIsManipulated[i];
		if (pageManagerName == currentPageManagerClass) {
			shouldCheckReferer = true;
			break;
		}
	}
	
	if (!shouldCheckReferer) {
		//alert("No need to save referer for page " + currentPageManagerClass);
		return;
	}
	
	//alert("May need to save referer for page " + currentPageManagerClass);
	
	//alert("Referer is " + referer);
	
	var socialNetworkReferer = '';
	
	// see if referer saving should be done for the current referer
	for (socialNetworkName in supportedReferersForDefaultSaveCookieIsManipulation) {
		if (referer.indexOf(socialNetworkName) > -1) {
			socialNetworkReferer = supportedReferersForDefaultSaveCookieIsManipulation[socialNetworkName];
			break;
		}
	}
	
	if (socialNetworkReferer == '') {
		//alert("No need to save referer info");
		return;
	}
	
	//alert("Save referer info");
	
	// remember the referer
	setCookie('DefaultSave', socialNetworkReferer);

	if (socialNetworkReferer == 'bebo') {
		// make sure that the Bebo tab will be selected
		setCookie('CelebrityDemoTab', 'bebo');
	}
}

saveDefaultReferer();


// Flash Player Version Detection - Rev 1.5
// Detect Client Browser type
// Copyright(c) 2005-2006 Adobe Macromedia Software, LLC. All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;			
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			if ( descArray[3] != "" ) {
				tempArrayMinor = descArray[3].split("r");
			} else {
				tempArrayMinor = descArray[4].split("r");
			}
			var versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
    var str = '';
    if (isIE && isWin && !isOpera)
    {
  		str += '<object ';
  		for (var i in objAttrs)
  			str += i + '="' + objAttrs[i] + '" ';
  		for (var i in params)
  			str += '><param name="' + i + '" value="' + params[i] + '" /> ';
  		str += '></object>';
    } else {
  		str += '<embed ';
  		for (var i in embedAttrs)
  			str += i + '="' + embedAttrs[i] + '" ';
  		str += '> </embed>';
    }

    document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}


/************** Start of /FP/Scripts/general.js **************/

var selectedPage = -1;
var oldOpera = 0;
var issetFlash = 0;
var checkedForFlash = 0;
var MM_PluginVersion = 0;
var MM_contentVersion = 7; // minimal version required by our content
var flash7Installed = false;
var flash8Installed = false;

// todo: check user agent if: firefox, or if ie on win
// if yes, checkedForFlash should be 1, and proceed to code below
// if not, leave now

// there is a problem with user agents from AOL. In these agents we don't check for Flash
if (navigator.userAgent && navigator.userAgent.toUpperCase().indexOf("AOL") == -1 && ((navigator.userAgent.indexOf("Firefox") >=0 ) || 
	(navigator.userAgent.indexOf("MSIE") >= 0 && (navigator.appVersion.indexOf("Win") >= 0)))) {
   	checkedForFlash = 1;
}

if (typeof minimalFlashVersion == 'undefined') {
	var minimalFlashVersion = 7;
}

if (checkedForFlash) {
	var plugin = (navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
	if ( plugin ) {
		var words = navigator.plugins["Shockwave Flash"].description.split(" ");
	    for (var i = 0; i < words.length; ++i) {
	
			if (isNaN(parseInt(words[i])))
				continue;
			var MM_PluginVersion = words[i]; 
			
	    }
	    
		issetFlash = MM_PluginVersion >= MM_contentVersion;
	}
	else if (navigator.userAgent.indexOf("MSIE") >= 0 && (navigator.appVersion.indexOf("Win") >= 0)) {

		//alert("Can now check Flash version for IE with Windows");
		//alert("Checking what version of Flash is installed");
		
		// Using the Macromedia solution
		for (var i = 9; i >= minimalFlashVersion; i--) {	
			//alert("What about " + i + " ?");	
			var flashInstalled = DetectFlashVer(i, 0, 0);
			if (flashInstalled) {
				//alert("Yes, version " + i + " is installed!");
				MM_PluginVersion = i;
				break;
			}
			else {
				//alert("Flash " + i + " is not installed");
			}
		}

		issetFlash = (MM_PluginVersion != 0);
		
		//alert("Done iterating over Flash versions, issetFlash: " + issetFlash);
	}
	
	// at this point we know wether the user has Flash or not, so we remember this in a cookie
	setCookie('HasFlash', (issetFlash ? 'yes' : 'no'));
}


//issetFlash = 0;

function replaceParameter(oldURL, parameter, newValue) {
	
	var newURL;
	
	var startOfOldUParam = oldURL.indexOf('&' + parameter + '=');
	if (startOfOldUParam == -1) {
		startOfOldUParam = oldURL.indexOf('?' + parameter + '=');
	}
	if (startOfOldUParam == -1) {
		// failed to find the parameter

		var existanceOfParameters = oldURL.indexOf('?');
		if (existanceOfParameters != -1) {
			newURL = oldURL += '&' + parameter + '=' + newValue;
		}
		else {
			newURL = oldURL += '?' + parameter + '=' + newValue;
		}					
	}
	else {
		parameterStartsHere = startOfOldUParam + parameter.length + 2; // including ?/& and =
		
		// look for the end of the string value
		var endOfU = oldURL.indexOf('&', parameterStartsHere);
		if (endOfU == -1) {
			// The parameter was the last parameter
			newURL = oldURL.substr(0, parameterStartsHere) + newValue;
		}
		else {
			newURL = oldURL.substr(0, parameterStartsHere) + newValue + oldURL.substr(endOfU, oldURL.length);
		}
	}
	
	return newURL;
}

/**
 * looks for reference to the old session parameter 'u'
 * if found, replaces its value with the value of newSessionID
 * if not, append &u=<newSessionID> to the url and returns it
 */
function replaceSessionParameter(oldURL, newSessionID) {
	return replaceParameter(oldURL, 'u', newSessionID);
}

/**
 * extracts the value of a URL parameter from a URL.
 * If the parameter is not found, null is returned 
 */
function extractParameterValueFromURL(url, parameterName) {
	
	var parameterValue = null;
	
	var startOfParam = url.indexOf('&' + parameterName + '=');
	if (startOfParam == -1) {
		startOfParam = url.indexOf('?' + parameterName + '=');
	}
	if (startOfParam != -1) {
		parameterStartsHere = startOfParam + 2 + parameterName.length; // 2 is for &/? and =
		
		// look for the end of the session string value
		var endOfParameter = url.indexOf('&', parameterStartsHere);
		if (endOfParameter == -1) {
			endOfParameter = url.length;
		}
			
		parameterValue = url.substring(parameterStartsHere, endOfParameter);		
	}
	
	return parameterValue;
}

/**
 * disables right click
 */
function disableRightClick() {
	if (event.button == 2) {	
  		return false;
  	}
}

/**
 * invokes a URL from a Flash component
 */
function invokeFlashURL(page, parameters) {
		
	if (parameters == '') {
		document.location.href = page;
		return;
	}
	
	var paramsArray = parameters.split(',');
	var URL = page;
	var separator = '?';
	for (i=0; i<paramsArray.length; i++) {
		URL += separator;
		URL += paramsArray[i];
		separator = '&';
	}
		
	document.location.href = URL;
}

/**
 * returns an array describing the position and dimensions of an element in the page.
 * The entries in the array are:
 * 'left': left coordinate in pixels
 * 'top': top coordinate in pixels
 * 'width': width of the element in pixels
 * 'height': height of the element in pixels
 *
 * @param element The element whose position and dimensions we want
 */
function getPositionAndDimension(element) {
	
	var left = element.offsetLeft;
	var top = element.offsetTop;
	var width = element.offsetWidth;
	var height = element.offsetHeight;
	
	while (element.offsetParent != null) {
  		elementParent = element.offsetParent;
  		left += elementParent.offsetLeft;
		top += elementParent.offsetTop;
  		element = elementParent;
 	}
	
	var results = new Array(4);
	results['left'] = left;
	results['top'] = top;
	results['width'] = width;
	results['height'] = height;
		
	return results;	
}

/**
 * displays an alert prompt with information about a JavaScript error. 
 */
function showErrorMsg(message, url, line) {

 	var fs = "";
 	if (showErrorMsg.caller) {
 		var content = showErrorMsg.caller.toString();
 		var startIndex = 8;
 		var endIndex = content.indexOf("(");
 		var funcName = content.substring(startIndex, endIndex);
   	fs = funcName;
 	}
 	 	
 	// clean url string 	
 	var startIndex = url.lastIndexOf("/") - 3;
 	var endIndex = url.lastIndexOf("?");
 	if (endIndex == -1) {
 		endIndex = url.length;
 	}
 	var file = url.substring(startIndex, endIndex); 
 	 	
 	var params = "error.php?file=" + file + "&func=" + fs + "&line=" + line + "&msg=" + message;	
 	window.open(params, '', '');

	return true;
}

//window.onerror = showErrorMsg;

function preloadImages() { //v3.0
	var d=document; 
	if (d.images) { 
		d.MM_p = new Array();
    	var i, j = d.MM_p.length, a = preloadImages.arguments;
    	for (i=0; i<a.length; i++)
    		if (a[i].indexOf("#") != 0) { 
    			d.MM_p[j] = new Image; 
    			d.MM_p[j++].src= a[i];
    		}
    }
}


function preloadIcons(imagesArray) {
	for (i=0; i<imagesArray.length; i++) {
		var image = new Image;
		image.src = imagesArray[i];
	}
}

 
/**
 * preloads all the images that are needed for the navigation mechanism
 */
function preLoadNavigationImages(theme) {
		
	var navigationButtonStr = "";
	
	// make sure that the theme path contains the /FP/ subfolder
	if (theme.indexOf('/FP') == -1) {
		theme = '/FP' + theme;
	}
	
	navigationButtonStr += ' "' + theme + '/NavigationLine/Images/LTR/buttonBack.png" ';
	navigationButtonStr += ', "' + theme + '/NavigationLine/Images/LTR/buttonBackDisabled.png" ';
	navigationButtonStr += ', "' + theme + '/NavigationLine/Images/LTR/buttonNext.png" ';
	navigationButtonStr += ', "' + theme + '/NavigationLine/Images/LTR/buttonNextDisabled.png" ';
	navigationButtonStr += ', "' + theme + '/NavigationLine/Images/RTL/buttonBack.png" ';
	navigationButtonStr += ', "' + theme + '/NavigationLine/Images/RTL/buttonBackDisabled.png" ';
	navigationButtonStr += ', "' + theme + '/NavigationLine/Images/RTL/buttonNext.png" ';
	navigationButtonStr += ', "' + theme + '/NavigationLine/Images/RTL/buttonNextDisabled.png" ';
	
	if (navigationButtonStr){
		navigationButtonStr = 'preloadImages(' + navigationButtonStr + ')';
		eval(navigationButtonStr);
	}
}


function handleSuperSearchKeyUp(event, form, buttonID, minimalSearchLength) {

	var value = trim(form.query.value);
	
	var code = getEventCode(event);
	if (code == 13) {	// 13 is for hitting the "Enter" key
		if (value.length >= minimalSearchLength) {
			performSuperSearch(form, buttonID);
		}
	}
	else {
		
		if (value.length < minimalSearchLength) {
			disableButton(buttonID);
		}
		else {
			enableButton(buttonID);
		}
	}
}


function performSuperSearch(form, buttonID) {

	form.query.value = trim(form.query.value);
	if (buttonID != ''){
		disableButton(buttonID);
	}	
	form.submit();
	return false;
}

function openCenteredPopup2(url, width, height, name, params, callback) {	
	
	// extract the scrolling parameter
	var scrolling = 'no';	// The default value
	
	var scrollIndex = params.indexOf('scroll');
	if (scrollIndex != -1) {
		var endIndex = params.indexOf(';', scrollIndex);
		if (endIndex == -1) {	// this may have been the last parameter
			scrolling = params.substring(scrollIndex + 7, params.length);	// 7 is the legnth of 'scroll:'
		}
		else {
			scrolling = params.substring(scrollIndex + 7, endIndex);	// 7 is the legnth of 'scroll:'
		}
				
		// all possible "positive" values
		if (scrolling == 'yes' || scrolling == '1' || scrolling == 'on') {
			scrolling = 'auto';
		}
	}
			
	internalDoNotCallThisPopup(url, width, height, scrolling, callback, false);
}


/**
 * checks if the day, month and year supplied constitutes a legal date
 *
 * @param dayValue The day (1-31)
 * @param monthValue The month (1-12)
 * @param yearValue The year
 *
 * @return true if the day, month and year supplied constitutes a legal date, false otherwise
 */
function isDateLegal(dayValue, monthValue, yearValue) {
	
	var day = parseInt(dayValue, 10);
	var day = parseInt(dayValue, 10);
	
	if (day > 30 && (monthValue == 4 || monthValue == 6 || monthValue == 9 || monthValue == 11)) {
		// these months cannot have more than 30 days
		return false;
	}

	if (monthValue == 2)	{			
		// this is February
		// This calculates the basic leap year no matter the format, i.e. 2000 or 00.
						
		var isLeapYear = (((yearValue % 4 == 0) && (yearValue % 100 != 0)) || (yearValue % 400 == 0)) ? true : false;		
		
		if (!isLeapYear && day > 28) {
			return false;
		}
		else if (isLeapYear && day > 29) {
			return false;
		}	
	}

	return true;
}


/**
 * returns the Current UTC time on in SECONDS from 1/1/1970
 */
function getCurrentUTCTime(){
	var d = new Date();
	// divide by 1000 to convert milliseconds to seconds
	// multiple by 60 to convert minutes to seconds
	var currUTCTime = Math.floor(d.getTime()/1000)  +  (d.getTimezoneOffset() * 60);
	
	return (currUTCTime);
}

/**
 * returns a form element object by its name
 */
function getFormGroup(name) {
	return document.getElementsByName(name);
}
		

/**
 * returns the form element with the given name that is checked or null otherwise
 */
function getRadio(name) {
	var elements = getFormGroup(name);
	if (elements) {
		/* loop over all the radio buttons */
		for (i = 0; i < elements.length; i++) {
			if (elements[i].checked) {
				return elements[i];
			}
		}
	}
		/* either no group by that name was foundor none were selected */
	return null;
}

/**
 * returns the value of the checked radio button with the given name, or '' otherwise
 */
function getRadioValue(name) {
	var element = getRadio(name);
	if (element) {
		return element.value;
	}
		
	/* there must not have been a radio buttonselected */
	return '';
}


/**
 * returns a random string of a specific length
 * The string is composed of the letters A-Z
 */
function generateRandomString(length) {
	var randomValue = '';		 		
	for (var i=0; i<length; i++) {			
		var rndNum = Math.random();
		// rndNum from 0 - 1000
		rndNum = parseInt(rndNum * 1000); 
		
		// rndNum from 65 - 90 
		rndNum = (rndNum % 25) + 65;
		randomValue += String.fromCharCode(rndNum); 
	}
	
	return randomValue;
}


function setInnerText(objID, newText) {
	var obj = document.getElementById(objID);
	if (document.all) {
		// IE CODE
		obj.innerText = newText;
	} else {
		// MOZILLA & NETSCAPE CODE
		var nodes = obj.childNodes[0];
		nodes.nodeValue = newText;
	}
}

/**
 * prepares text for JavaScript
 */
function prepareTextForJavascript(stringValue) {
	
	if (typeof stringValue == 'string') {
		var output = "";	
		
		if (stringValue.length == 0) {
			return "!";
		}
		
		for (var i=0; i<stringValue.length; i++) {
			output += "!" + tohex(stringValue.charCodeAt(i)); 
		}
		return output;
	}
	else {
		return "!" + stringValue;
	}
}


/**
 * converts a decimal number to a hexadecimal
 */
function tohex(i) {
	var a2 = ''
	var ihex = hexQuot(i);
	var idiff = eval(i + '-(' + ihex + '*16)')
    a2 = itohex(idiff) + a2;
    while( ihex >= 16) {
    	var itmp = hexQuot(ihex);
         idiff = eval(ihex + '-(' + itmp + '*16)');
         a2 = itohex(idiff) + a2;
         ihex = itmp;
	} 
    var a1 = itohex(ihex);
    return a1 + a2 ;
}


function hexQuot(i) {
	return Math.floor(eval(i +'/16'));
}

function itohex(i) {
	if (i == 0) {
    	aa = '0';
	}
    else { 
    	if (i== 1) {
			aa = '1';
    	}
        else {
        	if (i== 2) {
				aa = '2';
        	}
            else {
            	if (i == 3) {
                	aa = '3';
            	}
               	else {
               		if (i== 4) {
                    	aa = '4';
               		}
                  	else {
                  		if (i == 5) {
                        	aa = '5'; 
                  		}
                     	else {
                     		if (i== 6) {
                            	aa = '6';
                     		}
                        	else {
                        		if (i == 7) {
                                	aa = '7'; 
                        		}
                           		else {
                           			if (i== 8) {
                                    	aa = '8';
                           			}
	                              	else {
	                              		if (i == 9) {
                                        	aa = '9';
	                              		}
	                                 	else {
	                                 		if (i==10) {
                                          		aa = 'A';
	                                 		}
                                    		else {
                                    			if (i==11) {
                                            		aa = 'B';
                                    			}
                                       			else {
                                       				if (i==12) {
                                                		aa = 'C';
                                       				}
                                          			else {
                                          				if (i==13) {
                                                   			aa = 'D';
                                          				}
                                             			else {
                                             				if (i==14) {
                                                      			aa = 'E';
                                             				}
                                                			else {
                                                				if (i==15) {
                                                         			aa = 'F';
                                                				}
                                                			}
                                             			}
                                          			}
                                       			}
                                    		}
                                 		}
                              		}
                           		}
                        	}
                     	}
                  	}
               	}
        	}
    	}
	}
	return aa
}

/**
 * defines the endWidth function for the String object
 */
String.prototype.endsWith = function(sEnd) {
	return (this.substr(this.length-sEnd.length)==sEnd);
}

/*
 * Replace a token in a string
 *  tokenToRemove  token to be found and removed
 *  tokenToAdd  token to be inserted
 *  returns new String
 */
function replace(string, tokenToRemove, tokenToAdd) {
	var index = string.indexOf(tokenToRemove);
  	var result = "";
  	var stringFound = (index != -1);
  	if (!stringFound) {    		 		
  		// special case. If the attempt was to replace a URL parameter
  		// try not just the '&' version but also the '?' version
  		// for example: &test= and ?test=
  		if (tokenToRemove.charAt(0) == '&' && tokenToAdd.indexOf(tokenToRemove) == 0) {
  			
  			tokenToRemove = '?' + tokenToRemove.substring(1);
  			tokenToAdd = '?' + tokenToAdd.substring(1);
  			index = string.indexOf(tokenToRemove);
  			stringFound = (index != -1);
  		}
  		
  		if (!stringFound) {
  			return string;
  		}
  	}
  	
  	result += string.substring(0, index) + tokenToAdd;
  	if (index + tokenToRemove.length < string.length) {
    	result += replace(string.substring(index + tokenToRemove.length, string.length), tokenToRemove, tokenToAdd);
  	}
  	return result;
}

/**
 * returns the extension of a file name
 */
function getExtension(fileName) {
		
	var dotIndex = 	fileName.lastIndexOf('.');
	if (dotIndex == -1) {
		// no dot was found
		return '';
	}
	
	if (dotIndex == (fileName.length - 1)) {
		return '';
	}
	return fileName.substring(dotIndex + 1, fileName.length);
}


function getRandomNumber(size) {

	var min_random = 0;
	var max_random = size;

	var now = new Date();
	var seed = now.getSeconds();
	var n = Math.floor(Math.random(seed)*max_random);
	return n;
}





function leftMenu(id)  {
		
	for (i=0; i<Lmenu.length; i++) {
		if (i != id) {
			document.getElementById('mh'+i+'_norm').style.display = '';
			document.getElementById('mh'+i+'_act').style.display = 'none';
			document.getElementById('mh'+i+'_menu').style.display = '';
		}
	}		
	document.getElementById('mh'+id+'_norm').style.display = 'none';
	document.getElementById('mh'+id+'_act').style.display = '';
	document.getElementById('mh'+id+'_menu').style.display = '';

	LMactive = id;	
}

function closePopup() {
	parent.hidePopWin(true); 
}

function getPopupParent() {
	return parent.doNotCallThisFunctionGetPopupParent();
}

function convertArrayToParameterList(parameterArray) {
	var list = "";
	for (i=0; i<parameterArray.length; i++) {		
		list += "'" + replace("" + parameterArray[i], "'", "\\'") + "'";
		if (i < (parameterArray.length - 1)) {
			list += ", ";
		}
	}
	
	return list;
}

// function to search a string in an array
function in_array(searchString, sourceArray) {
	var i, returnValue;
	returnValue = false;

	for(i=0; i<(sourceArray.length); i++) {
		if(searchString == sourceArray[i]) {
			return true;
		}
	} 
	return returnValue;
}

function isNaturalNumber(sText) {
	var validChars = "0123456789";
   	var ch;

   	for (i = 0; i < sText.length; i++)  { 
    	ch = sText.charAt(i); 
      	if (validChars.indexOf(ch) == -1) {
         	return false;
		}
	}
   
	return true;  
}

function isDigit(chr) {
	var validChars = "0123456789";
	if (validChars.indexOf(chr) == -1) {
         return false;
	}
	else {
		return true;
	}
}

/** 
 * returns true if the supplied string contains profanity, false otherwise
 */
function includeProfanity(stringToTest) {

	var profanities = ['fuck','shit','cunt'];
	
	for (var i=0; i<profanities.length; i++) {
		if (stringToTest.indexOf(profanities[i]) != -1) {
			return true;
		}
	}
	
	return false;
}

function doesStartWithForbiddenCharacter(string) {
	// make sure the nickname doesn't start with one of the forbidden characters
	var forbiddenStartCharacters = ["!", "'", ",", "."];
	var firstLetter = string.charAt(0);
	for (var i=0; i<forbiddenStartCharacters.length; i++) {
		if (firstLetter == forbiddenStartCharacters[i]) {
			return true;
		}
	}
	
	return false;
}

function trim(string) {
	return string.replace(/^\s*|\s*$/g,'');
}

// this function gets the cookie, if it exists
function getCookie(NameOfCookie) {
	
	var start = document.cookie.indexOf(NameOfCookie + "=");
	var len = start + NameOfCookie.length + 1;
	if ((!start) && (NameOfCookie != document.cookie.substring(0 ,NameOfCookie.length))) {
		// failed to find the cookie
		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));
}

// sets the value of a cookie
function setCookie(NameOfCookie, value, expirationInMillis) {
	
	var ExpireDate = new Date();
	if (expirationInMillis) {
		ExpireDate.setTime(expirationInMillis);
	}
	else {
		// one year from now
		ExpireDate.setTime(ExpireDate.getTime() + (365 * 24 * 3600 * 1000));	
	}
	var expires_date = ExpireDate.toGMTString();
	
	var cookieDomain = getCookieDomain();

	var cookieValue = NameOfCookie + "=" + escape( value ) +
		";expires=" + expires_date +
		";path=/" + 
		( ( cookieDomain != '' ) ? ";domain=" + cookieDomain : "" );
	
	document.cookie = cookieValue;
}

function deleteCookie(NameOfCookie) {
	if (getCookie(NameOfCookie)) {
		
		var cookieDomain = getCookieDomain();
		
		document.cookie = NameOfCookie + "=" + 
		";path=/" + 
		"; expires=Thu, 01-Jan-70 00:00:01 GMT" + 
		( ( cookieDomain != '' ) ? ";domain=" + cookieDomain : "" );	
	}
}

// returns the domain that will be used in managing the cookies
// it is safer to set the domain explicitly as we know what value is used
// and we leave nothing for the browser
function getCookieDomain() {
		
	var host = document.location.host.toLowerCase();
		
	var hostLength = host.length;
	var extensionIndex = host.lastIndexOf('.com');
		
	var cookieDomain = "";
	
	// 4 is the length of the '.com' string
	if (extensionIndex == -1 || (extensionIndex != (hostLength - 4))) {
		
		// did not find .com or the host didn't end with .com
		
		// could be localhost or an IP address
  		if (host.indexOf('localhost') != 0) {
			// IP address
			var cookieDomain = "";
		}
	}
	else {
		// host ends with .com
		
		// skip any subdomain and start with the first .
		// For example, if the host was www.myheritage.com
		// we use the domain myheritage.com
		// this makes the cookie available on all subdomains of myheritage.com 
		var firstPeriod = host.indexOf(".");
		cookieDomain = host.substr(firstPeriod + 1);
	}
		
	return cookieDomain;
}



function isMessageBoxNeeded(guid) {
	
	var cookieValue = getCookie('messageBox');
	if (cookieValue == null) {	
		// no such cookie exists - store it
		setCookie('messageBox', guid + ",");
		return true;
	}
		
	// see if the supplied GUID is found in this cookie
	
	var i = 0;
	var cookieLength = cookieValue.length;
		
	var GUIDEnd;
	while (i < cookieLength) {
		
		var delimeterIndex = cookieValue.indexOf(",", i);
		if (delimeterIndex == -1) {
			i++;
			continue;
		}
				
		if (cookieValue.substring(i, delimeterIndex) == guid) {			
			return false;		
		}
		else {
			i = delimeterIndex + 1;
		}		
	}
		
	// if we got here, no such GUID was found - add it to the cookie
	cookieValue += guid + ",";
	setCookie('messageBox', cookieValue);
	return true;
}



function addEvent(obj, evType, fn){
 if (obj.addEventListener){
    obj.addEventListener(evType, fn, true);
    return true;
 } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
 } else {
    return false;
 }
}
function removeEvent(obj, evType, fn, useCapture){
  if (obj.removeEventListener){
    obj.removeEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.detachEvent){
    var r = obj.detachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
    return false;
  }
}


function getViewportHeight() {
	if (window.innerHeight!=window.undefined) return window.innerHeight;
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientHeight;
	if (document.body) return document.body.clientHeight; 
	return window.undefined; 
}
function getViewportWidth() {
	if (window.innerWidth!=window.undefined) return window.innerWidth; 
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientWidth; 
	if (document.body) return document.body.clientWidth; 
	return window.undefined; 
}

/**
 * POPUP WINDOW CODE
 * Used for displaying DHTML only popups instead of using buggy modal windows.
 *
 * By Seth Banks (webmaster at subimage dot com)
 * http://www.subimage.com/
 *
 * Contributions by Eric Angel (tab index code) and Scott (hiding/showing selects for IE users)
 *
 * Up to date code can be found at http://www.subimage.com/dhtml/subModal
 *
 * This code is free for you to use anywhere, just keep this comment block.
 */

// Popup code

var gTopmostPopup = -1;

var maxNumPopups = 4
var gPopupMask = new Array(maxNumPopups);
var gPopupContainer = new Array(maxNumPopups)
var gPopFrame = new Array(maxNumPopups)
var gReturnFunc = new Array(maxNumPopups);
var gPopupIsShown = false;

var gHideSelects = false;
var gInitPopUpCalled = false;

var gTabIndexes = new Array();
// Pre-defined list of tags we want to disable/enable tabbing into
var gTabbableTags = new Array("A","BUTTON","TEXTAREA","INPUT","IFRAME");	

// If using Mozilla or Firefox, use Tab-key trap.
if (!document.all) {
	document.onkeypress = keyDownHandler;
}


/**
 * Initializes popup code on load.	
 */
function initPopUp() {
			
	// this is a fix for Opera
	gInitPopUpCalled=false;
	maxNumPopups = 4;

	if (!gInitPopUpCalled) {
		
		for (i=0; i<maxNumPopups; i++) {
			gPopupMask[i] = document.getElementById("popupMask" + i);
			gPopupContainer[i] = document.getElementById("popupContainer" + i);
			gPopFrame[i] = document.getElementById("popupFrame" + i);	
		}
			
		// check to see if this is IE version 6 or lower. hide select boxes if so
		// maybe they'll fix this in version 7?
		var brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10);
		if (brsVersion <= 6 && window.navigator.userAgent.indexOf("MSIE") > -1) {
			gHideSelects = true;
		}
	}
	
	gInitPopUpCalled = true;
}

addEvent(window, "load", initPopUp);


 /**
	* @argument width - int in pixels
	* @argument height - int in pixels
	* @argument url - url to display
	* @argument returnFunc - function to call when returning true from the window.
	*/

function showPopWin(url, width, height, returnFunc, scrolling) {
			
	//alert("opening in " + document.location.href);
	while (parent != window && (parent.location.href.indexOf('/FP/') != -1)) {
		//alert("going to parent");
		parent.showPopWin(url, width, height, returnFunc, scrolling);
		return;
	}
	
	if (!gInitPopUpCalled) {
		initPopUp();
	}	
	
	if (gTopmostPopup == -2) {
		if (window != window.parent) {
			window.parent.showPopWin(url, width, height, returnFunc, scrolling);
			return;
		}
		else {
			// bug, gTopmostPopup has a bad value
			return;
		}
	}
	
	if (gTopmostPopup == -1) {		
		// This is the very first popup page
		if (document.location.href.indexOf('&forcedCompanySkin=1') != -1 && url.indexOf('&forcedCompanySkin') == -1) {
			// check if the url doesn't already contain the 'forcedCompanySkin' parameter			
			// if so, keep using this parameter in the new popup too			
			url += '&forcedCompanySkin=1';			
		}
		else {		
			// if this is one of the pages in which the company skin should be forced, then make
			// sure we do this, by appending the 'forcedCompanySkin=1' parameter to the URL
			// if it is not already there	
			
			var forceCompanySkinPages = [
				'createSiteRegistration.php',
				'member-sign-up.php',
				'forgotPassword.php',
				'memberLogin.php'];
					
			for (var i=0; i<forceCompanySkinPages.length; i++) {
				if (document.location.href.indexOf(forceCompanySkinPages[i]) != -1) {	// page should force company skin
					// check if the url doesn't already contain the 'forcedCompanySkin' parameter
					if (url.indexOf('forcedCompanySkin') == -1) {
						// add the missing parameter
						
						if (url.indexOf('?') == -1) {
							url += '?';
						}
						else {
							url += '&';
						}
						
						url += 'forcedCompanySkin=1';
					}
					break;
				}
			}			
		}
	}
	else {		
		// this is the not the first page
		if (gPopFrame[gTopmostPopup].src.indexOf('forcedCompanySkin=1') != -1 && url.indexOf('forcedCompanySkin') == -1) {
			// check if the url doesn't already contain the 'forcedCompanySkin' parameter			
			
			if (url.indexOf('?') == -1) {
				url += '?';
			}
			else {
				url += '&';
			}
			
			url += 'forcedCompanySkin=1';			
		}
	}
	
	gTopmostPopup++;	
	
	if ((navigator.userAgent.indexOf('Opera') != -1) && gTopmostPopup >= 1) {	
		var myParent = document.getElementById('popupContainer' + (gTopmostPopup-1));
		myParent.style.display = 'none';
	}
	
	var popupFrame = document.getElementById('popupFrame' + gTopmostPopup);
	
	if (popupFrame) {
		popupFrame.scrolling = scrolling;
	//	popupFrame.src = '/FP/loading.html';
		popupFrame.src = '';
	}
		
	gPopupIsShown = true;
	
	disableTabIndexes();
		
	if (gPopupMask[gTopmostPopup] == null) {
		//alert('no gPopupMask for gTopmostPopup ' + gTopmostPopup);
	}
	
	gPopupContainer[gTopmostPopup].style.width = "1px";
	gPopupContainer[gTopmostPopup].style.height = "1px";
	
	gPopFrame[gTopmostPopup].style.width = "1px";
	gPopFrame[gTopmostPopup].style.height = "1px";
	
	gPopupMask[gTopmostPopup].style.display = "block";
	gPopupContainer[gTopmostPopup].style.display = "block";
			
	// calculate where to place the window on screen
	updateMask(width, height);
	centerPopup(width, height);
	
	var titleBarHeight = parseInt(document.getElementById("popupTitleBar" + gTopmostPopup).offsetHeight, 10);
	
	gPopupContainer[gTopmostPopup].style.width = width + "px";
	gPopupContainer[gTopmostPopup].style.height = (height+titleBarHeight) + "px";
	// need to set the width of the iframe to the title bar width because of the dropshadow
	// some oddness was occuring and causing the frame to poke outside the border in IE6
	
	gPopFrame[gTopmostPopup].style.width = parseInt(document.getElementById("popupTitleBar" + gTopmostPopup).offsetWidth, 10) + "px";
	gPopFrame[gTopmostPopup].style.height = (height) + "px";
	
	// set the url
	if (url.indexOf('?') == -1) {
		url += '?';
	}
	else {
		url += '&';
	}
	
	url += 'popupHeight=' + height;
	
	gPopFrame[gTopmostPopup].src = url;	


	var frameIndex = -1;
	
	gReturnFunc[gTopmostPopup] = returnFunc;
		
	// for IE, hide combo boxes because of their z-order problem
	if (gHideSelects == true) {
		hideSelectBoxes();
	}		

	hideTopmostFlashes();
	
	//window.setTimeout("setPopTitle();", 600);
}


function updateContainerHeight(requiredHeight) {
	
	if (window != window.parent) {
		parent.updateContainerHeight(requiredHeight);
		return;
	}
		
	originalContainerHeight = parseInt(gPopupContainer[gTopmostPopup].style.height);
	originalFrameHeight = parseInt(gPopFrame[gTopmostPopup].style.height);

	var extraHeight = requiredHeight - originalContainerHeight;
	
	if (extraHeight != 0) {	
		
		gPopupContainer[gTopmostPopup].style.height = (originalContainerHeight + extraHeight) + "px";
		gPopFrame[gTopmostPopup].style.height = (originalContainerHeight + extraHeight) + "px";
	}
}



//
var gi = 0;

function updateMask(width, height) {
		
	if (!gInitPopUpCalled) {
		initPopUp();
	}
	
	if (gPopupIsShown == true) {
		
		if (width == null || isNaN(width)) {
			width = gPopupContainer[gTopmostPopup].offsetWidth;
		}
		
		if (height == null) {
			height = gPopupContainer[gTopmostPopup].offsetHeight;
		}
			
		var fullHeight = getViewportHeight();				
		var fullWidth = getViewportWidth();
				
		var theBody = document.body;
		
		var scTop = parseInt(theBody.scrollTop,10);
		var scLeft = parseInt(theBody.scrollLeft,10);
				
		gPopupMask[gTopmostPopup].style.height = fullHeight + "px";
				
		// compensating for a horizontal scrollbar for non IE browsers
		if (!document.all && document.body.scrollHeight > document.body.clientHeight) {
			// Not IE and has a vertical scrollbar
			fullWidth -= 21;
		}
	
		gPopupMask[gTopmostPopup].style.width = fullWidth + "px";
						
		gPopupMask[gTopmostPopup].style.top = scTop + "px";
		gPopupMask[gTopmostPopup].style.left = scLeft + "px";
	}
}

function centerPopup(width, height) {
	
	if (gPopupIsShown == true) {
		
		var fullHeight = getViewportHeight();				
		var fullWidth = getViewportWidth();
		var theBody = document.body;
		
		var scTop = parseInt(theBody.scrollTop,10);
		var scLeft = parseInt(theBody.scrollLeft,10);
		
		var titleBarHeight = parseInt(document.getElementById("popupTitleBar" + gTopmostPopup).offsetHeight, 10);
		
		gPopupContainer[gTopmostPopup].style.top = (scTop + ((fullHeight - (height+titleBarHeight)) / 2)) + "px";
		gPopupContainer[gTopmostPopup].style.left =  (scLeft + ((fullWidth - width) / 2)) + "px";
	}
}

addEvent(window, "resize", updateMask);
//addEvent(window, "scroll", updateMask);
window.onscroll = updateMask;

/**
 * @argument callReturnFunc - bool - determines if we call the return function specified
 * @argument returnVal - anything - return value 
 */
function hidePopWin(callReturnFunc) {
			
	if (gPopupMask[gTopmostPopup] == null) {
		return;
	}

	gPopupMask[gTopmostPopup].style.display = "none";
	gPopupContainer[gTopmostPopup].style.display = "none";
			
	if ((navigator.userAgent.indexOf('Opera') != -1) && gTopmostPopup >= 1) {	
		var myParent = document.getElementById('popupContainer' + (gTopmostPopup-1));
		myParent.style.display = 'inline';
	}
	
	// Unset the parameters of the popup just closed
	var popupFrame = document.getElementById('popupFrame' + gTopmostPopup);
	if (popupFrame) {
		popupFrame.scrolling = 'no';
		//popupFrame.src = '/FP/loading.html';
		popupFrame.src = '';	
	}
	
	gTopmostPopup--;
	
	if (gTopmostPopup == -1) {	
		// The last popup was closed
		restoreTabIndexes();
		gPopupIsShown = false;		
	}
	
	// display all select boxes that we hid before opening the popup now being closed
	if (gHideSelects == true) {
		showSelectBoxes();
	}	
	
	showTopmostFlashes();
	
	stopDrag(null);
	
	if (callReturnFunc == true && gReturnFunc[gTopmostPopup+1] != null) {	
	
		// the grid creates the popup iframes as the first ones in the page
		// so the array lookup below will work
		var callbackFuncParam = window.frames[gTopmostPopup+1].returnVal; 
				
		// invoke the appropriate callback
		if (gTopmostPopup == -1) {			
			// this is the first popup
			var func = gReturnFunc[gTopmostPopup+1];
			//alert("about to run: " + func + "(" + callbackFuncParam + ")");
			eval (func + "(" + callbackFuncParam + ")");
		}
		else {							
			var frm = window.frames[gTopmostPopup]; 
			var execute = "frm." + gReturnFunc[gTopmostPopup+1] + "(" + callbackFuncParam + ")";			
			//alert("about to run: " + execute);
			eval (execute);
			
		}
	}	
	
	gReturnFunc[gTopmostPopup+1] = null;
}


function doNotCallThisFunctionGetPopupParent() {
		
	if (gTopmostPopup == -1) {
		// this is the underlying page
		return null;
	}
	else if (gTopmostPopup == 0) {
		return window;
	}
	else {
		return window.frames[gTopmostPopup-1];
	}
}

/**
 * Sets the popup title based on the title of the html document it contains.
 * Uses a timeout to keep checking until the title is valid.
 */
function setPopTitle() {
	/*
	if (window.frames["popupFrame"].document.title == null) {
		window.setTimeout("setPopTitle();", 10);
	} else {
		document.getElementById("popupTitle").innerHTML = window.frames["popupFrame"].document.title;
	}
	*/
}

// Tab key trap. iff popup is shown and key was [TAB], suppress it.
// @argument e - event - keyboard event that caused this function to be called.
function keyDownHandler(e) {
    if (gPopupIsShown && e.keyCode == 9)  return false;
}

// For IE.  Go through predefined tags and disable tabbing into them.
function disableTabIndexes() {
	
	if (document.all) {
		var i = 0;
		for (var j = 0; j < gTabbableTags.length; j++) {
			var tagElements = document.getElementsByTagName(gTabbableTags[j]);
			for (var k = 0 ; k < tagElements.length; k++) {
				gTabIndexes[i] = tagElements[k].tabIndex;
				tagElements[k].tabIndex = -1;
				i++;
			}
		}
	}
}

// For IE. Restore tab-indexes.
function restoreTabIndexes() {
	if (document.all) {
		var i = 0;
		for (var j = 0; j < gTabbableTags.length; j++) {
			var tagElements = document.getElementsByTagName(gTabbableTags[j]);
			for (var k = 0 ; k < tagElements.length; k++) {
				tagElements[k].tabIndex = gTabIndexes[i];
				tagElements[k].tabEnabled = true;
				i++;
			}
		}
	}
}


function changeSelectVisibilty(wnd, visibilityStyle) {	
	var selects = wnd.document.getElementsByTagName('select');
	for (var i = 0; i < selects.length; i++) {
		selects[i].style.visibility = visibilityStyle;
	}
}

function hideSelectBoxes() {
	
	if (gTopmostPopup == 0) {
		changeSelectVisibilty(window, "hidden");
	} 
	else if (gTopmostPopup > 0){
		changeSelectVisibilty(document.frames[gTopmostPopup-1], "hidden");
	}
}

function showSelectBoxes() {
	
	if (gTopmostPopup == -1) {
		changeSelectVisibilty(window, "visible");
	} 
	else if (gTopmostPopup > -1){
		changeSelectVisibilty(document.frames[gTopmostPopup], "visible");
	}
}

function changeFlashVisibilty(wnd, visibilityStyle) {
		
	// the array below holds the IDs of all the flash elements that need to be hidden and re-shown when
	// the popup mechanism is activated
	flashObjectIDsToHide = new Array('orange_label', 'facerecognitionflash', 'photoBrowserGenerator', 'immersiveFamilyTree', 'immersiveLight');
	
	var flashOjects = wnd.document.getElementsByTagName('object');
	for (var i = 0; i < flashOjects.length; i++) {
		for (j=0; j<flashObjectIDsToHide.length; j++) {
			if (flashOjects[i].id == flashObjectIDsToHide[j]) {
				flashOjects[i].style.visibility = visibilityStyle;
				break;
			}
		}
	}
	
	// WHen embedding the Flash in Mozilla, the tag 'embed' is being used.
	// The code below will handle Mozilla
	var flashOjects = wnd.document.getElementsByTagName('embed');
	for (var i = 0; i < flashOjects.length; i++) {
		for (j=0; j<flashObjectIDsToHide.length; j++) {
			if (flashOjects[i].id == flashObjectIDsToHide[j]) {
				flashOjects[i].style.visibility = visibilityStyle;
				break;
			}
		}
	}
}

function hideTopmostFlashes() {
	if (gTopmostPopup == 0) {
		changeFlashVisibilty(window, "hidden");
	} 
	else if (gTopmostPopup > 0) {
		//changeFlashVisibilty(document.frames[gTopmostPopup-1], "hidden");
	}
}

function showTopmostFlashes() {
	if (gTopmostPopup == -1) {
		changeFlashVisibilty(window, "visible");
	} 
	else if (gTopmostPopup > -1) {
		//changeFlashVisibilty(document.frames[gTopmostPopup], "visible");
	}
}



var gIsDragging = false;
var gie = document.all;
var gnn6 = document.getElementById && !document.all;
var mouseDownX, mouseDownY;
var gCurrContainer;
var startX, startY;

function startDrag(e, containerNumber, direction) {
	
	// for IE, hide combo boxes because of their z-order problem
	if (gHideSelects == true) {
		hideSelectBoxes();
	}		

	hideTopmostFlashes();
			
	mouseDownX = gnn6 ? e.clientX : event.clientX;
	mouseDownY = gnn6 ? e.clientY : event.clientY;	

	gCurrContainer = document.getElementById('popupContainer' + containerNumber);
	startX = parseInt(gCurrContainer.style.left);
	startY = parseInt(gCurrContainer.style.top);	

	// according to the language, run one of the snippets below
	// they check whether the click occurred on top of the X and if so they don't start a drag,
	// resulting in the X getting clicked and closing the popup
	
	if (direction == 'LTR') {	
		var edge = startX + parseInt(gCurrContainer.style.width);
		if (mouseDownX > (edge - 22)) {
			return;
		}
	}
	else {		
		var edge = startX;
		if (mouseDownX < (edge + 22)) {
			return;
		}
	}

	var dragCover = document.getElementById('dragCover');
	dragCover.style.width = window.document.body.scrollWidth + "px";
	dragCover.style.height = window.document.body.scrollHeight + "px";
	dragCover.style.cursor = 'move';
	dragCover.style.display = 'block';
	
	gIsDragging = true;
}

function moveDrag(e) {

	if (gIsDragging) {		
		
		var left = gnn6 ? startX + e.clientX - mouseDownX : startX + event.clientX - mouseDownX;
		//left = Math.max(left, 0);
		//left = Math.min(left, document.body.clientWidth - parseInt(gCurrContainer.style.width));
		gCurrContainer.style.left = left;
    	
		var top = gnn6 ? startY + e.clientY - mouseDownY : startY + event.clientY - mouseDownY;
    	//top = Math.max(top, 0);
    	//top = Math.min(top, document.body.clientHeight - parseInt(gCurrContainer.style.height) - 4);
    	gCurrContainer.style.top = top;
    	
	    return false;
  	}
}

function stopDrag(e) {
	
	if (gIsDragging) {
		document.getElementById('dragCover').style.display = 'none';
		gIsDragging = false;
		document.getElementById('dragCover').style.cursor = 'default';
	}
	
	if (gHideSelects == true) {
		hideSelectBoxes();
	}
	
	hideTopmostFlashes();
}

var gSection;
var gTitle;
var gBody;
var gIcon;
var gButtons;
var gDefaultButton;
var gCallback;
var gMessageboxURL;

function messageBox2(section, title, body, icon, buttons, defaultButton, callback) {

	// remember the supplied parameters. If we will fail to display the popup message
	// inline in the page, we will revert to the original modal solution
	gSection = section;
	gTitle = title;
	gBody = body;
	gIcon = icon;
	gButtons = buttons;
	gDefaultButton = defaultButton;
	gCallback = callback;
	gMessageboxURL = messageBox2URL;
	
	handleMessageBoxPopup();
}

function cmessageBox2(section, title, body, icon, buttons, defaultButton, callback) {
	
	// remember the supplied parameters. If we will fail to display the popup message
	// inline in the page, we will revert to the original modal solution
	gSection = section;
	gTitle = title;
	gBody = body;
	gIcon = icon;
	gButtons = buttons;
	gDefaultButton = defaultButton;
	gCallback = callback;
	gMessageboxURL = cmessageBox2URL;
		
	handleMessageBoxPopup();
}

function handleMessageBoxPopup() {
					
	// -1 indicates that there is no popup window now displayed
	if ((gButtons == MB_OK || gButtons == MB_CLOSE) && 
		gTopmostPopup == -1 && 
		document.location.href.indexOf('createSiteRegistration.php') == -1 &&
		document.location.href.indexOf('member-sign-up.php') == -1) {
		// instead of triggering the popup in new modal iframe, we display it inline
						
		var url = notificationPanelURL;
		url = replace(url, '&title=' , '&title=' + gTitle);
		url = replace(url, '&body=' , '&body=' + gBody);
		url = replace(url, '&icon=' , '&icon=' + gIcon);
		url += '&randomParam=' + generateRandomString(5);
		
		// this is a string from the company translation manager
		if (gMessageboxURL.indexOf('&company=') > -1) {
			url += '&company=';
		}
		
		// look for the iframe that will communicate with the server
		var iframe = document.getElementById('notificationPanelIFrame');
		if (!iframe) {
			//alert("look for iframe solution");
			// this solution works if the current page is an iframe
			iframe = top.document.getElementById('notificationPanelIFrame');
		}
		
		if (!iframe) {
			// failed to find the iframe that will be used to communicate with the server
			// and to prepare the notification panel - revert to originanl modal solution
			//alert("Failed to find");
			invokePopupMessagebox();
		}
		else {
			//alert("found frame");
			iframe.src = url;
		}
	}
	else {
		// use the original modal solution for all the other types of messsage box popups
		//alert("original solution");
		invokePopupMessagebox();
	}
}

function notificationPanelCallback() {
	if (gCallback != null) {
		eval (gCallback + "(" + gButtons + ")");
	}
}

function invokePopupMessagebox() {
	
	var url = gMessageboxURL;
	url = replace(url, '&section=' , '&section=' + gSection);
	url = replace(url, '&title=' , '&title=' + gTitle);
	url = replace(url, '&body=' , '&body=' + gBody);
	url = replace(url, '&icon=' , '&icon=' + gIcon);
	url = replace(url, '&buttons=' , '&buttons=' + gButtons);
	url = replace(url, '&defButton=' , '&defButton=' + gDefaultButton);
			
    internalDoNotCallThisPopup(url, 380, 132, 'no', gCallback, true);
}



function internalDoNotCallThisPopup(url, width, height, scrolling, callback, isMessageBox) {

	// this fix just makes sure that if the page forgot to include file /Scripts/messageBoxScript.php
	// the variable will be set
	if (typeof(isNewCompanySkin) == 'undefined') {
		isNewCompanySkin = true;
	}
	
	if (isNewCompanySkin && !isMessageBox) { 
		width = Math.max(width, 563);
	}
	
	// Need to encode the url since it may contain spaces and other special chars
	url = encodeURI(url);
	
	showPopWin(url, width, height, callback, scrolling);
}



// preloads the graphics that make up a button - this prevents flickers on mouse events
var enabledButtons = new Array();

function preloadButtonGraphics() {
	var buttonImageStr = "";
	
	buttonImageStr += ' "' + buttonImagePath + 'buttonLeft.png" ';
	buttonImageStr += ', "' + buttonImagePath + 'buttonCenter.png" ';
	buttonImageStr += ', "' + buttonImagePath + 'buttonRight.png" ';
	buttonImageStr += ', "' + buttonImagePath + 'buttonLeftDisabled.png" ';
	buttonImageStr += ', "' + buttonImagePath + 'buttonCenterDisabled.png" ';
	buttonImageStr += ', "' + buttonImagePath + 'buttonRightDisabled.png" ';
	buttonImageStr += ', "' + buttonImagePath + 'buttonLeftHighlighted.png" ';
	buttonImageStr += ', "' + buttonImagePath + 'buttonCenterHighlighted.png" ';
	buttonImageStr += ', "' + buttonImagePath + 'buttonRighHighlighted.png" ';
	
	if (buttonImageStr){
		buttonImageStr = 'preloadImages(' + buttonImageStr + ')';
		eval(buttonImageStr);
	}
}

/**
 * invoked when the mouse moves over or out of a button
 */
function mouseMovement(buttonID, leftImage, centerImage, rightImage) {
			
	var value = enabledButtons[buttonID];		
	if (value == false) {		
		// the button is disabled
		return;
	}
	
	var leftID = 'buttonLeft' + buttonID;
	var centerID = 'buttonCenter' + buttonID;
	var rightID = 'buttonRight' + buttonID;			
		
	if (browserName == 'IE') {		
		// IE code
		var obj = document.getElementById(leftID);	
		obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, src='" + leftImage + "', sizingMethod=scale)";
	
		var obj = document.getElementById(centerID);
		obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, src='" + centerImage + "', sizingMethod=scale)";
	
		var obj = document.getElementById(rightID);
		obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, src='" + rightImage + "', sizingMethod=scale)";
	} else { 
		var obj = document.getElementById(leftID);	
		obj.src = leftImage;
		
		var obj = document.getElementById(centerID);
		obj.style.backgroundImage = 'url(' + centerImage + ')';
		
		var obj = document.getElementById(rightID);	
		obj.src = rightImage;
	}
}

/**
 * disables a button
 */
function disableButton(buttonID) {

	if (typeof(enabledButtons[buttonID]) == 'undefined' || enabledButtons[buttonID] == false) {
		// the button is already disabled
		return;
	}
	
	changeButtonMode(buttonID, false);
	var button = document.getElementById(buttonID);	
	button.className = 'normalHand';

	var centerID = document.getElementById("buttonCenter" + buttonID);
	centerID.className = 'ButtonDisabled';
}

/**
 * enables a button
 */
function enableButton(buttonID) {
	
	if (enabledButtons[buttonID] == true) {
		// the button is already enabled
		return;
	}
	
	changeButtonMode(buttonID, true);
	
	var button = document.getElementById(buttonID);	
	if (button != null){
		button.className = 'cursorHand';
	}
	var centerID = document.getElementById("buttonCenter" + buttonID);	
	if (centerID != null){
		centerID.className = 'Button';
	}	
}

function changeButtonMode(buttonID, shouldEnable) {
		
	var leftID = 'buttonLeft' + buttonID;
	var centerID = 'buttonCenter' + buttonID;
	var rightID = 'buttonRight' + buttonID;	
	
	var path = '' + buttonImagePath + '';
	if (shouldEnable) {
		var leftImage = path + 'buttonLeft.png';
		var centerImage = path + 'buttonCenter.png'
		var rightImage = path + 'buttonRight.png';
	}
	else {
		var leftImage = path + 'buttonLeftDisabled.png';
		var centerImage = path + 'buttonCenterDisabled.png'
		var rightImage = path + 'buttonRightDisabled.png';
	}
	
	var obj = document.getElementById(leftID);
	if (obj != null){
		if (browserName == 'IE') {		
			
			// IE code
			
			obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, src='" + leftImage + "', sizingMethod=scale)";
		
			var obj = document.getElementById(centerID);
			obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, src='" + centerImage + "', sizingMethod=scale)";
		
			var obj = document.getElementById(rightID);
			obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, src='" + rightImage + "', sizingMethod=scale)";
		} else { 
				
			obj.src = leftImage;
			
			var obj = document.getElementById(centerID);
			obj.style.backgroundImage = 'url(' + centerImage + ')';
			
			var obj = document.getElementById(rightID);	
			obj.src = rightImage;
		}
	}
	enabledButtons[buttonID] = shouldEnable;
}



function createSiteCallback(createSiteURL) {
			
	if (typeof createSiteURL == 'undefined' || createSiteURL == -1) {
		return;
	}
	
	if (createSiteURL.indexOf('&u=') != 0) {
					
		// the wizard was completed successfully
		var positionOfSessionParameter = createSiteURL.indexOf('u=');
		if (positionOfSessionParameter != 0) {
			// Visit the site - the targetURL is the url for visiting the new page
			window.location.href = createSiteURL;
			return;
		}
	}
	
	// The user either finished the wizard and created the site but asked
	// NOT to visit the new site, OR the user prematurely closed the wizard
	
	// need to refresh the underlying page		
	var newSession = extractParameterValueFromURL(contactMemberPopupURL, 'u');
	if (newSession == null) {
		return;
	}		
	
	refreshUnderlyingPage(newSession);	
}

// invoked when the pre reg completes
function createSitePreRegCallback(newSessionID) {
					
	var targetURL = getPreRegURL(newSessionID);
	if (targetURL == '') {
		// the user prematurely closed the pre-reg wizard
		return;
	}
	
	var windowParameters = 'width=742,height=567,left='+((screen.width-745)/2)+',top='+(((screen.height-570)/2)-50);
	windowParameters += ',location=no,toolbar=no,menubar=no,status=no,resizable=no';
	window.open(targetURL, '_blank', windowParameters);	
}


/** 
 * launch the create site wizard
 */
function createSite() {			
	launchCreateSiteWizard(createSiteURL);		
}



var gPreRegTargetURLOnceLoggedIn;

function getPreRegURL(newSessionString) {
	
	var returnedValue = newSessionString;
	if (typeof returnedValue == 'undefined' || returnedValue == -1) {
		// The Wizard was closed prematurely by the user
		return '';
	}
		
	// If we got here, the user must have successfully passed pre-reg
	// which means logged in, or created a new account and logged into it
	// This means that the user has a new session now (u parameter)
	// and we need to embed it into gPreRegTargetURLOnceLoggedIn instead of the old session
	// parameter which is there, and is stale
	
	var startOfUParam = gPreRegTargetURLOnceLoggedIn.indexOf('&u=');
	if (startOfUParam == -1) {	
		startOfUParam = gPreRegTargetURLOnceLoggedIn.indexOf('?u=');
	}
	if (startOfUParam == -1) {
		// The caller supplied a target URL without a session parameter nothing to replace - continue using it
		return gPreRegTargetURLOnceLoggedIn;
	}
		
	var sessionStartsHere = startOfUParam; 
		
	var afterU = gPreRegTargetURLOnceLoggedIn.indexOf('&', sessionStartsHere + 3);	// 3 is the length of '&u=' or '?u='
	if (afterU == -1) {
		// it was the last parameter
		newURL = gPreRegTargetURLOnceLoggedIn.substring(0, sessionStartsHere) + newSessionString;
	}
	else {
		// there are parameters after it
		newURL = gPreRegTargetURLOnceLoggedIn.substring(0,sessionStartsHere) + newSessionString + gPreRegTargetURLOnceLoggedIn.substring(afterU);
	}
			
	return newURL;
}

/** 
 * launch the Log in wizard
 */
function logIn() {		
	openCenteredPopup2(memberLoginURL, 380, 92, '', 'scroll:no;', 'logInCallback'); 
}









