// used by Invite & Announce Tools
function doToggle(form) {	
  	cbxs=form.selectedItems

  	if (cbxs[0]==null) { // handle singular object
    	cbxs.checked=form.checkAll.checked
  	} else { //handle array
    	for(i=0;i<cbxs.length; i++) {
      		cbxs[i].checked=form.checkAll.checked    
    	}    
  	}	
}

//MyLife - used in Inbox pages
var allSelected = false;
function SelectUnSelectAll(my_form, field_name) {
	allSelected = !allSelected;
	len = my_form.elements.length;
	var index = 0;
	
	for( index=0; index < len; index++ ) {
		my_form.elements[index].checked = allSelected; //!my_form.elements[index].checked; 
	}
}
function isValidEmail(email) {
	return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email);
}
function isValidZip(zip) {
	isValid = false;
	if (zip && trim(zip).length >= 5) {
		isValid = /^[a-zA-Z0-9 ]+$/.test(zip);
	}
	return isValid;
}
function isValidDate(year, month, day) {
 	var DateVal = month + "/" + day + "/" + year;
    var dt = new Date(DateVal);
 	
    if(dt.getDate()!=day){ // this will catch a user who enters Feb 29th and a non-leap year.
       return(false);
    } else if(dt.getMonth()!=month-1){
       // JavaScript starts the month from 0
       return(false);
    } else if(dt.getFullYear()!=year){
       return(false);
    }
 	return true; 
}
function isValidFreeFormText(text) {
	var validChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+-={}|[];\":',./?`~ ";
   	var isValid = true;
   	var testChar = '';
	
	if (text && text.length > 0) { 
	   	for (i = 0; i < text.length && isValid; i++) { 
			testChar = text.charAt(i); 
	      	if (validChars.indexOf(testChar) == -1) {
	        	isValid = false;
	      	}
	   	}
   	}
   return isValid;
}
// prevents multiple submissions...use in form tags: onSubmit="return trapButton();"
var buttonTrap = true;
function trapButton() {
	if (buttonTrap) {
		buttonTrap = false;
		return true;
	} else {
		alert("Please wait while processing");
		return false;
	}
}

var newwindow;
function pop(url,scrollFlag)
{
	var scrollValue = "no";
	if(scrollFlag) {
		scrollValue = "yes"
	}
	newwindow=window.open(url,'name','height=571,width=450,left=300,top=200,resizable=no,scrollbars='+scrollValue + ',toolbar=no,status=yes,location=no');
	if (window.focus) {newwindow.focus()}
}
var popupWindow=null;
function popup(mypage,myname,w,h,pos,infocus){
	if (pos == 'random'){
		LeftPosition=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;
		TopPosition=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;
	}else{
		LeftPosition=(screen.width)?(screen.width-w)/2:100;
		TopPosition=(screen.height)?(screen.height-h)/2:100;
	}
	
	settings='width='+ w + ',height='+ h + ',top=' + TopPosition + ',left=' + LeftPosition + ',scrollbars=yes,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=yes';popupWindow=window.open('',myname,settings);
	if(infocus=='front'){
		popupWindow.focus();
		popupWindow.location=mypage;
	}
	if(infocus=='back'){
		popupWindow.blur();
		popupWindow.location=mypage;
		popupWindow.blur();
	}
}
function popUpPhoto(url, title) {
	popup(url, title, 500, 400, null, 'front');
}

// sets focus on the first field in form
function placeFocus() {
	// need the try/catch in case for the first field in the form is hidden or not enabled
	try {
		if (document.forms.length > 0) {
			var field = document.forms[0];
			
			for (i = 0; i < field.length; i++) {
				if ((field.elements[i].type == "text") || (field.elements[i].type == "textarea") || (field.elements[i].type.toString().charAt(0) == "s")) {
					document.forms[0].elements[i].focus();
					break;
			    }
			}
		}
	} catch(e) {
	}
}

var cur_lyr;	// holds id of currently visible layer
function swapLayers(lnk,id) {
	doLinkClass(lnk);
	if (cur_lyr) hideLayer(cur_lyr);
	showLayer(id);
	cur_lyr = id;
}

function showLayer(id) {
	var lyr = getElemRefs(id);
	if (lyr && lyr.css) lyr.css.display = "block";
}

function hideLayer(id) {
	var lyr = getElemRefs(id);
	if (lyr && lyr.css) lyr.css.display = "none";
}

