var page = 0;
var pages = 0;
var voteBox = null;
var embedBox = null;
var songs = [];
var songHTML = null;
var PAGE_SIZE = 10;

$(document).ready(function(){
  if ($.browser.msie) { $('body').addClass('ie'); }
	songHTML = $('#node').html();

	$.get('xml/songs.xml', function(data){
		songs = $(data).find('song');
		pages = Math.floor(songs.length / PAGE_SIZE);
		loadSongs();

		$('#drop-list').droppable({
			accept: ".drop",
			activeClass: 'droppable-active',
			hoverClass: 'droppable-hover',
			drop: function(ev, ui) {
				// only drop once
				if ($('#drop-list:has(#'+ui.draggable.attr('id')+')').length == 0) {
					if ($(this).children().length >= PAGE_SIZE) {
						var id = $('#drop-list li:last').attr('id');
						$('#drop-list li:last').remove();
						$('#' + id).removeClass('selected');
						$('#' + id).animate({opacity:'1'});
					}
					var d = ui.draggable.clone().appendTo($(this)).removeClass('drop');
					d.find('.add').hide();
					d.find('.remove').show();
					d.find('.remove').click(function(){
						var id = $(this).parent().attr('id');
						$(this).parent().remove();
						rerank();
						$('#' + id).removeClass('selected');
						$('#' + id).animate({opacity:'1'});
					});
					ui.draggable.addClass('selected');
					d.hide();
					d.fadeIn();
					rerank();
					ui.draggable.animate({opacity:'.2'});
				}
			}
		});
		$('#suggest-form').submit(function(){
			var children = $('#drop-list').children();
			var count = children.length;
			var add = $('#suggest-input').val();
			for (var i = 0; i < count; i++) {
				if (add == $(children[i]).attr('title')) {
					$.scrollTo('#drop-list #'+$(children[i]).attr('id'), 500);
//					new Boxy("<p>Check out your list. You've already added this lyric.</p>", {title: "Already added!", modal: true});
					return false;
				}
			}
			var lyric = $('#suggest-input').val();
			if (lyric != '') {
				$.get('api/submit_lyric.php?lyric='+escape(lyric));
				new Boxy("<p>Thanks. We'll add this lyric to our collection.</p>", {title: "Thank you!", modal: true});
			}
			return false;
		})
		$('#suggest-input').focus(function(){ $(this).addClass('focused'); });
		$('#suggest-input')
		$('#suggest-input').autocomplete({matchContains:true, max:5,
			formatResult:function(row) {
				var r = row[0].split('|');
				return r[0];
			},
			formatItem:function(row) {
				var r = row[0].split('|');
				return '<div class="lyric" title="'+r[0]+'">' + r[0] + '</div><div class="artist" title="'+r[1]+'"><span>as performed by </span>' + r[1] + '</div>';
			},
			data:songs.map(function(){
				return $(this).find('lyric').text() + '|' + $(this).find('artist').text() + '|' + $(this).attr('id');
			})
		});
		$('#suggest-input').autocomplete('result', function(event,data,formatted){
			var d = data + '';
			var r = d.split('|');
			if ($('#drop-list:has(#lyric_'+r[2]+')').length == 0) {
				if ($('#main-list:has(#lyric_'+r[2]+')').length == 0) {
					// create song
					$('#main-list').append(songHTML.replace(/{ID}/g, r[2]).replace('{RANK_CLASS}', '').replace('{RANK}', 0).replace(/{LYRIC}/g, r[0]).replace('{ARTIST}', r[1]));
					if ($('#main-list .title:last').height() > 18) {
						$('#main-list .title:last').height('16px').css('overflow', 'hidden');
					}
					$('#main-list .add:last').click(function(){
						if ($('#drop-list:has(#lyric_'+r[2]+')').length == 0) {
							if ($('#drop-list').children().length >= PAGE_SIZE) {
								var id = $('#drop-list li:last').attr('id');
								$('#drop-list li:last').remove();
								$('#' + id).removeClass('selected');
								$('#' + id).animate({opacity:'1'});
							}
							var d = $(this).parent().clone().appendTo($('#drop-list')).removeClass('drop');
							d.find('.add').hide();
							d.find('.remove').show();
							d.find('.remove').click(function(){
								var id = $(this).parent().attr('id');
								$(this).parent().remove();
								rerank();
								$('#' + id).removeClass('selected');
								$('#' + id).animate({opacity:'1'});
							});
							$(this).parent().addClass('selected');
							d.hide();
							d.fadeIn();
							rerank();
							$(this).parent().animate({opacity:'.2'});
						}
					});
				}
				sendOver('#lyric_' + r[2]);
			}
			$.scrollTo('#drop-list #lyric_' + r[2], 500);
		});
		setTimeout(simulate, 4000);
	});

	$('#vote-form').submit(function(){
		var email = $('#email').val();
		if (email == '') { $('#email').css('border', '1px solid #f00'); return false; }
		var votes = [];
		$('#drop-list').children().each(function(){
			votes.push($(this).attr('rel'));
		});
		voteBox.hide();
		$('#teaser-swf').hide();
		embedBox = new Boxy($('#embed-box'), {
			modal: true, 
			title:'Spread it!',
			closeable:true,
			afterHide:function () { $('#teaser-swf').show(); }
		});
		$.get('api/vote.php?email='+email+'&votes='+votes+'&r='+Math.random(), function(data){
			var embed = $(data).find('embed').text();
			if (embed != '') {
				$('#email').css('border', '1px solid #000');
				$('#widget').html(embed);
			} else {
				embedBox.hide();
				voteBox = new Boxy($('#vote-box'), {
					modal: true, 
					title:'Resubmit Email Address',
					closeable:true
				});
				$('#email').css('border', '1px solid #f00');
			}
		});
		return false;
	});

	$('#drop-list').sortable({stop:rerank});
	$('#scroll-up').click(function(){
		if (page > 0) {
			page--;
			loadSongs();
		}
	});
	$('#scroll-down').click(function(){
		if (page < pages) {
			page++;
			loadSongs();
		}
	});
	$('#save-button').click(function(){
		if ($('#drop-list').children().length >= 3) {
			voteBox = new Boxy($('#vote-box'), {
				modal: true, 
				title:'Make it count!',
				closeable:true
			});
		} else {
			new Boxy("<p>You must select at least <strong>3</strong> lyrics!</p>", {title: "Add a few more lyrics", modal: true});
		}
	});
	$('#instructions-image').click(simulate);
});

