var song_title_height = 54;
var main_div_width = 700;

$(function() {
	// Page fade in
	$('body').hide().delay('1000').fadeIn('5000');
	// Apply tablesorter
	$('table#song_list').tablesorter();
	// Apply lazyloader
	/*$("img").lazyload({
		placeholder:'images/default_thumb.jpg',
		effect:'fadeIn'
	});*/
	//show_artist_thumbs();
	bind_main_controls();
	// Tooltips
	bind_tooltips('.tip');
});

function bind_main_controls() {
	// refresh thumbs link - disabled
	bind_refresh_thumbs();
	// view playlists
	bind_view_playlists();
	// song list controls
	bind_song_list_controls();
	// login button
	bind_login_button();
	// logout button
	bind_logout_button();
	bind_mobile_button();
	bind_normal_button();
}

function bind_song_list_controls() {
	// song title bar clicks
	bind_song_rows();
	// add song link
	bind_open_add_song();
	// bind star ratings
	bind_star_ratings();
	// close page components when sorting table
	bind_sort_links();
	// artist thumbnail buttons
	bind_artist_info_popups();
}

function bind_song_controls(id) {
	bind_focus_song(id, 'tr#title_' + id + ' td.link');
	bind_edit_song('a#edit_' + id);
	bind_close_song('a#close_' + id);
	bind_split_pane('a#split_' + id);
	bind_open_add_to_playlist('a#add_to_playlist_' + id);
	bind_smaller(id);
	bind_bigger(id);
}

function bind_sort_links() {
	// Close page components before sorting table - avoids components being incorrectly sorted
	$('th.header').live('click', function() {
		close_page_components();
	});
}

function update_table_data() {
	$('table#song_list').trigger("update");
}

function close_page_components() {
	update_page_title();
	// remove playlist menu
	remove_component('div#playlists');
	// remove login bar
	remove_component('div#login');
	// remove content rows
	remove_component('tr.content');
	// remove edit rows
	remove_component('tr.edit');
	// remove add song form
	remove_component('div.song_form');
}

// Unused..
function show_artist_thumbs() {
	$('td.thumb').each(function(index) {
		var id = $(this).parents('tr.title').attr('id');
		var id = id.split('_');
		var id = id[1];
		var artist = $(this).children('input').val();
		$.ajax({
			url: 'ajax.php',
			data: {
				action:'show',
				section:'artist_thumb',
				artist:artist
			},
			success: function(data)
			{
				if (data)
				{
					$('tr#title_' + id + ' td.thumb').html('<img src="' + data + '"/>');
				}
			}
		});
	});
}

function bind_split_pane(id) {
	$(id).click(function()
	{
		$(this).unbind();
		var id = $(this).attr('id');
		var id = id.split('_');
		var id = id[1];
		
		//$('div#song_wrapper').height('');
		// Get window height
		var height = $(window).height();
		//console.log(height);
		//auto_increase_font_size(id, height);
		// Get div width & set new width to half
		var width = $('div#main').css('width');
		var new_width = width.replace('px','')*2 + 'px';
		$('div#main').css('width','98%');
		// Insert a load of line returns to allow scroll
		$('tr#song_' + id + ' td div pre').append('\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n');
		// Clone the div and float them left + right
		$('tr#song_' + id + ' td div')
			//.delay(6000)
			.attr('id','left')
			.css('overflow-x','hidden')
			//.css('height',height-70)
			.css('width','50%')
			.css('float','left')
			.clone()
			.appendTo('tr#song_' + id + ' td')
			.attr('id','right')
			.scrollTop(height-70);
		// Scroll the right div down to the page height minus 60 -has the effect of starting at the end of the left div
		$('tr#song_' + id + ' td div#left')
			.css('overflow','hidden');
	});
}

function bind_open_add_to_playlist(id) {
	$(id).click(function()
	{
		$(this).unbind();
		var id = $(this).attr('id');
		var id = id.split('_');
		var id = id[3];
		open_add_to_playlist(id);
	});
}

function open_add_to_playlist(id) {
	$.ajax({
		url: 'ajax.php',
		data: {
			action:'show',
			section:'add_to_playlist',
			id:id
		},
		success: function(data)
		{
			$('tr#controls_' + id).after(data).hide().next().hide().fadeIn('slow');
			create_add_to_playlist_bindings(id);
			bind_close_add_to_playlist(id);
			bind_open_create_playlist(id);
		}
	});
}

function bind_close_add_to_playlist(id) {
	$('tr#add_to_playlist_' + id).find('a#close_add_to_playlist').click(function() {
		$('tr#add_to_playlist_' + id).remove();
		bind_open_add_to_playlist('a#add_to_playlist_' + id);
		$('tr#controls_' + id).fadeIn('slow');
	});
}

