String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,""); }
String.prototype.ltrim = function() { return this.replace(/^\s+/,""); }
String.prototype.rtrim = function() { return this.replace(/\s+$/,""); }

//This function Checks the valid email
function isValidEmail(str) {
   return ((str.indexOf(" ") == -1) && (str.indexOf("'") == -1) && (str.indexOf("@") > 0));
 
}

function validateEmailList(emailField) {
	emails = emailField.value.split(",");
	alertString = (emails.length<2)?"Email address is invalid!":"One or more of your email addresses are invalid!";
	for( i=0; i<emails.length; i++ ) {
		if(!isValidEmail(trim(emails[i]))) {
			alert(alertString);
			emailField.focus();
			return false;
		}
	}
	return true;
}

/*
 * Verifies whether the string is blank.(i.e. null/String of length '0')
 */
function isBlank(strSource) {
	var strValue=strSource.replace(/^(\s*)/, "");
	strValue=strValue.replace(/(\s*)$/, "");
	if(strValue.length == 0 ) {
		return true;
	}
	else {
		return false;
	}
}


/*
 * Checks the string for digits. 
 */
function isDigit(intSource) {
	intSource=trim(intSource);
	var reg = /\D/;
	if (reg.test(intSource)) {
		return false;
	}
	else {
		return true;
	}
}

/*
 * This function removes leading and trailing spaces in the string.
 */
function trim(strSource) {
     if(isBlank(strSource)){
     return strSource
    }
	var strValue=strSource.replace(/^(\s*)/, "");
	strValue=strValue.replace(/(\s*)$/, "");
	return  strValue;
}

/*
 * Checks the string for digits. 
 */
function isDigit(intSource) {
	intSource=trim(intSource);
	var reg = /\D/;
	if (reg.test(intSource)) {
		return false;
	}
	else {
		return true;
	}
}

/*
 * Checks the string for alphabets and digits. 
 */
function isAplhanumeric(strSource) {
	strSource=trim(strSource);
	var reg = /[^a-zA-Z0-9\s_-]/
	if (reg.test(strSource)) {
		return false;
	}
	else {
		return true;
	}
}

/*
 * Checks the string for alphabets. 
 */
function isAlpha(strSource) {
	strSource=trim(strSource);
	var reg = /[^a-zA-Z\s_]/
	if (reg.test(strSource)) {
		return false;
	}
	else {
		return true;
	}
}

/*
 * Check if keycode is printable ASCII. 
 */
function isPrintable (keyCode) {
	return (keyCode == 32 || keyCode >= 48 && keyCode <= 90 || keyCode >= 96 && keyCode <= 111 || keyCode >= 188);
}

/*
 * Check if keycode is an arrow key (up, down, left, right). 
 */
function isArrowKey(keyCode) {
	return (keyCode >= 37 && keyCode <= 40);
}

/*
 * This function validates a phone number (Blank and '-' is allowed)
 */
function validatePhoneNo(strSource) {
	if(isBlank(trim(strSource)))
		return false;
	var reg =/!|@|#|\$|\%|\^|&|\*|\(|\)|[a-z]|[A-Z]/
	return reg.test(strSource)
}

/*
 * This function verifies the string for a valid email address (i.e. the one containing '@/.' character).
 */
function isEmail(strSource) {
	strSource=trim(strSource);
	var reg =/^(\w|-|.|_)+@(\w|-|.|_)*\.(\w*)$/;
	return reg.test(strSource)
}


// ********************************** Date Validation in MM/DD/YYYY *****************************************

/**
 * DHTML date validation script.
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

/**
 * creates Days Arrays
 */
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

/**
 * checks validation of Date
 */
function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}

/**
 * replaces old string with new
 */
function replaceAll(oldStr,findStr,repStr) {
  var srchNdx = 0;  // srchNdx will keep track of where in the whole line
                    // of oldStr are we searching.
  var newStr = "";  // newStr will hold the altered version of oldStr.
  while (oldStr.indexOf(findStr,srchNdx) != -1)  
                    // As long as there are strings to replace, this loop
                    // will run. 
  {
    newStr += oldStr.substring(srchNdx,oldStr.indexOf(findStr,srchNdx));
                    // Put it all the unaltered text from one findStr to
                    // the next findStr into newStr.
    newStr += repStr;
                    // Instead of putting the old string, put in the
                    // new string instead. 
    srchNdx = (oldStr.indexOf(findStr,srchNdx) + findStr.length);
                    // Now jump to the next chunk of text till the next findStr.           
  }
  newStr += oldStr.substring(srchNdx,oldStr.length);
                    // Put whatever's left into newStr.             
  return newStr;
}



// *****************************************************************************


