/*
* common js funcs used throughout site

Contains:
toggleVisibility for invisible/showing elements by id
toggleDisplay for hiding/displaying elements by id
getElementsByClassName returns array of all elements with given classname
ajaxRequest(msgData,postUrl,target,callbackFunc) for generic ajax requests; must provide own callbackFunc
giveMeWindowSize(whichOne) pass args "width" or "height" and will get pixel value


*/
var browserName=navigator.appName;
var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
var browserVersion=parseInt(navigator.appVersion); 
var appName = navigator.appCodeName;
if(navigator.userAgent.indexOf("Firefox")!=-1){
var versionindex=navigator.userAgent.indexOf("Firefox")+8
if (parseInt(navigator.userAgent.charAt(versionindex))>=1)
browserName = "Firefox";
}
if(navigator.userAgent.indexOf("Safari")!=-1){
browserName = "Safari";
}


function toggleNavMenu(whichOne)
	{
	$("#drop-down-"+whichOne).toggle();
	}


$(document).ready(function() {
						   
						   

		$("#top-nav-search #searchterm").focus(function(){
			if($(this).val()=="search"){$(this).val("");}
		});
		$("#top-nav-search #searchterm").blur(function(){
			if($(this).val()==""){$(this).val("search");}
		});
	
		$("body").css("background-image","url(/assets/bg/background_bottom-2009.gif)")

		//for nav
		$("#your-kids-global-nav-your-kids-baby").load("/modules/centerpage-kids/index.jhtml",{itemID:"10039",location:"nav"});
		$("#your-kids-global-nav-your-kids-toddler").load("/modules/centerpage-kids/index.jhtml",{itemID:"10040",location:"nav"});
		$("#your-kids-global-nav-your-kids-kid").load("/modules/centerpage-kids/index.jhtml",{itemID:"10042",location:"nav"});
		$("#your-kids-global-nav-your-kids-preschooler").load("/modules/centerpage-kids/index.jhtml",{itemID:"10041",location:"nav"});
		$("#your-kids-global-nav-your-kids-tween-teen").load("/modules/centerpage-kids/index.jhtml",{itemID:"10037",location:"nav"});

});



//frame burster
if (parent.frames.length > 0) {
    parent.location.href = self.document.location
}

// set contents for either nameTag or nameTagBG divs 
function wrapTxt(txt, len) {
	var L = len; //max chars per line
	if(txt.length > L) {
		if(txt.length < L + 3) {
			txt = txt.substring(0,L-2) + "<br/>" + txt.substring(L-2);
		} else {
			txt = txt.substring(0,L) + "<br/>" + txt.substring(L, txt.length);
		}
	}
	return txt;
}

/* Name Tag Email Pop-Up */
function nameTagEmail (t) {
	if ( $("#loginForm").css("display") === "block" || $(t).parents("#qodFormBegins")) {
		liForm = $(t).parents("#userLoginForm");
		checkEmail('#loginName', '#emailPopUpBg', '', liForm);
	} else {
		$("#emailPopUpBg").fadeOut(1500);
	}
}

/* Validate Email Structure */
function isEmail(s){
	var emailEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return emailEx.test(s);
}


/* Validate Email Address */
function checkEmail(id, show, msgTarget, tel){ 

	var inputText = $(tel).find(id).val();
	var inputWidth = $(tel).find(id).width();
	
	
	if ( isEmail( inputText.replace(/^\s+|\s+$/g, '') ) ) {
		$(tel).find(id).css("backgroundColor", "#FFF");
		
		if( show != "" && show != null ) {
			clearTimeout(t);
			$(show).fadeOut(1500);
		}
		
		if (msgTarget != "" &&  msgTarget != null){
			$(msgTarget).html("");
		}
	} else if ( inputText != "" && inputText != null ){
		if (msgTarget != "" && msgTarget != null){
			$(msgTarget).html("Please sign in with an email address.");
		}
		
		$(tel).find(id).css({
			"background-color" : "#FFDFDF",
			"border" : "1px solid #A7A6AA",
			"height" : "18px",
			"padding-left" : "2px"
		});
		
		if( show != "" && show != null ) {
			$(show).fadeIn(1500);
			t = setTimeout(function(){$('#emailPopUpBg').fadeOut(1500);},15000);
		}
		
		return false;
	}else{
		return false;
	}
}