function bind_open_create_playlist(id) {
	$('tr#add_to_playlist_' + id).find('a#create_new_playlist').click(function() {
		var new_playlist_html = '<input id="new_playlist" type="text"> '
		$(this).unbind()
			.text('Create Playlist')
			.before(new_playlist_html)
			.prev()
			.css('font-size','7pt');
		bind_create_playlist(id);
	});
}

function bind_create_playlist(id) {
	$('tr#add_to_playlist_' + id).find('a#create_new_playlist').click(function()
	{
		var playlist = $('tr#add_to_playlist_' + id).find('input#new_playlist').val();
		if (!playlist) {
			// Do not allow empty playlist name
			return false;
		}
		$(this).unbind();
		var link = $(this);
		
		$.ajax({
			url: 'ajax.php',
			data: {
				action:'save',
				section:'create_playlist',
				playlist:playlist
			},
			success: function(data)
			{
				if (data == 'success') {
					$('tr#add_to_playlist_' + id).remove();
					open_add_to_playlist(id)
				}
			}
		});
	});
}

function bind_add_to_playlist(id) {
	$('tr#add_to_playlist_' + id).find('a.add_to_playlist').click(function()
	{
		$(this).unbind();
		var link = $(this);
		var playlist_id = $(this).attr('id');
		var playlist_id = playlist_id.split('_');
		var playlist_id = playlist_id[1];
		
		$.ajax({
			url: 'ajax.php',
			data: {
				action:'save',
				section:'add_to_playlist',
				id:id,
				playlist_id:playlist_id
			},
			success: function(data)
			{
				if (data == 'success') {
					$(link).removeClass('add_to_playlist').addClass('remove_from_playlist');
					recycle_add_to_playlist_bindings(id);
				}
			}
		});
	});
}

function bind_remove_from_playlist(id) {
	$('tr#add_to_playlist_' + id).find('a.remove_from_playlist').click(function()
	{
		$(this).unbind();
		var link = $(this);
		var playlist_id = $(this).attr('id');
		var playlist_id = playlist_id.split('_');
		var playlist_id = playlist_id[1];
		
		$.ajax({
			url: 'ajax.php',
			data: {
				action:'save',
				section:'remove_from_playlist',
				id:id,
				playlist_id:playlist_id
			},
			success: function(data)
			{
				if (data == 'success') {
					$(link).addClass('add_to_playlist').removeClass('remove_from_playlist');
					recycle_add_to_playlist_bindings(id);
				}
			}
		});
	});
}

function recycle_add_to_playlist_bindings(id) {
	clear_add_to_playlist_bindings(id);
	create_add_to_playlist_bindings(id);
}

function clear_add_to_playlist_bindings(id) {
	$('tr#add_to_playlist_' + id).find('a.remove_from_playlist').unbind();
	$('tr#add_to_playlist_' + id).find('a.add_to_playlist').unbind();
}

function create_add_to_playlist_bindings(id) {
	bind_add_to_playlist(id);
	bind_remove_from_playlist(id);
}

function bind_star_ratings() {
	$('tr.title td.rating ul li a').live('click', function()
	{
		bind_star_rating(this);
	});
}

function bind_star_rating(link) {
	rating = $(link).parent('li').attr('title');
	var id = $(link)
		.parents('tr.title')
		.attr('id');
	var id_parts = id.split('_');
	var id = id_parts[1];
	star_rating = $(this).parents('ul.star_rating');
	$.ajax({
		url: 'ajax.php',
		data: {
			action:'save',
			section:'rating',
			id:id,
			rating:rating
		},
		success: function(data)
		{
			if (data == 'success')
			{
				rating_width = rating*20;
				$('tr#title_' + id + ' td.rating ul b.hidden_rating')
					.html(rating)
					.parent('ul')
					.children('li.current-rating')
					.width(rating_width);
				update_table_data();
			}
		}
	});
}

function bind_focus_song(id, elem) {
	$(elem).click(function()
	{
		$.scrollTo('tr#title_' + id, 800);
	});
}

function bind_edit_song(elem) {
	$(elem).click(function()
	{
		// remove add/edit song dialogs if present
		close_page_components();
		
		var id = $(this).attr('id');
		var id_parts = id.split('_');
		var id = id_parts[1];
		
		$.scrollTo('tr#title_' + id, 600);
		
		$.ajax({
			url: 'ajax.php',
			data: {
				action:'show',
				section:'edit_song_form',
				id:id
			},
			success: function(data)
			{
				// remove the song content
				remove_component('tr#song_' + id + '.content');
				//$('tr#song_' + id + '.content').remove();
				// insert new row with edit form
				$('tr#controls_' + id).after('<tr class="edit" id="edit_' + id + '"><td colspan="5">' + data + '</td></tr>');
				bind_update_song(id);
				bind_finish();
				bind_get_url();
			}
		});
	});
}

