//cookies

/**
 * Returns the current value of the named cookie
 */
function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');

	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while ( c.charAt(0) == ' ' )
		    c = c.substring(1, c.length);

		if (c.indexOf(nameEQ) == 0)
		    return c.substring(nameEQ.length,c.length);
	}

	return null;
}

/**
 * Creates a cookie with the given parameters
 */
function setCookie(name, value, days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}


/**
 * Deletes the cookie with the given name
 */
function deleteCookie( name ) {
	setCookie(name,"",-1);
}

/**
 * Session cookies, cookies that expire after the browser is closed
 */
function setSessionCookie(NameOfCookie, value) {

	//Obtain the real domain (e.g., aarp.org, aarp.net)
	var myDomain = document.domain;
	var lastDotIndex = myDomain.lastIndexOf('.');
	var nextLastDotIndex = myDomain.substr(0, lastDotIndex).lastIndexOf('.');
	var realDomain = myDomain.substr(nextLastDotIndex + 1);

	document.cookie = NameOfCookie + "=" + escape(value) + "; path=/; domain=."+ realDomain +"; ";
}

function readSessionCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

if(!readSessionCookie("onsite")) {
	setSessionCookie("onsite", "true");
}

//BOLT settings
// STORED SETTINGS
var SETTINGS_COOKIE = 'bolt_settings';
var SETTINGS_COOKIE_LIFE = 3650;

// setting constants
var SETTING_SHOW_VITALS             = 0;
var SETTING_SHOW_BACKGROUND         = 1;
var SETTING_SHOW_PERMA_CODES        = 2;
var SETTING_SHOW_NO_CONTENT_MESSAGE = 3;


function getSetting(index) {
    var settingsCookie  = getCookie(SETTINGS_COOKIE);

    if(settingsCookie != null) {
        var settings        = settingsCookie.split(":");
        return settings[index];
    }

    return '';
}

function storeSetting(index, value) {
    var settingsCookie  = getCookie(SETTINGS_COOKIE);
    if(settingsCookie == null) {
        settingsCookie = '';
    }
    
    var settings        = settingsCookie.split(":");

    // build new settings cookie
    settings[index] = value;
    var newSettingsCookie = settings.join(":");
    setCookie(SETTINGS_COOKIE, newSettingsCookie, SETTINGS_COOKIE_LIFE);
}

/*function initSettings(size) {
	var settingsCookie 	= getCookie(SETTINGS_COOKIE);
    var settings = new Array(size);
    var i;

	// initialize the cookie
	if((settingsCookie != null) && (settingsCookie.length > 0)) {
	    // initialize with old settings + empty ones
	  	var currentSettings	= settingsCookie.split(":");

	  	var newSize = (currentSettings.length > size) ? currentSettings.length : size;
        settings = new Array(newSize);

	  	// copy old settings into array
	  	for(i=0; i < currentSettings.length; i++) {
	  	    settings[i] = currentSettings[i];
	  	}

	    // add new entries
        for(i=currentSettings.length; i < newSize; i++) {
            settings[i] = 'on';
        }
	}
    else {
        // initialize with all empty entries
        for(i=0; i < size; i++) {
            settings[i] = 'on';
        }
    }

    // create new cookie string
    var newCookieString = "";
    for(i = 0; i < size; i++) {
        newCookieString += settings[i] + ":";
    }

    // remove trailing colon
    if(newCookieString.length > 0) {
        newCookieString = newCookieString.substring(0, newCookieString.length - 1);
    }
    
    setCookie(SETTINGS_COOKIE, newCookieString, SETTINGS_COOKIE_LIFE);
}*/

//for collapsible divs on profile pages
function setDiv(id) {

    cookieValue = getCookie(id);
	
    if (cookieValue == 'closed') {
		setCookie(id, 'closed');
		swapCollapse(id + 'Icon');
    } else {
		setCookie(id, 'open');
		Effect.toggle(id, 'blind', {duration: 0.2});
    }

}

function divToggle(id) {

    cookieValue = getCookie(id);

    if (cookieValue == 'open') {
		setCookie(id, 'closed');
    } else if (cookieValue == 'closed') {
		setCookie(id, 'open');
    } else {
		setCookie(id, 'open');
    }

    Effect.toggle(id, 'blind', {duration: 0.2});

}

//open and close collapsible divs on profile pages
function setCollapsibleDivs() {
	var boxIds = new Array("slideMyBookmarks", "slideMyComments", "slideMyScores", "slideMyCourses");
	for (i = 0; i < boxIds.length; i++) {
		if (boxIds[i]) {
			setDiv(boxIds[i]);
		}
	}
}

function goToUrl(url) {
    window.location = url;
}

//selects all content in input/textarea when input/textarea is clicked
function clickSelectAll(id) {
    document.getElementById(id).focus();
    document.getElementById(id).select();
}

//show and hide elements
function swapDisplay(id) {
	
	el = document.getElementById(id);
	if (el.style.display == 'block') {
		el.style.display = 'none';
	} else if (el.style.display == 'none') {
		el.style.display = 'block';
	}
	
}

function swapVisibility(id) {
	
	el = document.getElementById(id);
	if (el.style.visibility == 'visible') {
		el.style.visibility = 'hidden';
	} else if (el.style.visibility == 'hidden') {
		el.style.visibility = 'visible';
	}
	
}

function changeHeight(id, height) {
	
	el = document.getElementById(id);
	el.style.height = height;
	
}

//arrow changer for drop-downs
function swapArrow(arrow_id) {
    if (document.getElementById('arrow' + arrow_id).src == "http://assets.aarp.org/aarp.org_/images/icons/arrow_right.gif") {
        document.getElementById('arrow' + arrow_id).src = "http://assets.aarp.org/aarp.org_/images/icons/arrow_down.gif"
    } else if (document.getElementById('arrow' + arrow_id).src == "http://assets.aarp.org/aarp.org_/images/icons/arrow_down.gif") {
        document.getElementById('arrow' + arrow_id).src = "http://assets.aarp.org/aarp.org_/images/icons/arrow_right.gif"
    }
}

function swapCollapse(collapse_id) {
	
	//get file name (can't rely on full URL)
	var url = document[collapse_id].src;
	var end = (url.indexOf("?") == -1) ? url.length : url.indexOf("?");
	var file_name = url.substring(url.lastIndexOf("/")+1, end);

    if (file_name == "12icon_expand.gif") {
        document[collapse_id].src = "http://assets.aarp.org/aarp.org_/images/icons/12icon_collapse.gif"
    } else if (file_name == "12icon_collapse.gif") {
        document[collapse_id].src = "http://assets.aarp.org/aarp.org_/images/icons/12icon_expand.gif"
    }
	
}

//"edit in place" code (for inline editing)
Event.observe(window, 'load', init, false);

function init() {
    // changing it up for now.
    if ($('titleTextareaDiv')) {
        // get the descendants
        var editableDescendants = $('titleTextareaDiv').descendants();

        var editableElementIdRegExp = /(\D+)(\d+)(\D+)/;
        var editableElementArray = editableElementIdRegExp.exec(editableDescendants[0].id);

        if (editableElementArray != null) {
            var titleChangeDiv = 'titleTextarea' + editableElementArray[2] + editableElementArray[3];
            var descriptionChangeDiv = 'descriptionTextarea' + editableElementArray[2] + editableElementArray[3];
        }

        if ($(titleChangeDiv)) {
            makeEditable(titleChangeDiv);
        }
        if ($(descriptionChangeDiv)) {
            makeEditable(descriptionChangeDiv);
        }
    }
}

function makeEditable(id) {
	Event.observe(id, 'click', function(){edit($(id))}, false);
	Event.observe(id, 'mouseover', function(){showAsEditable($(id))}, false);
	Event.observe(id, 'mouseout', function(){showAsEditable($(id), true)}, false);
}

function edit(obj) {
	Element.hide(obj);
	
	//if title field is being edited, format title textarea
	var div_check = obj.id.search('titleTextarea');
	if (div_check != -1) {
		var textareaClass = 'mediaItemTitleEdit';
	}
	
	//if description field is being edited, format description textarea
	var div_check = obj.id.search('descriptionTextarea');
	if (div_check != -1) {
		var textareaClass = 'mediaItemDescEdit';
	}
		
	var textarea = '<div id="'+obj.id+'_editor"><textarea id="'+obj.id+'_edit" name="'+obj.id+'" class="'+textareaClass+'">'+obj.innerHTML+'</textarea>';
	var button   = '<div><input id="'+obj.id+'_save" type="button" value="Save" /> <input id="'+obj.id+'_cancel" type="button" value="Cancel" /></div></div>';
	new Insertion.After(obj, textarea+button);	

	Event.observe(obj.id+'_save', 'click', function(){saveChanges(obj)}, false);
	Event.observe(obj.id+'_cancel', 'click', function(){cleanUp(obj)}, false);
}