function toggleVisibility(idName)
	{
	if(document.getElementById(idName).style.visibility=="hidden")
		{
		document.getElementById(idName).style.visibility="visible";
		} else {
		document.getElementById(idName).style.visibility="hidden";
		}
	}

	
/* COMMUNITY FUNCTIONS */

function showGroupsBoards(moduleName){
	if ( moduleName === "groups" ) {
		$(".hsn_groups").addClass("hsn_groups_onState");
		$(".hsn_comBoards").removeClass("hsn_comBoards_onState");
		
		$("#groupsHeader").css("background", "url(/assets/community/tab_comm_grp_ON.gif) no-repeat -2px 0px");
		$("#messageBoardsHeader").css("background", "url(/assets/community/tab_comm_msg_OFF.gif) no-repeat");
		$("#groupsHeadder").css("display", "block");
		$("#groupsFooter").css("display", "block");
		$("#groupList").css("display", "block");
		$("#boardsHeadder").css("display", "none");
		$(".module_middle").css("display", "none");
		$(".module_bottom").css("display", "none");
		
	} else if ( moduleName === "messageBoard" ) {
		$(".hsn_groups").removeClass("hsn_groups_onState");
		$(".hsn_comBoards").addClass("hsn_comBoards_onState");
		
		$("#groupsHeader").css("background", "url(/assets/community/tab_comm_grp_OFF.gif) no-repeat -2px 0px");
		$("#messageBoardsHeader").css("background", "url(/assets/community/tab_comm_msg_ON.gif) no-repeat");
		$("#groupsHeadder").css("display", "none");
		$("#groupList").css("display", "none");
		$("#groupsFooter").css("display", "none");
		$("#boardsHeadder").css("display", "block");
		$(".module_middle").css("display", "block");
		$(".module_bottom").css("display", "block");
	}
}


/* Check input to see if it equals the defalut value */
function checkInput(id, chkValue){
	if( document.getElementById(id).value === chkValue){
		alert("You must enter a keyword!");
		return false;
	}
}

	
function toggleDisplay(idName) 
	{
	if(document.getElementById(idName).style.display=="")
		{
		document.getElementById(idName).style.display="none";
		} else {
		document.getElementById(idName).style.display="";
		}
	}
	
	
/* Clear Input */
function clearInput(id, text){
	if ( text != "" && text != null ) {
		if ( document.getElementById(id).value == text ) {
			document.getElementById(id).value = "";
		}
	} else if ( document.getElementById(id).value != "" && document.getElementById(id).value != null ) {
		document.getElementById(id).value = "";
	}
}

function defaultInput(id, text){
	if ( document.getElementById(id).value === "" && document.getElementById(id).value != null ) {
		document.getElementById(id).value = text;
	}
}
	
	
function reportAbuse(e,reportAbuseType,boardID,threadID,messageID,reportUserID,reportUsername){
	var ra = document.getElementById('reportAbuse');
	if(ra.style.display==""){
		ra.style.display="none";
		if(document.getElementById('sortBySelected_bottom')){
			document.getElementById('sortBySelected_bottom').style.display="";
		}
		if(document.getElementById('sortBySelected_top')){
			document.getElementById('sortBySelected_top').style.display="";
		}
	} else {
		if(document.getElementById('sortBySelected_top')){
			document.getElementById('sortBySelected_top').style.display="none";
		}
		
		if(document.getElementById('sortBySelected_bottom')){
			document.getElementById('sortBySelected_bottom').style.display="none";
		}
		
		ra.style.display="";
		ra.style.left= getMouseXPos(e)+"px"; //-203
		ra.style.top= getMouseYPos(e)+"px"; //+10
		
			
		//populate form elements...
		var formy = document.getElementById("ReportAbuseForm");
		formy.reportAbuseType.value = reportAbuseType;
		formy.linkUrl.value = document.location.href;
		formy.boardID.value = boardID;
		formy.threadID.value = threadID;
		formy.messageID.value = messageID;
		formy.reportUserID.value = reportUserID;
		formy.reportUsername.value = reportUsername;
	}
}

