// Register Global Responder for onFailure callback on all Ajax Calls.
var searchTimer;

var isSafari = navigator.userAgent.toLowerCase().indexOf( 'safari' ) != -1;

Ajax.Responders.register({
	onCreate: function(request, transport, json) 
	{
		//$('waitIndicator').style.display="block";
	},
	onComplete: function(request, transport, json)
	{     
		//alert('onComplete ' + json);
		//$('waitIndicator').style.display= "none";
		if (json && json.callback) 
		{
			execute(json.callback);
		}
		else
		{
			// Don't gotoErrorPage if request has custom onFailure handler
			if (!request.success() && !request.options['onFailure'])
			{
				gotoErrorPage();
			}
		}
	}
});

// Determine if user is logged in
function isLoggedIn() {
	return ($('signindiv').style.display == "none");
}

// Toggle an image
function toggleImg(img, imgName) {
	img.src = staticContentBase + "/images/" + imgName;
}

// Generic error page forward
function gotoErrorPage(json) {
	document.location = contextRoot + "/error.html";
}

// Generic forward to force login
function gotoForceLogin() {
	document.location = contextRoot + "/forceSignin.html";
}

// Generic JSON error handler
function doJsonError(json) {
	displayError("Error performing function " + json.error);
	gotoErrorPage(json);
}

// Generic print function
function printPage() {
	window.print();
}

// Placeholder for contextual widgit resizing
function resizeContextualWidgets() {
	alert("Window resized!");
}

// Navigates to specific page
function gotoit(page) {
	document.location= contextRoot + "/" + page;
	return false;
}

// Go's to a specific video in either the skills or video
// section depending on your logged in state
function gotoCalloutVideo(section, vid) {
	var tab = "skills";
	if (isLoggedIn()) {
		tab = "video";
	}
	if (vid && vid != '') {
		return gotoit(tab + "/" + section + "/" + vid + ".html");
	} 
	return gotoit(tab + ".html");
}

// Generic display an error function
function displayError(msg)
{
	alert(msg);
}
// Utility function to replace a page in a div via an 
// Ajax 'get'
function AjaxReplacePage(div, page, pars, async) {
	var url = contextRoot + "/" + page;
	if (async === null) {
		async = true;
	} else {
		async = false;
	}
	
	var httpRequest = new Ajax.Request(
		url,
		{
			method: 'get',
			asynchronous: async,
			parameters: pars,
			onSuccess: function(transport) {
				$(div).innerHTML = transport.responseText;
			},
            requestHeaders: ['Content-Type', 'text/html;charset=UTF-8']
		});
}
// Utility function to replace a page in a div via an 
// Ajax update
function AjaxUpdateDiv(div, page) {
	var url = contextRoot + "/" + page;
	new Ajax.Updater(div, url,
			{
				// force script execution in root Javascript context
				// note that in IE, variables must be predefined in root html
				asynchronous: false,
				// evaluate <script> blocks
				evalScripts: true
			});
}

// Utility function for all numeric string check
function IsNumeric(sText)
{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
   { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) {
         IsNumber = false;
      }
   }
   return IsNumber;
}
function textCounter(field, countdiv, maxlimit) {
        var text='';
	if (field) {
		var remaining = maxlimit - field.value.length;
		if (remaining < 0) {
			field.value = field.value.substring(0, maxlimit);
			remaining = 0;
                        text ="you have reached the character limit for this field";
		}
                else
                    text = remaining + " character" + (remaining != 1 ? "s" : "") + " remaining...";
		
	} 
	if ($(countdiv)) $(countdiv).innerHTML = text;
}

function validEmail(e)
{
	//e = e.replace(/^\s+|\s+$/g, '');
	//if ( (e == '') || !((e.indexOf('.') > 2) && (e.indexOf('@') > 0)) || e.indexOf(',') > 0)	
	//	return false;

	//return true;
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(e)){
		return true;
	}
	return false;
}

function validPhone(p)
{
	p = p.replace(/^\s+|\s+$/g, '');
	if (!IsNumeric(p) || p.length != 10) return false;

	return true;
}

