/* --------------- START DOJO INCLUDES --------------------------- */

dojo.hostenv.loadModule("dojo.io.\*");
dojo.require("dojo.widget.ContentPane");

/* --------------- END DOJO INCLUDES --------------------------- */

/* --------------- STA	RT COOKIE MANAGEMENT --------------------------- */

function getCookie(cookieName) {
  var results = document.cookie.match ('(^|;) ?' + cookieName + '=([^;]*)(;|$)');
  if (results)
    return (unescape(results[2]));
  else
    return null;
}

function expireCookie(cookieName) {
	document.cookie = cookieName + '=;expires=Sat, 1 Dec 2007 12:00:00 UTC;path=/;';  
}

/* --------------- END COOKIE MANAGEMENT --------------------------- */

/* ---------------- SETUP SOME PNOENV STUFF -------------------- */
if(!pnoenv['chat.domain'])
	pnoenv['chat.domain'] = '';
if(!pnoenv['tomcat.domain'])
	pnoenv['tomcat.domain'] = '';
if(!pnoenv['secure.domain'])
	pnoenv['secure.domain'] = '';

if(getCookie('bypassDomain')) {
	pnoenv['listener.domain'] = getCookie('bypassDomain');
}
function getBaseCookieDomain() {
	var basePath = location.hostname;
	if (basePath) {
		var basePathParts = basePath.split('.');
		if (basePathParts && basePathParts.length > 2 // make sure url is not gay.com and we end up using '.com' 
			&& basePathParts[0] && isNaN(Number(basePathParts[0]))) // make sure URL is not IP 
		{
			basePathParts.splice(0,1);
			return basePathParts.join('.');
		}
	}
	return null;
}

/* --------------- START SIMPLE BROWSWER DETECT --------------------------- */
var isIE8 = navigator.userAgent.indexOf('MSIE 8') != -1;
var isIE7 = navigator.userAgent.indexOf('MSIE 7') != -1;
var isIE = navigator.userAgent.indexOf('MSIE') != -1;
var operationWillAbort = false;
if(isIE) operationWillAbort = true;
var isFirefox = navigator.userAgent.indexOf('Firefox') != -1;
var isOldFirefox = false;
if (isFirefox && (navigator.userAgent.indexOf('Firefox/0') != -1
		|| navigator.userAgent.indexOf('Firefox/1') != -1
		|| navigator.userAgent.indexOf('Firefox/2') != -1)){
	isFirefox = false; // excluding older versions
	isOldFirefox = true;
}
var isSafari = navigator.userAgent.indexOf('Safari') != -1;
if (isSafari && (navigator.userAgent.indexOf('Version') < 0
		|| navigator.userAgent.indexOf('Version/3.0') != -1)) {
	isSafari = false;  // excluding older versions
}
function isSupportedBrowser() {
	return isIE7 || isIE8 || isFirefox || isSafari;
}
// For the profile photo slider
var isWindows = navigator.platform.indexOf('Win') != -1;
var isMac = navigator.platform.indexOf('Mac') != -1;
var isFirefox3Mac104 = isMac && isFirefox && navigator.userAgent.indexOf('Firefox/3.0') != -1
				&& navigator.userAgent.indexOf('OS X 10.4') != -1;
/* ---------------- END SIMPLE BROWSWER DETECT ---------------------------- */

/* ------------------ START VIEWPORT DIMENSIONS --------------------------- */ 
function getViewportDimensions() {
	var viewportwidth;
	var viewportheight;
	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	if (typeof window.innerWidth != 'undefined') {
		viewportwidth = window.innerWidth;
		viewportheight = window.innerHeight;
	} // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
	else if (typeof document.documentElement != 'undefined' && 
				typeof document.documentElement.clientWidth !='undefined' && 
				document.documentElement.clientWidth != 0) {
		viewportwidth = document.documentElement.clientWidth;
		viewportheight = document.documentElement.clientHeight;
	} else { // older versions of IE
		viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
		viewportheight = document.getElementsByTagName('body')[0].clientHeight;
	}
	var viewport = {'width':viewportwidth, 'height':viewportheight};
	
	return viewport;
}

/* ------------------ END VIEWPORT DIMENSIONS --------------------------- */ 

/* --------------- START LOGIN MISC --------------------------- */

function setLoginPrefs() {
	if (location.href.indexOf('login') < 0) {
		document.cookie = "loginUrl="+location.href+"; path=/";
	}
}

function killLiteBox() {
	if(document.getElementById('liteBoxContainerDiv')) 
		document.getElementById('liteBoxContainerDiv').style.display = 'none';
}

function validateLoginForm(form) {
   if (form.j_username.value == '' || !form.j_username.value) {
		$("loginMsg").innerHTML="Please enter a username";
		return false;
	} else if (form.j_password.value == '' || !form.j_username.value) {
		$("loginMsg").innerHTML="Please enter a password";
		return false;	
	}else if (form.j_username.value.length > 30){	
	    $("loginMsg").innerHTML="Username cannot be more than 30 char";
		return false;
	}
	 else {
		return true;
	}
}

function openWhatsNewLogin() {
	var newWin = window.open('/help/whatsnew.do','whatsnew','width=871,height=520,scrollbars=no,location=no,menubar=no,toolbar=no');
	newWin.focus();
}

/* --------------- END LOGIN MISC --------------------------- */

/* ---------------- START NOT SUPPORTED BROWSWER LITEBOX ------------------ */
function openBrowserNotSupportedLitebox(){
	closePopupDetectorOverlay();
	if (location.href.indexOf('/help/tech/general.do') >= 0) {
		return;
	}
	var pane = dojo.widget.createWidget('ContentPane', {widgetId:'liteBoxContainerDiv'});
	pane.domNode.className = 'liteBoxContainer';
	document.body.appendChild(pane.domNode);
	pane.setUrl("/help/popupDetectorLitebox.do");
	pane.domNode.style.display = 'block';
	
	var viewport = getViewportDimensions();
	// Modify horizontal positioning for IE6
	if (isIE && !isIE7 && !isIE8) {
		var x = Math.round((viewport.width - 800) / 2) - 428;
		pane.domNode.style.left = x + 'px';
	} else {
		pane.domNode.style.left = Math.round((viewport.width - 800) / 2) + 'px';
	}
	pane.domNode.style.top = document.documentElement.scrollTop + Math.round((viewport.height - 320) / 2) + 'px';
	
	$("container").className = 'liteBoxBG';
}

function skipBrowserNotSupportedLitebox() {
	var oneMonthLater = new Date();
	oneMonthLater.setDate(oneMonthLater.getDate() + 30);
	var domain = getBaseCookieDomain();
	if (domain != null) domain = "domain="+domain+";" 
	else domain = "";
	document.cookie = "seenBrowserNotSupported="+true+";expires="+oneMonthLater.toUTCString()+";path=/;"+domain;
	closePopupDetectorOverlay();
	showingBrowserNotSupported = false;
	return false;
}

try {	
	var showingBrowserNotSupported = true;
	if (!isSupportedBrowser()) {
		var cookie = getCookie('seenBrowserNotSupported');
		if (cookie) {
			showingBrowserNotSupported = false;
		} else {
			dojo.addOnLoad(openBrowserNotSupportedLitebox);
		}
	} else {
		showingBrowserNotSupported = false;
	}
} catch (ex) {}
/* ---------------- END NOT SUPPORTED BROWSWER LITEBOX ------------------ */

/* ----------------- START POPUP BLOCKER SECTION ------------ */
if(getCookie('popupsnotblocked') == 'true') {
	isPopupBlocked = false;
} else {
	isPopupBlocked = true;
}

if(getCookie('openPopupDetectorLiteboxOnload') && !location.href.indexOf("/help/tech/popout.do") >= 0) {
	dojo.addOnLoad(function(evt) { openPopupDetectorLitebox(); });
	expireCookie('openPopupDetectorLiteboxOnload');
}

function runPopupDetector() {
	isPopupBlocked = true;
	if(getCookie('popupsnotblocked') == 'true') {
		isPopupBlocked = false;
		return;
	}

	try {
		window.open("about:blank","","width=1,height=1").close();
		isPopupBlocked = false;
		document.cookie = "popupsnotblocked=true;path=/;";
		try {
			closePopupDetectorOverlay();
		} catch(e) {}
	} catch (e) {
	}
}

/* ----------------- END POPUP BLOCKER SECTION ------------ */

/* --------------- START PROTOTYPE --------------------------- */

/*  Prototype JavaScript framework
 *  (c) 2005 Sam Stephenson <sam@conio.net>
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://prototype.conio.net/
*/

//note: modified & stripped down version of prototype.

var Class = {
	create: function() {
		return function() {
			this.initialize.apply(this, arguments);
		}
	}
}

Object.extend = function(destination, source) {
	for (property in source) destination[property] = source[property];
	return destination;
}

Function.prototype.bind = function(object) {
	var __method = this;
	return function() {
		return __method.apply(object, arguments);
	}
}

Function.prototype.bindAsEventListener = function(object) {
var __method = this;
	return function(event) {
		__method.call(object, event || window.event);
	}
}

function $() {
	if (arguments.length == 1) return get$(arguments[0]);
	var elements = [];
	$c(arguments).each(function(el){
		elements.push(get$(el));
	});
	return elements;

	function get$(el){
		if (typeof el == 'string') el = document.getElementById(el);
		return el;
	}
}

if (!window.Element) var Element = new Object();

Object.extend(Element, {
	remove: function(element) {
		element = $(element);
		element.parentNode.removeChild(element);
	},

	hasClassName: function(element, className) {
		element = $(element);
		if (!element) return;
		var hasClass = false;
		element.className.split(' ').each(function(cn){
			if (cn == className) hasClass = true;
		});
		return hasClass;
	},

	addClassName: function(element, className) {
		element = $(element);
		Element.removeClassName(element, className);
		element.className += ' ' + className;
	},
  
	removeClassName: function(element, className) {
		element = $(element);
		if (!element) return;
		var newClassName = '';
		element.className.split(' ').each(function(cn, i){
			if (cn != className){
				if (i > 0) newClassName += ' ';
				newClassName += cn;
			}
		});
		element.className = newClassName;
	},

	cleanWhitespace: function(element) {
		element = $(element);
		$c(element.childNodes).each(function(node){
			if (node.nodeType == 3 && !/\S/.test(node.nodeValue)) Element.remove(node);
		});
	},

	find: function(element, what) {
		element = $(element)[what];
		while (element.nodeType != 1) element = element[what];
		return element;
	}
});

var Position = {
	cumulativeOffset: function(element) {
		var valueT = 0, valueL = 0;
		do {
			valueT += element.offsetTop  || 0;
			valueL += element.offsetLeft || 0;
			element = element.offsetParent;
		} while (element);
		return [valueL, valueT];
	}
};

document.getElementsByClassName = function(className) {
	var children = document.getElementsByTagName('*') || document.all;
	var elements = [];
	$c(children).each(function(child){
		if (Element.hasClassName(child, className)) elements.push(child);
	});  
	return elements;
}

//useful array functions
Array.prototype.iterate = function(func){
	for(var i=0;i<this.length;i++) func(this[i], i);
}
if (!Array.prototype.each) Array.prototype.each = Array.prototype.iterate;

function $c(array){
	var nArray = [];
	for (var i=0;i<array.length;i++) nArray.push(array[i]);
	return nArray;
}


/* --------------- END PROTOTYPE --------------------------- */

/* --------------- START STRING TRIM  --------------------------- */

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
String.prototype.trimAll = function() {
	return this.replace(/(\s)/g,"");
}

/* --------------- END STRING TRIM  --------------------------- */

/* --------------- FORM SANITATION  --------------------------- */

function cleanXmlTags(str) {
	var strInputGtLt = str.replace(/&(lt|gt);/g, function (strMatch, p1){
			return (p1 == "lt")? "<" : ">";
		})
	var strInputEntLt = strInputGtLt.replace("&#60;","<");
	var strInputFin = strInputEntLt.replace("&#62;",">");
	var newString = strInputFin.replace(/<\/?[^>]+(>)/g, "");
	return newString;
}

function cleanFormValue(element) {
	element.value = cleanXmlTags(element.value);
}

/* --------------- END FORM SANITATION  --------------------------- */

/* --------------- START DASHBOARD AJAX --------------------------- */

var onlineStatusMap = new Array();
onlineStatusMap['ask_me'] = "Chatting";
onlineStatusMap['chat'] = "Chatting";
onlineStatusMap['watching_videos'] = "Chatting";
onlineStatusMap['meet_friends'] = "Chatting";
onlineStatusMap['hook_up'] = "Chatting";
onlineStatusMap['find_a_relationship'] = "Chatting";
onlineStatusMap['custom'] = "Chatting";
onlineStatusMap['check_email'] = "Chatting";
onlineStatusMap['invisible'] = 'Invisible';
onlineStatusMap['logged_out_of_chat'] = 'Online'; // online (no chat)
onlineStatusMap['offline']='Offline';

var onlineStatusCSSMap = new Array();
onlineStatusCSSMap['ask_me'] = 'headerOnline';
onlineStatusCSSMap['chat'] = 'headerOnline';
onlineStatusCSSMap['watching_videos'] = 'headerOnline';
onlineStatusCSSMap['meet_friends'] = 'headerOnline';
onlineStatusCSSMap['hook_up'] = 'headerOnline';
onlineStatusCSSMap['find_a_relationship'] = 'headerOnline';
onlineStatusCSSMap['custom'] = 'headerOnline';
onlineStatusCSSMap['check_email'] = 'headerOnline';
onlineStatusCSSMap['invisible'] = 'headerOnline invisibleStatus';
onlineStatusCSSMap['logged_out_of_chat'] = 'headerOnline noChatStatus';
onlineStatusCSSMap['offline']='headerOnline invisibleStatus';

var alertTimerTitleId = 0;
var titlePosition = 0;
var newMailGlobal = false;
// called by the dashboard when there is new mail
function setNewMailGlobalTrue() {
	newMailGlobal = true;
}
//This function rotate the title bar
//between the original title bar window, new mail
//and new IM requests

var alertTimerId;
function changeTitlebar()
{
	var newMail = newMailGlobal; 
	
	var msg  = "gay.com";
	var speed = 2000;
	var pos = titlePosition;

	var msg1  = document.getElementById("pageTitle").value;
	if (msg1 == null || msg1 == ""){
		msg1 = document.title;
	//	changeBackgroundNewMail(newMail);  
	//	changeBackgroundNewIM(newIM);     
		document.getElementById("pageTitle").value = msg1;
	}
	var msg2  = "New Mail ";
	
	if (newMail == false){
		document.title = msg1;
		if (alertTimerId != null || alertTimerId > 0){
			clearTimeout ( alertTimerId );
		}
		return;
	}
	
	//Show the original Title
	if(pos == 0){
		msg = msg1;
		pos = 1;
	}
	else if(pos == 1){  //Show "New Mail" title
		msg = msg2;
		pos = 0;
	}
	
	titlePosition = pos;
//	changeBackgroundNewMail(newMail);  //Make the dasboard Mail link to blink and change color 
//	changeBackgroundNewIM(newIM);     //Make the dasboard IM Request link to blink and change color
	document.title = msg;
	clearTimeout ( alertTimerTitleId );
	alertTimerTitleId = window.setTimeout("changeTitlebar()",speed);
}


/* --------------- END DASHBOARD AJAX --------------------------- */




/* --------------- START WINDOW MGMT --------------------------- */



var messengerRef;

var domainForTarget;
if(pnoenv['tomcat.domain'] && pnoenv['tomcat.domain'] != '') {
	domainForTarget=pnoenv['tomcat.domain'].substring(pnoenv['tomcat.domain'].indexOf('/')+2).toString().replace(/\./g, '_');
	if(domainForTarget.indexOf(':') >= 0)
		domainForTarget = domainForTarget.substring(0, domainForTarget.indexOf(':'));
} else {
	domainForTarget=document.domain.toString().replace(/\./g, '_');
}
var bypassDomainSwitch = false;
function setBypassDomainSwitch(value) {
	bypassDomainSwitch = value;
}

var mainWindowOptions = 'width=1000,height=700,toolbar=yes,menubar=yes,directories=yes,location=yes,resizable=yes,scrollbars=yes,status=yes';
function getMainWindowTarget() {
	// calling getMessengerWindow would open messenger if it's not open
	// that's ok because this is only used in chat
	return 'mainWindow_'+domainForTarget+'_'+getMessengerWindow().domainForTargetCount;
}

function getMainWindow() {
	var mainWindow = window.open('', getMainWindowTarget(), mainWindowOptions);
	try {
		if(mainWindow && !mainWindow.closed && mainWindow.document.domain == document.domain) {
			return mainWindow;
		} else {
			mainWindow.name = '';
		}
	} catch (ex) {}
	getMessengerWindow().domainForTargetCount++;
	return getMainWindow();
}

function openInMainWindow(url) {
	var mainWindow = window.open('', getMainWindowTarget(), mainWindowOptions);
	try {
		if(mainWindow && !mainWindow.closed && mainWindow.document.domain == document.domain) {
			mainWindow.document.location.href = url;
			mainWindow.focus(); 
			return;
		} else {
			mainWindow.name = '';
		}
	} catch (ex) { }
	getMessengerWindow().domainForTargetCount++;
	openInMainWindow(url);
}

function getBackLinkForwardPath() {
	if (isChatWindow()) {
		var the_opener = getMainWindow();
		if (the_opener && !the_opener.closed) {
			return escape(the_opener.location.pathname + the_opener.location.search);
		} else {
			return "";
		}
	} else {
		return escape(location.pathname + location.search);
	}
}
function isChatWindow() {
	return (document.getElementById("messengerChatWindow") ||
				document.getElementById("groupChatWindow") ||
				document.getElementById("privateChatWindow"));
}
function isSmallScreen() {
	return screen.height < 700;
}
function getChatWindowOpenOptions(w, h) {
	return 'width='+w+',height='+(h)+',resizable=yes';
}
function getMessengerWindowOpenOptions() {
	return getChatWindowOpenOptions(275, 673);
}

var lastOpen = new Date(); 
lastOpen.setDate(lastOpen.getDate()-1);
function openMessenger() {
	var diff = new Date() - lastOpen;
	// Protect from double clicking messenger.
	if(diff < 2000) {
		return false;
	}
	window.name = 'mainWindow_'+domainForTarget+'_1';//must match format in getMainWindowTarget()
	lastOpen = new Date();
	messengerRef = window.open('/chat/messenger.do', 'gcom_messenger'+domainForTarget, getMessengerWindowOpenOptions());
	return messengerRef;
}

function doSecureMessenger() {
	window.open(pnoenv['tomcat.domain'] + '/chat/secureMessengerPopper.do?type=msg', 'popper', 'height=1,width=1');
}

function doSecureGrp() {
	window.open(pnoenv['tomcat.domain'] + '/chat/secureMessengerPopper.do?type=grp', 'popper', 'height=1,width=1');
}

function getMessengerWindow() {
	if(isPopupBlocked) {
		try {
			/* This will fail everywhere except in chat windows because we
			define isChatWin there. Thus it goes into the catch block. */
			if(isChatWin) {}
		} catch(e) {
			openPopupDetectorLitebox();
			return null;
		}
	}
	if(pnoenv['secure.domain'] != '' && location.href.indexOf(pnoenv['secure.domain']) == 0) {
		doSecureMessenger();
		return;
	}
	
	if(messengerRef == null) {
		messengerRef = window.open('', 'gcom_messenger'+domainForTarget, getMessengerWindowOpenOptions());
	}
	try {
		if(messengerRef.document.getElementById('MessengerContentPaneDiv') != null) {
			return messengerRef;
		}
	} catch(ex) {}
	var retVal = openMessenger();
	if(retVal == false) {
		messengerRef.close();
	}
	return retVal;
}

function openFromMessenger(child, chatwith) {
	if(child == 'grp' && pnoenv['secure.domain'] != '' && location.href.indexOf(pnoenv['secure.domain']) == 0) {
		doSecureGrp();
		return;
	}
	if(isMsgrWinOpen()) {
		if (child == 'grp') {
			if(getMessengerPane().isConnected) {
				getMessengerPane().openGroupChatWindow();
			}
		}
		if (child == 'pvt')
			getMessengerPane().openPvtChatWindow(chatwith);
	} else {
		if(!getMessengerWindow())
			return;
		window.setTimeout(function(evt) { openFromMessenger(child, chatwith); }, 2000);
	}
}

function getMessengerPane() {
	try {
		return getMessengerWindow().dojo.widget.getWidgetById('messenger');
	} catch(e) {
		window.setTimeout(function(evt) { getMessengerPane(); }, 1000);
	}
}

// Chat cookie
function getChatCookieDomain() {
	var dom = location.hostname;
	if (dom == "") {
		return "";
	}
	var domain = dom.split(".");
	var domainLength = domain.length;
	if (domainLength == 4 && dom.replace("\.", "").match("^[0-9]*$")) {
		return "";
	} 
	if (domainLength <= 2) {
		return "";
	}
	domain[0] = "";
	return "domain="+domain.join(".")+";";
}
function isMsgrWinOpen() {
	var msgCookie = getCookie("chat");
	var msgCookieStatus = (msgCookie != null && msgCookie.charAt(0) == 1)?true:false;
	return msgCookieStatus;
}

function getConfirmCloseCookieValue() {
	var msgCookie = getCookie("chat");
	var msgCookieStatus = (msgCookie != null && msgCookie.charAt(1) == 1)?true:false;
	return msgCookieStatus;
}

function setMsgrWinOpen(chatWinOpen) {
	var confirmClose = (getConfirmCloseCookieValue())?1:0;
	document.cookie = "chat=" + chatWinOpen + confirmClose + ';path=/;' + getChatCookieDomain();
}

function setConfirmCloseStatus(confirmClose) { 
	var chatWinOpen = (getConfirmCloseCookieValue())?1:0;
	document.cookie = "chat=" + chatWinOpen + confirmClose + ';path=/;' + getChatCookieDomain();
}

function setWelcomeReturnInterceptCookie(welcomeReturnUrl) {
	document.cookie = "WELCOME_PAGE_RETURN_URL=" + welcomeReturnUrl + ';path=/;';
}

// to initiate IM with another user
function showIM(chatwith) {
	if(document.getElementById("messengerChatWindow")) {
		// onl do this from messenger, or IM window will not work correctly
		addIMSession(getPvtChatWindow(), chatwith);
	} else {
		// call this method from messenger since this window is not messenger
		openFromMessenger('pvt', chatwith);
	}
}

/* --------------- END WINDOW MGMT --------------------------- */

/* --------------- START POPUP DETECTOR LITE-BOX --------------------------- */
function showPopupDetectorSteps() {
	if(isFirefox){
		browserBasedClassName = "popupDetectorFF";
	} else if(isIE7 || isIE8) { /* IE6 is considered "other" */
		browserBasedClassName = "popupDetectorIE7Plus";
	} else if (isSafari) {
		browserBasedClassName = "popupDetectorSafari";
	} else {
		browserBasedClassName = "popupDetectorOther";
	}
	var liteBoxContentDiv = $("liteBoxContentDiv");
	liteBoxContentDiv.className="popupDetectorLitebox "+browserBasedClassName;
	
	liteBoxContentDiv.style.left = Math.round((document.body.clientWidth - 750) / 2) + 'px';
	if (document.documentElement.scrollTop == 0) {
		liteBoxContentDiv.style.top = document.documentElement.scrollTop+90 + "px";
	} else {
		liteBoxContentDiv.style.top = document.documentElement.scrollTop+20 + "px";
	}
}
function openPopupDetectorLitebox(){
	if(showingBrowserNotSupported) {
		return; // don't show two liteboxes at the same time
	}
	if(document.readyState && document.readyState!="complete" && isIE) {
		dojo.addOnLoad(openPopupDetectorLitebox);
		return;
	}
	closePopupDetectorOverlay();
	var pane = dojo.widget.createWidget('ContentPane', {widgetId:'liteBoxContainerDiv'});
	pane.domNode.className = 'liteBoxContainer';
	document.body.appendChild(pane.domNode);
	pane.setUrl("/chat/popupDetectorLitebox.do");
	pane.domNode.style.display = 'block';
	try {
		showPopupDetectorSteps();
	} catch (ex) {
		pane.onLoad=showPopupDetectorSteps;
	}
	$("container").className = 'liteBoxBG';
}


function openBlockIntercept(targetId){
	var viewport = getViewportDimensions();
	var pane = dojo.widget.createWidget('ContentPane', {widgetId:'liteBoxContainerDiv'});
	pane.domNode.className = 'liteBoxContainer';
	document.body.appendChild(pane.domNode);
	pane.setUrl('/profile/interceptBlock.do?formAction=blockIntercept&memberId=' + targetId);
	
	pane.domNode.style.left = Math.round((viewport.width - 266) / 2) + 'px';
	pane.domNode.style.top = Math.round((viewport.height - 200) / 2) + 'px';
	
	pane.domNode.style.display = 'block';
	$("container").className = 'liteBoxBG';
}

 
function closePopupDetectorOverlay() {
	if(dojo.widget.getWidgetById('liteBoxContainerDiv')) {
		var pane = dojo.widget.getWidgetById('liteBoxContainerDiv');
		pane.domNode.style.display = 'none';
		pane.destroy();
		$("container").className = '';
	}
}
/* --------------- END POPUP DETECTOR LITE-BOX --------------------------- */