function showAsEditable(obj, clear) {
	if (!clear){
		Element.addClassName(obj, 'editable');
	} else {
		Element.removeClassName(obj, 'editable');
	}
}

function saveChanges(obj) {

    var new_content = escape($F(obj.id + '_edit'));

    // break up the id of the object so we can go ahead and have the right variables.
    var idRegExp = /(\D+)(\d+)(\D+)/;
    var idArray = idRegExp.exec(obj.id);


    var success = function(t) {
        editComplete(t, obj);
    }
    var failure = function(t) {
        editFailed(t, obj);
    }

    //submit title form if title has been changed
    //if description field is bing edited, format description inputs
    var div_check = obj.id.search('titleTextarea');

    if (div_check != -1) {

        if (new_content == '') {
            cleanUp(obj);
            var errorText = '<B id="' + obj.id + '_error" style="color:red">Title must not be empty!</B>';
            new Insertion.After(obj, errorText);
            return false;
        } 
else if (new_content.length > 255){
	
	 cleanUp(obj);
        var errorText = '<B id="' + obj.id + '_error" style="color:red">Title must not be over 255 characters!</B>';
        new Insertion.After(obj, errorText);
        return false;
	
	}else {
            obj.innerHTML = "Saving...";
            cleanUp(obj, true);
            var url = '/community/' + idArray[3] + '/title/edit.bt';
            var pars = idArray[3] + 'Id=' + idArray[2] + '&' + idArray[1] + '=' + new_content;
            var myAjax = new Ajax.Request(url, {method:'post', postBody:pars, onSuccess:success, onFailure:failure});

        }
    }

     //submit description form if description has been changed
    var div_check = obj.id.search('descriptionTextarea');
    if (div_check != -1) {

        if ((new_content == '') || (unescape(new_content) == 'Click here to add a description.')) {
            cleanUp(obj);
            return false;
        } else {
            obj.innerHTML = "Saving...";
            cleanUp(obj, true);
            var url = '/community/' + idArray[3] + '/description/newEdit.bt';
            var pars = idArray[3] + 'Id=' + idArray[2] + '&' + idArray[1] + '=' + new_content;
            var myAjax = new Ajax.Request(url, {method:'post', postBody:pars, onSuccess:success, onFailure:failure});
        }
    }

}

function cleanUp(obj, keepEditable) {
    if ($(obj.id + '_editor')) {
        Element.remove(obj.id + '_editor');
    }
    if ($(obj.id + '_error')) {
        Element.remove(obj.id + '_error');
    }
    Element.show(obj);
    if (!keepEditable) showAsEditable(obj, true);
}

function editComplete(t, obj) {
    obj.replace(t.responseText);
	//reset
    makeEditable(obj.id);
    //showAsEditable(obj, true);
}

function editFailed(t, obj) {
    obj.innerHTML = 'Sorry, the update failed.';
    cleanUp(obj);
}

//from the old profile_scripts.js
function removeFromContacts() {

    var checkBoxes = document.getElementsByName("selectContact");
    var urlToSubmit = '/community/contacts/dropContact.bt?';
    var checkedCount = 0;
    for (var i = 0; i < checkBoxes.length; i++)
    {
        if (checkBoxes[i].checked == true)
        {
            checkedCount = checkedCount + 1;
            if (checkedCount == 1)
            {
                urlToSubmit = urlToSubmit + "contactsToRemove=" + checkBoxes[i].value;
            }
            else
            {
                urlToSubmit = urlToSubmit + "&contactsToRemove=" + checkBoxes[i].value;
            }
        }
    }

    if (checkedCount != 0)
    {
        window.location.replace(urlToSubmit);
    }
}

function removeFromPendingContacts() {

    var checkBoxes = document.getElementsByName("selectPendingContact");
    var urlToSubmit = '/community/contacts/dropContact.bt?';
    var checkedCount = 0;
    for (var i = 0; i < checkBoxes.length; i++)
    {
        if (checkBoxes[i].checked == true)
        {
            checkedCount = checkedCount + 1;
            if (checkedCount == 1)
            {
                urlToSubmit = urlToSubmit + "contactsToRemove=" + checkBoxes[i].value;
            }
            else
            {
                urlToSubmit = urlToSubmit + "&contactsToRemove=" + checkBoxes[i].value;
            }
        }
    }

    if (checkedCount != 0)
    {
        window.location.replace(urlToSubmit);
    }
}

function loginToWAM(loginToWamURL){
//    alert(loginToWamURL+"?referrer="+window.location.href);
    
    window.location.replace(loginToWamURL+"?referrer="+encodeURIComponent(window.location.href));
}

