var CDNBaseUrl = "http://cdn.faniq.com/";
var FBAPIKey = '87b2d59992d96aefe8e970d49eae1d0d';

function getElement(whichElement) {
	if (document.getElementById)
	{
		// this is the way the standards work
		var myStyle = document.getElementById(whichElement).style;
	}
	else if (document.all)
	{
		// this is the way old msie versions work
		var myStyle = document.all[whichElement].style;
	}
	else if (document.layers)
	{
		// this is the way nn4 works
		var myStyle = document.layers[whichElement].style;
	}
	return myStyle;
}


function toggleLayer(whichLayer,toggleType,layerType)
{
	var myStyle = getElement(whichLayer);
	// block is the default display type if nothing else was defined
	if (typeof(layerType) == 'undefined') {
		var layerType = 'block';
	} 
	if (toggleType == 'on') {
		myStyle.display = layerType;
	} else if (toggleType == 'off') {
		myStyle.display = "none";
	} else if (toggleType == 'toggle') {
		myStyle.display = (myStyle.display == layerType) ? "none":layerType;
	}
}

function toggleTableRow(whichLayer, toggleType)
{
  var layerType = navigator.userAgent.indexOf("Gecko") >= 0 ?'table-row':'block';
	toggleLayer(whichLayer, toggleType, layerType);
}

function toggleAllLayers(whichLayer,toggleType,layerList)
{
	if (! layerList.length) return;
	// block is the default display type if nothing else was defined
	if (typeof(layerType) == 'undefined') {
		var layerType = 'block';
	}
	// get all layers that start with the whichLayer prefix
	for(i=0;i<layerList.length;i++) {
		thisLayer=whichLayer+"["+layerList[i]+"]";
		//alert(thisLayer);
		var myStyle = getElement(thisLayer);
		if (toggleType == 'on') {
			myStyle.display = layerType;
		} else if (toggleType == 'off') {
			myStyle.display = "none";
		} else if (toggleType == 'toggle') {
			myStyle.display = (myStyle.display == layerType) ? "none":layerType;
		}
	}
}

function changeColor(whichLayer,newColor) {
	var myStyle = getElement(whichLayer);
	myStyle.color = newColor;
}

function toggleRadio(whichField,whichOption,whichAction) {
	for(i=0; i<whichField.length; i++) {
		if (whichField[i].value == whichOption) {
			if (whichAction == 'check') {
				whichField[i].checked = true;
			} else if (whichAction == 'uncheck') {
				whichField[i].checked = false;
			} else if (whichAction == 'disable') {
				whichField[i].checked = false;
				// make it unselectable too
				whichField[i].disabled = true;
			} else if (whichAction == 'enable') {		
				whichField[i].disabled = false;
			}
			return;
		}
	}
}

function clearRadioButtons(whichField) {
	for (i=0; i<whichField.length; i++) {
		whichField[i].checked = false;
	}
}

function checkAll(theForm) {
	for (var i=0, j=theForm.elements.length; i<j; i++) {
        myType = theForm.elements[i].type;
        if (myType == 'checkbox')
            theForm.elements[i].checked = true;
	}
}

function countCheckboxes(theForm) {
	var numChecked = 0;
	for (var i=0; i < theForm.elements.length; i++) {
		if (theForm.elements[i].type == 'checkbox' && theForm.elements[i].checked) {
			numChecked++;
		}
	}
	return numChecked;
}

function MoveOptionNosort(objSourceElement, objTargetElement, moveAll) {
	var aryTempSourceOptions = new Array();
	var aryTempTargetOptions = new Array();
	var x = 0;
	
	//looping through source element to find selected options
	for (var i = 0; i < objSourceElement.length; i++) {
		if (objSourceElement.options[i].selected || moveAll) {
			//need to move this option to target element
			var intTargetLen = objTargetElement.length++;
			objTargetElement.options[intTargetLen].text = objSourceElement.options[i].text;
			objTargetElement.options[intTargetLen].value = objSourceElement.options[i].value;
		} else {
			//storing options that stay to recreate select element
			var objTempValues = new Object();
			objTempValues.text = objSourceElement.options[i].text;
			objTempValues.value = objSourceElement.options[i].value;
			aryTempSourceOptions[x] = objTempValues;
			x++;
		}
	}
	
	//sorting and refilling target list
	for (var i = 0; i < objTargetElement.length; i++) {
		var objTempValues = new Object();
		objTempValues.text = objTargetElement.options[i].text;
		objTempValues.value = objTargetElement.options[i].value;
		aryTempTargetOptions[i] = objTempValues;
	}
	
	for (var i = 0; i < objTargetElement.length; i++) {
		objTargetElement.options[i].text = aryTempTargetOptions[i].text;
		objTargetElement.options[i].value = aryTempTargetOptions[i].value;
		objTargetElement.options[i].selected = false;
	}
	
	//resetting length of source
	objSourceElement.length = aryTempSourceOptions.length;
	//looping through temp array to recreate source select element
	for (var i = 0; i < aryTempSourceOptions.length; i++) {
		objSourceElement.options[i].text = aryTempSourceOptions[i].text;
		objSourceElement.options[i].value = aryTempSourceOptions[i].value;
		objSourceElement.options[i].selected = false;
	}
}

function selectAll(objTargetElement) {
	for (var i = 0; i < objTargetElement.length; i++) {
		objTargetElement.options[i].selected = true;
	}
   return false;
}


function clearForm(theForm) {
    for (var i=0, j=theForm.elements.length; i<j; i++) {
        myType = theForm.elements[i].type;
        if (myType == 'checkbox' || myType == 'radio')
            theForm.elements[i].checked = false;
        if (myType == 'hidden' || myType == 'password' || myType == 'text' || myType == 'textarea')
            theForm.elements[i].value = '';
        if (myType == 'select-one' || myType == 'select-multiple')
            for (var k=0, l=theForm.elements[i].options.length; k<l; k++)
                theForm.elements[i].options[k].selected = false;
    }
}

function setNumericOptions(updatefield, minNum, maxNum) {
	var defaultValue = updatefield.options[updatefield.selectedIndex].value;
	updatefield.options.length=0;
	for (var i=minNum; i<=maxNum; i++) {
		var selected = (i == defaultValue) ? true : false; 
		updatefield.options[updatefield.options.length] = new Option(i, i, selected);
	}
}

function popWin(jj, wWidth, wHeight) {
	if (! wWidth) wWidth=500;
	if (! wHeight) wHeight=500;
	var popup = window.open(jj, 'popup', 'height='+wHeight+',width='+wWidth+',channelmode=0,dependent=0,directories=0,fullscreen=0,location=0,menubar=0,resizable=0,scrollbars=1,status=1,toolbar=0');
	popup.focus();
}


function checkCR(evt,allow) {
	var evt  = (evt) ? evt : ((event) ? event : null);
	var allow = (allow) ? allow : 'N';
	var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
	if ((evt.keyCode == 13) && (node.type!="textarea")) {
        return (allow != 'Y') ? false : true;
    }
}

// limit the # of characters in a textarea field
function limitText(limitField, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	}
}

// for dynamic select menu -- create new script, set relative URL, and load it - yes kids, this was old school AJAX!!!
function attach_file( p_script_url ) {
	script = document.createElement('script');
	script.src = p_script_url;
	document.getElementsByTagName('head')[0].appendChild(script);
}

// For top navigation
function showNavDropdown(tabName, state) {
    var tab = document.getElementById('navTab'+tabName);
    var dropdown = document.getElementById('navDropdown'+tabName);
    if (state == 'on') {
        tab.className += ' over';
        if (dropdown) {
            dropdown.style.display = 'block';
            if (isIE7() == true) {
                var hero = document.getElementById('fantasyHero');
                if (hero) {
                    hero.style['zIndex'] = -1;
                }
            }
        }
    } else {
        tab.className = tab.className.replace('over', '');
        if (dropdown) {
            dropdown.style.display = 'none';
            if (isIE7() == true) {
                var hero = document.getElementById('fantasyHero');
                if (hero) {
                    hero.style['zIndex'] = 0;
                }
            }
        }
    }
}
// end navigation

// start message popup functions
/**
 * updateNewMsgCountHref: update the text display of the new message count
 * 		
 *
 * @param newMsgCount the new message count.
 */
 function updateNewMsgCountHref(newMsgCount) {
	document.getElementById('newMsgCount').innerHTML = newMsgCount;
} // end updateNewMsgCountHref

/**
 * enableNewMsgLinkAbsolute: enable the new message link and adjust other
 *		associated UI no matter what.
 */ 
function enableNewMsgLinkAbsolute() {
	// enable new msg link and disable recent msg link
	document.getElementById('newMsgLink').style.display = 'inline';
	document.getElementById('recentMsgLink').style.display = 'none';
	
	// adjust drop down message box for new message
	document.getElementById('msgDropDownNew').src = CDNBaseUrl + 'img/main_header_mini_profile_arrow_silver_up.gif';
	
	// reset before any display or hide UI call
	document.getElementById('hideNotifMsgUi').value = 'n';
	
	// display the message panel
	displayMessageNotif(false, false);
} // end enableNewMsgLinkAbsolute