/* --------------- START Block Intercept LITE-BOX --------------------------- */
function closeBlockOverlay() {
	if(dojo.widget.getWidgetById('liteBoxContainerDiv')) {
		var pane = dojo.widget.getWidgetById('liteBoxContainerDiv');
		pane.domNode.style.display = 'none';
		pane.destroy();
		$("container").className = '';
	}
}
/* --------------- END Block Intercept LITE-BOX --------------------------- */

/* --------------- START DIGITAL MEDIA --------------------------- */


var digitalMediaSlideshowIntervalLength = 10000; // miliseconds
var currentDigitalMediaArticle = 0;
var digitalMediaSlideshowInterval = false;

function setDigitalMediaArticle(ndx) {
	if (document.getElementsByClassName('digitalMediaArticle').length > 0) {
		$("digitalMediaJumpButton-"+currentDigitalMediaArticle).className = " ";
		document.getElementsByClassName('digitalMediaArticle')[currentDigitalMediaArticle].style.display = "none";

		currentDigitalMediaArticle = ndx;
		if (currentDigitalMediaArticle >= document.getElementsByClassName('digitalMediaArticle').length) currentDigitalMediaArticle = 0;
		if (currentDigitalMediaArticle < 0) currentDigitalMediaArticle = document.getElementsByClassName('digitalMediaArticle').length-1;

		$("digitalMediaJumpButton-"+currentDigitalMediaArticle).className = "current";
		document.getElementsByClassName('digitalMediaArticle')[currentDigitalMediaArticle].style.display = "block";
	} else $('digitalMediaArticleTitle').innerHTML = "There are no articles to display.";
}

function pausePlayDigitalMediaSlideshow(pause) {
  if (pause) {
	window.clearInterval(digitalMediaSlideshowInterval);
	digitalMediaSlideshowInterval = false;
	$('digitalMediaPausePlay').className = 'digitalMediaPlay';
	$('digitalMediaPausePlay').title = digitalMediaTranslations['play'];
  } else {
	advanceDigitalMediaSlideshow();
	digitalMediaSlideshowInterval = window.setInterval("advanceDigitalMediaSlideshow()", digitalMediaSlideshowIntervalLength);
	$('digitalMediaPausePlay').className = 'digitalMediaPause';
	$('digitalMediaPausePlay').title = digitalMediaTranslations['pause'];
  }
}

function toggleDigitalMediaSlideshow() {
  pausePlayDigitalMediaSlideshow(digitalMediaSlideshowInterval);
}

function advanceDigitalMediaSlideshow() {
  setDigitalMediaArticle(currentDigitalMediaArticle+1);
}

function jumpToDigitalMediaArticle(ndx) {
  pausePlayDigitalMediaSlideshow(true);
  setDigitalMediaArticle(ndx);
}

function writeDigitalMediaJumpButtons() {
	var newHtml = "<table><tr>";
	for(ndx = 0; ndx < document.getElementsByClassName('digitalMediaArticle').length; ndx++) {
	  newHtml += "<td><a href='#' id='digitalMediaJumpButton-"+ndx+
					 "' onclick='jumpToDigitalMediaArticle("+ndx+"); return false;'>"+(ndx+1)+"</a></td>";
	}
	newHtml += "</tr></table>";
	
	$('digitalMediajumpButtons').innerHTML = newHtml;
}

function writeDigitalMediaJumpButtonsHomePage(pageType) {
	var newHtml = "<table class='digitalMediajumpTable' border='0'><tr>";
	var thumbMedia;
	var count; 
	for(ndx = 0; ndx < document.getElementsByClassName('digitalMediaArticle').length; ndx++) {
	  count = parseInt(ndx) + parseInt(1);
	  thumbMedia = document.getElementById("digitalMediaPicture_"+ (parseInt(ndx) + parseInt(1)));
	  newHtml += "<td><a href='#' id='digitalMediaJumpButton-"+ndx+
					 "' onclick='" + 
					 (!pageType ? "toggleHomeThumbnail(\"digitalMediaThumbs\");" : "")  + 
					 "jumpToDigitalMediaArticle("+ndx+"); return false;'><img src='"+thumbMedia.value+"'/></a></td>";
	}
	newHtml += "</tr></table>";	
	$('digitalMediajumpButtons').innerHTML = newHtml;
}

var dojo_io_required = 0;

function checkCommentForm(){
  var the_comment = document.addCommentForm.comment;
  var msg = "";
  if(!notEmptyField(the_comment.value)) {
    msg += "Please enter comment.";
  }
  if(the_comment.value.length >= 4000) {
    msg += "Please enter comment less than 4000 characters.";
  }
  if(msg) {
   dojo.byId("addMsg").innerHTML = msg;
   the_comment.focus();
   return false;
  } else {
   return true;
  }
}
function notEmptyField(content) {
 var re = /\w/;
 if(re.test(content)) {
  return true;
 } else {
  return false;
 } 
}

function submitSuppressCommentForm(id,the_action) {
 var the_form = document.addCommentForm;
 var contentUrl = the_form.contentUrl.value;
 var contentCollection = the_form.contentCollection.value;
 var contentId = the_form.contentId.value;
 
 if(the_action == "display") {
  var actionText = '<a href="" onclick="submitSuppressCommentForm(' + id + ',\'hidden\');return false;"><b>hide comment</b></a>';
 } else {
  var actionText = '<a href="" onclick="submitSuppressCommentForm(' + id + ',\'display\');return false;"><b>display comment</b></a>';
 }
 
 dojo.io.bind({
 url: "/content/discussion/suppressComment.do?commentId=" + id + "&commentAction=" + the_action + "&contentUrl=" + escape(contentUrl) + "&contentCollection=" + contentCollection + "&contentId=" + contentId,
 load: function(type, data, evt) {
   dojo.byId("msg" + id).innerHTML = data;
   if (data.indexOf("login")==-1) {
	   dojo.byId("actionLink" + id).innerHTML = actionText;
	   document.getElementById("comment" + id).className = the_action;
   }
   return;
  },
  method: "GET"
 });
 
}

/* --------------- END DIGITAL MEDIA --------------------------- */

/* --------------- START SEARCH LOCATION AJAX--------------------------- */





var sortTermGlobal;

var activeSearchForm = null;	
	
function doRefreshSearch(locationId, typeRefresh, formName, cityName, postal) {
    activeSearchForm = (formName ? document.forms[formName] : document.searchForm );
	dojo.io.bind( {
	        url: "/locationList.do",
	        content: {locationId: locationId, refresh: typeRefresh, postal: postal, formName: formName},
	        method: "POST",
	        mimetype: "text/html",
	        load: function(type, value, evt) {
	            processResponseSearch(value, locationId, typeRefresh, postal, formName);
	        },            
	        error: function(type, error) { alert("Error: " + error.reason); }
	   });
}

function processResponseSearch(response, locationId, typeRefresh, postal, formName) {

	if (typeRefresh == 'POSTALCHECK') {
		refreshLocationSearch(response, typeRefresh, postal, formName);
	} else {		
		refreshDropDownListSearch(response, typeRefresh, postal, formName);
		
	}
}

function refreshDropDownListSearch(response, typeRefresh, postal, formName){
	var form = document.forms[formName];

	var xmlDoc = dojo.dom.createDocumentFromText(response);
	var listLocation = xmlDoc.getElementsByTagName('LIST');  
    var listType = listLocation[0].attributes[0].nodeValue;
	var ClearState  = listLocation[0].attributes[1].nodeValue;
	var listElements = xmlDoc.getElementsByTagName('NAME');
	var listElementsId = xmlDoc.getElementsByTagName('ID');   
	if ( 'YES' == ClearState){
		removeAllOptionSearch("stateSelected");
	}
	if (typeRefresh = 'STATE'){
		removeAllOptionSearch("citySelected");
	}
	
	removeAllOptionSearch(listType);
	for (var i = 0; i < listElements.length; i++) {
		insertOptionSearch(listElements[i].firstChild.nodeValue, listElementsId[i].firstChild.nodeValue, listType);
	}
}

function refreshLocationSearch(response, typeRefresh, postal, formName) {
    activeSearchForm = document.forms[formName];
  	var xmlDoc = dojo.dom.createDocumentFromText(response);
	var stateLoc = xmlDoc.getElementsByTagName('STATE'); 
	var cityLoc = xmlDoc.getElementsByTagName('CITY');
	var locContainer = document.getElementById('location');
	var stateTxt = document.createTextNode(stateLoc[0].firstChild.nodeValue);
	var dataCheck = stateLoc[0].firstChild.nodeValue;
	var sepTxt = document.createTextNode(', ');
	var cityTxt = document.createTextNode(cityLoc[0].firstChild.nodeValue);
	//TODO Remove hard coded error, no i18l, no CSS control
	var errorTxt = "<span class='errorColor'>(We cant find that ZIP code.)</span>";
	
	removeChildren(locContainer);
	
	if (dataCheck != "null") {	
		locContainer.appendChild(cityTxt);
		locContainer.appendChild(sepTxt);
		locContainer.appendChild(stateTxt); 
	} else {
		locContainer.innerHTML = errorTxt;
	}
}

function insertOptionSearch(name, value, listType){
    //var elSel = document.getElementsByName(listType)[0];
    var elSel = activeSearchForm.elements[listType];
    
	if (elSel != null && elSel.options != null) {
        elSel.options[elSel.options.length] = 
            new Option(name, value, false, false);
    }
}

function removeAllOptionSearch(listType) {
	//var elSel = document.getElementsByName(listType)[0];
	var elSel = activeSearchForm.elements[listType];
	if (elSel.length > 0) {	
		var elOptNew = document.createElement('option');
		for (var i=elSel.options.length-1;i>=0;i--) {
			elSel.remove(i);
		}
		if(listType=="stateSelected") {
		 var selectText = "SELECT";
		 } else if (listType=="citySelected") {
		  var selectText = "SELECT";
		} else {
		 var selectText = "SELECT";
		}
		elOptNew.text = selectText;
		elOptNew.value = "";
		elSel.options[0]=elOptNew;
	}
}

function removeChildren(parent) {
	if (parent && parent.hasChildNodes()) {
    	while (parent.childNodes.length >= 1) {
        	parent.removeChild(parent.firstChild);       
    	} 
	}
}	

// For search
function setHiddenValuesSearch(formName) {
	activeSearchForm = (formName ? document.forms[formName] : document.searchForm );
    var form=activeSearchForm;
     
	var indexCountry = form.countrySelected.selectedIndex;	
	var indexState = form.stateSelected.selectedIndex;
	var indexCity = form.citySelected.selectedIndex;
		
	var cityName = form.citySelected[indexCity].text ;
	var stateName = form.stateSelected[indexState].text ;
	var countryName = form.countrySelected[indexCountry].text;
    var postalCodeName = form.postalCodeSelected.value;
	
	var cityId =  form.citySelected[indexCity].value;
	var stateId = form.stateSelected[indexState].value; 
	var countryId = form.countrySelected[indexCountry].value;
	
	form.country.value = countryName;
	if (stateId == "") {
		form.state.value = "";
	} else {
		form.state.value = stateName;
	}
	if (cityId == "") {
		form.city.value = "";
	} else {
		form.city.value = cityName;
	}
	form.postalCode.value = postalCodeName;
	if (postalCodeName != "") {
		form.city.value = "";
	}
}

//Set join fields status
//233 - United States, 231 - United Kingdom, 46 - Canada
function setLocationFieldsSearch(formName, arg) {	
    var activeSearchForm = document.forms[formName];
    var form = document.forms[formName];
 
	var stateField = document.getElementById('stateField_'+formName);
	var cityField = document.getElementById('cityField_'+formName);
	var postalField = document.getElementById('postalField_'+formName);
	//var indexCountry = document.getElementsByName('countrySelected')[0].selectedIndex;
	//var countryId = document.getElementsByName('countrySelected')[0][indexCountry].value;
	var indexCountry = form.elements['countrySelected'].selectedIndex;
	var countryId = form.elements['countrySelected'][indexCountry].value;
	
	//US Default
	if (countryId == "233") {
		stateField.style.display = 'block';
		postalField.style.display = 'none';
		if (arg == 'city') {			
			cityField.style.display = 'block';		
		} else {
		    cityField.style.display = 'none';
		}
	}
	if (countryId == "46" || countryId == "231") {		
		stateField.style.display = 'block';
		postalField.style.display = 'none';
		if (arg == 'city') {
			cityField.style.display = 'block';
		} else {
			cityField.style.display = 'none';
		}
	}
	
	if (countryId != "46" && countryId != "231" && countryId != "233") {	
		stateField.style.display = 'none';
		cityField.style.display = 'block';
		postalField.style.display = 'none';
	}
	
	if (arg == 'postalHidden') {
		form.proximityPostalCode.value = form.postalCode.value;	
		form.postalCodeSelected.value = form.postalCode.value;	
		doRefreshSearch('233','POSTALCHECK',formName,'233', form.postalCode.value)
	}
	
	if (arg == 'stateHidden') {
		showFieldsSearch('state',formName);
	}
}

//State or Postal links
function showFieldsSearch(fields, formName, doNotClearLocation) {
	var form=activeSearchForm;
	var clearLocation = (doNotClearLocation ? false : true);
	var postalField = document.getElementById('postalField_'+formName);
	var stateField = document.getElementById('stateField_'+formName);
	var cityField = document.getElementById('cityField_'+formName);
	var locContainer = document.getElementById('location');
	
	if (fields == 'postal') {
		if (clearLocation) {
			removeChildren(locContainer);
		}
		form.state.value = "";
		form.city.value = "";
		removeAllOptionSearch("stateSelected");
		removeAllOptionSearch("citySelected");
		postalField.style.display = 'block';
		stateField.style.display = 'none';
		cityField.style.display = 'none';
	}
		
	if (fields == 'state') {
		if (clearLocation) {
			removeChildren(locContainer);
		}
		form.postalCode.value = "";
		form.postalCodeSelected.value = "";
		postalField.style.display = 'none';
		stateField.style.display = 'block';
		cityField.style.display = 'none';
	}

	if (fields == 'country') {
		if (clearLocation) {
			removeChildren(locContainer);
		}
		form.postalCodeSelected.value = "";
	}	
}


function getCountryId() {
	//var indexCountry = document.getElementsByName('countrySelected')[0].selectedIndex;
	//var countryId = document.getElementsByName('countrySelected')[0][indexCountry].value;
	var indexCountry = activeSearchForm.elements['countrySelected'].selectedIndex;
	var countryId = activeSearchForm.elements['countrySelected'][indexCountry].value;
	return countryId;
}
function getStateId() {
	//var indexState = document.getElementsByName('stateSelected')[0].selectedIndex;
	//var stateId = document.getElementsByName('stateSelected')[0][indexState].value;
	var indexState = activeSearchForm.elements['stateSelected'].selectedIndex;
	var stateId = activeSearchForm.elements['stateSelected'][indexState].value;
	return stateId;
}
function getCityId() {
	//var indexCity = document.getElementsByName('citySelected')[0].selectedIndex;
	//var cityId = document.getElementsByName('citySelected')[0][indexCity].value;
	var indexCity = activeSearchForm.elements['citySelected'].selectedIndex;
	var cityId = activeSearchForm.elements['citySelected'][indexCity].value;
	return cityId;
}		
function getStateHidden(form) {
	var stateHidden = form.state.value;
	return 	stateHidden;
}		
function getCityHidden(form) {
	var cityHidden = form.city.value;
	return 	cityHidden;
}		
function getPostalCodeHidden(form) {
	var postalCodeHidden = form.postalCode.value;
	return postalCodeHidden;
}	

// Initialize field status
function fieldInitSearch(formName) {
		
   var form=(formName ? document.forms[formName] : document.searchForm);
   activeSearchForm=form;
   var countryId = getCountryId();
   var countryName = form.country.value;
   if(countryId=='233' && countryName!="United State") {
    for(var i=0; i < form.countrySelected.options.length; i++) {
     if(form.countrySelected.options[i].text.toLowerCase() == countryName.toLowerCase()) { 
       countryId=form.countrySelected.options[i].value;
       form.countrySelected.options[i].selected=true;
       break;
     }
    }
   }
	
	// Empty fields; reset to default
	if ((getStateHidden(form) == "") && (getCityHidden(form) == "") && (getPostalCodeHidden(form) == "")) {
		window.document.onload = doRefreshSearch(countryId,'STATE',formName);
		window.document.onload = setLocationFieldsSearch(formName);
	}

	// Have postal in US
	if (getPostalCodeHidden(form) != "" && getCountryId() == '233') {
	    window.document.onload = showFieldsSearch('postal',formName);
		window.document.onload = setLocationFieldsSearch(formName,'postalHidden');
	}
	
	// Have state in US
	if (getStateHidden(form) != "" && countryId == '233') {
		window.document.onload = showFieldsSearch('state',formName);
		window.document.onload = setLocationFieldsSearch(formName,'stateHidden');
		window.document.onload = doRefreshSearch(getCountryId(),'STATE',formName);
		setTimeout(
		function doState() {
			for (var i=0;i<form.stateSelected.options.length;i++) {
    			if (form.stateSelected.options[i].text == form.state.value) {
					form.stateSelected.options[i].selected = true;
				}
			}
			doRefreshSearch(getStateId(),'CITY');
			document.getElementById('cityField_'+ formName).style.display = 'block';
			
		}, 1000);
	}
	
	
	// Have state and city and in US
	if (getStateHidden(form) != "" && getCityHidden(form) != "" && countryId == '233') {
		window.document.onload = showFieldsSearch('state',formName);
		window.document.onload = setLocationFieldsSearch(formName,'stateHidden');
		window.document.onload = doRefreshSearch(getCountryId(),'STATE',formName);
		setTimeout(
		function doState() {
			for (var i=0;i<form.stateSelected.options.length;i++) {
    			if (form.stateSelected.options[i].text == form.state.value) {
					form.stateSelected.options[i].selected = true;
				}
			}
			doRefreshSearch(getStateId(),'CITY');
			document.getElementById('cityField_'+ formName).style.display = 'block';
			setTimeout(
			function doCity() {				
				for (var i=0;i<form.citySelected.options.length;i++) {
	   				if (form.citySelected.options[i].text.toLowerCase() == form.city.value.toLowerCase()) {
						form.citySelected.options[i].selected = true;
					}
				}
			}, 1000);
		}, 1000);
		
	}
	
	
	// Have state and city in CA or UK
	if ((getStateHidden(form) != "" || getCityHidden(form) != "") && (countryId  == '231' || countryId  == '46')) {
		window.document.onload = setLocationFieldsSearch(formName);
					
		window.document.onload = doRefreshSearch(getCountryId(),'STATE',formName);
		
		setTimeout(
		function doState() {
			for (var i=0;i<form.stateSelected.options.length;i++) {
    			if (form.stateSelected.options[i].text == form.state.value) {
					form.stateSelected.options[i].selected = true;
				}
			}
			doRefreshSearch(getStateId(),'CITY',formName);
			document.getElementById('cityField_'+ formName).style.display = 'block';
			setTimeout(
			function doCityAjax() {
		  		doRefreshSearch(getStateId(),'CITY',formName);
		  		setTimeout(
				function doCity() {
					for (var i=0;i<form.citySelected.options.length;i++) {
	   					if (form.citySelected.options[i].text == form.city.value) {
							form.citySelected.options[i].selected = true;
						}
					}
				}, 1000);
		  	}, 1000);
		}, 1000);
		
	}
	
	
	// Have Intl country and city
	if ((countryId  != '233') && (countryId  != '231') && (countryId  != '46')) {
		window.document.onload = setLocationFieldsSearch(formName);
		
		doRefreshSearch(countryId ,'CITY',formName);
		
		setTimeout (
		function doIntlCity() {
			for (var i=0;i<form.citySelected.options.length;i++) {
    			if (form.citySelected.options[i].text == form.city.value) {
					form.citySelected.options[i].selected = true;
				}
			}
		},1000);	
	}
}

function eraseProximityPostalCode(formName) {
	//clear-out proximity-check when users select state or city instead
	var form = document.forms[formName];
	form.proximityPostalCode.value = "";	
	document.getElementById('location').innerHTML = "";
}

function toggleElement(id, display_status) {
 var obj = document.getElementById(id);
 if(!display_status) {
	 if (obj.style.display=="block") {
	   obj.style.display="none";
	   return false;
	 } else {
	   obj.style.display="block";
	   return true;
	 }
  } else {
   obj.style.display=display_status;
  }
}
function toggleCheckBox(box,id){
 if(box.checked) {
   var the_status="block";
 } else {
   var the_status="none";
 }
 toggleElement(id,the_status);
}

function toggleRadioButton(buttonId) {
	var button = document.getElementById(buttonId);
	button.checked = true;
}

function disableRadioButton(buttonId, disable) {
	var button = document.getElementById(buttonId);
	button.disabled = disable;
}

function toggleSearchCategory(id) {
 var the_status=toggleElement(id);
 var the_title=document.getElementById(id+"Title");
 if(the_status) {
  the_title.className="searchModule opened";
 } else {
  the_title.className="searchModule";
 }
 
}
function toggleWOLTitleBar(count) { /* WOL=who's online */
	toggleElement('cityList-'+count);
	var obj = document.getElementById('toggleArrow-' + count);
	var className = obj.className;
	if (className.indexOf('opened') > -1) {
		obj.className = 'searchModule';
	} else {
		obj.className = 'searchModule opened';
	}
}

function displayRightNote(){

var currVisible= document.getElementById("profileVisibleEveryone").checked;
var adultVisible= document.getElementById("adultProfileVisibleShow").checked;

toggleElement('adultPhotosVisibleMsg','none');
toggleElement('adultPhotosMsg','none');

if(currVisible) {
	if(adultVisible) {
	 toggleElement('adultPhotosVisibleMsg','inline');
	}
	else
	{
	toggleElement('adultPhotosMsg','inline');
	}
}
}

function selectOption(formName, selectName, value) {
	var options = document.forms[formName].elements[selectName].options;
	if((selectName=="heightMin") && heightOptions.length==0) { 
	 var addHeightOption=1;
	} else {
	 var addHeightOption=0;
	}
	for (var i=0; i<options.length; i++) {
		if (options[i].value == value) {
			options[i].selected = true;
		}
		if(addHeightOption) {
		  heightOptions[i]= {'value':options[i].value, 'text':options[i].text};
		}
	}
}

var heightOptions=new Array();
function changeHeightOptions(formName, selName) {
  activeSearchForm=document.forms[formName]
  var sel = activeSearchForm.elements[selName];
  var selIndex = sel.selectedIndex;
  var selValue = sel.options[selIndex].value;
  if(heightOptions.length==0) {
   selectOption(formName, 'heightMin', selIndex);
  }
  if(selName=="heightMax") {
      var changeName="heightMin";
      var min=0;
      var max=selValue;
  } else {
      var changeName="heightMax";
      var min=selValue;
      var i=heightOptions.length-1
      var max=heightOptions[i].value+1;
  }
  if(!selIndex) {
   min=0;
   max=245;
  }
  var changeSel=document.forms[formName].elements[changeName];
  var changeValue=changeSel.options[changeSel.selectedIndex].value;
  
  if(selIndex) {
	   removeAllOptionSearch(changeName);
	   changeSel.options[0].value=0;
	   for(var i=0; i<heightOptions.length; i++) {
	    var opt=heightOptions[i];
	    if(opt.value != 0 && opt.value >= min && opt.value <= max) {
		    insertOptionSearch(opt.text, opt.value, changeName);
		    if(opt.value==changeValue) {
		     var len = changeSel.options.length;
		     changeSel.options[len-1].selected=true;
		    }
		 }
	   }
   }
}

//Refreshes City values if you searchForm has state/region already selected
function searchCityRefreshListner() {
	var options = document.forms['searchForm'].stateSelected.options;
	for (var i=0; i<options.length; i++) {
	    if (options[i].selected)
	        var selectedState = options[i];
	}
	if (selectedState.value != "")
		doRefreshSearch(selectedState.value,'CITY', 'searchForm');
}

/* --------------- END SEARCH LOCATION AJAX --------------------------- */





/* --------------- START LOCATION AJAX --------------------------- */


function doRefresh(locationId, typeRefresh, cityName, postal) {
	dojo.io.bind( {
	        url: "/locationList.do",
	        content: {locationId: locationId, refresh: typeRefresh, postal: postal},
	        method: "POST",
	        mimetype: "text/html",
	        load: function(type, value, evt) {
	            processResponse(value, locationId, typeRefresh, postal);
	        },            
	        error: function(type, error) { alert("Error: " + error.reason); }
	   });
}



function processResponse(response, locationId, typeRefresh, postal) {

	if (djConfig['isDebug']) {
		dojo.debug("ajax response: " + response);
	}
	
	if (typeRefresh == 'POSTALCHECK') {
		refreshLocation(response, typeRefresh, postal);
	} else {
		refreshDropDownList(response, typeRefresh, postal);
	}
}

function refreshDropDownList(response, typeRefresh, postal){

	var xmlDoc = dojo.dom.createDocumentFromText(response);
	var listLocation = xmlDoc.getElementsByTagName('LIST');  
	var listType = listLocation[0].attributes[0].nodeValue;
	var ClearState  = listLocation[0].attributes[1].nodeValue;
	var listElements = xmlDoc.getElementsByTagName('NAME');
	var listElementsId = xmlDoc.getElementsByTagName('ID');   
	if ( 'YES' == ClearState){
		removeAllOption("stateSelected");
	}
	removeAllOption(listType);
	for (var i = 0; i < listElements.length; i++) {
		insertOption(listElements[i].firstChild.nodeValue, listElementsId[i].firstChild.nodeValue, listType);
	}
	
}

