/*
	Sri Chinmoy Songs site javascript
*/

var CKGSongs = function() 
{
	var kEmptyBookSearchPrompt = 'Search book title';
	var kEmptySongSearchPrompt = 'Search';


	function searchOnFocus(event)
	{
		if (this.value === event.data.emptyText)
			this.value = '';
		
		$(this).removeClass('empty');
	}


	function searchOnBlur(event)
	{
		if (this.value === '')
		{
			this.value = event.data.emptyText;
			$(this).addClass('empty');
		}
	}
	
	
	function observeCommentToggle()
	{
		var tog = $('#comment-toggle');
	
		if (tog.length)
		{
			tog.click(function() {
				var comments = $('#comments');
				var visible = comments.css('display') !== 'none';
				
				if (visible)
				{
					tog.text('Show comments');
					comments.fadeOut('fast');
				}
				else
				{
					tog.text('Hide comments');
					comments.fadeIn('fast');
				}
			});
		}
	}
	
	
	function observeSearchFields()
	{
		// Set up searchboxes
		var field = $('input.search');		
		field.bind('focus', { emptyText: kEmptySongSearchPrompt }, searchOnFocus);
		field.bind('blur', { emptyText: kEmptySongSearchPrompt }, searchOnBlur);
	}
	
	
	var RE_HYPHENATED = /(\w+-\w+\*?)/g;
	var RE_SEARCH_TERMS = /(".+?"|[\w\']+\*?)+/g;
	
	function observeSearch(formId, inputId, queryParam, url, allButtonId)
	{
		var form = $('#' + formId);
	
		if (form.length)
		{
			var doSearch = function(event)
			{
				var input = $('#' + inputId);
				var text = input.val();
				
				if (text && !input.hasClass('empty'))
				{
					// Split the search up into search terms.
					var terms = text.match(RE_SEARCH_TERMS);
					var query = '';
					
					for (var i = 0; i < terms.length; ++i)
						query += encodeURIComponent(terms[i]) + '+';
					
					// Trim trailing +
					query = query.substr(0, query.length - 1);
					window.location = url + '?' + event.data.queryParam + '=' + query;
					return false;
				}
			};
			
			form.bind('submit', { queryParam: queryParam }, doSearch);
			
			// NOTE: We had to wrap the button img in a span because IE6 won't generate
			// a click event on an img, but it will for a span wrapping it.			
			form.children('img.go').bind('click', { queryParam: queryParam }, doSearch);
			
			var all = $('#' + allButtonId);
			
			if (all.length)
			{
				all.bind('click', function(event) {
					window.location = url;
				});
			}
		}
	}
	
	
	// When the arrow starts, this is the left position where it starts
	// (relative to the table's left edge)
	var kHiliteArrowOffsetStartX = -35;
	
	// When the arrow is pointing where we want, this is the left position
	// (relative to the table's left edge).
	var kHiliteArrowOffsetEndX = -16;
		
	// How far we slide the hilite arrow when fading out
	var kHiliteArrowFadeOutX = 10;
	
	// How long the fade in should take in millis
	var kHiliteArrowFadeInDuration = 500;
	
	// How long the fade out should take in millis
	var kHiliteArrowFadeOutDuration = 250;
	
	
	function hiliteSong()
	{
		window.setTimeout(function() 
		{
			// If a song id was passed in a cookie, try to find the song and hilite it
			var id = $.cookies.get('hilite');
			
			if (id)
			{
				var song = $('#song_' + id);
	
				if (song.length)
				{
					// Find the relative offset and height of the song's row
					var tableOffset = song.parents('table.list').offset();
					var tableTop = tableOffset['top'];
					var tableLeft = tableOffset['left'];
					var row = song.parent();
					var rowTop = row.offset()['top'];
					var rowHeight = row.height();
					
					// Now show the arrow and position it vertically in the middle of the row
					// and horizontally back 20 pixels so we can slide into position.
					var arrow = $('#hilite-arrow');
					arrow.css({
						display: 'block',
						opacity: 0,
						top: rowTop + Math.round((rowHeight - arrow.height()) / 2),
						left: tableLeft + kHiliteArrowOffsetStartX
					})
					
					// Now slide it left to right with a bounce at the end and fade in
					.animate(
						{ 
							left: '' + (tableLeft + kHiliteArrowOffsetEndX) + 'px',
							opacity: 1
						}, 
						{
							duration: kHiliteArrowFadeInDuration,
							easing: 'easeOutBounce',
							complete: function()
							{
								// When we are done sliding in, wait 1.5 seconds
								setTimeout(function()
								{
									// After waiting, slide right and fade out
									arrow.animate({
										left: '+=' + 10 + 'px',
										opacity: 0
									}, kHiliteArrowFadeOutDuration);
								}, 1500);
							}
						}
					);
				}
					
				$.cookies.del('hilite');
			}
		}, 200);
	}
	
	
	/*
		Row mouseover/out handlers for lists. When a list row is moused over,
		hilite the row. When it is moused out, restore the normal background.
	*/
	var kRowHoverCSS = {
		'background-color': '#E8F3FF'
	};
	
	var kRowOutCSS = {
		'background-color': '#fff'
	};
	
	var currentListQtip = null;
	
	function initLists()
	{
		$('table.list>tbody')
			.children('tr')
			.not('tr.foot')
			.hover(onListOver, onListOut)
			.click(onListClick)
			.qtip({
				content: { text: 'Click to open this item' },
				
				style: { 
					name: 'cream', 
					tip: false,
					border: { width: 4 },
					color: '#555'
				},

				position: {
					target: 'mouse',
					corner: {
						target: 'mouse',
						tooltip: 'topLeft'
					},
					adjust: {
						x: 7,
						y: 5,
						screen: true
					}
				},
				
				show: {
					delay: 1000
				},
				
				api: {
					onShow: function() { currentListQTip = this; },
					onHide: function() { currentListQtip = null; }
				}		
			});
	}
	
	
	function onListOver()
	{
		$(this).children('td').css(kRowHoverCSS);
	}
	
	
	function onListOut()
	{
		$(this).children('td').css(kRowOutCSS);		
	}
	
	
	function onListClick(event)
	{
		// Make sure the qtip is hidden after a click
		if (currentListQtip)
			currentListQtip.hide();
			
		// Don't allow the current page to leave if a modifier is pressed.
		// This is so that Command-clicking in Safari/FF will open a new tab
		// without changing the list.
		if (event.ctrlKey || event.shiftKey || event.metaKey)
			return;
		
		// In the title cell of the row is a link to the item
		var url = $(this).find('.title a').attr('href');
		window.location = url;
	}
	
	
	function enableFormSubmitOnEnter()
	{
		$('input').keydown(function(e)
		{
			if (e.keyCode == 13)
			{
				$(this).parents('form').submit();
				return false;
			}
		});
	}
	
	function printSheetMusic()
	{
		// Add print=1 to the url
		var url = window.location;
		
		if (window.location.search.length > 0) {
		 	url += '&print=1';
		} else {
			url += '?print=1';
		}
		
		// Make a unique window name so we always get a new window.
		var name = 'print_' + (new Date().getMilliseconds());
		
		// Open a window that is 100px shorter than the screen height.
		var w = window.open(url, name, 
							'outerHeight=' + (screen.availHeight - 100) + ',' +
							'innerWidth=800,width=800' +
							'location=no,menubar=no,toolbar=yes,status=no,scrollbars=yes,resizable=no');
	}
	
	
	function initTooltips()
	{
		// Replace html title attributes with toolips
		$('[title]').qtip({ 
			style: { 
				name: 'cream', 
				tip: false,
				border: { width: 4 },
				color: '#555'
			},
			
			position: {
				corner: {
					target: 'bottomMiddle',
					tooltip: 'topMiddle'
				},
				adjust: {
					y: 7
				}
			},
			
			show: {
				delay: 700
			}
		});
		
		$('#search .help').qtip({
			content: { text: $('#search .search-help') },
			
			style: { 
				tip: false,
				width: 550,
				border: { 
					width: 0,
					color: '#777'
				},
				background: '#222',
				color: '#fff'
			},
			
			position: {
				corner: {
					target: 'bottomLeft',
					tooltip: 'topRight'
				},
				adjust: {
					y: 5,
					screen: true
				}
			}
		});
	}
		

	/*********************************
		MAIN
	**********************************/
	
	return {
		
		init: function()
		{
			// Turn off the no-javascript warning
			$('.no-javascript').hide();
			
			// Turn on corner rounding
			$('.rounded').corners();
			
			enableFormSubmitOnEnter();
			observeCommentToggle();
			observeSearchFields();
			observeSearch('search_form', 'qs', 'qs', '/song/list/', 'b_all_songs');
			initTooltips();
			
			switch (document.body.id)
			{
				case 'book-list':
				case 'book-view':
				case 'song-search':
					initLists();
					
					if (document.body.id === 'book-view')
						hiliteSong();
						
					break;
				
				case 'song-view':
					$('td.print').click(printSheetMusic);
					
					// Disable clicks on the score
					$('img.score')
						.bind('contextmenu', function() { return false; })
						.mousedown(function() { return false; });
					break;
					
				case 'song-print':
					$('#b_print').click(function() { window.print(); });
					break;
				
				default:
					// pass
			}
		},
		
		
		returnToBook: function(id)
		{
			// Set a cookie with the id of the song to hilite when we return to the book
			$.cookies.set('hilite', id);
		}
	};
}();

$(document).ready(CKGSongs.init);