function loadSongs() {
	var listSongs = songs.slice(page*PAGE_SIZE, page*PAGE_SIZE+PAGE_SIZE);
	$('#main-list-container').addClass('load');
	$('#main-list').empty();
	listSongs.each(function(i){
		i = page*PAGE_SIZE + i;
		var c = '';
		if ( i >= 99 ) { c = 'rank-small'; }
		var s = $(this);
		var artist = s.find('artist').text();
		var lyric = s.find('lyric').text();
		// create song
		$('#main-list').append(songHTML.replace(/{ID}/g, s.attr('id')).replace('{RANK_CLASS}', c).replace('{RANK}', i+1).replace(/{LYRIC}/g, lyric).replace('{ARTIST}', artist));
		var last = $('#main-list .title:last');
		if (last.height() > 18) {
			last.height('16px').css('overflow', 'hidden');
			last.text(last.text().substring(0, 40)+'...');
		}
		$('#main-list .add:last').click(function(){
			if ($('#drop-list:has(#lyric_'+s.attr('id')+')').length == 0) {
				if ($('#drop-list').children().length >= PAGE_SIZE) {
					var id = $('#drop-list li:last').attr('id');
					$('#drop-list li:last').remove();
					$('#' + id).removeClass('selected');
					$('#' + id).animate({opacity:'1'});
				}
				var d = $(this).parent().clone().appendTo($('#drop-list')).removeClass('drop');
				d.find('.add').hide();
				d.find('.remove').show();
				d.find('.remove').click(function(){
					var id = $(this).parent().attr('id');
					$(this).parent().remove();
					rerank();
					$('#' + id).removeClass('selected');
					$('#' + id).animate({opacity:'1'});
				});
				$(this).parent().addClass('selected');
				d.hide();
				d.fadeIn();
				rerank();
				$(this).parent().animate({opacity:'.2'});
			}
		});

		if ($('#drop-list:has(#'+$('#main-list li:last').attr('id')+')').length > 0) {
			$('#main-list li:last').addClass('selected');
			$('#main-list li:last').animate({opacity:'.2'});
		}
	});
	$('#main-list-container').removeClass('load');
	$('#main-list li').draggable({helper:'clone'});
}

function rerank() {
	$('#drop-list .rank').each(function(i){
		$(this).text(i+1);
	})
}

function sendOver(selector) {
	$(selector + ' .add').click();
}

function simulate() {
	if (page == 0 && $('#drop-list:has(#'+$('.drop:first').attr('id')+')').length == 0 && $('#drop-list').children().length == 0) {
		$('#instructions-image').unbind('click');
		$('.drop:first').clone().appendTo('#main-list').css('position', 'relative').css('opacity', 0).animate({top: '-=410px'}, 0, 'linear', function(){$(this).css('opacity', 1)}).animate({left:'+=490px'}, 500, 'linear', function(){
			$(this).remove();
			sendOver('#' + $('.drop:first').attr('id'));
		});
		// timeout?
		$('#instructions-image').click(simulate);
	}
}