function refreshLocation(response, typeRefresh, postal) {
	var xmlDoc = dojo.dom.createDocumentFromText(response);
	var stateLoc = xmlDoc.getElementsByTagName('STATE'); 
	var cityLoc = xmlDoc.getElementsByTagName('CITY');
	var locContainer = document.getElementById('location');
	var stateTxt = document.createTextNode(stateLoc[0].firstChild.nodeValue);
	var dataCheck = stateLoc[0].firstChild.nodeValue;
	var sepTxt = document.createTextNode(', ');
	var cityTxt = document.createTextNode(cityLoc[0].firstChild.nodeValue);
	var errorTxt = "<span class='errorColor'>We can't find that postal code</span>";
	
	removeChildren(locContainer);
	
	if (dataCheck != "null") {	
		locContainer.appendChild(cityTxt);
		locContainer.appendChild(sepTxt);
		locContainer.appendChild(stateTxt); 
	} else {
		locContainer.innerHTML = errorTxt;
	}
}

function insertOption(name, value, listType){
    var elSel = document.getElementsByName(listType)[0];
    
	if (elSel != null && elSel.options != null) {
        elSel.options[elSel.options.length] = 
            new Option(name, value, false, false);
    }
}

function removeAllOption(listType) {
	var elSel = document.getElementsByName(listType)[0];
	if (elSel.length > 0) {	
		var elOptNew = document.createElement('option');
		for (var i=elSel.options.length-1;i>=0;i--) {
			elSel.remove(i);
		}
		elOptNew.text = "--Select--";
		elOptNew.value = "";
		elSel.options[0]=elOptNew;
	}
}


//State or Postal links
function showFields(fields) {
	var postalField = document.getElementById('postalField');
	var stateField = document.getElementById('stateField');
	var cityField = document.getElementById('cityField');
	var locContainer = document.getElementById('location');
	
	if (fields == 'postal') {
		removeChildren(locContainer);
		form.state.value = "";
		form.city.value = "";
		removeAllOption("stateSelected");
		removeAllOption("citySelected");
		postalField.style.display = 'block';
		stateField.style.display = 'none';
		cityField.style.display = 'none';
	}
		
	if (fields == 'state') {
		removeChildren(locContainer);
		form.postalCode.value = "";
		form.postalCodeSelected.value = "";
		postalField.style.display = 'none';
		stateField.style.display = 'block';
		cityField.style.display = 'none';
	}

	if (fields == 'country') {
		removeChildren(locContainer);
		form.postalCodeSelected.value = "";
	}	
}



/* --------------- END LOCATION AJAX --------------------------- */




/* --------------- START JOIN MEMBER-NAME --------------------------- */

function isAvailable(memberName) {
	dojo.io.bind({
		url: "/members/join/nameCheck.do?memberName=" + escape(memberName),
		load: function(type, data, evt) {
			if(memberName == '')
				return;
			
			var tempDiv = dojo.byId("memberNameAvailabilityDiv");
			tempDiv.innerHTML = data;
			tempDiv.style.display = "block";
			return;
		},
		method: "GET"
	});
}

/* --------------- END JOIN MEMBER-NAME --------------------------- */





/* --------------- START JOIN MISC --------------------------- */




/* ---------- check for valid/real date ---------- */

function checkDate(number) { 
	return (number < 1000) ? number + 1900 : number; 
}
function isDate (day,month,year) {
	var today = new Date();
	year = ((!year) ? checkDate(today.getYear()):year);
	month = ((!month) ? today.getMonth():month-1);
if (!day) return false
	var test = new Date(year,month,day);
if ( (checkDate(test.getYear()) == year) &&
	(month == test.getMonth()) &&
	(day == test.getDate()) )
	return true;
else
	return false;
}
function checkDateValidity(date) {
	if (isDate(document.accountJoinValidatorForm.birthDay.options[document.accountJoinValidatorForm.birthDay.selectedIndex].value,document.accountJoinValidatorForm.birthMonth.options[document.accountJoinValidatorForm.birthMonth.selectedIndex].value,document.accountJoinValidatorForm.birthYear.options[document.accountJoinValidatorForm.birthYear.selectedIndex].value)) {
		return true;
	} else {
		return false;
	}
}


function checkDateValidate() {
	if (isDate(document.profileEditBasicValidatorForm.birthDay.options[document.profileEditBasicValidatorForm.birthDay.selectedIndex].value,document.profileEditBasicValidatorForm.birthMonth.options[document.profileEditBasicValidatorForm.birthMonth.selectedIndex].value,document.profileEditBasicValidatorForm.birthYear.options[document.profileEditBasicValidatorForm.birthYear.selectedIndex].value)) {
		return true;
	} else {
		return false;
	}
}






/* ---------- Join Change Email Form ---------- */

function showEmailFormContainer() {
	var container = $('emailFormContainer');
	var space = $('emailFormSpace');

	if (container.style.display == 'none' && space.style.display == 'block') {
		container.style.display = 'block';
		space.style.display = 'none';
	} else {
		container.style.display = 'none';
		space.style.display = 'block';
	}
}

/* --------------- END JOIN MISC --------------------------- */




/* --------------- START JOIN LOCATION-AJAX --------------------------- */


function setHiddenValues(formName) {
    
    var indexCountry = document.getElementsByName('countrySelected')[0].selectedIndex;
	var indexState = document.getElementsByName('stateSelected')[0].selectedIndex;
	var indexCity = document.getElementsByName('citySelected')[0].selectedIndex;
	
	var cityName = document.getElementsByName('citySelected')[0][indexCity].text ;
	var stateName = document.getElementsByName('stateSelected')[0][indexState].text ;
	var countryName = document.getElementsByName('countrySelected')[0][indexCountry].text;
    var postalCodeName = form.postalCodeSelected.value;
	
	var cityId =  document.getElementsByName('citySelected')[0][indexCity].value;
	var stateId = document.getElementsByName('stateSelected')[0][indexState].value; 
	var countryId = document.getElementsByName('countrySelected')[0][indexCountry].value;
	
	form.country.value = countryId;
	form.state.value = stateId;
	form.city.value = cityId;
	form.postalCode.value = postalCodeName;
	if (postalCodeName != "") {
		form.city.value = "";
	}
}

//Set join fields status
function setLocationFields(formName, arg) {
	var form = document.forms[formName];
	var statePostalLabels = document.getElementById('statePostalLabels');
	var stateRegionLabel = document.getElementById('stateRegionLabel');
	var stateField = document.getElementById('stateField');
	var cityField = document.getElementById('cityField');
	var postalField = document.getElementById('postalField');
	var indexCountry = document.getElementsByName('countrySelected')[0].selectedIndex;
	var countryId = document.getElementsByName('countrySelected')[0][indexCountry].value;
	
	//US Default
	if (countryId == "233") {
		statePostalLabels.style.display = 'block';
		stateField.style.display = 'none';
		cityField.style.display = 'none';
		postalField.style.display = 'block';
		stateRegionLabel.style.display = 'none';
		if (arg == 'city') {
			stateField.style.display = 'block';
			stateRegionLabel.style.display = 'none';
			cityField.style.display = 'block';
			postalField.style.display = 'none';
		}
	}
	if (countryId == "46" || countryId == "231") {
		statePostalLabels.style.display = 'none';
		stateRegionLabel.style.display = 'block';
		stateField.style.display = 'block';
		cityField.style.display = 'none';
		postalField.style.display = 'none';
		if (arg == 'city') {
			cityField.style.display = 'block';
		}
	}
	
	if (countryId != "46" && countryId != "231" && countryId != "233") {
		statePostalLabels.style.display = 'none';
		stateRegionLabel.style.display = 'none';
		stateField.style.display = 'none';
		cityField.style.display = 'block';
		postalField.style.display = 'none';
	}
	
	if (arg == 'postalHidden') {
		form.postalCodeSelected.value = form.postalCode.value;	
	}
	
	if (arg == 'stateHidden') {
		showFields('state');
	}
	
	try {toggleUnlink('refresh');}
	catch (e) {}
}

// Initialize field status
function fieldInit(formName) {
	// Empty fields; reset to default
	if ((getStateHidden() == "") || (getCityHidden() == "") && (getPostalCodeHidden() == "")) {
		window.document.onload = doRefresh(getCountryId(),'STATE');
		window.document.onload = setLocationFields(formName);
	}

	// Have postal in US
	if (getPostalCodeHidden() != "" && getCountryId() == '233') {
	    window.document.onload = showFields('postal');
		window.document.onload = setLocationFields(formName,'postalHidden');
	}
	
	
	// Have state and city and in US
	if (getStateHidden() != "" && getCityHidden() != "" && getCountryId() == '233') {
		window.document.onload = showFields('state');
		window.document.onload = setLocationFields(formName,'stateHidden');
		window.document.onload = doRefresh(getCountryId(),'STATE');
		
		setTimeout(
		function doState() {
			for (var i=0;i<form.stateSelected.options.length;i++) {
    			if (form.stateSelected.options[i].value == form.state.value) {
					form.stateSelected.options[i].selected = true;
				}
			}
		}, 1000);
		
		doRefresh(getStateId(),'CITY');
		
		document.getElementById('cityField').style.display = 'block';
		
		setTimeout(
		function doCity() {
			for (var i=0;i<form.citySelected.options.length;i++) {
   				if (form.citySelected.options[i].value == form.city.value) {
					form.citySelected.options[i].selected = true;
				}
			}
		}, 2000);
	}
	
	
	// Have state and city in CA or UK
	if ((getStateHidden() != "" || getCityHidden() != "") && (getCountryId() == '231' || getCountryId() == '46')) {
		window.document.onload = setLocationFields(formName);
					
		window.document.onload = doRefresh(getCountryId(),'STATE');
		
		setTimeout(
		function doState() {
			for (var i=0;i<form.stateSelected.options.length;i++) {
    			if (form.stateSelected.options[i].value == form.state.value) {
					form.stateSelected.options[i].selected = true;
				}
			}
		}, 1000);
		
		
		document.getElementById('cityField').style.display = 'block';
		
		setTimeout(
		  function doCityAjax() {
		  	doRefresh(getStateId(),'CITY');
		  }, 2000);
		
		setTimeout(
		function doCity() {
		    
		    
			for (var i=0;i<form.citySelected.options.length;i++) {
   				if (form.citySelected.options[i].value == form.city.value) {
					form.citySelected.options[i].selected = true;
				}
			}
		}, 3000);
		
	}
	
	// Have Intl country and city
	if ((getCountryId() != '233') && (getCountryId() != '231') && (getCountryId() != '46')) {
		window.document.onload = setLocationFields(formName);
		
		doRefresh(getCountryId(),'CITY');
		
		setTimeout (
		function doIntlCity() {
			for (var i=0;i<form.citySelected.options.length;i++) {
    			if (form.citySelected.options[i].value == form.city.value) {
					form.citySelected.options[i].selected = true;
				}
			}
		},1000);	
	}
}

function toggleUnlink(arg) {
	var zipLink = $('zipLink');
	var stateLink = $('stateLink');
	var postalField = $('postalField');

	if (arg == 'zip') {
		zipLink.className = 'unlink';
		stateLink.className = 'link';
	} 
	if (arg == 'state') {
		zipLink.className = 'link';
		stateLink.className = 'unlink';
	}
	
	if (arg == 'refresh' && postalField.style.display == 'inline') {
		zipLink.className = 'unlink';
		stateLink.className = 'link';
	}
}

/* --------------- END JOIN LOCATION-AJAX --------------------------- */





/* --------------- START VIEW PROFILE --------------------------- */

var add_note_form = null;
var add_note_container = null;
var add_note_msg=null;

function showMemberNote(id) {
	if(!add_note_form) {
		add_note_form = document.addNoteForm;
		add_note_container = $("addNoteContainer");
		add_note_msg = $("addNoteMsg");
	}
  
	var content_obj = $("note_" + id);

	var note = content_obj.innerHTML.trim().substring(0, 127);
	add_note_form.contentArea.value = html_entity_decode(note);
	add_note_container.style.display = "block";
	add_note_form.member_id.value = id;
}

function showListNote(id) {
	if(!add_note_form) {
		add_note_form = document.addNoteForm;
		add_note_container = $("addNoteContainer");
		add_note_msg = $("addNoteMsg");
	}
	
	var content_obj = $("note_" + id);
	var link_obj = $("note_link_" + id);
	var link_container = $("noteLinkDiv_" + id);

	var coors = findPos(link_obj);	 
	add_note_container.style.top = coors[1]-106  + "px";
	add_note_container.style.left = coors[0]-10 + "px";
	
	var note = content_obj.innerHTML.trim().substring(0, 127);
	
	add_note_form.contentArea.value = html_entity_decode(note);
	add_note_container.style.display = "block";
	add_note_form.member_id.value = id;
}

function noteDisplaySwitch(id, bool) {
	if (bool) {
		$('noteTitleDiv_' + id).style.display = 'inline';
		$('noteLinkDiv_' + id).style.display = 'inline';
		if ($("noteType").innerHTML == 'list') {
			$('note_' + id).style.display = 'none';
		} else {
			$('note_' + id).style.display = 'inline';
		}
		$('noteEditTitleDiv_' + id).style.display = 'none';
	} else {
		$('note_' + id).style.display = 'none';
		$('noteTitleDiv_' + id).style.display = 'none';
		$('noteLinkDiv_' + id).style.display = 'none';
		$('noteEditTitleDiv_' + id).style.display = 'inline';
	}	
}
 
function saveMemberNote(){
    var note = add_note_form.contentArea.value;
  	add_note_msg.innerHTML = "Saving...";
  	add_note_msg.style.display ="block";
  	var url = "/profile/notes.do";
  	if ($("noteType").innerHTML == 'profile') {
	    dojo.io.bind({
		   url: url,
		   content: {random:Math.random(), member_id:add_note_form.member_id.value, notes:note },
		   method: "GET",
		   load: saveProfileNoteSuccess,
		   error: saveNoteFailed
		});
  	} else {
	    dojo.io.bind({
		   url: url,
		   content: {random:Math.random(), member_id:add_note_form.member_id.value, notes:note },
		   method: "GET",
		   load: saveNoteSuccess,
		   error: saveNoteFailed
		});
  	}
 }

function closeNoteForm(id) {
	add_note_msg.innerHTML="";
	add_note_msg.style.display="none";
	add_note_form.contentArea.value="";
	add_note_form.member_id.value="";
	add_note_container.style.display="none";
}

function cancelNoteEdit(id) {
	closeNoteForm(id);
	noteDisplaySwitch(id, true);
}
 
function saveProfileNoteSuccess(){
	var id=add_note_form.member_id.value;
	var note=add_note_form.contentArea.value;
	if (note && note.length > 127) {
		note = note.substring(0,127);
	}
	$("note_" + id).innerHTML=html_entity_encode(note);
	$("note_" + id).style.display="block";
	$("addNoteContainer").style.display="none";
	$("notesTitleDiv").style.display="block";
	add_note_msg.innerHTML = '';
}
function saveNoteSuccess(){
	var id=add_note_form.member_id.value;
	var note=add_note_form.contentArea.value;
	if (note && note.length > 127) {
		note = note.substring(0,127);
	}
	$("note_" + id).innerHTML=html_entity_encode(note);
	
	if ($("noteType").innerHTML == 'list') {
		var noteLinkText = "";
		if (note == "") { noteLinkText="Add Note"; }
		else { noteLinkText="Read Note"; }
		$("note_link_" + id).innerHTML=noteLinkText;
	}
	var the_link=$("add_note_link");
	if(the_link) the_link.innerHTML="Edit note";
	closeNoteForm();
	noteDisplaySwitch(id, true);
}

function saveNoteFailed(){
	var id = add_note_form.member_id.value;
	if ($("note_" + id).innerHTML != '') {
		add_note_msg.innerHTML	= "Sorry, the update failed.";
		add_note_msg.style.display = "block";
	}
}

function limitContentLength(obj,max_length) {
	var the_value=obj.value;
	if (the_value.length > max_length) {
		obj.value=the_value.substring(0,max_length);
	}
}

function selectAllCheckboxes(form_name, the_status) {
	if (typeof(the_status)=="undefined") {
		var the_status = true;
	}
	var the_form = document.forms[form_name];

	for(var i=0; i < the_form.elements.length; i++) {
		if (the_form.elements[i].type=="checkbox") {
			the_form.elements[i].checked = the_status;
		}
	}
}

function deletedSelectedCheckboxes(form_name) {
	removeFromMyList(form_name);
}

function displayListNoteForm() {	
	document.write('<div id="addNoteContainer" class="popBlock">' + 
		'        <div id="addNoteMsg"></div>' + 
		'            <form name="addNoteForm">' + 
		'                <input name="member_id" type="hidden"/>' +   
		'                <textarea name="contentArea" id="contentArea" onkeypress="limitContentLength(this,126);"></textarea>' + 
		'                <div class="PopupButton">' + 
		'                    <a href="#" onclick="saveMemberNote();return false;"/>SAVE</a>&nbsp;' + 
		'                    <a href="#" onclick="closeNoteForm();return false;"/>CANCEL</a>' + 
		'                </div>' + 
		'            </form>' + 
		'</div>');	
}

var removeActions = new Array();
removeActions["buddyList"]=["/personals/buddy.do","endSelectedBuddyRelationships"];
removeActions["hotList"]=["/personals/hottie.do","removeSelectedHotties"];
removeActions["bookmarkList"]=["/personals/bookmark.do","deleteSelectedBookmarks"];
removeActions["blockedList"]=["/personals/block.do", "removeSelectedBlocks"];

var pageNameReg = /\/([a-zA-Z]+)\.do/;
var thisPageName = "";
var thisHref=location.href;
function getMyPageName() {
	if(pageNameReg.test(thisHref)) {
	  return RegExp.$1;
	}
	return "";
	
}
function removeFromMyList(form_name) {
	var the_form = document.forms[form_name];
	var selected = 0;
	for(var i=0; i < the_form.elements.length; i++) {
     if (the_form.elements[i].type=="checkbox" && the_form.elements[i].checked) {
      selected++;
      break;
     }
    }
    if (!selected) {
       alert("Please select at least one.");
    } else {
		if (!thisPageName) thisPageName = getMyPageName();
	
		var action_url = removeActions[thisPageName][0];
		var the_action = removeActions[thisPageName][1];
		the_form.action = action_url;
		the_form.formAction.value = the_action;
	
		the_form.submit();
	}
}

var interactMenuState = 0; // 0=hidden,1=showing,2=shown,3=hiding

function showInteractMenu(interactMenuId, evt) {
	if (interactMenuState == 2) {
		return;
	}
	interactMenuState = 1;
	document.getElementById(interactMenuId).style.display = 'block';
	interactMenuState = 2;
}
function hideInteractMenu(interactMenuId, evt) {
	if (interactMenuState != 2) {
		return;
	}
	interactMenuState = 3;
	setTimeout(function(evt) { closeInteractMenu(interactMenuId); }, 400);
}
function closeInteractMenu(interactMenuId) {
	if (interactMenuState == 3) {
		// Close it
		document.getElementById(interactMenuId).style.display = 'none';
		interactMenuState = 0;
	}
}

/* --------------- END VIEW PROFILE --------------------------- */




/* --------------- START PRIVATE PHOTO LITE-BOX POPUP --------------------------- */

function openSharePhotoWindow(memberName, page, evt){
	closeSharePhotoWindow();
	var viewport = getViewportDimensions();
	var pane = dojo.widget.createWidget('ContentPane', {widgetId:'liteBoxContainerDiv', cacheContent:false});
	pane.domNode.className = 'liteBoxContainer';
	document.body.appendChild(pane.domNode);
	pane.setUrl("/photos/private/view.do?namelc=" + memberName);
	pane.domNode.style.display = 'block';
	
	var leftInt = Math.round((viewport.width - 819) / 2);
	var topInt = Math.round((viewport.height - 515) / 2);
	
	leftInt += hScroll();
	topInt += vScroll();
	
	pane.domNode.style.left = leftInt < 0?0 + 'px':leftInt + 'px';
	pane.domNode.style.top = topInt < 0?0 + 'px':topInt + 'px';
	
	$("container").className = 'liteBoxBG';			
}
 
function closeSharePhotoWindow() {
	if(dojo.widget.getWidgetById('liteBoxContainerDiv')) {
		var pane = dojo.widget.getWidgetById('liteBoxContainerDiv');
		pane.domNode.style.display = 'none';
		pane.destroy();
		$("container").className = '';
	}
}

/* --------------- END PRIVATE PHOTO LITE-BOX POPUP --------------------------- */



/* --------------- START PROFILE PHOTO SLIDER AND LITE-BOX POPUP --------------- */

//values to be set
var upCount = -1;
var upNumPages = -1;
var upCurPage = 0; //assume starting at first page
var upNotSliding = true; 

//magic numbers
var upNumPrePage = 4;
var upWidth = 106;
var nudgeAmount = upWidth/4;
var nudgeWait = 30; //millisecond
// photo slider is very slow on FF3/OSX10.4, so we'll
// try to be kind to those users
if (isFirefox3Mac104) {
	nudgeAmount = 106;
	nudgeWait = 20;
}

function slideInit() {
	upCount = Number($("userPhotosCount").value);
	if (isNaN(upCount)) upCount = 0;
	upNumPages = Math.ceil(upCount / upNumPrePage);
}
function showHidePhotoSliderButtons () {
	if (upCurPage <= 0) {
		$("userPhotoSlidePrevBtn").style.display = "none";
	} else {
		$("userPhotoSlidePrevBtn").style.display = "inline-block";
	}
	if(upCurPage >= upNumPages - 1) {
		$("userPhotoSlideNextBtn").style.display = "none";
	} else {
		$("userPhotoSlideNextBtn").style.display = "inline-block";
	}
}

function slideUserPhotoBack() {
	if (upNotSliding) {
		if (upCount < 0 || upNumPages < 0) { slideInit(); }
		if (upCurPage >= 0) {
			upNotSliding = false;
			upCurPage--;
			showHidePhotoSliderButtons();
			nudgeUPSliderBack();
		}
	}
}
function nudgeUPSliderBack() {
	var leftMargin = trimPx($("userPhotosContainerId").style.marginLeft);
	$("userPhotosContainerId").style.marginLeft = (leftMargin + nudgeAmount) + "px";
	leftMargin = trimPx($("userPhotosContainerId").style.marginLeft);
	if(-upWidth*upNumPrePage*upCurPage <= leftMargin) {
		$("userPhotosContainerId").style.marginLeft = (-upWidth*upNumPrePage*upCurPage) + "px";
		upNotSliding = true;
	} else {
		setTimeout("nudgeUPSliderBack()", nudgeWait);
	}
}
function slideUserPhotoForward() {
	if (upNotSliding) {
		if (upCount < 0 || upNumPages < 0) { slideInit(); }
		if (upCurPage < upNumPages - 1) {
			upNotSliding = false;
			upCurPage++;
			showHidePhotoSliderButtons();
			nudgeUPSliderForward();
		}
	}
}
function nudgeUPSliderForward() {
	var leftMargin = trimPx($("userPhotosContainerId").style.marginLeft);
	$("userPhotosContainerId").style.marginLeft = (leftMargin - nudgeAmount) + "px";
	leftMargin = trimPx($("userPhotosContainerId").style.marginLeft);
	if(-upWidth*upNumPrePage*upCurPage >= leftMargin) {
		$("userPhotosContainerId").style.marginLeft = (-upWidth*upNumPrePage*upCurPage) + "px";
		upNotSliding = true;
	} else {
		setTimeout("nudgeUPSliderForward()", nudgeWait);
	}
}

 // photo details litebox
function getCurPhotoPos() {
	var pos = Number($("currentPhotoPosition").value);
	if (isNaN(pos)) { pos = 1; }
	return pos;
}
function setCurPhotoPos(pos) {
	if (!isNaN(Number(pos)) && $("currentPhotoPosition"))
		$("currentPhotoPosition").value = pos;
}

function showHidePhotoDetailButtons () {
	if (upCount < 0 || upNumPages < 0) { slideInit(); }
	var curPos = getCurPhotoPos();
	if (curPos <= 0) { $("photoDetailsSlidePrevBtn").style.display = "none"; }
	else { $("photoDetailsSlidePrevBtn").style.display = "inline-block"; }
	if(curPos >= upCount - 1) { $("photoDetailsSlideNextBtn").style.display = "none"; }
	else { $("photoDetailsSlideNextBtn").style.display = "inline-block"; }
}

