/**
* handle account pages behaviors
*/

/*--- Initialization ---*/
//initialized in calling page on domready

//Account Constructor, extend Class
var Account = Class.extend({
	init: function(type){
		//console.log("init account class");
		this.messageLibrary	= {
			'add_success':'let the good times roll! your account is ready.',
			'login_success':'let the good times roll! you\'re logged in.',
			'invalid_email':'really? that\'s your email?',
			'invalid_password':'try that password again.',
			'password_mismatch':'hmmm. your passwords don\'t match.',
			'duplicate_email':'sorry, that email address has been used.',
			'login_mismatch':'sorry, that email address and password do not match.',
			'logged_in_already':'Hmmm, I think you are already signed in to your account.',
			'email_not_found':'sorry, that email address is not associated with an account.',
			'forgot_success':'Great. Now go check your email to finish resetting your password.',
			'request_success':'Great. Now go check your email to confirm your shiny, new account.',
			'password_success':'Success! Your password has been reset.',
			'password_update_failure':'Hmmm... your password update failed.',
			'update_success':'Congrats. Your account has been updated.',
			'update_failure':'hmmm. I wasn\'t able to update your account.',
			'introduction':'You have a basic account',
			'default_collection':'enter a collection name...',
			'default_collection_description':'Enter a brief description of this collection',
			'default_collection_media':'This new collection is empty for now... but while reading letters you can add them to this collection.'
		}
		this.nodes 				= {'confirm':null,'email':null,'password':null,'message':null,'submit':null};
		this.type				= type;
		this.collections		= null;
		this.workbar			= null;
		this.container			= $('#contents');
		this.avatarFileNames	= null;
		this.avatarImgNodes		= null;
		
		switch(this.type){
			case "add":				
				this.nodes.submit 	= $('#contents #add_user');
				this.nodes.email 	= $('#contents #email');
				this.nodes.password = $('#contents #password');
				this.nodes.confirm 	= $('#contents #confirm');
				this.nodes.message 	= $('#contents .message');
				break;
			case "add-inline":
				this.nodes.submit 	= $('#dialog #add_user');
				this.nodes.email 	= $('#dialog #email');
				this.nodes.password = $('#dialog #password');
				this.nodes.confirm 	= $('#dialog #confirm');
				this.nodes.message 	= $('#dialog .message');
				break;
			case "collections":
				//note: all highly dependent on assumptions about dom tree structure.
				this.collections = {'event_handlers':{},'sorting':{}};
				var lex = this;
				
				$('#collection_library div.collection').each(function(){
						//
						lex.collections[$(this).attr('id')] = $	(this).find('input.text').val();
						//change public/private link if no media associated with collection
						if( $(this).next().children('ul').children('li.media').length == 0 ){
							$(this).children('a.toggle_display').text('private').addClass('private');
						}
					});
				this.nodes.container = $('#collection_library');
				break;
			case "forgot":
				this.nodes.submit 	= $('#contents #forgot');
				this.nodes.email 	= $('#contents #email');
				this.nodes.message 	= $('#contents .message');
				break;
			case "reset":
				this.nodes.submit 	= $('#contents #reset_password');
				this.nodes.password = $('#contents #password');
				this.nodes.confirm 	= $('#contents #confirm');
				this.nodes.message 	= $('#contents .message');
				break;
			case "login":
				this.nodes.submit 	= $('#contents #login_submit');
				this.nodes.email 	= $('#contents #email');
				this.nodes.password = $('#contents #password');
				this.nodes.message 	= $('#contents .message');
				break;
			case "update":
				this.nodes.username 	= $('#contents #user_name');
				this.nodes.firstname 	= $('#contents #first_name');
				this.nodes.lastname 	= $('#contents #last_name');
				this.nodes.email 		= $('#contents #email');
				this.nodes.status 		= $('#contents #status');
				this.nodes.description 	= $('#contents #description');
				this.nodes.interest 	= $('#contents #interest');
				this.nodes.credit 		= $('#contents #user_credit');
				this.nodes.avatar		= $('#contents #avatar');	
				this.nodes.avatar_link	= $('#contents #avatar_link');		
				
				this.nodes.message 		= $('#contents .message');
				this.nodes.submit 		= $('#contents #update_settings');
				
				//pre-fetch avatar file names
				this.avatarImgNodes	= this.createAvatarImgNodes();
				/*
				var lex = this;
				var json_url = "http://www.familytales.org/setUserIconPath_json.php";
				if( !this.avatarFileNames){
					$.getJSON(json_url, function(json){
		  				if(!json.error){
							lex.avatarFileNames = json;
							lex.avatarImgNodes	= lex.createAvatarImgNodes();
						}else{//handle server returned error
							//lex.nodes.message.addClass('error');
							//lex.nodes.message.text(lex.messageLibrary['duplicate_email']);
							console.log('error fetching avatar names');
						}
		  			});
				}
				*/
				
				//Dialog object initialization
				this.container.append("<div id='dialog'></div>");
				$('#dialog').dialog({
				    autoOpen: false,
				    bgiframe: true,
				    resizable: false,
				    height: 300,
				    width: 400,
				    modal: true,
				    overlay:
				            {
				                backgroundColor: '#000',
				                opacity: 0.5
				            }
				        ,
				    title: 'Click on an image to choose it as your avatar',
					close:this.handle_dialog_close
				});
				
				
				this.populate_page_fields();
				break;
				
			case 'workbar':
				this.workbar = {'event_handlers':{}};
				this.nodes.collections = $('#workbar li');
				FT_Globals.document_id = jQuery.url.param("id");
				break;
				
		}
		
		this.assign_behaviors();
	},
	//todo: simplify duplicate code.
	assign_behaviors: function(){
		var lex = this;
		//console.log("assign behaviors");
		switch(this.type){
			case "add":
			case "add-inline":
				this.nodes.submit.bind(
					'click' , function(){
						var error = lex.validate();
						if( !error ){
							var email 				= lex.nodes.email.val();
							var password			= lex.nodes.password.val();
							//note:premiumMediaInstance only exists on the search results page - not the add account page
							var documentLink		= (FT_Globals.premiumMediaInstance)?FT_Globals.premiumMediaInstance.documentLink:'';
							var documentLinkText	= (FT_Globals.premiumMediaInstance)?FT_Globals.premiumMediaInstance.documentLinkText:'';
							
							
							var json_url = "http://www.familytales.org/requestUserAccount_json.php?email=" + email + "&password=" + password + "&linktext=" + documentLinkText + "&link=" + documentLink ;//note - ampersanded params in link are lost
							
							$.getJSON(json_url, function(json){
					  			if(!json.error){
									lex.nodes.message.removeClass('error');
									if( lex.type == 'add' ){
										lex.nodes.message.addClass('success');
										lex.nodes.message.text(lex.messageLibrary['request_success']);
										lex.nodes.submit.attr('disabled','disabled');
									}
									
									if( lex.type == 'add-inline' ){
										lex.nodes.message.text('');
										$('#dialog').dialog('option', 'title', 'Thanks! We just sent you an email.');
										lex.nodes.submit.attr('disabled','disabled');
									}
								}else{//handle server returned error
									lex.nodes.message.addClass('error');
									lex.nodes.message.text(lex.messageLibrary['duplicate_email']);
								}
					  		});
							//return false;//to stop event bubbling and default behaviors
						}else{//handle client side error
							lex.nodes.message.addClass('error');
							lex.nodes.message.text(lex.messageLibrary[error]);
						}
					}
				);
				break;
			case "collections":
				//add UI for new collection
				$('#collection_create').bind(
					'click',function(){
						var newCollection = lex.createNewCollectionNodes();
						lex.nodes.container.prepend( newCollection );
						newCollection.find('input.text').focus();
					}
				)
								
				//set public/primary links
				//only if collection has associated media - otherwise it remains private
				
				$('#collection_library div.collection a.toggle_display').bind(
					'click', function(){
						var elem = this;
						var hasContent = $(this).parent().next().children('ul').children('li.media').length;//no content, no async call.
						var make_public = ($(this).parent().hasClass('public')) ? 0 : 1;
						var collection_id = $(this).parent().attr('id').split('_')[1];
						
						if(hasContent){
							var json_url = "http://www.familytales.org/mediaCollections_json.php?a=set_display&public=" + make_public + "&collection_id=" + collection_id;
							$.getJSON(json_url, function(json){
								if(!json.error){
									//on success toggle UI
									$(elem).parent().toggleClass('public');
									var text_str = ($(elem).text() == 'make public')?'make private':'make public';
									$(elem).text(text_str);
								}else{
									//worth showing error?
								}
							});
						}
						
					}
				);
				
				//title inline edit
				$('#collection_library div.collection a.title').bind(
					'click', function(){
						$(this).next('.edit').addClass('inline');
						$(this).addClass('edit');
					}
				);
				
				//remove media from a given collection
				$(".collection_content li a.remove").click(function(e){
					var target = $(this);
					var media_id = target.parent().attr('id');
					var collection_id = target.closest('div.collection_content').attr('id').split("_")[1];
					var json_url = "http://www.familytales.org/json/mediaToCollection_json.php?a=remove&mid=" + media_id + "&cid=" + collection_id;
					$.getJSON(json_url, function(json){
						
			  			if(!json.error){
							target.parent().fadeOut("slow");
							
						}else{//handle server returned error
							//lex.nodes.message.addClass('error');
							//lex.nodes.message.text(lex.messageLibrary[json.error]);
							console.log(json.error);
						}
					});
					
				});
				
				/*--Save event handlers for binding to multiple element nodes--*/
				//collection media toggler
				lex.collections.event_handlers['toggle_media'] = function(e){
					var target = e.target;
					var collection_content_id = "#" + $(target).parent().attr('id') + "_content";
					$(collection_content_id).slideToggle("slow");
					$(target).toggleClass('closed');
					
				}
				//set the title
				lex.collections.event_handlers['set_title'] = function(e){
					//console.log('set title');
					var target = e.target;
					var title = $(target).prev().val();
					var collection_id = $(target).parent().parent().attr('id').split('_')[1];
					var json_url = "http://www.familytales.org/mediaCollections_json.php?a=set_title&title=" + title + "&collection_id=" + collection_id;
					//console.log(json_url);
					$.getJSON(json_url, function(json){
						if(!json.error){
							$(target).parent().prev().removeClass('edit');
							$(target).parent().prev().html(title + " <span>rename</span>");
							$(target).parent().removeClass('inline');
							FT_Globals.account.collections[ $(target).parent().parent().attr('id') ] = title;//update our obj model ref
						}else{
							//show error?
						}
					});
					
				}
				//cancel title change
				lex.collections.event_handlers['cancel_title'] = function(e){
					//console.log('cancel title change');
					var target = e.target;
					var collection_id = $(target).parent().parent().attr('id');
					$(target).prevAll('input.text').val(FT_Globals.account.collections[collection_id]);//re-insert original value
					$(target).parent().prev().removeClass('edit');
					$(target).parent().removeClass('inline');
				}
				//display description edit fields
				lex.collections.event_handlers['edit_description'] = function(e){
					//console.log('toggle description edit fields');
					var target = e.target;
					$(target).parent().next('.edit').addClass('inline');
					$(target).parent().addClass('edit');
				}

				//hide description edit fields
				lex.collections.event_handlers['cancel_description'] = function(e){
					//console.log('cancel description edit fields');
					var target = e.target;
					$(target).parent().prev().removeClass('edit');
					$(target).parent().removeClass('inline');
				}
				//set the description
				lex.collections.event_handlers['set_description'] = function(e){
					//console.log('set description');
					var target = e.target;
					var desc = $(target).prev().val();
					var collection_id = $(target).parent().parent().parent().attr('id').split('_')[1];
					var json_url = "http://www.familytales.org/mediaCollections_json.php?a=set_description&description=" + desc + "&collection_id=" + collection_id;
					//console.log(json_url);
					
					$.getJSON(json_url, function(json){
						if(!json.error){
							$(target).parent().fadeOut("slow",function(){
								//console.log($(this))
								$(this).removeClass('inline');
								$(this).prev().text(desc+" ").append($("<a class='named_anchor clickable edit'>edit</a>").click(lex.collections.event_handlers['edit_description']));//update <p> value
								$(this).prev().removeClass('edit');
							});
							
						}else{
							//show error?
						}
					});
					
				}
				
				$('#collection_library a.toggle').bind(
					'click' , lex.collections.event_handlers['toggle_media']
				);

				$('#collection_library div.collection input.save').bind(
					'click', lex.collections.event_handlers['set_title']
				);
				
				$('#collection_library div.collection input.cancel').bind(
					'click.cancel', lex.collections.event_handlers['cancel_title']
				);

				$('#collection_library div.collection_content .description a.edit').bind(
					'click', lex.collections.event_handlers['edit_description']
				);	
				
				$('#collection_library div.collection_content .description input.cancel').bind(
					'click', lex.collections.event_handlers['cancel_description']
				);	
							
				$('#collection_library div.collection_content .description input.save').bind(
					'click', lex.collections.event_handlers['set_description']
				);				
							
								
				//mke collection list items to be sortable
				$('#collection_library ul').sortable({ 
					cursor: 'crosshair', 
					items: 'li',
					opacity : 0.6,
					start: function(event,ui){
						lex.collections.sorting['cid'] = $(ui.item).parents('.collection_content').attr('id').split('_')[1];
						lex.collections.sorting['item'] = $(ui.item).attr('id');
						lex.collections.sorting['orig_next'] = ($(ui.item).nextAll().length > 1) ? $(ui.item).nextAll()[1].id : '';
						//console.log("start sort - nextAll");
						//console.log($(ui.item).nextAll());
						lex.collections.sorting['orig_prev'] = ($(ui.item).prev().attr('id') == undefined)?'':$(ui.item).prev().attr('id');
					},
					stop: function(event,ui){
						//lex.collections.sorting['new_next'] = ($(ui.item).nextAll().length > 1) ? $(ui.item).nextAll()[1].id : null;
						lex.collections.sorting['new_next'] = ($(ui.item).next().attr('id') == undefined)?'last':$(ui.item).next().attr('id');
						lex.collections.sorting['new_prev'] = ($(ui.item).prev().attr('id') == undefined)?'first':$(ui.item).prev().attr('id');
						//save new positions if sortable actually moved (avoid async request that resets same information)
						if(lex.collections.sorting['orig_next'] != lex.collections.sorting['new_next'] && lex.collections.sorting['new_prev'] != lex.collections.sorting['orig_prev']){
							var json_url = "http://www.familytales.org/json/mediaToCollection_json.php?a=order&item="+lex.collections.sorting['item']+"&cid="+lex.collections.sorting['cid']+"&oa="+lex.collections.sorting['orig_prev']+"&ob="+lex.collections.sorting['orig_next']+"&na="+lex.collections.sorting['new_prev']+"&nb="+lex.collections.sorting['new_next'];
							$.getJSON(json_url, function(json){
			  					if(!json.error){
								
									}else{//handle server returned error
										console.log(json.error);
									}
							});
						}
					}
				 });
				
				break;
			case "forgot":
				this.nodes.submit.bind(
					'click' , function(){
						var error = lex.validate();
						if( !error ){
							var email 				= lex.nodes.email.val();
							var json_url = "http://www.familytales.org/forgotPassword_json.php?email=" + lex.nodes.email.val();
							$.getJSON(json_url, function(json){
								if(!json.error){
									lex.nodes.message.removeClass('error');
									lex.nodes.message.addClass('success');
									lex.nodes.message.text(lex.messageLibrary['forgot_success']);
									lex.nodes.submit.attr('disabled','disabled');
								}else{//handle server returned error
									lex.nodes.message.addClass('error');
									lex.nodes.message.text(lex.messageLibrary[json.error]);
								}
							});
							
						}else{//handle client side error
							lex.nodes.message.addClass('error');
							lex.nodes.message.text(lex.messageLibrary[error]);
						}
					}
				);
				break;
				
				case "reset":
					this.nodes.submit.bind(
						'click' , function(){
							var error = lex.validate();
							if( !error ){
								var password 	= lex.nodes.password.val();
								var cid			= jQuery.url.param("cid");
								var json_url = "http://www.familytales.org/resetPassword_json.php?password=" + password + "&cid=" + cid;
								$.getJSON(json_url, function(json){
									if(!json.error){
										lex.nodes.message.removeClass('error');
										lex.nodes.message.addClass('success');
										lex.nodes.message.text(lex.messageLibrary['password_success']);
										lex.nodes.submit.attr('disabled','disabled');
									}else{//handle server returned error
										lex.nodes.message.addClass('error');
										lex.nodes.message.text(lex.messageLibrary[json.error]);
									}
								});

							}else{//handle client side error
								lex.nodes.message.addClass('error');
								lex.nodes.message.text(lex.messageLibrary[error]);
							}
						}
					);
					break;
				
			case "login":
				this.nodes.submit.bind(
					'click' , function(){
						var error = lex.validate();
						if( !error ){
							
							var json_url = "http://www.familytales.org/loginUserAccount_json.php?email=" + lex.nodes.email.val() + "&password=" + lex.nodes.password.val();
							$.getJSON(json_url, function(json){
								
					  			if(!json.error){
									document.location.href = 'http://www.familytales.org/account/';
									lex.nodes.message.removeClass('error');
									lex.nodes.message.addClass('success');
									lex.nodes.message.text(lex.messageLibrary['login_success']);
									FT_Globals.user = json;//update client with user object
									lex.nodes.submit.attr('disabled','disabled');
								}else{//handle server returned error
									lex.nodes.message.addClass('error');
									lex.nodes.message.text(lex.messageLibrary[json.error]);
								}
							})
							
						}else{//handle client side error
							lex.nodes.message.addClass('error');
							lex.nodes.message.text(lex.messageLibrary[error]);							
						}
					}
				);
				break;
			case "update":
				this.nodes.submit.bind(
					'click' , function(){
						var json_url = "http://www.familytales.org/updateUserAccount_json.php?firstname=" + jQuery.trim(lex.nodes.firstname.val()) + "&lastname=" + jQuery.trim(lex.nodes.lastname.val()) + "&description=" + encodeURI(lex.nodes.description.val()) + "&interest=" + encodeURI(lex.nodes.interest.val());
						$.getJSON(json_url, function(json){
							
				  			if(!json.error){
								lex.nodes.message.removeClass('error');
								lex.nodes.message.addClass('success');
								lex.nodes.message.text(lex.messageLibrary['update_success']);
								FT_Globals.user = json;//update client with user object
							}else{//handle server returned error
								lex.nodes.message.addClass('error');
								lex.nodes.message.text(lex.messageLibrary[json.error]);
							}
						})
						
					}
				);
				
				this.nodes.avatar_link.bind(
					'click' , function(){
						
						if(lex.avatarImgNodes){
							$("#dialog").append(lex.avatarImgNodes);
							$('#dialog').dialog('open');
							
							//add event handler after images added to dom (in the dialog box)
							$("#avatar_container a").bind(
								'click' , function(e){
									var split_target = e.target.src.split('/');
									var file_name = split_target[ split_target.length - 1 ];
									lex.nodes.avatar.attr('src',e.target.src);//set image src on screen.
									FT_Globals.user.avatar = file_name;//update clientside user object.
								}
							);
							
						}
					}
				);
				break;
				
			case 'workbar':
			
				/*--Save event handlers for binding to multiple element nodes--*/
				//add document to collection
				this.workbar.event_handlers['add_to_collection'] = function(e){
					var target = $(e.target);
					var collection_id = target.attr('id').split('_')[1];
					var json_url = "http://www.familytales.org/json/mediaToCollection_json.php?a=add&mid=" + FT_Globals.document_id + "&cid=" + collection_id;
					$.getJSON(json_url, function(json){
		  				if(!json.error){
							target.one('click', lex.workbar.event_handlers['remove_from_collection']);
							var new_text = "X " + target.text();
							target.attr('title','remove from collection');
							target.text(new_text).addClass('added').removeClass('not_added');
						}else{//handle server returned error
							//console.log(json.error);
						}
					});
				}
				//remove document from collection
				this.workbar.event_handlers['remove_from_collection'] = function(e){
					var target = $(e.target);
					var collection_id = target.attr('id').split('_')[1];
					var json_url = "http://www.familytales.org/json/mediaToCollection_json.php?a=remove&mid=" + FT_Globals.document_id + "&cid=" + collection_id;
					$.getJSON(json_url, function(json){
		  				if(!json.error){
							target.one('click', lex.workbar.event_handlers['add_to_collection']);
							var new_text = target.text().replace(/X /,'');
							target.attr('title','add to collection');
							target.text(new_text).removeClass('added').addClass('not_added');
						}else{//handle server returned error
							//console.log(json.error);
						}
					});
				}
			
				$('#workbar li a.not_added').one('click', lex.workbar.event_handlers['add_to_collection']);
				$('#workbar li a.added').one('click', lex.workbar.event_handlers['remove_from_collection']);
				break;
		}
	},
	concat_interest_tags: function(){
		var returnStr = '';
		var delimiter = ',';
		var tags = FT_Globals.user.tags;
		for(var i =0;i< tags.length;i++){
			if(tags[i] != ''){
				returnStr += tags[i] + ((i < tags.length-1 || tags[i+1] == '') ? delimiter : '');
			}
		}
		return returnStr;
	},
	createAvatarImgNodes: function(){
		//console.log('createAvatarImgNodes');
		//console.log(this.avatarFileNames);
		var imgNodeStr = "";
		for(var i = 0;i < FT_Globals.avatars.length;i++){
			imgNodeStr += '<a class="avatar"><img src="/images/historic/avatar/' + FT_Globals.avatars[i] + '" class="user_icon"/></a>';
		}
		var imgNodeContainer = $('<div id="avatar_container"></div>').append(
			imgNodeStr
		);
		//console.log(imgNodeContainer);
		return imgNodeContainer;
	},
	
	createNewCollectionNodes: function(){
		var lex = this;
		var collectionNodes = $("<div id='' class='collection'><span class='toggle_display'>private</span><a class='toggle new'></a></div>");
		var titleStr = $("<a class='title edit'>" + lex.messageLibrary['default_collection'] + "</a>").bind(
			'click',function(){
				$(this).next('.edit').addClass('inline');
				$(this).addClass('edit');
			});
		var titleEditContainer = $("<div class='edit inline'></div>");
		var titleEditTextInput = $("<input type='text' class='text' value='" + lex.messageLibrary['default_collection'] + "'/>").bind(
			'click keydown',function(){
				if($(this).val() == lex.messageLibrary['default_collection']){
					$(this).val('');
				};
			}
			);
		var titleEditTextSave = $("<input type='button' value='save' class='save button'/>").bind(
			'click.create',function(){
				//if validated that title is not blank
				var elem = this;
				var title = $(this).prev().val();
				var description = lex.messageLibrary['default_collection_description'];
				if( title != '' && title != lex.messageLibrary['default_collection']){
					//console.log('you passed validation')
					var json_url = "http://www.familytales.org/mediaCollections_json.php?a=create&title=" + title + "&public=0&description=" + description;
					
					//todo: refactor the element node traversing below
					$.getJSON(json_url, function(json){
						if(!json.error){
							var collection_id = "collection_" + json.id;
							FT_Globals.account.collections[ collection_id ] = json.title;//update our obj model ref
							
							//create media container
							var mediaContainer = $("<div id='"+collection_id+"_content' class='collection_content'><ul class='media'><li>" + lex.messageLibrary['default_collection_media'] + "</li></ul></div>");
							//create description element nodes
							var descriptionContainer = $("<div class='description'></div>").append(
								$("<p>" + lex.messageLibrary['default_collection_description'] + " ---></p>").append(
									$("<a class='named_anchor clickable edit'>edit</a>").click(lex.collections.event_handlers['edit_description'])
								),
								$("<div class='edit'><textarea>" + lex.messageLibrary['default_collection_description'] + "</textarea></div>").append(
									$("<input type='button' class='save button' value='save changes' />").click(lex.collections.event_handlers['set_description']),
									$("<input type='button' value='cancel' class='cancel button'/>").click(lex.collections.event_handlers['cancel_description'])
								)
							);
							mediaContainer.prepend(descriptionContainer);
							/*-- update UI --*/
							$(elem).parent().parent().attr('id',collection_id);//containing collection div gets new id
							$(elem).parent().parent().after(mediaContainer);//add media container
							$(elem).parent().prev().removeClass('edit');
							$(elem).parent().prev().html(title + " <span>rename</span>");
							$(elem).parent().removeClass('inline');
							$(elem).unbind('click.create');//behavior no longer needed.
							$(elem).after("<input type='button' value='cancel' class='cancel button'/>").bind(
								'click', lex.collections.event_handlers['set_title']
								);//change to new behavior
							$(elem).next().bind( 'click', lex.collections.event_handlers['cancel_title'] );
							$(elem).parent().prevAll('a.toggle.new').removeClass('new').addClass('closed').click( lex.collections.event_handlers['toggle_media'] ).trigger('click');
							
						}else{
							//console.log("error returned: "+json.error);
						}
					});
					
					//assign the set of existing collection behaviors - rename, add description
				
				}else{
					console.log('please enter a title name');
				}
			}
			);
		//put the pieces together
		titleEditContainer.append(titleEditTextInput);
		titleEditContainer.append(titleEditTextSave);
		collectionNodes.append(titleStr);
		collectionNodes.append(titleEditContainer);
		
		return collectionNodes;
	},
	
	//save user's choice to db when they close the avatar dialog box
	handle_dialog_close: function(){
		var json_url = "http://www.familytales.org/userAvatar_json.php?action=set&file=" + FT_Globals.user.avatar;
		
		$.getJSON(json_url, function(json){
  				if(!json.error){
					//console.log('success setting avatar');
				}else{//handle server returned error
					//console.log('error setting avatar');
				}
  		});
		
	},
	
	populate_page_fields: function(){

		if(this.type == 'update'){//note: may need to turn this into a switch later.
			var avatar_path = '/images/historic/avatar/' + FT_Globals.user.avatar;
			this.nodes.avatar.attr('src',avatar_path);
			this.nodes.username.val(FT_Globals.user.username);
			this.nodes.firstname.val(FT_Globals.user.firstname);
			this.nodes.lastname.val(FT_Globals.user.lastname);
			this.nodes.email.val(FT_Globals.user.email);
			this.nodes.status.text(this.messageLibrary[FT_Globals.user.payment_status]);
			this.nodes.description.val(FT_Globals.user.description);
			this.nodes.interest.val( this.concat_interest_tags() );
			this.nodes.credit.text( Math.floor((parseFloat(FT_Globals.user.credit)*100)) );
		}
	},
	
	validate: function(){
		var error = false;
		
		if(this.nodes.email && (this.nodes.email.val() == '' || this.nodes.email.val().indexOf('@') == -1) ){
			error = 'invalid_email';
		}else if(this.nodes.password && this.nodes.password.val() == ''){
			error = 'invalid_password';
		}
		//Only for add accounts check if passwords match
		if(this.type == 'add' || this.type == 'add-inline' || this.type == 'reset'){
			if( this.nodes.password.val() != this.nodes.confirm.val() ){
				error = 'password_mismatch';
			}
		}
		
		return error;

	}
});