function popWindow(url) {
	var popWin = window.open(url,'','scrollbars=yes,menubar=no,height=450,width=550,resizable=yes,toolbar=no,location=no,status=no');
	if (window.focus) { popWin.focus() }
	return false;
}
// -->

/**
 * Generic Tab controls (see UserInfo page)
 */
function selectTabs( tabCssPrefix, elementCssPrefix, index, numTabs ) {
	for (var i = 0; i < numTabs; i++) {
		document.getElementById( tabCssPrefix + "-" + i ).className = tabCssPrefix;
		document.getElementById( elementCssPrefix + "-" + i ).style.display = "none";
	}
	document.getElementById( tabCssPrefix + "-" + index ).className = tabCssPrefix + "-on";
	document.getElementById( elementCssPrefix + "-" + index ).style.display = "block";
	return false;
}

function highlightTab( tabCssPrefix, index, numTabs ) {
	for (var i = 0; i < numTabs; i++) {
		try {
			document.getElementById( tabCssPrefix + "-" + i ).className = tabCssPrefix;
		} catch(e) {
			// tab may not exist, this prevents error
		}
	}
	document.getElementById( tabCssPrefix + "-" + index ).className = tabCssPrefix + "-on";
	return false;
}

function toggleCssDisplay(id,type) {
	var element = document.getElementById(id);
	if (element) {
		if ( type=='block' || type=='inline' || type=='none' ) { // display types supported by all browsers
			element.style.display=type;
		} else if ( type=='table-cell' || type=='inline-block' ) { // makes sense to default these to 'inline' if not supported
			try { 
				element.style.display=type; 
			} catch(e) {
				element.style.display='inline'; 
			}
		} else { // use 'block' for everything else, if not supported by browser (ex. IE)
			try { 
				element.style.display=type; 
			} catch(e) {
				element.style.display='block'; 
			}
		}
	}
}
function showElement(id) { 
	toggleCssDisplay(id,"block");
}
function showInlineElement(id) { 
	toggleCssDisplay(id,"inline");
}
function hideElement(id) { 
	toggleCssDisplay(id,"none");
}
var toggleObject = {};

function toggleElement(id,type) {
	var displayType = type || "block";
	if (toggleObject[id] && (toggleObject[id] == displayType)) {
		toggleCssDisplay(id,'none');
		toggleObject[id] = "none";
	} else {
		toggleCssDisplay(id,displayType);
		toggleObject[id] = displayType;
	}
}

function hideIfComplete(id) { 
	if (hideIntervalComplete) 
		hideElement(id);
}
function showIfComplete(id) { 
	if (showIntervalComplete) 
		showElement(id);
}

var hideIntervalComplete = true;
var showIntervalComplete = true;

function hideElementAfterInterval(eid,millis) {
	hideIntervalComplete=true;
	setTimeout("hideIfComplete('"+eid+"')",millis);
}
function showElementAfterInterval(eid,millis) {
	showIntervalComplete=true;
	setTimeout("showIfComplete('"+eid+"')",millis);
}

function toggleElements(id1,id2) {
	var e1 = document.getElementById(id1);
	var e2 = document.getElementById(id2);
	//alert("e1: "+e1.style.display+"\ne2: "+e2.style.display);
	var tempDisp = e1.style.display;
	e1.style.display=e2.style.display;
	e2.style.display=tempDisp;
	//alert("e1: "+e1.style.display+"\ne2: "+e2.style.display);
	return false;
}

function switchCssDisplay(id,typeA, typeB) { 
	
	try {
		var currentType = document.getElementById(id).style.display;
		var newType = typeA;
		if(currentType == typeA) {
			newType = typeB;
		} else if (currentType == typeB) {
			newType = typeA;
		}
		document.getElementById(id).style.display=newType;
		
		return newType; 
	} catch(e) {
		//alert( e.message );
	}
}

// Used to copy text from <textarea> to clipboard
function copyTextarea(ta) {
	ta.focus();
	ta.select();
	try {
		r=ta.createTextRange();
		r.execCommand('copy');
		alert('Your link was copied.');
	} catch(e) {
		alert("Your browser does not support this action.");
	}
}

function getFieldValue(inputObj) {
	if(!inputObj)
		return "";
	if(inputObj.type == 'radio' || inputObj.type == 'checkbox')
		return getCheckedValue(inputObj);
	return inputObj.value;
}


/**
 * Get value of a radio button or checkbox
 */
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

/**
 * Check a specific radio button or checkbox based on value
 */
function checkFormField(radioObj, value) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength != undefined) {
		// radio or multibox
		for(var i = 0; i < radioLength; i++) {
			if(radioObj[i].value == value) {
				radioObj[i].checked = true;
				return;
			}
		}
	} else {
		// boolean checkbox
		if (radioObj.value == value) {
			radioObj.checked = true;
		} else {
			radioObj.checked = false;
		}
	}
}