/**
 * enableNewMsgLink: enable the new message link and adjust other
 *		associated UI.
 *
 * @param displayMsgNotif if set to true, disaply msg notification UI.
 * @param flipDropDown if set to true, flip drop down button.
 */
function enableNewMsgLink(displayMsgNotif, flipDropDown) {
	// enable new msg link and disable recent msg link
	document.getElementById('newMsgLink').style.display = 'inline';
	document.getElementById('recentMsgLink').style.display = 'none';
	
	// get drop down message box for new message
	var curSrc = document.getElementById('msgDropDownNew').src;
	var newSrc = '';
	
	// reset before any display or hide UI call
    document.getElementById('hideNotifMsgUi').value = 'n';
	
	// prepare new drop down gif
    if (curSrc.indexOf('up') < 0) {
		newSrc = CDNBaseUrl + 'img/main_header_mini_profile_arrow_silver_up.gif';
		if (displayMsgNotif) {
			displayMessageNotif(false, false);
		}
	} else {
		newSrc = CDNBaseUrl + 'img/main_header_mini_profile_arrow_silver.gif';
		hideMessageNotif(false);
	}
	
	// apply new drop down gif
	if (flipDropDown) {
		document.getElementById('msgDropDownNew').src = newSrc;
	}
} // end enableNewMsgLink

/**
 * enableRecentMsgLink: enable the recent message link and adjust other
 * 		associated UI.
 *
 * @param displayMsgNotif if set to true, disaply msg notification UI.
 * @param flipDropDown if set to true, flip drop down button.
 */
function enableRecentMsgLink(displayMsgNotif, flipDropDown) {
	// enable recent msg link and disable new msg link
	document.getElementById('newMsgLink').style.display = 'none';
	document.getElementById('recentMsgLink').style.display = 'inline';
	
	// get drop down message box for recent message
	var curSrc = (document.getElementById('msgDropDownRecent')) ? document.getElementById('msgDropDownRecent').src : '';
	var newSrc = '';
	
	// reset before any display or hide UI call
	document.getElementById('hideNotifMsgUi').value = 'n';
	
	// prepare new drop down gif
    if (curSrc.indexOf('up') < 0) {
		newSrc = CDNBaseUrl + 'img/main_header_mini_profile_arrow_silver_up.gif';
		if (displayMsgNotif) {
			displayMessageNotif(true, true);
		}
	} else {
		newSrc = CDNBaseUrl + 'img/main_header_mini_profile_arrow_silver.gif';
		hideMessageNotif(false);
	}
	
	// apply new drop down gif
	if (flipDropDown) {
		document.getElementById('msgDropDownRecent').src = newSrc;
	}
} // end enableRecentMsgLink

/**
 * toggleMessageDropDownBox: toggle the behavior for the message drop down box. 
 *
 * @param isForReadMsg if set to true, it's displayed for recent messages.
 * @param imgElmtId id tag of the image element.
 * @param reloadMsgNotifFrame if set to true, reload the message notification
 *		frame when needed.
 */
function toggleMessageDropDownBox(isForReadMsg, imgElmtId, reloadMsgNotifFrame) {
	var curSrc = document.getElementById(imgElmtId).src;
	var newSrc = '';
	// reset before any display or hide UI call
	document.getElementById('hideNotifMsgUi').value = 'n';

	// prepare new drop down gif
    if (curSrc.indexOf('up') < 0) {
		newSrc = CDNBaseUrl + 'img/main_header_mini_profile_arrow_silver_up.gif';
		displayMessageNotif(isForReadMsg, reloadMsgNotifFrame);
	} else {
		newSrc = CDNBaseUrl + 'img/main_header_mini_profile_arrow_silver.gif';
		hideMessageNotif(reloadMsgNotifFrame);
	}
	document.getElementById(imgElmtId).src = newSrc;
} // end toggleMessageDropDownBox

/**
* displayMessageNotifForRecentMessages: display the message notification main
* 		panel to display recent messages.
*/
function displayMessageNotifForRecentMessages() {
    displayMessageNotif(true, true);
} // end displayMessageNotifForRecentMessages

/**
* displayMessageNotif: display the message notification main panel.
*
* @param isForReadMsg if set to true, it's displayed for recent messages.
* @param reloadMsgNotifFrame if set to true, reload message notification frame.
* @param sendToMember : if set, send to a specific member
*/
function displayMessageNotif(isForReadMsg, reloadMsgNotifFrame, sendToMember) {
    if (isForReadMsg) {
        document.getElementById('getReadMsg').value = 'y';
    }
    if (sendToMember) {
        document.getElementById('sendMessageTo').value = sendToMember;
    } else {
        document.getElementById('sendMessageTo').value = '';
    }
    document.getElementById('msgNotifFrame').style.display = 'block';
    
    if (reloadMsgNotifFrame) {
        document.getElementById('msgNotifFrame').src = document.getElementById('msgNotifFrame').src; // reload frame
    }
    
    offsetFrameHeight();
} // end displayMessageNotif

function offsetFrameHeight() {
    // update offset height for base frame to adjust frame height when
    // displaying message body that is too long
    var scrollHeight = frames['msgNotifFrame'].document.getElementById('msgNotifPanel').scrollHeight;
    document.getElementById('msgNotifFrame').height = scrollHeight + 2; // pad with offset
}

/**
* hideMessageNotif: hide the message notification main panel.
*
* @param reloadMsgNotifFrame if set to true, reload the message notification
*		frame.
*/
function hideMessageNotif(reloadMsgNotifFrame) {
    document.getElementById('msgNotifFrame').style.display = 'none';

    // so that after the frame reloads, it won't display the UI right the way.
    document.getElementById('hideNotifMsgUi').value = 'y';
    
    if (reloadMsgNotifFrame) {
        document.getElementById('msgNotifFrame').src = document.getElementById('msgNotifFrame').src; // reload frame
    }
    document.getElementById('getReadMsg').value = 'n'; // reset
} // end hideMessageNotif

// end message popup functions


function check_over(val,news_item){
	if(val == 1 || val==2){
		document.getElementById(news_item).src = CDNBaseUrl + 'img/ico_check_black.gif';
		if (val==2) {
			var parts = news_item.split('_');
			var news_id = parts[1];
			var news_link = 'news_link_'+news_id;
			document.getElementById(news_link).onmouseout='';
		}
	}else{
		document.getElementById(news_item).src = CDNBaseUrl + 'img/ico_check_grey.gif';
	}
}

// highlight a newsfeed tab
function highlightTab(tabID, toggleType) {
	var thisTab = document.getElementById(tabID);
	var tabClass = (toggleType == 'on') ? 'newsfeed_tab_active' : 'newsfeed_tab';
	thisTab.className = tabClass;
}


// for fan (clubhouse) actions: update the display and call the ajax to do the backend work
// 12/10/07 CF: add a check on a global variable to see if we need to redirect the whole page on success 
// 8/25/08 CF: add a check on a global variable (fanActionResponseType) to see if we want to send an abbreviated response
function ajaxFanAction(profileId, actionId, elementId, actionText, userName, awardId, replyId, contextId, contextParams) {
	// update the display to reflect the action was done
	if( !isLoggedIn )
	{
		registrationShowOverlay();
		return false;
	}
	
    if (actionText)
    {
    	document.getElementById(elementId).className = 'arrow_red txt_red';
        if (window.fanActionResponseType === undefined) {
            var responseText = 'You successfully ' + actionText + ' ' + userName;
        } else if (window.fanActionResponseType == 'short') {
            var responseText = actionText;
        }
    	document.getElementById(elementId).innerHTML = responseText;
    }
    
	// defining the URL for the call
	var sUrl = 'ajax/profile_fanaction.php';
	var postString = 'id=' + profileId + '&action_id=' + actionId;
	if (awardId) {
		postString = postString + '&award=' + awardId;
	}
	if (replyId) {
		postString = postString + '&reply=' + replyId;
	}
    if (contextId) {
        postString = postString + '&context_id=' + contextId;
        if (contextParams) {
            postString = postString + '&' + contextParams;
        }
    }
	
	//alert(postString);
	
	// making the call (no callback function)
	new Ajax.Request(sUrl, {
		method: 'post',
		parameters: postString
	});
	
	//alert(redirectPageURL);
	if (window.redirectPageURL !== undefined) {
		window.location.href = redirectPageURL;
	}
}