function getElemRefs(id) {
	var el = (document.getElementById)? document.getElementById(id): (document.all)? document.all[id]: (document.layers)? getLyrRef(id,document): null;
	if (el) el.css = (el.style)? el.style: el;
	return el;
}

// get reference to nested layer for ns4
// from old dhtmllib.js by Mike Hall of www.brainjar.com
function getLyrRef(lyr,doc) {
	if (document.layers) {
		var theLyr;
		for (var i=0; i<doc.layers.length; i++) {
			theLyr = doc.layers[i];
			if (theLyr.name == lyr) return theLyr;
			else if (theLyr.document.layers.length > 0)
			if ((theLyr = getLyrRef(lyr,theLyr.document)) != null) return theLyr;
		}
		return null;
	}
}

function init(id,lyr) {
	var lnk = getElemRefs(id);
	swapLayers(lnk,lyr);
}

// trim leading and trailing whitespace characters from string
function trim(s) {
    return s.replace(/(^\s+)|(\s+$)/g, "")
}

// clean html spaces, paragraphs and breaks
function trimAll(s) {
     s = s.replace(/<p><\/p>/g, '');
     s = s.replace(/&nbsp;\s*/g, '');
     s = s.replace(/<br \/>\s*/g, '');
     s = s.replace(/ /g, '');
     return s;
}
// check if value is numeric
function isNumeric(val){
   var validChars = "0123456789";
   var isNumber = true;
   var testChar = '';
 
   for (i = 0; i < val.length && isNumber; i++) { 
      testChar = val.charAt(i); 
      if (validChars.indexOf(testChar) == -1) {
         isNumber = false;
      }
   }
   
   return isNumber;
}
function validName(field) {
	var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	var inValid = "1234567890`~!@#$%^&*()=+[{]}\\|;:,<.>?/\""
	var permissible = "'-"
	var ok = "no";
	var temp, beg, end;
	//check if have any valid characters
	for (var i=0; i<field.value.length; i++) {
		temp = "" + field.value.substring(i, i+1);
		if (valid.indexOf(temp) != "-1")  {
			ok = "yes";
		}
	}
	
	//check if have any invalid characters. Only space, apostrophe, and dash are allowed
	for (var i=0; i<field.value.length; i++) {
		temp = "" + field.value.substring(i, i+1);
		if (inValid.indexOf(temp) != "-1") {
			ok = "no";
		}
	}
	
	//not allow permissible characters at the beginning or end
	beg = "" + field.value.substring(0, 1);
	end = "" + field.value.substring(field.value.length-1, field.value.length);
	if (permissible.indexOf(beg) != "-1" || permissible.indexOf(end) != "-1") {
		ok = "no";
	}
	
	if (ok == "no") {
		return false;
   	} else {
   		return true;
   	}
}
// validate people search parameters on any form
function checkPeopleSearch(checkForm){
 
	if(checkForm.wel_fname) {
		if(checkForm.wel_fname.value == "" || trim(checkForm.wel_fname.value) == ""
			|| trim(checkForm.wel_fname.value).toLowerCase() == "first name"
			|| trim(checkForm.wel_fname.value).toLowerCase() == "name"  
			||!validName(checkForm.wel_fname)){			
			checkForm.wel_fname.focus();
			alert("Please enter proper First Name");
			return false;
		}
	}

	if(checkForm.wel_lname) {
		if(checkForm.wel_lname.value == "" || trim(checkForm.wel_lname.value) == ""
			|| trim(checkForm.wel_lname.value).toLowerCase() == "last name"
			|| trim(checkForm.wel_lname.value).toLowerCase() == "name" 
			|| !validName(checkForm.wel_lname)){
			checkForm.wel_lname.focus();
			alert("Please enter proper Last Name");
			return false;
		}
	}

	if (checkForm.wel_age) {
	
		if(checkForm.wel_age.value == "" || trim(checkForm.wel_age.value) == ""){
			checkForm.wel_age.focus();
			alert("Please enter approximate age");
			return false;
		} else if(!isNumeric(trim(checkForm.wel_age.value))){
			alert("Please enter approximate age");
			return false;
		} else if(trim(checkForm.wel_age.value)>101){
			alert("Age cannot be over 100.");
			return false;
		} else if(trim(checkForm.wel_age.value)<13 ){
			alert("The minimum search age is 13.");
			return false;
		}
	}
	return true;
}