function uncheckFormField(radioObj, value) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength != undefined) {
		// radio or multibox
		for(var i = 0; i < radioLength; i++) {
			if(radioObj[i].value == value) {
				radioObj[i].checked = false;
				return;
			}
		}
	} else {
		// boolean checkbox
		if (radioObj.value == value) {
			radioObj.checked = false;
		} else {
			radioObj.checked = true;
		}
	}
}

function toggleCheckField(radioObj, value, flag) {
	if (flag) {
		checkFormField(radioObj, value);
	} else {
		uncheckFormField(radioObj, value);
	}
}

function clearFormField( form, field ) {
	if(document.forms[form].elements[field]) {
		document.forms[form].elements[field].value = "";
	}
}

function getRatingHTML( rating, showAll, useHalfs, imgPrefix ) {
	var ratingHtml = "";
	if ( isNaN(rating) ) {
		return ratingHtml;
	}
	var prefix = imgPrefix || "rating_icon";
	var maxRating = 5;
	var remainder = (rating-Math.floor(rating));
	var step = Math.round(remainder*2);
	var halfStar = (useHalfs && (step == 1) ) ? 1 : 0;
	var ratingRounded = useHalfs ? (Math.floor(rating) + Math.floor(step/2)) : Math.round(rating);
	for( var i=0; i<ratingRounded; i++ ) {
		ratingHtml += "<img src=\"" + IMAGEPATH + prefix + "_on.gif\"/>";
	}
	if ( halfStar == 1 ) {
		ratingHtml += "<img src=\"" + IMAGEPATH + prefix + "_half.gif\"/>";
	}
	if (showAll) {
		for( var i=(ratingRounded+halfStar); i<maxRating; i++ ) {
			ratingHtml += "<img src=\"" + IMAGEPATH + prefix + "_off.gif\"/>";
		}
	}
	return ratingHtml;
}

// User object, used on User profile page
//for group stat firststat = nooffriends , secondstat = noofreview , thirdstat = noofplacevisited
//for location stat firststat = rating , secondstat= isReviewed , thirdstat = isInwishList
function networkInfo( name, userid, imgsrc, firststat, secondstat, thirdstat ,type) {
	this.name = name;
	this.userid = userid;
	this.imgsrc = imgsrc;
	this.firststat = firststat;
	this.secondstat = secondstat;
	this.thirdstat = thirdstat;
	this.type = type;
}

function displayNetworkUsers( limit, noStats ) {
	numUsers = limit || networkUsers.length;
	displayUsersWithStats( networkUsers, numUsers, '', noStats );
}

function displayUsersWithStats( userList, limit ,entityId, noStats) {
	var numUsers = limit || userList.length;
	var displayStats = typeof(noStats) == 'undefined' ? true : !noStats;
	for( i=0; i<numUsers; i++ ) {
		user = userList[i];
	   displayUserIcon(user,entityId,displayStats)
	}
}

/* DEBUGGING FUNCTIONS */

/**
 * Debug util function - used in other JS functions, text will be displayed 
 * in upper right hand corner. If debug box element does not exist, it will
 * be created dynamically via DOM
 */

function highlightUser(imgobj, userid, color) {
	color = color ? color : "#ff6702";
	imgobj.style.border = "2px solid "+color;
} 

function highlightUserOff(imgobj, userid) {
	imgobj.style.border = "2px solid #fff";
}

var poppedUser = ""; // to keep track of which user popups are open

function clickUser(userid,entityid,entitytype) {
	if (poppedUser != "") { // there's a box open, close it
		switchCssDisplay('userpop-' + poppedUser, 'block', 'none');
	} 
	if (poppedUser != userid) { // opening new popup
		poppedUser = userid;
		eidStr = entityid ? "&" + (entitytype == 'L' ? "locationID" : "groupID" ) + "="+entityid : "";
		switchCssDisplay('userpop-' + userid, 'block', 'none');
		toggleSaving(null, 'userpop-' + userid, 'prog-'+ userid);
		ajaxRequestSender(null,"/ajax/GetUserProfileInfo.do?userID="+userid+eidStr,"",null,StdInnerHTML,"userpop-"+userid, "POST", true);
	} else { // not opening new popup, reset
		poppedUser = "";
	}
}

function closeUser(userid) {
	switchCssDisplay('userpop-' + userid, 'block', 'none');
	poppedUser = "";
}