function showConfirmationDialogOnDelete(delId) {
    var checkBoxes = document.getElementsByName("selectContact");
    var checkedCount = 0;
    for (var i = 0; i < checkBoxes.length; i++)
    {
        if (checkBoxes[i].checked == true)
        {
            checkedCount = checkedCount + 1;
        }
    }
    if (checkedCount != 0)
    {
        
        document.getElementById(delId).style.display = 'block';
    }
}
function hideConfirmationDialogOnDelete(delId) {
    document.getElementById(delId).style.display = 'none';
}
function insertAd(number) {
    document.write('<' + 'script language="JavaScript" type="text/javascript"' + '>');
    document.write('ord=Math.random()*10000000000000000;');
    document.write('</scr' + 'ipt>');
    document.write('<' + 'script language="JavaScript" src="http://ad.doubleclick.net/adj/bolt.dart/spotlight;tile=' + number + ';tout=spot' + number + ';sz=300x202;ord=' + ord + '?" type="text/javascript">');
    document.write('<' + '/script><noscript' + '><a href="http://ad.doubleclick.net/jump/bolt.dart/spotlight;tile=' + number + ';tout=spot' + number + ';sz=300x202;ord=123456789?" target="_blank"><img src="http://ad.doubleclick.net/ad/bolt.dart/spotlight;tile=' + number + ';tout=spot' + number + ';sz=300x202;ord=123456789?" width="300" height="202" border="0" alt=""></a></noscript' + '>');
}
function previewTestimonial() {
    form = document.getElementById('testimonialForm');
    form.action = "/community/profile/previewTestimonial.bt";
    form.submit();
}
function showDeleteConfirmation(theId) {
    document.getElementById("deleteButton" + theId).style.display = 'none';
    document.getElementById("deleteConfirmationFormDiv" + theId).style.display = 'block';
}
function submitDeleteForm(tId) {
    form = document.getElementById("deleteForm" + tId);
    form.submit();
}
function showDeleteForm(tId) {
    document.getElementById("deleteConfirmationFormDiv" + tId).style.display = 'none';
    document.getElementById("deleteButton" + tId).style.display = '';
}
function showForm(tId) {
    document.getElementById("formDiv" + tId).style.display = 'none';
    document.getElementById("button" + tId).style.display = '';
}
// function makeContact (memName) {
function makeContact(memName) {
    temp = window.confirm("Add " + memName + " as contact?");
    //temp = window.confirm("Add as contact?");
    if (temp == true) {
        form = document.getElementById("makeContactForm");
        form.submit();
    }
}
/* GENERIC FUNCTIONS */
function showDiv(tId) {
    document.getElementById(tId).style.display = 'block';
}
function hideDiv(tId) {
    document.getElementById(tId).style.display = 'none';
}
function showConfirmation(tId) { // when you click the "x" button or the "make contact" button for example
    document.getElementById("link" + tId).style.display = 'none';
    document.getElementById("confirmationDiv" + tId).style.display = 'block';
}
function showConfirmation2(str, tId) { // when you click the "x" button or the "make contact" button for example
    document.getElementById("link" + str + tId).style.display = 'none';
    document.getElementById("confirmationDiv" + str + tId).style.display = 'block';
}
function showConfirmationFormAndDiv(tId) { // when you click the "x" button or the "make contact" button for example
    document.getElementById("link" + tId).style.display = 'none';
    document.getElementById("form" + tId).style.display = 'block';
    document.getElementById("confirmationDiv" + tId).style.display = 'block';
}
function hideFollowUpNote(tId) { // when you click ok button on the follow-up note (e.g. "an email will be sent to this person")
    document.getElementById("followUpNoteDiv" + tId).style.display = 'none';
}
function submitForm(tId) { // when you click submit button
    form = document.getElementById("form" + tId);
    form.submit();
}
function submitForm2(str, tId) { // when you click submit button
    form = document.getElementById("form" + str + tId);
    form.submit();
}
function submitFormAndUnhideFollowUpNoteIfFriendRequest(tId) { // when you click submit button
    var inputNodes = document.getElementsByTagName("input");
    //alert("inputNodes = " + inputNodes);
    for (var idx = 0; idx < inputNodes.length; idx++) {
        var curNode = inputNodes[idx];
        if ((curNode.name == "relType") && (curNode.value == "friend") && (curNode.checked == true)) {
            document.getElementById("followUpNoteDiv" + tId).style.display = '';
        }
        /*
        alert ("curNode = " + curNode);
        alert ("curNode.name = " + curNode.name);
        alert ("curNode.value = " + curNode.value);
        alert ("curNode.checked = " + curNode.checked);
        */
    }
    form = document.getElementById("form" + tId);
    form.submit();
}
function hideConfirmation(tId) { // when you click cancel button
    document.getElementById("form" + tId).style.display = 'none';
    document.getElementById("confirmationDiv" + tId).style.display = 'none';
    document.getElementById("link" + tId).style.display = '';
}
function hideConfirmation2(str, tId) { // when you click cancel button
    document.getElementById("form" + str + tId).style.display = 'none';
    document.getElementById("confirmationDiv" + str + tId).style.display = 'none';
    document.getElementById("link" + str + tId).style.display = '';
}
/* FEEDS */
function loadFeedContent(feedUrl, encodedUrl) {
    url = '/community/profile/feeds/loadFeedContent.bt?feedUrl=' + feedUrl;
    BXmlHttp.quickRequest(url,
            function(responseText) {
                var titleDiv = document.getElementById("feedTitle" + encodedUrl);
                titleDiv.innerHTML = parseFeedTitleHTML(responseText);
                var entriesDiv = document.getElementById("feedEntries" + encodedUrl);
                entriesDiv.innerHTML = parseFeedEntriesHTML(responseText);
            }
            );
}
function parseFeedTitleHTML(responseText) {
    var startIndex = responseText.indexOf('BOLTINCPROFILEFEEDTITLE:');
    var endIndex = startIndex + 'BOLTINCPROFILEFEEDTITLE:'.length;
    var endHTMLIndex = responseText.indexOf('BOLTINCPROFILEFEEDENTRIES:') - 1;
    var titleHTML = responseText.substring(endIndex + 1, endHTMLIndex);
    return titleHTML;
}
function parseFeedEntriesHTML(responseText) {
    var startIndex = responseText.indexOf('BOLTINCPROFILEFEEDENTRIES:');
    var endIndex = startIndex + 'BOLTINCPROFILEFEEDENTRIES:'.length;
    var entriesHTML = responseText.substring(endIndex, responseText.length - 1);
    return entriesHTML;
}
/* Relationships */
//function loadFriendContent(friendUrl, encodedUrl) {
function loadContactContent(friendUrl, divName) {
    //url = '/community/profile/feeds/loadFeedContent.bt?feedUrl='+friendUrl;

    //alert ("loadContactContent: friendUrl = " + friendUrl);
    //divName = "friendsDiv"
    //if (friendOrContact == "contact") {
    //    divName = "contactsDiv";
    //}
    //alert ("loadContactContent: divName = " + divName);
    url = friendUrl;
    BXmlHttp.quickRequest(url,
            function(responseText) {
                var contactsDiv = document.getElementById(divName);
                //alert ("responseText = " + responseText);
                contactsDiv.innerHTML = responseText;
                //var entriesDiv = document.getElementById("feedEntries"+encodedUrl);
                //entriesDiv.innerHTML = parseFeedEntriesHTML(responseText);
            }
            );
}

function openAddContentToGroup(contentId) {
	Effect.Appear('addContentToGroupOverlay' + contentId);
}

function closeAddContentToGroup(contentId) {
	Effect.Squish('addContentToGroupOverlay' + contentId);
}

var currentAddContentToGroupLinkId = null;

function sendAddContentToGroup(contentId,groupId) {
    sendAddContentToGroupFromMyContent("/community/groups/addGroupToContent.bt?contentId="+contentId+"&groupId="+groupId);
    currentAddContentToGroupLinkId = contentId;
}

function sendAddContentToGroupFromMyContent(url) {
	if (window.XMLHttpRequest) { // Non-IE browsers
		req = new XMLHttpRequest();
		req.onreadystatechange = addContentToGroupFromMyContentUpdate;
		try {
			req.open("GET", url, true);
		} catch (e) {
			alert(e);
		}
		req.send(null);

	} else if (window.ActiveXObject) { // IE
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			req.onreadystatechange = addContentToGroupFromMyContentUpdate;
			req.open("GET", url, true);
			req.send();
		}
	}
}

function addContentToGroupFromMyContentUpdate(){
   if (req.readyState == 4) { // Complete
		if (req.status == 200) { // OK response
            // remove link
            var linkElement = document.getElementById('addContentToGroupLink' + currentAddContentToGroupLinkId);
            linkElement.parentNode.removeChild(linkElement);
            var divElement = document.getElementById('addContentToGroupOverlay' + currentAddContentToGroupLinkId);
            divElement.parentNode.removeChild(divElement);
		} else {
			alert("Problem: " + req.statusText);
		}
	}
}

function paneSwitch(requestedPane) {
	var correctUrl = "/community/profile/update" + requestedPane + ".bt?method=view" + requestedPane + "Pane";
	var req = new Ajax.Updater('settingsPane', correctUrl);
}

function submitSettingsUpdate(settingArea) {
	var correctUrl = "/community/profile/update" + settingArea + ".bt?method=update" + settingArea;
	var formValues = $(settingArea + 'Form').serialize(); 
	var req = new Ajax.Updater("settingsPane", correctUrl, {method: 'post', parameters: formValues} );
}

//Snapfish overlay
function openSnapfish_AARP_Overlay() {
	overlayUI();

	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','snapfishAARP_Overlay');
	objOverlay.style.display = 'none';

	$$('body')[0].appendChild(objOverlay);
	$('snapfishAARP_Overlay').update($('snapfish_AARP_OverlayContents').innerHTML);

	$('snapfishAARP_Overlay').show();
}

//new registration overlay (from old new_registration.js)
function openNewReg() {
	overlayUI();

	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','newRegOverlay');
	objOverlay.style.display = 'none';

	var objOverlayForm = document.createElement('form');
	objOverlayForm.setAttribute('id', 'ProfileFormOverlay1');
	objOverlayForm.setAttribute('enctype', 'multipart/form-data');
	objOverlayForm.setAttribute('encoding', 'multipart/form-data');
	objOverlayForm.setAttribute('method', 'post');
	objOverlayForm.setAttribute('action', '/community/profile/performOverlayAjax1.bt');

	$$('body')[0].appendChild(objOverlay);
	$('newRegOverlay').appendChild(objOverlayForm);
	$('ProfileFormOverlay1').onsubmit = function() { submitProfileOverlay(); return false; };
	$('ProfileFormOverlay1').update($('newRegOverlayContents').innerHTML);

	$("newRegOverlay").show();
}