function redirectUser(){
	var curLoc = document.location.href;
	
	/* Find ? params to be removed */
	var lastQes = curLoc.indexOf("?");
	var newLoc = curLoc.substr(0, lastQes);
	if (lastQes != -1) {
		document.location="/me/blockPage.jhtml?returnPage="+newLoc;
	} else {
		document.location="/me/blockPage.jhtml?returnPage="+curLoc;
	}
}


//function loginBalloon(win){
function requiredLogin(win,align)
	{
	var hoverPosition = $(win).offset();
	var leftOffset = 0;
	var topOffset = 0;
	if(align=="left")
		{
		leftOffset = hoverPosition.left-10;
		topOffset = hoverPosition.top+10;
		$("#login-carrot").attr("src","/assets/login/2009/carrot_left.gif");
		} else {
		leftOffset = hoverPosition.left-170;
		topOffset = hoverPosition.top+10;
		$("#login-carrot").attr("src","/assets/login/2009/carrot_right.gif");
		}
	$("#login-form-housing").css('left',leftOffset);
	$("#login-form-housing").css('top',topOffset);
	$("#login-form-housing").toggle();
	}


function loginPrompt(placeWhere)
	{
	var uniqueHeader = "<div>You must be logged in to do that!</div>" 
	uniqueHeader +="<div id='inpageLoginFormHeader'><span style='float:right'><a href='/me/registration/index.jhtml'>Join Now!</a> | <a href='/me/pswrdreq.jhtml'>Forgot Password?</a> </span><img src='/assets/login/Sign_In_Log_In_Header_Trans.gif' /></div>"
	//document.getElementById('textAreaGrey').innerHTML=uniqueHeader+document.getElementById('loginFormCodeBegins').innerHTML
	//document.getElementById('textAreaGrey').style.backgroundColor="white";
	//document.getElementById('textAreaGrey').style.padding="10px";
	$(placeWhere).html($('#login-balloon .content').html())
	$(placeWhere).css({"width":"300px", "border":"1px solid #ccc","padding":"20px"});
	}






/**********************************************************/


function reportThisAbuse()
	{
	var formy = document.getElementById('ReportAbuseForm')
	var list = formy.reason;
	var listValue = list.options[list.selectedIndex].value;
	var msgData ="";
	if(listValue=="_")
		{
		alert("Please select a reason for this report");	
		} else {
		var reportAbuseComment = formy.reportAbuseComment.value;
		if(reportAbuseComment==""){ reportAbuseComment="none given"; }
		msgData = "type="+formy.reportAbuseType.value+"&reason="+listValue+"&comment="+reportAbuseComment+"&linkUrl="+formy.linkUrl.value;
		msgData+="&boardID="+formy.boardID.value+"&threadID="+formy.threadID.value+"&messageID="+formy.messageID.value+"&reportUserID="+formy.reportUserID.value;
		msgData+="&reportUsername="+formy.reportUsername.value;
		var postUrl ="/modules/reportAbuse/reportAbuseHandler.jhtml";
		var target = "formArea";
		var callbackFunc = "AbuseReported";
		//alert(msgData);
		ajaxRequest(msgData,postUrl,target,callbackFunc);
		
		}
	}
	