function clickUserResponser(ajaxXHR, ajaxFRM, ajaxRHP) {
	if(ajaxXHR.responseText.length > 0) {
		StdInnerHTML(ajaxXHR, ajaxFRM, ajaxRHP)
		document.getElementById(ajaxRHP).style.width = "100px";
	} else {
		toggleCssDisplay(ajaxRHP, 'none');
	}
}

var userStateCounter = 50;
function displayUserIcon(user,entityId,showStats){
				userStateCounter--;
				var userstyle = user.type == 'L' ? "user-location" : "user";
                document.write('<div class="'+ userstyle +'" style="position: relative; z-index: ' + userStateCounter +  '" onmouseover="this.style.border=\'solid 1px #ccc\'; document.getElementById(\'plus-' + user.userid + '\').style.visibility=\'visible\';" onmouseout="this.style.border=\'solid 1px #fff\'; document.getElementById(\'plus-' + user.userid + '\').style.visibility=\'hidden\';">');
				document.write(' <div class="avatar-small"><a href="' + PROFILEPATH + user.userid + '" title="' + user.name + '"><img src="' + user.imgsrc + '" border="0" width="60" height="60" alt="" onclick="clickUser(\'' +user.userid+ '\', \'' + entityId + '\', \'' + user.type + '\'); return false;" onmouseover="highlightUser(this, \'' +user.userid+ '\'); return false;" onmouseout="highlightUserOff(this, \''+user.userid+ '\'); return false;" /></a></div>');
				if (showStats) {
				    document.write('    <div class="stats">');
					if (user.type == 'L') {
						document.write(getRatingHTML(user.firststat,true,true))
						if(user.secondstat >0){
							document.write('		<div class="stat-location"><a style ="text-decoration: none !important" href="FullReview.do?locationID='+entityId+'&uid='+user.userid+'"><div class="stat-icon"><img src="' + IMAGEPATH + 'icons/icon_reviewed_on.gif" border="0" alt="Reviews" title="Reviews"/></div> <div class="done" >Review </div></a></div>');
						}else{
							document.write('		<div class="stat-location"><div class="stat-icon"><img src="' + IMAGEPATH + 'icons/icon_reviewed_off.gif" alt="Reviews" title="Reviews"/></div> <div class="notdone" >Review </div></div>');
						}
						if(user.thirdstat > 0){
							document.write('		<div class="stat-location"><div class="stat-icon"><img src="' + IMAGEPATH + 'icons/icon_wlcheck_on.gif" alt="Wish List" title="wish List"/></div> <div class="done" >Wish List</div></div>');
		            	}else{
		            		document.write('		<div class="stat-location"><div class="stat-icon"><img src="' + IMAGEPATH + 'icons/icon_wlcheck_off.gif" alt="Wish List" title="Wish List"/></div> <div class="notdone">Wish List</div></div>');
		           	 	}
		           	} else { // different fields if not location
						document.write('		<div class="stat"><div class="stat-icon"><img src="' + IMAGEPATH + 'icon_friend_small.gif" alt="Friends" title="Friends"/></div><span class="number">' + user.firststat + '</span></div>');
						document.write('		<div class="stat"><div class="stat-icon"><img src="' + IMAGEPATH + 'icon_r_letn.gif" alt="Reviews" title="Reviews"/></div><span class="number">' + user.secondstat + '</span></div>');
						document.write('		<div class="stat"><div class="stat-icon"><img src="' + IMAGEPATH + 'icon_pb.gif" alt="Places Been" title="Places Been"/></div><span class="number">' + user.thirdstat + '</span></div>');
		           	} 
	           	 	document.write('	</div>');
	           	}
           	 	document.write(' <div class="userid"><a href="#" onclick="clickUser(\'' +user.userid+ '\', \'' + entityId + '\', \'' + user.type + '\'); return false;" title="' + user.name + '">' + user.name + '</a></div>');
           	 	document.write(' <div class="plus" id="plus-' + user.userid + '"><a href="#" onclick="clickUser(\'' +user.userid+ '\', \'' + entityId + '\', \'' + user.type + '\'); return false;"><img src="'+ IMAGEPATH + 'icons/icon_plus_blue.gif" border="0"/></a></div>');
			    document.write('<div class="user-popup" id="userpop-' + user.userid + '">');
			    document.write('	<span style="background-color: #fff;"><img id="prog-'+user.userid+'" src="'+IMAGEPATH+'ajax_progress.gif" alt="Saving..."/> Loading...</span>');
           	 	document.write('</div>');

           	 	document.write('</div>');
           	 	
}