function submitProfileOverlay() {
	var errorFlag = 0;
	var citySpecial = 0;
	var maxLength = 2000;
	var errorString = 'Error(s):<br>';
	
	if ( $('ProfileFormOverlay1').snapshotFile.value == '' && $('ProfileFormOverlay1').schools.value == '' && 
	$('ProfileFormOverlay1').companies.value == '' && $('ProfileFormOverlay1').hometowns.value == '') {
		new Effect.Fade("newRegOverlay");
		closeOverlayUI();
		return false; 
	}

	if($('ProfileFormOverlay1').snapshotFile.value.length > 0 &&
	($('ProfileFormOverlay1').snapshotFile.value.lastIndexOf('.jpg')==-1) &&
	($('ProfileFormOverlay1').snapshotFile.value.lastIndexOf('.gif')==-1) &&
	($('ProfileFormOverlay1').snapshotFile.value.lastIndexOf('.pjpg')==-1) &&
	($('ProfileFormOverlay1').snapshotFile.value.lastIndexOf('.bmp')==-1)) {
		errorFlag = 1;
		errorString = errorString + '&nbsp;&nbsp;&nbsp;The image must be of type jpg, bmp, or gif<br>';
	}

    if ($('ProfileFormOverlay1').schools.value.length > maxLength) {
        errorFlag = 1;
        errorString = errorString + '&nbsp;&nbsp;&nbsp;The education field must be below '+maxLength+' characters<br>';
    }
    
    if ($('ProfileFormOverlay1').companies.value.length > maxLength) {
        errorFlag = 1;
        errorString = errorString + '&nbsp;&nbsp;&nbsp;The employment field must be below '+maxLength+' characters<br>';
    }

    if ($('ProfileFormOverlay1').hometowns.value.length > maxLength) {
        errorFlag = 1;
        errorString = errorString + '&nbsp;&nbsp;&nbsp;The hometowns field must be below '+maxLength+' characters<br>';
    }

	if (errorFlag == 1) {
		Effect.Shake('newRegOverlay');
		$('newRegOverlayErrors').update(errorString);
		return false;
	}
	else {
		$('ProfileFormOverlay1').submit();
	}
}

function offnewRegOverlayWait() {
	$('newRegOverlayWait').hide();
}

function showOverlayResponse1(originalRequest) {
	var gotBack = originalRequest.responseText;
	if (gotBack.match(/overlaysuccess/)) {
		$('leftProfileBox').update(gotBack);
		
		$('newRegOverlay').hide();
		$('newRegOverlay').remove();

		var objOverlay = document.createElement("div");
		objOverlay.setAttribute('id','newRegOverlay');
		objOverlay.style.display = 'none';

		var objOverlayForm = document.createElement('form');
		objOverlayForm.setAttribute('id', 'ProfileFormOverlay2');
		objOverlayForm.setAttribute('enctype', 'multipart/form-data');
		objOverlayForm.setAttribute("encoding","multipart/form-data");
		objOverlayForm.setAttribute('method', 'post');
		objOverlayForm.setAttribute('action', '/community/profile/performOverlayAjax2.bt');

		$$('body')[0].appendChild(objOverlay);
		$('newRegOverlay').appendChild(objOverlayForm);
		$('ProfileFormOverlay2').onsubmit = function() { submitProfileOverlay2(); return false; };
		$('ProfileFormOverlay2').update($('newRegOverlay2').innerHTML);

		$("newRegOverlay").show();
	} else {
		setTimeout("offnewRegOverlayWait()", 2000);
		setTimeout("Effect.Squish('newRegOverlay')", 2000);
		closeOverlayUI();
	}
}


function submitProfileOverlay2() {
	var errorFlag = 0;
    var maxLength = 2000;
    var errorString = 'Error(s):<br>';

	if ( $('ProfileFormOverlay2').snapshotFile.value == '' && $('ProfileFormOverlay2').bio.value == '' && $('ProfileFormOverlay2').schools.value == '' && 
	$('ProfileFormOverlay2').companies.value == '' && $('ProfileFormOverlay2').hometowns.value == '' && $('ProfileFormOverlay2').quote.value == '' ) {
		new Effect.Fade("newRegOverlay");
		closeOverlayUI();
		return false; 
	}

	if($('ProfileFormOverlay2').snapshotFile.value.length > 0 &&
	($('ProfileFormOverlay2').snapshotFile.value.lastIndexOf('.jpg')==-1) &&
	($('ProfileFormOverlay2').snapshotFile.value.lastIndexOf('.gif')==-1) &&
	($('ProfileFormOverlay2').snapshotFile.value.lastIndexOf('.pjpg')==-1) &&
	($('ProfileFormOverlay2').snapshotFile.value.lastIndexOf('.bmp')==-1)) {
		errorFlag = 1;
		errorString = errorString + '&nbsp;&nbsp;&nbsp;The image must be of type jpg, bmp, or gif<br>';
	}

    if ($('ProfileFormOverlay2').bio.value.length > maxLength) {
        errorFlag = 1;
        errorString = errorString + '&nbsp;&nbsp;&nbsp;The bio must be below '+maxLength+' characters<br>';
    }

    if ($('ProfileFormOverlay2').schools.value.length > maxLength) {
        errorFlag = 1;
        errorString = errorString + '&nbsp;&nbsp;&nbsp;The education field must be below '+maxLength+' characters<br>';
    }
    
    if ($('ProfileFormOverlay2').companies.value.length > maxLength) {
        errorFlag = 1;
        errorString = errorString + '&nbsp;&nbsp;&nbsp;The employment field must be below '+maxLength+' characters<br>';
    }

    if ($('ProfileFormOverlay2').hometowns.value.length > maxLength) {
        errorFlag = 1;
        errorString = errorString + '&nbsp;&nbsp;&nbsp;The hometowns field must be below '+maxLength+' characters<br>';
    }

    if ($('ProfileFormOverlay2').quote.value.length > maxLength) {
        errorFlag = 1;
        errorString = errorString + '&nbsp;&nbsp;&nbsp;The interests field must be below '+maxLength+' characters<br>';
    }

	if (errorFlag == 1) {
		Effect.Shake('newRegOverlay2');
		$('newRegOverlay2Errors').update(errorString);
		return false;
	}
	else {
		$('ProfileFormOverlay2').submit();
	}
}

/*
function showOverlayResponse2(originalRequest) {
	var gotBack = originalRequest.responseText;
    if (gotBack.match(/overlaysuccess/)) {
        offnewRegOverlayWait();
        Effect.Puff('newRegOverlay2');
	}
	else {
        alert('no match');
        $('myProfileSpan').update(gotBack)
		setTimeout("offnewRegOverlayWait()", 2000);
		setTimeout("Effect.Squish('newRegOverlay')", 2000);
	}
}

*/

//about me overlay
function turnOffInfoMessage(obj) {
	var status = 'off';
	var index = SETTING_SHOW_NO_CONTENT_MESSAGE;

	document.getElementById('profileMessage').style.display = 'none';
	storeSetting(index, status);
}
function displayInfoMessage(obj) {
	var status = 'off';
	var index = SETTING_SHOW_NO_CONTENT_MESSAGE;

	document.getElementById('profileMessage').style.display = 'none';
	storeSetting(index, status);
}

//group forums
function VerifyForm() {
	if (isWhitespace(document.messageboard_createTopicForm.body.value) || isWhitespace(document.messageboard_createTopicForm.topicTitle.value))
	{
		alert("Oops, you have to enter a subject and a topic in order to post!");
		return false;
	} else {
		return true;
	}
}

function isWhitespace(str) {
	var whitespace = " \t\n\r"

	if ((str == null) || (str.length == 0))
		return true

	for (j = 0; j < str.length; j++)
	{
		var c = str.charAt(j);
		if (whitespace.indexOf(c) == -1)
			return false
	}
	return true
}

//bookmarks
function deleteBookmark(itemTypeId, itemId) {
	var delBookmarkURL = "/community/content/favorite/remove.bt?itemTypeId="+itemTypeId+"&itemId="+itemId;
	//var req = new Ajax.Updater("colMR", delBookmarkURL);
	var ajaxResponse = new Ajax.Request(delBookmarkURL);
	location.reload();
}

function deleteGameBookmark(token, title) {
	delGameURL = "/community/games/deleteBookmark.action?token=" + token + "&bookmark=" + title;
	var ajaxResponse = new Ajax.Request(delGameURL);
	location.reload();
}

