$(document).ready(function() {
						   
	mt.loggedIn = $('#user-profile').length ? true : false;

	// get current id
/*
	var loc = document.location.href + '';
	loc = loc.replace(/http:\/\/[^/]*\/([0-9]+)\/{0,1}$/m, function(a, b) {
		if(b.length) mt.current = b;
	});
*/
	var loc = document.location.href + '';
	loc = loc.replace(/http:\/\/[^/]*(\/list2){0,1}\/([0-9]+)\/{0,1}$/m, function(a, b, c) {
		if(c.length) mt.current = c;
	});

	// links
	$('a').each(function() {
		if($(this).attr('rel') == 'external') {
			$(this).click(function() {
				window.open($(this).attr('href'));
				return false;
			});
		}
		$(this).mouseup(function() {
			$(this).blur();	
		});
	});
	
	// user menu
	$('#user-profile').click(function() {
		$('#user-menu').show();
		$(document.body).click(function() {
			$('#user-menu').hide();
			$(document.body).unbind('click');
		});
		return false;
	});

	// timeline button
	$('#user-timeline').click(function() {
		if(!mt.loggedIn) {
			mt.login('My Timeline');
			return false;
		}
	});

	// mentions button
	$('#user-mentions').click(function() {
		if(!mt.loggedIn) {
			mt.login('Mentions');
			return false;
		}
	});
	
	// update status button
	$('#user-status').click(function() {
		mt.status(this, 'tweet');	
		return false;						
	});
	
	// create button
	$('#nav-create').add('.button-create').click(function() {
		mt.mix.create();
		return false;
	});
	
	// search box focus
	$('#search-box').focus(function() {
		$(this).parent().addClass('focused');
	}).blur(function() {
		$(this).parent().removeClass('focused');
	});
	
	// lists
	$('.collapse').click(function() {
		var par = $(this).parent().parent();
		var state = '';
		if(par.hasClass('open')) {
			$.cookie(par.attr('id'), 'closed', { expires: 100, path:'/' });
			par.addClass('closed');
			par.removeClass('open');
		}
		else {
			$.cookie(par.attr('id'), 'open', { expires: 100, path:'/' });
			par.addClass('open');
			par.removeClass('closed');
		}
	});
	
	$('.list-link').live('click', function() {
		if($(this).parent().hasClass('selected')) {
			mt.mix.refresh();
			return false;
		}
	});
	
	// add buttons
	$('.user-lg span span').live('click', function() {
		var user = $(this).parent().parent().attr('href');
		user = user.replace(/.*\/([^/]*$)/m, function(a, b) { return b });
		if(mt.loggedIn) mt.add(user);
		else mt.login('Add ' + user);
		return false;
	});
	$('.user-sm span span').live('click', function() {
		var user = $(this).parent().parent().attr('href');
		user = user.replace(/.*\/([^/]*$)/m, function(a, b) { return b });
		if(mt.loggedIn) mt.add(user);
		else mt.login('Add ' + user);
		return false;
	});
	$('.user-profile span span').click(function() {
		var user = $(this).parent().parent().attr('href');
		user = user.replace(/.*\/([^/]*$)/m, function(a, b) { return b });
		if(mt.loggedIn) mt.add(user);
		else mt.login('Add ' + user);
		return false;
	});
	
	// save mix
	$('#mix-action-save').click(function() {
		if(mt.loggedIn) {
			if(mt.current) {
				if(!$(this).hasClass('disabled')) {
					mt.mix.save(mt.current);
				}
				else {
					var action = 'mt.mix.unsave(' + mt.current + ')';
					mt.prompt('Do you really want to unsave this list?', 'Unsave', action);
				}
			}
			return false;
		}
		else {
			mt.login('Save');	
		}
	});

	// unsave list
	$('.manage-unsave').click(function() {
		mt.tempUnsave = $(this).parent().parent();
		var url = $(this).attr('href');
		var mix = url.substring(url.indexOf('#') + 1);
		var action = 'mt.mix.unsave(' + mix + ', mt.tempUnsave)';
		mt.prompt('Do you really want to unsave this list?', 'Unsave', action);
		return false;
	});

	// delete list
	$('.manage-delete').click(function() {
		mt.tempDelete = $(this).parent().parent();
		var url = $(this).attr('href');
		var mix = url.substring(url.indexOf('#') + 1);
		var action = 'mt.mix.del(' + mix + ', mt.tempDelete)';
		mt.prompt('Do you really want to permanently delete this list?', 'Delete', action);
		return false;
	});
	
	// more
	$('.mix-more').live('click', function() {
		mt.mix.more();
		return false;									   
	});
	
	// hover action
	$('.post').hover(function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	});

	// clip button
	$('.action-clip').live('click', function() {
		if(mt.loggedIn) {
			var top = $(this).parent().parent().parent().parent();
			var sid = top.attr('id').substring(4);
			$.ajax({
				type: 'POST',
				url: '/ajax/clip/add/' + sid,
				success: function(count) {
					if(count) {
						$('#collections-clips .right').html(count);
						mt.alert('<a href="/collections/clips">This tweet has been added to your clips.</a>', 2500);
					}
				},
				error: function(e1, e2, e3) {
					 mt.error(e1, e2, e3);
				}
			});	
		}
		else {
			mt.login('Clip');	
		}
		return false;
	});

	// unclip button
	$('.action-unclip').live('click', function() {
		var top = $(this).parent().parent().parent().parent();
		var sid = top.attr('id').substring(4);
		$.ajax({
			type: 'POST',
			url: '/ajax/clip/remove/' + sid,
			success: function(count) {
				if(count) {
					$('#collections-clips .right').html(count);
					mt.alert('This tweet has been unclipped.', 2500);
					top.slideUp('slow', function() {
						top.remove();
					});
				}
			},
			error: function(e1, e2, e3) {
				 mt.error(e1, e2, e3);
			}
		});	
		return false;
	});
	
	// reply button
	$('.action-reply').live('click', function() {
		mt.status(this, 'reply');	
		return false;
	});
	
	// retweet button
	$('.action-retweet').live('click', function() {
		mt.status(this, 'retweet');	
		return false;
	});
	
	// suggest link
	$('#suggest-link').live('click', function() {
		if(mt.loggedIn) mt.status(this, 'suggest');
		else mt.login('Suggest Someone');
		return false;
	});
	
	// close alert
	$('#alert a.close').live('click', function() {
		$('#alert').fadeOut(function() {
			$('#alert').remove();								 
		});
		return false;
	});

	// refresh
	$('#refresh').live('click', function() {
		mt.mix.refresh();
		return false;
	});

	$('#refresh-top').live('click', function() {
		mt.mix.refresh();
		return false;
	});
	
	// align refresh button
	mt.alignRefresh = function() {
		$('#button-refresh').css({
			top: $(window).height() - 40,
			left: $(window).width() - 57
		});
	}
	$(window).resize(mt.alignRefresh);
	$(document).resize(mt.alignRefresh);
	mt.alignRefresh();
	
	// edit list
	$('#mix-action-edit').click(function() {
		if(!$(this).hasClass('disabled')) {
			mt.mix.edit();
		}
		else {
			mt.mix.finish();
		}
		return false;
	});
	
	// auto edit new list
	if($('#mix-edit').hasClass('open-edit')) {
		$('#mix-action-edit').trigger('click');
		$('#mix').show();
	}
	
	// privacy
	$('#privacy').live('click', function() {
		mt.mix.privacy(this);
		return false;
	});

	// edit list buttons		
	$('#edit-buttons a').not('.right').click(function() {
		var id = $(this).attr('id');
		var t = id.substring(id.lastIndexOf('-') + 1);
		$('.edit-section').hide();
		$('#edit-section-' + t).show();
		$(this).parent().parent().find('.selected').removeClass('selected');
		$(this).parent().addClass('selected');
		return false;										
	});
	
	// browse friends popup
	$('#add-user-browse').live('click', function() {
		mt.mix.browse();
		return false;									 
	});

	// remove users
	$('#remove-existing li a').live('click', function() {
		if(!$(this).hasClass('changed')) {
			mt.mix.remove($(this), $(this).html());
		}
		return false;									 
	});	

	// mix embed
	$('#mix-action-embed').click(function() {
		$.get('/ajax/' + mt.current + '/embed', function(data) {
			mt.popup.open(data, 'Embed "' + truncate($('#mix-title span').html(), 45) + '"', 750, 540);
			mt.embed();
		});
		return false;
	});

	// mix share
	$('#mix-action-share').click(function() {
		$.get('/ajax/' + mt.current + '/share', function(data) {
			mt.popup.open(data, 'Share "' + truncate($('#mix-title span').html(), 30) + '"', 400, 235);
			$('#share-via-twitter').click(function() {
				var m = $(this).attr('mixtitle') + ': ' + $(this).attr('href')
				mt.status(this, 'tweet', m);
				return false;									   
			});
		});
		return false;
	});
	
	// search people
	$('#search-people-submit').click(function() {
		var m = '<p><img src="/images/loading-wheel.gif" width="15" height="15" '
		+ 'class="left" style="margin-right:5px" /> finding people...</p>';
		var q = $('#search-people').val();
		if(q.length) {
			$('#user-list').html(m);
			mt.tweepsearch(q, 30);
		}
		else mt.message('Please type something in, then try again.', 'Search People');
		return false;										  
	});
	$('#search-people').keyup(function(e) {
		if(e.keyCode == 13) $('#search-people-submit').trigger('click');
	});
	
	// ratings
	mt.mix.rating.init();
	
	// poll interval (secs)
	mt.pollint = 25;
		
	// init poll or load list
	if(!mt.current) {
		if(!mt.polling) mt.polling = setInterval('mt.poll()', mt.pollint * 1000);
	}
	else {
		mt.mix.load();
	}

	
});

