WHUFFIE = {
	utils: {
		html_decode : function(value){
			return $('<div/>').html(value).text(); 
		}
	},

	profile : {
		topic_list_url : '/topic-list',
		bio_url: '',
		current_topic : '',
		current_topic_code : '',
		current_statement: '',



		init : function(topic_list_url, bio_url, ajax_url){
			// Setup event handlers for edit bio submit buttons and save urls

			this.topic_list_url = topic_list_url;
			this.bio_url = bio_url;
			this.ajax_url = ajax_url;

			$('#edit_statement button').click(WHUFFIE.profile.post_bio_factory(function(){
				bio = $('#edit_statement textarea').val();
				WHUFFIE.profile.bio[WHUFFIE.profile.current_topic_code][0] = bio;
				WHUFFIE.profile.load_topic(WHUFFIE.profile.current_topic_code);
			}));


			$('#edit_bio button').click(WHUFFIE.profile.post_bio_factory(function(){
				bio = $('#edit_bio textarea').val();
				$('div.bio').text(bio);
			}));
		},

		load_topic: function(topic){
			$(".statement").html('');

			// Save off the current statement/topic so the edit boxes will work correctly (if applicable)
			this.current_statement = this.bio[topic][0];
			this.current_topic = this.bio[topic][1];
			this.current_topic_code = topic

			$('.side_nav li').removeClass('selected');
			$('#ri-' + topic).addClass('selected');

			// Generate the personal statement
			var html =
				"<h1>" + this.bio[topic][1] + "</h1>" +
				"<div class='avatar'>" +
					"<img src='" + this.profile_thumb + "' alt='" + this.profile_full_name + " Thumb'>" +
				"</div>" +
				"<div class='box'>" +
					"<div class='point'></div>" +
					"<div class='cell statement_box'>" +
						"<strong>" + this.profile_full_name + "'s personal statement for this topic:</strong>";
			if (WHUFFIE.profile.self){
						html +=	" <a onclick='WHUFFIE.profile.edit_personal_statement()' class='edit'>(edit personal statement)</a>"
			}
			if (this.bio[topic][0]){
						html += "<p>" + this.bio[topic][0] + "</p>"
			} else {

						html += "<p>" + this.first_name + " does not have a personal statement for this topic.</p>"
			}
					html += "</div>" +
				"</div>"

			// Insert the personal statement
			$('.statement').append(html);

			// Setup the title for the feedback
			var link = WHUFFIE.profile.topic_list_url + '?topic=' + topic;
			$('.feedback').html('<h2>What people are saying about ' + this.first_name + ' as a(n) <a href="' + link + '">' + this.bio[topic][1] + '</a>:</h2>');

			$.get(this.ajax_url + topic, this.load_referrals);
		},

		load_referrals: function(data) {

			for (ii=0; ii < data.length; ii++) {
				var ref = data[ii];

				if (ref.source.follow) {
					css = "avatar avatar-follow";
					text = "<span class='you_follow'>You follow " + ref.source.name + "</span>"
				} else {
					css = "avatar"
					text = ""
				}

				// Generate the referral html
				var link = '<a href="' + ref.source.profile + '">';
				var html =

					"<div class='" + css + "'>" +
						link + "<img src='" + ref.source.thumb + "' alt='" + ref.source.name + " Thumb'/></a>" +
					"</div>" +
					"<div class='cell'>" +
						"<h3>" + link + ref.source.name + "</a> <span class='date'>(" + ref.date + ")</span></h3>" + text +
						"<p>" + ref.testimonial + "</p>" +
 					"</div>"

				// attach the referral html
				$('.feedback').append(html);
			}

			// Adjust the height of the side nav box
			$('#referred_for .side_nav').height($('#referred_for').height()-45);
		},

		edit_bio: function() {
			// Open the edit bio box with the current bio prefilled

			bio = WHUFFIE.utils.html_decode($('div.bio').text());
			$('#edit_bio textarea').text(bio);


			showProfileLightbox('edit_bio');
		},

		edit_personal_statement : function(current_statement, current_topic, current_topic_code) {
			// Open the edit personal statement box

			current_statement = current_statement? current_statement : WHUFFIE.profile.current_statement;
			current_statement = WHUFFIE.utils.html_decode(current_statement);
			current_topic = current_topic? current_topic : WHUFFIE.profile.current_topic;
			current_topic_code = current_topic_code? current_topic_code : WHUFFIE.profile.current_topic_code;

			$('#edit_statement textarea').text(current_statement);
			$('#edit_statement h1').text(current_topic);
			$('#edit_statement #topic_code').val(current_topic_code);

			showProfileLightbox('edit_statement');
		},

		post_bio_factory : function(callback){

			return function(){

				my_parent = $(this).parent();
				bio = $('textarea', my_parent).val();

				// Grab the topic code (if available)
				topic = $('#topic_code', my_parent).val();

				post_data = {bio: bio, topic: topic};

				closeLightbox();

				$.post(WHUFFIE.profile.bio_url, post_data, function(data){

					if(data['errno'] < 0){
						alert("Error changing your bio: " + data['msg']);
					} else {
						callback();
					}
				});
			}
		}
	},

	emails : {
		add_email_url : '',
		make_primary_url: '',

		init : function(add_email_url, make_primary_url){
			this.add_email_url = add_email_url;
			this.make_primary_url = make_primary_url;
		},

		add_email_slot : function() {
			$('#add_email_box').removeClass('hidden');
		},

		add_email : function() {
			// Add an email to this user's account

			email = $('#add_email_box input').val();
			if (!email) {
				alert("You must input an email address");
				return;
			}

			var post_data = { email: email };
			$.post(WHUFFIE.emails.add_email_url, post_data, function(data){

				if (data['errno'] < 0) {
					alert('Error adding email address: ' + data['msg']);
					return;
				}

				$('#emails_box span.address:last').after('<span class="address"><span class="email">' + email  + '</span><span class="primary">Unverified</span></span>');

				// Take away the "Add email" Box
				$('#add_email_box input').val('');
				$('#add_email_box').addClass('hidden');
			 });
		},

		make_email_primary : function(email) {

			var post_data = { email: email };
			$.post(WHUFFIE.emails.make_primary_url, post_data, function(data){

				var old_email;
				var link;

				if (data['errno'] < 0) {
					alert('Error changing primary email: ' + data['msg']);
					return;
				}

				// Create the "make primary" link
				$old_row = $('#emails_box span.address:first');
				old_email = $('span.email', $old_row).text();
				link = "javascript:WHUFFIE.emails.make_email_primary('" + old_email + "');";

				$('span.primary', $old_row).html('<a href="' + link + '">Make Primary</a>');

				// Remove the new primary email from the table
				$('#emails_box span.address').each(function(index){
					if ($('span.email', this).text() === email){
						$(this).remove();
						return false;
					}
				});

				// Add back our new email as the primary email
				$old_row.before('<span class="address"> <span class="email">' + email + '</span> <span class="primary"> Primary </span> </span>');
			});
		}
	},

	message : {

		initialized: false,
		pk: 0,
		url: '',

		init: function(url){
			// Initialize the messaging subsystem
			// Only initialize once
			if(this.initialized){ return; }

			this.initialized = true;
			this.url = url;

			this.$cb = $('#send_message');

			$('input[type$="button"]', this.$cb).click(this.send_message);
			$('.message-btn').click(this.open_dialog);

		},

		send_message: function(){
			// Callback for message submittal


			var body = $('textarea', WHUFFIE.message.$cb).val();
			var subject = $('input[name$="subject"]', WHUFFIE.message.$cb).val();

			// If there's no message, skip the sending and keep the dialog open
			if ( !body ){
				alert("You must enter a message");
				return;
			}

			// We'll allow no subject, but we need to manually add filler text
			if ( !subject ){
				subject = '(no subject)'
			}

			$.post(WHUFFIE.message.url, {
					subject: subject,
					body: body,
					recipient: WHUFFIE.message.pk
				},

				function(data){
					closeLightbox();
					if(data['errno'] >= 0){
						// Clear out the subject/message
						$('textarea', WHUFFIE.message.$cb).val('');
						$('input[name$="subject"]', WHUFFIE.message.$cb).val('');
						alert("Message sent");
					} else {
						alert("Error sending message: " + data['msg']);
					}
				}
			).error(function(data, jqXHR){alert("Failed to send your message.")});
		},

		open: function(pic_url, name, pk){
			// Open the send message dialog

			if( !this.initialized ){}
		},

		open_dialog: function(){
			// Open the send message dialog

			if( !WHUFFIE.message.initialized ){
				alert("Internal Error: Message dialog not initialized.  Our apologies.");
				return;
			}

			// Close any existing tooltip (necessary for the topic_list page
			$('div.tooltip').hide();

			WHUFFIE.message.pk = $(this).attr('pk');
			var name = $(this).attr('name');
			var pic_url = $(this).attr('pic_url');

			// Set the name and picture, then open the dialog
			$('#send_message img').attr('src', pic_url);
			$('#send_message input[name$="to"]').val(name);
			showProfileLightbox('send_message');
		}
	},

	follow: {
		url: '/assoc/',
		error_str: 'Follow Failed',
		class_str: 'is_following',
		refresh: false,

		active_text: '<div class="glyph follow"></div>Following',
		activate_text: '<div class="glyph follow"></div>Follow My Referrals',
		deactivate_text: '<div class="glyph follow"></div>Unfollow',

		init: function(skip_text){

			button_text_func = WHUFFIE.bookmark.button_text_factory(this);
			$('.follow-btn').click(WHUFFIE.bookmark.toggle_factory(this, button_text_func));
			if(!skip_text){
				$('.follow-btn').each(function(){
					button_text_func($(this));
				});
			}
		},

		get_data: function(is_following){
			if (is_following) {
				return { follow: 0, level: 1};
			} else {
				return { follow: 1, level: 1};
			}
		}
	},

	bookmark: {
		// Bookmark functionality
		url: '/assoc/',
		error_str: 'Bookmark Failed',
		class_str: 'is_bookmarked',

		active_text: '<div class="glyph bookmark"></div>bookmarked',
		activate_text: '<div class="glyph bookmark"></div>bookmark me',
		deactivate_text: '<div class="glyph bookmark"></div>unbookmark',

		init: function(){
			button_text_func = WHUFFIE.bookmark.button_text_factory(this)
			$('.bookmark-btn')
				.click(WHUFFIE.bookmark.toggle_factory(this, button_text_func))
				.each(function(){
					button_text_func($(this));
			});
		},

		button_text_factory: function(obj){
			return function($btn) {
				// Set the text for our button

				if ($btn.hasClass(obj.class_str)) {
					$btn.html(obj.active_text);
					$btn.hover(
						function(){ $(this).addClass('hovered').html(obj.deactivate_text); },
						function(){ $(this).removeClass('hovered').html(obj.active_text); }
					);
				} else {
					$btn.html(obj.activate_text);
					$btn.unbind('mouseenter').unbind('mouseleave');
				}
			}
		},

		get_data: function(is_bookmarked){
			if(is_bookmarked){
				return { bookmark: 0 }
			} else {
				return { bookmark: 1 }
			}
		},

		toggle_factory: function(obj, func){

			return function(){
				// Toggle following a person.  We get the current state and pk from the button itself

				var that = this;
				var url = WHUFFIE.bookmark.url + $(this).attr('pk');
				var data = obj.get_data($(this).hasClass(obj.class_str));

				$.post(url, data, function(data){

						if(data['errno'] >= 0){
							if (obj.refresh){
								location.reload();
							} else {
								$(that).toggleClass(obj.class_str);
							}
							func($(that));
						} else if (data['errno'] == -100) {
							alert("You are not logged in");
						} else {
							alert(obj.error_str + '  ' + data['errno'] + '  ' + data['msg']);
						}
					}
				).error(function(data, jqXHR){alert(obj.error_str)});
			}
		}
	},

	accounts: {
		change_password_url: '',
		change_password: function(){
			// Change the user's password.  We assume the input names 'new_password1', 'new_password2', and 'old_password'

			var post_data = {
				'new_password1': $('input[name$="new_password1"]').attr('value'),
				'new_password2': $('input[name$="new_password2"]').attr('value'),
				'old_password': $('input[name$="old_password"]').attr('value')
			}

			$('input[name$="new_password1"]').attr('value','')
			$('input[name$="new_password2"]').attr('value','')
			$('input[name$="old_password"]').attr('value','')

			$.post(WHUFFIE.accounts.change_password_url, post_data, function(data){
				if(data['errno'] < 0){
					alert("Error changing password: " + data['msg']);
				} else {
					$('#notify').notify('create', {title: 'Password Changed'});
				}
			});
		}
	},

	contacts : {
		contacts : [],
		contacts_url : '',

		filter : {
			'bookmark': true,
			'refer': true,
			'refer_me': true,
			'following': true,
			'following_me': true
		},

		init : function(contacts_url){
			this.contacts_url = contacts_url;
			this.download_contacts();
		},

		download_contacts: function(){
			$.getJSON(WHUFFIE.contacts.contacts_url, function(data) {
				WHUFFIE.contacts.contacts = data;
				WHUFFIE.contacts.reload();
			});
		},

		load_prefs: function(){
			$('input.filter').each(function(){
				WHUFFIE.contacts.filter[$(this).attr('name')] = $(this).attr('checked');
			});
			WHUFFIE.contacts.reload();
		},

		update_filter : function(){
			// Update the filters.  Called when someone clicks the filter buttons

			WHUFFIE.contacts.filter.bookmark = $('#filter_bookmarked').hasClass("checked");
			WHUFFIE.contacts.filter.refer = $('#filter_referred').hasClass("checked");
			WHUFFIE.contacts.filter.refer_me = $('#filter_i_referred').hasClass("checked");
			WHUFFIE.contacts.filter.following = $('#filter_im_following').hasClass("checked");
			WHUFFIE.contacts.filter.following_me = $('#filter_following_me').hasClass("checked");

			WHUFFIE.contacts.reload();
		},

		filter_contact : function(cc){
			if (this.filter['following'] && cc['following'] > 0) return true;
			if (this.filter['following_me'] && cc['following_me']) return true;
			if (this.filter['refer'] && cc['refs_made'].length) return true;
			if (this.filter['refer_me'] && cc['refs_from'].length) return true;
			if (this.filter['bookmark'] && cc['bookmark']) return true;

			return false;
		},

		get_how_connected : function(cc){
			// Generate the DOM for the "follow_status" div

			$ret = $('<div class="follow_status"></div>');

			if(cc['following'] > 0 && cc['following_me']){
				$ret.append('<div class="status"><div class="icon mutual"></div><span>Mutually Following</span></div>');
			} else if (cc['following'] > 0) {
				$ret.append('<div class="status"><div class="icon following"></div><span>I\'m Following</span></div>');
			} else if (cc['following_me'] > 0) {
				$ret.append('<div class="status"><div class="icon following_me"></div><span>Following Me</span></div>');
			}

			if(cc['bookmark']){
				$ret.append('<div class="status"><div class="icon bookmarked"></div><span>I\'ve Bookmarked</span></div>');
			}

			return $ret;
		},

		reload : function(){
			$('.filter_items').html('');

			for(idx in this.contacts){

				contact = this.contacts[idx]

				if(this.filter_contact(contact)){

					var html = $('<div class="row">' +
						'<img src="' + contact['thumb'] + '" class="avatar"/>' +
						'<div class="info">' +
							'<h1> <a href="' + contact['profile'] + '">' +  contact['first_name'] + ' ' + contact['last_name'] + '</a></h1>' +
						'</div>' +
						'</li>');

					/* Add topics for which this person has been referred */
					var title = '';
					var comma = '';
					for(topic in contact['topics']){
						title += comma + '<a href="/topic-list?topic=' + contact['topics'][topic]['topic'] + '">' + contact['topics'][topic]['topic_name'] + '</a>';
						comma = ', ';
					}
					$('div.info', html).append('<h2>' + title + '</h2>');

					/* Add referrals made tags */
					for(ref in contact['refs_made']){
						$('div.info', html).append(
							'<span class="action">I referred ' + contact['first_name'] + ' for "' + contact['refs_made'][ref]['topic_name'] + '" on ' +
							contact['refs_made'][ref]['date_format'] +
							' <a onclick="WHUFFIE.contacts.revoke_referral(\'' + contact['refs_made'][ref]['url'] + '\');">(revoke referral)</a></span>');
					}

					/* Add referrals from tags */
					for(ref in contact['refs_from']){
						$('div', html).append('<span class="action">' + contact['first_name'] + ' referred me "' + contact['refs_from'][ref]['topic_name'] + '" on ' +
						contact['refs_from'][ref]['date_format'] + '</span>');
					}

					/* Add the stuff for "how we're connected" box */
					$box = WHUFFIE.contacts.get_how_connected(contact);

					$('div.info', html).after($box);

					/* Put this jumble on the page */
					$('.filter_items').append(html);
				}
			}
		},

		revoke_referral : function(url){

			var r=confirm("Revoke this referral?");
			if(r){
				$.ajax({
					url: url,
					type: 'DELETE',
					success: WHUFFIE.contacts.download_contacts
				});
			}
		}
	},

	tooltip : {

		hover_num : 0,

		init : function(){
			// Hook up the hover functions
			$('.user_thumb .image').hover(this.hover_on, this.hover_off);

		},

		hover_on : function () {
			// Show the popup box
			
			$('.tooltip', this).show();
			return;
	
			// VARIABLES
			img_id = this.id.slice(4);
			obj = $('.tooltip');
	
			var t = $(this).parent(),
				t_offset = t.offset(),
				w = obj.width(),
				h = obj.height(),
				win = $(window).width()-45
	
			// Displays Obj 
			obj.css({display: 'block'})
	
			// Check how close popup is to the edge of the window
			if((win-420) < t_offset.left){
				obj.css({
					backgroundPosition: '-430px 0px',
					top: t_offset.top-(h),
					left: t_offset.left-(w-45)
				})
				} else {
				obj.css({
					backgroundPosition: '0px 0px',
					top: t_offset.top-(h),
					left: t_offset.left
				})
			}
		}, 
			
		hover_off : function(){

			$('.tooltip', this).hide();
			return;

			img_id = this.id.slice(4);
			$('#tooltip' + img_id).css({display: 'none'})
		}
	}
};

