if (typeof(BCNTRY) == 'undefined') { BCNTRY = {}; }
if (typeof(BCNTRY.profile) == 'undefined') { BCNTRY.profile = {}; }
if (typeof(BCNTRY.profile.widget) == 'undefined') { BCNTRY.profile.widget = {}; }

BCNTRY.profile.widget.Dialog = function(el, args) { this.init(el, args); };
YAHOO.extend(BCNTRY.profile.widget.Dialog, YAHOO.widget.Dialog, {
	init: function(el, args) {
		BCNTRY.profile.widget.Dialog.superclass.init.call(this, el, args);

		this.hideEvent.subscribe(function() {
			yd.addClass(el, 'none');
		});
		this.showEvent.subscribe(function() {
			yd.removeClass(el, 'none');
		});
	}
});

BCNTRY.profile.widget.HelpPopup = function(el, args) { this.init(el, args); };
YAHOO.extend(BCNTRY.profile.widget.HelpPopup, YAHOO.widget.Overlay, {
	_coordsInContainer: function(mouse_coords, container) {
		var region = yd.getRegion(container.id);
		return this._coordsInRegion(mouse_coords, region);
	},
	_coordsInRegion: function(mouse_coords, region) {
		return (mouse_coords[1] >= region.top
			&& mouse_coords[0] >= region.left
			&& mouse_coords[1] <= region.bottom
			&& mouse_coords[0] <= region.right
		);
	},
	init: function(el, args) {
		if (typeof(args) == 'undefined') { args = {}; }
		if (typeof(args.context) == 'undefined') { args.context = [el,"tl","bl"]; }
		if (typeof(args.visible) == 'undefined') { args.visible = false; }
		if (typeof(args.constraintoviewport) == 'undefined') { args.constraintoviewport = true; }
		BCNTRY.profile.widget.HelpPopup.superclass.init.call(this, el, args);
	},
	render: function() {
		BCNTRY.profile.widget.HelpPopup.superclass.render.call(this);
		// IE6 does not handle drop shadows well.  Need to add other class
		if (YAHOO.env.ua.ie == 6) {
			yd.addClass(this.id, 'help_popup_ie6');
		}
		ye.on(this.id, 'mouseout', function(evt) {
			var mouse_coords = ye.getXY(evt);
			if ( ! this._coordsInContainer(mouse_coords, this) ) {
				this.hide();
			}
		}, this, true);
	}
});


(function(){
	// Maintains a list of passions for the user, to detect what needs to be added/removed
	BCNTRY.profile.widget.PassionDialog = function(el, args) { 
		this.init(el, args); 
		this._passionsListId = 'passions_list';
		this._passionsLIPrefix = 'passion_';
		this.resetPassionsAsDefault(); // For initialization

		this.hideEvent.subscribe(function() {
			this.refreshPassionsToInitial(); // For after they cancel
		});
	};
	YAHOO.extend(BCNTRY.profile.widget.PassionDialog, BCNTRY.profile.widget.Dialog, {
		resetPassionsAsDefault: function() {
			this._initialPassions = [];
			this.to_add = [];
			this.to_delete = [];
			var t = this;
			yd.getElementsByClassName('selected', 'li', this._passionsListId, function(el) {
				t._initialPassions.push( el.id.replace(t._passionsLIPrefix, '') );
			});
		},
		refreshPassionsToInitial: function() {
			// Make a map of ids that should be selected
			var map = {};
			var init = this._initialPassions;
			var i;
			for (i = 0; i < init.length; i++) {
				map[this._passionsLIPrefix + init[i]] = true;
			}

			var children = yd.getChildren( this._passionsListId );
			for( i = 0; i < children.length; i++ ) {
				var child = children[i];
				if (map[child.id]) {
					yd.addClass(child, 'selected');
				}
				else {
					yd.removeClass(child, 'selected');
				}
			}
		},
		addPassion: function(id, callback) {
			this._remove_from_all(id);
			this.to_add.push(id);

			this.form.add_passions.value = id;
			this.form.remove_passions.value = '';
			this._submit(callback);

			this.resetPassionsAsDefault();
			var el_id = this._passionsLIPrefix+id;
			yd.addClass(el_id, 'selected'); 
		},
		removePassion: function(id, callback) {
			this._remove_from_all(id);
			this.to_delete.push(id);

			this.form.add_passions.value = '';
			this.form.remove_passions.value = id;
			this._submit(callback);

			this.resetPassionsAsDefault();
			var el_id = this._passionsLIPrefix+id;
			yd.removeClass(el_id, 'selected'); 
		},
		isEmpty: function() {
			return (this.to_delete.length === 0
				&& this.to_add.length === 0);
		},
		_get_index: function(id, array) {
			var p = array;
			for (var i = 0; i < p.length; i++) {
				if (p[i] == id) {
					return i;
				}
			}
			return null;
		},
		_remove_from_all: function(id) {
			var i = this._get_index(id, this.to_add);
			if (i !== null) { this.to_add.splice(i,1); }
			i = this._get_index(id, this.to_delete);
			if (i !== null) { this.to_delete.splice(i,1); }
		},
		_submit: function(callback) {
			var form = this.form;
			var obj = this;
			yc.setForm(form);
			yc.asyncRequest(form.method, form.action, {
				timeout: ajax_timeout,
				success: function(o) {
					var result = eval('('+o.responseText+')');
					if (result.success) {
						obj.resetPassionsAsDefault();
						callback.success(result);
					}
					else {
						callback.error(result);
					}
				},
				failure: function(e) {
					callback.failure(e);
				}
			});
		}
	});
})();