// Scale an image 
function scale_image(imgId, containerWidth)
{
	var img = document.getElementById(imgId);
	var box = img.parentNode; //document.getElementById("container");

	// Grab the image's dimensions
	var imgH = img.clientHeight;
	var imgW = img.clientWidth;

	// Find which dimension is scaled the most
	var scaleH = box.clientHeight / img.clientHeight;
	//var scaleW = box.clientWidth / img.clientWidth;
	
	// The above does not work in ie6 as the container width automatically
	// expands to the size of the contained image, so the scale is always
	// effectively 1.0
	var scaleW = containerWidth / img.clientWidth;
	
	// Scale the image
	if (scaleH < scaleW) {
		img.style.height = box.clientHeight + "px";
		img.style.width = Math.round(imgW * scaleH) + "px";
	} else {
		//img.style.width = box.clientWidth + "px";
		// See aboove comment for why we can't use box.clientWidth
		img.style.width = containerWidth + "px";
		img.style.height = Math.round(imgH * scaleW) + "px";
	}
}

// Peform the submit to track an accordian's state
function trackAccordionState(openIndex, acc)
{
	var url = contextRoot + '/AccordionState.do';
	var options = {
			parameters: {
				id: acc.id,
				openIndex: openIndex
			}
	};
    new Ajax.Request(url, options);
}

// Execute or eval function or string passed in
function execute(fn, json, pars) {
	var type = typeof(fn);
	if (type == 'function') {
		fn(json, pars);
	} else if (type == 'string') {
		eval(fn);
	} else {
		displayError("doJsonAjaxRequest: unsupported function data type - " + type);
	}
}

// Generic Ajax request method.
// NOTE: onFailure is automatically handled in the Global Responder
//		 defined at the top of the page.
function doJsonAjaxRequest(url, pars, succeedFunction, errorFunction ) {
	var options = {
		parameters: pars,
		onSuccess: function(transport,json) {
		  	//alert(json ? Object.inspect(json) : "no JSON object");
		   	if (json.ok)
		   	{
		   		if (succeedFunction) execute(succeedFunction, json, pars); 
		   	}
		   	else // error
		   	{
		   		if (errorFunction) {
		   			execute(errorFunction, json, pars);
		   		} else {
		   			doJsonError(json);
		   		}
		    }
		}
	};
    new Ajax.Request(url, options);	
    return false;
}

// Not sure if we need this.
function doJsonAjaxUpdater(div, url, pars) {
	var options = {
		asynchronous: false,
		evalScripts: true,
		parameters: pars,
		onFailure: function(transport,json) {
		  	doJsonError(json);
		}
	}
	new Ajax.Updater(div, url, options);
}

function doShowInviteFriendPopup() {
	showForminvite(contextRoot + "/inviteFriend.jsp");
    return false;
}
function cancelOverlayInviteEmail() {
	closeForminvite();
	return false;
}
function sendOverlayInviteEmail() {
	if (validateInviteOverlayEmail()) {
		var toList = $F('inviteOverlayTo');
		var url = contextRoot + '/emailInviteFriend.do';
		var pars = {
			fromName: $F('inviteFromName'),
			fromEmail: $F('inviteFromEmail'),
			email: toList,
			message: $F('inviteOverlayMsg')
		};
		
    	doJsonAjaxRequest(url, pars, emailOverlaySuccess, emailOverlayFailure);
    
	}
	return false;
}
function validateInviteOverlayEmail() {
	var rlist = $F('inviteOverlayTo');
    var recpts = $A(rlist.split(','));
    var errors = false;
    var s = "";
	recpts.each(function(recipient) {
		if (!validEmail(recipient)) {
			errors = true;
		}
	});
	if (errors) s = s + 'Please enter valid \'To\' email addresses.<br />';
	if (!validEmail($F('inviteFromEmail'))) {
		errors = true;
		s = s + "Please enter a valid 'From' email address.<br />";
	}
	if ($F('inviteFromName') == "") {
		errors = true;
		s = s + "Please enter Your Name <br />";
	}
	
	if (errors) {
		$('inviteOverlayErrors').innerHTML = s;
		$('inviteOverlayErrors').style.display="block";
	} else {
		$('inviteOverlayErrors').innerHTML ='';
		$('inviteOverlayErrors').style.display="none";
	}
	return !errors;
}
// emailSuccess
function emailOverlaySuccess() {
	displayEmailMsg('Thanks, we hope they enjoy it!<br/>' +
						'Your Email has been sent to:<br/>' + 
						$F('inviteOverlayTo'));
}

// emailFailure
function emailOverlayFailure() {
	displayEmailMsg('Sorry, there were errors attempting to send your email to:<br/>' +
						$F('inviteOverlayTo'));
}
// Function display the message in the email div
function displayEmailMsg(msg) {
	$('emailInviteOverlayContainer').style.display = 'none';
	$('emailThanksOverlayContainer').style.display = 'block';
	$('emailThanksOverlayContainer').innerHTML= msg;
}

