/*
 @ChangeDate:	$LastChangedDate: 2009-03-18 17:52:54 +0000 (Wed, 18 Mar 2009) $
 @Revision:		$Rev: 171 $
 @Author: 		$Id: view.js 171 2009-03-18 17:52:54Z philippryce $
*/

$.fn.toolbar = function () {
	this.each(function () {		
		$('ul.rating').bind('mouseover', function () {
			$('.current-rating', this).stop().hide();
		}).bind('mouseout', function () {
			$('.current-rating', this).stop().show();
		});
		
		function showMessage (message) {
			$('.toolbarAction').stop().find('p').html(message).end().slideDown(600);
			setTimeout(hideMessage, 7000);
		}
		function hideMessage () {
			$('.toolbarAction').stop().slideUp(800);
		}
		
		function shareLyric () {
			var from = null;
			var to = $('#share_to', $('.window')).val();
			var custom = $('#share_custom', $('.window')).val();
			if ($('#share_from', $('.window')).length == 1) { from = $('#share_from', $('.window')).val(); }
			var post_data = {
				token: CI.uri.segment(3),
				to: to,
				from: from,
				custom: custom
			};
			$.postJSON('/json/emailTicket', post_data, function (json) {
				
				if (json.message) {
					$.popper({ title: 'Error sharing lyric', content: json.message });
					return;
				}
				$.popper({ title: 'Share this lyric', content: json.data.result });
			});
			
		}
		function closeShare () {
			$('.window input, .window textarea').val('');
			$('.window').fadeOut('fast');
		}
		
		$('a.bookmarkIcon', this).bind('click', function () {
			url = $(this).attr('href').split('/');
			token = url[3];
			
			$.postJSON('/json/bookmark', {token: token}, function (json) {
				if (json.status == "OK") {
					showMessage('You bookmarked this lyric. <a href="/user/bookmarks/'+json.data.user_name+'">View your bookmarks</a>');
				}
				else {
					showMessage(json.message);
				}
			});
			return false;
		});
		$('a.shareIcon', this).bind('click', function () {
			$.popper({
				title: 'Share this lyric',
				content: $('.shareForm', $('#view')).clone().show(),
				buttons: { 'Send': { onclick: shareLyric }, 'Cancel': {onclick: closeShare } }
			});
			return false;
		});
		$('ul.rating a', this).bind('click', function (e) {
			target = $(e.target);
			stars = target.text();
			url = target.attr('href').split('/');
			token = url[4];
			session = url[5];
			
			$.postJSON('/json/rate', {token: token, session: session, rating: stars}, function (json) {
				if (json.status == "OK") {
					showMessage('You rated this lyric ' + stars + ' stars.');
				}
				else {
					showMessage(json.message);
				}
			});
			
			return false;
		});
	});
};

$(function () {
	include('/javascript/common/tooltip.jquery.js');
	
	if (Loaded.tooltip) {
		$('.toolbar a').tooltip( { filterOut: '.rating a' } );
	}
	
	$('.toolbar').toolbar();
});