function disPlayUserStateForGroup(user, noStats){
                document.write('<div class="user">');
		        document.write(' <div class="avatar-small"><a href="' + PROFILEPATH + user.userid + '"><img src="' + user.imgsrc + '" border="0" width="60" height="60" alt=""/></a></div>');
			    if(!noStats) {
			    	document.write('    <div class="stats">');
					document.write('		<div class="stat"><div class="stat-icon"><img src="' + IMAGEPATH + 'icon_friend_small.gif" alt="Friends" title="Friends"/></div><span class="number">' + user.firststat + '</span></div>');
					document.write('		<div class="stat"><div class="stat-icon"><img src="' + IMAGEPATH + 'icon_r_letn.gif" alt="Reviews" title="Reviews"/></div><span class="number">' + user.secondstat + '</span></div>');
					document.write('		<div class="stat"><div class="stat-icon"><img src="' + IMAGEPATH + 'icon_pb.gif" alt="Places Been" title="Places Been"/></div><span class="number">' + user.thirdstat + '</span></div>');
		        	document.write('	</div>');
		        }
		        document.write('	<div class="userid"><a class="userinfo-link" href="' + PROFILEPATH + user.userid + '" title="' + user.name + '">' + user.name + '</a></div>');
		        document.write('</div>');
}
function filterLocationType(id,numDisplay){
	if(document.locationMemberFrm.strLocationType.value != id.value){
		document.locationMemberFrm.strLocationType.value = id.value;
		filterMemberInternal(numDisplay);
	}
	return false;
}

function filterMember(id,numDisplay){
	if(document.locationMemberFrm.hfilterType.value != id.value){
		document.locationMemberFrm.hfilterType.value = id.value;
		filterMemberInternal(numDisplay);
	}
	return false;
}

function filterMemberInternal(numDisplay) {
	if(document.locationMemberFrm.o && document.locationMemberFrm.n){
		document.locationMemberFrm.o.value=0;
		document.locationMemberFrm.n.value = numDisplay;
	}
	document.locationMemberFrm.submit();
}

function navigateMembersForLocation(offset , numDisplay,type){
  if(type ==-1){
   document.locationMemberFrm.o.value =(offset-numDisplay);
   document.locationMemberFrm.n.value =numDisplay;
   document.locationMemberFrm.submit();
  }
  if(type ==1){
   document.locationMemberFrm.o.value =(offset+numDisplay);
   document.locationMemberFrm.n.value =numDisplay;
   document.locationMemberFrm.submit();
  }
  return false;
}
function debug(text,isTimestamp,isClear,debugBoxId,debugFlagOverride) {
	if (codeDebug || debugFlagOverride) {
		var defaultBoxId = "debug-box";
		var dbid = debugBoxId || defaultBoxId;
		var clear = isClear || false;
		var timestamp = isTimestamp || false;
		var box;
		try {
			box = document.getElementById(dbid);
			box.style.display='block';
		} catch (e) {
			var div = document.createElement('div');
			div.id = defaultBoxId;
			//box.className = "";
			//alert( "div.id="+div.id );
			document.body.appendChild(div);
			box = document.getElementById(defaultBoxId);
			box.style.display='block';
		}
		if (timestamp) text = (new Date()) + ': ' + text;
		if (!clear) text = box.innerHTML + text;
		box.innerHTML=text + "<br/>";
	}
}

function changeBorderBoxStyle(id,type) {
	if (type) {
		document.getElementById(id).className = "border-box border-box-" + type;
	} else {
		document.getElementById(id).className = "border-box";
	}
}

/* DEBUGGING FUNCTIONS END */

/**
 * Utility functions for smooth popups
 * 
 */

var fl = 5;		// frame length in millis, smaller = smoother, but more CPU
var d = 300;	// length of transition, in millis

function expandBox( box, maxX, maxY, dur ) {
	return resizeBox( box, 0, 0, maxX, maxY, dur);
}

function shrinkBox( box, maxX, maxY, dur ) {
	return resizeBox( box, maxX, maxY, 0, 0, dur);
}

function resizeBox( box, startX, startY, finX, finY, duration, frameLength ) {
	if ( typeof(box) == "string" ) box = document.getElementById(box);
	//debug("Init params:<br>startX: "+startX+"<br>startY: "+startY+"<br>finX: "+finX+"<br>finY: "+finY+"<br>duration: "+duration+"<br>frameLength: "+frameLength+"<br>", true, "debug-box", true );
	var dur = duration || d;
	var fLen= frameLength || fl;
	var numFrames = (dur/fLen);
	var xinc = ( finX-startX ) / numFrames;
	var yinc = ( finY-startY ) / numFrames;
	setDim(box, startX, startY);
	if (xinc>=0) { toggleCssDisplay(box.id,"block"); }
	for ( var i=0; i<numFrames; i++ ) {
		var newx = box.offsetWidth + (xinc*i) ;
		var newy = box.offsetHeight + (yinc*i) ;
		window.setTimeout('setDim(document.getElementById("' + box.id + '"),'+newx+','+newy+')',(fLen*i));
	}
	window.setTimeout('setDim(document.getElementById("' + box.id + '"),'+finX+','+finY+');if('+xinc+'<0){toggleCssDisplay("' + box.id + '","none");}',dur);
}