function AbuseReported(response,status,target)
	{
	alert(response);
	document.getElementById('reportAbuseComment').value="";
	document.getElementById('boardID').value="";
	document.getElementById('threadID').value="";
	document.getElementById('messageID').value="";
	document.getElementById('reportUserID').value="";
	document.getElementById('reportUsername').value="";
	document.getElementById('reason').options[0].selected=true
	reportAbuse();
	} //end func

function restoreScroll(){
	//reattaches scroll
	/* commenting out for new board code
	
	if(navigator.appName=="Netscape"){
			var tmpDiv = document.getElementById("msgList");
			
			if(tmpDiv != null){
				tmpDiv.style.overflow = "auto";	
				
			}
		}
		
	*/
}

function getElementsByClassName(className, tag, elm){
	var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
}				


	function ajaxRequest(msgData,postUrl,target,callbackFunc) {
	   /* all works...
	   alert("msgData is "+msgData);
	   alert("postUrl is "+postUrl);
	   alert("target is "+target);
	   alert("callbackFunc is "+callbackFunc);
		*/
	   var AJAX = null;                                 // Initialize the AJAX variable.
	   if (window.XMLHttpRequest) {                     // Does this browser have an XMLHttpRequest object?
		  AJAX=new XMLHttpRequest();                    // Yes -- initialize it.
	   } else {                                         // No, try to initialize it IE style
		  AJAX=new ActiveXObject("Microsoft.XMLHTTP");  //  Wheee, ActiveX, how do we format c: again?
	   }  
													 // End setup Ajax.
	   if (AJAX==null) {
	   return false
		} else {
			// var url='/modules/chat/postHandlerBean.jhtml';This is the URL we will call.
		   AJAX.open("POST", postUrl, true);
		   AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		   AJAX.onreadystatechange = function() {                      
			  if (AJAX.readyState==4 || AJAX.readyState=="complete") 
			  { 
				/*
					alert(AJAX.responseText);
				
				 escape double qotes
					noQuoteText = AJAX.responseText.replace(/"/g, "\'");
					
					alert("no quote: " + noQuoteText);*/
					
			     eval(callbackFunc+"(AJAX.responseText,AJAX.status,'"+target+"')")
				 //callback(AJAX.responseText, AJAX.status,target); 
			  }                               
		   }                                  
		   //if(msgData.indexOf("cat")<0){msgData=msgData+"&cat="+document.getElementById("cat").value;}
		   //alert(msgData);
		   AJAX.send(msgData);
		}
	}

  function pgGotoPage(pageNumber, pgForm, pgLimit, pgTotal, pgUrlPrefix, pgParamName) {		
  	//alert("formName="+pgForm.name);		
  	if (pageNumber == '' || isNaN(pageNumber) || pageNumber == '0') return false;
  	if (((pageNumber - 1) * pgLimit) > pgTotal) return false;
  	var pgOffset = (pageNumber - 1) * pgLimit;		
  	var gotoUrl = pgUrlPrefix+"&"+pgParamName+"="+pgOffset;
  	//alert(gotoUrl);
  	pgForm.action = gotoUrl;
  	return true;
  }

	function giveMeWindowSize(whichOne) {
	  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;
	  }
	  //window.alert( 'Width = ' + myWidth );
	  //window.alert( 'Height = ' + myHeight );
	  if(whichOne=="width"){
	  return myWidth;
	  } else {
	  return myHeight;
	  }
	}
	
	/****************************************************
	AJAX REQUEST WITH JSON SUPPORT
	****************************************************/
	function ajaxJsonRequest(msgData,postUrl,target,callbackFunc) {
		/*
			all works...
			alert("msgData is "+msgData);
			alert("postUrl is "+postUrl);
			alert("target is "+target);
			alert("callbackFunc is "+callbackFunc);
		*/
		var AJAX = null;                                // Initialize the AJAX variable.
		if (window.XMLHttpRequest) {                    // Does this browser have an XMLHttpRequest object?
			AJAX=new XMLHttpRequest();                    // Yes -- initialize it.
		} else {                                        // No, try to initialize it IE style
			AJAX=new ActiveXObject("Microsoft.XMLHTTP");  //  Wheee, ActiveX, how do we format c: again?
		}  
		// End setup Ajax.
	 
		if (AJAX==null) {
			return false
		} else {
			// var url='/modules/chat/postHandlerBean.jhtml';This is the URL we will call.
			AJAX.open("POST", postUrl, true);
			AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			AJAX.onreadystatechange = function() {
				
				if (AJAX.readyState==4 || AJAX.readyState=="complete"){ 
					response = eval("(" + AJAX.responseText + ")");
					//alert(response.entryList[0].url);
					
					eval(callbackFunc + "(response, AJAX.status, '" + target + "')");
 					
					//eval(callbackFunc+"(AJAX.responseText,AJAX.status,'"+target+"')")
					//callback(AJAX.responseText, AJAX.status,target); 
					return true;
				}else{
					return false;
				}
			}
			AJAX.send(msgData);
		}
	}
	
	/****************************************************
	open external link
	****************************************************/
	function launchFramed(urlString){
		
		window.open(urlString,"_blank");
		
	} //end func


	/****************************************************
	cookies; credit: techpatterns.com
	****************************************************/

