var comment_char_count = 5000;

function submit_comment(e) {
	if($F('new_comment').blank()) return alert('You must enter a comment!');

	$(e).disabled = true;
	new Ajax.Request(site_url + 'home/submit_comment/', {
		parameters:	{
			comment: $F('new_comment'),
			fk_music_id: fk_music_id
		}, 
		onSuccess: function(transport) {
			if(isNaN(transport.responseText)) {
				errors = $H(transport.responseText.evalJSON());
				errors.each(function(s){ $(s.key).innerHTML = s.value });
			} else {
				refresh_comments();
				$(e).innerHTML = "Comment Posted";
			}			
		}
	});
}

function show_reply (e) {
	Effect.toggle($(e).up().next(3), 'blind');	
}

function reply(e, id) {
	if($F($(e).previous(1)).blank()) return alert('You must enter a comment!');
	
	$(e).disabled = true;
	new Ajax.Request(site_url + 'home/submit_comment/', {
		parameters:	{
			comment: $F($(e).previous(1)),
			fk_music_id: fk_music_id,
			fk_parent_id: id
		}, 
		onSuccess: function(transport) {
			if(isNaN(transport.responseText)) {
				errors = $H(transport.responseText.evalJSON());
				$(e).previous().innerHTML = errors.get('comment_error');
			} else refresh_comments();		
		}
	});
}

function delete_comment(comment_id) {
	new Ajax.Request(site_url + 'home/delete_comment/' + comment_id, {
		onSuccess: function(transport) {
			if(!isNaN(transport.responseText)) refresh_comments();
		}
	});
}

function refresh_comments() {
	new Ajax.Updater('comments', site_url + 'home/get_comments/' + fk_music_id);
}

function comment_onkeyup(e) {
	if($(e).next(2).innerHTML == 'Register') return;
	if($F(e).length > comment_char_count) $(e).value = $F(e).substr(0, comment_char_count);
	e.next(2).innerHTML = comment_char_count - $F(e).length;
}

jQuery(function() {

	var new_playlist = jQuery('#new_playlist').validate({
		rules: {
			playlist_name: 'required'
		}
	});

	jQuery('#new_playlist_modal').dialog({
		title: 'New Playlist',
		autoOpen: false,
		modal: true,
		buttons: {
			Cancel: function() {
				jQuery(this).dialog('close');
			},
			OK: function() {
				if(new_playlist.form()) {
					jQuery.ajax({
						type: 'post',
						url: 'playlist/add_to_playlist/' + fk_music_id,
						data: {
							playlist_name: jQuery('#playlist_name').val()
						},
						success: function() {
							jQuery('#new_playlist_modal').dialog('close');
							refreshPlaylists();
						}
					});
				}
			}
		}
	});

	jQuery('#playlist_id').live('change', function() {
		if(jQuery(this).val() == '') {
			return;
		} else if(jQuery(this).val() == 'new') {
			jQuery('#new_playlist_modal').dialog('open');
			jQuery('#playlist_id').val('');
		} else {
			jQuery.get('playlist/add_to_playlist/' + fk_music_id + '/' + jQuery(this).val(), refreshPlaylists);
		}
	});

	refreshPlaylists();

});

function refreshPlaylists()
{
	jQuery('#playlists').load('playlist/view_widget/' + fk_music_id);
}
