Date.format = 'mm/dd/yyyy';

var sliderMin = 0;
var sliderMax = 200;
var sliderVal = 50;

var emailAddressCount = 0;
var findRegistryResultsFirst = true;
var addAnotherMoneyUnitCur = 1;
var all_question_options = null;
var total_security_questions = 3;

isOpera = navigator.userAgent.match(/opera/i);
isIE = !isOpera && navigator.userAgent.match(/msie/i);
isIE6 = isIE && (navigator.userAgent.match(/msie 6/i));
isFirefox = navigator.userAgent.match(/firefox/i);
isSafari = navigator.userAgent.match(/safari/i);

// Read referral_code and set to cookie
if(document.location.search.match(/referral_?[cC]ode=([^&]*)/)) {
	var cookieString = "referralCode=" + RegExp.$1 + ";path=/";
	if (RegExp.$1.length == 0) {
		cookieString = cookieString + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
	document.cookie = cookieString;
}

// Read beta features and set to cookie
if(document.location.search.match(/beta_?[fF]eatures=([^&]*)/)) {
	var cookieString = "betaFeatures=" + RegExp.$1 + ";path=/";
	if (RegExp.$1.length == 0) {
		cookieString = cookieString + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
	document.cookie = cookieString;
}

//Read invitation code and set to cookie
if(document.location.search.match(/^\??code=([^&]*)/i)) {
	setInvitationCookie(RegExp.$1);
}
function setInvitationCookie(value) {
	var cookieString = "invitationCode=" + value + ";path=/";
	if (value.length == 0) {
		cookieString = cookieString + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
	document.cookie = cookieString;
	
}

$.fn.centerInClient = function(options) {
    // / <summary>Centers the selected items in the browser window. Takes into
	// account scroll position.
    // / Ideally the selected set should only match a single element.
    // / </summary>
    // / <param name="fn" type="Function">Optional function called when
	// centering is complete. Passed DOM element as parameter</param>
    // / <param name="forceAbsolute" type="Boolean">if true forces the element
	// to be removed from the document flow
    // / and attached to the body element to ensure proper absolute positioning.
    // / Be aware that this may cause ID hierachy for CSS styles to be affected.
    // / </param>
    // / <returns type="jQuery" />
    var opt = { forceAbsolute: false,
                container: window,    // selector of element to center in
                completeHandler: null
              };
    $.extend(opt, options);
   
    return this.each(function(i) {
        var el = $(this);
        var jWin = $(opt.container);
        var isWin = opt.container == window;

        // force to the top of document to ENSURE that
        // document absolute positioning is available
        if (opt.forceAbsolute) {
            if (isWin)
                el.remove().appendTo("body");
            else
                el.remove().appendTo(jWin.get(0));
        }

        // have to make absolute
        el.css("position", "absolute");

        // height is off a bit so fudge it
        var heightFudge = isWin ? 2.0 : 1.8;

        var x = (isWin ? jWin.width() : jWin.outerWidth()) / 2 - el.outerWidth() / 2;
        var y = (isWin ? jWin.height() : jWin.outerHeight()) / heightFudge - el.outerHeight() / 2;

        el.css("left", x + jWin.scrollLeft());
        el.css("top", y + jWin.scrollTop());

        // if specified make callback and pass element
        if (opt.completeHandler)
            opt.completeHandler(this);
    });
}

function maskInputs(target) {
	if (!target) target = $("body");
	target.find('#phone_masked').mask("(999) 999-9999",{placeholder:" "});
	target.find('#phone_number_p1').mask("(999) 999-9999",{placeholder:" "});
	target.find('#phone_number').mask("(999) 999-9999",{placeholder:" "});
	target.find('#phone_number_re_enter_p1').mask("(999) 999-9999",{placeholder:" "});
	target.find('#ssn_number, #ssn_number_re_enter, #beneficial_owner_ssn_number, #beneficial_owner_ssn_number_re_enter').mask("999-99-9999",{placeholder:" "});
	target.find('#forgot_password_id').mask("999-99-9999",{placeholder:" "});
}

var documentIsReady = false;
$(document).ready(function(){
	documentIsReady = true;
	try {
		if(!window['printWindow'])
		{
			var totalRow = $('#account_transaction_history tr').length - 1;
		
			if ($("#account_transaction_history").dataTable) {
				$("#account_transaction_history").dataTable({
							"bFilter": false, 
							"bSort": false, 
							"sPaginationType": "full_numbers"       			
			 		});
				$("#account_transaction_history").each(function() {
					if (totalRow <= 10) {
						$("#account_transaction_history_info").hide();			
						$("#account_transaction_history_length").hide();			
						$(".dataTables_paginate").hide();			
					} else {
						$("#account_transaction_history_info").show();			
						$("#account_transaction_history_length").show();			
						$(".dataTables_paginate").show();			
					}
				});
			}
		}
	} catch (exception) {
		// do nothing, as we expect this to sometimes fail (if table has no
		// data)
	}

	/* Text input */
	// Add Description
	$("input[type='text'],textarea").attr('value', function(){
		var thisObj = $(this);
		
		if (thisObj.val()=='' && thisObj.attr('title').length) {
			thisObj.addClass('inputDescription');

			return thisObj.attr('title');	
		}
		
	});
	// On focus
	$("input[type='password'],input[type='text'],textarea,select").focus(function(){
		$("input[type='password'],input[type='text'],textarea,select").removeClass('hasFocus');
		var thisObj = $(this);
		thisObj.addClass('hasFocus');
	});
	$("input[type='text'],textarea").focus(function(){
		var thisObj = $(this);
		var title = thisObj.attr('title');
		var value = thisObj.val();		
		
		if (value==title) {			
			currentFocus = thisObj;
			thisObj.val("");
			thisObj.select();
		}
		thisObj.removeClass('inputDescription');
	});
	// On blur
	$("input[type='password'],input[type='text'],textarea,select").blur(function(){
		var thisObj = $(this);
		thisObj.removeClass('hasFocus');
	});
	
	$("input[type='text'],textarea").blur(function(){
		 
		 var thisObj = $(this);
		 var title = thisObj.attr('title'); var value = thisObj.val();
	    if (value=='') { 
	    	thisObj.addClass('inputDescription').val(title); 
	    }
	    return true;
	  });
	
	/* Auto submit on enter */
	$('.submitOnEnter input').keydown(function(e) {
		if(e.keyCode == 13) {
			var obj = $(this);
			while (obj && !obj.is('form'))
				obj = obj.parent();
			clearDefaults();
			$(obj).submit();
			return false;
		}
		return true;
	});

	/* Modal Window */
	/* Close */
	$('.closeModalWindow, .closeModalWindowNormal').live("click", function() {
		$('.modalOverlay, .modalOverlayNoClose').remove();
		
		$(this).closest(".modalWindow").hide();

		return false;
	});
	
	$(".modalOverlay").click(function(){
	    $('.closeModalWindow').click();
	});
	
	$(".modalWindowAuto").bind("open", function(event, openedBy, width, height) {
		$('body').append('<div class="modalOverlay"></div>');
        var boxObj = $(this);
        if (openedBy) {
			var pos = $(openedBy).offset();
			var openerWidth = $(openedBy).width();
			var curLeft = pos['left'];
	        var curTop = pos['top'];
	        if (width)
	        	boxObj.css("left", curLeft + (openerWidth / 2) - (width / 2));
	        if (height)
	        	boxObj.css("top", curTop - (height / 2));
	    }
        if (width)
        	boxObj.css("width", width);
        if (height)
        	boxObj.css("height", height);
        boxObj.show();
	});


	/**
	 * Login Submit
	 */
	$("#formLogin input#password_verify_email").keydown(function(e){if(e.keyCode ==13){$("#formLogin").submit();return false;}});
	/*
	 * $("#formOpenAccount input").keydown(function(e){if(e.keyCode
	 * ==13){$("#formOpenAccount").submit();return false;}});
	 */
	
	$("#loginFormBottom .loginSubmit").click(function(){
		$('#formLogin').submit();

		return false;
		
	});

	/**
	 * Search Submit
	 */
	 
	$("#searchPeopleSubmit").click(function(){
		$('#formHomePageSearch').submit();
		return false;
	});

	$("#searchPeople").keydown(function(e) {
		if(e.keyCode == 13) {
			$('#formHomePageSearch').submit();
			return false;
		}
		return true;
	});
	
	$('#formHomePageSearch').submit(function() {
		var email = $('#searchPeople')[0].value;
		email = $.trim(email);
		if (email.length > 0) {    	
			window.location.href = 'acSearchRegistry?emailAddress=' + $('#searchPeople')[0].value.replace('@', '%40') + '&hm=1';
		}
		return false;
	});

	/**
	 * Help
	 */
	$("#navHelp").click(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		$('body').append('<div class="modalOverlay"></div>');
		var boxObj = $('#helpBox');
		
		boxObj.css({"left":curLeft-400, "top":curTop+100}).show();

		return false;
		
	});
	
	/**
	 * My Profile Change Picture
	 */
	$("#myProfileChangePicture").click(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		$('body').append('<div class="modalOverlay"></div>');
		var boxObj = $('#myProfileChangePictureBox');
		
		boxObj.css({"left":curLeft+250, "top":curTop+20}).show();

		return false;
		
	});
	
	$(".IncentiveMessagePromo .terms").live("click", function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		$('body').append('<div class="modalOverlay"></div>');
		var boxObj = $('#offerTermsAndConditionsBox');
		var termsAndConditions = $(this).closest(".IncentiveMessagePromo").find(".offerTermsAndConditions").html();
		boxObj.find(".popupContent").html(termsAndConditions);
		$(this).closest(".tooltipContainer").hide();
		var left = curLeft-(boxObj.width() / 2);
		if (left < 0) left = 0;
		var top = curTop-(boxObj.height() / 2);
		if (top < 0) top = 0;
		boxObj.css({"left":left, "top":top}).show();

		return false;
		
	});

	/**
	 * Vertically center reminder buttons
	 */
	$(".reminderActions").each(function(){
		var actionsContainer = $(this);
		var actionLinks = actionsContainer.find("a");
		if (actionLinks.length == 0) return; // nothing to do
		var reminderHeight = actionsContainer.closest("li").height();
		// An action link is 18 pixels high
		var contentHeight = 18;
		if (actionLinks.length == 2) {
			// Add another 18 plus 5 padding for the second action link
			contentHeight += 23;
		}
		var paddingTop = Math.floor((reminderHeight - contentHeight) / 2);
		actionsContainer.css("padding-top", paddingTop);
	});
	
	/**
	 * Close Reminder
	 */
	$(".reminderClose").click(function(){
		var link = $(this);
		var reminder = link.closest("li");
		var reminderSection = reminder.closest(".remindersSection");
		var allVisibleReminders = reminderSection.find(".reminderList li:visible");
		if (allVisibleReminders.length == 1) {
			// This is the last remaining reminder, hide the entire section
			reminderSection.fadeOut();
		} else {
			// Just fade out this reminder
			reminder.fadeOut();
		}
		return false;
	});

	$(".noticeClose").click(function() {
		var noticeObj = $($($(this).parent().get(0)).parent().get(0));
		
		noticeObj.fadeOut();
		
		return false;
		
	});
	
	$('#formContentContactInfo #email_address').keyup(function(e) {
		if(e.keyCode == 13) {
			userNameChange();
		}
	});

	
	$("#btnAddEmail").click(function(){
		var emailAddressField = $('#email_addresses');
		var emailAddressList = $('#emailAddress');
		if (emailAddressField.attr('value') == '') {
			return false;
		}
		var emailAddresses = emailAddressField.attr('value').split(/[,;]/);
		for (var i in emailAddresses) {
			var emailAddress = emailAddresses[i];
			if (emailAddressCount >= 25) {
				alert('Cannot add more than 25 emails at a time.');
				emailAddressField.focus();
				return false;
			}
			++emailAddressCount;
	
		    emailAddressList.append("<span><input type='hidden' name='toEmails' value='" + emailAddress + "'/>"+emailAddress+"<a href=\"javascript:;\" class=\"emailItemRemove\">X</a><br /></span>");
			
			if(emailAddressCount==1){
				$('#btnSendMessage').show();
			}
			
			$(".emailItemRemove").click(function(){
				if (emailAddressCount>0){
					--emailAddressCount;
	
					$($(this).parent().get(0)).remove();
					
					if(emailAddressCount==0){
						$('#btnSendMessage').hide();
					}
					
				}
				return false;
			});
		}
		
		emailAddressField.val("");
		emailAddressField.focus();
		return false;
	});
	$("#message_text").change(function(){
		var selectedObj = $('#message_text :selected');
	    if(selectedObj.val()=='write_message'){
			$('#fundraising_now_text').text("");
		} else{
		    $('#fundraising_now_text').text(selectedObj.text());
		}
		return false;
	});
	
	/* Withdrawal Different Help Info */
	$(".withdrawalDifferent").hover(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#withdrawalDifferentBox');
		
		boxObj.css({"left":curLeft-400, "top":curTop-220}).show();
		
		return false;
	},function(){
		$('#withdrawalDifferentBox').hide();
		
		return false;
	});
	
	$(".withdrawalDisabled").click(function(){
		var boxObj = $('#withdrawalDisabledBox');
		boxObj.centerInClient().show();
		return false;
	});
	
	if ( $(".date-pick").length>0 ) {
		try {
			$(".date-pick").datePicker({startDate:'01/01/1990'});
		} catch (error) {
			if (typeof(console) != 'undefined') {
				console.error("Unable to set up date pickers", error);
			}
		}
	}

	/* Monthly Withdrawal Amount */
	// Decrease
	$("#btnMonthlyAmountDecrease").click(function(){
		var px = 109/(sliderMax-sliderMin);
		
		var sliderPos = calcPosition(document.getElementById('slider'));
		var sliderLeft = sliderPos['left'];
		var pos = calcPosition(document.getElementById('sliderSelector'));
		var curLeft = pos['left'];

		
		if (sliderVal-5>=sliderMin){
			sliderVal -= 5;
			curLeft -= 5*px;
		}else{
			sliderVal = sliderMin;
			curLeft = sliderLeft;
		}
		$('#sliderSelector').css({"left":curLeft}).show();
		$('.sliderValue').text('$'+sliderVal.toFixed(2));
		
		return false;
	});
	// Increase
	$("#btnMonthlyAmountIncrease").click(function(){
		var px = 109/(sliderMax-sliderMin);
		
		var sliderPos = calcPosition(document.getElementById('slider'));
		var sliderLeft = sliderPos['left'];
		var pos = calcPosition(document.getElementById('sliderSelector'));
		var curLeft = pos['left'];
							
		if (sliderVal+5<=sliderMax){
			sliderVal += 5;
			curLeft += 5*px;
		}else{
			sliderVal = sliderMax;
			curLeft = sliderLeft+109;
		}
		
		$('#sliderSelector').css({"left":curLeft}).show();
		$('.sliderValue').text('$'+sliderVal.toFixed(2));					  
		return false;
	});
	// Slider Click
	$("#slider").click(function(e){
		var sliderPos = calcPosition(this);
		var sliderLeft = sliderPos['left'];
		var pos = calcPosition(document.getElementById('sliderSelector'));
		var curLeft = pos['left'];
		
		if(e.pageX<sliderLeft){
			curLeft = sliderLeft;
		} else if(e.pageX>sliderLeft+109){
			curLeft = sliderLeft+109;
		} else{
			curLeft = e.pageX; 
		}
							
		sliderVal = (curLeft-sliderLeft)*(sliderMax-sliderMin)/109;
		
		$('#sliderSelector').css({"left":curLeft}).show();
		$('.sliderValue').text('$'+sliderVal.toFixed(2));					  
		return false;
	});
	
	/* Performance Help Info */
	$("#whatDoesMeanPerformance").click(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#whatDoesMeanPerformanceBox');
		
		boxObj.css({"left":curLeft, "top":curTop-320}).show();
		
		return false;
	},function(){
		$('#whatDoesMeanPerformanceBox').hide();
		
		return false;
	});
	
	/* Top Holdings Help Info */
	$("#whatDoesMeanTopHoldings").click(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#whatDoesMeanTopHoldingsBox');
		
		boxObj.css({"left":curLeft-200, "top":curTop-320}).show();
		
		return false;
	},function(){
		$('#whatDoesMeanTopHoldingsBox').hide();
		
		return false;
	});
	
	/* Data validations */ 
	$('#forgot_password_id').alphanumeric({allow:" -.,"});
	$('#forgot_password_zip_code').numeric();
	
	$('#zip, #zip_code').numeric();
	$('#phone_ext').numeric();
	
	//$('#cc_number').numeric();
	$('#cc_expiration_mm').numeric();
	$('#cc_expiration_yy').numeric();
	$('#cvv').numeric();
	
	$('#depositAmount1').numeric();
	$('#depositAmount2').numeric();
	
	$('input.month, input.day, input.year').numeric();
	
	/* Make form updates on hitting enter */
	
	$('#goalFundraisingNowForm #email_addresses').keydown(function(e) {
		if(e.keyCode == 13) {
			$("#btnAddEmail").click();
			return false;
		}
		return true;
	});
	$('#email_address_edit input').keydown(function(e) {
		if(e.keyCode == 13) {
			updateEmailAddress('formContentContactInfo');
			return false;
		}
	});
	$('#mailing_address_edit input, #mailing_address_edit select').keydown(function(e) {
		if(e.keyCode == 13) {
			updateMailingAddress();
			return false;
		}
		return true;
	});
	$('#phone_number_edit input').live("keydown", function(e) {
		if(e.keyCode == 13) {
			updatePhoneNumber('formContentContactInfo');
			return false;
		}
		return true;
	});
	$('#passwordSecurityPassword input').keydown(function(e) {
		if(e.keyCode == 13) {
			submitUpdatePassword();
			return false;
		}
		return true;
	});
	
	$('#passwordSecurityQuestions input, #passwordSecurityQuestions select').keydown(function(e) {
		if(e.keyCode == 13) {
			if (e.target.id.match(/_([0-9])/))
				submitUpdateQuestion(RegExp.$1);
			return false;
		}
		return true;
	});
	
	$('#passwordSecurityPIN input').keydown(function(e) {
		if(e.keyCode == 13) {
			submitUpdateIvrPin();
			return false;
		}
		return true;
	});
	
	/* Edit Email Address */
	$("#editEmailAddress").live("click", function(){
		$('#email_address_label').hide();
		$('.edit').hide();
		$('#email_address').show();
		$('#saveEmailAddress').show();
		$('#cancelEmailAddress').show();
		return false;
	});
	
	/* Save Email Address */
	$("#saveEmailAddress").live("click", function(){
		updateEmailAddress("formContentContactInfo");
		return false;
	});
	/* Save Email Address */
	$("#cancelEmailAddress").live("click", function(){
		$('#email_address_label').show();
		$('.edit').show();
		$('#email_address').hide();
		$('#saveEmailAddress').hide();
		$('#cancelEmailAddress').hide();
		return false;
	});
		
	/* Continue Save Email Address */
	$("#continueSaveEmailAddress").click(function(){
		$('.closeModalWindow').click();
		
		$('#email_address').hide();
		$('#saveEmailAddress').hide();
		$('#cancelEmailAddress').hide();
		$('#email_address_save_note').show();
		
		return false;
	});
	/* Edit Phone Number */
	$("#editPhoneNumber").live("click", function(){
		$('#phone_number_label').hide();
		$('.edit').hide();

		$('#phone_number').show();
		$('#savePhoneNumber').show();
		$('#cancelPhoneNumber').show();
		
		return false;
	});
	/* Save Phone Number */
	$("#savePhoneNumber").live("click", function(){
		updatePhoneNumber("formContentContactInfo");
		return false;
	});
	/* Save Phone Number */
	$("#cancelPhoneNumber").live("click", function(){
		$('#phone_number').hide();
		$('#savePhoneNumber').hide();
		$('#cancelPhoneNumber').hide();
		
		$('.edit').show();
		$('#phone_number_label').show();
		return false;
	});
	/* Continue Save Phone Number */
	$("#continueSavePhoneNumber").click(function(){
		$('.closeModalWindow').click();
		
		$('#phone_number').hide();
		$('#savePhoneNumber').hide();
		$('#cancelPhoneNumber').hide();
		
		$('#editPhoneNumber').show();
		$('#phone_number_label').show();
		
		return false;
	});
	/* Save Mailing Address */
	$("#saveMailingAddress").live("click", function(){
		updateMailingAddress()
		return false;
	});
	$("#cancelMailingAddress").live("click", function(){
		clearEditMailingAddress()
		return false;
	});
	/* Continue Mailing Address */
	$("#continueSaveMailingAddress").click(function(){
		$('.closeModalWindow').click();
		
		$('#care_oof').hide();
		$('#street_apo_fpo').hide();
		$('#apt_unit').hide();
		$('#city').hide();
		$('#state').hide();
		$('#zip_code').hide();
		$('#saveMailingAddress').hide();
		
		$('#care_oof_label').show();
		$('#street_apo_fpo_label').show();
		$('#apt_unit_label').show();
		$('#city_label').show();
		$('#state_label').show();
		$('#zip_code_label').show();
		$('#editMailingAddress').show();
		
		return false;
	});
	/* Edit Password */
	$("#editPassword").click(function(){
		$('#passwordView').hide();
		$('#passwordEdit').show();
		$('.edit').hide();
		
		return false;
	});
	
	/* Edit Question 1 */
	$("#editQuestion1").click(function(){
		$('#question_1_password').val(''); // clear password
		$('#viewQ1').hide();
		$('#editQ1').show();
		$('.edit').hide();
		kill_existing_questions("#question_1", "#question_2", "#question_3");
		
		return false;
	});
	/* Save Question 1 */
	$("#saveQuestion1").click(function(){
		$('#editQ1').hide();
		$('#viewQ1').show();
		
		return false;
	});
	
	/* Edit Question 2 */
	$("#editQuestion2").click(function(){
		$('#question_2_password').val(''); // clear password
		$('#viewQ2').hide();
		$('#editQ2').show();
		$('.edit').hide();
		kill_existing_questions("#question_2", "#question_1", "#question_3");
		
		return false;
	});
	/* Save Question 2 */
	$("#saveQuestion2").click(function(){
		$('#editQ2').hide();
		$('#viewQ2').show();
		
		return false;
	});
	
	/* Edit Question 3 */
	$("#editQuestion3").click(function(){
		$('#question_3_password').val(''); // clear password
		$('#viewQ3').hide();
		$('#editQ3').show();
		$('.edit').hide();
		kill_existing_questions("#question_3", "#question_1", "#question_2");
		
		return false;
	});
	/* Save Question 3 */
	$("#saveQuestion3").click(function(){
		$('#editQ3').hide();
		$('#viewQ3').show();
		
		return false;
	});
	/* Edite IVR Pin */
	$("#editIVRPin").click(function(){
		$('#ivrPinView').hide();
		$('#ivrPinEdit').show();
		$('#newIvrPin').val(''); // clear pin
		$('#confirmIvrPin').val(''); // clear pin
		$('.edit').hide();

		
		return false;
	});
	/* Alerts lower threshold */
	$("input[name='accountHolderAlerts.lowerAlertThresholdOn']").change(function() {
	    if ($("input[name='accountHolderAlerts.lowerAlertThresholdOn']:checked").val() == 'true') {
	    	 $("#less_than").attr("disabled","");
	    } else {
	    	$("#less_than").attr("disabled","disabled");
	    }
	});
	/* Alerts upper threshold */
	$("input[name='accountHolderAlerts.upperAlertThresholdOn']").change(function() {
	    if ($("input[name='accountHolderAlerts.upperAlertThresholdOn']:checked").val() == 'true') {
	    	 $("#more_than").attr("disabled","");
	    } else {
	    	$("#more_than").attr("disabled","disabled");
	    }
	});
	
	$("#formAlerts").submit(function(){
		wait_on("#formAlerts")
	});
	
	
	// Glossary links
	$("a").each(function() {
		var link = $(this);
		var location = link.attr("href");
		if (location && location.indexOf("financial-glossary#") == 0) {
			link.attr("href", "javascript:void(0);");
			link.addClass("hover");
			link.hover(
					function() {
						$(this).children(".hoverBox").show();
					},
					function() {
						$(this).children(".hoverBox").hide();
					}
			);
			var sectionTitle = $.trim(location.substring(location.indexOf("#") + 1));
			var page = $.trim(location.substring(0, location.indexOf("#")));
			var hoverBox = $('<div class="hoverBox hide"><b>' + sectionTitle + '</b></div>');
			var glossaryLink = $('<div onClick="location.href=\'' + location + '\'">Glossary</div>');
			hoverBox.append(glossaryLink);
			$.ajax({
				url: page,
				success: function(data) {
					var simplifiedData = data.substring(data.indexOf("<body>")).replace("</html>", "");
					simplifiedData = simplifiedData.replace("<body>", "<div>");
					simplifiedData = simplifiedData.replace("</body>", "</div>");
					var glossary = $(simplifiedData);
					glossary.find("dt.dt-collapsed").each(function() {
						var candidateSection = $(this);
						if ($.trim(candidateSection.html().toLowerCase()) == sectionTitle.toLowerCase()) {
							var description = $('<span><br/>' + candidateSection.next().html() + '</span>');
							hoverBox.append(description);
						}
					});
				}
			});
			link.prepend(hoverBox);
		}
	});
	
	/* Not A US Resident or Don't Have a SSN Help Info */
	$("#notUSResident").hover(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#notUSResidentBox');
		
		boxObj.css({"left":curLeft+100, "top":curTop+20}).show();
		
		return false;
	},function(){
		$('#notUSResidentBox').hide();
		
		return false;
	});
	/* Why do you need this info Help Info */
	$("#whyNeedEmailAddress").hover(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#whyNeedEmailAddressBox');
		
		boxObj.css({"left":curLeft-200, "top":curTop-220}).show();
		
		return false;
	},function(){
		$('#whyNeedEmailAddressBox').hide();
		
		return false;
	});
	/* Why do you need this info Help Info */
	$("#whyNeedAtLeast18").hover(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#whyNeedAtLeast18Box');
		
		boxObj.css({"left":curLeft-200, "top":curTop-220}).show();
		
		return false;
	},function(){
		$('#whyNeedAtLeast18Box').hide();
		
		return false;
	});
	/* Help Info */
	$("#whyNeedCareOf").hover(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#whyNeedCareOfBox');
		
		boxObj.css({"left":curLeft-200, "top":curTop-220}).show();
		
		return false;
	},function(){
		$('#whyNeedCareOfBox').hide();
		
		return false;
	});
	/* Help Info */
	$("#whyNoPOBoxes").hover(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#whyNoPOBoxesBox');
		
		boxObj.css({"left":curLeft-200, "top":curTop-220}).show();
		
		return false;
	},function(){
		$('#whyNoPOBoxesBox').hide();
		
		return false;
	});
	/* Help Info */
	$("#whyNeedIDType").hover(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#whyNeedIDTypeBox');
		
		boxObj.css({"left":curLeft-200, "top":curTop-220}).show();
		
		return false;
	},function(){
		$('#whyNeedIDTypeBox').hide();
		
		return false;
	});
	/* Help Info */
	$("#whyNeedPhoneNumber").hover(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#whyNeedPhoneNumberBox');
		
		boxObj.css({"left":curLeft-200, "top":curTop-220}).show();
		
		return false;
	},function(){
		$('#whyNeedPhoneNumberBox').hide();
		
		return false;
	});
	/* Help Info */
	$("#whatIfPhoneNumber").hover(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#whatIfPhoneNumberBox');
		
		boxObj.css({"left":curLeft-200, "top":curTop-220}).show();
		
		return false;
	},function(){
		$('#whatIfPhoneNumberBox').hide();
		
		return false;
	});
	/* Help Info */
	$("#whyNeedSecurityQuestions").hover(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#whyNeedSecurityQuestionsBox');
		
		boxObj.css({"left":curLeft-200, "top":curTop-220}).show();
		
		return false;
	},function(){
		$('#whyNeedSecurityQuestionsBox').hide();
		
		return false;
	});
	
	/* What Is add money units Help Info */
	$("#whatIsAddMoneyUnits").hover(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#whatIsAddMoneyUnitsBox');
		
		boxObj.css({"left":curLeft-300, "top":curTop-220}).show();
		
		return false;
	},function(){
		$('#whatIsAddMoneyUnitsBox').hide();
		
		return false;
	});
	/* What Is SetUp Bank Help Info */
	$("#whatIsSetUpBank").hover(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#whatIsSetUpBankBox');
		
		boxObj.css({"left":curLeft-300, "top":curTop-220}).show();
		
		return false;
	},function(){
		$('#whatIsSetUpBankBox').hide();
		
		return false;
	});
	/* What Is Add Moeny From Bank Just One Time Help Info */
	$("#whatIsAddFromBankOneTime").hover(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#whatIsAddFromBankOneTimeBox');
		
		boxObj.css({"left":curLeft-300, "top":curTop-220}).show();
		
		return false;
	},function(){
		$('#whatIsAddFromBankOneTimeBox').hide();
		
		return false;
	});
	/* What Is Edit Recurring Transactions Help Info */
	$("#whatIsEditRecurringTransactions").hover(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#whatIsEditRecurringTransactionsBox');
		
		boxObj.css({"left":curLeft-300, "top":curTop-220}).show();
		
		return false;
	},function(){
		$('#whatIsEditRecurringTransactionsBox').hide();
		
		return false;
	});
	/* What Is Set Up Recurring Transactions Help Info */
	$("#whatIsSetUpRecurringTransactions").hover(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#whatIsSetUpRecurringTransactionsBox');
		
		boxObj.css({"left":curLeft-300, "top":curTop-220}).show();
		
		return false;
	},function(){
		$('#whatIsSetUpRecurringTransactionsBox').hide();
		
		return false;
	});
	/* What Is Edit Recurring Transaction Help Info */
	$("#whatIsEditRecurringTransaction").hover(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#whatIsEditRecurringTransactionBox');
		
		boxObj.css({"left":curLeft-300, "top":curTop-220}).show();
		
		return false;
	},function(){
		$('#whatIsEditRecurringTransactionBox').hide();
		
		return false;
	});

	$("#whatMeanAddRecurringMonthlyTransaction").hover(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#whatMeanAddRecurringMonthlyTransactionBox');
		
		boxObj.css({"left":curLeft-300, "top":curTop-220}).show();
		
		return false;
	},function(){
		$('#whatMeanAddRecurringMonthlyTransactionBox').hide();
		
		return false;
	});
	/* Where Do I Find Routing Name Help Info */
	$("#whereFindRoutingName").click(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#whereFindRoutingNameBox');
		
		boxObj.css({"left":curLeft-300, "top":curTop-220}).show();
		
		return false;
	},function(){
		$('#whereFindRoutingNameBox').hide();
		
		return false;
	});
	/* Help Me Find Authorization Number Help Info */
	$(".helpMeFindAuthorizationNumber").click(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		$('body').append('<div class="modalOverlay"></div>');
		var boxObj = $('#helpMeFindAuthorizationNumberBox');
		
		boxObj.css({"left":curLeft, "top":curTop-220}).show();
		
		return false;
	});
	/* Help Me Find PIN Help Info */
	$(".helpMeFindPIN").click(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		$('body').append('<div class="modalOverlay"></div>');
		var boxObj = $('#helpMeFindPINBox');
		
		boxObj.css({"left":curLeft-300, "top":curTop-220}).show();
		
		return false;
	});
	
	maskInputs();	
	
	// $('#zip_code').mask("99999-9999",{placeholder:" "});
	
	all_question_options = $("#question_list option");
	$("#formOpenAccount_userQuestions_0__question_id").change(function() {process_security_question(0)});
	$("#formOpenAccount_userQuestions_1__question_id").change(function() {process_security_question(1)});
	$("#formOpenAccount_userQuestions_2__question_id").change(function() {process_security_question(2)});
     
	$("#pin1").keyup(function(){
			if ($(this).attr('value').length > 4)
				$("#authorization_number1_label").text('$100');
	});

	/**
	 * Withdraw Close Submit
	 */
	$("#subjectToBackupWithholding").click(function(){
		if ($('#subjectToBackupWithholding').attr('checked'))
		{
			var pos = calcPosition(this);
			var curLeft = pos['left'];
			var curTop = pos['top'];
	
			$('body').append('<div class="modalOverlay"></div>');
			var boxObj = $('#btnWithHold');
			
			boxObj.css({"left":curLeft-300, "top":curTop-220}).show();
		}
		return true;
	});

	
	/* Buy Money Unit */
	
	
	$(".buyMoneyUnitGoalBlock").click(function() {
		$(".buyMoneyUnitGoalBlockSelected").each(function(){$(this).attr('class', 'buyMoneyUnitGoalBlock')});
		$(this).attr('class', 'buyMoneyUnitGoalBlockSelected');
		$('#buyMoneyUnitGoalGroupSelection').val($(this).attr('title'));
	});

	$("#buyMoneyUnitSelect").change(function() {
		$(".buyMoneyUnitGoalGroup").hide();
		$("#buyMoneyUnitGoalGroup_" + $(this).val()).show();
		$(".buyMoneyUnitGoalBlockSelected").each(function(){$(this).attr('class', 'buyMoneyUnitGoalBlock')});
		$('#buyMoneyUnitGoalGroupSelection').val('');
	});

	$('#buyMoneyUnitsConfirmDeliveryForm input').keydown(function(e) {
		if(e.keyCode == 13) {
			$("#btnBuyMoneyUnitDeliverySubmit").click();
			return false;
		}
		return true;
	});

	$("#physical_delivery").click(function () {
		$("#to_name").removeAttr("disabled");
		$("#gifter_name").removeAttr("disabled");
		$(".online_delivery, .facebook_delivery").each(function (){$(this).hide()});
		$(".physical_delivery").each(function (){$(this).show()});
		$("#previewGoalPacksButton").show();
	});
	$("#online_delivery").click(function () {
		$("#to_name").removeAttr("disabled");
		$("#gifter_name").removeAttr("disabled");
        $(".physical_delivery, .facebook_delivery").each(function (){$(this).hide()});
		$(".online_delivery").each(function (){$(this).show()});
		$("#previewGoalPacksButton").hide();
	});
	$("#facebook_delivery").click(function () {
		$("#to_name").attr("disabled", "disabled");
		$("#gifter_name").attr("disabled", "disabled");
		setGiftNamesFromFacebook();
		$(".physical_delivery, .online_delivery").each(function (){$(this).hide()});
		$(".facebook_delivery").each(function (){$(this).show()});
		$("#previewGoalPacksButton").hide();
	});
	$("#order_is_gift").click(function () {
		if($(this).attr('checked')) {
			// If first name and last name have been filled in
			if ($('#delivery_first_name.inputDescription, #delivery_last_name.inputDescription').length == 0) {
				// Prepopulate the gift to field
				var deliveryFirstName = $("#delivery_first_name").val();
				var deliveryLastName = $("#delivery_last_name").val();
				if (!$("#to_name").val() && deliveryFirstName && deliveryLastName) {
					$("#to_name").removeClass("inputDescription").val(deliveryFirstName + " " + deliveryLastName);
				}
			}
			
			$(".gift_options_wrapper").show();
		} else {
			$(".gift_options_wrapper").hide();
		}
	});
	$("#prewritten_message").click(function () {
		$("#gift_options_pre_written").show();
		$("#gift_options_personalized").hide();
	});
	$("#personalized_message").click(function () {
		$("#gift_options_pre_written").hide();
		$("#gift_options_personalized").show();
	});
	$("#same_as_billing").click(function() {
		var $this = $(this);
		var fields = ["address_1", "address_2", "city", "state", "zip", "phone_masked", "phone_ext"];
		for (var ix = 0; ix < fields.length; ++ix) {
			var value = $this.attr('checked') ? $("#delivery_" + fields[ix]).val() : "";
			$("#" + fields[ix]).val(value);
		}
	});
	
	$("#btnBuyMoneyUnitDeliveryViewDisclosure").click(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		$('body').append('<div class="modalOverlay"></div>');
		var boxObj = $('#btnBuyMoneyUnitDeliveryDisclosure');
		
		boxObj.css({"left":curLeft-300, "top":curTop-300}).show();
		return false;
	});
	
	$("#no_message").click(function () {
		$("#gift_options_pre_written").hide();
		$("#gift_options_personalized").hide();
	});
	$("#receive_confirmation").click(function () {
		if ($(this).attr('checked')) 
			$(".receive_confirmation").each(function (){$(this).show()});
		else
			$(".receive_confirmation").each(function (){$(this).hide()});
	});
	$("#pre_written_message").change(function () {
		$("#pre_writte_message_preview").text((this).value);
	});
	/* Add Another Money Unit */
	$("#addAnotherMoneyUnit").click(function(){
		// validate

		validateMoneyUnits("formAddMoneyUnits", function() {
			$('input[name="authorizationNumber"]').attr('disabled','disabled');
			$('input[name="pin"]').attr('disabled','disabled');
			addMoneyTableRow("formAddMoneyUnits");
		});
		
		return false;
	});
	
	$('#btnAddMoneyUnitsContinue').click(function(){
		$('#formAddMoneyUnits').hide();
		$('#formContributionMoneyUnits').show();
		
		return false;
	});
	$('#btnEditRecurringTransactionChange').click(function(){
		$('#editRecurringTransactionView').hide();
		$('#btnEditRecurringTransactionChange').hide();
		$('#btnEditRecurringTransactionDelete').hide();

		$('#editRecurringTransactionEdit').show();
		$('#btnEditRecurringTransactionSave').show();
		
		return false;
	});
	$('#btnEditRecurringTransactionSave').click(function(){
		$('#editRecurringTransactionEdit').hide();
		$('#btnEditRecurringTransactionSave').hide();
		
		$('#editRecurringTransactionView').show();
		$('#btnEditRecurringTransactionSubmit').show();
		$('#btnEditRecurringTransactionCancel').show();

		
		return false;
	});
	$('#btnEditRecurringTransactionSubmit').click(function(){
		$('#formEditRecurringTransaction').hide();
		
		$('#contributionConfirmationmEditRecurringTransaction').show();

		
		return false;
	});
	/**
	 * Withdraw Close Submit
	 */
	$("#btnTakeOutMoneyCloseAccountSubmit").click(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		$('body').append('<div class="modalOverlay"></div>');
		var boxObj = $('#btnCloseGoalAccountBox');
		
		boxObj.css({"left":curLeft-300, "top":curTop-220}).show();

		return false;
		
	});
	/**
	 * Withdraw Check Summary Submit
	 */
	$("#btnWithdrawCheckSummary").click(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		$('body').append('<div class="modalOverlay"></div>');
		var boxObj = $('#btnCloseGoalAccountBox');
		
		boxObj.css({"left":curLeft, "top":curTop-220}).show();

		return false;
		
	});
	/**
	 * Edit Goal Name
	 */
	$("#editGoalName").live("click", function() {
		$('#goalNameView').hide();
		$('#goalNameEdit').show();
		$(".edit").hide();
		
		$("#goalNameEdit input").unbind('keydown');
		$("#goalNameEdit input").keydown(
			function(e)
			{
				if(e.keyCode == 13) {
					$("#saveGoalName").click();
					return false;
				}
				return true
			}
		);
		return false;
		
	});
	/**
	 * Save Goal Name
	 */
	$("#cancelGoalName").live("click", function() {
		$('#goalNameEdit').hide();
		$('#goalNameView').show();
		$(".edit").show();
	});
	$("#saveGoalName").live("click", function() {
		wait_on("#edit_goal_name_fields");
		$.ajax({			
			type: "POST",
			url: "acUpdateGoalName",	
			data: $("#formEditGoal").serialize(),
			success: function(html) {
				wait_off();
				$("#hidden_ajax_result").html(html);
				
				$("#tableAjaxFieldMessages li").each(function(){
		 			$('#'+ $(this).attr('title')).html($(this).html());
				});

				$('#tableAjaxFieldErrors li').each(function() {
		 			$('.mappedfielderror li[title='+ $(this).attr('title') +']').html($(this).html())
		 		});
				
				if ($('#tableAjaxFieldErrors li').length == 0) {
					$("#edit_goal_name_fields").html(html);
					$('#goalNameEdit').hide();
					$('#goalNameView').show();
					$('.edit').show();
				}
			}, 
			error: function() {
				alert("Error loading page");
			}
		});
		return false;
	});
	/**
	 * Edit Goal Options
	 */
	$("#editGoalOptions").live("click", function() {
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		$('body').append('<div class="modalOverlay"></div>');
		var boxObj = $('#editGoalOptionsBox');
		
		var browserWidth = $(document).width();
		boxObj.css({"left":(browserWidth/2) - 200, "top":curTop-220}).show();
		
		return false;
		
	});
	/**
	 * Continue Edit Goal Options
	 */
	$("#continueEditGoalOptions").click(function(){
		$('#goalOptionsView').hide();
		$(".edit").hide();
		$('#goalOptionsEdit').show();
		$('#saveGoalOptions').show();
		
		$('#editGoalOptionsBox .closeModalWindow').click();

		return false;
		
	});
	/**
	 * Save Goal Options
	 */
	$("#saveGoalOptions").live("click", function() {
		$.ajax({			
			type: "POST",
			url: "acUpdateGoalOptions",	
			data: $("#formEditGoal").serialize(),
			success: function(html) {
				$("#hidden_ajax_result").html(html);
				
				$("#tableAjaxFieldMessages li").each(function(){
		 			$('#'+ $(this).attr('title')).html($(this).html());
				});

				$('#tableAjaxFieldErrors li').each(function() {
		 			$('.mappedfielderror li[title='+ $(this).attr('title') +']').html($(this).html())
		 		});
				
				if ($('#tableAjaxFieldErrors li').length == 0) {
					$("#goal_options_fields").html(html);
					$('#saveGoalOptions').hide();
					$('#goalOptionsEdit').hide();
					$('#goalOptionsView').show();
					$(".edit").show();
				}
			}, 
			error: function() {
				alert("Error loading page");
			}
		});
		return false;
	});
	$("#editFinancialProduct").live("click", function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		$('body').append('<div class="modalOverlay"></div>');
		var boxObj = $('#editFinancialProductBox');
		
		boxObj.css({"left":curLeft-200, "top":curTop-220}).show();

		return false;
	});
	/**
	 * Close Down Goal Account
	 */
	$("#btnCloseGoalAccount").click(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		$('body').append('<div class="modalOverlay"></div>');
		var boxObj = $('#btnCloseGoalAccountBox');
		
		var browserWidth = $(document).width();
		// boxObj.css({"left":(browserWidth/2) - 200}).show();
		// boxObj.css({"left":curLeft, "top":curTop-220}).show();
		boxObj.css({"left":(browserWidth/2) - 200, "top":curTop-220}).show();

		return false;
		
	});
	/**
	 * Send Message Public Profile
	 */
		
	$("textarea:regex(class, ^maxlength.*)").keypress (
		function(event) {
			TruncateFields();
			if (event.keyCode == 8 || event.keyCode == 46)
				return true;
			if ($(this).attr('className').match(/maxlength([0-9]+)/))
			{
				var length = RegExp.$1;
				$(this).nextAll(".maxlength:first").html("You have " + (length - $(this).val().length) + " remaining character(s)");
				return $(this).val().length < length;
			}
			return true;
		}
	);
	$("textarea:regex(class, ^maxlength.*)").blur (function(){TruncateFields();return true});
	$("textarea:regex(class, ^maxlength.*)").focus (
		function() {
			if (!truncateFieldTimer)
				truncateFieldTimer = setInterval("TruncateFields()", 100);
			return true;
		}
	);
	
	/*
	 * Public FundRaising - output error since we are having problems doing so
	 * via struts
	 */
	$('#btnBuyMoneyUnits, #btnPublicProfileGiftSubmit').click(
		function()
		{
			var form = $(this).closest("form");
			
			function reportError(error) {
				form.find("ul.error").hide();
				$('#jsError').html(error);
			}
			
			var goalPackValue = $("input.goalPackValue").val();
			var goalPackQuantity = $(".goalPackQuantity").val();
			
			if (!goalPackValue || goalPackValue.length == 0) {
				reportError("Please specify a value");
			} else {
				if (goalPackValue < 5 || goalPackValue > 200) {
					reportError("Please specify a value between $5 and $200");
				} else if (!goalPackQuantity || goalPackQuantity.length == 0 || goalPackQuantity == 0){
					reportError("Please specify a quantity");
				} else {
					var result = sumMoneyUnits();
					var moneyUnits = result[0];
					var limit = 100000; // default limit is $1,000 per order
					var stringLimit = "1,000";
					if ("true" == form.find("#internalFlag").val()) {
						limit = 1000000; // for internal orders, limit is $10,000 per order
						stringLimit = "10,000";
					}
					if (moneyUnits > limit) {
						reportError("Please limit your purchase to $" + stringLimit + " of gift cards or less");
					} else {
						form.submit();
					}
				}
			}
			
			return false;
		}
	);
	
	/**
	 * Send Message Public Profile Submit
	 */
	$("#btnSendMessagePublicProfileSubmit").click(function(e){
		$("#tableAjaxFieldErrors").hide();
	    var message = $("#send_message_public_text").val();
	    wait_on("#myProfile")
		$('.closeModalWindow').click();
	    message = $.trim(message);
	    if (message.length > 0) {
	    	wait_on("#myProfile");
		    var postObject = "&message=" + message;
		    $.ajax({
		        type: "POST",
		        url: "sendMessage",
		        data: postObject,
		        success: function(html) {
		    		wait_off();
		    		$("#hidden_send_ajax_result").html(html);
		    		if ($('#tableAjaxFieldErrors li').length != 0) {
		    			$("#tableAjaxFieldErrors").show();
					}
		    		confirm_on("#myProfile", null, "Message sent");
		    	},
		        error: function() {
		            alert("Error sending message. Try later.");
		        }
		    });
		    
	    }
		return false;
		
	});
	
	$('#usernameChangeForm input').keyup(function(e) {
		if(e.keyCode == 13) {
			userNameChange();
		}
	});

	/**
	 * Find Registry Submit
	 */
	$("#btnFindRegistrySubmit").click(function(){
		$('#resultLabel').show();
        if(findRegistryResultsFirst){
			findRegistryResultsFirst = false;
			$('#findRegistryNoResult').show();
		} else{
			$('#findRegistryNoResult').hide();
			$('#findRegistryResultsContent').show();
		}

		return false;
		
	});
		
	/**
	 * Have Money Unit Continue
	 */
	
	$('#formHaveMoneyUnit input').keydown(function(e) {
		if(e.keyCode == 13) {
			$("#btnHaveMoneyUnitContinue").click();
			return false;
		}
		return true;
	});
	$("#btnHaveMoneyUnitContinue").click(function(){

		validateMoneyUnits("formHaveMoneyUnit", function() {
			$('input[name="authorizationNumber"]').attr('disabled','disabled');
			$('input[name="pin"]').attr('disabled','disabled');

			$('#moneyUnitValue').show();
			$('#btnHaveMoneyUnitContinue').hide();
			$('#haveMoneyUnitButtonContainerLoggedIn').show();
			$('#btnHaveMoneyUnitHaveAccount').show();
			$('#btnHaveMoneyUnitOpenAccount').show();
			
		}, null, 'acValidateMoneyUnitsGuest');
		return false;
		
	});
	$("#btnHaveMoneyUnitOpenAccount").click(function(){
		// Remember this MU for 24 hours
		var expires = new Date();
		expires.setTime(expires.getTime() + 24 * 60 * 60 * 1000);
		document.cookie = "pendingmu=" + $('input[name="authorizationNumber"]').val() + $('input[name="pin"]').val() + "; expires=" + expires.toGMTString();
		document.location.href = 'acSignup';
	});
	/**
	 * Reset Password Continue
	 */
	$("#btnResetPasswordContinue").click(function(){
		$(this).hide();
		
		$('#forgotPasswordQuestions').show();
		$('#btnResetPasswordSubmit').show();

		return false;
		
	});
	/**
	 * Retrieve Username Continue
	 */
	$("#btnRetrieveUsernameContinue").click(function(){
		$(this).hide();
		
		$('#retrieveUsernameQuestions').show();
		$('#btnRetrieveUsernameSubmit').show();

		return false;
		
	});
   
	$('#fundAccountMoneyUnitsAdd').click(function(){
		addMoneyTableRow("formAddMoneyUnits");
		$('#formAddMoneyUnits').show();
		return false;
	});
	$('#fundAccountBankAdd').click(function(){
		$('#formMoveMoneyFromBank').show();
		$('#amount_to_transfer').numeric({allow:"."});		
		$('#account_number').numeric();
		$('#routing_name').numeric();
		return false;
		
	});
	
	$('.limitCurrency').numeric({allow:"."});
	$('.limitCurrencyDollarComma').numeric({allow:".$,"});
	
	$('#open_account_password').keyup(function(){
		var strength_message = passwordStrength2($(this).val(), $("#email_address").val())[0];
		var strength_code = passwordStrength2($(this).val(), $("#email_address").val())[1];
		$('#open_account_password_strength').html(strength_message);
	});
	$('#newPassword').keyup(function(){
		var strength_message = passwordStrength2($(this).val(), "")[0];
		var strength_code = passwordStrength2($(this).val(), "")[1];
		$('#open_account_password_strength').html(strength_message);
	});

	/* Tell Me About Bank Funding */
	$("#tellMeAboutBankFunding").hover(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];

		var boxObj = $('#tellMeAboutBankFundingBox');
		
		boxObj.css({"left":curLeft-200, "top":curTop-220}).show();
		
		return false;
	},function(){
		$('#tellMeAboutBankFundingBox').hide();
		
		return false;
	});

	/* No linked bank account */
	$("#whatDoesMeanNolink").click(function(){
		var pos = calcPosition(this);
		var curLeft = pos['left'];
		var curTop = pos['top'];
		var boxObj = $('#smallBox');
		boxObj.css({"left":curLeft, "top":curTop-75}).show();
		return false;
	},function(){
		$('#helpBox').hide();
		return false;
	});

	
	$("input[name='amounts'], input[name='quantities'], select[name='quantities']").change(recalcMoneyUnits);
	
	// Submit goalpack form when all digits entered
	/*
	 * $(".widgetGoalRedeemGoalpack input").focus ( function () { if
	 * (($(".widgetGoalRedeemGoalpack #authorizationCode").val().length == 0) &&
	 * ($(".widgetGoalRedeemGoalpack #pin").val().length == 0) &&
	 * !moneyUnitCheckTimer) moneyUnitCheckTimer =
	 * setInterval("checkMoneyUnitsEntered()", 250); } );
	 */
	// Percy - Rewrote because jquery position does not work inside relative containers
	// and was displaying the popup in the wrong place you can delete this comment
	
	$(".tooltip, .tooltipLarge, .tooltipXLarge, .tooltipXXLarge").live('mouseover', function() {
		var link = $(this);
		var tooltipContainer = link.find(".tooltipContainer");
		
		if (tooltipContainer.length == 0) {
			var linkWidth = link.width();
			var linkHeight = link.height();
			tooltipContainer = $("<span class='tooltipContainer' style='display: none;position: absolute;z-index: 10000'></span>");
			link.css('position', 'relative'); 
			
			link.prepend(tooltipContainer);
	        tooltipContainer.css("left", 0 - Math.floor(tooltipContainer.width() / 2 + 14 - linkWidth / 2));
	        tooltipContainer.css("top", 0 - tooltipContainer.height() - linkHeight / 2);
			var content = link.next(".tooltipContent");
			
            if (content.hasClass("tooltipContent")) {
	            tooltipContainer.html(content.html());
	            content.remove();
            } else {
	            var title = link.attr("title");
	            link.attr("title", "");
	            tooltipContainer.html(title);
            }
		}
		
        tooltipContainer.css("display", "block");
    
	});
	$(".tooltip, .tooltipLarge, .tooltipXLarge, .tooltipXXLarge").live('mouseout', function() {
		
		var link = $(this);
		var tooltipContainer = link.find(".tooltipContainer");
		tooltipContainer.css("display", "none");
		
	});
	
	$(".hoverNew").live('mouseover', function() {
		var link = $(this);
		var tooltipContainer = link.find(".hoverContent");
		
		var linkWidth = link.width();
		var linkHeight = link.height();
		tooltipContainer.css("display", "none");
		tooltipContainer.css("position", "absolute");
		tooltipContainer.css("z-index", 10000);
		link.css('position', 'relative'); 
		
		tooltipContainer.css("left", 0 - Math.floor(tooltipContainer.width() / 2 + 14 - linkWidth / 2));
        tooltipContainer.css("top", 0 - tooltipContainer.height() - linkHeight / 2);
		
        tooltipContainer.css("display", "block");
    
	});
	$(".hoverNew").live('mouseout', function() {
		
		var link = $(this);
		var tooltipContainer = link.find(".hoverContent");
		tooltipContainer.css("display", "none");
		
	});
	
});