// for thumbs up ratings: update the display and call the ajax to do the backend work
function ajaxThumbs(objectType, objectID, thumbType, subType, showPlus) {
	
	// display the not logged in error
	if (objectType == 'login_error') {
		registrationShowOverlay();
		//alert('You must be logged in to give a rating.');
		return;
	}


	// for trivia just turn on the next question since there is no text to update 
	if (objectType == 'trivia') {
		toggleTrivia();
		
	// for all other rating types, need to adjust the thumbs and rating text
	} else {
	
		// there could be up to 2 rating objects on the page for the same object
		var suffix = new Array();
		suffix[0] = '';
		suffix[1] = 'b';
	
	    // if we are doing a subtype rating, define the possible subtypes
		if (subType || objectType == 'comments') {
			var subTypes = new Array();
		    subTypes[0] = 'smart';
		    subTypes[1] = 'funny';
		    subTypes[2] = 'bold';
		    subTypes[3] = 'poor';
		}          
		
		for (i=0; i<suffix.length; i++) {
			// get thumbs display object if it exists
			var ratingObj = document.getElementById('rating_' + objectType + objectID + suffix[i]);
			
			if (ratingObj) {	
				// for trivia, the display change is different
				
				// only change the rating text if this was a thumbs up (not a poor quality /thumbs down)
				if (thumbType != 'down') {
					// get the current rating
					var ratingValue = ratingObj.innerHTML;
					
					// strip off the plus sign and nbsp, if any
					ratingValue = ratingValue.replace(/[^0-9]/gi, '');
					
					// increment the rating
					ratingValue++;
				
		            // if this was the first thumb for a subtype rating, show the thumb image
					if (ratingValue == 1 && subType != '') {
		                var ratingThumbImg = document.getElementById('thumb_img_' + objectType + objectID + suffix[i]);
		                ratingThumbImg.style.display = 'block';
		            }
					
					// put the plus sign and nbsp back on, if needed
					if (showPlus != '') {
						ratingValue = '+' + ratingValue;
					}
					ratingValue = ratingValue + '&nbsp;';
					
					// update the text in the rating object
					ratingObj.innerHTML = ratingValue;            
				}
				 
				// on the subtype version, we need to update the subtype buttons row
				if (subType != '') {   
		            // update text in the rating subtype object
		    		var ratingSubtypeObj = document.getElementById('rating_' + subType + '_' + objectType + objectID + suffix[i]);
		    		if (ratingSubtypeObj) {
		    			// get the old rating and increment it
						var ratingSubtypeValue = ratingSubtypeObj.innerHTML;
						ratingSubtypeValue = ratingSubtypeValue.replace(/[^0-9]/gi, '');
						ratingSubtypeValue++;
						
						// update the text in the rating subtype object
		    			ratingSubtypeObj.innerHTML = '(' + ratingSubtypeValue + ')';
		                
		                // update the lead-in text to say "You rated it..."
		                var rateTextID = document.getElementById('rate_' + objectType + objectID + suffix[i]);
					    if (rateTextID) {
						    rateTextID.innerHTML = 'You rated it...';
		                }
		            }
				} 
				
                // disable all the buttons for this comment so the user can't re-rate
                // and change the buttons they didn't choose to the grey version
				if (objectType == 'comments') {	
	                for (j=0; j<subTypes.length; j++) {
	                    var ratingSubtypeLink = document.getElementById('rating_link_' + subTypes[j] + '_' + objectType + objectID + suffix[i]);
	                    ratingSubtypeLink.href = 'javascript:void(0);';
	                    if (subTypes[j] != subType) {
	                        var ratingSubtypeImg = document.getElementById('rating_img_' + subTypes[j] + '_' + objectType + objectID + suffix[i]);
	                        ratingSubtypeImg.src = ratingSubtypeImg.src.replace('.gif', '_gray.gif');
	                    }
	                }
				}
			
				//var ilastIndexOf = img.src.lastIndexOf("/") + 1;
				//var base = img.src.substring(0, ilastIndexOf);
			
				// change the thumb from blue->grey (is this still used anywhere?)
				//img.src = base + 'thumbs-up-gray.gif';

				// switch the thumb to inactive or hide it
			    var img_id = 'img_up_' + objectType + objectID + suffix[i];
			    var img = document.getElementById(img_id);
                // allow for implementation as sprite with background image
				if (img && img.tagName == 'img') {
					if (img.src.match('ico_thumb')) {
	   					img.src = img.src.replace('ico_thumb', 'ico_thumb_inactive');
	   	 			} else if (img.src.match('thumbs_like')) {
                        img.src = img.src.replace('thumbs_like', 'thumbs_like_clicked');
                    } else {
						// hide the thumb
	   					img.style.display = 'none';
					}
				}
				
			    // disable the link
				var ratingLink = document.getElementById('rating_link_' + objectType + objectID + suffix[i]);
	            if (ratingLink) {
					ratingLink.href = 'javascript:void(0);';
					ratingLink.onclick = '';
                    ratingLink.onmouseover = '';
                    ratingLink.onmouseout = '';
				}
									
				// if there's a vote link, hide it
				var voteObj = document.getElementById('vote_' + objectType + objectID + suffix[i]);
				if (voteObj) {
					voteObj.innerHTML = '';
		    	}
		
				// The text that says "like it?" (underneath the thumb icon) should change to "you liked it"
				if (! subType) {
					var rateTextID = document.getElementById('rate_' + objectType + objectID + suffix[i]);
					if (rateTextID) {
						rateTextID.innerHTML = 'You liked it';
						rateTextID.className = 'rating_text_rated';
					}
				}
			}
		}
	}
	
	// now construct the url for the ajax call that updates the database
	var sUrl = 'ajax/thumbs.php';
	var postString = 'type=' + objectType + '&id=' + objectID + '&thumb=' + thumbType;
	if (subType) {
		postString = postString + '&subtype=' + subType;
	}
	
	// making the call (no callback function)
	new Ajax.Request(sUrl, {
		method: 'post',
		parameters: postString
	});
	
}

function flagComment(objectType, objectID, thumbType, subType, memberId) {
	// update the subtype buttons row
	if (subType != '') {   
           // update text in the rating subtype object
   		var ratingSubtypeObj = document.getElementById(objectType + 'Rating_' + subType + '_' + objectID);
   		if (ratingSubtypeObj) {
   			// get the old rating and increment it
			var ratingSubtypeValue = ratingSubtypeObj.innerHTML;
			ratingSubtypeValue = ratingSubtypeValue.replace(/[^0-9]/gi, '');
			ratingSubtypeValue++;
			
			// update the text in the rating subtype object
			var ratingSubtypePrefix = (subType == 'poor') ? '-' : '+';
			if (subType == 'poor' && objectType == 'comments' && thumbType == 'down') {
				var postString = "objectId=" + objectID+"&objectType=" + objectType + "&memberId="+ memberId;
				YAHOO.util.Connect.asyncRequest('POST', "ajax/CheckFlag.php", {
					success: function(res) {
					    data = res.responseText;
					    if (data == 'failure') {
				        	displayGenericPopupWide("warning", "You have flagged this comment!", 5000);
				        	return;
				        }
				        else if (data != 'success') {
				        	displayGenericPopupWide("warning", data, 5000);
				        	return;
				        }
				        else {
				        	ratingSubtypeObj.innerHTML = ratingSubtypePrefix + ratingSubtypeValue;
				        	// now construct the url for the ajax call that updates the database
				        	var sUrl = 'ajax/thumbs.php';
				        	var postString = 'type=' + objectType + '&id=' + objectID + '&thumb=' + thumbType;
				        	if (subType) {
				        		postString = postString + '&subtype=' + subType;
				        	}
				        	// making the call (no callback function)
				        	YAHOO.util.Connect.asyncRequest('POST', sUrl, null, postString);
				        }
					}
				}, postString);
			}
			else {
				ratingSubtypeObj.innerHTML = ratingSubtypePrefix + ratingSubtypeValue;
				// now construct the url for the ajax call that updates the database
				var sUrl = 'ajax/thumbs.php';
				var postString = 'type=' + objectType + '&id=' + objectID + '&thumb=' + thumbType;
				if (subType) {
					postString = postString + '&subtype=' + subType;
				}
				// making the call (no callback function)
				YAHOO.util.Connect.asyncRequest('POST', sUrl, null, postString);
			}
		}
	} 
}

// for numeric ratings: convert the number to the equivalent thumb, then call the ajax to do the backend work
function ajaxAddRating(objectType, objectID, rating, skipDisplay) {
	
	// if this object has already been rated, just return
	if (hasRatedObject) {
		return;
	}
	
	// convert the numeric rating to thumbs up or down
	var ratingString = parseInt(rating).toString();
	if (ratingString == 'NaN') {
		return;
	} 
    
    thumbType = '';
	//var ratingObj = document.getElementById('rating_' + objectType + objectID);
	
	// precalculate the new average - right now it seems to be too slow to allow the ajax to do the content updating
	if (! skipDisplay) {
		var ratingCount = parseInt(document.getElementById('rating_count').innerHTML);
		var ratingAvg = (ratingTotalPoints + rating) / ratingCount;
		document.getElementById('rating_avg').innerHTML = ratingAvg.toFixed(1);
	}
	
	// construct the url for the ajax call that updates the database
	// do not do this part if we are faking the rating (i.e. the user is not logged in)
	if (objectType != 'login_error') {
		var sUrl = 'ajax/thumbs.php';
		var postString = 'type=' + objectType + '&id=' + objectID + '&thumb=' + thumbType + '&rating=' + rating;
		
		// making the call - this will update the target with the new content
		// this is too slow right now - we are precalculating instead
		//new Ajax.Updater(
		//	{ success: 'rating_avg' },
		//	sUrl, {
		//		method: 'post',
		//		parameters: postString
		//	}
		//);
		new Ajax.Request(
			sUrl, {
				method: 'post',
				parameters: postString
			}
		);
	}
	
	// set the hasRatedObject variable to prevent the appearance of re-rating
	hasRatedObject = true;
	
	if (! skipDisplay) {
		// display the rating average
		toggleLayer('rating_header', 'off');
		toggleLayer('rating_avg_container', 'on');
		
		// display my rating and turn off the rating form (if applicable)
		if (document.getElementById('my_rating')) {
			toggleLayer('rating_form_container', 'off');
			document.getElementById('my_rating').innerHTML = ratingString;
		}
		
		// for trivia only
		if (objectType == 'trivia' || window.startCountdown === true) {
			toggleLayer('countdown_container', 'on');
			// start the clock on the countdown
			startTriviaCountdown();
		
		// redirect the page to the next after 1.5 seconds
		} else if (window.redirectPageURL !== undefined) {
			toggleLayer('countdown_container', 'on');
			setTimeout('window.location.href = redirectPageURL',1500);
		}
	}
}