function updatePhotoDetailLitebox() {
	try {
		var curPos = getCurPhotoPos();
		showHidePhotoDetailButtons();
		
		var fullImgUrl = $("photoPathFull_"+curPos).value;
		$("photoDetailsImage").src = fullImgUrl;
		$("photoDetailsCaption").innerHTML = $("captionByPos_"+curPos).innerHTML;
		$("photoDetailsCurPic").innerHTML = curPos+1; // curPos starts counting at 0
		$("photoDetailsTotalPics").innerHTML = upCount;
		
		var lppic = $("largePhotoPremiumInterceptContainer");
		if (lppic) {
			if ($("photoClass_"+curPos).value != 'DEFAULT') {
				lppic.style.display = "block";
				$("interceptThumbnailImg").src = $("photoPathThumbnail_"+curPos).value;
				
				var maskType = $("photoMaskType_"+curPos).value;
				if ((maskType == "PRIVATE_PHOTO_MASK") || (maskType == "PRIVATE_PHOTO_UPSELL_MASK")) {
					if ($("photoInterceptUpgradeLink")) {
						$("photoInterceptUpgradeLink").href = "/members/subscribe/select.do?msgkey=subscribe.photodetail.private";
					}
				} else if (maskType == "ADULT_PHOTO_MASK") {
					$("photoInterceptUpgradeLink").href = "/members/subscribe/select.do?msgkey=subscribe.photodetail.adult";
				} else {
					$("photoInterceptUpgradeLink").href = "/members/subscribe/select.do?msgkey=subscribe.photodetail.full.size";
				}
			} else {
				lppic.style.display = "none";
			}
		}
	} catch (ex) { }
}
function slidePhotoDetailsBack() {
	var curPos = getCurPhotoPos();
	if (curPos > 0) {
		setCurPhotoPos(curPos - 1);
		updatePhotoDetailLitebox();
	}
}
function slidePhotoDetailsForward() {
	var curPos = getCurPhotoPos();
	if (curPos <= upCount - 2) {
		setCurPhotoPos(curPos + 1);
		updatePhotoDetailLitebox();
	}}
function initializePhotoDetailsLitebox() {
	var tempSpan = document.createElement("span");
	tempSpan.style.display = "none";
	var tempContent =  $('photoDetailsLiteboxTempContainer');
	if (tempContent != null && tempContent.innerHTML != "") {
		tempSpan.innerHTML = tempContent.innerHTML;
		tempContent.innerHTML = "";
	}
	tempSpan.id = "photoDetailsLiteboxContainer";
	tempSpan.className = "liteBoxContainer";
	document.body.appendChild(tempSpan);
	initalizedPhotoDetailsLitebox = true;
}
function openDetailPhotoWindow(position){
	setCurPhotoPos(position);
	var viewport = getViewportDimensions();
	if (!$('photoDetailsLiteboxContainer')) {
		initializePhotoDetailsLitebox();
	}
	var pdlb = $('photoDetailsLiteboxContainer');
	updatePhotoDetailLitebox();
	var leftInt;
	if (isIE7) {
		leftInt = Math.round((viewport.width - 800) / 2) + hScroll();
	} else {
		leftInt = Math.round((viewport.width - 622) / 2) + hScroll();
	}
	var topInt = Math.round((viewport.height - 650) / 2) + vScroll();
	pdlb.style.left = leftInt < 0?0 + 'px':leftInt + 'px';
	// Make sure lightbox doesn't get covered up by dashboard strip
	pdlb.style.top = topInt < 31?31 + 'px':topInt + 'px';
	
	pdlb.style.display = 'block';
	$("container").className = 'liteBoxBG';
}
function closeDetailPhotoWindow() {
	var pdlb = $('photoDetailsLiteboxContainer');
	if(pdlb){
		pdlb.style.display = "none";
		$("container").className = "";
	}
}

/* --------------- END PROFILE PHOTO SLIDER AND LITE-BOX POPUP --------------- */


/* --------------- START SUBSCRIBE --------------------------- */


// Used on Payment Dropdowns
function setStates(form){
	if(!form) { 
		var form = document.forms["submitPaymentForm"];
	}
	var submitPaymentForm = form;
	var countryCode = submitPaymentForm['creditCard.country'].value;
	var postalCodeElem = submitPaymentForm['creditCard.postalCodeUS'];
	var postalCodeValue = submitPaymentForm['creditCard.postalCodeUS'].value;
	var postalIntlElem = submitPaymentForm['creditCard.postalCodeIntl'];
	var postalIntlValue = submitPaymentForm['creditCard.postalCodeIntl'].value;
	var stateDiv = document.getElementById('stateDiv');
	//var state = submitPaymentForm['state'];
	var state = submitPaymentForm['creditCard.stateUS'];
	var provinceDiv = document.getElementById('provinceDiv');
	var province = submitPaymentForm['creditCard.province'];
	var stateTextDiv = document.getElementById('stateTextDiv');
	var postalCodeDiv = document.getElementById('postalCodeDiv');
	var postalCodeIntlDiv = document.getElementById('postalCodeIntlDiv');
	
	if (countryCode != "" || countryCode != null) {
		if (countryCode == 'us') {
			stateDiv.style.display = 'block';
			province.hidden = true;
			provinceDiv.style.display = 'none';
			stateTextDiv.style.display = 'none';
			postalCodeDiv.style.display = 'block';
			postalCodeIntlDiv.style.display = 'none';
			if (postalIntlValue) {
				postalIntlElem.value = '';
			}
		} else if (countryCode == 'ca') {
			stateDiv.style.display = 'none';
			state.hidden = true;
			provinceDiv.style.display = 'block';
			stateTextDiv.style.display = 'none';
			postalCodeDiv.style.display = 'none';
			postalCodeIntlDiv.style.display = 'block';
			if (postalCodeValue) {
				postalCodeElem.value = '';
			}
    	} else {
			stateDiv.style.display = 'none';
			state.hidden = true;
			province.hidden = true;
			provinceDiv.style.display = 'none';
			stateTextDiv.style.display = 'block';
			postalCodeDiv.style.display = 'none';
			postalCodeIntlDiv.style.display = 'block';
			if (postalCodeValue) {
				postalCodeElem.value = '';
			}
		}	
	}
}

// look for the selected value of the radio button that is passed in
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}



/* --------------- END SUBSCRIBE --------------------------- */





/* --------------- START MESSAGE --------------------------- */




function updatePageCount(form, page){
    document.forms[form].currentPage.value = page;
}

//can go away soon
function decrementPageCount(page){
    document.forms['folderValidatorForm'].currentPage.value = parseInt(page)-1;
}
//can go away soon
function incrementPageCount(page){
    document.forms['folderValidatorForm'].currentPage.value = parseInt(page)+1;
}

//Must be called when an action is performed so servlet knows
//which action to perform
function setActionFlag(formName, actionFlag){
    document.forms[formName].actionFlag.value = actionFlag;
}

//Sets where the message is being moved to
function setToFolderId(formName, target) {
	document.forms[formName].toFolderId.value = target;
}

function setAllCheckBoxes(formName, checkValue, theCheckBox) {
    if (checkValue == "" && theCheckBox) {
	    var checkValue = (theCheckBox.checked? "true" : "false");
	}
	var form = document.forms[formName];
	var el = form.elements;
	for(var i = 0; i < el.length; i++) {
	  	if(el[i].type == "checkbox" ) {
	    	if(checkValue == "true" && el[i].disabled == false) {
	      		el[i].checked = true;
	    	} else if  (checkValue == "false") {
	      		el[i].checked = false;
	    	} else {
	    		el[i].checked = false;
	    	}
	    }	
	 }
}
				
function setCheckBoxToMessage(id) {
	var form = document.forms['folderValidatorForm'];
	var el = form.elements;
	for (var i=0; i < form.length; i++) {
		if (el[i].type == "checkbox" && el[i].value == id) { 
			el[i].checked = true;
			el[i].disabled = false;
		}
	}
}

function setReadMessageVals(formName, messageId, folderMessageId) {
    document.forms[formName].messageId.value = messageId;
    setFolderMessageId(formName, folderMessageId);
    
}

function setFolderMessageId(formName, folderMessageId) {
    document.forms[formName].folderMessageId.value = folderMessageId;
}

function setCurrentFolder(formName, currentFolder) {
    document.forms[formName].currentFolder.value = currentFolder;
}

function confirmMessageAction(form, toFolderId, folderMessageId, messageId, type, action) {
	var messagePre = "Do you really want to ";
	var message = (folderMessageId != null)?messagePre + "delete this message?":messagePre + "delete the selected message(s)?";
	if (type == 'rescind') {
		message = "Are you sure you want to recall this message?";
	}
	if (type == 'delete') {
		message = messagePre + "empty the trash?";
	}
	var choice = confirm(message);
	if (choice == true) {
		setToFolderId(form, toFolderId);
		if (type == 'deleteMessage' && folderMessageId != null) {
			setAllCheckBoxes(form, 'false');
			setCheckBoxToMessage(folderMessageId);
		}
		if (type == 'rescind' && folderMessageId != null) {
			setAllCheckBoxes(form, 'false');
			setCheckBoxToMessage(folderMessageId);
			setReadMessageVals(form, messageId, folderMessageId);
			document.forms[form].action = action; 
		}
		if (type == 'delete') {
			setAllCheckBoxes(form, 'true');
			document.forms[form].action = action;
		}
		document.forms[form].submit();
		return true;
	} else {
		return false;
	}
}

function messageAction(form, toFolderId, folderMessageId, messageId, type, action) {

		setToFolderId(form, toFolderId);
		if (type == 'deleteMessage' && folderMessageId != null) {
			setAllCheckBoxes(form, 'false');
			setCheckBoxToMessage(folderMessageId);
		}
		if (type == 'rescind' && folderMessageId != null) {
			setAllCheckBoxes(form, 'false');
			setCheckBoxToMessage(folderMessageId);
			setReadMessageVals(form, messageId, folderMessageId);
			document.forms[form].action = action; 
		}
		if (type == 'delete') {
			setAllCheckBoxes(form, 'true');
			document.forms[form].action = action;
		}
		document.forms[form].submit();
		return true;
}

/* --------------- END MESSAGE --------------------------- */






/* --------------- START MINI-PANES --------------------------- */
/*
 * What's a Mini Pane?
 * Mini Pane is a widget that lets you load an entire page (e.g. jsp) into a div
 * The javascript below handles when we show and hide the mini pane div
 * 
 * Mini goes through a series of phases before and after it is "active"
 * 
 * Mini Stages:
 * miniDiv.state == 0	->	mini is invisible and everyone's happy about it	
 * 
 * miniDiv.state == 1	->	mini is "previsible" 
 * 							Someone rolled over something that invokes mini, 
 * 							and we're waiting a second or so to be sure they 
 * 							really want mini before showing it.  If they
 * 							roll off the link before mini becomes "visible"
 * 							(state 2) then mini will revert to state 0 and 
 * 							never become visible at all.
 * 
 * miniDiv.state == 2	->	mini is actively visible and everyone's happy.  
 * 							The user is actively looking at mini.
 * 							Their mouse is still on the link or image that 
 * 							invoked mini or it is over the mini area itself
 * 
 * miniDiv.state == 3	->	mini is "ghost visible" or about to disappear.
 * 							The user has rolled the mouse off mini and any 
 * 							mini-invoking links.  Mini then entered a state
 * 							of ghost visibility meaning it will disappear 
 * 							in a sec unless the user rolls back over  
 * 							mini itself or a mini-invoking link first
 *  
 * miniDiv.state == 6	->	mini is frozen visible.  It will stay that way  
 * 							until unfrozen even if the user mouses off.  
 * 							It will not enter ghost state if user mouses off
 * 							while frozen.  Instead, it will stay in frozen
 * 							visible state until js unfreezes it.
 *     
 */

function showMini(myName, memberName, evt, pos) {
	// THIS IS THE GENERIC MINI PROFILE INVOKER
	if(!evt) evt = window.event;	
	if(memberName && myName != memberName) 
		showMiniFrame("/profile/mini.do?memberName=" + memberName + (pos=='chat' ? "&inChat=true" : ""), 262, 200, 1500, 1000, evt);
}

function showMiniFrame(miniUrl, w, h, hoverDelay, ghostDelay, evt) {
			// alert(document.readyState);
			var time = new Date();
			if(operationWillAbort) {
				return;
			} 
			// THIS IS THE GENERIC MINIFRAME INVOKER
			// WE USE THIS WITH /profile/mini.do FOR MINI PROFILE
			var miniDiv = getMiniDiv();
			if(miniDiv.state > 1 && miniUrl != miniDiv.miniUrl) {
				// MINI WAS PREVIOUSLY SHOWN SOMEWHERE ON THE PAGE
				// WITH ANOTHER URL (DIFFERENT PROFILE) IN IT
				// BUT NOW WE WANT TO MAKE IT PREVISIBLE IN A NEW PLACE
				// KILL THE OLD MINI!
				killMini();
			}
			miniDiv.ghostDelay = ghostDelay;
			miniDiv.width = w;
			miniDiv.height = h;
			miniDiv.style.width = w;
			miniDiv.style.height = h;
			if(miniDiv.state == 0) {	// MINI WAS INVISIBLE
				updateMousePos(evt, miniDiv);
    			miniDiv.state = 1; 	// NOW IT IS PRE-VISIBLE
           		
           		setAnimationVisible(true);
				miniDiv.miniUrl = miniUrl;
    			setTimeout('setMiniFrameVisibility(true)', hoverDelay);
			} else if(miniDiv.state == 3) {	// MINI WAS GHOST VISIBLE
				// SOMETIMES WE INVOKE MINI WHILE ITS ALREADY SHOWING ON PURPOSE
				// FOR INSTANCE, SOMEONE MAKES MINI SHOW BY ROLLING OVER A LINK
				// THEN THEY ROLL OFF THE LINK AND INTO MINI
				// WHEN THEY ROLL OFF THE LINK, MINI GOES INTO "GHOST STATE"
				// BUT IF YOU ROLL INTO MINI BEFORE IT DISAPPEARS, THEN TAKE 
				// IT OUT OF GHOST STATE AND PUT IT INTO REGULAR VISIBLE STATE INSTEAD
    			cancelMiniCancel();
    		}
		}
	function showRelativeMiniFrame(miniUrl, w, h, hoverDelay, ghostDelay, evt, relToObj) {
			// alert(document.readyState);
			if(document.readyState && document.readyState!="complete" && isIE) return;
			// THIS FUNCTION ACTS JUST LIKE REGULAR SHOWMINIFRAME
			// EXCEPT IT SHOWS MINI RELATIVE TO AN ELEMENT ON THE PAGE (NAV ITEM)
			// INSTEAD OF RELATIVE TO THE MOUSE POSITION
			var miniDiv = getMiniDivForQuickSearch();
			document.onclick = function() {};

			miniDiv.ghostDelay = ghostDelay;
			miniDiv.width = w;
			miniDiv.height = h;
			miniDiv.style.width = w;
			miniDiv.style.height = h;
	
       		getMiniPaneForQuickSearch(miniUrl);
    		miniDiv.miniUrl = miniUrl;
    		
    		var coors = findPos(relToObj);
			miniDiv.style.top = coors[1] + 25 +  "px";
			miniDiv.style.left = coors[0] + "px";	
		}
		
		
		function getMiniDivForQuickSearch() {
			// RETURNS A DIV ELEMENT OBJECT REPRESENTING THE CONTENT PANE OF THE 
			// MINI DOJO WIDGET
			// PARAMS LIKE POSITION, URL, ETC. ARE STORED AS ATTRIBUTES ON THIS DIV
			// MINI IS GENERATED SYSTEMATICALLY IF NOT ALREADY CREATED THE FIRST
			// TIME IT IS REQUESTED
			var miniDiv = document.getElementById('miniDivQuickSerch');
			if(miniDiv) return miniDiv;
			miniDiv = document.createElement('div');
			miniDiv.id = 'miniDivQuickSerch';
			miniDiv.state = 0;	// INITIALLY IT IS INVISIBLE
			miniDiv.style.position = 'absolute';
			miniDiv.style.top = '-500px';
			miniDiv.style.left = '-500px';
			miniDiv.style.zIndex = '10';
			miniDiv.mousex = 0;
			miniDiv.mousey = 0;
       		var mPane = getMiniPaneForQuickSearch('');
       		miniDiv.appendChild(mPane.domNode);
			document.getElementsByTagName('body')[0].appendChild(miniDiv);
			return miniDiv;
		}	
	
		function getMiniPaneForQuickSearch(u) { 
			// UPDATES THE URL IN THE MINIPANE AND RETURNS A HANDLE FOR THE WIDGET
			var pane = dojo.widget.getWidgetById('miniPaneQuickSearch');
			if(!pane) {
				pane = dojo.widget.createWidget('ContentPane', {widgetId:'miniPaneQuickSearch', loadingMessage:' '});
			}
			if(u) pane.setUrl(u);
			return pane;
		}
	
		function cancelQuickSearchMini(){
			var miniDiv = getMiniDivForQuickSearch();
			miniDiv.style.top = '-500px';
			miniDiv.style.left = '-500px';
		}
		function positionMini(miniDiv) {
			// WHEN IT IS TIME TO MAKE MINI VISIBLE, WE SET ITS COORDINATES
			// TO THE APPROPRIATE POSITION ON THE PAGE (BASED ON MOUSE POS
			// OR RELATIVE ELEMENT).  
			// WHEN MINI IS INVISIBLE, IT IS ACTUALLY POSITIONED ABOVE THE 
			// TOP OF THE SCREEN
			var miniX = miniDiv.mousex + 10;
			var miniY = miniDiv.mousey - 10;
			
			if(isIE) {
				miniY += vScroll();
				miniX += hScroll();
			}
			
			var hScrollNum = hScroll();
			var vScrollNum = vScroll();
			var minX = 10;
			var maxX = pageWidth() + hScrollNum - getDivWidth(miniDiv) - 25;
			var minY = 10;
			var maxY = pageHeight() + vScrollNum - getDivHeight(miniDiv) - 25;
			
			if(isIE && !isIE8) {
				minX -= 150;
				maxX -= 150;
			}
			
			// alert('VSCROLL is ' + vScroll() + ' AND PAGE HEIGHT IS ' + pageHeight() + ' and mini Y IS ' + miniY + ' / '+ ' THEREFORE MAX Y IS ' + maxY + ' / ' + isIE);
			// alert('X: ' + minX + ' < ' + miniX + ' < ' + maxX + ' - ' + getDivWidth(miniDiv) + ', Y: ' + minY + ' < ' + miniY + ' < ' + maxY + ' - ' + getDivHeight(miniDiv));
			if(miniY < minY) {
				// WHOOPS, SLID OFF THE TOP OF THE SCREEN.  COME BACK DOWN
				miniY = minY;
				// alert('SHIFT DOWN TO ' + miniY + ' BECAUSE PAGE IS SCROLLED TO ' + vScroll() + ' AND MOUSE IS AT ' + miniDiv.mousey + ' AND BOTTOM OF SCREEN IS AT ' + pageHeight());
			} else if(miniY > maxY) {
				// WHOOPS, SLID OFF THE BOTTOM OF THE SCREEN.  COME BACK UP
				miniY = maxY;
				// alert('SHIFT UP TO ' + miniY + ' BECAUSE PAGE IS SCROLLED TO ' + vScroll() + ' AND MOUSE IS AT ' + miniDiv.mousey + ' AND BOTTOM OF SCREEN IS AT ' + pageHeight());
			} else {
				// alert('DEFAULT VERTICAL OK ' + miniY);
			}
			if(miniX < minX) {
				// WHOOPS, SLID OFF THE RIGHT SIDE OF THE SCREEN.  TRY TO SHOW ON LEFT INSTEAD
				miniX = minX;
				// alert('SHIFT RIGHT TO ' + miniX);
			} else if(miniX > maxX) {
				// WHOOPS, SLID OFF THE RIGHT SIDE OF THE SCREEN.  TRY TO SHOW ON LEFT INSTEAD
				miniX = maxX;
				// alert('SHIFT LEFT TO ' + miniX);
			} else {
				// alert('DEFAULT HORIZONTAL OK');
				
			} 
			// alert("X: " + miniX);
			miniDiv.style.top =  miniY + 'px';
			if(isIE && !isIE8) miniDiv.style.left = (miniX - 150) + 'px';
			else miniDiv.style.left = miniX + 'px';
		}
		function getMiniPane(u) { 
			// UPDATES THE URL IN THE MINIPANE AND RETURNS A HANDLE FOR THE WIDGET
			var pane = dojo.widget.getWidgetById('miniPane');
			if(!pane) {
				pane = dojo.widget.createWidget('ContentPane', {widgetId:'miniPane', loadingMessage:' '});
				pane.onLoad=miniPaneLoaded;
			}
			if(u) pane.setUrl(u);
			return pane;
		}
		function getMiniDiv() {
			// RETURNS A DIV ELEMENT OBJECT REPRESENTING THE CONTENT PANE OF THE 
			// MINI DOJO WIDGET
			// PARAMS LIKE POSITION, URL, ETC. ARE STORED AS ATTRIBUTES ON THIS DIV
			// MINI IS GENERATED SYSTEMATICALLY IF NOT ALREADY CREATED THE FIRST
			// TIME IT IS REQUESTED
			var miniDiv = document.getElementById('miniDiv');
			if(miniDiv) return miniDiv;
			miniDiv = document.createElement('div');
			miniDiv.id = 'miniDiv';
			miniDiv.state = 0;	// INITIALLY IT IS INVISIBLE
			miniDiv.style.position = 'absolute';
			miniDiv.style.top = '-500px';
			miniDiv.style.zIndex = '101';
			miniDiv.style.left = '-500px';
			miniDiv.mousex = 0;
			miniDiv.mousey = 0;
       		var mPane = getMiniPane('');
       		miniDiv.appendChild(mPane.domNode);
			document.getElementsByTagName('body')[0].appendChild(miniDiv);
			miniDiv.onmouseout = cancelMini;
			miniDiv.onmouseover = cancelMiniCancel;
			document.onclick = killMini;
			return miniDiv;
		}
		function updateMousePos(e, miniDiv) {
			miniDiv.mousex = (e.pageX) ? e.pageX : (e.clientX) ? e.clientX : 0;
			miniDiv.mousey = (e.pageY) ? e.pageY : (e.clientY) ? e.clientY : 0;
        }
		function updateRelativeMousePos(relObj, miniDiv) {
          miniDiv.mousex = getposOffset(relObj, 'left') - 10;
          miniDiv.mousey = (getposOffset(relObj, 'top') + 30) - document.documentElement.scrollTop;
        }
        function cancelMiniCancel() {
        	// THIS MEANS MINI WAS GHOST VISIBLE - PREPARING TO DISAPPEAR IN A SEC
        	// AND THE USER ROLLED BACK OVER SOMETHING TO PREVENT MINI FROM DISAPPEARING
        	// FOR INSTANCE, THE MINI LINK OR IMAGE, OR PERHAPS MINI ITSELF
        	// THIS CHANGES THE STATE FROM GHOST VISIBLE BACK TO "REGULAR" VISIBLE
        	var miniDiv = getMiniDiv();
			if(miniDiv.state == 6) return;
			miniDiv.state = 2; 	// NOW IT IS REGULAR VISIBLE AGAIN
        }
        function freezeMini(freezer) {
        	// MINI IS FROZEN AND WILL NOT DISAPPEAR EVEN IF YOU ROLL OFF.
        	var miniDiv = getMiniDiv();
			miniDiv.freezer = freezer; 	
			miniDiv.priorState = miniDiv.state; 	
			miniDiv.state = 6; 	// NOTHING CAN MAKE MINI CHANGE WHEN MINI STATE IS 6
        }
        function unfreezeMini(unfreezer) {
        	// RETURNS MINI TO NORMAL SO IT WILL DISAPPEAR AFTER A SEC IF YOU ROLL OFF
        	var miniDiv = getMiniDiv();
			if(miniDiv.state != 6) return;
			if(miniDiv.freezer != unfreezer) return;
			var priorSt = miniDiv.priorState;
			if(!priorSt) priorSt = 0;
			miniDiv.state = priorSt; 	// NOTHING CAN MAKE MINI CHANGE WHEN MINI STATE IS 6
        }
        function cancelMini() {
			if(operationWillAbort) {
				return;
			} 
        	// THIS FUNCTION MAKES MINI DISAPPEAR IN A SEC UNLESS YOU MOUSE BACK OVER THE LINK FIRST 
          	var miniDiv = getMiniDiv();
			if(miniDiv.state == 6) return;
          	if(miniDiv.state == 1) {
        		miniDiv.state = 0;
          	} else if(miniDiv.state == 2) {
        		miniDiv.state = 3;
				setTimeout('setMiniFrameVisibility(false)', miniDiv.ghostDelay);
          	}
        }
        function killMini() {
        	// THIS FUNCTION MAKES MINI DISAPPEAR IMMEDIATELY 
        	var miniDiv = getMiniDiv();
			miniDiv.state = 3;
			setMiniFrameVisibility(false);
        }
        function setMiniFrameVisibility(vis) {
			var miniDiv = getMiniDiv();
			if(vis) {
				if(miniDiv.state != 1) return; 	// ONLY SHOW IT IF THE MINI IS IN PRE-VISIBLE MODE, NOT IF WE MOUSED OFF
				getMiniPane(miniDiv.miniUrl);
				miniDiv.state = 2;
				positionMini(miniDiv);
			} else {
				if(miniDiv.state != 3) return; 	// ONLY CANCEL IT IF THE MINI IS IN GHOST-VISIBLE MODE, NOT IF WE MOUSED BACK ON
				miniDiv.state = 0;
				miniDiv.style.top = '-500px';
				miniDiv.style.left = '-500px';
			}
		}
		function miniPaneLoaded() {
			setAnimationVisible(false);
			var mp = getMiniDiv();
			var repos = false;
			if(mp.width != mp.clientWidth) repos = true; 
			if(mp.height != mp.clientHeight) repos = true; 
			mp.width = mp.clientWidth;
			mp.height = mp.clientHeight;
			mp.style.width = mp.clientWidth;
			mp.style.height = mp.clientHeight;
			if(mp.state == 2 && repos)
				positionMini(mp);
		}
		function setAnimationVisible(vis) {
			if(vis) {
				if(document.getElementById('miniFrame')) document.getElementById('miniFrame').style.display = 'none';
			} else {
				if(document.getElementById('miniFrame')) document.getElementById('miniFrame').style.display = 'block';
			}
		}
        function pageWidth() {
		  var myWidth = 0;
		  if( typeof( window.innerWidth ) == 'number' ) {
		    //Non-IE
		    myWidth = window.innerWidth;
		  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		    //IE 6+ in 'standards compliant mode'
		    myWidth = document.documentElement.clientWidth;
		  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		    //IE 4 compatible
		    myWidth = document.body.clientWidth;
		  }
        	return myWidth; 
        }
        function pageHeight() {
        	// return document.body ? document.body.clientHeight : ( window.innerHeight != null ? window.innerHeight: null );
		  var myHeight = 0;
		  if( typeof( window.innerWidth ) == 'number' ) {
		    //Non-IE
		    myHeight = window.innerHeight;
		  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		    //IE 6+ in 'standards compliant mode'
		    myHeight = document.documentElement.clientHeight;
		  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		    //IE 4 compatible
		    myHeight = document.body.clientHeight;
		  }
        	return myHeight;
        }
        function hScroll() {
			var st = document.body.scrollLeft;
			if (st == 0) {
				if (window.pageXOffset)
					st = window.pageXOffset;
				else
					st = (document.body.parentElement) ? document.body.parentElement.scrollLeft : 0;
			}
			return st;
        }
        function vScroll() {
			var st = document.body.scrollTop;
			if (st == 0) {
				if (window.pageYOffset)
					st = window.pageYOffset;
				else
					st = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
			}
			return st;
        }
        function getDivHeight(miniDiv) {
        	var c = miniDiv.style.height;
        	if(c.indexOf('px') > -1)
        		c = c.substring(0, c.indexOf('px'));
        	if(!c || c == "0")
        		c = miniDiv.height;
        	return Number(c); 
        }
        function getDivWidth(miniDiv) {
        	var c = miniDiv.style.width;
        	if(c.indexOf('px') > -1)
        		c = c.substring(0, c.indexOf('px'));
        	if(!c || c == "0")
        		c = miniDiv.width;
        	return Number(c); 
        }



