function sumMoneyUnits() {
	var moneyUnits 		= 0;
	var fulfillmentFees = 0;		
	
	var amounts = $("input[name='amounts']");
	var quantities = $("input[name='quantities'], select[name='quantities']");
	
	for (var i=0; i<amounts.length; i++) {
		var amount = $(amounts.get(i)).val();
		var quantity = $(quantities.get(i)).val();
		if (amount != null && amount.length > 0 && quantity != null && quantity.length > 0) {
			amount = parseInt(amount);
			quantity = parseInt(quantity);
			if (amount > 0 && quantity > 0) {
				moneyUnits += (amount * quantity * 100);
				for (var f=0; f<moneyUnitFulfillmentFees.length; f++) {
					var fulfillmentFee = moneyUnitFulfillmentFees[f];
					if (fulfillmentFee.from <= amount && fulfillmentFee.to >= amount) {
						fulfillmentFees += (quantity * fulfillmentFee.fee * 100);
						break;
					}
				}
			}
		}
	}
	
	return [moneyUnits, fulfillmentFees];
}

function recalcMoneyUnits() {
	var result = sumMoneyUnits();
	var moneyUnits = result[0];
	var fulfillmentFees = result[1];
	
	$('#moneyUnits').text(add_commas(moneyUnits / 100));
	$('#fulfillmentFees').text(add_commas(fulfillmentFees / 100));
	$('#totalMoneyPurchase').text(add_commas((moneyUnits + fulfillmentFees) / 100));
}