// give respect to the given content item and author and launch a popup with the result
function giveRespect(contentType, contentId, authorId, callbackFunctionName, callbackArgs) {
    new Ajax.Request('ajax/respect.php', {
		method: 'get',
		parameters: { content_type:contentType, content_id:contentId, author_id:authorId },
		onSuccess: function (transport) {
            // there could be up to 2 rating objects on the page for the same content
    		var ratingObjSuffix = new Array();
    		ratingObjSuffix[0] = '';
    		ratingObjSuffix[1] = 'b';
			var response = transport.responseText.evalJSON();
			if (typeof showAlertPopup == 'function') {
				popupDuration = (response.result == 'confirm' && response.respectBalance > 0) ? 5000 : null;
				showAlertPopup(response.result, response.message, popupDuration);
			} else {
	            displayGenericPopupWide(response.status, response.message, 5000);
			}
            // update the rating
            if (response.status === 'success') {
                for (i=0; i<ratingObjSuffix.length; i++) {
                    var ratingObj = document.getElementById('rating_' + contentType + contentId + ratingObjSuffix[i]);
    			    if (ratingObj) {
    					// get the current rating
    					var ratingValue = ratingObj.innerHTML;
    					// strip off anything non-numeric
    					ratingValue = ratingValue.replace(/[^0-9]/gi, '');
    					// increment the rating and update the html
    					ratingValue++;
                        ratingObj.innerHTML = ratingValue;
                    }
					// if there's "rated it" text, display the text and hide the link
					var ratedText = document.getElementById('rated_text_' + contentType + contentId + ratingObjSuffix[i]);
	            	var ratingLink = document.getElementById('rating_link_' + contentType + contentId + ratingObjSuffix[i]);
					if (ratedText) {
						ratedText.style.display = 'inline';
						ratingLink.style.display = 'none';
	            		ratingLink.onclick = null;
		            // otherwise just disable the onclick
					} else if (ratingLink) {
	            		ratingLink.onclick = null;
	            	}
	                toggleRespectImg(contentType + contentId + ratingObjSuffix[i], 'inactive');
			    }
				if (callbackFunctionName != null && callbackFunctionName != '') {
					var callbackFunction = eval(callbackFunctionName);
					if (typeof callbackFunction == 'function') {
						callbackFunction(callbackArgs); 
					} 
				}
			}
        },

		onFailure: function (transport) {
		}

	});
}
// mouseover/mouseout for respect
function toggleRespectImg(divId, over) {
    var respectImgObj = document.getElementById('respectImg_'+divId);
    if (respectImgObj) {
        if (over == 'over') {
            respectImgObj.className = respectImgObj.className.replace('_active','_over');
        // state is ambiguous in this case
        } else if (over == 'inactive') {
            respectImgObj.className = respectImgObj.className.replace('_over','_inactive');
            respectImgObj.className = respectImgObj.className.replace('_active','_inactive');
        } else {
            respectImgObj.className = respectImgObj.className.replace('_over','_active');
        }
    }
}
// buy respect
function buyRespect(qty) {
	if (typeof showAlertPopup == 'function') {
		showAlertPopup('loading', 'Processing... please wait');
	}
	new Ajax.Request('ajax/respect_purchase.php', {
		method: 'get',
		parameters: { qty:qty },
		onSuccess: function (transport) {
			var response = transport.responseText.evalJSON();
			if (typeof showAlertPopup == 'function') {
				// on success, show a confirmation popup and update the qbucks balance displayed
				if (response.status == 'confirm') {
					showAlertPopup(response.status, response.message, 5000);
					debitQbuckBalance(response.amount);
				} else {
					showAlertPopup(response.status, response.message);
				}
			} else {
				// convert to old status type and show old-school popup message
				var oldStatus = (response.status == 'confirm') ? 'success' : response.status;
	            displayGenericPopupWide(oldStatus, response.message, 5000);
			}
		}
	});
}

// filter a newsfeed to show only one category of stuff
// targetID is the target container for the display - sport/team/league/member will be extracted from the id
// filterCategory is the category to show
// feedTable (optional) allows us to pull from the archive table instead of the main one (for the "see all" pages)
// startNum (optional) allows us to paginate on the "see all" pages
// numResults (optional) allows us to update the page nav on the "see all" pages
function ajaxFilterFeed(targetID, filterCategory, feedTable, startNum, numResults) {
	// get the member or the sport and team / league (optional) from the targetID
	// format is newsfeed_${sport_id}_${team_id}_${league_id} (team and league both optional)
	// or newsfeed_member_${member_id} or newsfeed_friends_${member_id}
	var paramArray = targetID.split('_');
	if (paramArray[1] == 'member' || paramArray[1] == 'friends') {
		var memberID = paramArray[2];
	} else {
		var sportID = paramArray[1];
		if (paramArray[2]) {
			var teamID = paramArray[2];
		}
		if (paramArray[3]) {
			var leagueID = paramArray[3];
		}
	}
	
	// blank out the current content so it looks like something is happening
	document.getElementById(targetID).innerHTML = '';
	
	// construct the url for the ajax call that queries the database
	var sUrl = 'ajax/feed_filter.php';
	var postString = 'filter=' + filterCategory;
	if (memberID) {
		postString += '&member_id=' + memberID;
		if (paramArray[1] == 'friends') {
			postString += '&friends=1';
		}
	} else {
		postString += '&sport_id=' + sportID;
		if (teamID) {
			postString += '&team_id=' + teamID;
		}
		if (leagueID) {
			postString += '&league_id=' + leagueID;
		}
	}
	if (feedTable == 'archive') {
		postString += '&archive=1';
	}
	if (startNum) {
		postString += '&s=' + startNum;
	}
	if (numResults) {
		postString += '&num_results=' + numResults;
	}
	//alert(postString);
	
	// making the call - this will update the target with the new content
	new Ajax.Updater(
		{ success: targetID },
		sUrl, {
			method: 'post',
			parameters: postString
		}
	);
}


// remove a feed item from the league display: update the display and call the ajax to do the backend work
function ajaxHideFeedItem(actionID, leagueID) {
	if (confirm('Are you sure you want to remove this item from displaying in the feed?')) {
		// hide the row
		toggleLayer('feed'+actionID, 'off');
		
		// now construct the url for the ajax call that updates the database
		var sUrl = 'ajax/feed_hide_item.php';
		var postString = 'action_id=' + actionID + '&league_id=' + leagueID;

		// making the call (no callback function)
		new Ajax.Request(sUrl, {
			method: 'post',
			parameters: postString
		});
	}
}

// remove a shared quiz: update the display and call the ajax to do the backend work
function removeSharedQuiz(quizID) {
	if (confirm('Are you sure you want to remove this quiz from your shared quizzes list?')) {
		// hide the row
		toggleLayer('quiz'+quizID, 'off');
		
		// now construct the url for the ajax call that updates the database
		var sUrl = 'ajax/remove_shared_quiz.php';
		var postString = 'quiz_id=' + quizID;

		// making the call (no callback function)
		new Ajax.Request(sUrl, {
			method: 'post',
			parameters: postString
		});
	}
}