function setDim( box, x, y ) {
	rx = Math.round(x);
	ry = Math.round(y);
	//debug("width: "+rx+"<br>height: "+ry+"<br>\n", true, "debug-box", true );
	box.style.width=Math.round(x)+"px";
	box.style.height=Math.round(y)+"px";
}

/**
 * Set innerHTML of element by its ID
 */
function setInnerHTMLById( id, html ) {
	try {
		document.getElementById(id).innerHTML = html;
	} catch(e) {
		debug("Element with id='" + id + "' does not exist!");
	}
}

/**
 * Get innerHTML of element by its ID
 */
function getInnerHTMLById( id ) {
	var html;
	try {
		html = document.getElementById(id).innerHTML;
	} catch(e) {
		debug("Element with id='" + id + "' does not exist!");
		html = null;
	}
	return html;
}


function capitalizeFormField(obj) {
	val = obj.value;
	newVal = '';
	val = val.split(' ');
	for(var c=0; c < val.length; c++) {
		newVal += val[c].substring(0,1).toUpperCase() +
			val[c].substring(1,val[c].length).toLowerCase() + ' ';
	}
    obj.value = newVal;
    return false;
}

/**
 * Utility functions for arrays
 * Usage:	var myArray = new Array();
 *			// add elements to array
 *			var index = myArray.indexOf('somevalue');
 *			if (myArray.contains('othervalue')) { ... }
 */
Array.prototype.indexOf = function(n) { 
	for( var i=0; i<this.length; i++ ) { 
		if (this[i]===n) {return i;}
	}
	return -1;
};
Array.prototype.contains = function(n) { return this.indexOf(n) != -1; };

// Custom JS objects

/**
 * All-purpose Hash object
 * Usage:
 *			var myHash = new Hash('prop1','value1','prop2','value2',...);
 *			myHash.set('prop2','newvalue');
 *			myHash.add('newprop','othervalue');
 *			for( var i in myHash.getAll() ) {
 *				var myItem = myHash.get(i);
 *				// do something
 *			}
 */
function Hash() {
	this.length = 0;
	var items = {};
	for (var i = 0; i < arguments.length; i += 2) {
		if (typeof(arguments[i + 1]) != 'undefined') {
			this.items[arguments[i]] = arguments[i + 1];
			this.length++;
		}
	}
	this.get 	= function(key)		{ return this.items[key]; };
	this.getAll	= function() 		{ return items; };
	this.set	= function(key, value) {
		if (typeof(value) != 'undefined') {
			if (typeof(this.items[key]) == 'undefined') {
				this.length++;
			}
			this.items[key] = value;
		}
		return value;
	};
	this.hasItem= function(key)		{ return typeof(this.items[key]) != 'undefined'; };
	this.remove	= function(key) {
		var tmp_value;
		if (typeof(this.items[key]) != 'undefined') {
			this.length--;
			var tmp_value = this.items[key];
			delete this.items[key];
		}
		return tmp_value;
	};
}

/**
 * All-purpose Tree object, used initially for Travel Map on My Travels page
 * 
 * See mytravels.jsp for usage
 */
function Tree(nodeid,nodevalue) {
    this.nodeid = nodeid;
    var nodevalue = nodevalue;
    var children = {};
    var numChildren = 0;
    this.getNodeValue	= function () { return nodevalue; };
    this.getChild		= function (id) { return children[id]; };
    this.getChildNodes	= function () { return children; };
    this.getNumChildren	= function () { return numChildren; };
    this.addChild		= function (child) { children[child.nodeid] = child; numChildren++; };
    this.isChild		= function (id) { return typeof children[id] != 'undefined'; };
    this.getNode		= function () {
        if (arguments.length == 1) {
            return this.getChild(arguments[0]);
        } else {
            var tempArr = [];
            for( var i=1, len=arguments.length; i<len; i++ ) tempArr[i-1] = arguments[i];
            return arguments.callee.apply(this.getChild(arguments[0]),tempArr);
        }
    };
    this.findNode		= function (id) {
        if (nodeid == id) {
            return this;
        } else {
            for ( var i in children ) {
                var newNode = this.getNode(i);
                if ( newNode == null ) continue;
                var subNode = newNode.findNode(id);
                if (subNode == null) continue;
                return subNode;
            }
            return null;
        }
    };
    this.addNode	= function (parentid, node) { this.findNode(parentid).addChild(node); };
    this.toString	= function () { var out="ID: "+nodeid+"<br/>Value: "+nodevalue+"<br/>Children: "; for(var i in children) out+=i+" "; return out+"<br/>"; };
}