function closeConfirm(){
	$('.modalOverlay').remove();
	$('#commonBox').hide();
}


$.fn.centerInClient = function(options) {
    // / <summary>Centers the selected items in the browser window. Takes into
	// account scroll position.
    // / Ideally the selected set should only match a single element.
    // / </summary>
    // / <param name="fn" type="Function">Optional function called when
	// centering is complete. Passed DOM element as parameter</param>
    // / <param name="forceAbsolute" type="Boolean">if true forces the element
	// to be removed from the document flow
    // / and attached to the body element to ensure proper absolute positioning.
    // / Be aware that this may cause ID hierachy for CSS styles to be affected.
    // / </param>
    // / <returns type="jQuery" />
    var opt = { forceAbsolute: false,
                container: window,    // selector of element to center in
                completeHandler: null
              };
    $.extend(opt, options);
   
    return this.each(function(i) {
        var el = $(this);
        var jWin = $(opt.container);
        var isWin = opt.container == window;

        // force to the top of document to ENSURE that
        // document absolute positioning is available
        if (opt.forceAbsolute) {
            if (isWin)
                el.remove().appendTo("body");
            else
                el.remove().appendTo(jWin.get(0));
        }

        // have to make absolute
        el.css("position", "absolute");

        // height is off a bit so fudge it
        var heightFudge = isWin ? 2.0 : 1.8;

        var x = (isWin ? jWin.width() : jWin.outerWidth()) / 2 - el.outerWidth() / 2;
        var y = (isWin ? jWin.height() : jWin.outerHeight()) / heightFudge - el.outerHeight() / 2;

        el.css("left", x + jWin.scrollLeft());
        el.css("top", y + jWin.scrollTop());

        // if specified make callback and pass element
        if (opt.completeHandler)
            opt.completeHandler(this);
    });
}