// function inviteFriend
function inviteFriend(mid, id, email, fname, lname, userfname, userlname, sendInvite) {
    
	var url = contextRoot + '/memberMail.do';
	var pars = {
		action: "sendInvite",
		memberId: mid,
		message: $F('inviteMessage' + id),
                toEmail:email,
                firstName:fname,
                lastName:lname,
                userFirstName:userfname,
                userLastName:userlname,
                sendEmail:sendInvite
	};
	
   	doJsonAjaxRequest(url, pars, function() {
   		$('inviteFormWrapper' + id).style.display = "none";
   		$('inviteStatusArea' + id).style.display = "block";
   	},
   	function(json) {
   		// Failure gets called when an invitation cannot be issued
   		var s = json.error;
   		if (s != "") {
   			$('inviteFormWrapper' + id).style.display = "none";
   			$('inviteStatusArea' + id).innerHTML = s;
   			$('inviteStatusArea' + id).style.display = "block";
   		}
   	});
	return false;
}

function toggleInviteFriendForm(div, id, gid) {
	var qpos = syncGroupedBlindDowns(div, id, gid);
	if ($(div).className == "tab_selected") {
		$(div).className = "tab";
		Effect.BlindUp('InviteFriendForm'+id);
	} else {
		$(div).className = "tab_selected";
		Effect.BlindDown('InviteFriendForm'+id, { queue: qpos});
		textCounter($('inviteMessage'+id), 'inviteMessageCounter'+id, 1024);
	}
	return false;
}

function acceptInvite(id) {
	var url = contextRoot + '/memberMail.do';
	var pars = {
		action: "acceptInvite",
		inviteId: id
	};
	
   	doJsonAjaxRequest(url, pars, function() {
   		var cnt = $F('inviteCount') - 1;
   		var s= ''; 
   		if (cnt > 0) {
   			s = "(" + cnt + " New! Sa-weet!)";
   		}
   		$('numInvites').innerHTML = s;
   		$('invite' + id).style.display = "none";
   		$('accept' + id).style.display = "block";
   	});
	return false;
}

function rejectInvite(id) {
	var url = contextRoot + '/memberMail.do';
	var pars = {
		action: "rejectInvite",
		inviteId: id
	};
	
   	doJsonAjaxRequest(url, pars, function() {
   		var cnt = $F('inviteCount') - 1;
   		var s= ''; 
   		if (cnt > 0) {
   			s = "(" + cnt + " New! Sa-weet!)";
   		}
   		$('numInvites').innerHTML = s;
   		$('invite' + id).style.display = "none";
   		$('reject' + id).style.display = "block";
   	});
	return false;
}

function startSearchTimer() {
	searchTimer = setInterval("memberSearch()", 500);
}
function stopSearchTimer() {
	clearInterval(searchTimer);
}
function memberSearch() {
	if ($F('screenNameFragment') != '' && $F('screenNameFragment') != oldScreenNameFragment && searching == false){
    	$('searchMessage').innerHTML = 'searching....';
    	searching = true;
   		
    	oldScreenNameFragment= $F('screenNameFragment');
	    var url = contextRoot + "/searchMembers.do";
	    var options = { 
	  		asynchronous: false,
			evalScripts: true,
			parameters: {
				fragment: $F('screenNameFragment'),
				resultsPage: resultsPage
			},
			onSuccess: function(transport) {
				// provide the illusion of a search taking some time.
				// when some searches return rediculously fast, you 
				// never see the message
	            setTimeout('clearSearchMessage()', 500);
	          	searching = false;
	        },
	        onFailure: function(transport) {
	        	$('searchMemberContents').innerHTML = '';
	        	setTimeout('clearSearchMessage()', 500);
	        	searching = false;
	        }
		};
		new Ajax.Updater('searchMemberContents', url, options);
		
	} 
}	

function clearSearchMessage() {
	$('searchMessage').innerHTML = ''
}