//message center
function loadReplyForm(noteId) {
    url = '/community/notes/createNote.bt?r=' + noteId;
    goToUrl(url);
}
function loadSaveNote(noteId) {
    url = '/community/notes/saveNote.bt?i=' + noteId;
    goToUrl(url);
}
function loadForwardNote(noteId) {
    url = '/community/notes/forwardNote.bt?i=' + noteId;
    goToUrl(url);
}
function loadDeleteNote(noteId) {
    url = '/community/notes/deleteNote.bt?i=' + noteId;
    goToUrl(url);
}
function deleteSelectedNotes() {
	// if no notes selected, do not delete
	var checkboxes = document.getElementsByName('noteIds');
	var oneChecked = false;
	for (var i = 0; i < checkboxes.length; i++) {
		if (checkboxes[i].checked == true)
			oneChecked = true;
	}

	if (oneChecked == false)
		return false;

    theForm = document.getElementById('moveNotesForm');
    theForm.action = "/community/notes/deleteNotes.bt";
    theForm.submit();
}
function saveSelectedNotes() {
    theForm = document.getElementById('moveNotesForm');
    theForm.submit();
}
function moveSelectedNotesToInbox() {
    theForm = document.getElementById('moveNotesForm');
    theForm.action = "/community/notes/moveNotesToInbox.bt"
    theForm.submit();
}
function loadMoveNoteToInbox(noteId) {
    url = '/community/notes/moveNoteToInbox.bt?i=' + noteId;
    goToUrl(url);
}
function addMemberToSendToField() {
    to = document.getElementById('noteToField');
    oldTo = to.value;
    importSelect = document.getElementById('memberSelect');
    newMember = importSelect.value;
    if (oldTo == '') {
        to.value = newMember;
    }
    else {
        to.value = oldTo + ', ' + newMember;
    }
}
function previewNote() {
    //from form
    var body = document.getElementById('createNoteFormBody');
    var replacedBody = replaceAll(body.value, "\n", "<br />");
    var bodyText = '<div class="contentSpacer"><!-- spacer --></div><h3 class="noteHeading">Preview</h3><div class="previewDivContent"><div class="previewDivContentPad">' + replacedBody + '<div style="width:100%;text-align:right"><a href="#" onclick="javacript:previewNoteClose();return false;">close</a></div></div>';
    // new node to be added
    var previewTextNode = document.createTextNode(bodyText);
    // replace or append
    var previewDiv = document.getElementById('previewDiv');
    // old node in div
    previewDiv.innerHTML = bodyText;
}
// when the cancel button is hit
function cancelNote() {
    // go to the inbox
    var inboxUrl = '/community/notes/inbox.bt';
    goToUrl(inboxUrl);
}
function previewNoteClose() {
    var previewDiv = document.getElementById('previewDiv');
    previewDiv.innerHTML = '';
}

function decideFriendships(answer){
	
	var checkedItems = enableAcceptRejectButtons(); 

	if (checkedItems) {
	
	  $('acceptOrDenyForm').acceptOrReject.value= answer;
	
	  $('acceptOrDenyForm').submit();
	}
	
}

function enableAcceptRejectButtons() {

    var checkBoxes = document.getElementsByName("memberIds");
    var checkedCount = 0;
    var enable=false;
    for (var i = 0; i < checkBoxes.length; i++)
    {

        if (checkBoxes[i].checked == true)
        {
            checkedCount = checkedCount + 1;
        }
    }
    if (checkedCount != 0)
    {
          enable=true ;
    }

    return enable;
}
function delegateCheckboxes(thisObj, objName) {
    if (thisObj.checked) {
        checkAllCheckboxesWithName(objName);
    }
    else uncheckAllCheckboxesWithName(objName);
}
function delegateAllCheckboxes(thisObj, objName) {
    if (thisObj.checked) {
        checkAllCheckboxes();
    }
    else uncheckAllCheckboxes();
}
function checkAllCheckboxesWithName(objName) {
    var cb = document.getElementsByName(objName);
    for (var i = 0; i < cb.length; i++) {
        cb[i].checked = true;
    }
}
function checkAllCheckboxes() {
    var cb = document.getElementsByTagName('input');
    for (var i = 0; i < cb.length; i++) {
        if (cb[i].getAttribute('type') == 'checkbox')
            cb[i].checked = true;
    }
}
function uncheckAllCheckboxesWithName(objName) {
    var cb = document.getElementsByName(objName);
    for (var i = 0; i < cb.length; i++) {
        cb[i].checked = false;
    }
}
function uncheckAllCheckboxes() {
    var cb = document.getElementsByTagName('input');
    for (var i = 0; i < cb.length; i++) {
        if (cb[i].getAttribute('type') == 'checkbox')
            cb[i].checked = false;
    }
}

function openDeleteNote() {
	Effect.Appear('deleteOverlay');
}

function closeDeleteNote() {
	Effect.Squish('deleteOverlay');
}

function preprocessRemove() {
	var checkBoxes = document.getElementsByName("selectPendingContact");
	var checkedCount = 0;
	for (var i = 0; i < checkBoxes.length; i++) {
		if (checkBoxes[i].checked == true) {
			checkedCount = checkedCount + 1;
		}
	}
	if (checkedCount == 0) {
		closeOverlayConfirmation();
	} else {
		removeFromPendingContacts();
	}
}

function preprocessRemoveFriend() {
	var checkBoxes = document.getElementsByName("selectContact");
	var checkedCount = 0;
	for (var i = 0; i < checkBoxes.length; i++) {
		if (checkBoxes[i].checked == true) {
			checkedCount = checkedCount + 1;
		}
	}
	if (checkedCount == 0) {
		closeOverlayConfirmation();
	} else {
		removeFromContacts();
	}
}

function preprocessRemoveNotes() {
	var checkBoxes = document.getElementsByName("noteIds");
	var checkedCount = 0;
	for (var i = 0; i < checkBoxes.length; i++) {
		if (checkBoxes[i].checked == true) {
			checkedCount = checkedCount + 1;
		}
	}
	if (checkedCount == 0) {
		closeOverlayConfirmation();
	} else {
		deleteSelectedNotes();
	}
}

function quitGroup(groupId) {
	var urlToSubmit = '/community/groups/quitGroup.bt?groupId='+groupId;
	window.location.replace(urlToSubmit);
}

function joinGroup(groupId, invite) {
	var urlToSubmit = '/community/groups/joinGroup.bt?groupId='+groupId+'&invitedToGroup='+invite+'&redirectUrl='+document.location.href;
	window.location.replace(urlToSubmit);
}

//flag/remove user overlay
 function openFlagUserOverlayDialog() {
	overlayUI();

	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','flagUserOverlayDialog');
	objOverlay.style.display = 'none';

	var objOverlayForm = document.createElement('form');
	objOverlayForm.setAttribute('id', 'formFlagUser');
	objOverlayForm.setAttribute('method', 'post');
	objOverlayForm.setAttribute('action', '/community/profile/flagMember.bt');

	$$('body')[0].appendChild(objOverlay);
	$('flagUserOverlayDialog').appendChild(objOverlayForm);
	$('formFlagUser').onsubmit = function() { flagMember(); return false; };
	$('formFlagUser').update($('flagUserOverlayDialogContents').innerHTML);

	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	var dialogBoxTop = arrayPageScroll[1] + ( Math.abs(arrayPageSize[3] -  $('flagUserOverlayDialog').getHeight()) / 2 );
	var dialogBoxWidth = 400;
	var dialogBoxLeft = ((arrayPageSize[2] / 2) - (dialogBoxWidth / 2)) + arrayPageScroll[0];
	$('flagUserOverlayDialog').style.top = dialogBoxTop +"px";
	$('flagUserOverlayDialog').style.left = dialogBoxLeft +"px";
	$('flagUserOverlayDialog').setStyle({position: 'absolute', zIndex: 100});

	$("flagUserOverlayDialog").show();
}

function openRemoveUserOverlayDialog() {
            overlayUI();
 
            var objOverlay = document.createElement("div");
            objOverlay.setAttribute('id','removeUserOverlayDialog');
            objOverlay.style.display = 'none';
 
            var objOverlayForm = document.createElement('form');
            objOverlayForm.setAttribute('id', 'formRemoveUser');
            objOverlayForm.setAttribute('method', 'post');
            objOverlayForm.setAttribute('action', '/community/profile/flagMember.bt');
 
            $$('body')[0].appendChild(objOverlay);
            $('removeUserOverlayDialog').appendChild(objOverlayForm);
            $('formRemoveUser').onsubmit = function() { removeMember(); return false; };
            $('formRemoveUser').update($('removeUserOverlayDialogContents').innerHTML);
 
            var arrayPageSize = getPageSize();
            var arrayPageScroll = getPageScroll();
            var dialogBoxTop = arrayPageScroll[1] + ( Math.abs(arrayPageSize[3] -  $('removeUserOverlayDialog').getHeight()) / 2 );
            var dialogBoxWidth = 400;
            var dialogBoxLeft = ((arrayPageSize[2] / 2) - (dialogBoxWidth / 2)) + arrayPageScroll[0];
            $('removeUserOverlayDialog').style.top = dialogBoxTop +"px";
            $('removeUserOverlayDialog').style.left = dialogBoxLeft +"px";
            $('removeUserOverlayDialog').setStyle({position: 'absolute', zIndex: 100});
 
            $("removeUserOverlayDialog").show();
}
 