/**
 * Deprecated - this method overrides the built in confirm method and this causes problems with Selenium.  Use popConfirm() instead.
 * 
 * @param caller
 * @param message
 * @param callback
 * @param nocancel
 * @returns {Boolean}
 */
function confirm(title, message, callback, nocancel) {
	if (!callback) callback = "";
    var str = title ? '<h3 class="modalPopupHeader" style="margin-top: -10px; width: 400px; margin-left:-20px">' + title + '</h3>' : "";
    str += '<div class="confirmContent">';
    if (message.length < 80)
    	message = "<br /><br />" + message;
    str += '<p>' + message + '</p>';
    str += '<p style="text-align: center"><a class="" href="javascript:;" onclick="' + callback +';closeParentModalWindow(this);">Continue</a>';
    str += '</p></div>';
    openModalWindow(str, 400, 200, false);
	
	return false;
}

/**
 * Replacement for confirm()
 */
function popConfirm(caller, message, callback, nocancel) {
	if (!callback) callback = "";
    var str = "";
    str += '<div class="confirmContent">';
    str += '<p>' + message + '</p>';
    str += '<p>&nbsp;&nbsp;&nbsp;&nbsp;<a class="button standardBlue" href="javascript:;" onclick="' + callback +';closeParentModalWindow(this);">Continue</a>&nbsp;&nbsp;&nbsp;&nbsp;';
    if (!nocancel)
    	str += '<a class="continueSave floatLeftTextLink" href="javascript:;" onclick="closeParentModalWindow(this)">Cancel</a>';
    str += '</p></div>';
    openModalWindow(str, 400, 200, false);
    fixButtons($(document.body));
	
	return false;
}

function popMessage(message, redirect, force) {
	var str = (force ? '' : '<a class="closeModalWindow" href="javascript:;"><span class="hide">Close Window</span></a>');
	str += '<div class="popupContent">';
	str += '<p>' + message + '</p>';
	
	if (typeof (redirect) != 'undefined') {
		str += '<p><a class="continueSave button standardBlue" href="' + redirect + '">Ok</a></p>';
	} else {
		str += '<p><a class="continueSave button standardBlue" href="javascript:;" onclick="closeConfirm()">Ok</a></p>';
	}
	
	str += '</div>';
	$('body').append('<div class="modalOverlay"></div>');
	$('#commonBox').html(str);
	$('#commonBox').show().centerInClient();
	return false;
}

function updateProgressBarValueTips(){
	/* Show Progress Bar Value Tips */
	$(".progressBarGoal").each(function(){

		var thisObj = $(this);
		var tipsObj = $(".progressBarValueTips", this);
		var valueObj = $(".progressBarValue", this);
		
		curLeft = valueObj.width() - Math.floor(tipsObj.width()/2);
		curTop =  0 - tipsObj.height();
		
		tipsObj.css({"left":curLeft, "top":curTop}).show();
	});
	$(".goalContainer").each(function(){

		var thisObj = $(this);
		var tipsObj = $(".progressBarValueTips", this);
		var valueObj = $(".rightBulb", this);
		
		curLeft = 6 + valueObj.width() - Math.floor(tipsObj.width()/2);
		curTop =  0 - tipsObj.height();
		
		tipsObj.css({"left":curLeft, "top":curTop}).show();
	});
}

function updateSliderSelector(sliderVal){
	if ($('#sliderSelector').length > 0) {
	var px = 109/(sliderMax-sliderMin);
	    var sliderPos = calcPosition(document.getElementById('slider'));
		curLeft = sliderPos['left'];
		curTop = sliderPos['top'];
	
	    curLeft += sliderVal*px;
	    $('#sliderSelector').css({"left":curLeft, "top":curTop});
		
	}
	
}

function calcPosition(obj){
	var curLeft = 0;
	var curTop = 0;
	var curWidth = 0;
	var curHeight = 0;
	if (obj && obj.offsetParent)
	{
			curHeight = obj.offsetHeight ? obj.offsetHeight : obj.clientHeight;
			curWidth = obj.offsetWidth ? obj.offsetWidth : obj.clientWidth;
			curLeft = obj.offsetLeft;
			curTop = obj.offsetTop;
			while (obj = obj.offsetParent) {
					curLeft += obj.offsetLeft;
					curTop += obj.offsetTop;
				}
	}
	
	return {"left":curLeft, "top":curTop, "width": curWidth, "height": curHeight};
}
function initSIFR()
	{
		if(typeof sIFR == "function")
		{
			sIFR.replaceElement("h3", named({sFlashSrc: "css/sifr/gotham_bold.swf", sColor: "#576870", sWmode:"transparent"}));
		};
	}

function clearDefaults() {
	$("input[type='text']").attr('value', function(){
		var thisObj = $(this);
		
		if (thisObj.attr('title') == thisObj.val()) {
			return "";
		}
		return thisObj.val();	
	});
}

function closePopup(popupId) {
	$('.modalOverlay').remove();
	$("#" + popupId).hide();
	return false;
}


var moneyUnitCheckTimer = null;
function checkMoneyUnitsEntered ()
{
	if ($(".widgetGoalRedeemGoalpack #authorizationCode").val().length == 16 &&
		$(".widgetGoalRedeemGoalpack #pin").val().length == 4)
	{
		wait_on(".widgetGoalRedeemGoalpack");
		clearInterval(moneyUnitCheckTimer);
		$("#cashFunctionForm").submit();
		return false
	}
	return true;
}



/**
 * Validates money units.
 */
function validateMoneyUnits(formId, callback, ignoreBlank, validateUrl) {
	$('.mappedfieldmessage span').html("");
	$('.mappedfielderror li').html("");
	
	clearDefaults();
	$('input[name="authorizationNumber"]').attr('disabled',false);
	$('input[name="pin"]').attr('disabled',false);
	
	var postUrl = "acValidateMoneyUnits"; 
	if (validateUrl !== null) {
		postUrl = "acValidateMoneyUnitsGuest";
	}
	wait_on('#' + formId);
	$.ajax({			
		type: "POST",
		url: postUrl,
		data: $("#" + formId).serialize() + "&ignoreBlank=" + ignoreBlank,
		success: function(html) {
			wait_off();
			// update labels
			$("#hidden_ajax_result").html(html);
			
			$("#tableAjaxFieldMessages li").each(function(){
	 			$('#'+ $(this).attr('title')).html($(this).html());
			});

			$('#tableAjaxFieldErrors li').each(function() {
				if ($(this).attr('title') == 'lockedout') {
					location.href = 'acHome';
				}
	 			$('.mappedfielderror li[title='+ $(this).attr('title') +']').html($(this).html())
	 		});
			
			if ($('#tableAjaxFieldErrors li').length == 0) {
				if (typeof(callback) == 'function') {
					callback();
				}
			}
		}, 
		error: function() {
			alert("Error loading page");
		}
	});
}

 // This function submits the form to the specific url\
 // The response must incorporate the parent container with and id attribute
 // that indicates where the html is to be injected into the page.