function Paginator(nitemstoshow, total, objectid, onvalue) {
	var nItemsToShow = nitemstoshow;
	var totalItems = total;
	var id = objectid;
	var onValue = onvalue;
	var cursor = 0;
	
	this.showList = function() {
		var stop = cursor + nItemsToShow;
		if(stop > totalItems) {
			stop = totalItems;
		}
		var t;
		var s;
		for(i=0; i< totalItems; i++) {
			t = id + '-' + i;
			s = 'none';
			if(i>=cursor && i < stop) {
				s=onValue;
			}
			toggleCssDisplay(t, s);
		}
	};
	
	this.paginateList = function() {
	
		cursor += nItemsToShow;
		if(cursor >= totalItems) {
			cursor = 0;
		}
		this.showList();
	};
}

function fixUrl(element) {
	if(element && element.value != '') {
		if((element.value.indexOf(".") == -1) && (element.value.indexOf("localhost") == -1)) {
			alert("The URL you entered does not look valid");
			element.focus();
			return false;
		}
		if(element.value.length > 7) {
			if(element.value.substring(0,7) != 'http://') {
				element.value = 'http://' + element.value;
			}
		} else {
			element.value = 'http://' + element.value
		}
	}
	return false;
}

// disables Enter key from submitting form for all text fields in form
function disableEnterSubmit(form) {
	for ( var i=0, len=form.elements.length; i<len; i++) { 
		input=form.elements[i]; 
		if(input.type == "text") {
			input.onkeypress = function (e) { return noenter(e) };
		} 
	}
}

var isChecked = false;
function updateCharsLeft(chars, minChars) {
	if (chars >= minChars) {
		var ret = '';
		if(!isChecked) {
			ret = "<img src='"+IMAGEPATH+"icons/green_check_blue.gif' alt='check'/>";
		}
		isChecked = true;
		return ret;
	} else {
		isChecked = false;
		return "<span class='needmore'>You need <span class='num'>"+(minChars-chars)+"</span> more characters</span>";
	}
}

function clickAddToTagFormField(formname, formField, entry ,isMulti,locfield) {
	if(formField.value.length > 0) {
		var trimmed = trim(formField.value);
		if(trimmed.length > 0) {
			if (trimmed.charAt(trimmed.length - 1) == ','){ 
				formField.value = trimmed + " ";
			} else {
				formField.value = trimmed + ", ";
			}
		}
	}
	if(isMulti){
		formField.value += entry + ", ";
		setCursorPosition(formField, formField.value.length);
	} else {
		formField.value =entry
		if(locfield) {
			lookupSingleKeyword(entry, 'Location', formname, locfield);
		}
	}
	return false; 
}	

function setCursorPosition(obj, pos) { 
    if(obj.createTextRange) { 
        var range = obj.createTextRange(); 
        range.move("character", pos); 
        range.select(); 
    } else if(obj.selectionStart) {  
        obj.focus(); 
        obj.setSelectionRange(pos, pos); 
    }
} 

function addCompliment(etype,eid,elementID,label,uid) {
	var html = "";
	html += "<div class=\"close\"><a href=\"#\" onclick=\"$('pop-"+elementID+"').innerHTML='';return false;\">X</a></div>";
	if (label) html += "<label for=\"text-"+elementID+"\">"+label+":</label>";
	html += "<textarea id=\"text-"+elementID+"\" class=\"text-compliment\"/></textarea><br/>";
	html += "<div class=\"desc\">Your Thank You will appear on member's Profile page when approved</div>";
	html += "<div class=\"nav\">";
	html += "	<a href=\"#\" onclick=\"$('pop-"+elementID+"').innerHTML='';return false;\">Cancel</a>";
	html += "	<a class=\"sendlink\" href=\"#\" onclick=\"if(sendCompliment('"+etype+"','"+eid+"',$('text-"+elementID+"').value,'create','"+uid+"')) { $('pop-"+elementID+"').innerHTML=''; } return false;\"><img src=\""+IMAGEPATH+"button_blue_send_b.gif\" alt=\"Send\" border=\"0\"/></a>";
	html += "</div>";
	return html;
}

function addComplimentNotLoggedIn() {
	var html = '<a href="Login.do">Login</a> or <a href="Registration_Step1.do">Register</a> to Add a Thank You';
	return html;
}