function closeFlagUserOverlayDialog() {
            $('flagUserOverlayDialog').hide();
            $('flagUserOverlayDialog').remove();
            closeOverlayUI();
}
 
function closeRemoveUserOverlayDialog() {
            $('removeUserOverlayDialog').hide();
            $('removeUserOverlayDialog').remove();
            closeOverlayUI();
}
 
function flagMember() {
    if ($('formFlagUser').violation.selectedIndex == 0) {
                  //      closeFlagUserOverlayDialog();
        //$('flagUserError').update('<div class=\"systemError\" style=\"margin-bottom: 0; margin-top: 20px;\">You must select a violation.</div>');
alert("You must select a violation to continue.");    

} else {
        var formValues = $('formFlagUser').serialize(true);
        //formValues=formValues+"&userAction=USERFLAG";
        var regRequest = new Ajax.Request('/community/profile/flagMember.bt', {method: 'post', parameters: formValues});
        $('flagUserError').hide();
                        closeFlagUserOverlayDialog();
                        overlayConfirmation('flagUserConfirmation');
    }
}

function removeMember() {
    if ($('formRemoveUser').violation.selectedIndex == 0) {
                     //   closeRemoveUserOverlayDialog();
       // $('flagUserError').update('<div class=\"systemError\" style=\"margin-bottom: 0; margin-top: 20px;\">You must select a violation.</div>');
     alert("You must select a violation to continue.");   
    } else {
        var formValues = $('formRemoveUser').serialize(true);
       //formValues=formValues+"&userAction=ADMINREMOVE";
        var regRequest = new Ajax.Request('/community/profile/flagMember.bt', {method: 'post', parameters: formValues});
        $('flagUserError').hide();
                        closeFlagUserOverlayDialog();
                        overlayConfirmation('removeUserConfirmation');
    }
} 

//contentTypeId 1 means that , we are changing the status of the blocked user to 1. 
function removeFromBlockedContacts() {

    var checkBoxes = document.getElementsByName("selectContact");
    var urlToSubmit = '/community/contacts/dropContact.bt?contentTypeId=1&';
    var checkedCount = 0;
    for (var i = 0; i < checkBoxes.length; i++)
    {
        if (checkBoxes[i].checked == true)
        {
            checkedCount = checkedCount + 1;
            if (checkedCount == 1)
            {
                urlToSubmit = urlToSubmit + "contactsToRemove=" + checkBoxes[i].value;
            }
            else
            {
                urlToSubmit = urlToSubmit + "&contactsToRemove=" + checkBoxes[i].value;
            }
        }
    }

    if (checkedCount != 0) {
        window.location.replace(urlToSubmit);
    }
}


//flag/remove user overlay
function openBlockUserOverlayDialog() {
    overlayUI();
    
    var objOverlay = document.createElement("div");
    objOverlay.setAttribute('id','blockUserOverlayDialog');
    objOverlay.style.display = 'none';

    var objOverlayForm = document.createElement('form');
    objOverlayForm.setAttribute('id', 'formBlockUser');
    objOverlayForm.setAttribute('method', 'post');
    objOverlayForm.setAttribute('action', '/community/profile/blockMember.bt');

    $$('body')[0].appendChild(objOverlay);
    $('blockUserOverlayDialog').appendChild(objOverlayForm);
    $('formBlockUser').onsubmit = function() { blockMember(); return false; };
    $('formBlockUser').update($('blockUserOverlayDialogContents').innerHTML);

    var arrayPageSize = getPageSize();
    var arrayPageScroll = getPageScroll();
    var dialogBoxTop = arrayPageScroll[1] + ( Math.abs(arrayPageSize[3] -  $('blockUserOverlayDialog').getHeight()) / 2 );
    var dialogBoxWidth = 400;
    var dialogBoxLeft = ((arrayPageSize[2] / 2) - (dialogBoxWidth / 2)) + arrayPageScroll[0];
    $('blockUserOverlayDialog').style.top = dialogBoxTop +"px";
    $('blockUserOverlayDialog').style.left = dialogBoxLeft +"px";
    $('blockUserOverlayDialog').setStyle({position: 'absolute', zIndex: 100});

    $("blockUserOverlayDialog").show();
}

function closeBlockUserOverlayDialog() {
    $('blockUserOverlayDialog').hide();
    $('blockUserOverlayDialog').remove();
    closeOverlayUI();
}

function blockMember() {
	var formValues = $('formBlockUser').serialize(true);
	var regRequest = new Ajax.Request('/community/profile/blockMember.bt', {method: 'post', parameters: formValues});
	$('blockUserError').hide();
	$('blockUserNotify').update('<div class=\"systemError\" style=\"margin-bottom: 0;\">User has been blocked.</div>');
}

function checkForEditPost(entryId, topicId, groupId) {
	checkURL = "/community/groups/forums/editTopicPost.bt?method=editPost&groupId=" + groupId + "&parentId=" + entryId + "&topicId=" + topicId + "&type=edit";
	var ajaxResponse = new Ajax.Request(checkURL, {method: 'post', onSuccess: determineEditTimeAndResponse});
}

function checkForEditTopic(topicTitle, topicId, groupId) {
	checkURL = "/community/groups/forums/editTopicPost.bt?method=editTopic&groupId=" + groupId + "&topicId=" + topicId + "&title=" + topicTitle + "&type=edit";
	var ajaxResponse = new Ajax.Request(checkURL, {method: 'post', onSuccess: determineEditTimeAndResponse});
}

function determineEditTimeAndResponse(originalRequest) {
	var gotBack = originalRequest.responseText;
	if (gotBack.match(/ERROR~/)) {
			overlayConfirmation('editPostOverlay');
			return false;
	} else {
			window.location = checkURL;
	}
}