var mt = {

	current: null,
	
	poll: function(init) {
		var postdata = new Object();
		if(mt.current) postdata.list = mt.current;
		var first = $('#posts .post').eq(0).attr('id') || '';
		first = first.substring(4);
		if(first.length) postdata.status_id = first;
		$.ajax({
			type: 'POST',
			url: '/ajax/poll',
			data: postdata,
			dataType: 'json',
			success: function(data) {
				if(parseInt(data.list_count)) {
					alertCount(data.list_count);
				}
				function makeItem(t) {
					var c = t.count > 999 ? 999 : t.count;
					var p = t.private ? ' private' : '';
					return '<li><a href="' + t.url + '" class="list-link' + p + '" title="'
					+ t.title + '"><span class="left">' + t.title
					+ '</span><span class="right">' + c + '</span></a></li>';
				}
				function alertCount(c) {
					//var s = c != 1 ? ' Tweets' : ' Tweet';
					//if(c > 99) s = 'Tw...';
					//$('#refresh').html(c + ' New' + s);
					
					var t = '<span class="top">+' + c + '</span>';
					var b = '<span class="bottom">+' + c + '</span>';
					$('#refresh').html(t + b);
					if($('#button-refresh').css('display') == 'none') {
						$('#button-refresh').fadeIn();
						$('#refresh-top').fadeIn();
					}
				}
				var myLists = '';
				var savedLists = '';
				$.each(data.my_lists, function() {
					myLists += makeItem(this);
				});
				$.each(data.subscribed_lists, function() {
					savedLists += makeItem(this);
				});
				$('#my-lists').html(myLists);
				$('#saved-lists').html(savedLists);
				$('#lists a').each(function() {
					var href = $(this).attr('href');
					var id = href.substring(href.lastIndexOf('/') + 1);
					if(id == mt.current) {
						$(this).parent().addClass('selected');
						var count = parseInt($(this).find('.right').html());
						if(!init && count) {
							alertCount(count);							 
						}
						else {
							$(this).find('.right').html('0');
						}
					}
				});
			},
			error: function(e1, e2, e3) {
				// do not show polling errors
				// mt.error(e1, e2, e3);
			}
		});	
	},

	mix: {
		load: function() {
			if(mt.current) {
				// get tweets
				mt.loader.show();
				$.ajax({
					type: 'GET',
					url: '/ajax/' + mt.current,
					dataType: 'html',
					success: function(html) {
						$('#posts').html(html);
						$('.post').hover(function() {
							$(this).addClass('hover');
						}, function() {
							$(this).removeClass('hover');
						});
						$('#mix').show();
						if(!mt.polling) mt.polling = setInterval('mt.poll()', mt.pollint * 1000);
						mt.loader.hide();
					},
					error: function(e1, e2, e3) {
						mt.error(e1, e2, e3);
					}
				});		
				// get users list
				$.ajax({
					type: 'GET',
					url: '/ajax/' + mt.current + '/friends',
					dataType: 'html',
					success: function(html) {
						$('#mix-people-list').html(html);
					},
					error: function(e1, e2, e3) {
						mt.error(e1, e2, e3);
					}
				});	
			}
		},
		
		refresh: function() {
			$('#button-refresh').fadeOut();
			$('#refresh-top').fadeOut();
			mt.scrollTimes = $('#content').height() / 10;
			mt.scrollPos = parseInt($(window).scrollTop());
			mt.scrollToTop = function() {
				if(mt.scrollPos >= mt.scrollTimes) {
					var pos = mt.scrollPos - mt.scrollTimes;
					if(pos < mt.scrollTimes) pos = 0;
					mt.scrollPos = pos;
					window.scrollTo(0, pos);
					setTimeout('mt.scrollToTop()', 10);	
				}
				else {
					mt.mix.load();
					$('#lists .selected .right').html('0');
					window.scrollTo(0, 0);
				}
			}
			mt.scrollToTop();
		},
		
		loadingMore: false,
		
		more: function() {
			if(mt.current && !mt.mix.loadingMore) {
				var lastpost = $('.post:last').attr('id');
				lastpost = lastpost.substring(4);
				$('.mix-more').eq(0).html('Loading...').blur();
				mt.mix.loadingMore = true;
				mt.loader.show();
				$.ajax({
					type: 'GET',
					url: '/ajax/' + mt.current + '/more/' + lastpost,
					dataType: 'html',
					success: function(html) {
						$('.mix-more:first').remove();	
						$('#posts').append(html);
						$('.post').hover(function() {
							$(this).addClass('hover');
						}, function() {
							$(this).removeClass('hover');
						});
						mt.loader.hide();
						mt.mix.loadingMore = false;
					},
					error: function(e1, e2, e3) {
						mt.error(e1, e2, e3);
						mt.mix.loadingMore = false;
					}
				});
			}
		},
		
		create: function(user) {
			user = user || '';
			$.get('/_modules/user/templates/ajax_create.php?u=' + user, function(data) {
				mt.popup.open(data, 'Create New List', 480, 230);
				var title = $('#create-new input:first');
				$('#create-new form').submit(function() {
					if(title.val().length == 0) {
						title.focus();
						return false;
					}
				});
				$('#create-new-submit').click(function() {
					$('#create-new form').submit();
					return false;
				});
			});
		},
		
		edit: function() {
			$('#mix-action-edit').addClass('disabled');
			$('.edit-section').hide();
			$('#edit-section-add').show();
			$('#add-users').val('');
			$('#mix-edit').slideDown();
			mt.addPoll = setInterval(function() {
				if($('#add-users').val().length) {
					$('#add-user-submit-disabled').attr('id', 'add-user-submit');
				}
				else {
					$('#add-user-submit').attr('id', 'add-user-submit-disabled');
				}
			}, 100);
			$('#add-user-submit-disabled').live('click', function() {
				return false;											  
			});
			$('#add-user-submit').live('click', function() {
				mt.mix.add($('#add-users').val());
				return false;											  
			});
			$('#edit-button-finish').click(function() {
				mt.mix.finish();
				return false;										
			});
			$('#title').focus(function() {
				$(this).attr('orig', $(this).val());
			}).blur(function() {
				var orig = $(this).attr('orig');
				if(!$(this).val().length) $(this).val(orig);
				else if($(this).val() != orig) {
					$('#mix-title span').html($(this).val());
					mt.mix.details('title', $(this).val());
				}
			});
			$('#desc').focus(function() {
				$(this).attr('orig', $(this).val());								   
			}).blur(function() {
				if($(this).val() != $(this).attr('orig')) {
					mt.mix.details('description', $(this).val());
					$('#mix-description').find('#description').html($(this).val());
				}
			});
			var tag1 = $('#mix-tags a').eq(0).html() || '';
			var tag2 = $('#mix-tags a').eq(1).html() || '';
			var tag3 = $('#mix-tags a').eq(2).html() || '';
			tag1 = tag2.length ? tag1 + ', ' : tag1;
			tag2 = tag3.length ? tag2 + ', ' : tag2;
			$('#tags').val(tag1 + tag2 + tag3);
			$('#tags').keyup(function() {
				var str = $(this).val();
				str = str.toLowerCase();
				str = str.replace(/[^a-z0-9\s]/gi, ' ');
				str = str.replace(/\s+/g, ' ');
				str = str.replace(/\s*$/gm, '');
				var html = '';
				mt.tempTags = new Array();
				mt.tempTags = str.split(' ');
				if(!str.length) mt.tempTags = [];
				for(i in mt.tempTags) {
					if(i < 3) {
						html += '<a href="/explore/' + mt.tempTags[i] + '">'
						+ mt.tempTags[i] + '</a>, ';
					}
					else mt.tempTags.splice(i);
				}
				html = html.replace(/,\s*$/gm, '');
				$('#mix-tags').html(html);
			}).blur(function() {
				mt.mix.details('tags', mt.tempTags.join(' '));
			});
		},
		
		finish: function() {
			$('#mix-action-edit').removeClass('disabled');
			$('#mix-edit').slideUp();
			clearInterval(mt.addPoll);
			mt.mix.load();
		},
		
		details: function(property, content) {
			var dataObj = new Object();
			dataObj[property] = content;
			$.ajax({
				type: 'POST',
				url: '/ajax/' + mt.current + '/edit',
				data: dataObj,
				dataType: 'text',
				success: function(msg) {
					if(msg == 'true') {
						if(property == 'title') mt.poll();
					}
					else {
						setTimeout(function() { 
							mt.message(msg, 'Problem');
						}, 200);
					}
				},
				error: function(e1, e2, e3) {
					mt.error(e1, e2, e3);
				}
			});
		}, 
		
		browse: function() {
			mt.temp = '';
			$.get('/_modules/user/templates/ajax_browse.php', function(data) {
				mt.popup.open(data, 'Add Friends', 600, 450);
				var rand = Math.floor(Math.random() * 1000000);	
				function getPage(p) {
					$('#add-existing-pages span').css({
						background: 'url(/images/loading-wheel.gif) center no-repeat'
					}).html('');
					rand = p.length ? '' : rand;
					$.ajax({
						type: 'GET',
						url: '/ajax/friends/browse/' + rand + p,
						success: function(data) {
							$('#add-existing-wrapper').html(data);
							$('#add-existing li a').click(function() {
								var user = $(this).attr('title').substring(4) + ' ';
								var temp = mt.temp;
								if(temp.indexOf(user) > -1) {
									$(this).removeClass('user-remove');
									mt.temp = temp.replace(new RegExp(user), '');
								}
								else {
									mt.temp += user;
									$(this).addClass('user-remove');
								}
								return false;
							});
							$('#add-existing-pages a').click(function() {
								var href = $(this).attr('href');
								var page = href.substring(href.indexOf('browse/') + 7);
								if(href.indexOf('#') < 0) getPage(page);
								return false;
							});
							var temp = mt.temp;
							if(temp.length) {
								var users = temp.split(' ');
								users.pop();
								$('#add-existing li a').each(function() {
									var el = $(this);
									var name = el.attr('title').substring(4);
									$.each(users, function() {
										if(this == name) el.addClass('user-remove');
									});
								});
							}
						},
						error: function(e1, e2, e3) {
							mt.error(e1, e2, e3);
						} 
					});
				}
				getPage('');
			});
			$('#add-existing-done').live('click', function() {
				if(mt.temp.length) {
					mt.mix.add(mt.temp);
				}
				mt.popup.close();
				return false;
			});
		},
		
		add: function(val) {
			val = val.replace(/\s+/g, ' ');
			if(val.length && val != ' ') {
				mt.friendChange = true;
				$('#new-list-prompt').slideUp();
				mt.loader.show();
				$.ajax({
					type: 'POST',
					url: '/ajax/' + mt.current + '/friend/add',
					data: {
						'friends': val
					},
					dataType: 'json',
					success: function(data) {
						$('#add-users').val('');
						$.each(data.successful, function() {
							$('#remove-existing').append('<li><a href="#" title="Remove '
							+ this + '">' + this + '</a></li>');
						});
						mt.addErrors(data);
						mt.mix.load();
					},
					error: function(e1, e2, e3) {
						mt.error(e1, e2, e3);
					}
				});	
			}
			else {
				mt.message('Enter one or more Twitter usernames, then try again.', 'Problem');
			}
		},
		
		remove: function(e, u) {
			mt.prompt('Are you sure that you want to remove ' + u + ' from this list?', 'Remove', function() {
				$.ajax({
					type: 'POST',
					url: '/ajax/' + mt.current + '/friend/delete',
					data: {
						'friend': u
					},
					dataType: 'html',
					success: function(data) {
						if(data == 'true') {
							$(e).addClass('changed');
							mt.mix.load();
						}
						else mt.message(data, 'Problem');
					},
					error: function(e1, e2, e3) {
						mt.error(e1, e2, e3);
					}
				});						
			});
		},
		
		privacy: function(t) {
			var button = $(t).find('span');
			var public = button.html().indexOf('Private') > -1;
			if(public) {
				mt.loader.show();
				$.get('/ajax/' + mt.current + '/privacy/1', function(msg) {
					if(msg == 'true') {
						button.html('Make Public');
						$('#sidebar li.selected a').addClass('private');
						//$('#privacy-done').fadeIn('fast');	
						setTimeout(function() {
							//$('#privacy-done').fadeOut('slow');		
						}, 1500);
						$('#refresh').show();
						mt.loader.hide();
					}
					else mt.message(msg, 'Problem');
				});
			}
			else {
				mt.loader.show();
				$.get('/ajax/' + mt.current + '/privacy/0', function(msg) {
					if(msg == 'true') {
						button.html('Make Private');
						$('#sidebar li.selected a.private').removeClass('private');
						//$('#privacy-done').fadeIn('fast');
						setTimeout(function() {
							//$('#privacy-done').fadeOut('slow');		
						}, 1500);
						mt.loader.hide();
					}
					else mt.message(msg, 'Problem');
				});				
			}	
		},
		
		save: function(id) {
			$.ajax({
				type: 'GET',
				url: '/ajax/' + id + '/subscribe',
				success: function(response) {
					if(response == 'true') {
						mt.poll();
						mt.mix.load();
						mt.alert('This list has been saved.', 2500);
						$('#mix-action-save').html('Saved').addClass('disabled');
					}
					else document.location = response;
				},
				error: function(e1, e2, e3) {
					mt.error(e1, e2, e3);
				}
			});
		},
		
		unsave: function(id, el) {
			$.ajax({
				type: 'GET',
				url: '/ajax/' + id + '/unsubscribe',
				success: function(response) {
					if(response == 'true') {
						mt.poll();
						mt.alert('The list has been unsaved.', 2500);
						$('#mix-action-save').html('Save').removeClass('disabled');
					}
					else document.location = response;
					if(el) el.slideUp(function() { 
						el.remove();
					});
				},
				error: function(e1, e2, e3) {
					mt.error(e1, e2, e3);
				}
			});			
		},

		del: function(id, el) {
			$.ajax({
				type: 'GET',
				url: '/ajax/' + id + '/delete',
				success: function(response) {
					if(response == 'true') {
						mt.poll();
						mt.alert('The list has been deleted.', 2500);
					}
					else document.location = response;
					if(el) el.slideUp(function() { 
						el.remove();
					});
				},
				error: function(e1, e2, e3) {
					mt.error(e1, e2, e3);
				}
			});			
		},
		
		rating: {
			timeout: null,
			original: null,
			init: function() {
				mt.mix.rating.original = $('#rating').html();
				$('#rating').mouseover(function() {
					clearTimeout(mt.mix.rating.timeout);
				}).mouseout(function() {
					mt.mix.rating.timeout = setTimeout(function() {
						$('#rating').html(mt.mix.rating.original);
						$('#rating span').mouseover(function() {
							mt.mix.rating.hover(this);					 
						}).click(function() {
							mt.mix.rating.change(this);
						});
					}, 100);
				});
				$('#rating span').mouseover(function() {
					mt.mix.rating.hover(this);					 
				}).click(function() {
					mt.mix.rating.change(this);
				});					
			},
			
			hover: function(e) {
				$('#rating span').removeClass('full').removeClass('half').removeClass('my');
				$(e).addClass('my');
				$(e).prev().addClass('my');
				$(e).prev().prev().addClass('my');
				$(e).prev().prev().prev().addClass('my');
				$(e).prev().prev().prev().prev().addClass('my');
			},
			
			change: function(e) {
				if(mt.loggedIn) {
					var rating = $(e).attr('id').substring(4);
					mt.loader.show();
					$.ajax({
						type: 'GET',
						url: '/ajax/' + mt.current + '/rate/' + rating,
						dataType: 'json',
						success: function(data) {
							if(data) {
								var stars = '';
								for(i = 1; i <= 5; i ++) {
									var c = '';
									var r = parseFloat(data.rating);
									if(r == (i - 1) + .5) c = 'half';
									else if(r >= i) c = 'full';
									stars += '<span id="star' + i + '" class="' + c + '"></span>';
								}
								mt.mix.rating.original = stars;
								var s = rating == 1 ? '' : 's';
								$('#rating').html(stars).attr('title', 'You\'ve voted: ' + rating + ' star' + s);
								$('#rating span').mouseover(function() {
									mt.mix.rating.hover(this);					 
								}).click(function() {
									mt.mix.rating.change(this);
								});	
								var s = data.votes == 1 ? '' : 's';
								$('#votes').html(data.votes + ' vote' + s);
								mt.message('Thanks, your vote has been accounted for!', 'Rating Saved');
								mt.loader.hide();
							}
						},
						error: function(e1, e2, e3) {
							mt.error(e1, e2, e3);
						}
					});
				}
				else {
					mt.login('Rating');	
				}
			}		
		}
	},
	
	add: function(user) {
		$.get('/ajax/add/' + user, function(data) {
			mt.popup.open(data, 'Add ' + user, 500, 300);
			$('#add-follow').click(function() {
				if(user) {
					$('#add-to-loading').show();
					$.ajax({
						type: 'GET',
						url: '/ajax_twitter/follow/' + user,
						success: function(data) {
							if(data == 'true') {
								mt.message('You are now following ' + user + '!', 'Follow');
							}
						},
						error: function(e1, e2, e3) {
							mt.error(e1, e2, e3);
						}
					});	  
				}
				return false;							
			});
			$('#add-to-mix ul li a').click(function() {
				if($(this).hasClass('add-to-new')) {
					mt.mix.create($('#add-username').html());
				}
				else {
					$('#add-to-loading').show();
					var href = $(this).attr('href');
					var title = $(this).html();
					var mix = href.substring(href.lastIndexOf('/') + 1);
					var val = user;
					mt.loader.show();
					$.ajax({
						type: 'POST',
						url: '/ajax/' + mix + '/friend/add',
						data: { 'friends': val },
						dataType: 'json',
						success: function(data) {
							mt.popup.close();
							if(data.successful.length == 1) {
								mt.message(val + ' has been added to ' + title + '.', 'Add');
								mt.poll();
							}
							else mt.addErrors(data);
							if(mt.current == mix) {
								mt.mix.load();
							}
							mt.loader.hide();
						},
						error: function(e1, e2, e3) {
							mt.error(e1, e2, e3);
						}
					});						
				}
				return false;
			});
		});
	},

	addErrors: function(data) {
		var errors = '';
		if(data.unsuccessful.length) {
			errors += 'The following people could not be added:<br />';
			$.each(data.unsuccessful, function(i) {
				errors += this;
				if(i != data.unsuccessful.length - 1) errors += ', ';
				else errors += '<br />';
			});
		}
		if(data.overtally.length) {
			if(errors.length) errors += '\n\n';
			errors += 'You\'ve reached the maximum per list. The following people could not be added:<br />';
			$.each(data.overtally, function(i) {
				errors += this;
				if(i != data.overtally.length - 1) errors += ', ';
				else errors += '<br />';
			});
		}
		if(errors.length) {
			mt.message(errors, 'Add');
			mt.loader.hide();
		}
	},

	status: function(el, t, m) {
		var title = 'Status Update';
		var button = 'Update';
		var m = m || '';
		if(t == 'retweet') {
			title = 'Retweet';
			button = 'Retweet';
		}
		if(t == 'reply') {
			title = 'Reply';
			button = 'Reply';
		}
		if(t == 'suggest') {
			title = 'Suggest Someone';
			button = 'Suggest';
		}
		if(mt.loggedIn) {
			$.get('/_modules/user/templates/ajax_status.php', function(data) {
				mt.popup.open(data, title);
				if(t != 'tweet') {
					$('#tweet-submit').html(button);
					var rt = t == 'retweet' ? 'RT ' : '';
					var txt = $(el).parent().parent().parent().find('.message') || '';
					var msg = t == 'retweet' ? txt.html() : '';
					msg = msg.replace(/<a [^>]*?>/gi, '');
					msg = msg.replace(/<\/a>/gi, '');
					msg = msg.replace(/<span>/gi, '');
					msg = msg.replace(/<\/span>/gi, '');
					if(t == 'suggest') msg = 'Suggestion for "' + $('#mix-title span').html()
					+ '" (http://mixtweet.com/' + mt.current + '): @';
					var user = $(el).attr('href').substring($(el).attr('href').lastIndexOf('#') + 1);
					$('#tweet-message').val(rt + '@' + user + ' ' + msg).focus();
				}
				else $('#tweet-message').val(m).focus();
				$('#tweet-submit').click(function() {
					if(!$(this).hasClass('button-disabled')) {						  
						$(this).addClass('button-disabled');
						var id = $(el).parent().parent().parent().parent().attr('id').substring(4);
						var postdata = new Object();
						postdata.status = $('#tweet-message').val();
						if(t == 'reply') postdata.in_reply_to_status_id = id;
						$.ajax({
							type: 'POST',
							url: '/ajax_twitter/status',
							data: postdata,
							dataType: 'text',
							success: function(data) {
								if(data == 'true') {
									mt.popup.close();
								}
								else mt.message(data, 'Problem');
							},
							error: function(e1, e2, e3) {
								mt.error(e1, e2, e3);
							}
						});
					}
					return false;
				});
				var charCount = setInterval(function() {
					if($('#chars-left').length) {
						var len = $('#tweet-message').val().length;
						if(len > 140) $('#chars-left').addClass('warn');
						else $('#chars-left').removeClass('warn');
						$('#chars-left').html(140 - len);
					}
					else clearInterval(charCount);
				}, 100);
			});	
		}
		else {
			mt.login(title);	
		}
	},
	
	tweepsearch: function(query, count) {
		var url = 'http://tweepsearch.com/search.json?query=' + query + '&page=1&count=' + count + '&callback=?';
		$.getJSON(url, function(data) {
			var content = '<ul>';
			$.each(data, function(i, user) {
				var img = user['profile_image_url'].replace('_normal', '_mini');
				var link = 'http://twitter.com/' + user['screen_name'];
				var desc = '';
				if(user['description']) {
					desc = user['description'].replace(/(<span class\=\"match\">|<\/span>)/gi, '');
				}
				desc = desc.replace(/\"/gi, '\"'); 
				content += '<li><a href="' + link + '" title="'
				+ desc + '" target="_blank" class="people-img user-sm"><img src="'
				+ img + '" alt="" height="24" width="24"><span class="corners"><span title="Add"></span></span>'
				+ '</a><a href="' + link + '" title="' + desc + '" target="_blank" class="people-link">'
				+ truncate(user['screen_name'], 10) + '</a></li>';
			});
			content += '</ul>';
			$('#user-list').html(content);
		});
	},
	
	error: function(e) {
		if(e.status == 500 && e.statusText) { 
			mt.message(e.statusText, 'Problem');
		}
		//else throw(e);
		mt.loader.hide();
	},
	
	alertTime: null,
	
	alert: function(msg, timeout) {
		if(mt.alertTime) clearTimeout(mt.alertTime);
		var msg = '<p><a href="#" class="close"></a> ' + msg + '</p>';
		if(!$('#alert').length) {
			$('#content').prepend('<div id="alert"></div>');
			$('#alert').html(msg).fadeIn();
		}
		else {
			$('#alert').html(msg);
		}
		if(timeout) {
			mt.alertTime = setTimeout(function() {
				$('#alert a.close').trigger('click');
				mt.alertTime = null;
			}, timeout);
		}
	},
	
	message: function(message, title) {
		title = title || 'Message';
		if(message) {
			var height = 130 + (Math.ceil(message.length / 70) * 20);
			var content = '<p class="center">' + message + '</p><p style="padding-left:185px">'
			+ '<a href="#" class="button-single popup-close">OK</a></p>';
			mt.popup.open(content, title, 500, height);
			mt.loader.hide();
		}
	},

	prompt: function(message, title, action) {
		message = message || '';
		title = title || '';
		var height = 130 + (Math.ceil(message.length / 70) * 20);
		var content = '<p class="center">' + message + '</p><p style="padding-left:132px">'
		+ '<a href="#" id="popup-prompt-yes" class="button-single" style="margin-right:10px">Yes</a> '
		+ '<a href="#" class="button-single popup-close">No</a></p>';
		mt.popup.open(content, title, 500, height);
		$('#popup-prompt-yes').click(function() {
			if(action) setTimeout(action, 1);
			mt.popup.close();
			return false;									 
		});
		mt.loader.hide();
	},

	login: function(title) {
		title = title || 'Login';
		var content = '<p class="center">Please login with your twitter account, then try again.</p>'
		+ '<p style="padding-left:132px"><a href="/login" id="login-button" class="button-single"'
		+ 'style="margin-right:10px">Login</a><a href="#" class="button-single popup-close">Cancel</a></p>';
		mt.popup.open(content, title, 500, 150);
		mt.loader.hide();
	},
	
	popup: {
		open: function(html, title, width, height) {
			html = html || '';
			title = title || '';
			width = width || 500;
			height = height || 250;
			var padding = 13;
			var tmp = '<div id="popup"><div id="popup-t"><div id="popup-tl"></div><div id="popup-tm"></div>'
			+ '<div id="popup-tr"></div></div><div id="popup-m"><div id="popup-ml"></div><div id="popup-content">'
			+ '<div id="popup-title"><span>' + title + '</span><a href="#" id="popup-close"></a></div>'
			+ html + '</div><div id="popup-mr"></div></div><div id="popup-b"><div id="popup-bl"></div>'
			+ '<div id="popup-bm"></div><div id="popup-br"></div></div></div>';
			mt.popup.close();
			$(document.body).prepend(tmp);
			$('#popup').width(width);
			$('#popup').height(height);
			$('#popup-tm').width(width - (padding * 2));
			$('#popup-content').width(width - (padding * 2));
			$('#popup-bm').width(width - (padding * 2));
			$('#popup-ml').height(height - (padding * 2));
			$('#popup-content').height(height - (padding * 2));
			$('#popup-mr').height(height - (padding * 2));
			$('#popup-close').add('.popup-close').click(function() {
				mt.popup.close();
				return false;											 
			});
			mt.popup.center();
			$(window).resize(mt.popup.center);
			$('#popup').show();
			$('#popup input[type=text]').eq(0).focus();
		},
		
		close: function() {
			$('#popup').remove();
			$(window).unbind('resize', mt.popup.center);
		},
		
		center: function() {
			var p = $('#popup');
			var t = ($(window).height() / 2) - (p.height() / 2);
			var l = ($(window).width() / 2) - (p.width() / 2);
			p.css({top: t, left: l});
		}
		
	},
	
	embed: function() {
		mt.temp = {};
		mt.temp.sizes = [[390, 170], [200, 300]];
		mt.temp.settings = {
			id: mt.current,
			width: 390,
			height: 170,
			effect: null,
			delay: null,
			color: ''
		};
		mt.temp.generateCode = function() {
			var c = mt.temp.settings.color == 'custom' ? $('#custom').val() : mt.temp.settings.color;
			if(c.length < 6) c = '';
			var url = 'http://mixtweet.com/flash/mixtweet.swf';
			var effect = mt.temp.settings.effect ? '&effect=' + mt.temp.settings.effect : '';
			var delay = mt.temp.settings.delay ? '&delay=' + mt.temp.settings.delay : '';
			var color = c ? '&color=' + c : '';
			var urlstring = url + '?id=' + mt.temp.settings.id + effect + delay + color;
			var code = '<object width="' + mt.temp.settings.width + '" height="' + mt.temp.settings.height + '">'
			+ '<param name="movie" value="' + urlstring + '"></param>'
			+ '<param name="allowscriptaccess" value="always"></param>'
			+ '<param name="wmode" value="transparent"></param>'
			+ '<embed src="' + urlstring + '" type="application/x-shockwave-flash" '
			+ 'allowscriptaccess="always" wmode="transparent" width="'
			+ mt.temp.settings.width + '" height="' + mt.temp.settings.height + '"></embed></object>';
			$('#code').val(code);
			$('#preview-area').html($('#code').val());
		}
		$('input[name=setting-size]').click(function() {
			mt.temp.settings.width = mt.temp.sizes[$(this).val()][0];
			mt.temp.settings.height = mt.temp.sizes[$(this).val()][1];
			mt.temp.generateCode();
			this.blur();
		});
		$('input[name=setting-effect]').click(function() {
			mt.temp.settings.effect = $(this).val();
			mt.temp.generateCode();
			this.blur();
		});
		$('input[name=setting-delay]').click(function() {
			mt.temp.settings.delay = $(this).val();
			mt.temp.generateCode();
			this.blur();
		});
		$('a.setting-color').click(function() {
			mt.temp.settings.color = $(this).html();
			$('#setting-color-custom').show();
			$('#custom-color').hide();
			mt.temp.generateCode();
			this.blur();
			return false;
		});
		$('#setting-color-custom').click(function() {
			mt.temp.settings.color = 'custom';
			$(this).hide();
			$('#custom-color').show();
			mt.temp.generateCode();
		});
		$('#custom').keyup(function() {
			if($(this).val().length == 6) mt.temp.generateCode();
		}).blur(function() {
			mt.temp.generateCode();
		});
		$('#code').click(function() {
			$(this).focus();
			this.select();	
		});
		mt.temp.settings.width = mt.temp.sizes[0][0];
		mt.temp.settings.height = mt.temp.sizes[0][1];
		mt.temp.settings.effect = null;
		mt.temp.settings.delay = null;
		mt.temp.settings.color = '';
		$('#custom-color').hide();
		$('#preview-area').html('');
		setTimeout('mt.temp.generateCode()', 200);

	},
	
	loader: {
		show: function() {
			if(!$('#loading').length) {
				$(document.body).prepend('<img src="/images/loading.gif" '
				+ 'width="15" height="15" id="loading" />');
				$('#loading').css({
					position: 'absolute',
					zIndex: 9999,
					visibility: 'hidden'
				});
				$(document.body).mousemove(mt.loader.move);
				$(document.body).scroll(mt.loader.tempHide);
				$(window).scroll(mt.loader.tempHide);
			}
		},
		
		hide: function() {
			if($('#loading').length) {
				$(document.body).unbind('mousemove', mt.loader.move);
				$(document.body).unbind('scroll', mt.loader.tempHide);
				$(window).unbind('scroll', mt.loader.tempHide);
				$('#loading').remove();
			}
		},
		
		tempHide: function() {
			$('#loading').css({
				visibility: 'hidden'				 
			});
		},
		
		move: function(evt) {
			var top = evt.pageY + 15;
			var left = evt.pageX + 15;
			$('#loading').css({
				top: top,
				left: left,
				visibility: 'visible'
			});
		}
	}

}

function truncate(str, len) {
	return (str.length > len) ? str.substring(0, len) + '&hellip;' : str;
}