// toggle hot-list (mini-profile only) ----------------------
function hottieAction(hottieAction, hottieId) {	
	var actionType = document.getElementById("hottieStatus-"+hottieId).getAttribute('actionType');
	var bindUrl = "/personals/hottie.do?formAction="+actionType+"Hottie&memberId="+hottieId;
	dojo.io.bind({
		url:bindUrl, load:function(type, data, evt){
			if (actionType == "remove") {
				document.getElementById("hottieStatus-"+hottieId).innerHTML = "Add to Hot List";
				document.getElementById("hottieStatus-"+hottieId).setAttribute('actionType', 'add');
			} else {
				document.getElementById("hottieStatus-"+hottieId).innerHTML = "Remove from Hot List";
				document.getElementById("hottieStatus-"+hottieId).setAttribute('actionType', 'remove');
			}
			
		}
	});
}


// miniLogin special validation ----------------------
function validateMemberName(memberName) {
	if(!memberName.match(/^[0-9A-Za-z_-]*$/)) {
		document.getElementById("error_memberName").style.display = "block";
		document.getElementById("error_memberName").innerHTML = "Membername must contain letters, numbers, and underscores only.";
		document.getElementById("submitDivNo").style.display = "block";
		document.getElementById("submitDivYes").style.display = "none";		
	} else {
		document.getElementById("error_memberName").style.display = "none";
		document.getElementById("submitDivNo").style.display = "none";
		document.getElementById("submitDivYes").style.display = "block";
	}
}
function validatePassword(password) {
	if(!password.match(/^[0-9A-Za-z_]*$/)) {
		document.getElementById("error_password").style.display = "block";
		document.getElementById("error_password").innerHTML = "Password must contain letters and numbers only.";		
		document.getElementById("submitDivNo").style.display = "block";
		document.getElementById("submitDivYes").style.display = "none";		
	} else if (password.length > 10 || password.length < 4) {
		document.getElementById("error_password").style.display = "block";
		document.getElementById("error_password").innerHTML = "Password must be between 4 and 10 characters.";
		document.getElementById("submitDivNo").style.display = "block";
		document.getElementById("submitDivYes").style.display = "none";
	} else {
		document.getElementById("error_password").style.display = "none";
		document.getElementById("submitDivNo").style.display = "none";
		document.getElementById("submitDivYes").style.display = "block";
	}
}
function validateSubmitSetting() {
	document.getElementById("submitDivYes").style.display = "block";
	document.getElementById("submitDivNo").style.display = "none";
}




/* --------------- END MINI-PANES --------------------------- */



/* --------------- START SCROLLING PHOTOS --------------------------- */



var opacitySpeed = 2;	// Speed of opacity - switching between large images - Lower = faster
var opacitySteps = 10; 	// Also speed of opacity - Higher = faster
var slideSpeed = 5;	// Speed of thumbnail slide - Lower = faster
var slideSteps = 10;	// Also speed of thumbnail slide - Higher = faster
var columnsOfThumbnails = false;	// Hardcoded number of thumbnail columns, use false if you want the script to figure it out dynamically.

/* Don't change anything below here */
var scroller_largeImage = false;
var scroller_currentOpacity = 100;
var scroller_slideWidth = false;
var scroller_thumbTotalWidth = false;
var scroller_viewableWidth = false;

var currentUnqiueOpacityId = false;
var scroller_currentActiveImage = false;
var scroller_thumbDiv = false;
var scroller_thumbSlideInProgress = false;

var browserIsOpera = navigator.userAgent.indexOf('Opera')>=0?true:false;
var leftArrowObj;
var rightArrowObj;
var thumbsLeftPos = false;

var scroller_largeCaption = false;
var imageCount = false;
var imagePosition = false;
var imageTotal = false;
var imageFirst = false;
var imageLast = false;
var imageToShow = false;
var showAlwaysArrow = false;



function initFeauturedMemberScrolling(viewableImages){
	leftArrowObj = document.getElementById('leftArrowPhotoLink');		
	rightArrowObj = document.getElementById('rightArrowPhotoLink');	
	var startPosition = document.getElementById('scroller_thumbs_inner').getElementsByTagName('DIV')[0].offsetWidth * -1;
	leftArrowObj.style.visibility='visible';
	rightArrowObj.style.visibility='visible';
	showAlwaysArrow = true
	scroller_largeImage = document.getElementById('scroller_largeImage').getElementsByTagName('IMG')[0];
	var innerDiv = document.getElementById('scroller_thumbs_inner');
	scroller_slideWidth = innerDiv.getElementsByTagName('DIV')[0].offsetWidth ;
	scroller_thumbDiv = document.getElementById('scroller_thumbs_inner');
	scroller_viewableWidth = document.getElementById('scroller_thumbs').offsetWidth;
	scroller_thumbTotalWidth = document.getElementById('feuturedMemberTotalWidth').value;
	var subDivs = scroller_thumbDiv.getElementsByTagName('DIV');	
	var tmpLeft = startPosition;	
	for(var no=0;no<subDivs.length;no++){
		if(subDivs[no].className=='strip_of_thumbnails'){
			subDivs[no].style.left = tmpLeft + 'px';
			subDivs[no].style.top = '0px';
			tmpLeft = tmpLeft + subDivs[no].offsetWidth;
		}
	}
	
	imageToShow = viewableImages/1;
	imageFirst = 1;
	imageLast = 4; 
	imageTotal = document.getElementById('scroller_thumbs').getElementsByTagName('IMG').length;	
}

function initFilmStrip(startPositon, viewableImages){
	scroller_largeImage = document.getElementById('scroller_largeImage').getElementsByTagName('IMG')[0];
	scroller_thumbDiv = document.getElementById('scroller_thumbs_inner');
	var subDivs = scroller_thumbDiv.getElementsByTagName('DIV');
	scroller_slideWidth = scroller_thumbDiv.getElementsByTagName('DIV')[0].offsetWidth ;
	scroller_thumbTotalWidth = 0;
	var tmpLeft = startPositon;
	for(var no=0;no<subDivs.length;no++){
		if(subDivs[no].className=='strip_of_thumbnails'){
			scroller_thumbTotalWidth = scroller_thumbTotalWidth + scroller_slideWidth;
			subDivs[no].style.left = tmpLeft + 'px';
			subDivs[no].style.top = '0px';
			tmpLeft = tmpLeft + subDivs[no].offsetWidth;
		}
	}
	imageToShow = viewableImages/1;
	imageFirst = 1;
	imageLast = 5;
	
	imageTotal = document.getElementById('scroller_thumbs').getElementsByTagName('IMG').length;	
	
	if(imageTotal>imageToShow){
		imageLast=imageToShow;
	}else{
		imageLast=imageTotal;
	}
	
}


function initGalleryScript(viewableImages)
{
	leftArrowObj = document.getElementById('scroller_leftArrow');		
	rightArrowObj = document.getElementById('scroller_rightArrow');	
	scroller_viewableWidth = document.getElementById('scroller_thumbs').offsetWidth;
	initFilmStrip(0, viewableImages);
	showPhotosAmount();
	slideToTheCorrectPhoto();
	
	//Check if we have more than photo to display the right arrow
	if (imageTotal <= imageToShow ){
		if (rightArrowObj) {
			rightArrowObj.style.visibility='hidden';
		}
	}

	if (imagePosition <= imageToShow){
		if (leftArrowObj) {
			leftArrowObj.style.visibility='hidden';
		}
	}
	scroller_currentActiveImage = document.getElementById('photoObject_'+imagePosition).getElementsByTagName('IMG')[0];
	scroller_currentActiveImage.className='activeImage';
	
	if (imagePosition > imageToShow) {
		for (var i = 0; i < imageToShow; i++) {
			showSelectedPhoto(imagePosition - i);
		}
	}

	displayOrHidePremiumIntercept(imagePosition);
}

function showPhotosAmount(){
	imagePosition = document.getElementById("photoPositionSelected").value;	
	document.getElementById('photoCount1').innerHTML = "&nbsp;" + imagePosition + " of " + imageTotal + "&nbsp;";
	document.getElementById('photoCount2').innerHTML = "&nbsp;" + imagePosition + " of " + imageTotal + "&nbsp;";
	displayOrHideNextPrevLink();
}

function displayOrHideNextPrevLink(){
	
	if (imagePosition <= 1){
		document.getElementById('prevPhotoLink').style.visibility='hidden';	
		document.getElementById('prevPhotoLink1').style.visibility='hidden';	
	}else{	
		document.getElementById('prevPhotoLink').style.visibility='visible';
		document.getElementById('prevPhotoLink1').style.visibility='visible';
	}
	
	if (imagePosition >= imageTotal){
		document.getElementById('nextPhotoLink').style.visibility='hidden';	
		document.getElementById('nextPhotoLink1').style.visibility='hidden';
	}else{
		document.getElementById('nextPhotoLink').style.visibility='visible';
		document.getElementById('nextPhotoLink1').style.visibility='visible';
	}
}

function displayOrHideArrows(){
	if (leftArrowObj) {
		if(imageFirst<= 1 || imageTotal<= imageToShow){
			leftArrowObj.style.visibility='hidden';
		}else{
			leftArrowObj.style.visibility='visible';
		}
	}
	if (rightArrowObj) {
		if(imageLast>=imageTotal || imageTotal<= imageToShow){
			rightArrowObj.style.visibility='hidden';
		}else{
			rightArrowObj.style.visibility='visible';
		}
	}
}



function slideToTheCorrectPhoto(){
	
	if (imageTotal > imageToShow){
		while (imagePosition < imageFirst ){
			movePhotoThumbnailLeft();
		}
		
		while (imagePosition > imageLast){
			movePhotoThumbnailRight();
		}
	}

}

function showNextPhoto(){
	
	imagePosition = parseInt(imagePosition) + 1.0;
	showPhotoByPosition(imagePosition);
}

function showPreviousPhoto(){

	imagePosition = parseInt(imagePosition) - 1.0;
	showPhotoByPosition(imagePosition);	
}

function getPhotoNumber() {
	var posToFind = parseInt(imagePosition);
    photoNumber = document.getElementById("photoNumberByPos_"+posToFind)
	if ( photoNumber != null){
		return photoNumber.value;
	}
}

function showSelectedPhoto(posToFind) {
	var image = document.getElementById('thumbImage_' + posToFind);
	var photo = document.getElementById('photoPathThumbnail_' + posToFind);
	image.src = photo.value;
}

function showPhotoByPosition(posToFind){
	var photoPositionToShow = document.getElementById("photoPosition_"+posToFind);
	if ( photoPositionToShow != null){
 		showSelectedPhoto(posToFind);
		showPreviewPhotoDetail(photoPositionToShow.value);
	}
}

function movePhotoThumbnails(moveDirection, continuousSliding)
{
	if (scroller_thumbSlideInProgress){
		return;
	}
	scroller_thumbSlideInProgress = true;
	
	if (continuousSliding == 'true') {
		continuousSlideImages(moveDirection);
	} else {
		dontContinuousSlideImages(moveDirection);
	}
}

function continuousSlideImages(moveDirection) {
	var moveCount=0;
	if(moveDirection=='left'){
		while (moveCount < imageToShow){
			movePhotoThumbnailLeft();
			moveCount ++;
		}
	}else{
		while (moveCount < imageToShow){
			movePhotoThumbnailRight();
			moveCount ++;
		}
	}
}

function dontContinuousSlideImages(moveDirection) {
	var moveCount=0;
	if(moveDirection=='left'){
		while (moveCount < imageToShow && imageFirst > 1 ){
			movePhotoThumbnailLeft();
			moveCount ++;
		}
	}else{
		while (moveCount < imageToShow && imageLast < imageTotal ){
			movePhotoThumbnailRight();
			moveCount ++;
		}
	}
}

function movePhotoThumbnailRight(){		
	slideThumbs((slideSteps*-1),0);
	imageFirst ++;
	imageLast ++;
}

function movePhotoThumbnailLeft(){	
	slideThumbs(slideSteps*+1,0);
	imageFirst --;
	imageLast --;
}

function slideThumbs(speed,currentPos)
{
	var leftPos = 0;
	currentPos = currentPos + Math.abs(speed);
	leftPos = leftPos + speed;
	var subDivs = scroller_thumbDiv.getElementsByTagName('DIV');
	var tmpLeft = 0;
	for(var no=0;no<subDivs.length;no++){
		if(subDivs[no].className=='strip_of_thumbnails'){
			tmpLeft = subDivs[no].style.left.replace('px','')/1 + leftPos;
			if (tmpLeft <= -2*scroller_slideWidth){
				subDivs[no].style.left = (scroller_thumbTotalWidth - 2*scroller_slideWidth) + 'px';
			}else{
				if( tmpLeft >= (scroller_thumbTotalWidth - scroller_slideWidth)){
					
					if (tmpLeft == (scroller_thumbTotalWidth - scroller_slideWidth)){
						subDivs[no].style.left = '-' +scroller_slideWidth+ 'px';						
					}else{//in the case we pass the left margin just add the leftpos to the position 
						subDivs[no].style.left = '-' +( scroller_slideWidth - leftPos )+ 'px';						
					}
				}else{
					subDivs[no].style.left = tmpLeft + 'px';
				}
				
			}
		}		
	}
	
	if(currentPos<scroller_slideWidth){
            setTimeout('slideThumbs(' + speed + ',' + currentPos + ')',slideSpeed);
      } else { 
            scroller_thumbSlideInProgress = false;
      }

}

function showPreviewPhotoDetail(picNumberPosition, ownGallery)
{		
	showPreview(picNumberPosition, true);	
	displayOrHidePremiumIntercept(picNumberPosition);
	showPhotosAmount();
	slideToTheCorrectPhoto();
			
	showSelectedPhoto(picNumberPosition);
	displayOrHideArrows();
}

function displayOrHidePremiumIntercept(picNumberPosition) {
	var premiumInterceptDiv = document.getElementById('largePhotoPremiumInterceptContainer');
	var photoClass = document.getElementById("photoClass_"+picNumberPosition).value;
	if (premiumInterceptDiv) {
		if (photoClass == 'DEFAULT') {
			premiumInterceptDiv.style.display = 'none';
		} else {
			premiumInterceptDiv.style.display = 'block';
		}
	}
}


function showPreviewFeauturedMember(picNumber){
	// alert('SHOW PREVIEW FOR MEMBER ' + picNumber);
	var photoObj = $("photoObject_"+picNumber)
	if(scroller_currentActiveImage){
		if(scroller_currentActiveImage==photoObj.getElementsByTagName('IMG')[0])return;
		scroller_currentActiveImage.className='';
	}

	//This is only for the homepage
	if ($("headline_"+picNumber) != null){
		var headLine = $("headline_"+picNumber).innerHTML;
		$('scroller_headline').innerHTML = headLine; 
	}
	
	var caption = $("caption_"+picNumber).innerHTML;
	var photoPath = $("photoPathFull_"+picNumber).value;
	scroller_currentActiveImage = photoObj.getElementsByTagName('IMG')[0];
	scroller_currentActiveImage.className='activeImage';
	$('scroller_largeCaption').innerHTML = caption;
	$("photoNumberSelected").value = picNumber;
	setSelectedPhoto(photoPath);
	var photoSelected  = $("photoPosition_"+picNumber).value; 
	$("photoPositionSelected").value = photoSelected;
	profileLink = document.getElementById("photoProfileLink_"+picNumber).value;
	document.getElementById("profileLink").href = profileLink;
}

function showPreview(picNumber, blackLoader){
	var photoObj = $("photoObject_"+picNumber)
	if(scroller_currentActiveImage){
		if(scroller_currentActiveImage==photoObj.getElementsByTagName('IMG')[0])return;
		scroller_currentActiveImage.className='';
	}

	//This is only for the homepage
	if ($("headline_"+picNumber) != null){
		var headLine = $("headline_"+picNumber).innerHTML;
		$('scroller_headline').innerHTML = headLine; 
	}
	
	var caption = $("caption_"+picNumber).innerHTML;
	var photoPath = $("photoPathFull_"+picNumber).value;
	
	var maskType = $("photoMaskType_"+picNumber).value;

	scroller_currentActiveImage = photoObj.getElementsByTagName('IMG')[0];
	scroller_currentActiveImage.className='activeImage';
	if ((maskType == "PRIVATE_PHOTO_MASK") || (maskType == "PRIVATE_PHOTO_UPSELL_MASK")) {
		$('scroller_largeCaption').innerHTML = $("photoUpsellText_"+picNumber).value;
		if ($('photoInterceptUpgradeLink')) {
			$('photoInterceptUpgradeLink').href = "/members/subscribe/select.do?msgkey=subscribe.photodetail.private";
		}
	} else {
		$('scroller_largeCaption').innerHTML = caption;
		if ($('photoInterceptUpgradeLink')) {
			if (maskType == "ADULT_PHOTO_MASK") {
				$('photoInterceptUpgradeLink').href = "/members/subscribe/select.do?msgkey=subscribe.photodetail.adult";
			} else {
				$('photoInterceptUpgradeLink').href = "/members/subscribe/select.do?msgkey=subscribe.photodetail.full.size";
			}
		}
	}
	$("photoNumberSelected").value = picNumber;
	if ($("interceptThumbnailImg") != null) {
		$("interceptThumbnailImg").src=scroller_currentActiveImage.src;
	}
	setSelectedPhoto(photoPath, blackLoader);
	
	var photoSelected  = $("photoPosition_"+picNumber).value; 
	$("photoPositionSelected").value = photoSelected;

}


function setSelectedPhoto(photoPath, blackLoader)
{
		var old_largeImage = $("large_image_detail_id");
		old_largeImage.className="large_image_detail";
		if (blackLoader) {
			old_largeImage.src = "/imgs/loader_Anim_black.gif";
		} else {
			old_largeImage.src = "/imgs/loader_Anim.gif";
		}
		old_largeImage.src = photoPath;
		old_largeImage.id="large_image_detail_id";
}

function uploadScrollingImages(direction, offset, positionsToOffset) {
	var scrollerThumbsInner = document.getElementById('scroller_thumbs_inner');
	var thumbnailDivs = scrollerThumbsInner.getElementsByTagName('DIV');
	var start = offset * positionsToOffset;	
	var positions = new Array(positionsToOffset);
	
	positions[0] = start;	
	if (direction == "left") { 
		start = scroller_thumbTotalWidth - (offset * (positionsToOffset/1 + 1));
		positions[0] = '-' + offset;
	}
	
	for (var i = 1; i < positionsToOffset; i++) {
		positions[i] = start + (offset*i);
	}

	var count = 0;
	for (var i = 0; i < thumbnailDivs.length; i++) {
		var tag = thumbnailDivs[i];
		var tagNumberPosition = tag.id.lastIndexOf('_');	
		if (tag.id.match('strip_of_thumbnails_')) {
			var tagNumber = tag.id.substr(tagNumberPosition);
			var image = document.getElementById('thumbImage' + tagNumber);						
			var leftStyle = tag.style.left.replace('px','');
			
			var photo = document.getElementById('photoPathThumbnail' + tagNumber); 	
			for (var j = 0; j < positions.length; j++) {
				if (leftStyle == positions[j]) {
					image.src = photo.value;
				}
			}
		}
	}
}

function setImgSrc(imgNum, str) {
	if($('thumbImage'+imgNum)) {
		$('thumbImage'+imgNum).src = str;
	}
}

/* --------------- END SCROLLING PHOTOS --------------------------- */





/* --------------- START TOGGLE --------------------------- */



//common across form
function toggle(boxId, linkId, closeText, openText) {
	if (document.getElementById(boxId).style.display == 'none') {
		display(boxId);
		changeLink(linkId, closeText);
		return;
	} else {
		hide(boxId);
		changeLink(linkId, openText);
	}
}

//common across form
function toggleTwoLinks(boxId, linkId, linkId2, closeText, openText) {
	if (document.getElementById(boxId).style.display == 'none') {
		display(boxId);
		changeLink(linkId, closeText);
		changeLink(linkId2, closeText);
		return;
	} else {
		hide(boxId);
		changeLink(linkId, openText);
		changeLink(linkId2, openText);
	}
}


//common across form when you have subtext below your section heading
function toggleHeading(boxId, linkId, sectionDescriptionId, closeText, openText) {
    toggle(boxId, linkId, closeText, openText);
    if (sectionDescriptionId != null) {
		if (document.getElementById(boxId).style.display == 'block') {
			hide(sectionDescriptionId);
		} else {
			display(sectionDescriptionId);
		}
	}
}

function display(id) { 
	document.getElementById(id).style.display = 'block';
}
function hide(id) { 
	document.getElementById(id).style.display = 'none';
}
function changeLink(linkId, text) {
	document.getElementById(linkId).innerHTML = text;
}



/* --------------- END TOGGLE --------------------------- */





/* --------------- START ACCOUNT --------------------------- */


//within the newsletter section, when a user clicks
//on a group, all newsletters should be selected
//within that group. Same logic for unselected.
function updateNewslettersWhenGroupSelected(groupId){

    var el = document.getElementById(groupId);
    var divChildNodes = el.childNodes;
    var groupLevelChecked = true;

    for (var i=0; i<divChildNodes.length; i++) {
        //this is the group-level checkbox
        if(divChildNodes[i].type == "checkbox") {
            if(divChildNodes[i].checked == true) {
                groupLevelChecked = true;
            }
            else if (divChildNodes[i].checked == false) {
                groupLevelChecked = false;
            }
        }
        //newsletter level checkbox
        else if (divChildNodes[i].id == "children") {
            var newsletterNodes = divChildNodes[i].childNodes;
            for (var j=0; j<newsletterNodes.length; j++) {
            	if(newsletterNodes[j].type == "checkbox" ) {
                	if (groupLevelChecked == true)
                        newsletterNodes[j].checked = true;
                	else if (groupLevelChecked == false)
                    	newsletterNodes[j].checked = false;
                }
            }
        }
    }
}

//within the newsletter section, when a user clicks
//on a newsletter, the group checkbox should be
//selected if all newsletters in the group are
//selected...same logic for unselecting.
function updateGroupWhenNewsletterSelected(groupId){

    var el = document.getElementById(groupId);
    var divChildNodes = el.childNodes;
    var groupCheckBoxElement;
    var allChildrenCheckedTrue = 0;
    var allChildrenCheckedFalse = 0;

    for (var i=0; i<divChildNodes.length; i++) {
        //this is the group-level checkbox -- we
        //want to store this for later
        if(divChildNodes[i].type == "checkbox") {
             groupCheckBoxElement = i;
        }
        //newsletter level checkbox
        else if (divChildNodes[i].id == "children") {
            var newsletterNodes = divChildNodes[i].childNodes;
            for (var j=0; j<newsletterNodes.length; j++) {
                if(newsletterNodes[j].type == "checkbox" ) {
                    if (newsletterNodes[j].checked == true)
                        allChildrenCheckedTrue += 1;
                    else if (newsletterNodes[j].checked == false)
                        allChildrenCheckedFalse += 1;
                }
            }
        }
    }
    if (allChildrenCheckedTrue > 0 && allChildrenCheckedFalse == 0)
        divChildNodes[groupCheckBoxElement].checked = true;
    else
        divChildNodes[groupCheckBoxElement].checked = false;
} 