function bind_close_song(elem) {
	$(elem).click(function()
	{
		update_page_title();
		
		var id = $(this).attr('id');
		var id_parts = id.split('_');
		var id = id_parts[1];
		
		remove_component('tr#controls_' + id);
		/*$('tr#controls_' + id).fadeOut('800', function() {
			$(this).remove();
		});*/
		remove_component('tr#add_to_playlist_' + id);
		/*$('tr#add_to_playlist_' + id).fadeOut('800', function() {
			$(this).remove();
		});*/
		remove_component('tr#song_' + id);
		/*$('tr#song_' + id).fadeOut('800', function() {
			$(this).remove();
		});*/
		remove_component('tr#edit_' + id);
		/*$('tr#edit_' + id).fadeOut('800', function() {
			$(this).remove();
		});*/
		$('div#main')
			.css('width',main_div_width + 'px')
			.slideDown('slow');
		//bind_song_row(id);
		// scroll to the row
		var scroll_here = $('tr#title_' + id + ' td.artist');
		$.scrollTo(scroll_here);
	});
}

function bind_song_rows() {
	var links = $('tr.title td.link');
	$(links).live('click', function() {
		var id = $(this).parent('tr.title').attr('id');
		var id_parts = id.split('_');
		var id = id_parts[1];
		if ($('tr#song_' + id).length == 0)
		{
			close_page_components();
			open_song(this);
			//$(this).parent('tr').children('td.link').unbind();
		}
		else
		{
			$('tr#song_' + id).scrollTo('300');
		}
	});
}
/*
function unbind_song_rows() {
	var links = $('tr.title td.link');
	$(links).unbind();
}

function bind_song_row(id) {
	var links = $('tr#title_' + id + '.title td.link');
	$(links).click(function()
	{
		$.scrollTo(this, 600);
		open_song(this);
		$(links).unbind();
	});
}
*/
function open_song(td) {
	var title_row = $(td).parent('tr.title');
	var id = $(td).parent('tr.title').attr('id');
	var id_parts = id.split('_');
	var id = id_parts[1];
	var artist = $(title_row).children('td.artist').text();
	var title = $(title_row).children('td.title').text();
	
	update_page_title(artist + ' - ' + title);
	
	$.ajax({
		url: 'ajax.php',
		data: {
			action:'show',
			section:'song',
			id:id
		},
		success: function(data)
		{
			$(title_row).after(data).next().next().hide().fadeIn('slow', function()
			{
				var height = $(window).height();
				// Auto increase font size to fit
				auto_increase_font_size(id, height);
				// Set div height to window minus 50px for title & subtitle
				$('div.song_wrapper').css('height',height-song_title_height + 'px');
				// Scroll to the title
				$.scrollTo('tr#title_' + id, 600);
				// link bindings
				bind_song_controls(id);
			});
		}
	});
}

function auto_increase_font_size(id, max_height) {
	var max_increments = 5;
	var div_height = $('div.song_wrapper').height() + 50;
	var count = 0;
	while (div_height < max_height && count < max_increments) {
		//console.log('div:' + div_height + ' max:' + max_height + ' count:' + count + '/' + max_increments);
		increase_song_font_size(id);
		var div_height = $('div.song_wrapper').height() + 50;
		count++;
	}
}

function bind_smaller(id) {
	$('a#smaller_' + id).click(function()
	{
		var div = 'tr#song_' + id + ' td div';
		var font_size = $(div)
			.children('pre')
			.css('font-size');
		var font_size = font_size.replace('px','');
		var new_font_size = parseFloat(font_size) - 1;
		$(div).children('pre')
			.css('font-size',new_font_size);
	});
}

function bind_bigger(id) {
	$('a#bigger_' + id).click(function()
	{
		increase_song_font_size(id);
	});
}

function increase_song_font_size(id) {
	var div = 'tr#song_' + id + ' td div';
	var font_size = $(div)
		.children('pre')
		.css('font-size');
	var font_size = font_size.replace('px','');
	var new_font_size = parseFloat(font_size) + 1;
	$(div).children('pre')
		.css('font-size',new_font_size);
}