function toggleGiveStarForm(div, id, gid) {
	var qpos = syncGroupedBlindDowns(div, id, gid);
	if ($(div).className == "givestar") {
		$(div).className = "givestar_selected";
		Effect.BlindDown('GiveStarForm'+id, { queue: qpos});
		textCounter($('starMessage'+id), 'starMessageCounter'+id, 1024);
	} else {
		$(div).className = "givestar";
		Effect.BlindUp('GiveStarForm'+id);
	}
	return false;
}
function giveStar(id, mid, source, screenName, blogId, email, fname, lname, userfname, userlname,sendStar) {
	var url = contextRoot + '/memberMail.do';
	var bid = 0;
	if (blogId) bid = blogId;
	var pars = {
		action: "giveStar",
		memberId: mid,
		source: source,
		blogId: bid,
		message: $F('starMessage' + id),
                toEmail:email,
                firstName:fname,
                lastName:lname,
                userFirstName:userfname,
                userLastName:userlname,
                sendEmail:sendStar,
                screenName:screenName
	};
	
   	doJsonAjaxRequest(url, pars, function(json) {
   		$('giveStarFormWrapper' + id).style.display = "none";
   		$('giveStarStatusArea' + id).style.display = "block";
   		$('giveStarStatusArea' + id).innerHTML = "Thanks! Your star has been sent to " + json.screenName + ".";
	},
	function() {
		$('giveStarFormWrapper' + id).style.display = "none";
   		$('giveStarStatusArea' + id).style.display = "block";
   		$('giveStarStatusArea' + id).innerHTML = "You can only give a star to a specific person once a day.";
	
	});
	
	// To do add blog comment linked to star
	return false;
}