function showLightbox(type, input){
    // alert('type:  ' + type);
    //
	window.scrollTo(0,0);
        $('#make_referral, .mask').fadeIn(250);
	$('.button').removeClass('pressed');
	$('#find').fadeOut(250);
	$('#make').fadeOut(250);
	$('#topic-type').text(type + '!');
	$('#id_topic').replaceWith('<select class="hidden" name="topic" id="id_topic"><option selected="selected" value="' + input + '">' + type + '</option></select>');
}

function showProfileLightbox(id){

	window.scrollTo(0,0);
	$('#' + id + ', .mask').fadeIn(250)
	$('.button').removeClass('pressed');
	$('#find').fadeOut(250);
	$('#make').fadeOut(250);
}

function closeLightbox(){

	// $('.lightbox, .mask').fadeOut(250)
    $('.lightbox, .mask, #how_it_works').fadeOut(250)
	$('.button').removeClass('pressed')
	$('#find').fadeOut(250)
	$('#make').fadeOut(250)
}

function step(n){

	if(n == 'close'){
		closeLightbox();
		step('1');
	}

	$('#step_'+n).siblings().fadeOut(250)
	$('#'+n).addClass('active').siblings().removeClass('active')
	$('#step_'+n).delay(250).fadeIn(250)
}

$(document).ready(function(){

    // homepage
	// $('.index_nav .tab').click(function(){
	// 	var t = $(this),
	// 		obj = t.attr('slide')

	// 	t.addClass('active').siblings().removeClass('active')

	// 	// $('#'+obj).siblings().hide()
	// 	// $('#'+obj).show()


	// });

	$('#howitworksbutton').click(function(){
		$('#how_it_works').fadeIn(250)
		$('.mask').fadeIn(250)
	});

    $('#accept-ref-unreg').click(function() {
        $('#accept-ref-unreg-cont0').hide();
        $('#accept-ref-unreg-cont1').fadeIn(250);
    });


        function close_dropdown(name){

		but = $('.button[name="' + name + '"]');
		typ = but.attr('name'),
		obj = $('#'+typ),

		but.removeClass('pressed')
		obj.fadeOut(250)
	}

	$('.button[name="find"]').click(function(){
		var but = $(this),
			typ = but.attr('name'),
			obj = $('#'+typ),
			pos = but.offset()

		if(but.hasClass('pressed')){
			but.removeClass('pressed')
			obj.fadeOut(250)
		} else {
			but.addClass('pressed')
			obj.css({
				top: pos.top+32,
				left: pos.left
			}).fadeIn(250)
		}

		close_dropdown('make');
	});

	$('.button[name="make"]').click(function(){
		var but = $(this),
			typ = but.attr('name'),
			obj = $('#'+typ),
			pos = but.offset()

		if(but.hasClass('pressed')){
			but.removeClass('pressed')
			obj.fadeOut(250)
		} else {
			but.addClass('pressed')
			obj.css({
				top: pos.top+32,
				left: pos.left
			}).fadeIn(250)
		}

		close_dropdown('find');
	});

	$('#make li span').click(function() {
		$('#make').fadeOut(250);
		type_text = $(this).text();
		type_input = $(this).attr('name');
		showLightbox(type_text, type_input);
	});

	$('#referral li span').click(function() {
		type_text = $(this).text();
		type_input = $(this).attr('name');
		showLightbox(type_text, type_input);
	});


	/* POSITION LOGIN WINDOW
	var obj = $('#login_window');
	var h = obj.height()
	obj.css({marginTop: -1*(h/2)});
	*/

	/* Sets the sidebar equal to the height of #referred_for */
	$('#referred_for .side_nav').height($('#referred_for').height()-45);

	/* CONTACTS FILTER */
	$('.filter li').click(function(){
		var obj = $(this),
			filt = obj.attr('id')
		obj.hasClass('checked') ? switcher = 1 : switcher = 0;

		if(switcher){
			$('.'+filt).slideUp(250);
			obj.removeClass();
		} else {
			$('.'+filt).slideDown(250);
			obj.addClass('checked')
		}
                WHUFFIE.contacts.update_filter();
	});
});