function show_add_song_form() {
	$.ajax({
		url: 'ajax.php',
		data: {
			action:'show',
			section:'add_song_form'
		},
		success: function(data)
		{
			$('table#header').after(data)
				.next()
				.hide()
				.fadeIn('300');
			bind_save_song();
			bind_finish();
			bind_get_url();
		}
	});
}

function show_song_row(id, replace) {
	$.ajax({
		url: 'ajax.php',
		data: {
			action:'show',
			section:'song_row',
			id:id
		},
		success: function(data)
		{
			if (replace) {
				$(replace).replaceWith(data);
			}
			else {
				$('table#song_list tbody').prepend(data);
			}
			bind_song_row(id);
			$('tr#title_' + id +' td.rating ul li a').click(function() {
				bind_star_rating(this);
			})
			update_table_data();
		}
	});
}

function bind_save_song() {
	$('div#add_song').find('button#save').click(function()
	{
		var artist = $('input#artist').val();
		var title = $('input#title').val();
		var content = $('textarea#content').val();
		var rating = $('select#rating').val();
		var tags = $('input#tags').val();
		$.ajax({
			url: 'ajax.php',
			data: {
				action:'save',
				section:'song',
				artist:artist,
				title:title,
				content:content,
				rating:rating,
				tags:tags
			},
			type: 'POST',
			success: function(data)
			{
				if (parseInt(data) > 0) {
					$('input#artist').val('');
					$('input#title').val('');
					$('textarea#content').val('');
					show_song_row(data, false);
				}
				else
				{
					// error
				}
			}
		});
	});
}

function bind_get_url() {
	$('button#get_url').click(function()
	{
		var artist = $('input#artist');
		var title = $('input#title');
		var content = $('textarea#content');
		var url = $('input#url').val();
		$.ajax({
			url: 'ajax.php',
			data: {
				action:'show',
				section:'from_url',
				url:url
			},
			dataType: 'json',
			success: function(data)
			{
				if (data) {
					$(artist).val(data.artist);
					$(title).val(data.title);
					$(content).val(data.song);
				}
			}
		});
	});
}

function bind_update_song(id) {
	var row = $('tr#edit_' + id);
	$(row).find('button#save').click(function()
	{
		var artist = $(row).find('input#artist').val();
		var title = $(row).find('input#title').val();
		var content = $(row).find('textarea#content').val();
		var tags = $(row).find('input#tags').val();
		$.ajax({
			url: 'ajax.php',
			data: {
				action:'update',
				section:'song',
				artist:artist,
				title:title,
				content:content,
				tags:tags,
				id:id
			},
			success: function(data)
			{
				if (data == 'success') {
					$(row).fadeOut('800',function() {
						var title_row = $('tr#title_' + id);
						remove_component('tr#controls_' + id + '.content');
						show_song_row(id, title_row);
					})
				}
				else
				{
					// error
				}
			}
		});
	});
}

function bind_open_add_song() {
	$('a#add').live('click', function()
	{
		if ($('div#add_song').length == 0) {
			close_page_components();
			show_add_song_form();
		}
		else
		{
			remove_component('div#add_song');
		}
	});
}

function bind_refresh_thumbs() {
	$('a#refresh_thumbs').click(function(e)
	{
		$('a#refresh_thumbs')
			.text('Please Wait......')
			.css('text-decoration','blink')
			.css('color','yellow');
		$.ajax({
			url: 'ajax.php',
			data: {
				action:'refresh_thumbs'
			},
			success: function(data)
			{
				location.reload();
			}
		});
	});
}

function bind_view_playlists() {
	$('a#view_playlists').live('click', function() {
		if ($('div#playlists').length == 0) {
			// show playlists div 
			$.ajax({
				url: 'ajax.php',
				data: {
					action: 'show',
					section: 'playlists'
				},
				success: function(data)
				{
					$('table#header').after(data).next().hide().fadeIn('slow');
					bind_playlist_links();
				}
			});
		}
		else
		{
			// hide playlists div
			remove_component('div#playlists');
		}
	});
}

function bind_login_button() {
	$('a#login').live('click', function() {
		if ($('div#login').length == 0)
		{
			// show login div
			$.ajax({
				url: 'ajax.php',
				data: {
					action: 'show',
					section: 'login'
				},
				success: function(data)
				{
					$('table#header').after(data).next().hide().fadeIn('slow');
					bind_login_control();
					// focus on loginid
					$('input#id').focus();
				}
			});
		}
		else
		{
			// hide login div
			remove_component('div#login');
		}
	});
}