(function() {

var original_profile_html;
function user_id() { return $('profile_user_id').value; }

// For managing a single request (to prevent multiple ajax requests at once)
var request = {
	_active: false,
	active: function() { return this._active; },
	set_active: function() { yd.addClass(document.body, 'yui-busy'); this._active = true; },
	set_inactive: function() { yd.removeClass(document.body, 'yui-busy'); this._active = false; }
};


BCNTRY.profile.ui = {
	locationDialog: null,
	passionsDialog: null,
	displayNameDialog: null,
	realNameDialog: null,
	realNameHelpPopup: null,
	top50HelpPopup: null,
	rankingsHelpPopup: null,

	_setErrorMessage: function(id, message) {
		yd.getElementsByClassName( 'error_message', 'div', id, function(el) {
			el.innerHTML = message;
		});
	},
	_hideAllDialogs: function() {
		if (this.locationDialog) { this.locationDialog.hide(); }
		if (this.passionsDialog) { this.passionsDialog.hide(); }
		if (this.displayNameDialog) { this.displayNameDialog.hide(); }
		if (this.realNameDialog) { this.realNameDialog.hide(); }
		if (this.realNamePopup) { this.realNamePopup.hide(); }
	},
	_fadeOutAndIn: function(el_id, callback) {
		var fadeOut = new YAHOO.util.Anim(el_id, { opacity: { to: 0 } }, 0.1);
		fadeOut.onComplete.subscribe(function() {
			callback();
			var fadeIn  = new YAHOO.util.Anim(el_id, { opacity: { to: 1 } }, 0.2);
			fadeIn.animate();
		});
		fadeOut.animate();
	},
	_coordsInContainer: function(mouse_coords, container) {
		var region = yd.getRegion(container.id);
		var arrow_region = yd.getRegion(container.arrow);
		return this._coordsInRegion(mouse_coords, region) ||
			this._coordsInRegion(mouse_coords, arrow_region);
	},
	_coordsInRegion: function(mouse_coords, region) {
		return (mouse_coords[1] >= region.top
			&& mouse_coords[0] >= region.left
			&& mouse_coords[1] <= region.bottom
			&& mouse_coords[0] <= region.right
		);
	},
	realNameHelpIconMouseOver: function(target) {
		if ( !this.realNameHelpPopup ) {
			this.realNameHelpPopup = new BCNTRY.profile.widget.HelpPopup('real_name_help_template');
			this.realNameHelpPopup.render();
		}
		this.realNameHelpPopup.cfg.setProperty('context', [target, 'tl', 'bl']);
		this.realNameHelpPopup.show();
	},
	realNameHelpIconMouseOut: function(evt) {
		var mouse_coords = ye.getXY(evt);
		if ( this.realNameHelpPopup && !this._coordsInContainer(mouse_coords, this.realNameHelpPopup) ) {
			this.realNameHelpPopup.hide();
		}
	},
	realNameHelpPopupMouseOut: function(evt) {
		if ( this.realNameHelpPopup ) {
			var mouse_coords = ye.getXY(evt);
			if ( ! this._coordsInContainer(mouse_coords, this.realNameHelpPopup) ) {
				this.realNameHelpPopup.hide();
			}
		}
	},
	top50HelpIconMouseOver: function(target) {
		if ( !this.top50HelpPopup ) {
			this.top50HelpPopup = new BCNTRY.profile.widget.HelpPopup('top_50_help_template');
			this.top50HelpPopup.render();
		}
		this.top50HelpPopup.cfg.setProperty('context', [target, 'tl', 'bl']);
		this.top50HelpPopup.show();
	},
	top50HelpIconMouseOut: function(evt) {
		var mouse_coords = ye.getXY(evt);
		if ( this.top50HelpPopup && !this._coordsInContainer(mouse_coords, this.top50HelpPopup) ) {
			this.top50HelpPopup.hide();
		}
	},
	top50HelpPopupMouseOut: function(evt) {
		if ( this.top50HelpPopup ) {
			var mouse_coords = ye.getXY(evt);
			if ( ! this._coordsInContainer(mouse_coords, this.top50HelpPopup) ) {
				this.top50HelpPopup.hide();
			}
		}
	},
	rankingsHelpIconMouseOver: function(target) {
		if ( !this.rankingsHelpPopup ) {
			this.rankingsHelpPopup = new BCNTRY.profile.widget.HelpPopup('rankings_help_template');
			this.rankingsHelpPopup.render();
		}
		this.rankingsHelpPopup.cfg.setProperty('context', [target, 'tl', 'bl']);
		this.rankingsHelpPopup.show();
	},
	rankingsHelpIconMouseOut: function(evt) {
		var mouse_coords = ye.getXY(evt);
		if ( this.rankingsHelpPopup && !this._coordsInContainer(mouse_coords, this.rankingsHelpPopup) ) {
			this.rankingsHelpPopup.hide();
		}
	},
	rankingsHelpPopupMouseOut: function(evt) {
		if ( this.rankingsHelpPopup ) {
			var mouse_coords = ye.getXY(evt);
			if ( ! this._coordsInContainer(mouse_coords, this.rankingsHelpPopup) ) {
				this.rankingsHelpPopup.hide();
			}
		}
	},
	editPassionOnClick: function(target)  {
		this._hideAllDialogs();
		if (!this.passionsDialog) {
			this.passionsDialog = new BCNTRY.profile.widget.PassionDialog( 'edit_passions_panel', {
				context: [target, 'tl', 'bl'],
				hideaftersubmit: false,
				width: '452px',
				constraintoviewport: true,
				close: false // TODO: Use this with our close button
			});
			this.passionsDialog.form = document.user_passions_edit_form;
			this.passionsDialog.render();
		}
		this.passionsDialog.cfg.setProperty('context', [target, 'tl', 'bl']);
		this.passionsDialog.show();
	},
	editPassionCloseOnClick: function(target)  {
		this.passionsDialog.hide();
	},
	updatePassionsText: function(passions) {
		for (var i = 0; i < passions.length; i++) {
			passions[i] = passions[i].name;
		}
		$('user_passion_list').innerHTML = passions.join(' // ');
	},
	editPassionDoneOnClick: function()  {
		this.passionsDialog.hide();
	},
	uploadPhotoOnClick: function() {
		this._hideAllDialogs();
		this._hideImageUploadButton();
		BCNTRY.profile.ui._fadeOutAndIn('profile_image', function() {
			if (!original_profile_html) {
				original_profile_html = $('profile_image').innerHTML;
			}
			var template = TrimPath.processDOMTemplate("image_upload_template", {});
			$('profile_image').innerHTML = template;
		});
	},
	uploadPhotoCancelOnClick: function() {
		var t = this;
		BCNTRY.profile.ui._fadeOutAndIn('profile_image', function() {
			$('profile_image').innerHTML = original_profile_html;
			t._showImageUploadButton();
		});
	},
	_hideImageUploadButton: function() {
		var fadeOut = new YAHOO.util.Anim('image_upload_button', { opacity: { to: 0 } }, 0.1);
		fadeOut.animate();
	},
	_showImageUploadButton: function() {
		var fadeIn = new YAHOO.util.Anim('image_upload_button', { opacity: { to: 1 } }, 0.1);
		fadeIn.animate();
	},

	uploadPhotoSubmitOnClick: function() {
		if (request.active()) { return; }

		var form = $('user_photo_upload');
		var method = form.getAttribute('method') || 'POST';
		method = method.toUpperCase();

		var url = form.getAttribute('action');
		yc.setForm(form, true);
		var t = this;

		yc.asyncRequest(method, url, {
			upload: function(o) {
				request.set_inactive();
				var result = eval('('+o.responseText+')');
				if (result.success) {
					// Pre-load image
					var img_url = result.attributes.image.url;

					var finished = false;
					var tries = 0;
					var setImage = function() {
						tries++;
						if (tries > 3) {
							if (!finished) {
								$('profile_image').innerHTML = original_profile_html;
								t._showImageUploadButton();
								alert("Error: Could not load image " + img_url);
							}
							return;
						}
						var img = new Image();
						var done = function() {
							finished = true;
							$('profile_image').innerHTML = '<img src="'+img.src+'" alt="" />';
							original_profile_html = $('profile_image').innerHTML;
							t._showImageUploadButton();
						};
						img.onload = done;
						img.oncomplete = done;
						img.onerror = setImage;
						img.onabort = setImage;
						img.src = img_url;
					};
					setImage();

					//omniture tracking
					track_profile_edit_photo();
				}
				else {
					var template = TrimPath.processDOMTemplate("image_upload_template", {});
					$('profile_image').innerHTML = template;
					t._setErrorMessage('profile_image', '<p>Upload Failed. Photo must be jpg, png, gif, or bmp and less than 5MB. Please try again.</p>');
				}
			},
			failure: function(o) {
				request.set_inactive();
				alert("Fail!");
				t._showImageUploadButton();
			}
		});
		request.set_active();
		var template = TrimPath.processDOMTemplate("image_upload_loading_template", {});
		$('upload_image').innerHTML = template;
	},
	editLocationOnClick: function(target) {
		this._hideAllDialogs();

		if (!this.locationDialog) {
			// TODO: Create a 'LocationDialog'
			this.locationDialog = new BCNTRY.profile.widget.Dialog( 'edit_location_panel', {
				width: '375px',
				context: ['user_location', 'tl', 'tl'],
				form: document.edit_location_form,
				hideaftersubmit: false,
				constraintoviewport: true,
				close: false // TODO: Get our close button to work with this
			});

			this.locationDialog.form = document.edit_location_form;
			this.locationDialog.default_bio = function() { return $('bio_content_default').value }
			this.locationDialog.default_location = function() { return $('location_content_default').value }

			this.locationDialog.showEvent.subscribe(function() {
				var bio = this.form.bio;
				var location = this.form.location;

				this.form.bio.value	  = this.form.bio.value || this.default_bio() || '';
				this.form.location.value = this.form.location.value || this.default_location();
				this.clearErrorMessages();

				// make sure dialog is above the fold
				var reg_viewport   = yd.getClientRegion();
				var reg_dialog	 = yd.getRegion(this.id);
				var reg_context	= yd.getRegion('user_location');
				var dialog_height  = reg_dialog.bottom - reg_dialog.top;
				var predict_bottom = reg_context.top + dialog_height;
				if ( predict_bottom > reg_viewport.bottom ) {
					this.cfg.setProperty('xy', [reg_context.left, reg_viewport.bottom - dialog_height]);
				}
				else {
					this.cfg.setProperty('context', ['user_location', 'tl', 'bl']);
				}
			});

			var t = this;
			this.locationDialog.clearErrorMessages = function() {
				yd.getElementsByClassName( 'error_message', 'div', this.form, function(el) {
					el.innerHTML = '';
				});
			};
			this.locationDialog.setBioErrorMessage = function(msg) {
				var el = yd.getElementsByClassName( 'error_message', 'div', this.form)[1];
				el.innerHTML = msg;
			};
			this.locationDialog.setLocationErrorMessage = function(msg) {
				var el = yd.getElementsByClassName( 'error_message', 'div', this.form)[0];
				el.innerHTML = msg;
			};

			this.locationDialog.validate = function() {
				var form = this.form;
				var error = false;
				this.clearErrorMessages();
				if (form.location.value === this.default_location()) {
					form.location.value = '';
				}
				if (form.location.value.length > 150) {
					this.setLocationErrorMessage('Location must be less than 150 characters');
					error = true;
				}
				if (form.bio.value === this.default_bio()) {
					form.bio.value = '';
				}
				if (form.bio.value.length > 7500) {
					this.setBioErrorMessage('Bio must be less than 7500 characters');
					error = true;
				}
				if (error) {
					request.set_inactive();
				}
				return !error;
			};

			this.locationDialog.hideEvent.subscribe(this.locationDialog.clearErrorMessages);

			this.locationDialog.callback = {
				success: function(res) { 
					request.set_inactive();
					var data = eval('('+res.responseText+')');
					if (data.success) {
						try {
							//omniture tracking
							var orig_loc = $('user_location').innerHTML;
							var orig_bio = '';
							yd.getElementsByClassName('bio_content', 'p', 'bio', function(el) { orig_bio = el.innerHTML; });
							if (orig_loc != data.attributes.location) {
								track_profile_edit_location();
							}
							if (orig_bio != data.attributes.bio) {
								track_profile_edit_bio();
							}

							// update ui
							$('user_location').innerHTML = data.attributes.location;
							yd.getElementsByClassName('bio_content', 'p', 'bio', function(el) { el.innerHTML = data.attributes.bio || ''; });
							t.locationDialog.hide();
						} catch(e) { alert(e.message); }
					}
					else {
						alert(data.errorMessage);
					}
				},
				failure: function() { request.set_inactive(); alert('failure'); }
			};

			var oDialog = this.locationDialog;
			var bio = this.locationDialog.form.bio;
			ye.addListener(bio, 'focus', function() {
				yd.addClass(bio, 'selected');
				if (bio.value === oDialog.default_bio()) {
					bio.value = '';
				}
			});
			var location = this.locationDialog.form.location;
			ye.addListener(location,'focus', function() {
				if (location.value === oDialog.default_location()) {
					location.value = '';
				}
			});
			this.locationDialog.render();
		}
		yd.removeClass(bio, 'selected');
		this.locationDialog.show();
	},
	editLocationCloseOnClick: function() {
		this.locationDialog.hide();
	},
	editLocationSubmitOnClick: function() {
		if (request.active()) { return; }
		request.set_active();
		if(!this.locationDialog.submit()) {
			request.set_inactive();
		}
	},
	editBrandOnClick: function() {
		alert("Edit brand button clicked");
	},
	showAllContributionsOnClick: function(el) {
		if (request.active()) { return; }
		var url = el.href;
		request.set_active();
		yc.asyncRequest('GET', url, {
			success: function(o) {
				request.set_inactive();
				$('contributions').innerHTML = o.responseText;
			},
			failure: function() {
				request.set_inactive();
				alert('Error getting all user contributions');
			}
		});
	},
	unFlagProfileOnClick: function(a_el) {
		if (request.active()) { return; }
		var url = a_el.getAttribute('href');
		var t = this;
		request.set_active();
		yc.asyncRequest('POST', url, {
			success: function(o) {
				var result = eval('('+o.responseText+')');
				if (result.success) {
					request.set_inactive();
					t.showInnerRockstar();
					yd.addClass("unflag_profile", "none");
					yd.removeClass("flag_profile", "none");
				}
				else {
					alert("Error: " + result.errorMessage);
				}
			},
			failure: function() {
				request.set_inactive();
				alert("Error removing flags");
			}
		});
	},
	showInnerRockstar: function() {
		var template = TrimPath.processDOMTemplate("inner_rockstar_template", {});
		$('inner_rockstar').innerHTML = template;
		yd.removeClass("unflag_profile", "none");
		yd.addClass('flag_profile_panel', 'none');
		yd.addClass("flag_profile", "none");
	},
	flagProfileOnClick: function() {
		this._hideAllDialogs();
		yd.removeClass('flag_profile_panel', 'none');
	},
	flagProfileCloseOnClick: function() {
		this._hideAllDialogs();
		yd.addClass('flag_profile_panel', 'none');
	},
	flagProfileSubmitOnClick: function() {
		if (request.active()) { return; }
		request.set_active();
		var form   = document.flag_profile_form;
		var url	= form.getAttribute('action');
		var method = form.getAttribute('method');

		yc.setForm(form);
		yc.asyncRequest(method, url, {
			success: function(o) {
				request.set_inactive();
				var result = eval('('+o.responseText+')');
				if (result.success) {
					var flag_msg;
					if (result.attributes.flag_description.length > 0) {
						flag_msg = 'Profile flagged as ' + result.attributes.flag_description + '.';
					}
					else {
						flag_msg = 'Profile flagged.';
					}
					var template = "<div id=\"profile_flagged\">"
						+"<h3>Good catch! Thanks for giving everyone the heads up.</h3>"
						+"<h2>"+flag_msg+"</h2>"
						+"<p><a href=\"#\" onclick=\"BCNTRY.profile.ui.showInnerRockstar(); return false;\">Click here to view.</a></p>"
						+"</div>";

					// Create the template if it doesn't exist
					if (!$('inner_rockstar_template')) {
						var t = document.createElement("textarea");
						t.setAttribute('id', 'inner_rockstar_template');
						yd.addClass(t, 'none');
						t.value = $('inner_rockstar').innerHTML;
						document.body.appendChild(t);
					}
					$('inner_rockstar').innerHTML = template;
					yd.addClass('flag_profile_panel', 'none');
					yd.addClass("flag_profile", "none");
					yd.addClass("unflag_profile", "none");
				}
				else {
					var p = document.createElement('p');
					p.appendChild( document.createTextNode(result.errorMessage) );
					document.getElementById('flag_error_message').appendChild( p );
				}
			},
			failure: function(e) {
				request.set_inactive();
				alert('Failure flagging profile');
			}
		});
	},
	editDisplayNameSaveOnClick: function() {
		if (request.active()) { return; }
		request.set_active();
		if (!this.displayNameDialog.submit()) {
			request.set_inactive();
		}
	},
	editDisplayNameCloseOnClick: function() {
		this.displayNameDialog.hide();
	},
	editDisplayNameOnClick: function(target) {
		this._hideAllDialogs();
		if (!this.displayNameDialog) {
			this.displayNameDialog = new BCNTRY.profile.widget.Dialog( 'display_name_panel', {
				context: [target, 'tl', 'bl'],
				form: document.display_name_form,
				hideaftersubmit: false,
				close: false // TODO: Get our close button to work with this
			});
			var dialog = this.displayNameDialog;

			this.displayNameDialog.form = document.display_name_form;
			this.displayNameDialog.setErrorMessage = function(msg) {
				yd.getElementsByClassName('error_message','div', this.form, function(el) {
					el.innerHTML = msg;
				});
			};
			var hideErrors = function() { this.setErrorMessage(''); };
			this.displayNameDialog.hideEvent.subscribe(hideErrors);
			this.displayNameDialog.beforeSubmitEvent.subscribe(hideErrors);
			this.displayNameDialog.callback = {
				success: function(res) { 
					request.set_inactive();
					var data = eval('('+res.responseText+')');
					if (data.success) {
						track_profile_edit_display_name();
						window.location.reload();
					}
					else {
						dialog.setErrorMessage(data.errorMessage);
					}
				},
				failure: function() { request.set_inactive(); alert('Couldn\'t set display name.'); }
			};
			this.displayNameDialog.render();
		}
		this.displayNameDialog.show();
	},
	editRealNameSaveOnClick: function() {
		if (request.active()) { return; }
		request.set_active();
		if (!this.realNameDialog.submit()) {
			request.set_inactive();
		}
	},
	editRealNameCloseOnClick: function() {
		this.realNameDialog.hide();
	},
	editRealNameOnClick: function(target) {
		this._hideAllDialogs();
		if (!this.realNameDialog) {
			this.realNameDialog = new BCNTRY.profile.widget.Dialog( 'real_name_panel', {
				context: [target, 'tl', 'bl'],
				form: document.real_name_form,
				hideaftersubmit: false,
				close: false // TODO: Get our close button to work with this
			});
			var dialog = this.realNameDialog;

			this.realNameDialog.form = document.real_name_form;
			this.realNameDialog.setErrorMessage = function(msg) {
				yd.getElementsByClassName('error_message','div', this.form, function(el) {
					el.innerHTML = msg;
				});
			};
			var hideErrors = function() { this.setErrorMessage(''); };
			this.realNameDialog.hideEvent.subscribe(hideErrors);
			this.realNameDialog.beforeSubmitEvent.subscribe(hideErrors);
			this.realNameDialog.callback = {
				success: function(res) { 
					request.set_inactive();
					var data = eval('('+res.responseText+')');
					if (data.success) {
						//TODO:Make omniture track function for this field
						//if it is wanted, like the one below that is for
						//editing display name.
						//track_profile_edit_display_name();
						track_profile_use_real_name();	
						window.location.reload();
					}
					else {
						dialog.setErrorMessage(data.errorMessage);
					}
				},
				failure: function() { request.set_inactive(); alert('Couldn\'t set real name.'); }
			};
			this.realNameDialog.render();
		}
		this.realNameDialog.show();
		$('real_name_input').focus();
	}
};


ye.onDOMReady(function() {
	// Listener for entire passions panel
	ye.addListener('passions_list', 'click', function(evt) {
		var target = ye.getTarget(evt);
		var nodeName = target.nodeName.toUpperCase();
		if (nodeName === 'LI' || nodeName === 'A') {
			var el = target;
			if (nodeName === 'A') {
				el = target.parentNode; 
			}
			var passion_id = el.id.replace('passion_','');

			var callback = {
				failure: function() { request.set_inactive(); alert("Failure"); },
				error: function(e) { request.set_inactive(); alert("Error: "+e.errorMessage); },
				success: function(o) {
					request.set_inactive();
					BCNTRY.profile.ui.updatePassionsText(o.attributes.passions);
				}
			};

			if (request.active()) { return; }
			request.set_active();
			if (yd.hasClass(el, 'selected')) {
				BCNTRY.profile.ui.passionsDialog.removePassion(passion_id, callback);
				//omniture tracking
				track_profile_edit_passions(passion_id, false);
			}
			else {
				BCNTRY.profile.ui.passionsDialog.addPassion(passion_id, callback);
				//omniture tracking
				track_profile_edit_passions(passion_id, true);
			}
		}
	});

	// Populated inline
	if (BCNTRY.profile.noBioOnLoad) {
		BCNTRY.profile.noBioOnLoad();
	}
});

})();