function submitReplace(formId, url, type) {
	doSubmitReplace(formId ? $("#" + formId) : null, url, type);
}

 /**
  * Like submitReplace but using the parent form of the supplied button
  */
function submitParentReplace(button) {
	var form = $(button).closest("form");
	doSubmitReplace(form, form.attr("action"), form.attr("method"));
	return false;
}

function doSubmitReplace(form, url, type) {
	if (!type) type = "POST";
	if (form)
		wait_on_element(form);
	else
		wait_on();
	$.ajax({			
		type: type,
		data: form ? form.serialize() : null,
		url: url,	
		dataType: "html",
		success: function(html) {
			wait_off();
			var div = document.createElement("DIV");
			div.innerHTML = html.replace(/^[\S\s]*?\</, "<");
			var targetElement;
			if (div.firstChild.id)
				targetElement = form ? form.closest("#" + div.firstChild.id) : $("#" + div.firstChild.id);
			else if (div.firstChild.className)
				targetElement = form ? form.closest("." + div.firstChild.className.replace(/ .*/, "")) : $("." + div.firstChild.className.replace(/ .*/, ""));
			else
				alert("malformed response");
			if (targetElement) {
				targetElement.html(div.firstChild.innerHTML);
				initUI(targetElement);
			}
		},
		error: function(request, status, error) {
			wait_off();
			alert("Error loading page " + status + " - " + error);
		}
	});
}

/**
 * Sends the fund raising email.
 */
function sendFundRaisingEmails(formId) {
	$('.mappedfieldmessage span').html("");
	$('.mappedfielderror li').html("");
	
	clearDefaults();
	wait_on("#goalFundraisingNowForm")
	$.ajax({			
		type: "POST",
		url: "emailFundraisingMessage",	
		data: $("#" + formId).serialize(),
		success: function(html) {
			wait_off();
			// update labels
			$("#hidden_ajax_result").html(html);
			
			$("#tableAjaxFieldMessages li").each(function(){
				$('#'+ $(this).attr('title')).html($(this).html());
			});
			
			$('#tableAjaxFieldErrors li').each(function() {
				$('.mappedfielderror li[title='+ $(this).attr('title') +']').html($(this).html())
			});
			
			if ($('#tableAjaxFieldErrors li').length == 0) {
				confirm_on("#goalFundraisingNowForm", null, "eMails have been sent");
				emailAddressCount = 0;
				$('div#emailAddress').children().remove();
				$('#btnSendMessage').hide();
				return false;
			}
		}, 
		error: function() {
			alert("Error loading page");
		}
	});
}
function submitAjaxAndReplace(formId, targetUrl, targetDiv, confirmation, redirect, callback, p1, p2, p3) {
	$('.mappedfieldmessage span').html("");
	$('.mappedfielderror li').html("");
	
	clearDefaults();
	wait_on(targetDiv);
	$.ajax({			
		type: "POST",
		url: targetUrl,	
		data: $("#" + formId).serialize(),
		success: function(html) {
		wait_off();
		// update labels
		$("#hidden_ajax_result").html(html);
		
		$("#tableAjaxFieldMessages li").each(function(){
			$('#'+ $(this).attr('title')).html($(this).html());
		});
		
		$('#tableAjaxFieldErrors li').each(function() {
			$('.mappedfielderror li[title='+ $(this).attr('title') +']').html($(this).html())
			$('.mappedfielderror li[title='+ $(this).attr('title') +']').removeClass("domster_hidden")
			$('.mappedfielderror li[title='+ $(this).attr('title') +']').parent().removeClass("domster_hidden")
		});
		
		if ($('#tableAjaxFieldErrors li').length == 0) {
			var target = $(targetDiv);
			if (!redirect)
				target.html(html);
			maskInputs(target);
			initUI(target);
			if (redirect)
				document.location.href=redirect;
			else if (confirmation)
				popMessage(confirmation, redirect, true)
			if (callback)
				callback.call(null, p1, p2, p3);
		}
	}, 
	error: function() {
		alert("Error loading page");
	}
	});

}

function updateEmailAddress(formId) {
	submitAjaxAndReplace(formId, "updateEmailAddress", "#email_address_edit", null, null, function() { $('.edit').show(); });
}

function updatePhoneNumber(formId) {
	submitAjaxAndReplace(formId, "updateTelephone", "#phone_number_edit", null, null, function() { $('.edit').show(); });
}
/* Edite Mailing Address */
function editMailingAddress()
{
	closeConfirm();
	$('#mailing_address_edit .fieldStaticAddress').hide();
	$('#mailing_address_edit .fieldEditAddress').show();
	$('#mailing_address_edit .fieldStatic').hide();
	$('#mailing_address_edit .fieldEdit').show();
	$('.edit').hide();
	$('#care_oof').focus();

	return false;
}
/* Clear Edite Mailing Address */
function clearEditMailingAddress()
{
	closeConfirm();
	$('#mailing_address_edit .fieldStaticAddress').show();
	$('#mailing_address_edit .fieldEditAddress').hide();
	$('#mailing_address_edit .fieldStatic').show();
	$('#mailing_address_edit .fieldEdit').hide();
	$('.edit').show();
	$('.mappedfielderror').addClass("domster_hidden")
	return false;
}

function updateMailingAddress() {
	submitAjaxAndReplace("formContentContactInfo", "updateMailingAddress", "#mailing_address_edit", null, null, function() { $('.edit').show(); });
}

function updateUserEmail(formId) {
	submitAjaxAndReplace(formId, "updateEmailAddress", "#email_address_edit");
}

function submitWithdrawalRequest(formId) {
	submitAjaxAndReplace(formId, "withdrawFunds", ".widgetGoalContentWithdraw");
}

function contributeAndUpdateBankFund() {
	wait_on(".widgetGoalContentContribute");
	$.ajax({			
		type: "POST",
		url: "acContributeBankFund",	
		success: function(html) {
		wait_off();
		$(".widgetGoalContentContribute").html(html);
	}, 
	error: function() {
		alert("Error loading page");
	}
	});
}

function contributeAndBankFund() {
	wait_on(".widgetGoalContentContribute");
	$.ajax({			
		type: "POST",
		url: "acProcessMoneyTransfer",	
		success: function(html) {
		wait_off();
		$(".widgetGoalContentContribute").html(html);
	}, 
	error: function() {
		alert("Error loading page");
	}
	});
}
function processWithdrawal() {
	wait_on(".widgetGoalContentWithdraw");
	$.ajax({			
		type: "POST",
		url: "processWithdraw",	
		success: function(html) {
		wait_off();
		// The code below should work but rejects this particular html for
		// reasons unknown
		// $(".widgetGoalContentWithdraw").html(html);
		$(".widgetGoalContentWithdraw").attr('innerHTML',html);
	}, 
	error: function() {
		alert("Error loading page");
	}
	});
}
function showLinkedBank(state)
{	
	
	if (state == "show") {
		$("#linkedBankInstructions").show();
		$("#bankTableEmpty").show();
		$(".fieldEdit").hide();
		$(".fieldStatic").show();
		$("#cancelLinkedAccount").hide();
		$("#deleteLinkedAccount").show();
		$("#createLinkedAccount").show();
		$(".edit").show();
		$("#submitSaveLinkedAccount").hide();
		$("#submitCreateLinkedAccount").hide();
		$("#cancelLinkedAccount").hide();
		findFocus();

	} else {
		$("#linkedBankInstructions").show();
		$("#bankTableEmpty").hide();
		$("#bankTable").show();
		$(".fieldEdit").show();
		$(".fieldStatic").hide();
		$("#cancelLinkedAccount").show();
		$("#deleteLinkedAccount").hide();
		$("#createLinkedAccount").hide();
		$(".edit").hide();
		if (state == "create") {
			$("#submitSaveLinkedAccount").hide();
			$("#submitCreateLinkedAccount").show();
		}
		if (state == "edit") {
			$("#submitCreateLinkedAccount").hide();
			$("#submitSaveLinkedAccount").show();
		}
		$(".bankTable #formAccountInfo input").unbind('keydown');
		$(".bankTable #formAccountInfo input").keydown(
			function(e)
			{
				if(e.keyCode == 13) {
					submitAjaxAndReplace('formAccountInfo', 'updateLinkedBankAccount', '#edit_account_fields');
					return false
				}
				return true;
			}
		);
	}
}

function deleteLinkedAccount() {
	closeConfirm();
	wait_on(".widgetAccountInfoContent")
	$.ajax({			
		type: "POST",
		url: "deleteLinkedBank",	
		success: function(html) {
			wait_off();
			popMessage(html, "acViewBankTransactions");
		}, 
		error: function() {
			alert("Error loading page");
		}
	});
	
}

function deleteRecurring() {
	closeConfirm();
	wait_on(".widgetAccountInfoContent")
	$.ajax({			
		type: "POST",
		url: "deleteRecurring",	
		success:
			function(html) {
					wait_off();
					popMessage(html, "acViewBankTransactions", true);
			}, 
	error: function() {
		alert("Error loading page");
	}
	});
}


function showWithdrawTab(){
	$(".TabwidgetGoalTabWithdraw").each(function() {
		var thisObj = $(this);
		var liObj = thisObj.parent();
		var ulObj = liObj.parent();
		var activeObj = $('.active', ulObj);
		var contentObj = $('.widgetGoalContent', ulObj.parent().parent().parent());
		
		// Hide content
		$('.widgetGoalContentOverview, .widgetGoalContentContribute, .widgetGoalContentFundraise', contentObj).hide();
		
		activeObj.removeClass('active');
		liObj.addClass('active');
	
		$('.widgetGoalContentWithdraw', contentObj).show();	
		updateSliderSelector(sliderVal);
		findFocus();

	});
	return false;
};

function showFundRaiseTab(){
	$(".TabwidgetGoalTabFundraise").each(function () {
		var thisObj = $(this);
		var liObj = thisObj.parent();
		var ulObj = liObj.parent();
		var activeObj = $('.active', ulObj);
		var contentObj = $('.widgetGoalContent', ulObj.parent().parent().parent());
		
		// Hide content
		$('.widgetGoalContentOverview, .widgetGoalContentContribute, .widgetGoalContentFundraise, .widgetGoalContentWithdraw', contentObj).hide();
		
		activeObj.removeClass('active');
		liObj.addClass('active');
	
		$('.widgetGoalContentFundraise', contentObj).show();	
		updateSliderSelector(sliderVal);
		findFocus();

	});
	return false;
};

function showContributeTab(root, expand){
	root.find(".TabwidgetGoalTabContribute").each(function() {
		var thisObj = $(this);
		var liObj = thisObj.parent();
		var ulObj = liObj.parent();
		var activeObj = $('.active', ulObj);
		var contentObj = $('.widgetGoalContent', ulObj.parent().parent().parent());
		
		// Hide content
		$('.widgetGoalContentOverview, .widgetGoalContentContribute, .widgetGoalContentFundraise, .widgetGoalContentWithdraw', contentObj).hide();
		
		activeObj.removeClass('active');
		liObj.addClass('active');
	
		$('.widgetGoalContentContribute', contentObj).show();
		if (expand) {
			$("." + expand).click();
		}
		updateSliderSelector(sliderVal);
		
		findFocus();

	});
	return false;
};

/* Goal Widget Tabs */
function showMyGoalTab(){
	var thisObj = $("#TabwidgetGoalTabOverview");
	var liObj = $(thisObj.parent().get(0));
	var ulObj = $(liObj.parent().get(0));
	var activeObj = $('.active', ulObj);
	var contentObj = $('.widgetGoalContent', $($($(ulObj.parent().get(0)).parent().get(0)).parent().get(0)));
	
	// Hide content
	$('.widgetGoalContentOverview, .widgetGoalContentContribute, .widgetGoalContentFundraise, .widgetGoalContentWithdraw', contentObj).hide();
	
	activeObj.removeClass('active');
	liObj.addClass('active');

	$('.widgetGoalContentOverview', contentObj).show();	

	updateSliderSelector(sliderVal);
    
	return false;
}
function clearUpdatePassword() {
	$('#passwordView').show();
	$('#passwordEdit').hide();
	$('.edit').show();
	return false;
};



function submitUpdatePassword() {
	clearMessages();

	var data = "";
	data += "oldPassword="+$("#oldPassword").val();
	data += "&newPassword="+$("#newPassword").val();
	data += "&confirmPassword="+$("#confirmPassword").val();
	wait_on("#formPasswordsSecurity");
	$.ajax({			
		type: "POST",
		url: "acUpdatePassword",	
		data: data,
		success: function(html) {
			// update labels
			$('#oldPassword').val("");
			$('#newPassword').val("");
			$('#confirmPassword').val("");
			wait_off();
			$("#hidden_ajax_result").html(html);
			
			var withError = false;
			$('#tableAjaxFieldErrors li').each(function() {
				withError = true;
	 			$('.passwordmappedfielderror li[title='+ $(this).attr('title') +']').html($(this).html())
	 		});
			if (withError) {
				$('#passwordEdit').show();
				$('#passwordView').hide();
			} else {
				confirm_on("#formPasswordsSecurity");

				$('#passwordEdit').hide();
				$('#passwordView').show();
				$('.edit').show();
			}
			
		}, 
		error: function() {
			alert("Error loading page");
			$('#passwordEdit').hide();
			$('#passwordView').show();
		}
	});	
}

function clearMessages() {
	$('#passMsgSpan').html(""); // clear
	$('.passwordmappedfielderror li').each(function() {
		$(this).html('');
	});
	$('.ivrmappedfield li').each(function() {
		$(this).html('');
	});
	for (var i=1; i<4; i++) {
		$('.qamappedfield'+i+' li').each(function() {
			$(this).html('');
		});
	}
}
function clearUpdateQuestion(qIndex) {
	$('#editQ'+qIndex).hide();
	$('#viewQ'+qIndex).show();
	$('.edit').show();
}
function submitUpdateQuestion(qIndex) {
	clearMessages();

	var data = "";
	data += "questionId="+$("#question_"+qIndex).val();
	data += "&answer="+$("#answer_"+qIndex).val();
	data += "&password="+$("#question_"+qIndex+"_password").val();
	data += "&questionIndex="+qIndex;
	wait_on("#formPasswordsSecurity")
	$.ajax({			
		type: "POST",
		url: "acUpdateSecurityQuestion",	
		data: data,
		success: function(html) {
			// update labels
			wait_off();
			$("#hidden_ajax_result").html(html);
			
			var withError = false;
			$('#tableAjaxFieldErrors li').each(function() {
				withError = true;
	 			$('.qamappedfield'+qIndex+' li[title='+ $(this).attr('title') +']').html($(this).html())
	 		});

			if (withError) {
				$('#editQ'+qIndex).show();
				$('#viewQ'+qIndex).hide();
			} else {

				confirm_on("#formPasswordsSecurity");
				
				// update values in view
				$('#question_'+qIndex).val($("#question_"+qIndex).val());
				$('#question_'+qIndex+'_disabled').val($("#question_"+qIndex).val());

				$('#editQ'+qIndex).hide();
				$('#viewQ'+qIndex).show();
				$('.edit').show();
			}
			
		}, 
		error: function() {
			alert("Error loading page");
			$('#editQ'+qIndex).hide();
			$('#viewQ'+qIndex).show();
		}
	});	
}
function clearUpdateIvrPin(qIndex) {
	$('#ivrPinEdit').hide();
	$('#ivrPinView').show();
	$('.edit').show();
}
function submitUpdateIvrPin(qIndex) {
	clearMessages();

	var data = "";	
	data += "ivrPin="+$("#newIvrPin").val();
	data += "&confirmIvrPin="+$("#confirmIvrPin").val();
	data += "&oldPasswordIVR="+$("#oldPasswordIVR").val();
	wait_on("#formPasswordsSecurity")
	$.ajax({
		type: "POST",
		url: "acUpdateIvrPin",	
		data: data,
		success: function(html) {
			// update labels
			wait_off();
			$('#oldPasswordIVR').val('');
			// $('#newIvrPin').val('');
			// $('#confirmIvrPin').val('');
			$("#hidden_ajax_result").html(html);

			var withError = false;
			$('#tableAjaxFieldErrors li').each(function() {
				withError = true;
	 			$('.ivrmappedfield li[title='+ $(this).attr('title') +']').html($(this).html())
	 		});

			if (withError) {
				$('#ivrPinEdit').show();
				$('#ivrPinView').hide();
			} else {
				confirm_on("#formPasswordsSecurity");

				$('#ivrPinEdit').hide();
				$('#ivrPinView').show();
				$('.edit').show();
			}
			
		}, 
		error: function() {
			alert("Error loading page");
			$('#ivrPinEdit').hide();
			$('#ivrPinView').show();
		}
	});	
}