function addComplimentOld(fromUserID,toUserID,elementID,label) {
	var sl = $('span-'+elementID);
	if ($('addcomp-'+elementID)) {
		sl.removeChild($('addcomp-'+elementID));
		return;
	}
	var node = document.createElement('div');
	node.id = "addcomp-"+elementID;
	node.className = "addcomp";
	var html = "";
	if (label) html += "<label for=\"text-"+elementID+"\">"+label+":</label>";
	html += "<textarea id=\"text-"+elementID+"\" class=\"text-compliment\"/></textarea><br/>";
	html += "<a class=\"sendlink\" href=\"#\" onclick=\"sendCompliment('"+fromUserID+"','"+toUserID+"','text-"+elementID+"'); return false;\"><img src=\""+IMAGEPATH+"button_blue_send.gif\" alt=\"Send\" border=\"0\"/></a>";
	node.innerHTML = html;
	sl.appendChild(node);
}

function subArray(arr) {
 	var arr2 = [];
  	var count = 0;
    for (var i = (arguments[1]||0); i < (arguments[2]||arr.length); i++)
      arr2[count++]=arr[i];
    return arr2;
}

function popShadowBox(outerid,innerclass,popid) {
	//codeDebug = true;
	if ($(popid).innerHTML != ''){
		$(popid).innerHTML = '';
		return;
	}
	var f = arguments[3] || defaultConfirm;
	//debug(f + ":" + f.id);
	var popDiv = $(popid);
	popDiv.className = "popdiv";
	var html = '<div class="shadow select-popup pop-outer" id="'+outerid+'">';
	html += '		<div class="shadow-inner pop-inner '+innerclass+'" id="'+outerid+'-inner">';
	html += f.apply(arguments[arguments.length-1],subArray(arguments,4));
	html += '		</div>';
	html += '	</div>';
	popDiv.innerHTML = html;
}


function popDimPage(outerid,innerclass,ePos) {
	if ($('popdiv')){
		closeAndUndim('popdiv');
		return;
	}
	debug("ePos: "+ePos);
	var f = arguments[3] || defaultConfirm;
	var popDiv = document.createElement('div');
	popDiv.id="popdiv";
	var shadowDiv = document.createElement('div');
	shadowDiv.className = "shadow select-popup pop-outer";
	shadowDiv.id = outerid;
	shadowDiv.style.marginTop = ePos[1]+"px";
	shadowDiv.style.left = ePos[0]+"px";
	var shadowInnerDiv = document.createElement('div');
	shadowInnerDiv.className = "shadow-inner pop-inner "+innerclass;
	shadowInnerDiv.id = outerid + "-inner";
	shadowDiv.appendChild(shadowInnerDiv);
	popDiv.appendChild(shadowDiv);
	document.body.insertBefore(popDiv,document.body.firstChild);
	shadowInnerDiv.innerHTML = f.apply(this,subArray(arguments,4));
	dimElement($('main-table'));
	//debug("popdiv position: "+findPos($('popdiv')));
	//debug("popdiv position: "+findPos($('popdiv')));
	//debug(outerid+" position: "+findPos($(outerid)));
	//debug(outerid + "-inner position: "+findPos($(outerid + "-inner")));
	//debug(findPos($('')));
}

function closeAndUndim(popid,pageid) {
	pageid = pageid || "main-table";
	document.body.removeChild($(popid));
	undimElement($(pageid));
}

function dimElement(element,level) {
	var level = level || 0.5;
	element.style.opacity = ""+level;
	element.style.filter = "alpha(opacity="+(level*100)+")";
}

function undimElement(element) {
	dimElement(element,1);
}

/*
*	Thanks to Peter-Paul Koch at quirksmode
*	http://www.quirksmode.org/js/findpos.html
*/
function findPos(obj) {
/*
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	//debug(obj.id + ": "+[curleft,curtop]);
	return [curleft,curtop];
*/
	return [findPosX(obj),findPosY(obj)];
}

function findPosX(obj) {
	var curleft = 0;
	if(obj.offsetParent)
		while(1) {
			curleft += obj.offsetLeft;
			if(!obj.offsetParent)
				break;
			obj = obj.offsetParent;
		}
	else if(obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	if(obj.offsetParent)
		while(1) {
			curtop += obj.offsetTop;
			if(!obj.offsetParent)
				break;
			obj = obj.offsetParent;
		}
	else if(obj.y)
		curtop += obj.y;
	return curtop;
}

var toggleFormSubmitted = false;			
function toggleSaving(divSubmitID, divProgressID, imgProgressID) {
	var html;
	if (! toggleFormSubmitted) {
		toggleFormSubmitted = true;
		ProgressImg = document.getElementById(imgProgressID);
		toggleCssDisplay(divSubmitID, 'none');
		document.getElementById(divProgressID).style.visibility = "visible";
		setTimeout("ProgressImg.src = ProgressImg.src",100);
		return true;
	} else {
		return false;
	}
}