function deleteMemberCommentAsAdmin(commentId, commentTypeId)
{
//    alert("CommentId = " + commentId);
//    alert("commentType = " + commentTypeId);
    if(commentTypeId == 1)   //content comment
    {
       window.location.replace('/community/admin/adminFlaggedContentComments!deleteContentComment.action?contentId=' + commentId);
    }else if(commentTypeId==2)//member comment
     {
       window.location.replace('/community/admin/adminFlaggedMemberComments!deleteMemberComment.action?contentId= '+commentId);
    }

 }
 
         function openFlagContentOverlayDialog(contentId) {
             var action = '/community/flagItems/flagContent.bt?method=flagContent';
             overlayUI();
 
             var objOverlay = document.createElement("div");
             objOverlay.setAttribute('id', 'flagContentOverlayDialog');
             objOverlay.style.display = 'none';
 
             var objOverlayForm = document.createElement('form');
             objOverlayForm.setAttribute('id', 'formFlagContent');
             objOverlayForm.setAttribute('method', 'post');
             objOverlayForm.setAttribute('action', action);
 
             $$('body')[0].appendChild(objOverlay);
             $('flagContentOverlayDialog').appendChild(objOverlayForm);
             $('formFlagContent').onsubmit = function() {
                 flagContentAsUser(contentId);
                 return false;
             };
             $('formFlagContent').update($('flagContentOverlayDialogContents').innerHTML);
 
             var arrayPageSize = getPageSize();
             var arrayPageScroll = getPageScroll();
             var dialogBoxTop = arrayPageScroll[1] + ( Math.abs(arrayPageSize[3] - $('flagContentOverlayDialog').getHeight()) / 2 );
             var dialogBoxWidth = 400;
             var dialogBoxLeft = ((arrayPageSize[2] / 2) - (dialogBoxWidth / 2)) + arrayPageScroll[0];
             $('flagContentOverlayDialog').style.top = dialogBoxTop + "px";
             $('flagContentOverlayDialog').style.left = dialogBoxLeft + "px";
             $('flagContentOverlayDialog').setStyle({position: 'absolute', zIndex: 100});
 
             $("flagContentOverlayDialog").show();
         }
 
         function openFlagContentAsAdminOverlayDialog(contentId) {
             var action = '/community/admin/adminFlaggedContent!deleteContent.action';
             overlayUI();
 
             var objOverlay = document.createElement("div");
             objOverlay.setAttribute('id', 'flagContentAsAdminOverlayDialog');
             objOverlay.style.display = 'none';
 
             var objOverlayForm = document.createElement('form');
             objOverlayForm.setAttribute('id', 'formFlagContentAsAdmin');
             objOverlayForm.setAttribute('method', 'post');
             objOverlayForm.setAttribute('action', action);
 
             $$('body')[0].appendChild(objOverlay);
             $('flagContentAsAdminOverlayDialog').appendChild(objOverlayForm);
             $('formFlagContentAsAdmin').onsubmit = function() {
                 flagContentAsAdmin(contentId);
                 return false;
             };
             $('formFlagContentAsAdmin').update($('flagContentAsAdminOverlayDialogContents').innerHTML);
 
             var arrayPageSize = getPageSize();
             var arrayPageScroll = getPageScroll();
             var dialogBoxTop = arrayPageScroll[1] + ( Math.abs(arrayPageSize[3] - $('flagContentAsAdminOverlayDialog').getHeight()) / 2 );
             var dialogBoxWidth = 400;
             var dialogBoxLeft = ((arrayPageSize[2] / 2) - (dialogBoxWidth / 2)) + arrayPageScroll[0];
             $('flagContentAsAdminOverlayDialog').style.top = dialogBoxTop + "px";
             $('flagContentAsAdminOverlayDialog').style.left = dialogBoxLeft + "px";
             $('flagContentAsAdminOverlayDialog').setStyle({position: 'absolute', zIndex: 100});
 
             $("flagContentAsAdminOverlayDialog").show();
         }
 
         function closeFlagContentOverlayDialog() {
             $('flagContentOverlayDialog').hide();
             $('flagContentOverlayDialog').remove();
             closeOverlayUI();
         }
 
         function closeFlagContentAsAdminOverlayDialog() {
             $('flagContentAsAdminOverlayDialog').hide();
             $('flagContentAsAdminOverlayDialog').remove();
             closeOverlayUI();
         }
 
         function flagContentAsUser(contentId) {
             var action = '/community/flagItems/flagContent.bt?method=flagContent&contentId='+ contentId;
             if ($('formFlagContent').violation.selectedIndex == 0) {
                 $('flagContentAsUserError').update('<div class=\"systemError\" style=\"margin-bottom: 0; margin-top: 20px;\">You must select a violation.</div>');
             } else {
                 var formValues = $('formFlagContent').serialize(true);
                 var regRequest = new Ajax.Request(action, {method: 'post', parameters: formValues});
                 $('flagContentAsUserError').hide();
                 $('flagContentNotify').update('<div class=\"systemError\" style=\"margin-bottom: 0;\">Thanks for reporting this to us. Your initiative will help keep our community beautiful.</div>');
             }
         }
 
         function flagContentAsAdmin(contentId) {
             var action = '/community/admin/adminFlaggedContent!deleteContent.action?contentId='+ contentId;
             if ($('formFlagContentAsAdmin').violation.selectedIndex == 0) {
                 $('flagContentAsAdminError').update('<div class=\"systemError\" style=\"margin-bottom: 0; margin-top: 20px;\">You must select a violation.</div>');
             } else {
                 var formValues = $('formFlagContentAsAdmin').serialize(true);
                 var regRequest = new Ajax.Request(action, {method: 'post', parameters: formValues});
                 $('flagContentAsAdminError').hide();
                 $('flagContentNotify').update('<div class=\"systemError\" style=\"margin-bottom: 0;\">Thanks for reporting this to us. Your initiative will help keep our community beautiful.</div>');
             }
         }

 
//edit vitals
// in this function, the table row/cells display properties are set. IE doesn't allow
// table-specific display values, and simply using block/inline does not render the way
// we want in firefox. so set the values to the empty string, and they will default
function updateLocationFields() {

	var countrySelect = document.getElementById("countrySelect");

	var isUSA = (countrySelect.options[countrySelect.selectedIndex].value == 1);
	var isCanada = (countrySelect.options[countrySelect.selectedIndex].value == 2);
	var isMexico = (countrySelect.options[countrySelect.selectedIndex].value == 162);

	var stateLabel = document.getElementById('stateLabelTD');
	var stateSelect = document.getElementById('stateSelectTD');
	var provinceLabel = document.getElementById('provinceLabelTD');
	var provinceCanadaSelect = document.getElementById('provinceCanadaSelectTD');
	var provinceMexicoSelect = document.getElementById('provinceMexicoSelectTD');
	var stateAndProvince = document.getElementById('stateAndProvinceTR');

	var provinceTextLabel = document.getElementById('provinceTextTD');
	var provinceInput = document.getElementById('provinceInputTD');

	var canadaSelect = document.getElementById('canadaSelect');
	var mexicoSelect = document.getElementById('mexicoSelect');

	if (isUSA) {

	    stateLabel.style.display = '';
	    stateSelect.style.display = '';

	    provinceLabel.style.display = 'none';
	    provinceCanadaSelect.style.display = 'none';
	    provinceMexicoSelect.style.display = 'none';

	    stateAndProvince.style.display = '';

	    provinceTextLabel.style.display = 'none';
	    provinceInput.style.display = 'none';

	    canadaSelect.disabled = true;
	    mexicoSelect.disabled = true;

	} else if (isCanada) {

	    stateLabel.style.display = 'none';
	    stateSelect.style.display = 'none';

	    provinceLabel.style.display = '';
	    provinceCanadaSelect.style.display = '';
	    provinceMexicoSelect.style.display = 'none';

	    stateAndProvince.style.display = '';

	    provinceTextLabel.style.display = 'none';
	    provinceInput.style.display = 'none';

	    canadaSelect.disabled = false;
	    mexicoSelect.disabled = true;

	} else if (isMexico) {

	    stateLabel.style.display = 'none';
	    stateSelect.style.display = 'none';

	    provinceLabel.style.display = '';
	    provinceCanadaSelect.style.display = 'none';
	    provinceMexicoSelect.style.display = '';

	    stateAndProvince.style.display = '';

	    provinceTextLabel.style.display = 'none';
	    provinceInput.style.display = 'none';

	    canadaSelect.disabled = true;
	    mexicoSelect.disabled = false;

	} else {

	    stateLabel.style.display = 'none';
	    stateSelect.style.display = 'none';

	    provinceLabel.style.display = 'none';
	    provinceCanadaSelect.style.display = 'none';
	    provinceMexicoSelect.style.display = 'none';

	    stateAndProvince.style.display = '';
	    provinceTextLabel.style.display = '';
	    provinceInput.style.display = '';

	    canadaSelect.disabled = true;
	    mexicoSelect.disabled = true;
	}

}

//printing
function printPopUp(URL) {
	var windowReference = window.open(URL,'printWindow','toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=780,height=580,left=330,top=160');
	//windowReference.print();
}

//Animated Collapsible DIV- Author: Dynamic Drive (http://www.dynamicdrive.com)
//Last updated Aug 1st, 07'. Fixed bug with "block" parameter not working when persist is enabled
//Updated June 27th, 07'. Added ability for a DIV to be initially expanded.