function confirmCancel(location) {
	var messagePre = "Please confirm:\n";
	var message = messagePre + "Are you sure you want to cancel your membership";
	var choice = confirm(message);
	if (choice == true) {
		window.location = location;
		return true;
	} else {
		return false;
	}
}

// Confirm password dialog
var cancelAction = false;
function confirmPasswordDialog(){
	closeConfirmPasswordDialog();
	var viewport = getViewportDimensions();
	var pane = dojo.widget.createWidget('ContentPane', {widgetId:'confirmPasswordDialogId', cacheContent:false});
	pane.domNode.className = 'confirmPasswordDialog';
	document.body.appendChild(pane.domNode);
	pane.setUrl("/members/account/confirmPassword.do");
	pane.domNode.style.display = 'block';
	
	var leftInt = Math.round((viewport.width - 338) / 2);
	var topInt = Math.round((viewport.height - 315) / 2);
	
	leftInt += hScroll();
	topInt += vScroll();

	pane.domNode.style.left = leftInt < 0?0 + 'px':leftInt + 'px';
	pane.domNode.style.top = topInt < 0?0 + 'px':topInt + 'px';
}

function closeConfirmPasswordDialog() {
	if(dojo.widget.getWidgetById('confirmPasswordDialogId')) {
		cancelAction = true;
		var pane = dojo.widget.getWidgetById('confirmPasswordDialogId');
		pane.domNode.style.display = 'none';
		pane.destroy();
	}
}

function doConfirmPassword(action) {
	if (document.confirmPasswordForm.passwd.value == '') {
		showConfirmPasswordError('Password not supplied');
		return;
	}
	document.getElementById('confirmPasswordFormContainer').style.display = 'none';
	document.getElementById('confirmPasswordMsg').style.display = 'block';
	dojo.io.bind( {
		        url: "/members/account/confirmPassword/submit.do",
		        content: {"passwd":document.confirmPasswordForm.passwd.value},
		        method: "POST",
		        mimetype: "text/html",
		        load: function(type, value, evt) {
		        	if (dojo.widget.getWidgetById('confirmPasswordDialogId')) {
					if (value == 'MATCH') {
						window.location.href = action;
					} else {
						showConfirmPasswordError('Password did not match');
					}
		        	}
		        },            
		        error: function(type, error) {
		        	if (dojo.widget.getWidgetById('confirmPasswordDialogId')) {
		        		showConfirmPasswordError(error.getMessage());
		        	}
		        }
	   });
}
function showConfirmPasswordError(msg) {
	var errDiv = document.getElementById('confirmPasswordError');
	errDiv.innerHTML = msg;
	errDiv.style.display = 'block';
	document.confirmPasswordForm.passwd.value = '';
	document.getElementById('confirmPasswordMsg').style.display = 'none';
	document.getElementById('confirmPasswordFormContainer').style.display = 'block';
	document.confirmPasswordForm.passwd.focus();
}
// End Confirm password dialog


/* --------------- END ACCOUNT --------------------------- */







/* --------------- START SEARCH --------------------------- */
var cX = 0; 
var cY = 0;;
var scrollbarY = 0;
var scrollbarX = 0;
function updateScrollPosition() {
  	if (window.pageYOffset){
        scrollbarY=window.pageYOffset;
        scrollbarX=window.pageXOffset;
    } else if (document.documentElement){
        scrollbarY=document.documentElement.scrollTop;
		scrollbarX=document.documentElement.scrollLeft;
    } else if (document.body){
        scrollbarY=document.body.scrollTop;
        scrollbarX=document.body.scrollLeft;
    }
}
function UpdateCursorPosition(e){ 
	if(document.all) { 
		cX = event.clientX-3 + document.body.scrollLeft; 
		cY = event.clientY-5 + document.body.scrollTop;
	} else { 
		cX = e.pageX; 
		cY = e.pageY;
	}
}

// assign position by event ----------------------
function AssignPosition(the_obj, evt, y, x) {
    if (!y) y = 0;
    if (!x) x = 0;
    updateScrollPosition();
	the_obj.style.top = (evt.clientY + y + scrollbarY) + "px";
	the_obj.style.left = (evt.clientX + x + scrollbarX-80) + "px";
}


//start ConfirmBox Functions
var activeConfirmBox=null;
function ConfirmBox(props){ 
 
 this.message = props.message;
 this.evt = (typeof(props.evt)!="undefined" ? props.evt : null);
 this.url = (typeof(props.url)!="undefined" ? props.url : "");
 this.confirmAction = (typeof(props.confirmAction)!="undefined" ? props.confirmAction : "");
 this.cancelAction = (typeof(props.cancelAction)!="undefined" ? props.cancelAction : "");
 this.okLabel = (typeof(props.okLabel)!="undefined" ? props.okLabel : "YES");
 this.cancelLabel = (typeof(props.cancelLabel)!="undefined" ? props.cancelLabel : "NO");
 this.title = (typeof(props.title)!="undefined" ? props.title : "");
 this.showOnTop = props.showOnTop;
 this.showPushLeft = props.showPushLeft;
 this.showSouthOfEvent = props.showSouthOfEvent;
 this.showTopLeft = props.showTopLeft;
 if(typeof(props.objectName)!="undefined") {
  this.callingObject = document.getElementById(props.objectName);
 } else if (typeof(props.callingObject)!="undefined") {
  this.callingObject = props.callingObject;
 } else {
  this.callingObject = null;
 }
 
 this.box=document.createElement("div");
 this.box.innerHTML="<div class='popBlock'>" +
                  "      <div class='close'>" + 
                  "          <a href='javascript:  void(0);' onclick='activeConfirmBox.hide();'>close" + 
                  "          <img src='/imgs/close.gif' alt='close'></a>" + 
                  "      </div>" +
                  "      <div class='content'>" + this.title + 
                  "          <p>" + this.message + "</p>" +
                  "      </div>" +   
                  "      <div class='PopupButton'>" +                  
                  "          <input type='button' value='" + this.okLabel + "' onclick='activeConfirmBox.ok();'>&nbsp;&nbsp;&nbsp;&nbsp;" + 
                  "          <input type='button' value='" + this.cancelLabel + "' onclick='activeConfirmBox.cancel();'>"
                  "      </div>"  + 
                  "  </div>";
 this.box.className="confirmBox";
}

ConfirmBox.prototype.show=function() {
 document.body.appendChild(this.box);
 if(this.evt) {
 	var top=0; var left=0;
 	if( this.showOnTop ) {
  		top=-135; left=0;
 	} else if( this.showPushLeft ) {
  		top=-145; left=-470;
 	} else if( this.showSouthOfEvent ) {
  		top=10; left=0;
 	} else if( this.showTopLeft) {
 		left=-180;
  		if (isIE) { top=document.body.scrollTop; }
  		else { top=-130; }
  	} else {
  		if(isIE) top=document.body.scrollTop;
  	}
	// alert("top: " + top + ", left: " + left + ", " + this.showOnTop + "/" + this.showPushLeft + "/" + this.showTopLeft);
  	AssignPosition(this.box, this.evt, top, left);
 } else if(this.callingObject) {
  this.box.style.top = this.callingObject.offsetTop + "px";
  this.box.style.left = this.callingObject.offsetLeft + "px";
 }
 this.box.style.display="block";
 this.box.style.position="absolute";
}
ConfirmBox.prototype.hide=function() {
 this.box.style.display="none";
 document.body.removeChild(this.box);
 activeConfirmBox=null;
}
ConfirmBox.prototype.ok=function() {
 this.hide();
 if(this.url) {
  location.href=this.url;
 } else if (typeof(this.confirmAction)=="function") {
    this.confirmAction();
 } else if (typeof(this.confirmAction)=="string") {
	eval(this.confirmAction);
 }
}
ConfirmBox.prototype.cancel=function() {
 this.hide();
 if(this.cancelAction) {
  this.cancelAction();
 }
}

function confirmMyAction(props) {
 if(operationWillAbort) return false;
 if(activeConfirmBox) {
   activeConfirmBox.hide();
 }
 activeConfirmBox = new ConfirmBox(props);
 activeConfirmBox.show();
 return false;
}
//end ConfirmBox functions

//start CVV2Box and OfferDetailsBox Functions
function showElement(elName) {
	var elVar = $(elName);
	if (elVar) { elVar.style.display = "block"; }
}
function hideElement(elName) {
	var elVar = $(elName);
	if (elVar) { elVar.style.display = "none"; }
}
//end CVV2Box and OfferDetailsBox functions

var profleSubNavActionMsgObj = null;
var profleSubNavActions = new Array();
profleSubNavActions["hotlist1"]=["/personals/hottie.do?formAction=addHottie&memberId=","Add to Hot List","You have removed ", " from your Hot List."];
profleSubNavActions["hotlist0"]=["/personals/hottie.do?formAction=removeHottie&memberId=","Remove from Hot List","You have added ", " to your Hot List."];
profleSubNavActions["bookmark1"]=["/personals/bookmark.do?formAction=add&memberId=","Bookmark","You have removed ", " from your Bookmarks."];
profleSubNavActions["bookmark0"]=["/personals/bookmark.do?formAction=delete&memberId=","Remove Bookmark","You have added ", " to your Bookmarks."];
profleSubNavActions["buddy1"]=["/personals/buddy.do?formAction=buddyRequest&memberId=","Send Friend Request","Your friend request for ", " has been cancelled."];
profleSubNavActions["buddy0"]=["/personals/buddy.do?formAction=cancelBuddyRequest&memberId=","Cancel Friend Request","Your friend request has been sent to ", "."];
profleSubNavActions["buddy2"]=["/personals/buddy.do?formAction=endBuddyRelationship&memberId=","Send Friend Request","You and ", " are no longer friends."];
profleSubNavActions["buddy3"]=["/personals/buddy.do?formAction=buddyAccept&memberId=","Remove Friend","You and ", " are now friends."];
profleSubNavActions["buddy4"]=["/personals/buddy.do?formAction=deniedBuddyRequest&memberId=","Send Friend Request","You have denied ", "'s friend invite."];
profleSubNavActions["block1"]=["/personals/block.do?formAction=addBlock&memberId=","Block", "", " has been removed from your Block List."];
profleSubNavActions["block0"]=["/personals/block.do?formAction=removeBlock&memberId=","Remove Block", "You have added ", " to your Block List."];

function doProfileSubNavAction(the_action,action_state,id, the_link_node, the_wrapper_node, uName, event) { 
	//alert("DO1 " + the_action + " STATE " + action_state);

	// Disable the active link because it should never be used again. The new link will be enabled.
	
	if (the_action != "block") // block has a dialog in between, so we dont need to do this
	{
		the_link_node.onclick = function(evt) {};
	}
	if(the_action == "block" && action_state == 1) {
 		confirmBlockAction(id, uName, the_link_node, event);
 		return;
 	}else if(the_action == "block" && action_state == 3) {
 		action_state = 1;
	}
	var my_action = profleSubNavActions[the_action+action_state];
	var the_url = my_action[0] + id + "&isAjax=1";
 	 //alert('AJAX URL ' + the_url);
 
	if (the_action == "buddy" && action_state == 2) {
		// REMOVE FRIEND, CHANGE LINK TO ADD FRIEND
		var reverse_state = 2;
	} else if (the_action == "buddy" && action_state == 3) {
		// ACCEPT FRIEND, CHANGE LINK TO REMOVE FRIEND
	  var reverse_state = 3;
	} else if (the_action == "buddy" && action_state == 4) {
		// DENY FRIEND, CHANGE LINK TO ADD FRIEND
	  var reverse_state = 4;
	} else if (!action_state) {
		// CANCEL INVITE, CHANGE LINK TO ADD FRIEND 	
	  var reverse_state = 1;
	} else {
	  var reverse_state = 0;
	}
	var success = function(){ profileSubNavActionSuccess(the_action, reverse_state, id, the_link_node, the_wrapper_node, uName ); }
	var failure = function(){ profileSubNavActionFailed(the_link_node); }

  dojo.io.bind({
   url: the_url,
   method: "GET",
   mimetype: 'text/html',
   preventCache: true,
   load: success,
   error: failure
  });
 
 return false;
}

function profileSubNavActionSuccess(the_action, action_state, id, the_link_node, the_wrapper_node, uName) {
	if(the_action == "block" && action_state == 0) {
		location.reload();
		return;
	}
	//alert('SUCCESS ' + the_action + ' - ' + action_state + '; ' + id);
	the_link_node.innerHTML = '';
	
 	var the_link;
	// THIS CONVERTS THE LINK TO "REMOVE FRIEND" AFTER ACCEPTING 
	// A REQUEST.	WE USE REV_ACTION_STATE INSTEAD OF CHANGING ACTION_STATE
	// BECAUSE THATS USED FOR DETERMINING THE CONFIRMATION MESSAGE 
	var rev_action_state = action_state;
	if(action_state == 2) rev_action_state = 1;	// REQUEST TO REMOVE, CHANGE TO ADD
	else if(action_state == 3) rev_action_state = 2; // REQUEST ACCEPTED, CHANGE TO REMOVE
	else if(action_state == 4) rev_action_state = 1; // REQUEST REJECTED, CHANGE TO ADD
	if(the_action == "buddy" && (action_state == 3 || action_state == 4)) {
		// special case when buddy request accepted/rejected.
		the_wrapper_node.innerHTML='';
		the_link = document.createElement('a');
		the_link.innerHTML=profleSubNavActions[the_action+action_state][1];
		the_link.href = "javascript:void(0);";
		the_link.onclick=function(evt) { 
			doProfileSubNavAction(the_action, rev_action_state, id, the_link, the_wrapper_node, uName, window.event != undefined ? window.event : evt);
			return false; 
		};
		the_wrapper_node.appendChild(the_link);
	} else { 
		the_link = the_link_node; 
		the_link.onclick=function(evt) { 
			doProfileSubNavAction(the_action, rev_action_state, id, the_link_node, the_wrapper_node, uName, window.event != undefined ? window.event : evt);
			return false; 
		};
		the_link.innerHTML=profleSubNavActions[the_action+action_state][1];
	}

	var confirmObject = top.document.getElementById("confirmationBox");
	// alert("CONF THIS " + confirmObject);
	if(confirmObject) {
		confirmObject.innerHTML=profleSubNavActions[the_action+action_state][2] + uName + profleSubNavActions[the_action+action_state][3];
		var confirmHolder = document.getElementById("confirmMessage");
		if(confirmHolder && confirmHolder.style.display == 'none') {
			confirmHolder.style.display = 'block';
		}
	} else if(document.getElementById('PvtChatContentPaneDiv')) {
		var str = profleSubNavActions[the_action+action_state][2] + uName + profleSubNavActions[the_action+action_state][3];
		var pvtChat = getPvtChatPane();
		pvtChat.addSystemMessage(str, uName);
	}
}

function profileSubNavActionFailed(the_link_node) {
	if (!profleSubNavActionMsgObj) {
		var msg="Sorry, there is an issue in processing your request.";
		profleSubNavActionMsgObj = document.createElement("div");
		profleSubNavActionMsgObj.id="myActionMsg";
		profleSubNavActionMsgObj.innerHTML=msg;
		profleSubNavActionMsgObj.style.position="absolute";
		document.body.appendChild(profleSubNavActionMsgObj);
	}
	profleSubNavActionMsgObj.style.top=(the_link_node.offsetTop - 20) + "px";
	profleSubNavActionMsgObj.style.left=the_link_node.offsetLeft + "px";
}
function confirmBlockAction(toId, targetMemberName, link, event) {
	var confirmAction = function() {
		doProfileSubNavAction('block',3, toId, link, targetMemberName, event);
	};
	var confirmProps = {
		'url':'',
		'confirmAction':confirmAction,
		'evt':event,
		'message':"Are you sure that you want to block all contact from " + targetMemberName + "?\n\n" + "<br/><br/>" + 
			"This will block mail and IM contact, remove this member from your lists, " +
			"and lock any private photos you have shared with this member.",
		'showTopLeft':'true'
	};
	confirmMyAction(confirmProps);
}

//Search Functions
var myActionMsgObj = null;
var myListActions = new Array();
myListActions["hotlist1"]=["/personals/hottie.do?formAction=addHottie&memberId=","Add to Hot List"];
myListActions["hotlist0"]=["/personals/hottie.do?formAction=removeHottie&memberId=","Remove from Hot List"];
myListActions["bookmark1"]=["/personals/bookmark.do?formAction=add&memberId=","Bookmark"];
myListActions["bookmark0"]=["/personals/bookmark.do?formAction=delete&memberId=","Remove Bookmark"];

function doMyListAction(the_action,action_state,id, the_link) {
 myListAction = the_action;
 var my_action = myListActions[the_action+action_state];
 var the_url = my_action[0] + id + "&isAjax=1";
 
 if (!action_state) {
   var reverse_state = 1;
 } else {
   var reverse_state = 0;
 }
 var success = function(){ myListActionSuccess(the_action, reverse_state, id, the_link ); }
 var failure = function(){ myListActionFailed(the_link); }

  dojo.io.bind({
   url: the_url,
   method: "GET",
   load: success,
   error: failure
  });
 
 return false;
}

function myListActionSuccess(the_action, action_state, id, the_link) {
  the_link.onclick=function() { doMyListAction(the_action, action_state, id, the_link) };
  the_link.innerHTML=myListActions[the_action+action_state][1];
}

function myListActionFailed(the_link) {
 if (!myActionMsgObj) {
	 var msg="Sorry, there is an issue in processing your request.";
	 myActionMsgObj = document.createElement("div");
	 myActionMsgObj.id="myActionMsg";
	 myActionMsgObj.innerHTML=msg;
	 myActionMsgObj.style.position="absolute";
	 document.body.appendChild(myActionMsgObj);
 }
 myActionMsgObj.style.top=(the_link.offsetTop - 20) + "px";
 myActionMsgObj.style.left=the_link.offsetLeft + "px";
}

//Save Search functions
var isSearchResult=0;
var callSearchFunctions=0;
var saveSearchFields = ["saveSearch","oldSearchName","memberLoggedIn","searchId","searchName","searchFrequency"];

function copySaveSearchForm(formName1, formName2) {
 var form1=document.forms[formName1];
 var form2=document.forms[formName2];
 
 if(formName1=="searchForm" && !isSearchResult) {
  var nameMsgDiv = document.getElementById("searchNameMsg_" + formName1);
  if (nameMsgDiv) {
   var nameMsg = nameMsgDiv.innerHTML;
   document.getElementById("searchNameMsg_" + formName2).innerHTML=nameMsg;
   if(nameMsg) { 
    toggleElement("saveSearchModule","block");
    toggleElement("searchNameMsg_" + formName2,"block");
   }
  }
 }
 for (var i=0; i < saveSearchFields.length; i++) {
      
	  var i_name = saveSearchFields[i];
	  var elem1 = form1.elements[i_name];
	  var elem2 = form2.elements[i_name];
	  if (!elem2 || !elem1) continue;
	  if(elem1.type=="checkbox" && elem1.checked) {
	     elem2.checked=true;
	  } else if (i_name=="searchFrequency") {
	     for(var a=0; a < elem1.length; a++ ) {
	      if(elem1[a].checked) { 
	       elem2[a].checked=true;
	      }
	     }
	  } else {
	     elem2.value=elem1.value;
	  }
	  
 }
 
}
function hideSaveSearch() {
  var form = document.forms["searchForm"];
  form.saveSearch.checked=false;
  toggleElement("saveSearchModule","none");
}
function modifyMySearch() {
 document.searchForm.modifySearch.value=1;
 // searchName only exists for logged in members
 if (document.searchForm.searchName) {
	 var searchName = document.searchForm.searchName.value;
	 if (searchName) {
	 	document.searchForm.saveSearch.value = '';
	 } else {
	 	document.searchForm.saveSearch.value = 'true';
	 }
 }
 document.searchForm.submit();
}

function submitSaveSearch(formName1, formName2) {
 if(formName1=="quickSaveSearchForm") copySaveSearchForm(formName1, formName2);
 
 if(!isSearchResult) {
 	if(validateSaveSearchForm(formName1)) {
   		setHiddenValuesSearch('searchForm');
   		document.searchForm.submit();
 	}
 } else {
  if(validateSaveSearchForm(formName1)) {
	  dojo.io.bind({
	    url: "/search/saveSearch.do",
	    method: "POST",
	    formNode: document.getElementById("searchForm"),
	    load: function(type, data, evt){ saveSearchResponse(type, data, evt, formName1) },
	    mimetype: "text/plain"
	  });
	  
   }  
 }
  return false;
}

function saveSearchResponse(type, data, evt, formName) {
 var the_obj = document.getElementById("saveMsg_" + formName);
 if(data.indexOf("SUCCESS")!=-1) {
  var quickSearchName = document.getElementById("searchName_quickSaveSearchForm");
  quickSearchName.value = "";
  var searchName = document.getElementById("searchName_searchForm");
  searchName.value = "";
  the_obj.innerHTML="<strong>Your search was saved.</strong>";
 } else {
  the_obj.innerHTML=data;
 }
 the_obj.style.display='block';
}

var searchNameError="Please enter a name for this search.";
var searchFrequencyError="Please select how often.";
function validateSaveSearchForm(formName){
 var form=document.forms[formName];
 var errors=0;
 var selected=0;
 if(form.searchName.value=="") {
   document.getElementById("searchNameMsg_" + formName).innerHTML=searchNameError;
   document.getElementById("searchNameMsg_" + formName).style.display='block';
   errors++;
 }else {
   document.getElementById("searchNameMsg_" + formName).innerHTML="";
   document.getElementById("searchNameMsg_" + formName).style.display="none";
 }
 //for(var i=0; i<form.searchFrequency.length; i++) {
 // if(form.searchFrequency[i].checked) {
  // selected++;
  //}
// }
 //if(!selected) {
  //document.getElementById("searchFrequencyMsg_" + formName).innerHTML=searchFrequencyError;
  //errors++;
 //} else {
 // document.getElementById("searchFrequencyMsg_" + formName).innerHTML="";
 //}
 if(errors) {
  return false;
 } else {
  return true;
 }
}

function nextSearchPage(pageNum, sortBy, pageSize){
 var form = document.searchForm;
 form.action=location.href;
 form.pageNumber.value=pageNum;
 if(sortBy) form.sortBy.value=sortBy;
 if(pageSize) form.pageSize.value=pageSize;
 if(form.memberLoggedIn != null && form.memberLoggedIn.value=="true") {
  form.saveSearch.checked=false;
 }
 form.submit();
}

function toggleRegionSearch() {
 if(document.searchForm.locationBasedSearch[1].checked) {
   toggleElement("proximityDistanceContainer", "block");
   toggleElement("regionContainer", "none");
 } else {
   //document.searchForm.proximityDistance.value="";
   toggleElement("proximityDistanceContainer", "none");
   toggleElement("regionContainer", "block"); 
 }
}
function toggleSearchView(isListView,pageNum){
  var form = document.searchForm;
  var loc = location.href;
  if(loc.indexOf('location')<0) {
    if(!isListView) {
      if(loc.indexOf('view=list')>0) { form.action=loc; } 
      else if(loc.indexOf('?')>0) { form.action=loc+"&view=list"; } 
      else { form.action=loc+"?view=list"; }
    } else {
      if(loc.indexOf('?view=list')>0) { form.action=loc.replace("?view=list", ""); } 
      else if(loc.indexOf('&view=list')>0) { form.action=loc.replace("&view=list", ""); } 
      else { form.action=loc; }
    }
  }
  form.listView.value=!isListView;
  if (pageNum) { form.pageNumber.value=pageNum; } 
  else { form.pageNumber.value=0; }
  form.submit();
}

/* --------------- END SEARCH --------------------------- */


/* --------------- START PHOTO MANAGER --------------------------- */


function modifySubmit(defaultChecked) {
	var div = document.getElementById("photoUploadSubmit");
	clearDiv(div);
	if (defaultChecked.checked) {
		if(document.forms['photoUploadValidatorForm'].elements['hasDefaultPhoto'].value == 'true') {
			appendConfirmation(div);
		}
	}else{
		resetSubmit();
	}
	return true;
}

function resetSubmit() {
	var div = document.getElementById("photoUploadSubmit");
	clearDiv(div);
	var updateButton = createUpdateButton();
	div.appendChild(updateButton);
	return true;
}
function clearDiv(div) {
	div.innerHTML = "";
}

function disableDefaultOption(disableDefault){
	showDefaultError(disableDefault);
}

function displayOrHidePrimaryUnderReviewText(defaultPhotoCheckBoxId, primaryPhotoReviewTextId ){
	// alert("displayOrHidePrimaryUnderReviewText(" + defaultPhotoCheckBoxId + ", " + primaryPhotoReviewTextId + ")");
	var isPrimaryChecked =  document.getElementById(defaultPhotoCheckBoxId);

	if (isPrimaryChecked != null){
		if (isPrimaryChecked.checked){
			document.getElementById(primaryPhotoReviewTextId).style.display = "block";
		}else{
			document.getElementById(primaryPhotoReviewTextId).style.display = "none";
		}
	}
}