function add_commas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = "";
	var decimals = (x.length > 1) ? x[1] : "00";
	var decimalsAdded = 0;
	var decimalIndex = 0;
	while (decimalIndex < 2) {
		if (decimalIndex >= decimals.length) {
			x2 = x2 + "0";
		} else {
			x2 = x2 + decimals.substr(decimalIndex, 1);
		}
		decimalIndex += 1;
	}
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + "." + x2;
}

function changeProductType(element) {
	hideProdSel();
	getProductSelect(element.value);
}

function hideProdSel() {
	var sel = document.getElementById('productTypes');
	for (var i=0; i< sel.options.length; i++) {
		var opt = sel.options[i];
		$('#'+opt.text+'_span').hide();
	}
}

function getProductSelect(selName) {
	$('#'+selName+'_span').show();
	var selected = document.getElementById(selName+'_select');
	// set to new product code
	$('#newProductCode').val(selected.value);
}

function changeProductCode(element) {
	$('#newProductCode').val(element.value);
}
function setSameAsBilling() {
	var fields = ["address_1", "address_2", "city", "state", "zip", "phone_masked", "phone_ext"];
	var same = true;
	for (var ix = 0; ix < fields.length; ++ix)
		if ($("#" + fields[ix]).val() != $("#delivery_" + fields[ix]).val())
			same = false;
	$("#same_as_billing").attr('checked', same);
}
function validateAndSubmit(formName) {
	$('.mappedfielderror li').html("");
	var form = $('#' + formName);
	// Clear pre-populated fields
	form.find("input[type='text'],textarea").each(function() {
		var thisObj = $(this);
		var title = thisObj.attr('title');
		var value = thisObj.val();		
		if (value==title) {			
			thisObj.val('');
		}
	});
	wait_on("#" + formName)
	$.ajax({
		type: "POST",
		url: form.attr("action"),
		data: form.serialize(),
		success: function(html){
	 		$('#hidden_ajax_result_large').html(html);
	 		wait_off();
	 		var submissionResult = $('#ajax_result_success_flag').html();
	 		if (submissionResult == 'true') {
	 			var resultType = $('#ajax_result_type').html();
	 			if (resultType == 'redirect') {
	 				window.location.href = $('#ajax_result_redirect').html();
	 			} else {
	 				popupBox('hidden_ajax_result_large');
	 			}
	 		} else {
		 		// form errors
		 		$('#tableAjaxFieldErrors li').each(function() {
		 			$('.mappedfielderror li[title='+ $(this).attr('title') +']').html($(this).html()).closest("ul").removeClass("domster_hidden");
		 		});
	 		}
		}
	});		
}

function popupBox(el) {
	$('body').append('<div class="modalOverlay"></div>');
	var boxObj = $('#' + el).centerInClient();
	boxObj.show();
}

function userNameChange(cnl) {
	if (cnl) {
		document.getElementById('nochange').value = 'Y';
	} else {
		document.getElementById('nochange').value = 'N';
	}
	$('#usernameChangeForm').submit();	
}

function stateChange(e) {
	var idx = e.selectedIndex; 
	document.getElementById('stateCode').value = e.options[idx].value; 
}
function kill_existing_questions(qc, q1, q2)
{
	var questions = $(qc + ' option');
	var question1 = $(q1 + ' option:selected').text();
	var question2 = $(q2 + ' option:selected').text();
	for (i = 0; i < questions.length; ++i)
		if (questions[i].text == question1 || questions[i].text == question2)
			$(questions[i]).remove();
}

all_question_options = $("#question_list option");

function process_security_questions()
{
	process_security_question(0);
}
function process_security_question(q_changed)
{
	
	// Get the ids of the security question selects and their respective values
	var values = [];
	var qid = [];
	for (var ix = 0; ix < total_security_questions; ++ix) {
		qid[ix] = "formOpenAccount_userQuestions_" + ix +"__question_id";
		var value = $("#" + qid[ix] + " option:selected").text();
		if (value && value.length > 0)
			values.push(value);
	}
	
	// Walk through each of the other questions (the ones not being changed)
	for (var qx = 0; qx < total_security_questions; ++qx)
		if (qx != q_changed)
		{
			// Restore the questions form the complete list and the current
			// selected value
			var select = $("#" + qid[qx]);
			var selected_value = $("#" + qid[qx] + " option:selected").text();
			select.empty().append(all_question_options.clone());
			select.val(selected_value);
		
			// Remove any values (other than the one currently selected)
			var options = $("#" + qid[qx] + " option");
			for (var ix = 0; ix < options.length; ++ix)
				for (jx = 0;jx < values.length; ++jx)
					if (options[ix].text == values[jx] && options[ix].text != selected_value)
						$(options[ix]).remove();
		}
}

var truncateFieldTimer = null;
function TruncateFields()
{
	$("textarea:regex(class, ^maxlength.*)").each (
		function() {
			if ($(this).attr('className').match(/maxlength([0-9]+)/))
			{
				var length = RegExp.$1;
				if ($(this).val().length > length)
					$(this).val($(this).val().substring(0, length - 1));
				$(this).nextAll(".maxlength:first").html("You have " + (length - $(this).val().length) + " remaining character(s)");
			}
		}
	);
}

var xtra_hide;

function confirm_on(form_id, xtra_hide_request, text) {
	confirm_on_form($(form_id), xtra_hide_request, text);
}

function confirm_on_form(form, xtra_hide_request, text)
{
	xtra_hide = xtra_hide_request;
	
	// Show the confirmation message and any extra bits that are scree specific
	// (xtra_hide_request)
	var confirmationMessageContainer = form.nextAll(".confirmMessageContainer:first");
	if (confirmationMessageContainer.length == 0) confirmationMessageContainer = form.find(".confirmMessageContainer:first");
	if (confirmationMessageContainer.length > 0)
		confirmationMessageContainer.html('<div id="saveConfirm">' + (text ? text : 'Your Changes Have Been Saved') + '</div>');
	else
		form.append('<div class="confirmMessageContainer"><div id="saveConfirm">' + (text ? text : 'Your Changes Have Been Saved') + '</div></div>');
	
	if (xtra_hide_request)
		$(xtra_hide_request).show();
	
	form.mouseup(function(){confirm_hide();return true;});
	form.keydown(function(){confirm_hide();return true;});
}
function hide_on_click(form_id, xtra_hide_request)
{
	xtra_hide = xtra_hide_request;
	$(form_id).mouseup(function(){confirm_hide();return true;});
	$(form_id).keydown(function(){confirm_hide();return true;});
}	
function confirm_hide()
{
	if ($("#saveConfirm"))
	{
		$("#saveConfirm").parent().html("&nbsp;");
	}
	if (xtra_hide)
		$(xtra_hide).hide();
}
function wait_on(selector)
{
	wait_on_element(selector ? $(selector) : null);
}
function wait_on_element(element) {
	// Default element to widgetGoal
	if (!element || element.length == 0) element = $(".widgetGoal");
	// Otherwise default element to mainContent
	if (element.length == 0) element = $("#mainContent");
	var offset = element.offset();
	var top = offset.top;
	var left = offset.left;
	var width = element.width();
	var height = element.height();
	$("#progress_container").css({top: top, left: left, width: width, height: height});
	$("#progress_container").show();
}
function wait_off()
{
	$("#progress_container").hide();
	session_timeout_reset();
}
var timeout_final_seconds;
var timeout_message;
var timeout_redirect;
var timeout_seconds;

function session_timeout(seconds, final_seconds, message, redirect)
{
	timeout_seconds = seconds;
	timeout_final_seconds = final_seconds;
	timeout_message = message;
	timeout_redirect = redirect;

	timeout_timer = setTimeout("session_timeout_expires_main()", timeout_seconds * 1000 - timeout_final_seconds * 1000 - 1000);
}
function session_timeout_expires_main()
{
	clearTimeout(timeout_timer);
	confirm("Still Working?", timeout_message, "session_timeout_extend()", true);
	timeout_timer = setTimeout("session_timeout_expires_final()", timeout_final_seconds * 1000);
}
function session_timeout_expires_final()
{
	document.location.href = timeout_redirect;
}
function session_timeout_extend()
{
	clearTimeout(timeout_timer);
	timeout_timer = null;
	$.ajax({			
		type: "POST",
		url: "keepalive",	
		data: "",
		success: function (html) {},
		error: function() {}
	});
	timeout_timer = setTimeout("session_timeout_expires_main()", timeout_seconds * 1000 - timeout_final_seconds * 1000 - 1000);
}

function session_timeout_reset()
{
	if ((typeof(timeout_timer) != 'undefined') && !timeout_timer) {
		clearTimeout(timeout_timer);
		session_timeout(timeout_seconds, timeout_final_seconds, timeout_message, timeout_redirect)
	}
}
function getCookieJar()
{
	var cookies = document.cookie.split(";");
	var jar = new Object();
	for (var i = 0; i < cookies.length; ++i)
		if (cookies[i].match(/[ ]*(.*?)=(.*)/))
			jar[RegExp.$1] = RegExp.$2;
	return jar;
}
function fbs_click() {
	u=location.href;
	t=document.title;window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}

// tooltips
$("#mainContent a.hover").hover(
	function() {
		$(this).children(".hoverBox").show();
	},
	function() {
		$(this).children(".hoverBox").hide();
	}
);
$("#copy a.hovertip").hover(
	function() {
		$(this).next().show();
	},
	function() {
		$(this).next().hide();
	}
);

// login overlay

$(document).ready(function() {
	$("#formLoginHeader input").keydown(function(e){if(e.keyCode ==13){$("#formLoginHeader").submit();return false;}});
	
	$(".defaultText").focus(function(srcc) { if ($(this).val() == $(this)[0].title) { $(this).val(""); }});
	$(".defaultText").blur(function()  	 { if ($(this).val() == "") { $(this).val($(this)[0].title); }});
	$(".defaultText").blur();  
	
	$("#passwordtext").focus(function() { 
		$('.passwordcapture').show();
		$('.passwordcapture').focus();
		$('#passwordtext').hide();
	});
	$(".passwordcapture").blur(function() { 
		if ($('.passwordcapture').val() == "") {
			$('.passwordcapture').hide();
			$('#passwordtext').show();
		}
	});
	
});
// Give focus to the last object of class "focus" that is visible
$(document).ready(function() {
	findFocus();
});
function findFocus() {
	$(".focus").each(function () {
		if ($(this).css('visibility') != 'hidden' &&
			$(this).css('display') != 'none')
			$(this).focus();
			return;
	});
}
$(document).ready(function() {
	// Enable tooltip for left column of account page
	$("#mainContentLeftCol a.hover").hover(
		function() {
			$(this).next().show();
		},
		function() {
			$(this).next().hide();
		}
	);
});

function showHideLoggedInElements(root) {
	var loggedInUserEmailAddress = getLoggedInUserEmailAddress();
	
	if (loggedInUserEmailAddress) {
		root.find("#emailAddressAndLink").text(loggedInUserEmailAddress);
		root.find(".visibleWhenLoggedIn").show();
		root.find(".visibleWhenLoggedOut").hide();
	} else {
		root.find(".visibleWhenLoggedOut").show();
		root.find(".visibleWhenLoggedIn").hide();
	}
}
function fixButtons(root) {
	root.find("a.button").each(function() {
		var button = $(this);
		if (button.find("span.left").length > 0) {
			// Button has already been styled, skip it
			return;
		}
		var text = button.html();
		button.contents().remove();
		button.append('<span class="left"></span>');
		button.append('<span class="text">' + text + '</span>');
	});
}
function initUI(root) {
	
	recurringTransactionEvents(root);

	// Set tab indexes
	var currentTabIndexForAutoSet = 1;
	$("[tabindex='0']").each(function() {
		if ($(this).attr("tabindex") == "0") {
			$(this).attr("tabindex", currentTabIndexForAutoSet);
			currentTabIndexForAutoSet += 1;
		}
	});
	// Style buttons
	fixButtons(root);
	if ((typeof(registrationPendingCIP) != 'undefined') && registrationPendingCIP) {
		// Hide any elements that require a verified account
		root.find(".hideOnPendingCIP").hide();
	}
	
	if ((typeof(accountBlocked) != 'undefined') && accountBlocked) {
		// Hide any elements that require an unblocked account
		root.find(".requiresUnblockedAccount").hide();
	}
	
	/**
	 * Hide/Show Section Widget
	 */
	root.find(".widgetSection .widgetSectionHeader").click(function(){
		toggleSection($(this).find(".widgetSectionToggle"));
	});
	
	$("#add_recurring_monthly_transaction_yes").click(function(){
		var checkbox = $('#add_recurring_monthly_transaction_yes');
		$("#add_recurring_monthly_transaction_yes").val(checkbox.attr('checked') ? 'true' : 'false')
		if (checkbox.attr('checked')) {
			$(".additionalField").each(function(){
				$(this).show();
			});
		} else {
			$(".additionalField").each(function(){
				$(this).hide();
			});
		}
	});
	
	root.find("a#editMailingAddress").click(function() {
		popConfirm(this, '<br /><br />Please note that you will not be able to have checks sent to you for 10 days after changing your address', 'editMailingAddress()');
		return false;
	});
	
	$("a#deleteLinkedAccount.deleteVerified").click(function() {
		popConfirm(this, '<br /><br />Deleting this bank account will also delete any automatic transactions associated with it. Do you still want to continue?', 'submitAjaxAndReplace(null, \'deleteLinkedBank\', \'#mainContent\', null, \'acViewBankTransactions\')');
		return false;
	});
	
	$("a#deleteLinkedAccount.deleteUnverified").click(function() {
		popConfirm(this, 'Are you sure you want to delete this linked bank account?', 'submitAjaxAndReplace(null, \'deleteLinkedBank\', \'#mainContent\', null, \'acViewBankTransactions\')');
		return false;
	});
	
	$("a#deleteLinkedAccount.deletePending").click(function() {
		popConfirm(this, 'This bank account has not yet been verified. If you delete this bank account, you will need to start the verification process from the beginning. Two new deposits will be sent to your bank account, which again will appear in 2 – 4 business days. You will see the old deposits in your account but these will no longer be valid for verification. Are you sure you want to delete this pending bank account?', 'submitAjaxAndReplace(null, \'deleteLinkedBank\', \'#mainContent\', null, \'acViewBankTransactions\')');
		return false;
	});
	
	$("a#editLinkedAccount").click(function() {
		popConfirm(this, 'Please note that once you add a new bank account, you will need to verify you are the account owner before you can start using it. This usually takes 2-3 business days.', 'showLinkedBank(\'edit\')');
		return false;
	});
	
	// Initialize AJAH forms
	var ajahForms = root.find("form.ajah");
	ajahForms.submit(submitAJAHForm);
	ajahForms.find("a.submitButton").click(function() {
		clearDefaults();
		$(this).closest("form.ajah").submit();
	});
	ajahForms.find('input').keydown(function(e) {
		if(e.keyCode == 13) {
			var obj = $(this);
			while (obj && !obj.is('form'))
				obj = obj.parent();
			clearDefaults();
			$(this).closest("form").submit();
			return false;
		}
		return true;
	});
	// Initialize AJAH links
	root.find("a.ajah").click(clickAJAHLink);
	// Remove the ajahReplace attribute
	root.find("[ajahReplace]").removeAttr("ajahReplace");
	
	showHideLoggedInElements(root);
	
	root.find("#accountActivityLink").click(function() {
		var goalId = $.cookie("currentGoalId");
		if (goalId == null || goalId == "null") goalId = "";
		location.href = 'acSearchHistory?searchGoalId=' + goalId;
	});
	
	root.find('.submitOnEnterWithSubmitButton input').keydown(function(e) {
		if(e.keyCode == 13) {
			var obj = $(this);
			while (obj && !obj.is('form'))
				obj = obj.parent();
			$("a.submitButton", obj).click();
			return false;
		}
		return true;
	});
	
	root.find(".disableOnClick").click(function() {
		var link = $(this);
		if (!link.data("disabled")) {
			link.data("disabled", true);
			link.attr("onclick", "");
			link.click(function() {
				return false;
			});
		}
	}); 
	
	root.find(".goalPackValue").numeric();
	
	$(".linkShare").click(function() {
		selectText($(this).children()[0]);
	});

	rotateStockMarketStories();
	
	initExternalWidgetOverlay(root);
	
	
	root.find(".bankFieldSet .hover").hover(
		function() {
			$(this).children(".hoverBoxCheck").show();
		},
		function() {
			$(this).children(".hoverBoxCheck").hide();
		}
	);
	
	// Set up profile functionality
	root.find(".reminderList li").hover(function() {
        var _this = $(this);
        _this.find(".reminderActions").css("visibility", "visible");
        var icon = _this.find(".reminderIcon");
        if (icon.length > 0) {
        	 var url = icon.attr("src");
             url  = url.substring(0, url.length - 4) + "_white.png";
             icon.attr("src", url);
        }
    }, function() {
    	var _this = $(this);
    	_this.find(".reminderActions").css("visibility", "hidden");
        var icon = _this.find(".reminderIcon");
        if (icon.length > 0) {
            var url = icon.attr("src");
            url  = url.substring(0, url.length - 10) + ".png";
            icon.attr("src", url);
        }
    });
    
	// Set up goal picker flyouts
	root.find(".goalDependent").hover(function() {
        var container = $(this);
        var picker = container.find(".flyoutPicker");
        container.addClass("goalDependentHover");
        picker.show();
        picker.animate({
            width: 400
        }, 250);
    }, function() {
        var container = $(this);
        var picker = container.find(".flyoutPicker");
        picker.stop();
        container.removeClass("goalDependentHover");
        picker.animate({
            width: 0
        }, 50, function() {
        	picker.hide();
        });
    });
	
	if (typeof(initPage) != 'undefined') {
		initPage(root);
	}
}