function Set_Cookie( name, value, expires, path, domain, secure ) 
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct 
expires time, the current script below will set 
it for x number of days, to make it for hours, 
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
( ( path ) ? ";path=" + path : "" ) + 
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function goToSelectedValue(goThere)
	{
	//alert("this.id is "+goThere);
	var url = document.getElementById(goThere).value;
	//alert(url);
	document.location = url;
	}

function escapeText(text){
	var returnString = text.replace(/\"/g, '\\"');
	return returnString;
}

function filterText(text, numChars){
	var realTextLength = 0; // Acutal text lenght minus html links in text
	var curPos = 0; // Current step position in the text string
	var newSting = ""; // New filtered string
	//text = "testing <a href='#!'>somthing else</a> some more text <a href='#!'><i>this</i></a>"; // Test String
	

	
	if(text.length > numChars){ // Make sure text has enough chars for the lenght limit
		
		if(text.indexOf("<", curPos) > 0){ // Check for at least one link in the string
			// Check text for html and re-evaluate length
			while(realTextLength < numChars){
				if(text.indexOf("<", curPos) > 0 && text.indexOf("<", curPos) < numChars){
					curPos = text.indexOf("<", curPos) + 1;
					realTextLengh = curPos;
				}else{
					break;
				}
				
				if(text.indexOf(">", curPos) > 0){ // Find Closing angle bracket
					curPos = text.indexOf(">", curPos) + 1;
					realTextLengh = curPos;
				}else{
					break;
				}
				
			}
		}
		
		// Return the text string at the new curPos cut off point and append " ... "
		if(curPos > 0 && curPos > numChars){ 
			newString = text.substring(0, curPos);
			newString = validateHTML(newString) + "...";
		} else { 
			if(text.indexOf(" ", numChars) != -1){
				newString = text.substring(0, text.indexOf(" ", numChars));
				newString = validateHTML(newString) + "...";
			} else {
				newString = text.substring(0, text.lastIndexOf(" ", text.length));
				newString = validateHTML(newString) + "...";
			}
		}
	}else{
		newString = text;
	}
	return newString;
}

function validateHTML(text){
	var curNode = ""; // current node
	var nodeArr = new Array(); //node array structure
	var valid = true;
	
	//text = "<a href='#!'>somthing else is going on <i><b>tadaa";
	
	// Get node array
	
	nodeArr = buildHTMLTagArray(text);
	
	//Look through node array
	/*for(x in nodeArr){
		alert("Node Arr [" + x + "]" + "=>" + nodeArr[x]);
	}*/
	
	
	//Validate Node Structure
	i=0;
	while(nodeArr.length > 0 && valid == true){
		// Capture first node
		//alert("Node Arr [" + i + "]" + "=>" + nodeArr[i]);
		if(valid == true && i <= (nodeArr.length - 1)){
			if(curNode == ""){
				curNode = nodeArr[i];
				i++;
			} else {
				// check if the next node is a closing node
				if(nodeArr[i].substr(1,1) == "/"){
					// check if it is a proper closing node
					if( nodeArr[i].replace("/", "") == curNode + ">"){
						nodeArr.splice(i, 1);
						nodeArr.splice((i - 1), 1);
						curNode = "";
						i=0;
					} else {
						// Structure is incorrect => retrun structure error
						alert("Your tag structure is incorrect!");
						valid = false;
					}
				// the next tag has to be an open tag so change curNode
				} else {
					curNode = nodeArr[i];
					i++;
				}
			}
		} else {
			// Structure is incorrect => retrun structure error
			// alert("Your tag structure is incorrect!");
			
			// Correct the tag structure
			for(y=(nodeArr.length-1); y>=0; y--){
				text += nodeArr[y].replace("<", "</") + ">";
			}
			valid = false;
		}
	}
	
	//alert("completed");
	return text;
}

function buildHTMLTagArray(text){
	var tagArray = new Array();
	var curPos = 0;
	while(curPos < text.length){
		var tags = new Array ("<a", "</a>", "<b", "</b>", "<i", "</i>", "<p", "</p>", "<u", "</u>", "<strong", "</strong>");
		var val = null;
		var addTag = "";
		
		for(x in tags){
			if(text.indexOf(tags[x], curPos) != -1){
				if(text.indexOf(tags[x], curPos) <= val || val == null){
					val = text.indexOf(tags[x], curPos);
					addTag = tags[x];
				}
			}
		}
		
		if(addTag == ""){
			break;
		}
		tagArray.push(addTag);
		
		//newPos = val + addTag.length;
		//alert("String Length: " + text.length + "\n\n | Adding Tag: " + addTag + 
		//		" | Current Pos: " + curPos + " | Tag Found At: " + val + " | Tag Length: " + addTag.length + " | New Position: " +  newPos);
		
		curPos = val + addTag.length;
	}
	
	//alert(tagArray);
	
	return tagArray;
}


function clearDefaults(inputField){
	// Current Default Values List
	var defVals = new Array('UNKNOWN', 'tempFirstName', 'tempLastName');
	
	for(i=0; i<defVals.length; i++){
		if(document.getElementById(inputField).value == defVals[i]){
			document.getElementById(inputField).value = "";
		}	
	}
}


var windowHousing = '<table id="hovering-avatar-action"><tr><td class="nw"><img src="/assets/balloons/avatar-actions-balloon_nw.gif"></td><td class="n"><img src="/assets/balloons/avatar-actions-balloon_n_carrot.gif"/></td><td class="ne"><img src="/assets/balloons/avatar-actions-balloon_ne.gif"></td></tr><tr><td class="w"></td><td class="content clearfix"><img src="/assets/ajax-loader.gif"></td><td class="e"></td></tr><tr><td class="sw"></td><td class="s"></td><td class="se"></td></tr></table>';
var flashPlaceHolder ='<div class="flash-placeholder">foo</div>';
function avatarActionRequest(toWhom,actionType,win,loginBypass,hideSortBySelect) {
	if ($("#hovering-avatar-action").length==0) {
		$(windowHousing).appendTo('#bottomBG'); 
	} else {
		$("#hovering-avatar-action").css('display','none');
	}
	var hoverPosition = $(win).offset();
	var leftOffset = hoverPosition.left-63;
	var topOffset = hoverPosition.top+10;
	$("#hovering-avatar-action").css('left',leftOffset);
	$("#hovering-avatar-action").css('top',topOffset);
	
	if (loginBypass) {
		//SHOW LOGIN FORM?
		var uniqueHeader ="<div id='close-link' class='login-width'>close</div>";//<div id='inpageLoginFormHeader'><span style='float:right'><a href='/me/registration/index.jhtml'>Join Now!</a> | <a href='/me/pswrdreq.jhtml'>Forgot Password?</a> </span><img src='/assets/login/Sign_In_Log_In_Header_Trans.gif' /></div>"
		var customLoginContent = uniqueHeader+$("#login-form-housing #login-balloon .content").html();	
		$("#hovering-avatar-action .content").html(customLoginContent);
		$("#hovering-avatar-action .content").wrap("<div id='login'></div>");
		showAndPostion(win);
	} else {
		//OR PROCEED WITH AJAX CALL?
		var postUrl = "";
		if(actionType=="note") { postUrl="/site/me/messages/avatar-action-compose-form.jhtml"; }
		if(actionType=="gift") { postUrl="/modules/gifts/gifts_table.jhtml"; }
		if(actionType=="board") { postUrl="/site/me/profile/droplets/avatar-actions-wall-compose-form.jhtml"; }
		$.post(postUrl, { to: toWhom },function(data){
			$("#hovering-avatar-action .content").html(data);
			if(hideSortBySelect){
			$("#sortBySelected_top").css('display','none');	
			$("#sortBySelected_bottom").css('display','none');	
			}
			showAndPostion(win);
		} ); //end $.post
		
	}
}

function initClose(){
	//STYLE THE CLOSE LINK
	$("#hovering-avatar-action #close-link").css('color','#1d83be');
	$("#hovering-avatar-action #close-link").css('cursor','pointer');
	//ASSIGN CLOSE FUNCTION TO LINK
	$("#hovering-avatar-action #close-link").click(function() {
		closeAvatarActionsPopUp();
		return false;
	});
}

function closeAvatarActionsPopUp()
{
	$("#hovering-avatar-action").css({"display":"none"});
	$(".flash-videos").css({"visibility":"visible"});
	$("#sortBySelected_top").css('display','');	
	$("#sortBySelected_bottom").css('display','');	
}

function showAndPostion(win) {
	$(".flash-videos").css({"visibility":"hidden"});
	var hoverPosition = $(win).offset();
	var leftOffset = hoverPosition.left-63;
	var topOffset = hoverPosition.top+10;
	var windowWidth = $(window).width();
	var popUpWidth = $("#hovering-avatar-action").width();
	var popRightEdge = leftOffset + popUpWidth;
	
	//POSITION DEBUG
	/*console.log("Window Width: " + windowWidth + " |  Left Offset " + leftOffset + 
											" | Hover Position Left: " + hoverPosition.left + " | Pop-up Width: " + 
											popUpWidth + " | Right Edge: " + popRightEdge);*/
	
	// Flip Pop-Up
	if ( windowWidth <= popRightEdge ) {
		$(".n").css("text-align", "right");
		$(".n").html('<img src="/assets/balloons/avatar-actions-balloon_n_carrot_r.gif"/>');
		leftOffset -= (popUpWidth - 143);
	}else{
		$(".n").css("text-align", "left");
		$(".n").html('<img src="/assets/balloons/avatar-actions-balloon_n_carrot.gif"/>');
		leftOffset = hoverPosition.left-63;
	}
	
	$("#hovering-avatar-action").css('left',leftOffset);
	$("#hovering-avatar-action").css('top',topOffset);
	initClose();
	
	if($("#hovering-avatar-action").css('display')=="none"){
		$("#hovering-avatar-action").css('display','block');
	}
}

function giftSwitchCategories(toWhom,cid) {
	$.post("/modules/gifts/gifts_table.jhtml", { to: toWhom, cid:cid },function(data){
		$("#hovering-avatar-action .content").html(data);
		initClose();
	 }); //end $.post
}

function avatarActionSubmit(actionType) {

	if (actionType=="note") { 
		var toUser = $("#avatar-action-pm-compose #msgTo").val();
		var toSubject = $("#avatar-action-pm-compose #msgSubject").val();
		var toMessage = $("#avatar-action-pm-compose #messageBody").val();
		
		if(toSubject=="" || toMessage==""){ alert("Your note must have a subject and a message.") } else {
		
			$("#hovering-avatar-action .content").html('<img src="/assets/ajax-loader.gif">');
			$.post("/site/me/messages/avatar-action-postMessageHandler.jhtml", { to: toUser, subject: toSubject, messageBody: toMessage },function(data){
				$("#hovering-avatar-action .content").html(data);
			} );
		}
	}
	if(actionType=="board") {
		var toUser = $("#hovering-avatar-action #compose").val();
		var toComment = $("#hovering-avatar-action #theComment").val();
		//console.log("user name: " + toUser + ", comment: " + toComment);
		$("#hovering-avatar-action .content").html('<img src="/assets/ajax-loader.gif">');
		$.post("/site/me/profile/droplets/avatar-actions-wall-postMessageHandler.jhtml", { username: toUser, theComment: toComment },function(data){
			$("#hovering-avatar-action .content").html(data);
		} );
	}
}

function customizeGift(giftID,to,c) {
	var postUrl = "/modules/gifts/customize_gift_before_sending.jhtml";
	$.post(postUrl, { size: "small",to: to, giftID: giftID,c:c,sections:window.location.pathname, minisite:com.mtvi.config.qs.minisite,testmode:com.mtvi.config.qs.testmode  },function(data){
		$("#hovering-avatar-action .content").html("<div id='close-link'><a href='#!'>close [x]</a></div>"+data);initClose();
	} );
}

function sendGift()	{
	if ($("#hovering-avatar-action #reasonDropDown option:selected").val()=="0") { 
		alert("Please choose a reason before sending."); 
	} else {
		//msgData=msgData+"&reason="+$F("reasonDropDown");
		var postUrl = "/modules/gifts/send.jhtml";
		$.post(postUrl, { to: $("#hovering-avatar-action #to").val(), c: $("#hovering-avatar-action #c").val(), giftID:$("#hovering-avatar-action #giftID").val(),reason:$("#hovering-avatar-action #reasonDropDown option:selected").val()  },function(data){
			$("#hovering-avatar-action .content").html("<div id='close-link'><a href='#!'>close [x]</a></div>"+data);initClose();
	  } );
	}
}

function prefixWrap(sel, nwords, open, close){
  // N.B! innerHTML of sel must be plain text
  var words = document.getElementById(sel).innerHTML.split(' ');
  if(words.length>=nwords){
    var newInner = open;
    for(i=0;i<words.length;i++){
      if(i == nwords) newInner += close;
      newInner += ((i!=0)?' ':'') + words[i];
    }
    document.getElementById(sel).innerHTML = newInner;
  }
}


var configureChatterModule = function (options){
    var loadByAjax = function(uri,selector,onComplete){
	    jQuery.ajax({
		    url: uri,
		    type: "GET",
		    dataType: "html",
		    data: {},
		    cache: false,
		    complete: function(res, status){
			    if ( status == "success" || status == "notmodified" ){
				    $(selector).fadeOut();
				    $(selector).html(res.responseText);
				    $(selector).fadeIn();
				    onComplete.call();
			    }else{
				    //console.log('error');
			    }
		    }
	    });
    }


    var ajaxLoadTodaysChatter = function (){
      loadByAjax(options.feedUrl,options.feedContainerSelector,
		 function(){})
    }
    $(options.refreshSelector).bind("click", ajaxLoadTodaysChatter);
    $(options.talkSelector).bind("click", function () { location.href=options.talkUrl; });
}