var uniquepageid=window.location.href.replace("http://"+window.location.hostname, "").replace(/^\//, "") //get current page path and name, used to uniquely identify this page for persistence feature

function animatedcollapse(divId, animatetime, persistexpand, initstate){
	this.divId=divId
	this.divObj=document.getElementById(divId)
	this.divObj.style.overflow="hidden"
	this.timelength=animatetime
	this.initstate=(typeof initstate!="undefined" && initstate=="block")? "block" : "contract"
	this.isExpanded=animatedcollapse.getCookie(uniquepageid+"-"+divId) //"yes" or "no", based on cookie value
	this.contentheight=parseInt(this.divObj.style.height)
	var thisobj=this
	if (isNaN(this.contentheight)){ //if no CSS "height" attribute explicitly defined, get DIV's height on window.load
		animatedcollapse.dotask(window, function(){thisobj._getheight(persistexpand)}, "load")
		if (!persistexpand && this.initstate=="contract" || persistexpand && this.isExpanded!="yes" && this.isExpanded!="") //Hide DIV (unless div should be expanded by default, OR persistence is enabled and this DIV should be expanded)
			this.divObj.style.visibility="hidden" //hide content (versus collapse) until we can get its height
	}
	else if (!persistexpand && this.initstate=="contract" || persistexpand && this.isExpanded!="yes" && this.isExpanded!="") //Hide DIV (unless div should be expanded by default, OR persistence is enabled and this DIV should be expanded)
		this.divObj.style.height=0 //just collapse content if CSS "height" attribute available
	if (persistexpand)
		animatedcollapse.dotask(window, function(){animatedcollapse.setCookie(uniquepageid+"-"+thisobj.divId, thisobj.isExpanded)}, "unload")
}

animatedcollapse.prototype._getheight=function(persistexpand){
	this.contentheight=this.divObj.offsetHeight
	if (!persistexpand && this.initstate=="contract" || persistexpand && this.isExpanded!="yes"){ //Hide DIV (unless div should be expanded by default, OR persistence is enabled and this DIV should be expanded)
		this.divObj.style.height=0 //collapse content
		this.divObj.style.visibility="visible"
	}
	else //else if persistence is enabled AND this content should be expanded, define its CSS height value so slideup() has something to work with
		this.divObj.style.height=this.contentheight+"px"
}


animatedcollapse.prototype._slideengine=function(direction){
	var elapsed=new Date().getTime()-this.startTime //get time animation has run
	var thisobj=this
	if (elapsed<this.timelength){ //if time run is less than specified length
		var distancepercent=(direction=="down")? animatedcollapse.curveincrement(elapsed/this.timelength) : 1-animatedcollapse.curveincrement(elapsed/this.timelength)
	this.divObj.style.height=distancepercent * this.contentheight +"px"
	this.runtimer=setTimeout(function(){thisobj._slideengine(direction)}, 10)
	}
	else{ //if animation finished
		this.divObj.style.height=(direction=="down")? this.contentheight+"px" : 0
		this.isExpanded=(direction=="down")? "yes" : "no" //remember whether content is expanded or not
		this.runtimer=null
	}
}


animatedcollapse.prototype.slidedown=function(){
	if (typeof this.runtimer=="undefined" || this.runtimer==null){ //if animation isn't already running or has stopped running
		if (isNaN(this.contentheight)) //if content height not available yet (until window.onload)
			alert("Please wait until document has fully loaded then click again")
		else if (parseInt(this.divObj.style.height)==0){ //if content is collapsed
			this.startTime=new Date().getTime() //Set animation start time
			this._slideengine("down")
		}
	}
}

animatedcollapse.prototype.slideup=function(){
	if (typeof this.runtimer=="undefined" || this.runtimer==null){ //if animation isn't already running or has stopped running
		if (isNaN(this.contentheight)) //if content height not available yet (until window.onload)
			alert("Please wait until document has fully loaded then click again")
		else if (parseInt(this.divObj.style.height)==this.contentheight){ //if content is expanded
			this.startTime=new Date().getTime()
			this._slideengine("up")
		}
	}
}

animatedcollapse.prototype.slideit=function(){
	if (isNaN(this.contentheight)) //if content height not available yet (until window.onload)
		alert("Please wait until document has fully loaded then click again")
	else if (parseInt(this.divObj.style.height)==0)
		this.slidedown()
	else if (parseInt(this.divObj.style.height)==this.contentheight)
		this.slideup()
}

// -------------------------------------------------------------------
// A few utility functions below:
// -------------------------------------------------------------------

animatedcollapse.curveincrement=function(percent){
	return (1-Math.cos(percent*Math.PI)) / 2 //return cos curve based value from a percentage input
}

animatedcollapse.dotask=function(target, functionref, tasktype){ //assign a function to execute to an event handler (ie: onunload)
	var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
	if (target.addEventListener)
		target.addEventListener(tasktype, functionref, false)
	else if (target.attachEvent)
		target.attachEvent(tasktype, functionref)
}

animatedcollapse.getCookie=function(Name){ 
	var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
		return document.cookie.match(re)[0].split("=")[1] //return its value
	return ""
}

animatedcollapse.setCookie=function(name, value){
	document.cookie = name+"="+value
}




function overlayConfirmationBig(dialogBoxContentsDivID) {
	hideSelectBoxes();
	hideFlash();

	var objBody = document.getElementsByTagName("body").item(0);
	
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','overlay');
	objOverlay.style.display = 'none';
	objBody.appendChild(objOverlay);

	var objDialogBox = document.createElement("div");
	objDialogBox.setAttribute('id','dialogBig');
	objDialogBox.style.display = 'none';
	objBody.appendChild(objDialogBox);

	var arrayPageSize = getPageSize();
	$('overlay').style.width = arrayPageSize[0] +"px";
	$('overlay').style.height = arrayPageSize[1] +"px";

	var overlayDuration = 0.2;	// shadow fade in/out duration
	var overlayOpacity = 0.6;	// controls transparency of shadow overlay
	new Effect.Appear('overlay', { duration: overlayDuration, from: 0.0, to: overlayOpacity });
	
	var arrayPageScroll = getPageScroll();
	var dialogBoxTop = arrayPageScroll[1] + 50;
	var dialogBoxWidth = 616;
	var dialogBoxLeft = ((arrayPageSize[2] / 2) - (dialogBoxWidth / 2)) + arrayPageScroll[0];
	
	$('dialogBig').style.top = dialogBoxTop +"px"; 
	$('dialogBig').style.left = dialogBoxLeft +"px"; 
	$('dialogBig').update($(dialogBoxContentsDivID).innerHTML);
	
	$('dialogBig').show();
}

function closeOverlayConfirmationBig() {
	$('dialogBig').hide();
	var overlayDuration = 0.2;	// shadow fade in/out duration
	new Effect.Fade('overlay', { duration: overlayDuration});
	showSelectBoxes();
	showFlash();
}

function externalLink(divId, externalUrl) {

	//add button HTML with external URL
	document.getElementById('externalLinkButtons').innerHTML = "<a href=\"" + externalUrl + "\" target=\"_blank\" onclick=\"closeOverlayConfirmation();\" class=\"btn24Blue\"><span class=\"left\">&nbsp;</span><span class=\"middle\">Continue</span><span class=\"right\">&nbsp;</span></a><div class=\"btnGutter\">&nbsp;</div><a href=\"#\" onclick=\"closeOverlayConfirmation(); return false;\" class=\"btn24\"><span class=\"left\">&nbsp;</span><span class=\"middle\">Cancel</span><span class=\"right\">&nbsp;</span></a><div class=\"clearer\"></div>";
	 
	overlayConfirmation(divId);
	
}

//***************
//FORM VALIDATION
//***************

//check to see if field is empty
function validateField(field, value) {
    if (value.length == 0) {
        if (!$(field).hasClassName('error')) {
            $(field).addClassName('error');
            $(field + 'Label').addClassName('error');
        }
        $('errorIndicator').update('<div class=\"systemError\" style=\"margin-bottom: 20px;\">Required fields have not been filled. Please check the highlighted errors below.</div>');
        return false;
    } else {
        $(field).removeClassName('error');
        $(field + 'Label').removeClassName('error');
        return true;
    }
}

//******************
//TOGGLE DIV DISPLAY
//******************
function toggleBlind(div1, div2) {

    if (div2 === undefined) {

        if ($(div1).hasClassName('open')) {
            Effect.BlindUp(div1, { duration: 0.25 });
            $(div1).removeClassName('open');
        } else {
            Effect.BlindDown(div1, { duration: 0.25 });
            $(div1).addClassName('open');
        }

    } else {

        if (!$(div1).hasClassName('open')) {
            Effect.BlindUp(div2, { duration: 0.25 });
            $(div2).removeClassName('open');
            Effect.BlindDown(div1, { duration: 0.25, delay: 0.35 });
            $(div1).addClassName('open');
        }

    }

}

function toggleBlindAll(direction, divs) {

    var len = divs.length;
    for (var i = 0; i < len; i++) {

        if (direction == "up") {
            Effect.BlindUp(divs[i], { duration: 0.25 });
            $(divs[i]).removeClassName('open');
        } else if (direction == "down") {
            Effect.BlindDown(divs[i], { duration: 0.25 });
            $(divs[i]).addClassName('open');
        }

    }

}

function paneSwitchWithEvalScripts(requestedPane) {
    var correctUrl = "/community/profile/update" + requestedPane + ".bt?method=view" + requestedPane + "Pane";
    var req = new Ajax.Updater('settingsPane', correctUrl, {evalScripts: true});
}

//hack to fix IE6 sprite flickering problem
try {
 document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}