/**
 * Selects all the text in the given element.
 * 
 * From StackOverflow, http://stackoverflow.com/questions/985272/jquery-selecting-text-in-an-element-akin-to-highlighting-with-your-mouse
 * 
 * @param text
 */
function selectText(text) {
	if ($.browser.msie) {
        var range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if ($.browser.mozilla || $.browser.opera) {
        var selection = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    } else if ($.browser.safari) {
        var selection = window.getSelection();
        selection.setBaseAndExtent(text, 0, text, 1);
    }
}

function toggleSection(obj) {
	var toggleLink = obj;
	
	var txt = $('span', toggleLink).text();
	
	// If this link is marked as toggling all, have it toggle all similar sections
	var toggleLinks = toggleLink.hasClass("widgetSectionToggleAll") ? $(".widgetSection .widgetSectionToggleAll") : toggleLink;
	
	toggleLinks.each(function() {
		var toggleLink = $(this);
		
		if(txt=='hide'){
			hideWidgetSection(toggleLink);
		} else {
			showWidgetSection(toggleLink);
		}
	});
	
	return false;

}
/**
 * Retrieves the logged in user's email address from cookies.  There are two cookies (session-based and time based)
 * that must both be present and equal in order for the logged in user's email address to be recognized.
 * 
 * @return
 */
function getLoggedInUserEmailAddress() {
	// If the current page does not allow itself to be displayed in a logged in state, never return an email address
	if (typeof (loggedInStateDisabled) != 'undefined' && loggedInStateDisabled)
		return null;
	return doGetLoggedInUserEmailAddress();
}

function doGetLoggedInUserEmailAddress() {
	try {
		var sessionBased = $.cookie('loggedInUserEmailAddressSessionBased');
		var timeBased = $.cookie('loggedInUserEmailAddressTimeBased');
		if (!sessionBased || !timeBased || sessionBased != timeBased) return null;
		else return sessionBased.replace(/"/g, "");
	} catch(error) {
		return null;
	}
}

/**
 * Submits an AJAH form (AJAX with HTML instead of XML). The action and method are taken from the form itself.
 * 
 * The top-level element in the returned HTML must include an "ajahReplace" attribute that provides a jQuery selector to
 * identify which element to replace with the returned markup.  The jQuery selector from ajahReplace is searched upward in the
 * DOM tree from the form element itself.
 * 
 * @return
 */
function submitAJAHForm() {
	var form = $(this);
	wait_on_element(form);
	var method = form.attr("method");
	if (!method) method = "POST";
	$.ajax({			
		type: method,
		data: form.serialize(),
		url: form.attr("action"),
		dataType: "html",
		success: function(html) {
			processAJAHResponse(form, html);
			wait_off();
		},
		error: function(request, status, error) {
			alert("Error loading page " + status + " - " + error);
			wait_off();
		}
	});
	return false;
}

/**
 * Processes an AJAH link. This is a link that is submitted via an AJAX GET request.
 * 
 * The returned HTML must contain an "ajahReplace" attribute - see submitAJAHForm() for more details.
 * 
 * @return
 */
function clickAJAHLink() {
	var link = $(this);
	var parentContainer = link.closest(".ajahContainer");
	if (parentContainer.length == 1) {
		wait_on_element(parentContainer);
	}
	var url = link.attr("href");
	// Add a timestamp to the link to avoid caching
	if (url.indexOf("?") >= 0) url = url + "&";
	else url = url + "?";
	url = url + (new Date()).getTime()
	$.ajax({			
		type: "GET",
		url: url,
		dataType: "html",
		success: function(html) {
			processAJAHResponse(link, html);
			if (parentContainer.length == 1) {
				wait_off();
			}
		},
		error: function(request, status, error) {
			alert("Error loading page " + status + " - " + error);
			if (parentContainer.length == 1) {
				wait_off();
			}
		}
	});
	return false;
}

function processAJAHResponse(target, html) {
	var isLoginPage = html.indexOf('form id="formLogin"') > 0;
	if (isLoginPage) {
		// Send user to login screen
		location.href = "login";
	} else {
		var newElement = $(html);
		var systemErrorContainer = newElement.find(".systemErrorContainer");
		if (systemErrorContainer.length == 1) {
			target.children().remove();
			target.append(systemErrorContainer.children());
		} else {
			var replaceSelector = newElement.attr("ajahReplace");
			if (!replaceSelector) {
				return;
			}
			var container = target.closest(replaceSelector);
			if (container.length == 0) {
				return;
			}
			container.children().remove();
			container.append(newElement.children());
			container.addClass("ajahContainer");
			revealFieldErrors();
			initUI(container);
		}
	}
}
function revealFieldErrors() {
	$("ui.mappedFieldError li").each(function(obj) {
		if ($(obj).html().length > 0) {
			$(obj).removeClass("domster_hidden");
			$(obj).parent().removeClass("domster_hidden");
		}
	});
}
$(document).ready(function() {
	initUI($(this));
});

$(document).ready(function() {
	$("#searchRegistryForm").submit(function() {
		clearDefaults();
		wait_on('.findRegistryForm');
	});
});
function printContent(location, title) {
	// First we expand any tables
	
	var printable = $(location).closest(".printable");
	var old = printable.find(".dataTables_length select").val();
	printable.find(".dataTables_length select").val(100);
	printable.find(".dataTables_length select").change();
	printTitle = title ? title : "";
	printData = printable.attr('innerHTML');
	printable.find(".dataTables_length select").val(old);
	printable.find(".dataTables_length select").change();
	window.open('acPrint','gmprint','width=920,height=500,status=no,copyhistory=no,location=no,scrollbars=1');
}
var printTitle="";
var printData="Nothing to Print";

function IE6FixPng(node)
{
	if (isIE6 && node.style.backgroundImage.match(/png/i))
	{
		var src=node.style.backgroundImage.replace(/url\(/,"").replace(/\)/,"");
		node.style.backgroundImage = node.style.backgroundImage.replace(/\/i\/.*/, "/i/spacer.png)");
		node.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' + src + ', sizingMethod=scale)';
		alert(node.parentNode.innerHTML);
	}
}
// Domster Filters
function format_scaled_currency_dollars(cents) {
	var negative = cents < 0;
	if (negative) alert(cents)
	if (negative) cents = cents.substr(1);
	result = "$ " +  format_scaled_whole(cents);
	if (negative) result = "(" + result + ")";
	return result;
}
function format_scaled_whole(cents) {
	cents = cents + "";
	var negative = cents < 0;
	if (negative) cents = cents.substr(1);
	while(cents.length < 3)
		cents = "0" + cents;
	var dollars = cents.substr(0, cents.length - 2);
	var cents = cents.substr(cents.length - 2);
	result = format_addCommas(dollars);
	if (negative) result = "(" + result + ")";
	return result;
}
function format_scaled_currency(cents) {
	var negative = cents < 0;
	if (negative) cents = (cents + "").substr(1);
	result = "$ " +  format_scaled(cents);
	if (negative) result = "(" + result + ")";
	return result;
}
function format_scaled(cents) {
	return do_format_scaled(cents, 2);
}
function format_scaled_shares(shares) {
	return do_format_scaled(shares, 3);
}
function do_format_scaled(cents, decimals) {
	cents = cents + "";
	var negative = cents < 0;
	if (negative) cents = cents.substr(1);
	while(cents.length < decimals + 1)
		cents = "0" + cents;
	var dollars = cents.substr(0, cents.length - decimals);
	var cents = cents.substr(cents.length - decimals);
	var result = format_addCommas(dollars + "." + cents);
	if (negative) result = "(" + result + ")";
	return result;
}
function format_scaled_currency_prefer_whole(cents) {
	var negative = cents < 0;
	if (negative) cents = (cents + "").substr(1);
	result = "$ " +  format_scaled_prefer_whole(cents);
	if (negative) result = "(" + result + ")";
	return result;
}
function format_scaled_prefer_whole(cents) {
	cents = cents + "";
	var negative = cents < 0;
	if (negative) cents = cents.substr(1);
	cents = (cents.length < 2 ? "0" + cents : cents);
	var dollars = cents.substr(0, cents.length - 2);
	var cents = cents.substr(cents.length - 2);
	var result = null;
	if (cents == "00")
		result = format_addCommas(dollars.length > 0 ? dollars : "0");
	else
		result = format_addCommas(dollars + "." + cents);
	if (negative) result = "(" + result + ")";
	return result;
}
function format_addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
function format_date_mm_dd_yyyy(time)
{
	var date = new Date();
	date.setTime(time);
	return (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear();
}
function format_iso_date_mm_dd_yyyy(dateString) {
	var date = new Date();
	date.setISO8601(dateString);
	return (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear();
}

function calculate_goal_progress(projectedBalance, target)
{
	var progress = Math.round(100 * projectedBalance / target);
	if (progress < 1 && projectedBalance > 0)
		progress = 1;
	return progress;
}
function calculate_goal_progress_bar(projectedBalance, target)
{
	var progress = calculate_goal_progress(projectedBalance, target); 
	if (progress > 100)
		var progress_bar = 95;
	else
		var progress_bar = progress * .95;
	if (progress_bar < 3.5)
    	progress_bar = 3.5;
    return progress_bar;
}
function calculate_goal_progress_width(projectedBalance, target)
{
    style_width = calculate_goal_progress_bar(projectedBalance, target);
    if (style_width > 100)
    	style_width = 95;
    return style_width;
}
function calculate_goal_progress_html(staticResources, goal)
{
	if (isIE6)
		return "<div class='leftBulb'  style='background: url(" + staticResources + 
			"/i/spacer.png) 0px 0px no-repeat;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" + staticResources +
			"/i/goals/progressBarBulb" + goal.type + ".png, sizingMethod=crop)'></div>" + 
	        "<div class='rightBulb' style='width: " + calculate_goal_progress_width(goal.projectedBalance, goal.target) + 
	        "%;background: url(" + staticResources + 
	        "/i/goals/progressBarBulb" + goal.type + ".png) -34px 0px no-repeat;'></div>";
    else
    	return "<div class='leftBulb' style='background: url(" + staticResources +
        	 "/i/goals/progressBarBulb" + goal.type + ".png) 2px 0px no-repeat;'></div>" +
        	 "<div class='rightBulb' style='width: " + calculate_goal_progress_width(goal.projectedBalance, goal.target) + 
        	 "%;background: url(" + staticResources + 
        	 "/i/goals/progressBarBulb" + goal.type + ".png) right top no-repeat;'></div>";

}

function setCurrentGoalId(goalId) {
	$.cookie("currentGoalId", goalId);
	$.cookie("currentAccountId", null);
}

function setCurrentAccountId(accountId) {
	$.cookie("currentGoalId", null);
	$.cookie("currentAccountId", accountId);
}

function refresh(excludeParams) {
	wait_on_element($("body"));
	var newLocation = location.pathname;
	if (location.search) {
		var search = location.search;
		for (var i in excludeParams) {
			excludeParam = excludeParams[i];
			search = search.replace(RegExp(excludeParam + "=[^$]+"), "");
		}
		if (search.length > 0)
			newLocation = newLocation + search;
	}
	location.href = newLocation;
}

function hideWidgetSection(toggleLink) {
	var headerObj = $(toggleLink.parent().get(0));
	var widgetSectionObj = $(headerObj.parent().get(0));
	var contentObj = $('.widgetSectionContent', widgetSectionObj);
	contentObj.hide();
	$('span', toggleLink).text('show');
	headerObj.removeClass('shown');
	headerObj.addClass('hidden');
}

function showWidgetSection(toggleLink) {
	var headerObj = $(toggleLink.parent().get(0));
	var widgetSectionObj = $(headerObj.parent().get(0));
	var contentObj = $('.widgetSectionContent', widgetSectionObj);
	
	if (!toggleLink.hasClass("widgetSectionToggleAll")) {
		/* Close up Everything Else */
		toggleLink.closest(".widgetSection").parent().find(".widgetSectionToggle").each( function()
		{
			var toggleLink = $(this);
			hideWidgetSection(toggleLink);
		});
	}
	
	// Show content
	contentObj.show();
	
	$('span', toggleLink).text('hide');
	headerObj.removeClass('hidden');
	headerObj.addClass('shown');
}
function recurringTransactionEvents(root) {
		
	root.find("a#deleteRecurringTransaction").click(function() {
		popConfirm(this, 'Are you sure you want to remove the recurring transaction?', 'deleteRecurring()');
	});
	
	/* Continue Delete Recurring Transaction */
	root.find("#continueDeleteRecurringTransaction").click(function(){
		$('#deleteRecurringTransactionBox .closeModalWindow').click();
		
		var pos = calcPosition(document.getElementById('deleteRecurringTransaction'));
		var curLeft = pos['left'];
		var curTop = pos['top'];

		$('body').append('<div class="modalOverlay"></div>');
		var boxObj = $('#deleteRecurringTransactionConfirmBox');
		
		boxObj.css({"left":curLeft-200, "top":curTop-220}).show();
		
		return false;
	});
	

	/* Create Recurring Transaction */
	root.find("#createRecurringTransaction").click(function()
	{
		$('#formTransactionInfo').removeClass("domster_hidden");
		$('#formTransactionInfo .form_field_static').addClass('domster_hidden')
		$('#formTransactionInfo .form_field_editable').removeClass('domster_hidden')

		$('#monthly_transfer_amount_label').hide();
		$('#day_of_month_transfer_label').hide();
		$('#monthly_transfer_amount').show();
		$('#monthly_transfer_amount').focus();
		$('#day_of_month_transfer').show();
		
		$(".edit").hide();
		$('#saveCreateRecurringTransaction').show();
		$('#cancelCreateRecurringTransaction').show();
	
		$("#formTransactionInfo input").unbind('keydown');
		$("#formTransactionInfo input,#formTransactionInfo select").keydown(
				function(e)
				{
					if(e.keyCode == 13) {
						$("#saveCreateRecurringTransaction").click();
						return false
					}
					return true;
				}
			);
		
		return false;
	});
	
	/* Change Recurring Transaction */
	root.find("#changeRecurringTransaction").click(function()
	{
		// Restore original values
		var originalFrequency = $('#originalFrequency').val();
		var originalDayOfMonth = $('#originalDayOfMonth').val();
		var originalDayOfWeek = $('#originalDayOfWeek').val();
		var originalRecurringAmount = $('#originalRecurringAmount').val();
		$('#formTransactionInfo ul.error li').addClass("domster_hidden").html("");
		if (originalFrequency == "Monthly") {
			$('#frequencyMonthly').click();
			$('#day_of_month_transfer').val(originalDayOfMonth);
		} else {
			$('#frequencyWeekly').click();
			$('#day_of_month_transfer').val(originalDayOfWeek);
		}
		$('#monthly_transfer_amount').val(originalRecurringAmount);
		$('#formTransactionInfo').removeClass("domster_hidden");
		$('#formTransactionInfo .form_field_static').addClass('domster_hidden')
		$('#formTransactionInfo .form_field_editable').removeClass('domster_hidden')
		
		$('#deleteRecurringTransaction').hide();
		$('#changeRecurringTransaction').hide();
		$('#saveChangeRecurringTransaction').show();
		$('#cancelChangeRecurringTransaction').show();
		
		$("#formTransactionInfo input").unbind('keydown');
		$("#formTransactionInfo input,#formTransactionInfo select").keydown(
			function(e)
			{
				if(e.keyCode == 13) {
					$("#saveChangeRecurringTransaction").click();
					return false;
				}
				return true
			}
		);

		// $('#changeRecurringTransactionBox .closeModalWindow').click();
		
		return false;
	});
	root.find(".frequencyRadioButtons .frequencyMonthly").click(function() {
		$(".recurringTransactionFieldset .hideIfNone").removeClass("domster_hidden");
		$(".recurringTransactionFieldset .dayOfMonth").removeClass("domster_hidden");
		$(".recurringTransactionFieldset .dayOfWeek").addClass("domster_hidden");
		$(".recurringTransactionFieldset .nextContribution").addClass("domster_hidden");
	});
	root.find(".frequencyRadioButtons .frequencyWeekly").click(function() {
		$(".recurringTransactionFieldset .hideIfNone").removeClass("domster_hidden");
		$(".recurringTransactionFieldset .dayOfMonth").addClass("domster_hidden");
		$(".recurringTransactionFieldset .dayOfWeek").removeClass("domster_hidden");
		$(".recurringTransactionFieldset .nextContribution").addClass("domster_hidden");
	});
	root.find(".frequencyRadioButtons .frequencyBiWeekly").click(function() {
		$(".recurringTransactionFieldset .hideIfNone").removeClass("domster_hidden");
		$(".recurringTransactionFieldset .dayOfMonth").addClass("domster_hidden");
		$(".recurringTransactionFieldset .dayOfWeek").removeClass("domster_hidden");
	});
	
	root.find(".frequencyRadioButtons .frequencyNone").click(function() {
		$(".recurringTransactionFieldset .hideIfNone").addClass("domster_hidden");
	});
	
	root.find("#recurringFrequencyDropDown").change(function() {
		var value = $(this).val();
		if (value == "Monthly") {
			$(".recurringTransactionFields .hideIfNone").removeClass("domster_hidden");
			$(".recurringTransactionFields .dayOfMonth").removeClass("domster_hidden");
			$(".recurringTransactionFields .dayOfWeek").addClass("domster_hidden");
			$(".recurringTransactionFields .nextContribution").addClass("domster_hidden");
		} else {
			$(".recurringTransactionFields .hideIfNone").removeClass("domster_hidden");
			$(".recurringTransactionFields .dayOfMonth").addClass("domster_hidden");
			$(".recurringTransactionFields .dayOfWeek").removeClass("domster_hidden");
			$(".recurringTransactionFields .nextContribution").addClass("domster_hidden");
		}
	});
	
	/* Save Recurring Transaction */
	root.find("#saveCreateRecurringTransaction").click(function()
	{
		submitAjaxAndReplace('formTransactionInfo', 'saveRecurring', '#edit_recurring_fields', null, null);
				
		return false;
	});
	
	function resetRecurringForm() {
		$('#formTransactionInfo .form_field_static').removeClass('domster_hidden')
		$('#formTransactionInfo .form_field_editable').addClass('domster_hidden')

		$('#cancelChangeRecurringTransaction').hide();
		
		$('#deleteRecurringTransaction').show();
		$('#changeRecurringTransaction').show();
		$('#saveChangeRecurringTransaction').hide();
		$('#cancelChangeRecurringTransaction').hide();
		$(".recurringTransactionFieldset .hideByDefault").addClass("domster_hidden");
		$(".recurringTransactionFieldset .showByDefault").removeClass("domster_hidden");
		return false;
	}
	
	/* Continue Save Recurring Transaction */
	// $("#continueSaveRecurringTransaction").click(function(){
	root.find("#saveChangeRecurringTransaction").click(function()
	{
		resetRecurringForm();
		submitAjaxAndReplace('formTransactionInfo', 'saveRecurring', '#edit_recurring_fields', null, null);
			
		return false;
	});

	/* Cancel Save Recurring Transaction */
	root.find("#cancelChangeRecurringTransaction").click(resetRecurringForm);
	/* Continue Save Recurring Transaction */
	root.find("#cancelCreateRecurringTransaction").click(function(){
		
		$('#formTransactionInfo').addClass("domster_hidden");
		$('#formTransactionInfo .form_field_static').removeClass('domster_hidden')
		$('#formTransactionInfo .form_field_editable').addClass('domster_hidden')
		$('#saveRecurringTransaction').hide();
		
		$('#cancelCreateRecurringTransaction').hide();
		$('#saveCreateRecurringTransaction').hide();
		$('#deleteRecurringTransaction').show();
		$('#changeRecurringTransaction').show();
		$(".edit").show();
		
		return false;
	});
	$(".hover").hover(
			function() {
				$(this).children(".hoverBox").show();
			},
			function() {
				$(this).children(".hoverBox").hide();
			}
	);

}

function rotateStockMarketStories() {
	// Initialize rotating stories on the front-page
	$("#stories ul").each(function() {
		var ul = $(this);
		var stories = ul.find("li");
		if (stories.length == 0) return;
		if (stories.length == 1) {
			stories.show();
			return;
		}
		var currentIndex = ul.data("currentIndex");
		var lastIndex = currentIndex;
		if (typeof(currentIndex) == 'undefined' || currentIndex == null) {
			currentIndex = 0;
			lastIndex = null;
		} else {
			currentIndex += 1;
		}
		if (currentIndex >= stories.length) currentIndex = 0;
		ul.data("currentIndex", currentIndex);
		var currentStory = $(stories.get(currentIndex));
		if (lastIndex != null) {
			$(stories.get(lastIndex)).fadeOut(500, function() {
				currentStory.fadeIn(500);
			});
		} else {
			currentStory.show();
		}
	});
	setTimeout("rotateStockMarketStories()", 5000);
}

var externalWidgetId = 0;
var externalWidgets = [];

function adjustExternalWidgetIframePosition(externalWidgetId) {
	var widget = externalWidgets[externalWidgetId];
	if (widget.is(":visible")) {
		var overlay = widget.data("externalWidgetOverlay");
		var lastOffset = widget.data("lastOffset");
		var offset = widget.offset();
		if (typeof(lastOffset) == "undefined" || lastOffset == null || offset.top != lastOffset.top || offset.left != lastOffset.left) {
			var body = $("body");
			widget.data("lastOffset", offset);
			var top = Math.round(offset.top - body.offset().top);
			var left = offset.left;
			var iframeUrl = widget.data("overlaySrc");
			iframeUrl = iframeUrl + (iframeUrl.indexOf("?") >= 0 ? "&widgetId=" : "?widgetId=") + widget.data("widgetId") + "&callbackUrl=" + encodeURIComponent(document.location) + "#top=" + Math.round(offset.top - body.offset().top) + "&left=" + Math.round(offset.left);
			overlay.attr("src", iframeUrl);
		}
	}
}

function initExternalWidgetOverlay(root) {
	root.find(".externalWidget").each(function() {
		var widget = $(this);
		var offset = widget.offset();
		var body = $("body");
		var window = $(window);
		var externalWidgetOverlay = $("<iframe class='externalWidgetOverlay' scrolling='no' allowtransparency='true' frameborder='0' width='" + window.width() + "px' height='" + window.height() + "px'></iframe>");
		var src = widget.attr("title");
		src = src.replace("[document.location]", encodeURIComponent(document.location)).replace("[document.title]", encodeURIComponent(document.title));
		widget.data("overlaySrc", src);
		widget.data("widgetId", externalWidgetId);
		widget.removeAttr("title");
		externalWidgetOverlay.attr("allowTransparency", true);
		var iframeUrl = widget.data("overlaySrc");
		iframeUrl = iframeUrl + (iframeUrl.indexOf("?") >= 0 ? "&widgetId=" : "?widgetId=") + widget.data("widgetId") + "&callbackUrl=" + encodeURIComponent(document.location) + "#top=" + Math.round(offset.top - body.offset().top) + "&left=" + Math.round(offset.left);
		externalWidgetOverlay.attr("src", iframeUrl);
		externalWidgetOverlay.data("widgetId", widget.data("widgetId"));
		body.append(externalWidgetOverlay);
		widget.data("externalWidgetOverlay", externalWidgetOverlay);
		widget.find().andSelf().mouseover(function() {
			var widget = $(this);
			adjustExternalWidgetIframePosition(widget.data("widgetId"));
			var overlay = widget.data("externalWidgetOverlay");
			overlay.css({top: "0px"});
			//if (document.location.hash.indexOf("#close") >= 0 || document.location.hash.indexOf("#did_close"))
			//	document.location.hash = "#re_opened";
		    return true;
		});
		externalWidgets[externalWidgetId] = widget;
		setInterval('adjustExternalWidgetIframePosition(' + externalWidgetId + ')', 200);
		externalWidgetId++;
	});
	
	setInterval(closeExternalWidgetOverlay, 200);
}

function closeExternalWidgetOverlay() {
	if (document.location.hash.indexOf("#close") >= 0) {
		$(".externalWidgetOverlay").css({top: "-10000px"});
		document.location.hash = "#did_close";
	}
}

function receiveMessage(event) {
	var widgetId = event.data;
	$(".externalWidgetOverlay").each(function() {
		var overlay = $(this);
		if (overlay.data("widgetId") == widgetId) {
			$(".externalWidgetOverlay").css({top: "-10000px"});
		}
	});
}

if (typeof(window.addEventListener) != 'undefined') window.addEventListener("message", receiveMessage, false);

jQuery.fn.aPosition = function() {
	thisLeft = this.offset().left;
	thisTop = this.offset().top; 
	thisParent = this.parent();
	parentLeft = thisParent.offset().left;
	parentTop = thisParent.offset().top;
	return {
	left: thisLeft-parentLeft, 
	top: thisTop-parentTop
	}
	}

var modalPopupWindowZIndex = 1000; 

/**
 * Opens a modal window with the given content.  Content can either be HTML or an id (starting with #).
 * If an id is given, the element identified by the ID is used as the content.
 * 
 * @param content
 * @param width the width of the window
 * @param height (optional) the height of the window.  Height is automatic if this is not indicated
 * @param allowsClose (optiona) indicates whether or not a close button is shown
 * @returns {Boolean}
 */
function openModalWindow(content, width, height, allowsClose) {
	if (allowsClose == null) allowsClose = false;
	var overlay = $('<div class="newModalOverlay"></div>');
    overlay.css("z-index", modalPopupWindowZIndex);
    modalPopupWindowZIndex += 1;
    $('body').append(overlay);
    if (content.indexOf("#") == 0) {
    	content = $(content).html();
    }
    var contentNode =  $("<div></div>");
    contentNode.html(content);
    var popupWindow = $('<div class="newModalWindow"></div>');
	popupWindow.data("overlay", overlay);
	if (allowsClose) {
		var closeButton = $('<a class="newCloseModalWindow" href="javascript:;"><span class="hide">Close Window</span></a>');
		closeButton.click(function() {
			closeParentModalWindow(this);
			return false;
		});
		popupWindow.append(closeButton);
	}
	popupWindow.css("z-index", modalPopupWindowZIndex);
	popupWindow.css("width", width);
	if (height) {
		popupWindow.css("height", height);
	}
	modalPopupWindowZIndex += 1;
	var popupContent = $('<div class="newPopupContent"></div>');
	popupWindow.append(popupContent);
	popupContent.append(contentNode);
	contentNode.show();
	$("body").append(popupWindow);
	popupWindow.centerInClient().show();
    return false;
}

function closeParentModalWindow(target) {
	var window = $(target).closest(".newModalWindow");
	window.hide().data("overlay").hide();
	modalPopupWindowZIndex -= 2;
}

/**
 * Adds a function to Date that populates it from an ISO8601 string (as sent by the server).
 * 
 * Courtesy of Dan at Dan's network - http://dansnetwork.com/2008/11/01/javascript-iso8601rfc3339-date-parser/
 * 
 * @param {Object} dString
 */
Date.prototype.setISO8601 = function(dString){
    var regexp = /(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))/;
    if (dString.toString().match(new RegExp(regexp))) {
        var d = dString.match(new RegExp(regexp));
        var offset = 0;
        this.setUTCDate(1);
        this.setUTCFullYear(parseInt(d[1], 10));
        this.setUTCMonth(parseInt(d[3], 10) - 1);
        this.setUTCDate(parseInt(d[5], 10));
        this.setUTCHours(parseInt(d[7], 10));
        this.setUTCMinutes(parseInt(d[9], 10));
        this.setUTCSeconds(parseInt(d[11], 10));
        if (d[12]) 
            this.setUTCMilliseconds(parseFloat(d[12]) * 1000);
        else 
            this.setUTCMilliseconds(0);
        if (d[13] != 'Z') {
            offset = (d[15] * 60) + parseInt(d[17], 10);
            offset *= ((d[14] == '-') ? -1 : 1);
            this.setTime(this.getTime() - offset * 60 * 1000);
        }
    }
    else {
        this.setTime(Date.parse(dString));
    }
    return this;
};

/**
 * Function provided for testing purposes that will click the element identified by the given id (ie only)
 * 
 * @param id
 */
function _IEclick(id) {
	document.getElementById(id).click();
}