function showDefaultError(disableDefault){

	var elSel = document.getElementsByName("defaultPhotoUpload");
	var locContainer = document.getElementById('defaultError');
	var errorTxt = "<span class='errorColor'>Your primary photo can not be premium.</font>";
	
	if (elSel.length > 0) {	
		var defaultCheckBox = elSel[0];
	}
	removeChildren(locContainer);
	
	if ( disableDefault && defaultCheckBox.checked) {
		locContainer.innerHTML = errorTxt;
		defaultCheckBox.checked = false;
	}else if (disableDefault ){
		defaultCheckBox.checked = false;
	}
	defaultCheckBox.disabled = disableDefault;
	displayOrHidePrimaryUnderReviewText('defaultPhotoUploadCheckBox', 'primaryPhotoReview');

}


function clearFields(){
	document.photoUploadValidatorForm.resetFields.click();
//	setCheckedValueRadioButton("adultPhoto");
	var div = document.getElementById("agreementError");
	clearDiv(div);
	var div2 = document.getElementById("selectPhotoError");
	clearDiv(div2);
	var div3 = document.getElementById("selectPhotoAdultError");
	clearDiv(div3);
	var div4 = document.getElementById("photoErrorSizeLimit");
	clearDiv(div4);
	
	document.photoUploadValidatorForm.defaultPhotoUpload.checked = false;
	disableDefaultOption(false);
	displayOrHidePrimaryUnderReviewText('defaultPhotoUploadCheckBox', 'primaryPhotoReview');
}

function clearField(inputField){

	var elSel = document.getElementsByName(inputField);
	
	if (elSel.length > 0) {	
		for (var i=0;i<elSel.length;i++) {
			var defaultCheckBox = elSel[i];
			var lengthE = defaultCheckBox.length; 
			if (defaultCheckBox.type == "checkbox"){
				defaultCheckBox.checked = false;
				defaultCheckBox.disabled = false;
			}else{
				defaultCheckBox.value = "";
			}
		}		
		
	}
}

function setCheckedValueRadioButton(inputField) {
	var radioObj = document.getElementsByName(inputField);

	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].value == "no") {
			radioObj[i].checked = true;
		}
	}
}

function modifyRadio(radioObj, value, select) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		if(radioObj.value == value)
			radioObj.checked = select;
			return;
	}
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].value == value) {
			return radioObj[i].checked = select;
		}
	}
	return;
}

function getValueRadioButton(inputField){
	var radioObj = document.getElementsByName(inputField);

	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].value == "yes") {
			return radioObj[i].checked;
		}
	}
}

function isRadioButtonSelected(inputField){
	var radioObj = document.getElementsByName(inputField);

	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return true;
		}
	}
	return false;
}



function checkRequiredFields() {
	var the_agreement = document.photoUploadValidatorForm.photoAgreement;
	var msg = "";
	var response = true; 
	if(!the_agreement.checked) {
	  msg = "Agreement is required";
	  document.getElementById("agreementError").innerHTML = msg;
	 	response =  false;
	}
  
	var the_photo = document.photoUploadValidatorForm.imageFile;
	if(the_photo.value == "") {
 	 	msg = "Please choose a photo.";
  	 	document.getElementById("selectPhotoError").innerHTML = msg;
  	 	response =  false;
  	 }
  	 
  	 var AdultPhotoValue = isRadioButtonSelected("adultPhoto");
  	 if(!AdultPhotoValue) {
 	 	msg = "Please make a selection.";
  	 	document.getElementById("selectPhotoAdultError").innerHTML = msg;
  	 	response =  false;
  	 }
	return response;
}

function sortByRedirect(sortByValue)
{
   var url_add = sortByValue;
   window.location.href = url_add;
}

function unlockOrLockAllPhotos(targetId, unlockOrLock, formName){
    if(!formName) {
     var form=document.forms["unlockLockAllForm"];
    } else {
     var form=document.forms[formName];
    }
	form.targetId.value = targetId;
	form.unlockOrLock.value = unlockOrLock
	form.submit();
}

function showProgress() {
	document.getElementById("progressBar").style.display = "block";
}

/* --------------- END PHOTO MANAGER --------------------------- */





/* --------------- START PRIVATE PHOTO --------------------------- */



	
	function lockPhoto(photoNumber){
		var sharedPhoto = document.getElementById("sharedPhoto_" + photoNumber);
		var divLockLink = document.getElementById("lockLink_" + photoNumber);
		var divUnLockLink = document.getElementById("unLockLink_" + photoNumber);
		var photoLockDiv = document.getElementById("photoLockDiv" + photoNumber);
		var photoUnLockDiv = document.getElementById("photoUnLockDiv" + photoNumber);
		divLockLink.style.display = "none";
		divUnLockLink.style.display = "inline";
		photoLockDiv.style.display = "block";
		photoUnLockDiv.style.display = "none";
		sharedPhoto.value = false;
		photoChanged();
	}
	
	function unLockPhoto(photoNumber){
		var sharedPhoto = document.getElementById("sharedPhoto_" + photoNumber);
		var divLockLink = document.getElementById("lockLink_" + photoNumber);
		var divUnLockLink = document.getElementById("unLockLink_" + photoNumber);
		var photoLockDiv = document.getElementById("photoLockDiv" + photoNumber);
		var photoUnLockDiv = document.getElementById("photoUnLockDiv" + photoNumber);
		divLockLink.style.display = "inline";
		divUnLockLink.style.display = "none";
		photoLockDiv.style.display = "none";
		photoUnLockDiv.style.display = "block";
		sharedPhoto.value = true;
		photoChanged();
	}
	
	function photoChanged(){
	 document.getElementById("photoPrivateChanged").value = true;
	}
	
	function lockOrUnlockLinkPhotos(totalPrivatePhotos, lockOrUnlock){
		var i=0;
 		
		for (i=0;i<totalPrivatePhotos;i++)
		{
			photoNumber = document.getElementsByName("sharedList["+i + "].picNum")[0].value;
			if (lockOrUnlock == 'unlock'){
				unLockPhoto(photoNumber);
			}else{
				lockPhoto(photoNumber);
			}
		}
	}

	function autorizePhotoChanges(){
		var photoChanged = document.getElementById("photoPrivateChanged").value;
 	
 		if (photoChanged == "false"){
 			alert("Please change something before authorize changes");
 			return;	
 		}
		
		 dojo.io.bind({
		   url: "/photos/private/share.do",
		   formNode: dojo.byId("photoShareForm"),
		   method: "POST",
		   load: function(event){closeSharePhotoWindow()},
		   error: function(event){}
		 });
	
	}
	
	function cancelPhotoChanges(){
		window.close();
	}
	
	

/* --------------- END PRIVATE PHOTO --------------------------- */



/* --------------- START OWN GALLERY --------------------------- */



var oldDiv = '';
var oldDivId = '';
var oldOnClick = '';

var edit_caption_form = null;
var edit_caption_container = null;
var edit_caption_msg=null;

var edit_private_photo_form = null;
var edit_private_photo__container = null;
var edit_private_photo_msg=null;


function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}


function html_entity_decode(str) {
  var ta=document.createElement("textarea");
  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
  return ta.value;
}

function html_entity_encode(str) {
	var div = document.createElement('div');
	var text = document.createTextNode(str);
	div.appendChild(text);
	return div.innerHTML;
}

 function showEditPhoto(photoNumber, photoClass, privatePhoto, ratingPhoto) {
	
	if(!edit_private_photo_form) {
	 edit_private_photo_form = document.editPrivatePhotoForm;
	 edit_private_photo_container = document.getElementById("editPhotoContainer");
	 edit_private_photo_msg = document.getElementById("editPhotoMsg");
	 edit_caption_msg = document.getElementById("editCaptionMsg");
	}
	
	var link_obj = document.getElementById("photo_link_" + photoNumber);
	var caption_obj = document.getElementById("caption_" + photoNumber);
	var caption = html_entity_decode(caption_obj.innerHTML);
	
	if (document.getElementById("primaryPhotoReviewHidden") != null){
		var primaryPhotoReview = document.getElementById("primaryPhotoReviewHidden").value + 
					' <a class="helpLink" onclick="openInMainWindow(\'/help.do\'); return false;" href="#"> ' +
					' Help  </a>';
	}
	
	

	edit_private_photo_form.contentArea.value=caption.replace(/^\s*|\s(?=\s)|\s*$/g, "");
	
	var coors = findPos(link_obj);	 
	
	edit_private_photo_container.style.top = coors[1]-80 + "px";
	edit_private_photo_container.style.left = coors[0]-15 + "px";
	
	edit_private_photo_container.style.display="block";
	edit_private_photo_form.photoNumber.value = photoNumber;
	edit_private_photo_form.photoClass.value = photoClass;
	edit_private_photo_form.privatePhoto.value = privatePhoto;
	edit_private_photo_form.caption.value = trimAll(caption);
	edit_private_photo_form.ratingPhoto.value = ratingPhoto;
	
	var hidePrivatePhoto = document.getElementById("setDefaultPhoto");
	var primaryPhotoReviewPhotosDiv = document.getElementById("primaryPhotoReviewPhotos");
	document.getElementById("underReviewPhotoDetail").style.display='none';
	primaryPhotoReviewPhotosDiv.style.display='none';
	primaryPhotoReviewPhotosDiv.innerHTML  = primaryPhotoReview;
	document.getElementById("photocheckboxes").checked = false
	
	hidePrivatePhoto.style.display = 'block';

	if (photoClass == 'ADULT'){
		hidePrivatePhoto.style.display = 'none';
		document.getElementById("photocheckboxes").disabled = true;
	}else{
		if (ratingPhoto == 'U' || ratingPhoto == '?'){
			if ( photoClass == 'DEFAULT' ){
				document.getElementById("underReviewPhotoDetail").style.display='block';
				document.getElementById("photocheckboxes").checked = true
				document.getElementById("photocheckboxes").disabled = true;
				primaryPhotoReviewPhotosDiv.style.display='block';
			}else{
				document.getElementById("photocheckboxes").disabled = false;
			}
				//send message
		}else{
			if (photoClass == 'DEFAULT'){
				document.getElementById("photocheckboxes").checked = true                 
				document.getElementById("photocheckboxes").disabled = true;
			}else {
				document.getElementById("photocheckboxes").disabled = false;
			}
		}

	}
	
	modifyRadio(edit_private_photo_form.privatePhotoRadio, privatePhoto, true);
  
 }

function showStateDisclaimer(id) {   

            if (id=="308") {
				
            	document.getElementById("disclaimerText").innerHTML = "I understand and acknowledge that <span class='gayComText'>gay.com</span> does not conduct criminal background checks on its members*.";
				document.getElementById("disclaimerContainer").style.display = "inline";

            } else {
            	document.getElementById("disclaimerContainer").style.display = "none";
            }
		
            
}

function showZipDisclaimer(zip) {   

            if ( +zip >= 7001 && +zip <= 8989) {
				
            	document.getElementById("disclaimerText").innerHTML = "I understand and acknowledge that <span class='gayComText'>gay.com</span> does not conduct criminal background checks on its members*.";
				document.getElementById("disclaimerContainer").style.display = "block";

            } else {
            	document.getElementById("disclaimerContainer").style.display = "none";
            }
		
            
}

function displayOrHidePrimaryUnderReviewPhotoUpdate(defaultPhotoCheckBoxId, primaryPhotoReviewTextId ){
	var isPrimaryChecked =  document.getElementById(defaultPhotoCheckBoxId);
	var ratingPhto = edit_private_photo_form.ratingPhoto.value;
	if (isPrimaryChecked != null){
		if (isPrimaryChecked.checked && (ratingPhto == 'U' || ratingPhto == '?' ) ){
			document.getElementById(primaryPhotoReviewTextId).style.display = "block";
			document.getElementById('underReviewPhotoDetail').style.display = "block";			
			
		}else{
			document.getElementById(primaryPhotoReviewTextId).style.display = "none";
			document.getElementById('underReviewPhotoDetail').style.display = "none";			
		}
	}
}
function displayEditPrivatePhoto(){
	document.write('<div class="popBlockText" id="editPhotoContainer">'
					+ '<form name="editPrivatePhotoForm" action="/photos/update.do">'
					+ '<input type="hidden" name="photoNumber" value="0"/>'
					+ '<input type="hidden" name="photoClass" value="SECONDARY"/>'
					+ '<input type="hidden" name="ratingPhoto" value="U"/>'
					+ '<input type="hidden" name="privatePhoto" value="PUBLIC"/>'
					+ '<input type="hidden" name="caption" value="dude"/>'
					+ '<div class="close"><a href="#" onclick="closeEditPrivatePhotoForm();return false;">close<img alt="close" src="/imgs/close.gif" border=0/></a></div>'
					+ '<div id="editPhotoMsg"></div> <div id="editCaptionMsg"></div>'
					+ '<div class="leftContent">'
					+ '		<p>Caption<br/>'
					+ '		<textarea onkeypress="limitContentLength(this,100) " id="contentArea" name="contentArea" cols=20 rows=5 ></textarea>'
					+ '		</p>'
					+ '		<div id="setDefaultPhoto" style="display: block;"><p>'
					+ '			<input type="checkbox" onclick="displayOrHidePrimaryUnderReviewPhotoUpdate(\'photocheckboxes\', \'primaryPhotoReviewPhotos\');" id="photocheckboxes" name="defaultPhotoCheckBox"/> Set As Primary<br/>'
					+ '			<span class="underReviewPhotoDetail" id="underReviewPhotoDetail" style="display: none;"> UNDER REVIEW </span>'
					+ '		</p></div>' 
					+ '		<div><p>' 
					+ '			<div id="primaryPhotoReviewPhotos" style="display: none;">primaryPhotoReviewPhotos</div>'
					+ '			<input type="radio" value="PRIVATE" name="privatePhotoRadio"/>  Private'
					+ '			<input type="radio" value="PUBLIC" name="privatePhotoRadio"/> Public'
					+ '		</p></div>'
					+ '	</div>'
					+ '	<div class="rightPopupButton">'
					+ '		<input type="button" value="Cancel" onclick="closeEditPrivatePhotoForm();return false;" class="prettyButton">'
					+ '		<input type="button" class="prettyButton" onclick="setPrivatePhotoBeforeSubmit();document.editPrivatePhotoForm.submit();" value="Save"/>'
					+ '	</div>'
					+ '</form>'
					+ '</div>');
}

function setCaptionBeforeSubmit(){
	 edit_caption_form.caption.value = edit_caption_form.contentArea.value;
	 return true;
}

function setPrivatePhotoBeforeSubmit(){
	var privateFlag = getCheckedRadioButton(edit_private_photo_form.privatePhotoRadio);
	
	if (edit_private_photo_form.photoClass.value != 'ADULT'){
		if (edit_private_photo_form.defaultPhotoCheckBox.checked ||
			edit_private_photo_form.photoClass.value == 'DEFAULT' ){
			edit_private_photo_form.photoClass.value = 'DEFAULT'
		}else {
			edit_private_photo_form.photoClass.value = 'SECONDARY'
		}
	}	
	edit_private_photo_form.privatePhoto.value = privateFlag;
	edit_private_photo_form.caption.value = edit_private_photo_form.contentArea.value;
}

function limitContentLength(obj,max_length) {
 var the_value=obj.value;
 if (the_value.length > max_length) {
  obj.value=the_value.substring(0,max_length);
 }
}

function closeEditCaptionForm() {
  edit_caption_msg.innerHTML="";
  edit_caption_form.contentArea.value="";
  edit_caption_form.photoNumber.value="";
  edit_caption_form.photoClass.value="";
  edit_caption_form.privatePhoto.value="";
  edit_caption_form.caption.value="";
  edit_caption_container.style.display="none";
 }


function closeEditPrivatePhotoForm() {
  edit_private_photo_msg.innerHTML="";
  edit_private_photo_form.photoNumber.value="";
  edit_private_photo_form.photoClass.value="";
  edit_private_photo_form.privatePhoto.value="";
  edit_private_photo_form.caption.value="";
  edit_private_photo_container.style.display="none";
  edit_private_photo_form.defaultPhotoCheckBox.checked = false;
 }

function selectAll(){
	changeCheckBoxState(true);
}

function unSelectAll(){
	changeCheckBoxState(false);
}

function removeSelected(confirmMessage){
	var elSel = document.getElementsByName("selectPhoto");
	var photosNumberSelected = "";
	
	if (elSel.length > 0) {	
		for (var i=0;i<elSel.length;i++) {
			var defaultCheckBox = elSel[i];
			
			if (defaultCheckBox.checked){
				if (photosNumberSelected == ""){
					photosNumberSelected = defaultCheckBox.id;
				}else{
						photosNumberSelected =  photosNumberSelected + "," + defaultCheckBox.id;
				}
				
			}	
		}
		if (photosNumberSelected != ""){
			document.photoDeleteForm.photosNumberString.value = photosNumberSelected;
			document.photoDeleteForm.submit();
		}else{
			alert("Select a photo to delete");
		}
	}
	
}

function modifyRadio(radioObj, value, select) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		if(radioObj.value == value)
			radioObj.checked = select;
			return;
	}
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].value == value) {
			return radioObj[i].checked = select;
		}
	}
	return;
}


function getCheckedRadioButton(radioObj) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
			return;
	}
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked == true) {
			return radioObj[i].value;
		}
	}
	return;
}

function changeCheckBoxState(checked){

	var elSel = document.getElementsByName("selectPhoto");
		
	if (elSel.length > 0) {	
		for (var i=0;i<elSel.length;i++) {
			var defaultCheckBox = elSel[i];
			defaultCheckBox.checked = checked;	
		}
	}
}

function changeCheckBoxState(checked){

	var elSel = document.getElementsByName("selectPhoto");
		
	if (elSel.length > 0) {	
		for (var i=0;i<elSel.length;i++) {
			var defaultCheckBox = elSel[i];
			defaultCheckBox.checked = checked;	
		}
	}
}