// Rollover Profile Popup


  // find position of a html element
	function findPos(obj) {
        var curleft = curtop = 0;
		var curscrolltop = curscrollLeft = 0;
		obj2 = obj;
		while(obj2 != document.body)
		{
			curscrolltop += obj2.scrollTop;
			curscrollLeft += obj2.scrollLeft;
			obj2 = obj2.parentNode;
		}
		while (obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
		return {x:curleft-curscrollLeft, y:curtop-curscrolltop};
        
	}
	
  // Get the size (width and height) of the current page
	function getPageSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' )
	{
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  }
	else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
	{
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return {width: myWidth, height:myHeight};
}

// get the scroll Position (x and y)
function getScrollPosition() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return { x:scrOfX, y:scrOfY };
}

	var profilePopupAjaxObject = {
		connectionObj : null,
		handleSuccess:function(o){
			if(isMouseStillOver)
			{
				
				document.getElementById("popupProfilePic").src = CDNBaseUrl + "img/spacer.gif";
	
				try {
					//alert(o.responseText);
					var requestedMember = YAHOO.lang.JSON.parse(o.responseText);
	
					var teams = "";
                    var teamCounter = 0;
					for(i=0;i<requestedMember.teams.length;i++)
					{
						if( requestedMember.teams[i].teamLogo != "" )
						{
							if (requestedMember.teams[i].teamPointRank > 0)
                            {
                                teams += '<div style="border:1px solid #D90000;float:left;margin-right:10px;margin-bottom:5px;width:48px;"><div style="background-color:#D90000;color:#fff;text-align:center;font-size:9px;">#' + requestedMember.teams[i].teamPointRank + ' Fan</div><img src="' + requestedMember.teams[i].teamLogo + '" /></div>';
                            }
                            else
                            {
                                teams += "<img src='" + requestedMember.teams[i].teamLogo + "'  style='float:left;margin-right:10px;margin-bottom:5px;'/>";
						    }
                            teamCounter++;
                            if (teamCounter % 4 == 0)
                                teams += '<br clear="all" />';
                        }
					}
					//alert(o.argument.element.offsetTop);
					//alert(o.argument.element.offsetLeft);
					document.getElementById("popupScreenName").innerHTML = requestedMember.username;
					document.getElementById("popupProfilePic").src = requestedMember.profilePicUrl;
					document.getElementById("popupBucks").innerHTML = requestedMember.bucks;
					document.getElementById("popupRespect").innerHTML = requestedMember.respect;
					document.getElementById("popupContributions").innerHTML = requestedMember.contributions;
					document.getElementById("popupName").innerHTML = requestedMember.firstname + ' ' + requestedMember.lastname;
					document.getElementById("popupGenderAndAge").innerHTML = requestedMember.gender + (requestedMember.gender=="" || requestedMember.age==""?"":", ")+ requestedMember.age ;
					document.getElementById("popupLocation").innerHTML = requestedMember.city + (requestedMember.city=="" || requestedMember.country==""?"":", ")+requestedMember.country;
					document.getElementById("popupFavoriteTeams").innerHTML = teams;

					document.getElementById("popupThought").innerHTML = requestedMember.thoughtOfDay;
                    if (requestedMember.teamLeaderLogos.length == 0) {
						document.getElementById("popupTeamLeadership").style.display = "none";
                    } else {
						document.getElementById("popupTeamLeadership").style.display = "block";
						document.getElementById("popupTeamLeaderLogos").innerHTML = "&nbsp;";   
                        for(i=0; i<requestedMember.teamLeaderLogos.length; i++) {
                            document.getElementById("popupTeamLeaderLogos").innerHTML +=
                            '<img src="' + requestedMember.teamLeaderLogos[i] + '" class="mrgR10" />';
                        }
                    }
					if( requestedMember.moderatorBadge == "" && requestedMember.writerBadge == "" )
					{
						document.getElementById("popupLeadership").style.display = "none";
					}
					else
					{
						document.getElementById("popupLeadership").style.display = "block";
						document.getElementById("popupLeaderBadge").innerHTML = "&nbsp;";
					}
					if( requestedMember.moderatorBadge != "" )
					{
						document.getElementById("popupLeaderBadge").innerHTML =
							"<img src='" + requestedMember.moderatorBadge + "' style='display:inline;padding-right:10px;'/>";
					}
					if( requestedMember.triviaBadge != "" )
					{
						document.getElementById("popupLeaderBadge").innerHTML += 
							"<img src='" + requestedMember.triviaBadge + "' style='display:inline;padding-right:10px;'/>";
						
					}
					if( requestedMember.welcomeBadge != "" )
					{
						document.getElementById("popupLeaderBadge").innerHTML += 
							"<img src='" + requestedMember.welcomeBadge + "' style='display:inline;padding-right:10px;'/>";
						
					}
					if( requestedMember.writerBadge != "" )
					{
						document.getElementById("popupLeaderBadge").innerHTML += 
							"<img src='" + requestedMember.writerBadge + "' style='display:inline;padding-right:10px;'/>";
						
					}
					var containerObj = document.getElementById("navigationContainer");
					var containerPosition = findPos(containerObj);
					var containerLimitRight = containerPosition.x + containerObj.clientWidth;
					var containerLimitBottom = containerPosition.y + containerObj.clientHeight;
					
					var pageSize = getPageSize();
					var scrollPosition = getScrollPosition();
					var pageLimitRight = pageSize.width + scrollPosition.x;
					var pageLimitBottom = pageSize.height + scrollPosition.y;
					
					var limitRight = Math.min(pageLimitRight, containerLimitRight);
					var limitBottom = pageLimitBottom;
	
					var popupObj = document.getElementById("profilePopup");
					var popupArrowObj = document.getElementById("popupArrow");

					// Calculate position before showing
					popupArrowObj.style.visibility = popupObj.style.visibility = "hidden";
					popupArrowObj.style.display = popupObj.style.display = "block";

                    var rollOverElement = o.argument.element;
					var rollOverPosition = findPos(rollOverElement);
					
					var withinRightBorder = rollOverPosition.x + rollOverElement.offsetWidth + popupObj.clientWidth + popupArrowObj.clientWidth < limitRight;
					var withinBottomBorder = rollOverPosition.y + popupObj.clientHeight < limitBottom;
	
					var popupArrowDirectionX = (withinRightBorder)? "w"  : "e";
					var popupArrowDirectionY = (withinBottomBorder)? "n" : "s";
					popupArrowObj.src = CDNBaseUrl + "img/popup_arrow2_"+popupArrowDirectionY+popupArrowDirectionX+".png";
	
					var popupArrowX = (withinRightBorder)? rollOverPosition.x + rollOverElement.offsetWidth : rollOverPosition.x - popupArrowObj.clientWidth;
					var popupArrowY = (withinBottomBorder)? rollOverPosition.y : rollOverPosition.y - popupArrowObj.clientHeight;
					var popupX = (withinRightBorder)? popupArrowX + popupArrowObj.clientWidth-2  : popupArrowX - popupObj.clientWidth +6;
					var popupY = (withinBottomBorder)? rollOverPosition.y - 10: rollOverPosition.y - popupObj.clientHeight + 10;
					
					popupArrowObj.style.left = popupArrowX+"px";
					popupArrowObj.style.top = popupArrowY+"px";
					popupObj.style.left = popupX + "px";
					popupObj.style.top = popupY + "px";
	
	
					popupArrowObj.style.visibility = popupObj.style.visibility = "visible";
					
				}
				catch (e) {
					// oops error parsing requested member
					alert(e);
				}
			}
		},
	
		handleFailure:function(o){
			// Failure handler
		},
	
		processResult:function(o){
			// This member is called by handleSuccess
		},
	
		startRequest:function(userId, usernameUrl) {
			if(userId)
			{
				this.connection = YAHOO.util.Connect.asyncRequest('GET', 'ajax/profile_popup.php?g_member_id='+userId, callback, null);
			}
			else if (usernameUrl)
			{
				this.connection = YAHOO.util.Connect.asyncRequest('GET', 'ajax/profile_popup.php?g_username_url='+usernameUrl, callback, null);				
			}
		}

	};
	var callback =
	{
		success:profilePopupAjaxObject.handleSuccess,
		failure:profilePopupAjaxObject.handleFailure,
		argument: new Object(),
		scope: profilePopupAjaxObject
	};
	
var timeoutHandle = null;
var ajaxCachingParameter = (new Date()).getTime();
var isMouseStillOver = false;

function popProfile(evt,userId, usernameUrl, targetSpecial)
{
	isMouseStillOver = true;
	if(timeoutHandle)
	{
		clearTimeout(timeoutHandle);
		timeoutHandle = null;
	}
	ajaxinProgress = YAHOO.util.Connect.isCallInProgress(profilePopupAjaxObject.connection); 
	if(ajaxinProgress)
	{
		YAHOO.util.Connect.abort(profilePopupAjaxObject.connection);
	}
    if (targetSpecial) {
        targetElement = document.getElementById(targetSpecial);
    } else {
    	targetElement=  evt.srcElement ? evt.srcElement : evt.target;
	}
    //var targetElementPosition = findPos(targetElement);

	callback.argument =
		{
			element: targetElement
		};
		
	timeoutHandle = setTimeout("profilePopupAjaxObject.startRequest("+userId+",'"+ usernameUrl +"')",50);
}

function popProfileBadge( imgSrc, ele )
{
	var containerObj = document.getElementById("container");
	var containerPosition = findPos(containerObj);
	var containerLimitRight = containerPosition.x + containerObj.clientWidth;
	var containerLimitBottom = containerPosition.y + containerObj.clientHeight;
	
	var pageSize = getPageSize();
	var scrollPosition = getScrollPosition();
	var pageLimitRight = pageSize.width + scrollPosition.x;
	var pageLimitBottom = pageSize.height + scrollPosition.y;
	
	var limitRight = Math.min(pageLimitRight, containerLimitRight);
	var limitBottom = pageLimitBottom;
	
	var popupObj = document.getElementById("badgePopup");
	var popupArrowObj = document.getElementById("popupArrow");

	// Calculate position before showing
	popupArrowObj.style.visibility = popupObj.style.visibility = "hidden";
	popupArrowObj.style.display = popupObj.style.display = "block";

	var rollOverElement = ele;
	var rollOverPosition = findPos(rollOverElement);
	
	var withinRightBorder = rollOverPosition.x + rollOverElement.offsetWidth + popupObj.clientWidth + popupArrowObj.clientWidth < limitRight;
	var withinBottomBorder = rollOverPosition.y + popupObj.clientHeight < limitBottom;
	
	var popupArrowDirectionX = (withinRightBorder)? "w"  : "e";
	var popupArrowDirectionY = (withinBottomBorder)? "n" : "s";
	popupArrowObj.src = CDNBaseUrl + "img/popup_arrow2_"+popupArrowDirectionY+popupArrowDirectionX+".png";
	
	var popupArrowX = (withinRightBorder)? rollOverPosition.x + rollOverElement.offsetWidth : rollOverPosition.x - popupArrowObj.clientWidth;
	var popupArrowY = (withinBottomBorder)? rollOverPosition.y : rollOverPosition.y - popupArrowObj.clientHeight;
	var popupX = (withinRightBorder)? popupArrowX + popupArrowObj.clientWidth- 40  : popupArrowX - popupObj.clientWidth + 50;
	var popupY = (withinBottomBorder)? rollOverPosition.y - 10: rollOverPosition.y - popupObj.clientHeight + 10;
	
	//popupArrowObj.style.left = popupArrowX+"px";
	//popupArrowObj.style.top = popupArrowY+"px";
	popupObj.style.left = (popupX) + "px";
	popupObj.style.top = (popupY) + "px";
	
	//popupArrowObj.style.visibility = popupObj.style.visibility = "visible";
	badge = document.getElementById("badgePopup");
	badge.style.visibility = "visible";
	badge.style.background = "transparent url(" + imgSrc + ") center no-repeat";
	
	//document.getElementById("popupBadgeImg").src = imgSrc;
}