function sendMessageBack(id,email,fname,lname,userfname,userlname,messageEmail) {
	var url = contextRoot + '/memberMail.do';
	var pars = {
		action: "sendMessageBack",
		memberId: id,
		subject: $F('sendBackSubject' + id),
		message: $F('sendBackMessage' + id),
                toEmail:email,
                firstName:fname,
                lastName:lname,
                userFirstName:userfname,
                userLastName:userlname,
                sendEmail:messageEmail
	};
	
   	doJsonAjaxRequest(url, pars, function() {
   		$('sendBackWrapper' + id).style.display = "none";
   		$('sendBackStatusArea' + id).style.display = "block";
   	});
	return false;
}
function toggleSendBackForm(div, id, gid) {
	var qpos = syncGroupedBlindDowns(div, id, gid);
	if ($(div).className == "sendmessage") {
		$(div).className = "sendmessage_selected";
		Effect.BlindDown('SendMessageBackForm'+id, { queue: qpos});
		textCounter($('sendBackMessage' + id), 'sendBackMessageCounter' + id, 1024);
	} else {
		$(div).className = "sendmessage";
		Effect.BlindUp('SendMessageBackForm'+id);
	}
	return false;
}
function toggleComposeMessage(div, id, gid) {
	var qpos = syncGroupedBlindDowns(div, id, gid);
	if ($(div).className == "compose") {
		$(div).className = "compose_selected";
		initSendMessage(id);
		Effect.BlindDown('ComposeNewMessageForm'+id, { queue: qpos});
		textCounter($('composeMessage' + id), 'composeMessageCounter' + id, 1024);
	} else {
		$(div).className = "compose";
		Effect.BlindUp('ComposeNewMessageForm'+id);
	}
	return false;
}
function sendMessage(id,userfname,userlname) {
	var url = contextRoot + '/memberMail.do';
	if (validateSendMessage(id) == true) {
		var pars = {
			action: "sendMessage",
			to: $F('composeTo' + id),
			subject: $F('composeSubject' + id),
			message: $F('composeMessage' + id),
                        firstName:$F('composeTo' + id),
                        userFirstName:userfname,
                        userLastName:userlname
                        
		};
		
	   	doJsonAjaxRequest(url, pars, function() {
	   		$('composeNewMessageWrapper' + id).style.display = "none";
	   		$('composeNewMessageStatusArea' + id).style.display = "block";
	   		var rlist = $F('composeTo' + id).split(",");
	   		var s = "";
	   		for (var i = 0; i < rlist.length; i++) {
	   			s = s + rlist[i] + "<br />";
	   		}
	   		$('recipientList' + id).innerHTML = s;
	   	}, function(json) {
	   		$('composeError' + id).style.display="block";
			$('composeError' + id).innerHTML = json.error;
	   	});
   	}
	return false;
}
function validateSendMessage(id) {
	var errors = false;
	var s = "";
	if ($F('composeTo' + id) == "") {
		s = s + "Please enter a member to send the message to.<br />";
		errors = true;
	} 
	if ($F('composeSubject' + id) == "") {
		s = s + "Please enter a Subject.<br />";
		errors = true;
	}
	if ($F('composeMessage' + id) == "") {
		s = s + "Please enter a message.<br />";
		errors = true;
	}
	if (errors) {
		$('composeError' + id).style.display="block";
		$('composeError' + id).innerHTML = s;
	} else {
		initSendMessage(id);
	}
	return !errors;
}
function initSendMessage(id) {
	if ($('composeError' + id)) {
		$('composeError' + id).style.display="none";
		$('composeError' + id).innerHTML = '';
	}
}
function initReportForm(id) {
	if ($('offensiveMember' + id)) {
		$('offensiveMember' + id).style.display="none";
		$('offensiveMember' + id).innerHTML = '';
	}
}
function validateReportMember(id) {
	var errors = false;
	var s = "";
	if ($F('reportName' + id) == "") {
		s = s + "Please enter a name.<br />";
		errors = true;
	}
	if (!validEmail($F('reportEmail' + id))) {
		s = s + "Please enter a valid email address.<br />";
		errors = true;
	}
	if ($F('reportReason' + id) == "") {
		s = s + "Please enter a reason.<br />";
		errors = true;
	}
	if (errors) {
		$('offensiveMember' + id).style.display="block";
		$('offensiveMember' + id).innerHTML = s;
	} else {
		initReportForm(id);
	}
	return !errors;
}
function reportMember(id, mid, reason, message) {
	var url = contextRoot + '/ReportUser.do';
    
    if (validateReportMember(id) == true) {
	    var pars = {
	            id: mid,
	            offensiveReason: $F(reason),
	            offensiveMessage: $F(message)
	        };
	    doJsonAjaxRequest(url, pars, function() {
	   		$('reportMemberFormWrapper' + id).style.display = "none";
	   		$('reportMemberStatusArea' + id).style.display = "block";
	   		$('reportMemberStatusArea' + id).innerHTML = "Thanks! One of our site administrators will evaluate this content very soon.";
		});
	}
    return false;
}
function toggleReportMember(div, id, gid) {
	var qpos = syncGroupedBlindDowns(div, id, gid);
	if ($(div).className == "report") {
		$(div).className = "report_selected";
		initReportForm(id);
		Effect.BlindDown('ReportMemberForm'+id, { queue: qpos});
		textCounter($('reportMessage' + id), 'reportMemberCounter' + id, 1024);
	} else {
		$(div).className = "report";
		Effect.BlindUp('ReportMemberForm'+id);
	}
	return false;
}
function syncGroupedBlindDowns(div, id, gid) {
	var qpos = "front";
	if (gid) {
		var group = $F(gid+id);
	
		var g = $A(group.split(","));
	
		g.each(function(tab) {
			var cn = $(tab).className;
			if (cn.indexOf("_selected") != -1 && tab != div) {
				var ncn = cn.substring(0, cn.indexOf("_selected"));
				$(tab).className = ncn;
				
				var tn = "";
				switch(ncn) {
					case 'report': 
						tn  = 'ReportMemberForm';
						break;
					case 'deletemessage': 
						tn = 'DeleteMessageForm';
						break;
					case 'replymessage': 
						tn = 'ReplyMessageForm';
						break;
					case 'compose':
						tn = 'ComposeNewMessageForm';
						break;
					case 'sent':
						tn = 'SentMessages';
						break;
					case 'sendmessage':
						tn = 'SendMessageBackForm';
						break;
					case 'givestar':
						tn = 'GiveStarForm';
						break;
					case 'remove':
						tn = 'RemoveFriendsForm';
						break;
					case 'tab':
						tn = "InviteFriendForm";
						break;
				}
				if (tn != "") {
					Effect.BlindUp(tn + id);
					qpos = "end";
				}
			}
			
		});
	}
	
	return qpos;
}
/**
 * Returns the value of the selected radio button in the radio group
 * 
 * @param {radio Object} or {radio id} el
 * OR
 * @param {form Object} or {form id} el
 * @param {radio group name} radioGroup
 */
function RF(el, radioGroup) {
	if($(el).type == 'radio') {
		var el = $(el).form;
		var radioGroup = $(el).name;
	} else if ($(el).tagName.toLowerCase() != 'form') {
		return false;
	} 
	var radio = ($(el).getInputs('radio', radioGroup).find(
		function(re) {return re.checked;}
	));
	if (radio) return $F(radio);
	return "";
}
function openSiteTour() {
	var w = window.open("siteTour.html", "sitetour", "width=930,height=490");
	return false;
}

// Return scrollbar X position of main window
// see http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
// Return scrollbar Y position of main window
// see http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
// Used by f_scrollLeft() and f_scrollTop()
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

// Trim leading and trailing whitespace
function trim(s)
{
	return s.replace(/^\s+|\s+$/g, '');
}