function bind_login_control() {
	// loginid field
	$('input#id').live('keypress', function(e) {
		var code = (e.keyCode ? e.keyCode : e.which);
		if(code == 13) {
			// Enter pressed
			$('input#password').focus();
		}
	});
	// password field
	$('input#password').live('keypress', function(e) {
		var code = (e.keyCode ? e.keyCode : e.which);
		if(code == 13) {
			// Enter pressed
			submit_login();
		}
	});
	// login button
	$('button#login').click(function() {
		submit_login();
	});
}

function submit_login() {
	var login_id = $('input#id').val();
	var password = $('input#password').val();
	$.ajax({
		url: 'ajax.php',
		data: {
			action: 'login',
			login_id:login_id,
			password:password
		},
		dataType: 'json',
		success: function(data)
		{
			if (data.auth)
			{
				// Successfully logged in - reload page to get more links
				window.location.reload();
			}
			else
			{
				// Login failed
				$('div#login b#messages').text('Login Failed...');
				$('input#id').focus();
			}
		}
	});
}

function bind_logout_button() {
	$('a#logout').live('click', function() {
		$.ajax({
			url: 'ajax.php',
			data: {
				action: 'logout'
			},
			success: function(data)
			{
				window.location.reload();
			}
		});
	});
}

function bind_mobile_button() {
	$('a#mobile_theme').live('click', function() {
		$.ajax({
			url: 'ajax.php',
			data: {
				action: 'mobile_theme'
			},
			success: function(data)
			{
				window.location.reload();
			}
		});
	});
}

function bind_normal_button() {
	$('a#normal_theme').live('click', function() {
		$.ajax({
			url: 'ajax.php',
			data: {
				action: 'normal_theme'
			},
			success: function(data)
			{
				window.location.reload();
			}
		});
	});
}

function bind_playlist_links() {
	$('div#playlists a.playlist').click(function() {
		var id = $(this).attr('id');
		var playlist_id = id.split('_');
		var playlist_id = playlist_id[1];
		// remove bold from playlist links
		$('a.playlist').css('font-style','');
		// bold clicked playlist link
		$(this).css('font-style','italic');
		open_playlist(playlist_id);
	});
	$('div#playlists a#close').click(function() {
		close_playlists();
	});
}

function close_playlists() {
	bind_view_playlists();
	$('div#playlists').slideUp('slow');
	$('div#playlists').fadeOut('slow');
}

function open_playlist(id) {
	//close_playlists();
	$('table#song_list').fadeOut('slow');
	$.ajax({
		url: 'ajax.php',
		data: {
			action: 'show',
			section: 'playlist',
			id:id
		},
		success: function(data)
		{
			$('table#song_list').replaceWith(data);
		}
	});
}

function bind_finish() {
	$('a#close_form').click(function()
	{
		remove_component('div.song_form');
	});
}

function update_page_title(text) {
	if (text)
		document.title = 'Guitar Songbook: ' + text;
	else
		document.title = 'Guitar Songbook';
}

function bind_artist_info_popups() {
	$('div.artist_thumb').click( function() {
		$.scrollTo($(this).parent('td'), 1200);
		$(this).unbind();
		bind_remove_image(this);
		var artist = $(this).parent('td').siblings('td.artist').text();
		var top = this.offsetTop + 10;
		var left = this.offsetLeft + 30;
		$.ajax({
			url: 'ajax.php',
			data: {
				action:'get_artist_info',
				artist:artist
			},
			dataType: 'json',
			success: function(data)
			{
				if (data.image_url) {
					$('body').append(
						'<div class="popup"><img src="' + data.image_url + '"/>' +
						'<div class="summary">' + data.artist_summary + '</div></div>'
					);
					$('div.popup')
						.css('left',left + 'px')
						.css('top',top + 'px')
						.fadeIn(1000);
				}
			}
		});
	});
}

function bind_remove_image(thumb) {
	$(this).click(function() {
		remove_component('div.popup');
		$('.artist_thumb').unbind();
		bind_artist_info_popups();
	});
}

function get_artist_image_url(artist) {
	var url = 'ajax.php?action=get_artist_image_url&artist=' + artist;
	$.get(url, function(data) {
		image = data;
	});
	return image;
}

// Removes any element - set to fadeout
function remove_component(elem) {
	$(elem).fadeOut('800', function() {
		$(this).remove();
	});
}

function bind_tooltips(elem) {
	$(elem).live('mouseover mouseout', function(event) {
		if (event.type == 'mouseover')
		{
			this.t = this.title;
			this.title = '';
			$('div#tooltip')
				.html(this.t)
				//.css('display','block');
				.fadeIn(300);
		}
		else
		{
			this.title = this.t;
			$('div#tooltip')
				//.css('display','none');
				//.fadeOut(300);
				.hide();
		}
	});
}