//MyLife - Form functions 
function checkInputText(obj,defaultValue) {
	if(obj.value == '') {
		obj.value = defaultValue;
		obj.className = 'gray9';
	}
}
function clearField(obj,defaultValue) {
	if(obj.value == defaultValue) {
		obj.value='';
		obj.className = 'gray3';
	}
}
function goToPage(url) {
	document.location = url;
}
function displayDiv(divId) {
	var e = document.getElementById(divId);
	e.style.display = "block";
}
function hideDiv(divId) {
	var e = document.getElementById(divId);
	e.style.display = "none";
}

/*
 * Gets all the elements that of type 'tag' and class 'className', and adds a space into any word longer than 'charCount'.
 * This is so that long words will wrap and not break the layout.
 */
function reflowByClass(className, tag, charCount) {
	
	var nodeList = YAHOO.util.Dom.getElementsByClassName(className, tag);
	reflowNodes(nodeList, charCount);
}
/*
 * Gets the element with id 'id', and adds a space into all words longer than 'charCount'.
 * This is so that long words will wrap and not break the layout.
 */
function reflowById(id, charCount) {
	var node = document.getElementById(id);
	reflowNodes([node], charCount);
}

/**
 * Used by reflowByClass and reflowById. Call one of them instead.
 *  
 * @param nodeList Array of DOM nodes to look at.
 * @param charCount Truncate words longer than this many characters.
 * @return nothing
 */
function reflowNodes(nodeList, charCount) {	
	
	for (var i=0; i<nodeList.length; i++) {
					
		var node = nodeList[i];
		if (node.nodeType == 3) { // 3 is text node
			node.nodeValue = reflowParagraphTo(node.nodeValue, charCount);
		}
		else if (node.hasChildNodes()) {
			reflowNodes(node.childNodes, charCount);
		}

	}
}

/*
 * Used by reflowByClass and reflowBId.
 */
function reflowParagraphTo(para, pos) {

	var result = [];
	
	var parts = para.split(' ');
	for (var i=0; i<parts.length; i++) {
		var word = trim(parts[i]);
		
		if (word.length < pos) {
			result[i] = word;
		}
		else {
			result[i] = word.substr(0, pos) +' '+ word.substr(pos);
		}
	}
	
	return result.join(' ');
}
/* Generate Random Background Image */
function generateRandomBg( imageArray, imagePath, divId) {
	var imageIndex = Math.floor(Math.random() * imageArray.length);
	$("#"+divId).css("background-image","url("+imagePath + imageArray[imageIndex] + ")");
}
function generateRandomBgPair( imageArray, imagePath, divId, imageIndex) {
	$("#"+divId).css("background-image","url("+imagePath + imageArray[imageIndex] + ")");
}

$(document).ready(function(){
	
	/* Tooltip Enabler and Disabler */
	$('.tooltipToggle').mouseover(function(){
		var tooltip = $(this).parent().find('.tooltip');
		tooltip.fadeIn('fast');
		$(".tooltip").mouseover(function(){
			tooltip.css('display','block')
		}).mouseout(function(){
			tooltip.css('display','none')
		});
	}).mouseout(function() {
		var tooltip = $(this).parent().find('.tooltip');
		tooltip.css('display','none');
	});
	
});
// Load the MyLife Tour Video
function loadMyLifeVideo() {
	var videoChannel = "Video Tour";
	var videoPageName = "Video Tour";
	var noFlashHtml = "<b class=\"gray6\">Adobe Flash is required to play the MyLife video.</b><br/><br/><a href=\"http://www.adobe.com/go/EN_US-H-GET-FLASH\">Download Now</a><br><a href=\"http://www.adobe.com/go/EN_US-H-GET-FLASH\"><img src=\"$staticServer/images/09/icons/iconAdobeFlash.png\" style=\"margin:10px 0px\" border=\"0\"></a><br/><br/><b class=\"gray6\">Go on...it only takes a minute and the video is worth watching.</b>";
	
	$('<div id="myLifeTour"><div style="height:23px;background-color:#83c45a"></div><div id="myLifeSwf"><div id="noFlash">'+noFlashHtml+'</div></div></div>').modal({
		close:true,
		overlayId:'myLifeTourOverlay',
		containerId:'myLifeTourContainer',
		onShow: function() { 
			$('#myLifeSwf').flash({
        	swf: 'http://a1.mylife.com/a/tour/videoAppNoLogo_v2.swf',
        	height:398,
        	width: 480,
			wmode:'transparent'});
			//Send Omniture Variables
			sendPageNameAndChannelToOmniture(videoPageName, videoChannel);
		}
	})
}