function hideProfileBadge()
{
	document.getElementById("badgePopup").style.visibility = "hidden";
	document.getElementById("popupArrow").style.visibility =  "hidden";
}

function hideProfilePopup()
{
	isMouseStillOver = false;
	clearTimeout(timeoutHandle);
	timeoutHandle = null;
	var popupObj = document.getElementById("profilePopup");
	var popupArrowObj = document.getElementById("popupArrow");

	popupObj.style.display = popupArrowObj.style.display = "none";
}


// Home Page hot links showing and hiding more news
var movedInHandle = null;
var movedOutHandle = null;
function showMoreNews()
{
	if(document.getElementById('moreNewsSummary').style.display == 'none')
	{
		movedInHandle=setTimeout("document.getElementById('moreNewsSummary').style.display = 'block';document.getElementById('moreHotlinks').style.display = 'none';",500);
	}
	else if(movedOutHandle)
	{
		clearTimeout(movedOutHandle);
		movedOutHandle = null;
	}
}

function hideMoreNews()
{
	if(document.getElementById('moreNewsSummary').style.display == 'block')
	{
		movedOutHandle=setTimeout("document.getElementById('moreNewsSummary').style.display = 'none';document.getElementById('moreHotlinks').style.display = 'block'",1000);
	}
	else if(movedInHandle)
	{
		clearTimeout(movedInHandle);
		movedInHandle = null;
	}
}

function showMoreNewsInfo(newsElement)
{
	newsElement.getElementsByTagName("div")[0].style.display="block";
}

function hideMoreNewsInfo(newsElement)
{
	newsElement.getElementsByTagName("div")[0].style.display="none";
}

function submitNewsLink(evt)
{
	evt.returnValue = false;
	if(confirm("You must be signed in to submit a link.  Please sign in."))
	{
		var target = evt.srcElement?evt.srcElement:evt.target;
		var newLocation = "/login.php?orig_url="+encodeURIComponent(target.href);
		location.href = newLocation;
	}
}

// Drop down Menu  
function appendString(str1, str2)
{
	return str1 + (str1==""?"":" ") + str2;
}

function removeString(str1, str2, str3)
{
	newStr = str1.indexOf(" "+str2) >= 0?str1.replace(" "+str2, str3):	str1.replace(str2, str3);
	
	return newStr;
}
function showDropdownMenu(menuObj)
{
	menuObj.className= appendString(menuObj.className, "rolledOver");
	menuObj.getElementsByTagName("div")[0].style.display = "block";
}

function hideDropdownMenu(menuObj)
{
	menuObj.className= removeString(menuObj.className, "rolledOver", "");
	menuObj.getElementsByTagName("div")[0].style.display = "none";
}

function GE(id)
{
    return document.getElementById(id);
}

function showTopMenuDropdown(id)
{
    document.getElementById(id).style.display = 'block';
}


// if the user is not logged in, alert them to login or register
// this should be turned into a nicer popup registration in the future 
function alertNoLogin(popupState, elementId)
{
	registrationShowOverlay();
}

function submitPickemQuickPick(gameId, selectedTeam, pickemUrl) {
	submitPickemQuickPick(gameId, selectedTeam, pickemUrl, false);
}
function submitPickemQuickPick(gameId, selectedTeam, pickemUrl, newWindow) {
    var sUrl = 'ajax/pickem_enter.php';
	var postString = "game_id="+gameId+"&gameType=pickem&pick="+selectedTeam;
    var pickemCallback =
    {
     success:handlePickemSuccess,
     failure:null
    };
    
	YAHOO.util.Connect.asyncRequest('POST', sUrl, pickemCallback, postString);
    
    function handlePickemSuccess() {
        if (!newWindow) {
        	document.location.href = pickemUrl;
        }
        else {
        	window.open(pickemUrl);
        }
    }
}
// mouseover/out for Talk module topic rows
function mouseOverTalkTopic(topicNum, toggleType)
{
    var section = document.getElementById('itemSection'+topicNum);
    var sectionBottom = document.getElementById('itemSectionBottom'+topicNum);
    var sectionIcon = document.getElementById('itemIcon'+topicNum);
    var readMore = document.getElementById('talkReadMore'+topicNum);
    var lastCommentUser = document.getElementById('talkLastCommentUsername'+topicNum);
    if (toggleType == 'over')
    {
        section.className += '_over';
        sectionBottom.className += '_over';
        if (sectionIcon) 
            sectionIcon.className += '_over';
        if (readMore)
            readMore.style.display = 'inline';
        if (lastCommentUser) 
            lastCommentUser.style.display = 'inline';
    }
    else
    {
        section.className = section.className.replace('_over', '');
        sectionBottom.className = sectionBottom.className.replace('_over', '');
        if (sectionIcon) 
            sectionIcon.className = sectionIcon.className.replace('_over', '');
        if (readMore)
            readMore.style.display = 'none';
        if (lastCommentUser) 
            lastCommentUser.style.display = 'none';
    }
}

// show or hide last comment - used for home page team talk section
function comment_get(id, lastCommentId, topic_id, content_type, reply_id, top_comment_id) {

	if (!topic_id && ! reply_id && strip_tags($('comments' + id).innerHTML) != 'Loading...') {
		return true;
	}
	if (!content_type) {
		content_type = null;
	}

	if (!topic_id) {
		topic_id = null;
	} else {
		if ($(id + 'See')) {
			$(id + 'See').update('<span class="cGrey4">Loading...</span>');
		}
	}
    if (! reply_id) {
        reply_id = null;
    }

	new Ajax.Request('ajax/comment.php', {
		method: 'get',
		parameters: { action: 'get', comment_id: lastCommentId, topic_id: topic_id, content_type: content_type, reply_id: reply_id, top_comment_id: top_comment_id, div_id: id },
		onSuccess: function (transport) {
			var response = transport.responseText.evalJSON();

			// : clear out all existing comments
			if (response.length > 1) {
				$('comments' + id).update();
                $('commentsTop' + id).hide();
			}

			for (var i =0, len = response.length; i < len; i++) {
                if (response[i].comment_type == 'top' || response[i].comment_type == 'first') {
                    $('commentsTop' + id).show();
                    $('commentsTop' + id).update(response[i].comment);
				} else if (strip_tags($('comments' + id).innerHTML) == 'Loading...') {
					$('comments' + id).update(response[i].comment);
				} else {
					$('comments' + id).innerHTML = $('comments' + id).innerHTML + response[i].comment;
				}
			}

			if (i > 1 && lastCommentId == null) {
				$(id + 'See').fade({duration: 0.4});
			}

			if (!$('comments' + id).visible()) {
				$('comments' + id).appear({duration: 0.4});
			}

		},

		onFailure: function (transport) {
			$('comments' + id).update('Error loading comment');
		}

	});
}

function comment_getLike(id, topic_id, type) {

	$(id).update('Loading...');

	new Ajax.Request('ajax/comment.php', {
		method: 'get',
		parameters: { action: 'likeGet', topic_id: topic_id, type: type },
		onSuccess: function (transport) {
			var response = transport.responseText.evalJSON();
			$(id).update(response.likes);
		},

		onFailure: function (transport) {
			alert('error with comment_getLike()');
		}

	});

}

function otherGet(id, game_id, type) {

	$(id).appear({duration: 0.3});
	$(id).update('Loading...');
    
	new Ajax.Request('ajax/comment.php', {
		method: 'get',
		parameters: { action: 'otherGet', game_id: game_id, type: type },
		onSuccess: function (transport) {
			var response = transport.responseText.evalJSON();
			$(id).update(response.others);
		},

		onFailure: function (transport) {
			alert('error with otherGet()');
		}

	});

}

function comment_addCheck(id, body, e, content_type, content_id, topic_id, spotlight) {

	if (window.event) {
		var keynum = window.event.keyCode;
	} else {
		var keynum = e.which
	}

	if (keynum == 13 && body != undefined && body != '' && body != 'Write a comment...') {
		comment_add(id, content_type, content_id, topic_id, spotlight);
	}

	return true;
}