function trimAll(sString)
{
	while (sString.substring(0,1) == ' ')
	{
	sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
	sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

function summarize(str, lngth) {
	if (!str || str.length <= lngth) {
		return str;
	}
	var truncated = str.substr(0, lngth);
	// search back to the last space
	if (truncated.lastIndexOf(" ") > 0) {
		truncated = truncated.substr(0, truncated.lastIndexOf(" "));
	}
	return truncated + "...";
}
function truncToChars(str, lngth) {
	if (!str || lngth < 3 || str.length <= lngth) {
		return str;
	}
	var truncated = str.substr(0, lngth - 2) + "...";
	return truncated;
}

/* --------------- END OWN GALLERY --------------------------- */




/* --------------- START HOMEPAGE FEATURE SWITCH --------------------------- */

function toggleHomeFeature(featureType) {	
	if (featureType == "thumbnails") {
		if (document.getElementById('featuredMemberBoxTitle').className == 'featuredMemberBoxTitleOver') {
			document.getElementById('featuredMemberBoxTitle').className = 'featuredMemberBoxTitleOff';
			document.getElementById('digitalMediaTitle').className = 'digitalMediaTitleOver';
			document.getElementById('digitalMedia_panel_one').style.display = 'block';	
			document.getElementById('featuredMemberHighlight').style.display = 'none';
		} else {
			document.getElementById('featuredMemberBoxTitle').className = 'featuredMemberBoxTitleOver';	
			document.getElementById('digitalMediaTitle').className = 'digitalMediaTitleOff';
			document.getElementById('featuredMemberHighlight').style.display = 'block';	
			document.getElementById('digitalMedia_panel_one').style.display = 'none';
			pausePlayDigitalMediaSlideshow(true);
		}
	} else if (featureType == "digitalMedia") {
		if (document.getElementById('digitalMediaTitle').className == 'digitalMediaTitleOver') {
			document.getElementById('featuredMemberBoxTitle').className = 'featuredMemberBoxTitleOver';	
			document.getElementById('digitalMediaTitle').className = 'digitalMediaTitleOff';
			document.getElementById('featuredMemberHighlight').style.display = 'block';	
			document.getElementById('digitalMedia_panel_one').style.display = 'none';
			pausePlayDigitalMediaSlideshow(true);		
		} else {
			document.getElementById('featuredMemberBoxTitle').className = 'featuredMemberBoxTitleOff';
			document.getElementById('digitalMediaTitle').className = 'digitalMediaTitleOver';
			document.getElementById('digitalMedia_panel_one').style.display = 'block';	
			document.getElementById('featuredMemberHighlight').style.display = 'none';
		}
	} else {	
		document.getElementById('featuredMemberBoxTitle').className = 'featuredMemberBoxTitleOff';
		document.getElementById('digitalMediaTitle').className = 'digitalMediaTitleOver';
		document.getElementById('digitalMedia_panel_one').style.display = 'block';	
		document.getElementById('featuredMemberHighlight').style.display = 'none';
	}
}

function toggleHomeThumbnail(featureType) {
	if (featureType == "thumbnailsThumbs") {
		document.getElementById('featuredMemberHighlight').style.display = 'block';	
		document.getElementById('digitalMedia_panel_one').style.display = 'none';
		document.getElementById('featuredMemberBoxTitle').className = 'featuredMemberBoxTitleOver';
		document.getElementById('digitalMediaTitle').className = 'digitalMediaTitleOff';
		pausePlayDigitalMediaSlideshow(true)	
	} else if (featureType == "digitalMediaThumbs") {
		document.getElementById('digitalMedia_panel_one').style.display = 'block';	
		document.getElementById('featuredMemberHighlight').style.display = 'none';
		document.getElementById('featuredMemberBoxTitle').className = 'featuredMemberBoxTitleOff';
		document.getElementById('digitalMediaTitle').className = 'digitalMediaTitleOver';
	} else {
		document.getElementById('digitalMedia_panel_one').style.display = 'block';	
		document.getElementById('featuredMemberHighlight').style.display = 'none';
		document.getElementById('featuredMemberBoxTitle').className = 'featuredMemberBoxTitleOff';
		document.getElementById('digitalMediaTitle').className = 'digitalMediaTitleOver';		
	}
}


	
/* --------------- END HOMEPAGE FEATURE SWITCH --------------------------- */


function toggleSection(id, obj) {
 var theStatus = toggleElement(id);
 if(!theStatus) {
 	obj.className = "smallArrow";
 } else {
 	obj.className = "smallArrow on";
 }
}

/* --------------- START SELECT BOX NAVIGATION --------------------------- */
function selectBoxNavigation(id) {
 var box = $(id);
 var destination = box.options[box.selectedIndex].value;
 if (destination) {
  window.location.href = destination;
 }
}
/* --------------- END SELECT BOX NAVIGATION --------------------------- */


/* --------------- START PRE-LOADED STRETCH-BUTTONS --------------------------- */

pic2=new Image(183,21);
pic2.src="/imgs/css/input-text-bg.gif";
/*pic3=new Image(500,21);
pic3.src="/imgs/css/btn-cancel-blue.gif";
pic4=new Image(500,21);
pic4.src="/imgs/css/btn-cancel-blue-over.gif";
*/
/* --------------- END PRE-LOADED STRETCH-BUTTONS --------------------------- */

/* --------------- POP-UNDER WINDOW --------------------------- */
function puBlackListCheck() {
	var popUnderBlackList = new Array(
		/* Domain Root(i.e. home page) blacklisted on server
		 * Edit additional blacklisted paths here */
		'/home',
		'/members/join',
		'/members/subscribe',
		'/tboy/redeem',
		'/login'
	);
	var check = true;
	var loc = new String(window.location.pathname);
	var i = 0;
	popUnderBlackList.iterate(function() {
			if (loc.indexOf(popUnderBlackList[i]) != -1) {
				check = false;
			}
			i++;
		}
	)
	return check;
}

function loadPopUnder(section){
	var puUrl = "/ads/popUnder.do?section=" + (section ? section : "");
	var puFeatures = "width=700,height=300,scrollbars=0,resizable=0,toolbar=0,location=0,menubar=0,status=0,directories=0";
	var puWin = window.open(puUrl,"puWin",puFeatures);
	puWin.blur();
	window.focus();
}

function firePopUnder(section) {
	if (getCookie('popunder') != 'yes' && puBlackListCheck()) {
		loadPopUnder(section);
		document.cookie="popunder=yes; path=/";
	}
}
/* --------------- END POP-UNDER WINDOW --------------------------- */

/* --------------- START SET CURSOR POSITION IN TEXT FIELD -------- */

function setTextFieldCursor(formName, fieldName) {
	var textField = document.forms[formName].elements[fieldName];
	textField.select();
}

/* --------------- END START SET CURSOR POSITION IN TEXT FIELD ---- */

function openVideoPlayer(vid) {
	// alert('OPEN ' + vid);
	if(vid < 0) return;
	var f = getFieldsFromURL();
	// alert('NAVPATH IS ' + navpath);
	var u = "/media/videoPlayer.do?r=" + vid;
	if(f["navpath"]) u += "&navpath=" + f["navpath"];
	var n = "pWin";
	var f = "height=615,width=750,resizable,scrollbars=false";
	previewWindow = open(u, n, f);
	if(previewWindow == null || previewWindow.closed) {
		alert("A popup blocker has prevented the video player from opening.");
	} else {
		previewWindow.focus();	
	}
}

function getFieldsFromURL() {
	var r = new Array();
	var defNP = "/channels/entertainment";
	var q = document.location.search;
	if(q.indexOf('?') == 0) q = q.substring(1);
	if(!q) q = "";
	// alert('Q IS ' + q);
	var qPairs = q.split('&');
	for(var aPair in qPairs) {
		var pBits = qPairs[aPair].split('=');
		// alert('aPair IS ' + qPairs[aPair]);
		if(pBits.length == 2 && pBits[0].toLowerCase() == 'navpath') {
			r["navpath"] = pBits[1];
		}
		if(r["navpath"]) break; 
	} 
	if(!r["navpath"]) r["navpath"] = defNP; 
	return r;
}

function openHelpCenter(url) {
	var helpWin = window.open(url, 'mainHelpWindow','width=860,height=640,location=no,menubar=no,toolbar=no,scrollbars=yes');
	helpWin.focus();
}
function pageLoadedInIE() {
	setTimeout("operationWillAbort = false;", 100);
}
function closeMessengerOnSignout() {
	setConfirmCloseStatus(1);
	if(isMsgrWinOpen()) {
		getMessengerWindow().confirmUnload = false;
		getMessengerWindow().close();
	}
}
if(isIE) dojo.addOnLoad(pageLoadedInIE);

// Check for 1x1(default fallback ad)
// Change class if no 1x1 is found
function checkAd(id, newClass) {
	if ($(id) && $(id).innerHTML.search('ads.pno.net/images/1x1') == -1)
		$(id).className = newClass;
}
// Check for 1x1(default fallback ad) in id
// Change class of banner to newClass if no 1x1 is found in id
function checkAdBanner(id, banner, newClass) {
	if ($(id) && $(id).innerHTML.search('ads.pno.net/images/1x1') == -1 && $(banner))
		$(banner).className = newClass;
}

function openHelpCenterEMN(url) {
	var helpWin = window.open(url, 'mainHelpWindow','width=750,height=400,location=no,menubar=no,toolbar=no,scrollbars=yes');
	helpWin.focus();
}

function editReviewLinksQuery(type) {
    var form = document.forms['submitPaymentForm'];

    var newOfferValues = new Array();
    for (var i=0; i<form.length;i++) {
      if (form[i].type == 'checkbox') {
        var name = form[i].name;
        if (name.search('offer-') != -1) {
            var nq = ''; 
            nq += form[i].name;
            nq += form[i].checked?"=on":"=off";
            newOfferValues.push(nq);
        }
      }     
    }
    
    if (type != 'payment') {   
        var links = ['editplan-link', 
                        'editpayment-link'];
    } else {
        var links = ['editplan-link'];
    }
    var i = 0;
    links.iterate(function (){
        var q = '';
	    //Validate qeury
   	    var qa = $(links[i]).href.split('?');
		if (qa[1] != "redir=PREMIUM")
		  qa[1] = '';
          q += '?' + qa[1] + newOfferValues.join("&");
          $(links[i]).href = qa[0] + q;
          i++;
        }
    )
}
function moveHPPromoScroller() {
	var ns = document.getElementById("hpPromoBox").nowShowing;
	if(!ns) ns = 1;
	ns++;
	if(ns > 3) ns = 1;
	document.getElementById("hpPromoBox").nowShowing = ns;
	document.getElementById("promo1").className = "inactivePromo";
	document.getElementById("promo2").className = "inactivePromo";
	document.getElementById("promo3").className = "inactivePromo";
	document.getElementById("promo" + ns).className = "activePromo";
	document.getElementById("promoLink1").style.display  = "none";
	document.getElementById("promoLink2").style.display = "none";
	document.getElementById("promoLink3").style.display = "none";
	document.getElementById("promoLink" + ns).style.display = "block";
	setTimeout("moveHPPromoScroller();", 3000);
}




// VIEW PAGE SEGMENT SLIDER
function trimPx(x) {
	if(x.indexOf("px") < 0) return x * 1;
	else return 1 * (x.substring(0, x.indexOf("px")));
}

function scrollSliderSegmentRight(section) {
	var d1 = document.getElementById(section + "-1");
	var d2 = document.getElementById(section + "-2");
	var d3 = document.getElementById(section + "-3");
	if(d3 != null) {
		if(trimPx(d1.style.left) == 675) { 
			// cant nudge anymore left
			d1.style.left = "675px";
			d2.style.left = "1350px";
			d3.style.left = "0px";
			nudgeSliderSegmentLeft(section, 50, 0);
		} else if(trimPx(d1.style.left) == 0)	{ // pos 2  
			d1.style.left = "0px";
			d2.style.left = "675px";
			d3.style.left = "1350px";
			nudgeSliderSegmentLeft(section, 50, -675);
		} else  { 
			d1.style.left = "-675px";
			d2.style.left = "0px";
			d3.style.left = "675px";
			nudgeSliderSegmentLeft(section, 50, -1350);
		}
	} else if(d2 != null) {
		if(trimPx(d1.style.left) == 0) { 
			// cant nudge anymore left
			d1.style.left = "0px";
			d2.style.left = "675px";
			nudgeSliderSegmentLeft(section, 50, -675);
		} else  { 
			d1.style.left = "675px";
			d2.style.left = "0px";
			nudgeSliderSegmentLeft(section, 50, 0);
		}
	}
}
function nudgeSliderSegmentLeft(section, nudgeAmount, edge) {
	if(document.getElementById(section + "-1")) document.getElementById(section + "-1").style.left = (trimPx(document.getElementById(section + "-1").style.left) - nudgeAmount) + "px";
	if(document.getElementById(section + "-2")) document.getElementById(section + "-2").style.left = (trimPx(document.getElementById(section + "-2").style.left) - nudgeAmount) + "px";
	if(document.getElementById(section + "-3")) document.getElementById(section + "-3").style.left = (trimPx(document.getElementById(section + "-3").style.left) - nudgeAmount) + "px";
	if(trimPx(document.getElementById(section + "-1").style.left) <= edge) {
		document.getElementById(section + "-1").style.left = edge + "px";
		if(edge == 0) {	// POS 1
			document.getElementById(section + "-1").style.left = "0px";
			if(document.getElementById(section + "-2")) document.getElementById(section + "-2").style.left = "675px";
			if(document.getElementById(section + "-3")) document.getElementById(section + "-3").style.left = "-675px";
		} else if(edge == -675) {	// POS 2
			document.getElementById(section + "-1").style.left = "-675px";
			if(document.getElementById(section + "-2")) document.getElementById(section + "-2").style.left = "0px";
			if(document.getElementById(section + "-3")) document.getElementById(section + "-3").style.left = "675px";
		} else { // POS 3
			document.getElementById(section + "-1").style.left = "675px";
			if(document.getElementById(section + "-2")) document.getElementById(section + "-2").style.left = "-675px";
			if(document.getElementById(section + "-3")) document.getElementById(section + "-3").style.left = "0px";
		}
	} else {
		setTimeout("nudgeSliderSegmentLeft('" + section + "', " + nudgeAmount + ", " + edge + ");", 20);
	}
}
function scrollSliderSegmentLeft(section) {
	var d1 = document.getElementById(section + "-1");
	var d2 = document.getElementById(section + "-2");
	var d3 = document.getElementById(section + "-3");
	if(d3 != null) {
		if(trimPx(d1.style.left) == 0) {
			d1.style.left = "0px";
			d2.style.left = "675px";
			d3.style.left = "-675px";
			nudgeSliderSegmentRight(section, 50, 675);
		} else if(trimPx(d1.style.left) == 675) {	// // pos FAR MIDDLE TO FAR RIGHT 
			d1.style.left = "675px";
			d2.style.left = "-675px";
			d3.style.left = "0px";
			nudgeSliderSegmentRight(section, 50, 1350);
		} else  { 
			d1.style.left = "-675px";
			d2.style.left = "0px";
			d3.style.left = "675px";
			nudgeSliderSegmentRight(section, 50, 0);
		}
	} else if(d2 != null){
		if(trimPx(d1.style.left) == 0) { 
			// cant nudge anymore left
			d1.style.left = "0px";
			d2.style.left = "-675px";
			nudgeSliderSegmentRight(section, 50, 675);
		} else  { 
			d1.style.left = "-675px";
			d2.style.left = "0px";
			nudgeSliderSegmentRight(section, 50, 0);
		}
	}
}
function nudgeSliderSegmentRight(section, nudgeAmount, edge) {
	document.getElementById(section + "-1").style.left = (trimPx(document.getElementById(section + "-1").style.left) + nudgeAmount) + "px";
	if(document.getElementById(section + "-2")) document.getElementById(section + "-2").style.left = (trimPx(document.getElementById(section + "-2").style.left) + nudgeAmount) + "px";
	if(document.getElementById(section + "-3")) document.getElementById(section + "-3").style.left = (trimPx(document.getElementById(section + "-3").style.left) + nudgeAmount) + "px";
	if(trimPx(document.getElementById(section + "-1").style.left) >= edge) {
		document.getElementById(section + "-1").style.left = edge + "px";
		if(edge == 0) {	// POS 1
			document.getElementById(section + "-1").style.left = "0px";
			if(document.getElementById(section + "-2")) document.getElementById(section + "-2").style.left = "675px";
			if(document.getElementById(section + "-3")) document.getElementById(section + "-3").style.left = "-675px";
		} else if(edge == -675) {	// POS 2
			document.getElementById(section + "-1").style.left = "-675px";
			if(document.getElementById(section + "-2")) document.getElementById(section + "-2").style.left = "0px";
			if(document.getElementById(section + "-3")) document.getElementById(section + "-3").style.left = "675px";
		} else if(edge == 675) {	// POS 2
			document.getElementById(section + "-1").style.left = "675px";
			if(document.getElementById(section + "-2")) document.getElementById(section + "-2").style.left = "-675px";
			if(document.getElementById(section + "-3")) document.getElementById(section + "-3").style.left = "0px";
			else document.getElementById(section + "-2").style.left = "0px";
		} else { // POS 3
			document.getElementById(section + "-1").style.left = "-675px";
			if(document.getElementById(section + "-2")) document.getElementById(section + "-2").style.left = "0px";
			if(document.getElementById(section + "-3")) document.getElementById(section + "-3").style.left = "675px";
		}
	} else {
		setTimeout("nudgeSliderSegmentRight('" + section + "', " + nudgeAmount + ", " + edge + ");", 20);
	}
}

function findPosition(domelement) {
	var curleft = 0; 
	var curtop = 0;
	if(domelement.offsetParent) {
		do {
			curleft += domelement.offsetLeft;
			curtop += domelement.offsetTop;
		} while(domelement = domelement.offsetParent);
	}
	return [curleft, curtop];
}
function getWindowSize() {
	var w = 0;
	var h = 0;
	//IE
	if(!window.innerWidth)
	{
		//strict mode
		if(!(document.documentElement.clientWidth == 0))
		{
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		}
		//quirks mode
		else
		{
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		}
	}
	//w3c
	else
	{
		w = window.innerWidth;
		h = window.innerHeight;
	}
	return {width:w,height:h,scrollTop:document.body.scrollTop,scrollLeft:document.body.scrollLeft};
}
function getPageSize() {
	var w = 0;
	var h = 0;
	return {width:document.body.offsetWidth,height:document.body.offsetHeight,scrollTop:document.body.scrollTop,scrollLeft:document.body.scrollLeft};
}
function toggleLightsOnVideo(vdiv) { 
	var aboveBox = document.getElementById("dimAbove");
	if(aboveBox && aboveBox.style.display == "block") {
		undimLightsOnVideo(vdiv)
	} else {
		dimLightsOnVideo(vdiv)
	}

}
function undimLightsOnVideo(vdiv) { 
	document.getElementById("dimAbove").style.display = "none";
	document.getElementById("dimBelow").style.display = "none";
	document.getElementById("dimLeft").style.display = "none";
	document.getElementById("dimRight").style.display = "none";
}
function dimLightsOnVideo(vdiv) {
	var vdivel = document.getElementById(vdiv);
	var posArr = findPosition(vdivel);
	var topPos = posArr[1];
	var leftPos = posArr[0];
	var w = vdivel.offsetWidth;
	var h = vdivel.offsetHeight;
	var ws = getWindowSize(); // 
	var ps = getPageSize(); // 
	if(ps["height"] > ws["height"]) ws["height"] = ps["height"];
	if(ps["width"] > ws["width"]) ws["width"] = ps["width"];
	var aboveBox = document.getElementById("dimAbove");
	if(!aboveBox) {
		aboveBox = document.createElement("div");
		aboveBox.id = "dimAbove";
		document.body.appendChild(aboveBox);
		aboveBox.style.display = "none";
		aboveBox.className = 'dimLightBox';
		aboveBox.onmousedown = function(evt) {toggleLightsOnVideo('premiumUpgradeBox');};
	}
	// alert("ABOVE BOX GOES FROM: (0, 0) to " + ws["width"] + ', ' + topPos);
	aboveBox.style.left = "0px";
	aboveBox.style.top = "0px";
	aboveBox.style.width = ws["width"] + "px";
	aboveBox.style.height = topPos + "px";
	aboveBox.style.display = "block";
	
	var belowBox = document.getElementById("dimBelow");
	if(!belowBox) {
		belowBox = document.createElement("div");
		belowBox.id = "dimBelow";
		document.body.appendChild(belowBox);
		belowBox.style.display = "none";
		belowBox.className = 'dimLightBox';
		belowBox.onmousedown = function(evt) {toggleLightsOnVideo('premiumUpgradeBox');};
	}
	// alert("BELOW BOX GOES FROM: (0, " + (topPos + h) + ", " + ws['width'] + ", " + ws['height']);
	belowBox.style.left = "0px";
	belowBox.style.top = (topPos + h) + "px";
	belowBox.style.width = ws["width"] + "px";
	belowBox.style.height = (ws['height'] - h - topPos) + "px";
	belowBox.style.display = "block";

	var leftBox = document.getElementById("dimLeft");
	if(!leftBox) {
		leftBox = document.createElement("div");
		leftBox.id = "dimLeft";
		document.body.appendChild(leftBox);
		leftBox.style.display = "none";
		leftBox.className = 'dimLightBox';
		leftBox.onmousedown = function(evt) {toggleLightsOnVideo('premiumUpgradeBox');};
	}
	leftBox.style.left = "0px";
	leftBox.style.width = leftPos + "px";
	leftBox.style.top = topPos + "px";
	leftBox.style.height = h + "px";
	leftBox.style.display = "block";
	
	var rightBox = document.getElementById("dimRight");
	if(!rightBox) {
		rightBox = document.createElement("div");
		rightBox.id = "dimRight";
		document.body.appendChild(rightBox);
		rightBox.style.display = "none";
		rightBox.className = 'dimLightBox';
		rightBox.onmousedown = function(evt) {toggleLightsOnVideo('premiumUpgradeBox');};
	}
	rightBox.style.left = (leftPos + w) + "px";
	rightBox.style.width = ( ws["width"] - (leftPos + w) ) + "px";
	rightBox.style.top = topPos + "px";
	rightBox.style.height = h + "px";
	rightBox.style.display = "block";
}
function showEmbedVideoCode(ptvid) {
	var objstr = '<object height="360" width="480" type="application/x-shockwave-flash" ' 
				+ 'data="http://devkit.permissiontv.com/Preloader.swf" id="flashContent" ' 
				+ 'style="visibility: visible;"><param name="allowFullScreen" value="true"/>' 
				+ '<param name="movie" value="http://devkit.permissiontv.com/Preloader.swf"/>'
				+ '<param name="AllowScriptAccess" value="always"/><param name="flashvars" ' 
				+ 'value="applicationSwf=' + freeApplicationSwfUrl 
				+ '&amp;licenseKey=c1eb7735-b29d-4b09-afa5-94b60bacb659&amp;channelID=' + freeChannelId + '&amp;environment=live' 
				+ '&amp;login=http://services.permissiontv.com/v2.2/auth/login.xml' 
				+ '&amp;services=http://services.permissiontv.com/v2.2/services.xml' 
				+ '&amp;CID=' + ptvid + '&amp;PID=' + freePlayerId + '"/>'
				+ '</object>'
	var vdivel = document.getElementById("viewVideoBox");
	var posArr = findPosition(vdivel);
	var topPos = posArr[1];
	var leftPos = posArr[0];
	var w = vdivel.offsetWidth;
	var h = vdivel.offsetHeight;
	var embedBox = document.getElementById("embedBox");
	if(!embedBox) {
		embedBox = document.createElement("div");
		embedBox.id = "embedBox";
		embedBox.className = "embedBox";
		embedBox.style.top = (topPos + 25) + "px";
		embedBox.style.left = (leftPos + 25 ) + "px";
		embedBox.style.width = ( w - 50) + "px";
		embedBox.style.height = (h - 50) + "px";
		var embedBoxBG = document.createElement("div");
		embedBoxBG.id = "embedBoxBG";
		embedBoxBG.className = "embedBoxBG";
		embedBoxBG.style.top = topPos + "px";
		embedBoxBG.style.left = leftPos + "px";
		embedBoxBG.style.width = w + "px";
		embedBoxBG.style.height = h + "px";
		document.body.appendChild(embedBoxBG);
		document.body.appendChild(embedBox);
	}
	embedBox.style.display = "block";
	document.getElementById("embedBoxBG").style.display = "block";
	embedBox.innerHTML = "";
	embedBox.innerHTML = "<div class='closeEmbedBox' onmousedown='document.getElementById(\"embedBox\").style.display=\"none\";document.getElementById(\"embedBoxBG\").style.display=\"none\";'>[X]</div><div class='embedHeading'>Embed Video</div><br/><div><textarea onmousedown='this.focus();this.select()' onclick='this.focus();this.select()' class='embedBoxArea'>" + objstr + "</textarea></div>";
}
function showEmbedVideoDisabled() {
	var vdivel = document.getElementById("viewVideoBox");
	var posArr = findPosition(vdivel);
	var topPos = posArr[1];
	var leftPos = posArr[0];
	var w = vdivel.offsetWidth;
	var h = vdivel.offsetHeight;
	var embedBox = document.getElementById("embedBox");
	if(!embedBox) {
		embedBox = document.createElement("div");
		embedBox.id = "embedBox";
		embedBox.className = "embedBox";
		embedBox.style.top = (topPos + 25) + "px";
		embedBox.style.left = (leftPos + 25 ) + "px";
		embedBox.style.width = ( w - 50) + "px";
		embedBox.style.height = (h - 50) + "px";
		var embedBoxBG = document.createElement("div");
		embedBoxBG.id = "embedBoxBG";
		embedBoxBG.className = "embedBoxBG";
		embedBoxBG.style.top = topPos + "px";
		embedBoxBG.style.left = leftPos + "px";
		embedBoxBG.style.width = w + "px";
		embedBoxBG.style.height = h + "px";
		document.body.appendChild(embedBoxBG);
		document.body.appendChild(embedBox);
	}
	embedBox.style.display = "block";
	document.getElementById("embedBoxBG").style.display = "block";
	embedBox.innerHTML = "";
	embedBox.innerHTML = "<div class='closeEmbedBox' onmousedown='document.getElementById(\"embedBox\").style.display=\"none\";document.getElementById(\"embedBoxBG\").style.display=\"none\";'>[X]</div><br clear='right'/><br clear='right'/><div>Embedding of premium videos is not allowed.</div>";
}
function showQuickSearch() {
	document.getElementById("quickSearchModule").style.display = "block";
}
function hideQuickSearch() {
	document.getElementById("quickSearchModule").style.display = "none";
}
function showMemberNameSearch() {
	showQuickSearch();
	setTextFieldCursor('memberNameSearchForm', 'memberName', 0);
}
function centerImages() {
	 var d;
	 if(document.getElementById("imgs_publicPhoto")) {
	 	d = document.getElementById("imgs_publicPhoto");
	 	for(var a =0; a < d.childNodes.length; a++) {
	 		if(d.childNodes[a].className != "onePhotoDiv") continue;
	 		var img = d.childNodes[a].getElementsByTagName("img")[0];
	 		img.style.marginTop = ((90 - img.offsetHeight) / 2) + "px";
	 	}
	 }
	 if(document.getElementById("imgs_privatePhoto")) {
	 	d = document.getElementById("imgs_privatePhoto");
	 	for(var a =0; a < d.childNodes.length; a++) {
	 		if(d.childNodes[a].className != "onePhotoDiv") continue;
	 		var img = d.childNodes[a].getElementsByTagName("img")[0];
	 		img.style.marginTop = ((90 - img.offsetHeight) / 2) + "px";
	 	}
	 }
	 if(document.getElementById("imgs_publicAdultPhotos")) {
	 	d = document.getElementById("imgs_publicAdultPhotos");
	 	for(var a =0; a < d.childNodes.length; a++) {
	 		if(d.childNodes[a].className != "onePhotoDiv") continue;
	 		var img = d.childNodes[a].getElementsByTagName("img")[0];
	 		img.style.marginTop = ((90 - img.offsetHeight) / 2) + "px";
	 	}
	 }
	 if(document.getElementById("imgs_privateAdultPhotos")) {
	 	d = document.getElementById("imgs_privateAdultPhotos");
	 	for(var a =0; a < d.childNodes.length; a++) {
	 		if(d.childNodes[a].className != "onePhotoDiv") continue;
	 		var img = d.childNodes[a].getElementsByTagName("img")[0];
	 		img.style.marginTop = ((90 - img.offsetHeight) / 2) + "px";
	 	}
	 }
}
window.chatIsAllowedToOpen = true;
function chatNotBlocked() { 
	if(window.chatIsAllowedToOpen) return true;
	else return false;
}
function blockChatOpening() {
	window.chatIsAllowedToOpen = false;
	setTimeout("window.chatIsAllowedToOpen = true", 2000);
}

var tickerParams = new Object();
tickerParams.tickPixels = 1;
tickerParams.tickFrequency = 30;
tickerParams.scrollHeadline1 = true;
tickerParams.scrollHeadline2 = false;
tickerParams.pauseTicking = false;
tickerParams.spaceBetweenEnds = 5;

tickerParams.tickCount = 0;
function scrollHeadlineTicker() {
	if(tickerParams.pauseTicking) {
		setTimeout("scrollHeadlineTicker()", 250);
		return;
	}
	// tickerParams.tickCount++;
	// if(tickerParams.tickCount > 35) tickerParams.tickCount = 0;
	var scroller1 = document.getElementById("headlineScroller1");
	var scroller2 = document.getElementById("headlineScroller2");
	var newPos1 = 0;
	var newPos2 = 0;
	if(tickerParams.scrollHeadline1) {
		newPos1 = trimPx(scroller1.style.left);
		if(!tickerParams.scrollHeadline2 && newPos1 + scroller1.offsetWidth < 900) {
			tickerParams.scrollHeadline2 = true;
			scroller2.style.left = (newPos1 + scroller1.offsetWidth + tickerParams.spaceBetweenEnds) + "px";
			scroller2.style.display = 'block';
		}
		if(newPos1 < (-1 * scroller1.offsetWidth) + 150) {
			newPos1 = 900;
			tickerParams.scrollHeadline1 = false;
			scroller1.style.display = 'none';
		} else {
			newPos1 -= tickerParams.tickPixels;
		}
		scroller1.style.left = newPos1 + "px";
	}
	if(tickerParams.scrollHeadline2) {
		newPos2 = trimPx(scroller2.style.left);
		if(!tickerParams.scrollHeadline1 && newPos2 + scroller2.offsetWidth < 900) {
			tickerParams.scrollHeadline1 = true;
			scroller1.style.left = (newPos2 + scroller2.offsetWidth + tickerParams.spaceBetweenEnds) + "px";
			scroller1.style.display = 'block';
		}
		if(newPos2 < (-1 * scroller2.offsetWidth) + 150) {
			newPos2 = 900;
			tickerParams.scrollHeadline2 = false;
			scroller2.style.display = 'none';
		} else {
			newPos2 -= tickerParams.tickPixels;
		}
		scroller2.style.left = newPos2 + "px";
	}
	// if(tickerParams.tickCount == 0) alert("NEWPOS 1 : 2 = " + newPos1 + " : " + newPos2);
	setTimeout("scrollHeadlineTicker()", tickerParams.tickFrequency);
}

function focusDbUsername(uField) {
	uField.className = "dbUsername noBg";
}
function focusDbPassword(pField) {
	pField.className = "dbPassword noBg";
}
function focusHpUsername(uField) {
	uField.className = "hpUsername noBg";
}
function focusHpPassword(pField) {
	pField.className = "hpPassword noBg";
}
function focusWhitePassword(pField) {
	pField.className = "whitePassword noBg";
}
function blurDBUserAndPwd() {
	var uField = $('dbUsername');
	if(uField.value == "") uField.className = "dbUsername";
	else uField.className = "dbUsername noBg";
	
	var pField = $('dbPassword');
	if(pField.value == "") pField.className = "dbPassword";
	else pField.className = "dbPassword noBg";
}
function blurHPUserAndPwd() {
	var uField = $('hpUsername');
	if(uField.value == "") uField.className = "hpUsername";
	else uField.className = "hpUsername noBg";

	var pField = $('hpPassword');
	if(pField.value == "") pField.className = "hpPassword";
	else pField.className = "hpPassword noBg";
}
function blurWhitePwd() {
	var pField = $('whitePassword');
	if(pField.value == "") pField.className = "whitePassword";
	else pField.className = "whitePassword noBg";
}
