(function ($)
{
	var title = '';

	/* Callback function for when input in sign-up overlay has focus */
	function input_focus(input, form) {
		var errormsg = $(input).nextAll(".error:first");
		errormsg.hide();
		var instructionmsg = $(input).next('.instruction:first');
		instructionmsg.show();
	}
	
	/* $trc constants */
	$trc.PROFILE_HOST = 'http://' + $trc.HOST_PREFIX + 'profiles.realsimple.com';

	/* Omniture tracking */
	$ ('#profile_box .profile_sign_up').live ('click', function () { Profile.rsOmniReg ('header | register link'); });
	$ ('#commenting_module .profile_log_in').live ('click', function () { Profile.rsOmniReg ('comment | clicked sign-in link'); });
	$ ('#commenting_module .profile_sign_up').live ('click', function () { Profile.rsOmniReg ('comment | sign-up link'); });
	$ ('#question_detail_question .profile_log_in').live ('click', function () { Profile.rsOmniReg ('rs asks | clicked sign-in link'); });
	$ ('#question_detail_question .profile_sign_up').live ('click', function () { Profile.rsOmniReg ('rs asks | sign-up link'); });
	$ ('#profile_actions #pa_save').live ('click', function () { Profile.rsOmniReg ('save | clicked save member'); });
	$ ('.cntToolbar #rs_add_bookmark').live ('click', function () { Profile.rsOmniReg ('save | clicked save content'); });
	$ ('#profile_sign_up_box .profile_sign_up').live ('click', function () { Profile.rsOmniReg ('public profile | create your own profile link'); });

 	$ (document).ready (function ()
	{
		
		$trc.BOARD_RESOURCE_ID = $("meta[name='board_resource_id']").attr("content");

		/* Get section name for profile and commenting */
		var parsed_url = (window.location.href).replace(/^http:\/\//i, "");
		parsed_url = parsed_url.split("/");
		
		tmpStrArray = parsed_url[1].split("-");
		
		/* Captialize first letter of each word in the section name */
		for (i = 0; i < tmpStrArray.length; i++) {
			tmpStrArray[i] = tmpStrArray[i].substring(0,1).toUpperCase() + tmpStrArray[i].substring(1,tmpStrArray[i].length);
		}
		
		/* Add section name to global RS object */
		$RS.SECTION_NAME = tmpStrArray.join('-');

		/*
		 * Profile.init
		 */
		var profileJSON = {base_url: $trc.PROFILE_HOST, cookie_domain: 'realsimple.com', signup_focus_callback: input_focus}

		/* 
		 * Recently Viewed Functionality - Bookmarking
		 */
		
		var h1;
		
		/* If this is a RSA detailed question page, the grab the title from the div, not the h1 */
		if ($("#featured_rsa_q").length) {
			h1 = $("#featured_rsa_q");
		} else {
		
			/* Find the h1 that is not inside a package header.  If there is no such h1, grab the package header h1 instead.  Otherwise, grab the h1. */
			h1 = $('h1').not('#packageheader h1');
			
			if (!h1.length) {
				h1 = $('#packageheader h1');
				
				/* If there is no h1 tag anywhere on the page, grab the title tag */
				if (!h1.length) {
					h1 = $("title");
				}
			} 
		}
		
		/* 
		 * An IE bug prevents us from extracting text using jQuery .text() on an element unless that 
		 * text has another element wrapped around it.  
		 */
		title = $('<div>' + h1.html() + '</div>').text();
		
		/* If the page is a Search Results page, we need to append the search term, because the H1 does not have it */
		if (pageID == "searchPg" || pageID == "searchPgNoRslt") {
			/* If this is an All Results page, set the variable, as it normally does not have a value */
			if (s_time.prop18 == "") {
				s_time.prop18 = "All Results";
			}
			title = title + " for " + s_time.prop18;
		}
		
		var bookmark_url;
		var bookmark_resource_id = $trc.BOARD_RESOURCE_ID;
		
		/* For galleries, use a different resource id */
		if ($("meta[name='c_type']").attr("content") == "rs:gallery") {
			bookmark_resource_id = $("meta[name='bookmark_resource_id']").attr("content");
		}
		
		/* Eliminate 'http://' from the beginning and split */
		bookmark_url = $trc.NON_PREVIEW_LOCATION.slice(7).split("/");
		var last_url_element = bookmark_url[bookmark_url.length - 1];
		
		/* 
		 * Check last array element for page*.html and append index.html.
		 * Otherwise, check last array element for index*.html and don't append index.html
		 */
		if (/page.*?\.html/i.test(last_url_element) || last_url_element == '') {
			bookmark_url.pop();
			bookmark_url = "http://" + bookmark_url.join("/") + "/index.html";
		} else {
			bookmark_url = $trc.NON_PREVIEW_LOCATION;
		}
		
		if (document.getElementById ('rs_add_bookmark'))
		{
			$.extend (profileJSON, {resource_name: title, resource_url: bookmark_url, resource_content_id: bookmark_resource_id, resource_image_url: $ ('meta[name=c_image]').attr ('content'), brand_name: "RealSimple", section_name: $RS.SECTION_NAME});
		}

		/* Actual Profile.init call */
		Profile.init (profileJSON);
		
		/* Render the login box */
		Profile.render_profile_box();

		/* 
		 * Recently Viewed - Record page if not the following:
		 * 1) Endeca (Browse) pages
		 * 2) Homepage
		 * 3) Profile pages that have 'recently_viewed' meta tag
		 */
		if (!(/browse\.realsimple\.com/.test(location.host)) && (pageID != "homepage") && !($ ("meta[name='recently_viewed']").length))
		{
			Profile.recently_viewed(location.href, title);
		}
	});	

	/*
	 * Profile templates
	 */ 
	 Profile.formIsNotValidated = false;
	 Profile.termsIsUnchecked = false;
	 Profile.on_blur_errors_callback = function (jInput, formIsNotValidated)
	 {
		 if (formIsNotValidated)
		 {
			 Profile.formIsNotValidated = true;
		 }
		 else
		 {
			 Profile.formIsNotValidated = false;
		 }
		 var facebox = jInput.parents ('#facebox');
		 var form = facebox.find ('form');
		 if (jInput.attr ('id') == 'profile_password_confirmation')
		 {
			 var h5Instructions = facebox.find ('h5 .instructions');
			 var h5Errors = facebox.find ('h5 .errors');
			 var jInputVal = jInput.val ();
			 if (jInputVal != form.find ('#profile_password').val ())
			 {
				Profile.formIsNotValidated = true;
				h5Instructions.hide ();
				h5Errors.html ('The passwords entered do not match. Please try again. Already registered? <a class="profile_log_in" href="#">Sign In</a>').show ();
			 }
			 else if (jInputVal.length && !Profile.termsIsUnchecked)
			 {
				 h5Instructions.show ();
				 h5Errors.hide ();
			 }
		 }
		 if (!Profile.formIsNotValidated)
		 {
			 form.enable_submit ();
		 }
		 else
		 {
			 form.disable_submit ();
		 }
	 };
	 
	var profileOverrides = 
	{
		log_in_form_template: function ()
		{
			return '<h4>Sign In</h4><h5><span class="instructions">Not a Member? <a class="profile_sign_up" href="#">Register Now</a></span><span class="errors">We could not find the e-mail address and password combination you provided. Please try again or <a href="#" class="profile_sign_up">register</a> if you are not a member.</span></h5><form id="profile_login_form" name="profile_login_form" action="#" method="post"><ul><li><label for="email">E-mail Address:</label><input id="email" name="email" type="text" value="[remembered_email]" alt="^[A-Za-z0-9._%+-]+@[A-Za-z0-9.]+[.]{1}[A-Za-z]{2,4}$" /><span class="error">Please fill in your e-mail address.</span></li><li><label for="password">Password:</label><input id="password" name="password" type="password" alt="^[A-Za-z0-9_]{8,}$" /><span class="error">Please fill in your password.</span></li></ul><a id="co_forgot_pwd" class="profile_forgot_password" href="#">Forgot Password?</a><div id="co_confirm"><input id="remember_me" name="remember_me" value="1" type="checkbox" /><label for="remember_me">remember me on this computer</label></div><input id="co_sign_in" class="co_submit" type="image" alt="Sign In" src="http://img4.realsimple.com/static/i/community/overlay_button_sign_in.png" /></form>';
		},
	  
		sign_up_form_template: function ()
		{
			Profile.rsOmniReg ('event19');
			return '<h4>Sign Up</h4><h5 class="co_sign_up"><span class="instructions">Already a member? <a class="profile_log_in" href="#">Sign In</a></span><span class="errors"></span></h5><form id="profile_sign_up_form" name="profile_sign_up_form" class="co_sign_up" action="#" method="post"><ul><li><label for="profile_email">E-mail Address:</label><input id="profile_email" name="profile[email]" type="text" alt="^[A-Za-z0-9._%+-]+@[A-Za-z0-9.]+[.]{1}[A-Za-z]{2,4}$" /><span class="instruction">You will use this e-mail address to sign-in</span><strong class="error">The e-mail address you provided in not valid. Please check for errors and try again.</strong></li><li><label for="profile_password">Create a Password:</label><input id="profile_password" name="profile[password]" type="password" alt="^[A-Za-z0-9_]{8,}$" /><span class="instruction">Must be at least 8 characters. Case sensitive.</span><strong class="error">Please fill in your password.</strong></li><li><label for="profile_password_confirmation">Confirm Password:</label><input id="profile_password_confirmation" name="profile[password_confirmation]" type="password" alt="^[A-Za-z0-9_]{8,}$" /><span class="instruction">Please re-enter your password.</span><strong class="error">Please confirm your password.</strong></li><li><label for="profile_name">Member Name:</label><input id="profile_name" name="profile[name]" type="text" alt="^[A-Za-z0-9]{6,15}$" /><span class="instruction">Will be displayed to the community (Ex. RSFan321 or Lauren).<br />Must be 6-15 alphanumeric characters (A-Z, a-z, 0-9).</span><strong class="error">This field is required. This name must be 6-15 alphanumeric characters (A-Z, a-z, 0-9).</strong></li></ul><div id="co_confirm"> <input name="profile[terms_of_service]" type="hidden" value="0" /><input id="profile_terms_of_service" name="profile[terms_of_service]" type="checkbox" value="1" /><label for="profile_terms_of_service">I agree with the <a href="http://cgi.timeinc.net/cgi-bin/mail/dnp/terms_of_service.cgi/realsimple" target="_blank">Terms of Service</a> and <a href="http://cgi.timeinc.net/cgi-bin/mail/dnp/privacy_centralized.cgi/realsimple?dnp_source=E" target="_blank">Privacy Policy</a></label><span class="error"></span></div><input id="co_sign_up" class="co_submit" type="image" alt="Sign Up" src="http://img4.realsimple.com/static/i/community/overlay_button_sign_up.png" /></form>';
		},
		
		sign_up_success_template: function ()
		{
			Profile.rsOmniReg ('event20');
			return '<h4>Check Your E-mail</h4><h5 class="co_confirmation_instructions">In order to keep our site and our members secure we ask that you confirm your e-mail address. Here\'s how:</h5> <ul class="co_confirmation_instructions"> <li id="co_li_1"><div><strong>Check your e-mail.</strong><p>We just sent a message to your e-mail address with your new account activation link.</p></div></li> <li id="co_li_2"><div><strong>Click the link in the e-mail.</strong><p>Be sure to click on the link soon&#8212;it will expire in 14 days.</p></div></li></ul><div id="co_troubleshooting"><strong>Can\'t Find It?</strong><p>Check your junk mail folder. And be sure to add register@realsimple.com to your address book so that important notices about your account don\'t get lost.</p><strong>Still Need Help?</strong><a href="https://secure.customersvc.com/servlet/Show?WESPAGE=sm/home.html&MSRSMAG=SM">Contact us.</a></div>';
		},
	  
		sign_up_confirmation_template: function ()
        {
			Profile.rsOmniReg ('event21');
			return '<h4>Registration Complete</h4><h5 class="co_sign_up_confirmation"><span class="instructions">You may now <a class="close" href="#">return to the site</a>.</span></h5><form action="#" method="post"><span id="co_sign_up_confirmation" class="co_submit close"></span></form>';
        },
	  
		profile_prompt_template: function ()
		{
			return '<h4>Personalize Your Profile, #{name}</h4><h5 class="co_profile_prompt">Now that you\'re a member of RealSimple.com, we started a public profile for you.<br /><a href="#{profile_url}">Check out your profile</a>.</h5><div id="co_profile_prompt" class="clear"><div class="cardcol"></div><div class="txtcol"><h6>Here\'s what you can do:</h6><ul><li><a href="#{profile_url}">Keep track of your favorite article and recipes</a></li><li><a href="#{profile_url}">Get Real Simple content based on your areas of interest</a></li><li><a href="#{profile_url}">Personalize your profile with photos and information about you</a></li><li><a href="#{profile_url}">Answer Real Simple Asks questions</a></li></ul><form action="#" method="post"><a id="co_complete_my_profile" class="co_submit" href="#{profile_url}"><img src="http://img4.realsimple.com/static/i/community/overlay_complete_my_profile.png" alt="Complete my profile" /></a><div id="co_opt_out"><a id="co_no_thanks" href="#">No thanks, I\'ll build my profile later.</a><div id="co_dont_show" class="clear"><input type="checkbox" name="co_dont_show_checkbox" class="" /><span>Don\'t show this message again</span><a id="co_complete_my_profile_close" href="#"><img src="http://img4.realsimple.com/static/i/community/overlay_complete_my_profile_close.png" alt="Close" /></a></div></div></form></div></div>';
		},
	  
		forgot_password_form_template: function ()
		{
			return '<h4>Forgot Password</h4><h5 class="co_forgot_password"><span class="instructions">Enter the e-mail address associated with your account, and we\'ll e-mail you a link to reset your password.</span><span class="errors">We could not find the e-mail address you provided. Please try again or <a class="profile_sign_up" href="#">register</a> if you are not a member.</span></h5><form id="profile_forgot_password_form" name="profile_forgot_password_form" class="co_forgot_password" action="#" method="post"><ul><li><label for="email">E-mail Address:</label><input id="email" name="email" type="text" alt="^[A-Za-z0-9._%+-]+@[A-Za-z0-9.]+[.]{1}[A-Za-z]{2,4}$" /><span class="instruction"></span><strong class="error">Please fill in your e-mail address.</strong></li><li></li></ul><input id="co_submit" class="co_submit" type="image" alt="Submit" src="http://img4.realsimple.com/static/i/community/overlay_button_submit.png" /><div id="co_cancel"><a href="#" class="close">Cancel</a></div></form>';
		},
	  
		forgot_password_success_template: function ()
		{
			return '<h4>Almost Done</h4><h5 class="co_forgot_password_instructions">We just sent you a message with a link to reset your password. Click the link in the e-mail to confirm change. Be sure to click on the link soon. It will expire in 14 days.</h5><form action="#" method="post"><span id="co_forgot_password_instructions" class="co_submit close"></span></form>';
		},
	
		reset_password_form_template: function ()
		{
			return '<h4>Change Password</h4><h5 class="co_reset_password"></h5><form class="co_reset_password" action="#" method="post"><ul><li><label for="co_new_pwd">New Password:</label><input id="co_new_pwd" type="password" alt="^[A-Za-z0-9_]{8,}$" /><span class="instruction">Must be at least 8 characters. Case sensitive.</span><span class="error">Please fill in your new password.</span></li><li><label for="co_confirm_new_pwd">Confirm New Password:</label><input id="co_confirm_new_pwd" type="password" alt="^[A-Za-z0-9_]{8,}$" /><span class="instruction">Re-enter your new password.</span><span class="error">Please confirm your new password.</span></li></ul><input id="co_reset_password" class="co_submit" type="image" alt="Change Password" src="http://img4.realsimple.com/static/i/community/overlay_button_change_password.png" /><div id="co_cancel"><a href="#" class="close">Cancel</a></div></form>';
		},
	  
		logged_in_profile_box_template: function() 
		{
   			return '<div class="login_msg">Welcome Back, #{name}</div><div class="clr"></div><img src="#{photos.small}" class="rs_profile_icon" alt="Real Simple Profile Icon" /><div class="notification_msg">#{login_msg}</div><div class="clr"></div><div class="login_toolbar"><a href="#" title="My Profile" class="my_profile">My Profile</a><span class="vseparator">|</span> Not #{name}? <a href="#" title="Sign Out" class="profile_log_out">Sign Out</a></div>';
		},
		
		logged_out_profile_box_template: function ()
		{
			return '<div class="signin_msg"><span class="lbl_signin_callout">Sign In</span> Not a Member? <a href="#" class="profile_sign_up">Sign Up</a>!</div><div class="clr"></div><form name="login" id="signin" method="post" action="' + Profile.post_log_in_url() + '"><img src="http://img4.realsimple.com/static/i/community/rs_profile_sm.gif" class="rs_profile_icon" alt="Real Simple Profile Icon" /><div class="row_email"><label for="email">E-mail Address:</label> <input type="text" name="email" id="email" maxlength="50" /></div><div class="row_pw"><label for="password">Password:</label> <input type="password" name="password" id="password" maxlength="30" /></div><div class="clr"></div><input id="hdr_signin_btn" name="hdr_signin_btn" type="image" src="http://img4.realsimple.com/static/i/community/hdr_signin_btn.gif" alt="Sign in" /><a href="#" class="profile_forgot_password">Forgot your Real Simple Password?</a></form>';
		},
		
		logged_out_profile_box_template_first: function ()
		{
			return '<div class="signin_msg"><span class="lbl_signin_callout">Sign In</span> Not a Member? <a href="#" class="profile_sign_up">Sign Up</a>!</div><div class="clr"></div><form name="login" id="signin" method="post" action="#"><img src="http://img4.realsimple.com/static/i/community/rs_profile_sm.gif" class="rs_profile_icon" alt="Real Simple Profile Icon" /><div class="row_email"><label for="email">E-mail Address:</label> <input type="text" name="email" id="email" maxlength="50" /></div><div class="row_pw"><label for="password">Password:</label> <input type="password" name="password" id="password" maxlength="30" /></div><div class="clr"></div><input id="hdr_signin_btn" name="hdr_signin_btn" type="image" src="http://img4.realsimple.com/static/i/community/hdr_signin_btn.gif" alt="Sign in" /><a href="#" class="profile_forgot_password">Forgot your Real Simple Password?</a></form>';
		},
		
		followed: function (id)
		{
			$('#pa_follow').find('.unfollow').show();
			$('#pa_follow').find('.follow').hide();
			omniCommunityTracker('saveprofile');
			Profile.callProfilePrompt ();
		},

		callProfilePrompt: function (delay)
		{
			Profile.logged_in (
			{
				success: function ()
				{
					if (Profile.profile.show_profile_prompt)
					{
						$.extend (Profile.profile, { profile_url : Profile.my_profile_url () });
						if (typeof delay == 'number' && delay > 0)
						{
							var wait = setTimeout (function ()
							{
								$.facebox (Template.evaluate (Profile.profile_prompt_template (), Profile.profile));
								Profile.record_prompt_view ();
							}, delay);
						}
						else
						{
							$.facebox (Template.evaluate (Profile.profile_prompt_template (), Profile.profile));
							Profile.record_prompt_view ();
						}
					}
				}
			});
		},
		
		refresh_page: function ()
		{
			location.reload (true);
		},
		
		/* Omniture Registration */
		rsOmniReg: function (eventId)
		{
			try { omniRegTrack (eventId); }
			catch (e) { $console.log ('The attempt to track the overlay registration in Omniture failed'); }
		},
		
		/* Character limit for textareas */
		TEXTAREA_CHAR_LIMIT: 1000,

		/* Function to enforce character limits on form input and textarea elements */
		enforceCharLimit: function(options){
			/* defaults */
			var defaults = {
				selector: '',
				charLimit: 1000
			};
			
			var options = $.extend(defaults, options);
			
			var charLength;
			var textfield;
			var charLimitReached = false;
			
			$(options.selector).live("keydown", function(event){
				textfield = $(this).val();
				charLength = $(this).val().length;
				
				/* Once character limit reached, only arrow keys, backspace, and delete keys will work in the textarea */
				if (!(event.which == 46 || event.which == 8 || event.which == 37 || event.which == 38 || event.which == 39 || event.which == 40) && (charLimitReached == true)) {
					event.preventDefault();
				}
			});
			
			$(options.selector).live("keyup", function(event){
				textfield = $(this).val();
				charLength = $(this).val().length;
				
				if (charLength >= options.charLimit) {
					charLimitReached = true;
					if (charLength > options.charLimit) {
						$(this).parent().find("div.errors").text("The message is too long (maximum of 1000 characters).");
					}
				}
				else {
					charLimitReached = false;
					$(this).parent().find("div.errors").text("");
				}
			});
		},
		form_data : function (form)
		{
			var values = {};
			$ (':input',form).each (function ()
			{
				var name = $ (this).attr ('name');
				if (name) { values [name] = $ (this).val (); }
			});
			return values;
		},
		/*
		 * Override Rails method to fix failure function to work when email address is already taken
		 * Rails will implement callback functions for success and failure in in 1st Q 2010.
		 */
		init_sign_up_behaviour: function() {
		 	
	      $(".profile_sign_up").live('click', function() {
			Profile.formIsNotValidated = false;
	        $.facebox(Profile.sign_up_form_template());
			var facebox = $ ('#facebox');
	        var form = facebox.find ('form').on_blur_errors(Profile.on_blur_errors_callback).submit(function(ev) {
	          ev.preventDefault();

				form.find (':text, :password').each (function (i)
				{
					this.focus ();
					this.blur ();
				});
				
				var h5Instructions = facebox.find ('h5 .instructions');
				var h5Errors = facebox.find ('h5 .errors');
				if (!form.find ('#profile_terms_of_service').attr ('checked'))
				{
					h5Instructions.hide ();
					h5Errors.html ('You must agree to the Terms of Service and Privacy Policy. Please try again. Already registered? <a class="profile_log_in" href="#">Sign In</a>').show ();
					Profile.formIsNotValidated = Profile.termsIsUnchecked = true;
				}
				else
				{
					Profile.termsIsUnchecked = false;
				}
				if (Profile.formIsNotValidated)
				{
					return false;
				}
	          var fields = {'email': "Email address", 'name': "Name", 'password': "Password", 'password_confirmation': 'Password Confirmation', 'terms_of_service': "Terms of Service"};
	          var blank_fields = [];
	          $.each(fields, function(k,v) {
	            if ($('#profile_' + k)[0].value == '') {
	              blank_fields.push(k);
	            }
	          });
	
	          function success(data) {
	            $("#facebox .content").html(
	              Template.evaluate(Profile.sign_up_success_template(), data.profile));
	          }
	
	          function failure(data) {
				var msg = '';
	            $.each(data.errors,function()
				{			
	              if (fields[this[0]]) {
	                if(this[1].match(/^\^/)) {
	                  msg += this[1].substr(1) + ' ';
	                } else {
	                  msg += fields[this[0]] + ' ' + this[1] + '. ';
	                }
	              }
	            });
				msg += 'Already registered? <a class="profile_log_in" href="#">Sign In</a>';
	              $("#facebox").find('.instructions').hide(); 
	              $("#facebox").find('.errors').html (msg).show();
	          }
	
	          if (blank_fields.length == 0) {
	            $(this).find('.error').hide();
	            $(this).find('.instruction').show();
	
	            $.getJSON(Profile.sign_up_url(),Profile.form_data(this),function(data) {
	              if (!data.errors) success(data);
	              else failure(data);
	            });
	          } else {
	            $(this).find('.error').hide();
	            $(this).find('.instruction').hide();
	            $.each(blank_fields, function(i, k) {
	              $('#profile_' + k).parent().find('.error').show();
	            });
	          }
	        });
	        if(Profile.signup_focus_callback)
	          form.on_inputs_focus(Profile.signup_focus_callback);
	        return false;
	      });
	    }
	}	

	$.extend (Profile, profileOverrides);
	
	/* Sign in Remember Me */
	var remembered_email = decodeURIComponent ($RS.getCookie ('ti_community_user_email'));
	var log_in_form_template = Profile.log_in_form_template ().replace (/\[remembered_email\]/, remembered_email);
	Profile.log_in_form_template = function () { return log_in_form_template; };


	/*
	 * Override Rails bookmarking methods
	 */	
	var savingContentOverride = {
		bookmark_add_bookmark_already_saved_callback: function(data) {
				if(data.resource) {
					/* Wrap in Profile.logged_in() to ensure user is logged in before trying to run the rest of the bookmarking code */
					Profile.logged_in({
						success: function(){
							var contentValue = $("meta[name='c_type']").attr("content");
							var contentType = contentValue.split(":");
							/* There are only two values from the above split */
							contentType = contentType[1];
							/* Two content types have to be changed */
							if (contentType == "tv-tool") {
								contentType = "tool";
							} else if (contentType == "content-package") {
								contentType = "package";
							}
							$(".cnttb_options").before("<div class='msg_saved_to_profile'>This " + contentType + " is saved to <a href='" + Profile.view_profile_url(Profile.profile.id) + "'>your profile</a>.</div>");
							$(".profile_add_bookmark").before("<span class='savedContent'>SAVE</span>").remove();
						}
					});
			} 
		},
		bookmark_add_bookmark_success_callback: function(response, form) {
			var contentValue = $("meta[name='c_type']").attr("content");
			var contentType = contentValue.split(":");
			/* There are only two values from the above split */
			contentType = contentType[1];
			/* Two content types have to be changed */
			if (contentType == "tv-tool") {
				contentType = "tool";
			} else if (contentType == "content-package") {
				contentType = "package";
			}
			$(".cnttb_options").before("<div class='msg_saved_to_profile'>This " + contentType + " is saved to <a href='" + Profile.view_profile_url(Profile.profile.id) + "'>your profile</a>.</div>");
			$(".profile_add_bookmark").before("<span class='savedContent'>SAVE</span>").remove();
			omniCommunityTracker('contentsaved');
			Profile.callProfilePrompt ();
		},
		bookmark_add_bookmark_failure_callback: function(response, form) {
			$console.log('Error trying to add bookmark.');
		}
	}
	
	$.extend (Profile, savingContentOverride);

	/*
	 * Override of Rail's Profile.log_in()
	 * This override is needed since the sign-in overlay appears separately from the login box
	 * in the upper right of the site.  The default method assumes an embedded login box only.
	 */
	Profile.log_in = function (form, override_callbacks)
	{
		Profile.profile = undefined;
		var callbacks, originalCallbacks;
		var forwardToProfile = false;
	
		var overlayFailure = function ()
		{
			form.unbind ();
			if (!form.find ('.co_submit').length)
			{
				/* Omniture tracking */
				Profile.rsOmniReg ('header | invalid credentials entered');

				forwardToProfile = true;
				var oldForm = form;
				oldForm.submit (function (event)
				{
					form = oldForm;
					forwardToProfile = false;
					formSubmitListener (event, originalCallbacks);
				});
				$.facebox (Profile.log_in_form_template ());
				form = $ ("#facebox form");
				form.find ('#email').val (oldForm.find ('#email').val ());
			}
			Profile.show_errors (form);
			callbacks.success = function (data)
			{
				if (forwardToProfile)
				{
					Profile.profile = data.profile;
					location.href = Profile.view_profile_url (Profile.profile.id);
				}
				else
				{ 
					document.cookie = 'call_prompt=yes';
					Profile.refresh_page ();
				}
			};
			form.on_blur_errors().submit (formSubmitListener);
		};

		var formSubmitListener = function (event)
		{
			if (typeof arguments [1] == 'object') { callbacks = arguments [1]; }
			event.preventDefault ();
			
			/* Flag applies to the signin overlay, not the global sign-in box */
			var flagBlankUserAndPw = false;
			
			if (form.find ('#email').val () == '' && form.find ('#password').val () == '' && form.closest("#profile_login_form").length) {
				flagBlankUserAndPw = true;
			}
			
			if (flagBlankUserAndPw == true)
			{
				form.closest(".content").find('.errors').hide();  /* Hide any previous server-side error message */
				form.find ('.error').show ();
			}
			else
			{
				form.find ('.error').hide ();
			}
			
			/* Only perform the AJAX call if the user name and password fields are not both blank */
			if (flagBlankUserAndPw == false) {
				if (typeof callbacks.before == 'function') {
					callbacks.before();
				}
				var formData = Profile.form_data(form);
				$.getJSON(Profile.log_in_url(), formData, function(data){
					if (typeof data.errors == 'undefined' || !data.errors) {
						omniCommunityTracker('login');
						callbacks.success(data); /* All logins flow through here, so tracker can be declared once */
					}
					else {
						callbacks.failure(data);
					}
				});
			}
		};

		callbacks = 
		{
			success: function () { document.cookie = 'call_prompt=yes'; Profile.refresh_page (); },
			failure: function () { overlayFailure (); }
		}
		originalCallbacks = callbacks;
		if (typeof form == 'undefined' || !form)
		{
			$.facebox (Profile.log_in_form_template ());
			form = $ ("#facebox form");
			if (typeof override_callbacks == 'object') jQuery.extend (callbacks, override_callbacks);
		}
		form.on_blur_errors().submit (formSubmitListener);		
	};

	/*
	 * Real Simple Asks templates
	 */
	var questionOverrides = 
	{
		require_profile_answer_form_logged_out_template: function()
		{
			return '<form id="new_answer_form" method="post" action="#"><div class="rsa_qdetail_ans_box"><span><a href="#" class="profile_sign_up">Sign Up</a> Or <a href="#" class="profile_log_in">Sign In</a> To Answer This Question</span><div class="clr"></div><img src="http://img4.realsimple.com/static/i/community/rs_profile_sm.gif" width="30" height="31" alt="Real Simple Profile Icon" class="rsa_profile_icon" /><textarea id="comment_body" name="comment[body]" class="answer_to_q" rows="10" cols="70" disabled="disabled"></textarea><div class="clr"></div><div class="rsa_user_ans_tb"><input id="btn_add_answer" name="btn_add_answer" type="image" alt="Add Answer" src="http://img4.realsimple.com/static/i/community/btn_rsa_add_ans_disabled.gif" class="btn_rsa_add_ans" disabled="disabled" /> <span class="disabled_link">Cancel</span></div></div></form>';
		},
		
		require_profile_answer_form_logged_in_template: function()
		{
			return '<form id="new_answer_form" method="post" action="#"><div class="rsa_qdetail_ans_box"><div><a href="#{profile_url}">#{user_name}</a>, Answer This Question</div><div class="clr"></div><a href="#{profile_url}"><img src="#{small_photo_url}" width="30" height="31" alt="Real Simple Profile Icon" class="rsa_profile_icon" /></a><textarea id="comment_body" name="comment[body]" class="answer_to_q" rows="10" cols="70"></textarea><div class="clr"></div><div class="errors"></div><div class="rsa_user_ans_tb"><input id="btn_add_answer" name="btn_add_answer" type="image" alt="Add Answer" src="http://img4.realsimple.com/static/i/community/btn_rsa_add_ans.gif" class="btn_rsa_add_ans" /> <a href="#">Cancel</a></div></div></form>';
		},
		require_profile_answer_form_already_answered_template: function ()
		{
			return '<form id="new_answer_form" method="post" action="#"><div class="rsa_qdetail_ans_box"><div><a href="#{profile_url}">#{user_name}</a>, you already answered this question.  <a href="#{profile_url}">Visit your profile</a> to edit your answer.</div></div></form>';
		},
		/* RSA Homepage Module */
		featured_question_template: function ()
		{
			return '<div class="rsa_hp_box"><h4 class="rsa_prof_hdr"><span></span>Real Simple Asks...</h4><div id="rsa_hp_mainq">#{question_text}</div><div id="rsa_hp_ans"><div class="rsa_hp_user_box"><a href="#{profile_url}"><img src="#{profile_small_pic_url}" class="rsa_hp_user_icon" /></a></div><div class="rsa_hp_ans_box"><div class="rsa_hp_user"><a href="#{profile_url}">#{profile_user_name}</a> says:</div><div class="rsa_hp_ans_txt">#{answer_text : Format.truncate}<a href="#{question_url}"> more</a></div></div><div class="num_users_ans"><a href="#{question_url}">#{question_num_answers} Members Answered This Question</a></div></div><a href="#{question_url}" class="rsa_hp_ansq">Answer This Question</a></div>';
		},
		answer_template: function()
		{
			return '<div class="answer" id="answer_#{id}"><div class="rsa_other_user_box"><a href="#{profile_url}"><img src="#{medium_photo_url}" class="rsa_other_user_icon" /></a><span class="rsa_other_answer_author clr"><a href="#{profile_url}">#{user_name}</a></span></div><div class="rsa_other_answer_box"><div class="rsa_other_answer_txt">#{body}</div><div class="rsa_other_answer_ts">#{created_at : Format.iso_date} <a href="#{profile_url}">View Profile</a><span class="vseparator">|</span><a href="#" class="get report_inappropriate_link">Report As Inappropriate?</a></div></div></div>';
		}
		,
		/* For calling profile prompt overlay */
		init_form_behaviours: function ()
		{
			var form = $ ('#new_answer_form');
			var textarea = form.find ('textarea');
			
			form.attr('action', Question.answers_url()).disable_on_submit().post_with_iframe(
			{
				success: function(response, f)
				{
					if(response.comment)
					{
						Question.insert_answer(response.comment);
						f.attr('style','display: none');
					}
					else if(response.notice)
					{
						Question.render_message(response.notice);
					}
					Question.reset_form(f, {hide: true});
					Profile.callProfilePrompt ();
				},
				failure: function(response, f)
				{
					f.enable_submit();
					Question.render_answer_errors(response.errors, f);
				}
			});
			
			/* Non-static element - maximum character limit enforcement */
			Profile.enforceCharLimit({charLimit: Profile.TEXTAREA_CHAR_LIMIT, selector: '.rsa_qdetail_ans_box textarea'});
		}
	}
	
	$.extend (Question, questionOverrides);

		
	/* Facebox Overlay Container Template */
	$.extend ($.facebox.settings,
	{
		opacity : 0.15,
		overlay : true,
		overlayClickable : false,
		faceboxHtml : '<div id="facebox"><div id="fb_top" class="fb_horizontal"><span></span><div></div><em class="close"></em></div><div id="fb_content_bkgd"><div class="content"></div></div><div id="fb_bottom" class="fb_horizontal"><span></span><div></div></div></div>'
	});

	/* Overlay Width Fixer for IE and Modal Background Height Maximizer for All Browsers */
	$ (document).bind ('reveal.facebox', function ()
	{
		if (/MSIE/i.test (navigator.userAgent))
		{
			var facebox = $ ('#facebox');
			var h5 = facebox.find ('h5');
			var fbh5Width = h5.width ();
			if (fbh5Width != null) { facebox.width ((h5.width () + 50) + 'px'); }
			facebox.css ('left', ($ (window).width () - facebox.outerWidth ()) / 2 + 'px')

		}
		$ ('#facebox_overlay').height (Math.max ($ ('window').outerHeight (), document.body.scrollHeight, document.body.offsetHeight) + 'px');
	
		/* Bind reset password event handlers */
		var rp_form = $ ('#facebox form.co_reset_password');
		if (rp_form.length) { Profile.reset_password_form (rp_form); }
	
		/* Profile prompt overlay */
		$ ('#co_profile_prompt').parent ().find ('a[id!=co_no_thanks][id!=co_complete_my_profile_close]').click (function (event)
		{
			Profile.update_prompt_preference (false, {});
		});
		$ ('#co_no_thanks').live ('click', function ()
		{
			$ (this).hide ().next ('#co_dont_show').show ().find ('#co_complete_my_profile_close').click (function (event)
			{
				var close = $ (this);
				if (close.prevAll (':checkbox[name=co_dont_show_checkbox]').attr ('checked') == true)
				{
					Profile.update_prompt_preference (false, {});
				}
				$ (document).trigger ('close.facebox');
				event.preventDefault ();
			});
			return false;
		});
	});
	
	$ (document).ready (function ()
	{
		/* If password_action is in the url query string, behave accordingly */
		var password_action = $trc.getUrlParameter ('password_action', '', true, '#');
		var password_action_href = $RS.getCookie ('password_action_href');
		if ((password_action_href == '' || location.href != password_action_href) && (password_action == 'confirm' || password_action == 'reset'))
		{
			if (password_action == 'confirm')
			{
				$.facebox (Profile.sign_up_confirmation_template ());
			}
			else
			{
				$.facebox (Profile.reset_password_form_template ());
			}
		}
		
		$ (window).unload (function () { document.cookie = 'password_action_href=' + location.href; });
	
		/* Real Simple Asks */
		if (pageID == 'homepage')
		{
			Format.truncate_length = 80;
			Question.init ({base_url : $trc.PROFILE_HOST, brand_name : 'RealSimple'});
			Question.render_featured_question ({scope : 'brand'});
		}

		/* View All Saved - Deleting Saved Content and People */
		var vas = $ ('.view_all_saved');
		var vas_hover_template = '<div class="vas_delete"><a href="#">Delete this <vas_type> from my <save_type></a></div>';
		var vas_confirm_delete_template = '<div class="vas_confirm_delete"><strong>Are you sure you want to delete this <vas_type> from your <save_type>?</strong><span><a href="#" rel="yes">Yes, delete this <vas_type></a> | <a href="#" rel="no">No, don\'t delete this <vas_type></a> </span></div>';
		vas.each (function ()
		{
			var vas_type = 'person';
			var save_type = 'favorites';
			if (/content/i.test (this.id))
			{
				vas_type = 'content';
				save_type = 'saves';
			}
			var vasTypePattern = new RegExp ('<vas_type>', 'g');
			var savePattern = new RegExp ('<save_type>', 'g');
			vas_hover_template = vas_hover_template.replace (vasTypePattern, vas_type).replace (savePattern, save_type);
			vas_confirm_delete_template = vas_confirm_delete_template.replace (vasTypePattern, vas_type).replace (savePattern, save_type);
			var vas_lis = vas.find ('li');
			var ignoreMouseEnter = false;
			vas_lis.mouseenter (function ()
			{
				if (ignoreMouseEnter)
				{
					ignoreMouseEnter = false;
					return;
				}
				var li = $ (this);
				li.css ('background-color', '#ebffcc');
				$ (vas_hover_template).appendTo (li);
				var vas_delete = li.find ('.vas_delete');
				vas_delete.find ('a').click (function (event)
				{
					event.preventDefault ();
					var vcd = $ (vas_confirm_delete_template);
					vcd.appendTo (li);
					ignoreMouseEnter = true;
					vas_delete.remove ();
					li.css ('background-color', '#fff');
					var changeSavesCount = function ()
					{
						li.remove ();
						var span = $('.vas_head > span');
						var newCount = parseInt (span.text ().split (' ') [0]) - 1;
						span.html (newCount + ' Saves');
					};
					vcd.mouseleave (function ()
					{				
						var self = $ (this);
						self.parent ().css ('background-color', '#fff');
						self.remove ();
					});
					vcd.find ('a').click (function (event)
					{
						event.preventDefault ();
						if (this.rel == 'yes')
						{
							/* Delete the item */
							if (vas_type == 'content')
							{
								$ ('<form id="vas_delete_form" name="vas_delete_form" action="' + $trc.PROFILE_HOST + '/profile/bookmarks/' + li.attr ('id') + '.json?callback=?" method="post"><input type="hidden" name="_method" value="delete" /></form>').appendTo (li);								
								var callbacks =
								{
									success : function () { changeSavesCount (); },
									failure : function () { $console.log ('Delete failed'); vcd.remove (); }
								}
								$ ('#vas_delete_form').post_with_iframe (callbacks).submit ();
							}
							else if (vas_type = 'person')
							{
								var hrefSplit = li.find ('.vas_text a:first').attr ('href').split ('/');
								var id = hrefSplit [hrefSplit.length - 1];
                                Profile.unfollow (id, function () { changeSavesCount (); });
							}
						}
						else if (this.rel == 'no')
						{
							vcd.remove ();
						}
					});
				});
			});
			vas_lis.mouseleave (function ()
			{
				var li = $ (this);
				li.find ('.vas_delete').remove ();
				li.css ('background-color', '#fff');
			});
		});

		/*** Commenting ***/
		
		/* 
		 * Convenience JSON Object to store configuration Rails Commenting 
		 * @param {string} base_url The URL of the comments database
		 * @param {string} brand_name The title of the publication
		 * @param {string} section_name The section where the board resides.  Used for Featured Comments, where editorial can showcase a comment.  Case-sensitive.
		 * @param {string} board_resource_id The unique ID to represent the board.
		 * @param {string} board_name The name of the board. This does not need to be unique.  This is usually the name of the article.
		 * @param {string} board_url The unique URL where the board resides.
		 * @param {string} max_level Number of nesting levels.
		 */

		var commentJSON = { 
			base_url: $trc.PROFILE_HOST,
			brand_name: "RealSimple",
			board_resource_id: $trc.BOARD_RESOURCE_ID,
			board_url: $trc.NON_PREVIEW_LOCATION,
			order: "DESC",
			max_level: 2,
			section_name: $RS.SECTION_NAME
		};
		
		/* Override Commenting Templates */
		var commentingTemplateOverrides = {
			require_profile_comment_form_logged_out_template: function() {
				return '<form id="#{form_id}" action=""><div class="your_comment_form"><div><a href="#" class="profile_sign_up">Sign Up</a> Or <a href="#" class="profile_log_in">Sign In</a> To Add Your Comment</div><img src="http://img4.realsimple.com/static/i/community/rs_profile_sm.gif" width="30" height="31" alt="Real Simple Profile Icon" class="your_profile_icon" /><textarea id="comment_body" name="comment[body]" class="your_comment" rows="10" cols="70" disabled="disabled"></textarea><div class="commenting_action_bar clr"><input id="btn_add_my_comment" name="btn_add_my_comment" type="image" alt="Add My Comment" src="http://img4.realsimple.com/static/i/community/btn_add_my_comment_disabled.gif" class="btn_add_my_comment" disabled="disabled" /> <span class="disabled_link">Cancel</span></div><div class="errors"></div></div></form>';
			},
			require_profile_comment_form_logged_in_template: function() {
				return '<form id="#{form_id}" action=""><div class="your_comment_form"><div><a href="#{profile_url}">#{user_name}</a>, <span class="addCommentCaption">Add Your Comment</span></div><a href="#{profile_url}"><img src="#{small_photo_url}" width="30" height="31" alt="Real Simple Profile Icon" class="your_profile_icon" /></a><textarea id="comment_body" name="comment[body]" class="your_comment" rows="10" cols="70"></textarea><div class="commenting_action_bar clr"><input id="btn_add_my_comment" name="btn_add_my_comment" type="image" alt="Add My Comment" src="http://img4.realsimple.com/static/i/community/btn_add_my_comment.gif" class="btn_add_my_comment" /> <a href="#" class="comment_form_cancel">Cancel</a></div><div class="errors"></div></div></form>';
			},
			comment_template: function() {
				return '<li class="comment #{profile_id:FUNCTION.IsOwner}" id="comment_#{id}"><div class="user_comment clear"><div class="comment_author"><a href="#{profile_id:Profile.view_profile_url}"><img src="#{medium_photo_url}" class="comment_author_icon" height="75 width="75" alt="Real Simple Author Icon" /></a></div><div class="comment_body"><div class="comment_txt"><a href="#{profile_id:Profile.view_profile_url}">#{user_name}</a>: #{body}</div><div class="comment_ts">Posted #{created_at:Format.iso_date} <a href="#{profile_id:Profile.view_profile_url}">View Profile</a> | <a href="#" class="get report_inappropriate_link">Report as inappropriate?</a></div><div class="comment_reply_tb"><a href="#" class="get expand_replies_link #{viewable_children_count:Format.quantity_class_name}" alt="#{viewable_children_count}">Read Replies (#{viewable_children_count})</a> <a href="#" class="get add_reply_link">Add Reply</a></div><div class="comment_delete"><a href="#">Delete My Comment</a></div><span class="clr"></span></div></div><div class="form"></div><ul class="replies"></ul></li>'; 
    		},
			/* Override default init_add_reply_links to change toggle behavior */
			init_add_reply_links: function()
			{
				$("#comments a.add_reply_link").live("click", function()
				{
					var anchor = $ (this);
					if (anchor.hasClass ('get'))
					{
						var comment_id = anchor.parents(".comment").attr("id").split('_').last();
						if (anchor.parents(".comment").length < Comment.max_level) { var parent_id = comment_id; }
						else { var parent_id = $(anchor.parents(".comment")[1]).attr("id").split('_').last(); }
						reply_form = Comment.clone_form(parent_id);
						reply_form.appendTo("#comment_"+comment_id+" div.form:first");
						Comment.init_form_behaviours(comment_id);
						Comment.scroll_to(reply_form);
						anchor.removeClass("get").addClass("toggle");
					}
					else if (anchor.hasClass ('toggle'))
					{
						var formDiv = anchor.closest ('li').find ('.form');
						formDiv.toggle();
						if (formDiv.is (':visible')) { Comment.scroll_to (formDiv); }
					}
					return false;
				});				
			},

			init_expand_replies_links: function() {
			  $("#comments a.get.expand_replies_link").live("click", function() {
				var anchor = $ (this);
				var comment_id = anchor.parents(".comment").attr("id").split('_').last();
				c.render_children(comment_id);
				anchor.removeClass("get").addClass("toggle expanded");
				return false;
			  });
		
			  $("#comments a.toggle.expand_replies_link").live("click", function() {
				var comment_id = anchor.parents(".comment").attr("id").split('_').last();
				var replies = $("#comment_"+comment_id+" .replies:first");
				var anchorHTML = anchor.html ();
				if(replies.is(":visible")) {
				  replies.hide();
				  anchor.removeClass("expanded");
				  anchor.html (anchorHTML.replace (/Hide/i, 'Read'));
				  
				} else {
				  replies.show();
				  anchor.addClass("expanded");
				  anchor.html (anchorHTML.replace (/Read/i, 'Hide'));
				  c.scroll_to(replies);
				}
				return false;
			  });
			},

			init_delete_comment_links: function()
			{
				$("#comments a.delete_comment").live("click", function() {
				
				var anchor = $ (this);
				if (!anchor.closest ('.comment').find ('li').length)
				{
				var replyCountAnchor = anchor.closest ('ul#comments > li').find ('.expand_replies_link:first');
				$console.log (replyCountAnchor.length);
				var splitArray = replyCountAnchor.html ().split ('(');
				var newReplyCount = parseInt ( splitArray [1].split (')') [0]) - 1;
				replyCountAnchor.html (splitArray [0] + '(' + newReplyCount + ')');
				}										   													   
				var comment_id = anchor.closest(".comment").attr("id").split('_').last();
				$("<form/>").hide().append('<input type="hidden" name="_method" value="delete" />').appendTo($(document.body)).attr("action", Comment.comment_url(comment_id)).post_with_iframe({
				success: function(response) {
				var comment = $("#comment_"+response.comment.id);
				if(comment.siblings().size() == 0) {
				comment.parents(".comment:first").find(".expand_replies_link:first").removeClass("not_empty").addClass("empty");
				}
				comment.remove();
				}
				}).submit();
				return false;
				});
			}

		} 
		
		$.extend (Comment, commentingTemplateOverrides);


		/*** Real Simple Asks ***/
		/* 
		 * Only activate if the Real Simple Asks question form is present
		 * Requires commentJSON object
		 */

		/* Static elements */
		if ($(".owner_answer").length) {
			Profile.enforceCharLimit({charLimit: Profile.TEXTAREA_CHAR_LIMIT, selector: '.owner_answer'});	
		}
		
		if ($(".new_answer textarea").length) {
			Profile.enforceCharLimit({charLimit: Profile.TEXTAREA_CHAR_LIMITt, selector: '.new_answer textarea'});	
		} 
		
		if ($(".edit_answer textarea").length) {
			Profile.enforceCharLimit({charLimit: Profile.TEXTAREA_CHAR_LIMIT, selector: '.edit_answer textarea'});	
		}
		
		/* Rails team provided override default clone */
		Comment.clone_form = function(comment_id) {
			var reply_form = $("#new_comment_form").clone();
			reply_form.removeAttr("id");
			reply_form.append('<input type="hidden" name="comment[parent_id]" value="'+comment_id+'" />');
			reply_form.find(".addCommentCaption").text("Add Your Reply");
			Comment.reset_form(reply_form);
			return reply_form;
		};
		
		/*
		 * Not using Comment.render_comments_with_pagination() due to requirements.
		 * Using two new methods supplied by the Rails team.  These are written exclusively for Real Simple. 
		 * They do not exist in the Rails community JS library. 
		 */
		Comment.render_comments_without_pagination = function(options) {
			Url.defaults = options || {};
			$.getJSON(Comment.comments_url(), function(data) {
				Pagination.init(data.pagination);
				
				if(Pagination.total_pages == Pagination.current_page) {
						$("#view_earlier_comments").hide();
				} else {
						/* Show View Earlier Comments link when there are more pages */
						$("#view_earlier_comments").show();
						Url.set_params({page: Pagination.current_page + 1});
				}

				/* If there are no comments, hide the View View Earlier Comments link */
				if (data.comments.length == 0) {
					$("#view_earlier_comments").hide();
				}
				
				Comment.render_comments(data.comments, "#comments");
				
				/* The last parent comment does not have a horizontal line */
				$("#comments li.comment:last").addClass("lastComment");
			});
		};

		Comment.init_comments_without_pagination = function() {
			Comment.init_expand_replies_links();
			Comment.init_add_reply_links();
			Comment.init_report_inappropriate_links();
			Comment.init_delete_comment_links();
			
			$("#view_earlier_comments").click(function(event) {
				Comment.render_comments_without_pagination({
					order: commentJSON.order
				});
				event.preventDefault ();
			});
		};
		
		/* 
		 * Override default Comment.init_expand_replies_links()
		 */
		Comment.init_expand_replies_links = function() {
			$("#comments a.get.expand_replies_link").live("click", function() {
    			var comment_id = $(this).parents(".comment").attr("id").split('_').last();
    			Comment.render_children(comment_id);
    			$(this).removeClass("get").addClass("toggle expanded").text("Hide Replies (" + $(this).attr("alt") + ")");
    			return false;
  			});

	  		$("#comments a.toggle.expand_replies_link").live("click", function() {
	    		var comment_id = $(this).parents(".comment").attr("id").split('_').last();
	    		var replies = $("#comment_"+comment_id+" .replies:first");
	    		if(replies.is(":visible")) {
	      			replies.hide();
	      			$(this).removeClass("expanded").text("Read Replies ("+$("#comment_"+comment_id).find(".comment").size()+")");
	    		} else {
	      			replies.show();
	      			$(this).addClass("expanded").text("Hide Replies (" + $("#comment_"+comment_id).find(".comment").size() + ")");
	      			Comment.scroll_to(replies);
	    		}
	    		return false;
	  		});
		};
		
		/* 
		 * Override default Comment.insert_comment() to make it interoperate with the new new Comment methods
		 * Code supplied by the Rails team
		 */
		Comment.insert_comment = function (comment)
		{
			comment = Comment.convert_comment_path_to_urls (comment);
						
			if (!$('#comments').size ())
			{
				window.location = Url.new_url ({order: 'DESC'}, decodeURIComponent (Comment.board_url));
			}
			else if (comment['parent_id'] > 0)
			{
				if ($ ('#comment_' + comment.parent_id + ' .expand_replies_link:first').hasClass ('get.expand_replies_link.not_empty'))
				{
					Comment.render_children (comment.parent_id, {highlight: comment.id});
				}
				else
				{
					var replies = $ ('#comment_' + comment['parent_id'] + ' .replies:first');
					replies.append (Template.evaluate (Comment.comment_template (), comment));
					if (replies.is (':hidden'))
					{
						replies.show ();
					}
				}			
				var anchor = $ ('#comment_' + comment.parent_id + ' .expand_replies_link:first').removeClass ('get').addClass ('toggle expanded');
				anchor.html (anchor.html ().replace (/Read/i, 'Hide'));
				Comment.update_replies_count (comment.parent_id);
				omniCommunityTracker('commentsubmitted');
				Profile.callProfilePrompt ();
			}
			else
			{
				/* If user adds a new parent comment through the main comment form, refresh and jump to the comments section */
				document.cookie = 'ti_comments_hash=comments_question';
				location.href = location.href.replace (/#.*/, '');
			}
		};

		/* Only call if the page actually has comments */		
		if (document.getElementById('comments')) {
			/*
			 * Clear contents of the current comment textarea and close the reply form if it is not the topmost
			 * reply form.
			 * Attach event to all cancel links, but only the current cancel link will invoke the code.
			 * Must use jQuery live() method since form is generated through AJAX, after document.ready() is done.  
			 */
			
		 	$(".comment_form_cancel").live("click", function(event) {
				var self = $ (this);
				/* Clear the contents of the reply form */
				self.closest(".your_comment_form").find(".your_comment").val("");
				
				/* 
				 * Check which reply form was cancelled and close it.
				 * However, the topmost reply form is never closed, because it has no
				 * li.comment parent element.
				 */
				self.closest("li div.form").hide(); 
				return false;
			});
			
			$ (document).ready (function ()
			{
				Comment.init({
					base_url: commentJSON.base_url,
					brand_name: commentJSON.brand_name,
					section_name: commentJSON.section_name,
					board_resource_id: commentJSON.board_resource_id,
					board_name: title,
					board_url: commentJSON.board_url,
					max_level: commentJSON.max_level
				});
				
				/* 
				 * Initialize comments and run render once.
				 * Subsequent renders will be called through anchor tag
				 */
				Comment.init_comments_without_pagination();
				Comment.render_comments_without_pagination({
					order: commentJSON.order
				});
				
				Profile.enforceCharLimit({charLimit: Profile.TEXTAREA_CHAR_LIMIT, selector: '.your_comment'});
			});
		}
		
		/* Commenting Deletion */
		var setDeleteProcess = function (selector, liSelector, isTopLevel)
		{
			var vas = $ (selector);
			var vas_delete_template = '<div class="vas_delete"><a href="#">Delete My Comment</a></div>';
			var vas_confirm_delete_template = '<div class="vas_confirm_delete"><strong>Are you sure you want to delete this comment?</strong><span><a class="delete_comment" href="#" rel="yes">Yes, Delete This Comment</a> | <a href="#" rel="no">No, Don\'t Delete This Comment</a></span></div>';
			var isContained = function (li, event)
			{
				var target = event.target;
				li.find ('*').each (function ()
				{
					if (this == target)
					{
						return true;
					}
				});
				return false;
			}
			var vas_delete_a = $ (liSelector + ' > div > div > .comment_delete a');
			vas_delete_a.live ('click', function (event)
			{
				var li = $ (this).parents ('li.comment:first');
				var vcd = $ (vas_confirm_delete_template);
				vcd.prependTo (li);
				vcd.height ((li.find ('.comment_body:first').outerHeight (true) - (isTopLevel ? 27 : 23) + 'px'));
				li.css ('background-color', '#fff');
				vcd.find ('a[rel=no]').click (function (event)
				{
					vcd.remove ();
					event.preventDefault ();
				});
				vcd.mouseleave (function ()
				{				
					var self = $ (this);
					self.parent ().css ('background-color', '#fff');
					self.remove ();
				});
				return false;
			});

			vas.each (function ()
			{
				var vas_lis = $ (liSelector);
				vas_lis.live ('mouseover', function (event)
				{
					var li = $ (this);
					li.parents ('#comments > li.comment').css ('background-color', '#fff').find ('.comment_delete:first a').hide ();
					li.find ('.comment_delete:first a').show ();
					if (li.hasClass ('owner'))
					{
						li.css ('background-color', '#ebffcc');
					}
					return false;
				});
				vas_lis.live ('mouseout', function (event)
				{					
					var li = $ (this);
					if (isContained (li, event))
					{
						return false;
					}
					li.find ('.comment_delete:first a').hide ();
					li.css ('background-color', '#fff');
					return false;
				});
			});
		};

		/* If user is logged in, Profile.profile exists */
		$ (document).ready (function ()
		{
			/* Cannot use if (Profile.profile) to test for presence of Profile object */
			Profile.logged_in (
			{
				success: function ()
				{
					/* 
					 * If user adds a new parent comment through the main comment form, look for the cookie for the comments hash. 
					 * If present, jump to comments section 
					 */
					var hash = $RS.getCookie ('ti_comments_hash');
					if (hash == 'comments_question')
					{
						location.href = location.href.replace (/#.*/, '') + '#' + hash;
						document.cookie = 'ti_comments_hash=empty';
						omniCommunityTracker('commentsubmitted');
						Profile.callProfilePrompt ();
					}
					
					/* If true, callProfilePrompt () */
					var callPrompt = $RS.getCookie ('call_prompt');
					if (callPrompt == 'yes')
					{
						document.cookie = 'call_prompt=no';
						Profile.callProfilePrompt ();
					}
					
					/* Disable profile prompt overlay if the user visits the edit profile page */
					var profileEditPattern = new RegExp ('profiles.realsimple.com/profile', 'i');
					if (profileEditPattern.test (location.href))
					{
						Profile.update_prompt_preference (false, {});
						return;
					}	
					
					/* Apply comments deletion behavior */
					setDeleteProcess ('#comments', '#comments > li', true);
					setDeleteProcess ('#comments > li', '#comments > li li', false);

				}
			});
		});

		/* 
		 * Function to test if the comment belongs to the current user; 
		 * Code designed by Rails, but implemented by FEDS 
		 */
		window.FUNCTION =
		{
			IsOwner : function (id)
			{
				try
				{
					if (id == Profile.profile.id)
					{
						return 'owner';
					}
					return '';
				}
				catch (error)
				{
					return '';
				}
			}
		};
	});

	/* 
	 * This is a Firefox 3.0.x fix only - RECO344,RECO390,RSG67
	 * Remove after Firefox 3.0.x market share has become insignificant
	 */	
	$(document).ready(function() {
		var regexPattern = /Firefox\/3[.]0[.]{0,1}\d+/;

		function wordWrapFF30(jQueryObjArg) {
			var anchor = jQueryObjArg;
			var anchorText = anchor.text();
			var anchorArray = anchorText.split('');
			var resultArray = new Array();
			
			var counter = 0;
			for (var i=0, l = anchorArray.length; i < l ; i++) {
				if (counter % 5 == 0) {
					resultArray[counter] = '&#8203;' + anchorArray[i];						
				} else {
					resultArray[counter] = anchorArray[i];
				}
				counter++;	
			}
			
			anchor.html(resultArray.join(''));
		}
		
		/*
		 * Read the anchor text in the Favorite People module and inject zero-width space
		 * to force word wrap
		 */
		if ((pageID == "profile") && ($("meta[name=recently_viewed]").length) && (regexPattern.test(navigator.userAgent) == true)) {
			$(".fav_ppl_list li div a").each(function(){
				wordWrapFF30($(this));
			});
		}
		
		/*
		 * Read the username in the anchor text in the Real Simple Asks detail page and inject zero-width space
		 * to force word wrap
		 */
		if (($(".featured_rsa_user a").length) && (regexPattern.test(navigator.userAgent) == true)) {
			$(".featured_rsa_user a").each(function(){
				wordWrapFF30($(this));
			});
		}
		
		if (($(".rsa_other_answer_author a").length) && (regexPattern.test(navigator.userAgent) == true)) {
			$(".rsa_other_answer_author a").each(function(){
				wordWrapFF30($(this));
			});
		}
	});
}) (jQuery);