function comment_addFocus(thisid, id, buttonid, contentType, contentId, spotlight) {
    var defaultText = ($('defaultText' + id)) ? $('defaultText' + id).value : '';
    var sl = (spotlight == true) ? 'a' : '';

	if ($(thisid).value == 'Write a comment...' || $(thisid).value == defaultText) {
		$(thisid).value = '';
	}

	$(thisid).className = 'talkCommentInput talkCommentInputActive';
	$(thisid).style.height = '50px';
	$(buttonid).show();
    // figure out whether or not to show the comment subscribe checkbox, and if so, what its default state should be
    if ($('commentSubscribe' + id + sl).style.display == 'none') {
        new Ajax.Request('ajax/comment_subscribe.php', {
    		method: 'get',
    		parameters: { action:'check', contentType:contentType, contentId:contentId },
    		onSuccess: function (transport) {
    			var response = transport.responseText.evalJSON();
                if (response.showCheckbox == 'show') {
                    $('commentSubscribe' + id + sl).style.display = 'block';
                    if (response.showCheckboxChecked == 1) {
                        $('commentSubscribeCheckbox' + id + sl).checked = true;
                    }
                }
    		}    
    	});
    }
}

function comment_addBlur(thisid, id, buttonid, forceBlur, spotlight) {
    var sl = (spotlight == true) ? 'a' : '';
    if ( $('checkboxState' + id + sl) && $('checkboxState' + id + sl).value == 1 ) return;
    
    var defaultText = ($('defaultText' + id)) ? $('defaultText' + id).value : '';
	if (forceBlur || $(thisid).value == '' || $(thisid).value == 'Adding comment...') {
		$(thisid).value = (defaultText) ? defaultText : 'Write a comment...';
		$(thisid).className = 'talkCommentInput cGrey4';
		$(thisid).style.height = '15px';
		$(buttonid).hide();
        $('commentSubscribe' + id + sl).style.display = 'none';
	}

}

function comment_add(id, content_type, content_id, topic_id, spotlight) {

	var sl = '';
	if (spotlight == true) {
		sl = 'a';
	}

	var body = $(id).value;
	var general_id = id.replace('addInput' + sl,'').replace('comment','');
    var reply_id = ($('replyId' + general_id + sl).value) ? $('replyId' + general_id + sl).value : null ;
    var comment_subscribe = ($('commentSubscribeCheckbox' + general_id + sl).checked) ? 1 : 0;

	$(id).className = 'talkCommentInput cGrey4';
	$(id).value = 'Adding comment...';

	if (strip_tags($('comments' + general_id + sl).innerHTML) == 'Loading...') {
		$('comments' + general_id + sl).update();
	}

	new Ajax.Request('ajax/comment.php', {
		method: 'get',
		parameters: { action: 'add', content_type: content_type, content_id: content_id, topic_id: topic_id, comment: body, reply_id: reply_id, comment_subscribe: comment_subscribe },
		onSuccess: function (transport) {
            
            var button_id = 'commentButton' + general_id + 'add' + sl;
			comment_addBlur(id, general_id, button_id, true, spotlight);

			var response = transport.responseText.evalJSON();

			$('comments' + general_id + sl).update($('comments' + general_id + sl).innerHTML + response[0].comment);
			$('comments' + general_id + sl).show();
			$('comments' + general_id + 'addTop' + sl).show();
			
		},

		onFailure: function (transport) {
			$('comments' + general_id + sl).update('Error loading comment');
		}

	});

}

function game_watch(game_id, go) {

	if (go) {
		var action = 'go';
	} else {
		var action = 'watch';
	}

	new Ajax.Request('ajax/comment.php', {
		method: 'get',
		parameters: { action: action, game_id: game_id },
		onSuccess: function (transport) {

			var response = transport.responseText;
			if (!response) {
				alert('error w/ watch();');
			}
		},
		onFailure: function (transport) {
				alert('error w/ watch();');
		}

	});

}


function strip_tags(input, htmlOnly) {

	input = input.replace(/(<([^>]+)>)/ig,""); 

	if (htmlOnly == 1) {
		return input;
	}

	input = input.replace(/^\s+|\s+$/g, "");
	input = input.replace(/\t|\r|\n/g, "");
	return input;
}



	function showNewMembersRising(base)
	{
		var rand = Math.floor(Math.random()*3); //every time this is run it will add betweem 1 and 10
		var rand2 = 0 //Math.floor(Math.random()*1000); //this way the number will be always be less than what is actually in the DB
		var rand3 = 750; //700 + Math.floor(Math.random()*500); //randomly find ms between 700-1200 ms 
		var users = base - rand2 + rand;
	var el = document.getElementById('nruCount');
	if(el)
	{
		el.innerHTML = 'Over ' + addCommas(users) + ' Users And Counting!';
	}
	var funcStr = "showNewMembersRising(" + (users - rand2) + ")";
	t=setTimeout(funcStr,750);

}
	function addCommas(nStr)
	{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
	}

    
// update a team take
function updateTeamTake(teamId, defaultValue) 
{
	var myTake = document.getElementById('myTake'+teamId);
    var newTake = myTake.value;
    
    // don't allow the default value to be submitted
    if (newTake == defaultValue || newTake == '')
        return false;
        
    // construct the url for the ajax call that updates the database
	var sUrl = 'ajax/profile_thought.php';
	var postString = 'team_id=' + teamId + '&thought=' + newTake;
	
	// make the call (no callback function)
	YAHOO.util.Connect.asyncRequest('POST', sUrl, null, postString);
    
    // update the current take and date
    var currentTake = document.getElementById('myTakeCurrent'+teamId);
    if (currentTake)
    {
        currentTake.innerHTML = newTake;
    }
    var takeDate = document.getElementById('myTakeDate'+teamId);
    if (takeDate)
    {
        var currentTime = new Date();
        takeDate.innerHTML = (currentTime.getMonth() + 1) + '/' + currentTime.getDate() + '/' + currentTime.getFullYear();
    }        
    
    // reset the take input field
    myTake.value = defaultValue;
    myTake.style.color = '#BEC5D4';
    var charsLeft = document.getElementById('myTakeCharsLeft'+teamId);
    if (charsLeft)
    {
        charsLeft.innerHTML = '140';
    }               

    // change the button to the inactive state
    var updateButton = document.getElementById('btnUpdateTake'+teamId);
    if (updateButton)
    {
        updateButton.className = updateButton.className.replace(/(_inactive|_over)/, '');
        updateButton.className += '_inactive';
    }
    
    return;
}

// update the member's take using the module in the fan feed
function updateFeedTake(defaultValue)
{	   
    // setup for the ajax call
    var feedTakeAjaxObject = {
        connectionObj : null,
        handleSuccess:function(o){
            //alert(o.responseText);
            // the response will contain the formatted block with the new take to prepend to the feed
            var responseData = YAHOO.lang.JSON.parse(o.responseText);
            if (responseData.content)
            {
                //document.getElementById('followFeedContainer').innerHTML += responseData.content;
                var currentContent = document.getElementById('followFeedContainer').innerHTML;
                $('followFeedContainer').update(responseData.content + currentContent);
            }
            // change the input area back to the default state
            document.getElementById('feedTakeInput').value = defaultValue;
            document.getElementById('feedTakeInput').className += '_inactive';
            document.getElementById('feedTakeSubmitButton').className = document.getElementById('feedTakeSubmitButton').className.replace('_inactive', '');
            document.getElementById('feedTakeCharCounter').innerHTML = '140';
            document.getElementById('feedTakeCharCounter').style.display = 'none';
            
        },
        handleFailure:function(o){
        // Failure handler
        },
        startRequest:function(teamId, myTake) {
            // sumbit button changes to inactive state; char counter changes to "loading" image
            document.getElementById('feedTakeSubmitButton').className = document.getElementById('feedTakeSubmitButton').className.replace('_over', '_inactive');
            document.getElementById('feedTakeCharCounter').innerHTML = '<img src="' + CDNBaseUrl + 'img/loader_grey_onwhite.gif" height=16 width=16 />';
            
            // construct the url for the ajax call that updates the database and fetches the results
        	var sUrl = 'ajax/profile_thought.php';
        	var postString = 'team_id=' + teamId + '&thought=' + myTake + '&show_feed=Y';
	        this.connection = YAHOO.util.Connect.asyncRequest('POST', sUrl, feedTakeCallback, postString);
        }
    };
    var feedTakeCallback =
    {
        success:feedTakeAjaxObject.handleSuccess,
        failure:feedTakeAjaxObject.handleFailure,
        argument: new Object(),
        scope: feedTakeAjaxObject
    };
    
    var teamId = document.getElementById('feedTakeTeamId').value;
    var myTake = document.getElementById('feedTakeInput').value;
    
    // don't allow the default value to be submitted
    if (myTake == defaultValue || myTake == '')
        return false;

    feedTakeAjaxObject.startRequest(teamId, myTake);    

}


function intervalGameClock(id) {
	setInterval(function() { updateGameClock(id); }, 1000);
}

function updateGameClock(id) {

	var time = $('gameClock' + id).innerHTML;
	var values = time.split(",");
	var min = values[0].replace(" min", '');
	var sec = values[1].replace(" sec", '');

	if (sec == 0) {
		min--;
		sec = 59;
	} else {
		sec--;
	}

	$('gameClock' + id).update(min + ' min, ' + sec + ' sec');
}

