var songs = [];
var lyricId = undefined;

$(document).ready(function(){
	$.get('xml/songs.xml', function(data){
		songs = $(data).find('song');
		$('#suggest-input').focus(function(){ $(this).addClass('focused'); });
		$('#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-form').submit(function(){
		var found = false;
		var lyric = $('#suggest-input').val();
		songs.each(function(){
			if ($(this).find('lyric').text() == lyric) {
				lyricId = $(this).attr('id');
				found = true;
				return false;
			}
		})

		if (found) {
			voteBox = new Boxy($('#vote-box'), {
				modal: true, 
				title:'Resubmit Email Address',
				closeable:true
			});
		} else {
			$.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;
	});

	$('#vote-form').submit(function(){
		var email = $('#email').val();
		if (email == '') { $('#email').css('border', '1px solid #f00'); return false; }
		$.get('api/vote.php?src=home&email='+email+'&votes='+lyricId+'&r='+Math.random(), function(){
			document.location = 'index.php?r=' + Math.random() +  '#suggest-box';
		});
		return false;
	});
});