if (typeof(BCNTRY) == 'undefined') { BCNTRY = {}; }
if (typeof(BCNTRY.wall) == 'undefined') { BCNTRY.wall = {}; }
if (typeof(BCNTRY.wall.user_contributions) == 'undefined') { BCNTRY.wall.user_contributions = {}; }

(function() {

var
	user_contributions = BCNTRY.wall.user_contributions,	// shorthand
	FLAG_ANSWER_ID_PREFIX = 'flag_answer_',
	FLAG_QUESTION_ID_PREFIX = 'flag_question_',
	EDIT_ANSWER_ID_PREFIX = 'answer_edit_',
	EDIT_QUESTION_ID_PREFIX = 'question_edit_',
	FLAG_CPI_ID_PREFIX = 'flag_cpi_';

BCNTRY.wall.user_contributions = {

	messages: {
		cpi: {
			get: {
				ERR_UNKNOWN: 'There was an viewing flagged photo.'
			},
			flag: {
				SUCCESS: 'Good Catch! Thanks for giving everyone the heads up.',
				ERR_UNKNOWN: 'There was an error flagging the photo.',
				ERR_NO_FLAGS: 'Why\'d you flag this?',
				ERR_TOO_MANY: 'You can only flag 2 items without logging in.'
			},
			unflag: {
				SUCCESS: 'Unflagged photo successfully.',
				ERR_UNKNOWN: 'There was an error unflagging the photo.',
				ERR_TOO_MANY: 'You can only unflag 2 items without logging in.'
			},
			delete_cpi: {
				SUCCESS: 'Kapow! Your photo has been deleted.',
				ERR_UNKNOWN: 'There was an error deleting the photo.'
			}
		},
		question: {
			inactivate: {
				SUCCESS: 'Kapow! Your question has been deleted.',
				ERR_UNKNOWN: 'There was an error deleting your question.'
			}
		},
        review: {
            inactivate: {
                SUCCESS: 'Kapow! Your review has been deleted.',
                ERR_UNKNOWN: 'There was an error deleting your review.'
            }
        },
		answer: {
			inactivate: {
				SUCCESS: 'Kapow! Your answer has been deleted.',
				ERR_UNKNOWN: 'There was an error deleting your answer.'
			}
		}
	},

	edit_question_submit_onclick: function(form) {
		var q = new BCNTRY.wall.QAndA.Question({
			question_id: form.question_id.value,
			content: form.question_content.value,
			association_type: 'product',
			association: 'EDIT',
            post_type: 'user_contributions'
		});

		q.invalidAssociation.subscribe(function(e, msg) {
			q.set_error_message(form, msg);
		});
		q.invalidAssociationType.subscribe(function(e, msg) {
			q.set_error_message(form, msg);
		});
		q.invalidContent.subscribe(function() {
			q.set_error_message(form, "We didn't get your edit.  Please enter it");
		});

		var p = this;

		q.submit({
			success: function(o) {
				var container = p._getParentElement(form, 'QandA');
				q.messaging.question = 'Thanks for editing your question, ' + q.obj.user.display_name + '.';
				container.innerHTML = q.html();
				ScSubmitQandA('Q', 'edit');
			},
			failure: function(o, e) {
				if (o.status != -1) { // Ignore aborts
					var error = 'There was an error editing the question';
					if (e) {
						error += ":\n" + e.message;
					}
					ajax_error(o, error, 'edit_question_onclick');
				}
			},
			error: function(o) {
				q.set_error_message(form, o.errorMessage);
			}
		});
	},

	// Makes its way up the element heirarchy until it reaches the 'parent' element
	// of the given classname
	_getParentElement: function(el, classname) {
		while( (el = el.parentNode) ) {
			if (el.className === classname) {
				return el;
			}
		}
	},

	_getChildElement: function(el, classname) {
		var els = yd.getElementsByClassName( classname, null, el );
		if (els) { return els[0]; }
	},

	set_error_message: function(el, message) {
		if (el.className != 'error_message') {
			el = yd.getElementsByClassName('error_message', 'div', el)[0];
		}

		var s = "<p>${message}</p>".process({ message: message});
		el.innerHTML = s;
	},

    // Submits an answer once the "save" button is pressed
	answer_question_onclick: function(form) {
		var a = new BCNTRY.wall.QAndA.Answer({
			question_id: form.question_id.value,
			answer_id: form.answer_id.value,
			content: form.answer_content.value,
			association: 'EDIT',
			association_type: 'product',
            post_type: 'user_contributions'
		});
		var qanda_el = this._getParentElement(form, 'QandA');

		a.invalidQuestionID.subscribe(function(e, msg) {
			a.set_error_message(qanda_el, msg);
		});
		a.invalidContent.subscribe(function() {
			a.set_error_message(qanda_el, "Your response wasn't entered.  Please answer below.");
		});

		var p = this;
		// Render the rich text editor (if there is one)
		a.submit({
			success: function(o) {
				if (form.answer_edit) { // Editing an existing question
					a.messaging.answer = 'Thanks for improving this answer, ' + a.obj.answer.user.display_name + '.';
					a.messaging.answer_id = a.obj.answer.answer_id;
					ScSubmitQandA('A', 'edit');
				}
                a.obj.messaging = a.messaging;
				a.html();//Populate the image_el_url elements (dont use the html() method since it uses qanda_submitted_question instead of qanda_submitted_answer)
				qanda_el.innerHTML = TrimPath.processDOMTemplate("qanda_submitted_answer", a.obj);
			},
			failure: function(o, e) {
				if (o.status != -1) {
					var error = 'There was an error submitting the answer';
					if (e) {
						error += ":\n" + e.message;
					}
					ajax_error(o, error, 'answer_question_onclick');
				}
			},
			error: function(o) {
				a.set_error_message(qanda_el, o.errorMessage);
			}
		});
	},


	view_flagged_answer_onclick: function(el, answer_id) {
		var qanda_el = this._getParentElement(el, 'QandA');
		var a = new BCNTRY.wall.QAndA.Answer({
			answer_id: answer_id,
			post_type: 'user_contributions'
		});
		a.load({
			success: function(o) {
				a.obj.messaging = a.messaging;
				a.html();//Populate the image_el_url elements (dont use the html() method since it uses qanda_submitted_question instead of qanda_submitted_answer)
				qanda_el.innerHTML = TrimPath.processDOMTemplate("qanda_submitted_answer", a.obj);
			},
			failure: function(o, e) {
				var error = 'There was an error loading the answer';
				if (e) {
					error += ":\n" + e.message;
				}   
				ajax_error(o, error, 'view_flagged_answer_onclick');
			},
			error: function(o) {
				//TODO: Set an error message for the user
			}
		});
	},


	view_flagged_question_onclick: function(el, question_id) {
		var qanda_el = this._getParentElement(el, 'QandA');
		var q = new BCNTRY.wall.QAndA.Question({
			question_id: question_id,
			post_type: 'user_contributions'
		});
		q.load(function() {
			qanda_el.innerHTML = q.html();
		});
	},


	view_flagged_cpi_onclick: function(el, cpi_id) {
		var cpi = new BCNTRY.wall.CPI({
			cpi_id: cpi_id,
			post_type: 'user_contributions'
		});
		var qanda_el = this._getParentElement(el, 'QandA');
		cpi.load({
			success: function(o) {
				qanda_el.innerHTML = cpi.html();
			},
			failure: function(o, e) {
				var error = 'There was an error loading the gear photo';
				if (e) {
					error += ":\n" + e.message;
				}   
				ajax_error(o, error, 'view_flagged_cpi_onclick');
			},
			error: function(o) {
				//TODO: Set an error message for the user
			}
		});
	},

	view_flagged_review_onclick: function(el, review_id) {
		var review = new BCNTRY.wall.Review({
			review_id: review_id,
			post_type: 'user_contributions'
		});
		var review_el = this._getParentElement(el, 'review');
		review.load( function(){
			review_el.innerHTML = review.html();
		});
	},


	// Shows the "Edit Answer" dialog
	improve_answer_onclick: function(el, question_id) {
		var ans_el = this._getParentElement(el, 'answer');
		var qanda_el = this._getParentElement(el, 'QandA');
		var association = qanda_el.id;
		var content = this._getChildElement(ans_el, "answer_text").innerHTML;
		content = this._filter_qanda_html(content);

		var answer_id = ans_el.id.split('_')[1];

		var t = TrimPath.processDOMTemplate("qanda_new_answer", { 
			question_id: question_id,
			answer_id: answer_id,
			content: content,
			association: association
		});

		var id = EDIT_ANSWER_ID_PREFIX + question_id;
		var r_el = $(id);
		if ( !r_el ) {
			this._remove_dialog(ans_el);
			r_el = this._create_dialog(t);
			r_el.id = id;
			ans_el.appendChild(r_el);
		}
	},

	// Closes a "dialog" (flagging a question, answer, etc)
	// If a classname is specified, it looks up the dom tree until that class is found
	close_dialog_onclick: function(el) {
		if (el.className !== 'qanda_dialog') {
			el = this._getParentElement(el, "qanda_dialog");
		}
		el.parentNode.removeChild(el);
	},

	// Removes a QandA dialog (for whatever reason) by searching the dom tree for
	// an element with a class named 'qanda_dialog', and removing that element if found
	_remove_dialog: function(parent_el) {
		if (!parent_el) { return; }
		var dialog_el = yd.getElementsByClassName('qanda_dialog', 'div', parent_el)[0];
		if (dialog_el) {
			dialog_el.parentNode.removeChild(dialog_el);
		}
	},

	// Creates a dialog filled with the specified html, and returns a DOM element
	_create_dialog: function(html) {
		var el = document.createElement("div");
		el.className = 'qanda_dialog';
		el.innerHTML = html;
		return el;
	},

	// Filters the html that is auto-populated from the page (within the div) to be placed
	// in the textbox 
	_filter_qanda_html: function(html) {
		html = html.replace(/^[\n ]+/, '');
		html = html.replace(/[\n ]+$/, '');
		html = html.replace(/<\/?p>/ig, '');
		html = html.replace(/<br ?\/?>/gi, "\n");
		html = html.replace(/<wbr ?\/?>/gi, '');
		return html;
	},

	// Pops open the "flag_cpi" dialog
	flag_cpi_onclick: function(el, cpi_id) {
		var cpi_el = this._getParentElement(el, 'cpi');
		var t = TrimPath.processDOMTemplate("template_cpi_flag_dialog", {
			cpi_id: cpi_id
		});
		var id = FLAG_CPI_ID_PREFIX + cpi_id;
		var r_el = $(id);
		if ( !r_el ) {
			r_el = this._create_dialog(t);
			r_el.id = id;
			cpi_el.appendChild(r_el);
		}
	},

	inactivate_question_submit_onclick: function(el, question_id) {
		try{
		if (BCNTRY.wall.connection) { return }
		var q = new BCNTRY.wall.QAndA.Question({
            question_id: question_id,
            post_type: 'user_contributions'
        });
		var container = this._getParentElement(el, 'QandA');
		var t = this;
		q.inactivate({
			success: function(a) {
				q.messaging.question  = t.messages.question.inactivate.SUCCESS;
				container.innerHTML = q.html();
			},
			error: function(o) {
				t.set_error_message(container, t.messages.question.inactivate.ERR_UNKNOWN);
			},
			failure: function(o, e) {
				error = '';
				if (e) {
					error += "\n" + e.message;
				}
				ajax_error(o, error, 'inactivate_question_submit_onclick');
			}
		});
		}catch(e){alert(e.message)}
	},
	inactivate_answer_submit_onclick: function(el, question_id, answer_id) {
		try{
		if (BCNTRY.wall.connection) { return }
		var container = this._getParentElement(el, 'answer');
		var a = new BCNTRY.wall.QAndA.Answer({
            question_id: question_id,
            answer_id: answer_id,
            post_type: 'user_contributions'
        });
		var t = this;
		a.inactivate({
			success: function(o) {
				var container = t._getParentElement(el, 'QandA');
                a.obj.answer = {
                    answer_id: answer_id,
                    display: 'inactive'
                }
                a.messaging.answer	= t.messages.answer.inactivate.SUCCESS;
                a.messaging.answer_id = a.obj.answer.answer_id;

                a.obj.messaging = a.messaging;
				container.innerHTML = TrimPath.processDOMTemplate("qanda_submitted_answer", a.obj);
			},
			error: function(o) {
				t.set_error_message(container, t.messages.answer.inactivate.ERR_UNKNOWN);
			},
			failure: function(o, e) {
				error = '';
				if (e) { error += "\n" + e.message }
				ajax_error(o, error, 'inactivate_question_submit_onclick');
			}
		});
		}catch(e){alert(e.message)}
	},

    /// Inactivates a review
        inactivate_review_submit_onclick: function(el, review_id) {
                if (BCNTRY.wall.connection) { return }
                    var container = this._getParentElement(el, 'review');
                    var review = new BCNTRY.wall.Review({ review_id: review_id });
                    var t = this;
                    review.inactivate({
                        success: function(a) {
                        review.obj.message = t.messages.review.inactivate.SUCCESS;
                        container.innerHTML = TrimPath.processDOMTemplate("review_deleted_full", review.obj);
                        },
                        failure: function(o, e) {
                        var error = t.messages.review.inactivate.ERR_UNKNOWN;
                        if (e) {
                                error += ":\n" + e.message;
                               }
                        ajax_error(o, error, 'inactivate_review_submit_onclick');
                        }
                    });
       },

	// Inactivates a cpi
	inactivate_cpi_submit_onclick: function(el, cpi_id) {
		if (BCNTRY.wall.connection) { return }
		var container = this._getParentElement(el, 'cpi');
		var cpi = new BCNTRY.wall.CPI({ cpi_id: cpi_id });
		var t = this;
		cpi.inactivate({
			success: function(a) {
				cpi.obj.message = t.messages.cpi.delete_cpi.SUCCESS;
				container.innerHTML = TrimPath.processDOMTemplate("template_cpi_inactive", cpi.obj);
			},
			failure: function(o, e) {
				var error = t.messages.cpi.delete_cpi.ERR_UNKNOWN;
				if (e) {
					error += "\n" + e.message;
				}
				ajax_error(o, error, 'inactivate_cpi_onclick');
			},
			error: function(o) {
				t.set_error_message(container, t.messages.cpi.delete_cpi.ERR_UNKNOWN);
			}
		});
	},

	// Compares two html strings to see if they match
	_compare_html: function(one, two) {
		one = one.replace(/<\/?[a-zA-Z"'() ]+>/g, '');
		two = two.replace(/<\/?[a-zA-Z"'() ]+>/g, '');
		return (one === two);
	},

	// Shows the "Edit question" dialog
	edit_question_onclick: function(el, question_id) {
		var qanda_el = this._getParentElement(el, 'QandA');
		var question_el = this._getParentElement(el, 'question');
		var content;
		var association = qanda_el.id;
		
		try { // If the content has unmatched tags (shouldn't happen), chances are, this won't work
			content = this._filter_qanda_html( this._getChildElement(question_el, "question_text").innerHTML );
		}
		catch(e) {
			content = '';
		}
		var t = TrimPath.processDOMTemplate("qanda_edit_question", { 
			question_id: question_id,
			content: content ,
			association: association
		});

		var id = EDIT_QUESTION_ID_PREFIX + question_id;
		var r_el = $(id);
		if ( !r_el ) {
			// If the flag question dialog exists, remove it
			this._remove_dialog(question_el);

			r_el = this._create_dialog(t);
			r_el.id = id;
			question_el.appendChild(r_el);
		}
		var form = yd.getFirstChildBy( r_el, function(o) {  return (o.tagName.toUpperCase() === 'FORM'); });
		var output_el = this._getChildElement(form, "question_chars");
		BCNTRY.wall.user_contributions._number_question_characters(form.question_content, output_el, 1000);
	},

	question_content_onkeyup: function(form) {
		var output_el = this._getChildElement(form, "question_chars");
		BCNTRY.wall.user_contributions._number_question_characters(form.question_content, output_el, 1000);
	},

	answer_content_onkeyup: function(form) {
//		var output_el = this._getChildElement(form, "answer_chars");
//		BCNTRY.wall.user_contributions._number_question_characters(form.answer_content, output_el, 5000);
	},

	_number_question_characters: function(textarea, output_el, chars) {
		var chars_left = chars - textarea.value.length;
			
		if (chars_left <= 0) {
			textarea.value = textarea.value.substr(0, chars);
			chars_left = 0;
		}
		if (chars_left <= 100) {
			output_el.innerHTML = chars_left + (chars_left === 1 ? ' character' : ' characters') + " left";
		}
		else {
			output_el.innerHTML = "";
		}
	},

	answer_content_onfocus: function(form_el) {
		yd.addClass(form_el, 'solicit_expanded');
		if (form_el.answer_content.value === 'Write your answer here...') {
			form_el.answer_content.value = '';
		}
	},

	question_content_onfocus: function(form_el) {
		yd.addClass(form_el, 'solicit_expanded');
		if (form_el.question_content.value === BCNTRY.wall.QAndA.Question.DEFAULT_TEXT) {
			form_el.question_content.value = '';
		}
	},

	show_full_review_onclick: function(el, review_id) {
		var container = this._getParentElement(el, 'review');
		var r = new BCNTRY.wall.Review({
			review_id: review_id
		});
		var p = this;
		r.load(function() {
			container.innerHTML = r.html();
			p.add_miniprofile_listeners(container);
		});
	}
};

})();

// Initialization for posts
ye.onDOMReady(function() {

	// run function on page load finish to clean up cookies for content that
	// still needs to be posted from QandA and reviews.
	var cookie_content = _readCookie('content_to_post');

	if (cookie_content) {
		if (window.location.href.match('user')) {
			//keep cookie
			//nothing to do here for now
		}
		else {
			//server should have already processed cookie,
			//or cookie isn't needed anymore
			_deleteCookie('content_to_post', '/');
		}
	}

	var cookie_event = _readCookie('fire_event');
	if (cookie_event) {
		var result = cookie_event.split('_');
		if (result[0] == 'Q' || result[0] == 'A') {
			if (result[1] == 'new' || result[1] == 'edit') {
				ScSubmitQandA(result[0], result[1]);
			}
		}
		else if (result[0] == 'R') {
			location.hash = 'reviews';
			ScSubmitReview(result[1]);
		}
		_deleteCookie('fire_event', '/');
	}
});