function addLoadEvent(func) { 
	var oldonload = window.onload; 
	if (typeof window.onload != 'function') { 
		window.onload = func; 
	} else { 
		window.onload = function() { 
		if (oldonload) { 
			oldonload(); 
		} 
			func(); 
		} 
	} 
} 


// send a follower request, or add follower; give popup confirmation
// memberId is the ID of the member you want to follow, or 'all' if you want to follow all members in a content area
// username is their username (for the popup confirmation) - if false, no confirmation needed
// buttonName is name of the element that will be hidden if the request is successful (optional)
// contentType is the content area if following all memmbers in an area
function followMember(memberId, username, buttonName, contentType)
{
    // setup for the ajax call
    var followMemberAjaxObject = {
        connectionObj : null,
        handleSuccess:function(o){
            //alert(o.responseText);
            var responseData = YAHOO.lang.JSON.parse(o.responseText);
            if (responseData.message)
                alert(responseData.message);
            // turn off the button(s) if applicable - using classname instead of id allows us to turn off multiple buttons per page
            if (buttonName)
            {
                var buttons = YAHOO.util.Dom.getElementsByClassName(buttonName);
                for(i=0; i<buttons.length; i++)
                {
                    buttons[i].style.display = 'none';
                }
            }
        },
        handleFailure:function(o){
        // Failure handler
        },
        startRequest:function() {
            var queryString = 'id='+memberId;
            if (contentType) queryString += '&content_type='+contentType;
            this.connection = YAHOO.util.Connect.asyncRequest('GET', 'ajax/follow_member.php?'+queryString, followMemberCallback, null);
        }
    };
    var followMemberCallback =
    {
        success:followMemberAjaxObject.handleSuccess,
        failure:followMemberAjaxObject.handleFailure,
        argument: new Object(),
        scope: followMemberAjaxObject
    };
    
    if (! isLoggedIn)
	{
		registrationShowOverlay();
	}
    else
    {
        if (username === false)
            followMemberAjaxObject.startRequest();   
        else if (confirm('Do you want to follow ' + username + '\'s updates?  Updates will appear on your home page in the "Fans I Follow" feed.'))
            followMemberAjaxObject.startRequest();
    }
}

// remove the given member from the list of members you are following
// memberId is the ID of the member you want to un-follow, or 'all' if you want to un-follow all members in a content area
// userType is the type of user (default faniq)
// username is their username (for the popup confirmation) - if false, no confirmation needed
function unFollowMember(memberId, userType, username)
{
    // setup for the ajax call
    var unFollowMemberAjaxObject = {
        connectionObj : null,
        handleSuccess:function(o){
            //alert(o.responseText);
            var responseData = YAHOO.lang.JSON.parse(o.responseText);
            if (responseData.status == 'success' && responseData.message)
                responseData.message += username;
            if (responseData.message)
                alert(responseData.message);
            // hide any records for this user
            var authorDivName = 'followTopicAuthor'+memberId+userType;
            var contentDivs = YAHOO.util.Dom.getElementsByClassName(authorDivName, 'div');
            if (responseData.status == 'success' && contentDivs.length > 0)
            {
                for(i=0; i<contentDivs.length; i++)
                {
                    contentDivs[i].style.display = 'none';
                }
                // also hide the user's photo if applicable
                if (document.getElementById('followFavPhoto'+memberId))
                    document.getElementById('followFavPhoto'+memberId).style.display = 'none';
                // decrease the # of fans I'm following
                if (document.getElementById('followFanCount'))
                {
                    var fanCount = document.getElementById('followFanCount').innerHTML;
                    document.getElementById('followFanCount').innerHTML = parseInt(fanCount) - 1;
                }
            }
        },
        handleFailure:function(o){
        // Failure handler
        },
        startRequest:function() {
            var queryString = 'id='+memberId+'&user_type='+userType;
            this.connection = YAHOO.util.Connect.asyncRequest('GET', 'ajax/unfollow_member.php?'+queryString, unFollowMemberCallback, null);
        }
    };
    var unFollowMemberCallback =
    {
        success:unFollowMemberAjaxObject.handleSuccess,
        failure:unFollowMemberAjaxObject.handleFailure,
        argument: new Object(),
        scope: unFollowMemberAjaxObject
    };
    
    if (! isLoggedIn)
	{
		registrationShowOverlay();
	}
    else
    {
        // only valid user types are faniq and external - default to faniq if not provided
        if (! userType || userType != 'external')
            userType = 'faniq';
        if (username === false)
            unFollowMemberAjaxObject.startRequest();
        else if (confirm('Are you sure you want to stop following ' + username + '?'))
            unFollowMemberAjaxObject.startRequest();
    }
}

// get records for the follower feed and append to the main follower feed container
// followFeedStartIndex is a global var that needs to be set in the main page
function getFollowFeed(numResults, feedType, feedMemberId)
{    
    // setup for the ajax call
    var getFollowFeedAjaxObject = {
        connectionObj : null,
        handleSuccess:function(o){
            //alert(o.responseText);
            var responseData = YAHOO.lang.JSON.parse(o.responseText);
            if (responseData.content)
            {
                //document.getElementById('followFeedContainer').innerHTML += responseData.content;
                var currentContent = document.getElementById('followFeedContainer').innerHTML;
                $('followFeedContainer').update(currentContent + responseData.content);
            }
            if (responseData.hideShowMore == 1)
                document.getElementById('followFeedShowMore').style.display = 'none';
            else
                followFeedStartIndex += numResults;
        },
        handleFailure:function(o){
        // Failure handler
        },
        startRequest:function() {
            var queryString = 'startNum='+followFeedStartIndex+'&numResults='+numResults;
            // feedType and feedMemberId are optional
            if (feedType) queryString += '&feedType='+feedType;
            if (feedMemberId) queryString += '&feedMemberId='+feedMemberId;
            this.connection = YAHOO.util.Connect.asyncRequest('GET', 'ajax/get_follow_feed.php?'+queryString, getFollowFeedCallback, null);
        }
    };
    var getFollowFeedCallback =
    {
        success:getFollowFeedAjaxObject.handleSuccess,
        failure:getFollowFeedAjaxObject.handleFailure,
        argument: new Object(),
        scope: getFollowFeedAjaxObject
    };
    
    getFollowFeedAjaxObject.startRequest();
}

// load the given team feed (home page)
function getTeamFeed(teamId) {
    // change the active tab - teamIdActive is a global var
    oldTeamId = teamIdActive;
    teamIdActive = teamId;
    
    document.getElementById('teamTab'+oldTeamId).className = 'teamTabInactive';
    document.getElementById('teamTab'+teamIdActive).className = 'teamTabActive';
    
    $('teamFeedContainer'+oldTeamId).hide();
    
    // if the team container already exists, just show it
    if (! $('teamFeedContainer'+teamIdActive).empty()) {
        $('teamFeedContainer'+teamIdActive).show();
    
    // otherwise, load the new team data
    } else {
        $('teamFeedLoading').show();   
        
        new Ajax.Request('ajax/get_team_feed.php', {
    		method: 'get',
    		parameters: { teamId:teamId },
    		onSuccess: function (transport) {
    			var response = transport.responseText.evalJSON();
                $('teamFeedLoading').hide();
                $('teamFeedContainer'+teamIdActive).show();
    			$('teamFeedContainer'+teamIdActive).update(response.content);
    		},
    
    		onFailure: function (transport) {
                $('teamFeedLoading').hide();
                $('teamFeedContainer'+teamIdActive).show();
    			$('teamFeedContainer'+teamIdActive).update('Error loading feed');
    		}
    
    	});
    }
}

// show the given overlay using the Lightview JS lib
function showLightviewOverlay(overlayId) {
    document.observe('lightview:loaded', function() {
        Lightview.show({
            href: overlayId,
            rel: 'inline',
            options: {
                autosize: true,
                closeButton: 'large',
                overlayClose : false
            }
        });
    });
}

// subscribe to receive comment notifications for the given piece of content
function commentSubscribe(contentTypeId) {
    new Ajax.Request('ajax/comment_subscribe.php', {
		method: 'get',
		parameters: { action: 'subscribe', contentTypeId: contentTypeId },
        onSuccess: function() { Lightview.hide(); }
    });
}


/**
 * Detects if browser is IE7
 */
function isIE7() {
    var browser = navigator.appName;
    var bVersion = navigator.appVersion;
    //alert (browser);
    //alert (bVersion);
    if (browser == 'Microsoft Internet Explorer' && bVersion.indexOf('MSIE 7.0') > -1) {
        return true;
    } else {
        return false;
    }
}

/**
 * challenging people to quick fantasy games, it's used on profile page, so I 
 * have to define it in this file.
 * @param memberId
 * @return
 */
function quickChallenge(memberId) {
	$jq = jQuery.noConflict();
	$jq.getJSON('ajax/fantasy2/getCurrentChallenge.php',
		function(result) {
			url = "/fantasy?pickPlayers&s=" + result.sportId + "&gameId=" + result.contestId + "&action=createMatch" + 
                "&friendId=" + memberId + "&privateGame=1&isFacebookOpp=0";  
           	window.location = url;
        }
	);	
}