// Sam's scripts
// requires jquery
// common controls

// select

// CSS classes used
// ui-seavan-val
// ui-seavan-select
// ui-seavan-option
// ui-seavan-option-header
// ui-seavan-option-index
// ui-seavan-option-body
// ui-seavan-jsonControl


(function($){

	/*$.fn.valOld = $.fn.val;

    $.fn.val = function($param)  {
        if( $(this).hasClass('ui-seavan-val'))
        {
            if( $(this).getOpts().seavanVal )
            {
                return $(this).getOpts().seavanVal(this);
            }
            else
            {
                alert('no seavanVal present in opts');
            }
        }
        return $.fn.val($param);
    }*/

	jQuery.fn.outer = function() {
		return $( $('<div></div>').html(this.clone()) ).html();
	}

	$.fn.getOpts = function() {
		return $(this).data('opts');
	}

	$.fn.seavanSelect = function(opts) {
		opts.seavanVal = function(_ref) {
			alert('seavanVal called');
		}
		return $(this).jsonControl(opts).addClass('ui-seavan-val ui-seavan-select');
	}

	$.fn.jsonControl = function(opts) {
		if( !opts.getUpdateUrl && opts.update_url ) {
			opts.getUpdateUrl = function() {
				return opts.update_url;
			}
		}

		this.addClass('ui-seavan-jsonControl');

		return this.each( function() {
			
			$(this).data('opts', opts);

		});
	}

	$.fn.jsonUpdate = function(){
		return this.each( function() {

			var opts = $(this).getOpts();
			if(opts.getUpdateUrl)
			{
				callback = function(_data) {
					var $this = $(this);
					var opts = $this.getOpts();
					$this.empty();
					data = _data;
					if( data == null ) data = new Array();
					else
						data = _data.result;
					if( data == null ) data = new Array();
					if(opts.prebind) {
						opts.prebind(this, data);
					}

					for(i = 0; i < data.length; ++i)
					{
						if(opts.populateItem)
						{
							//$(this).append("<option>teset</option>");
							$this.append(opts.populateItem(this, data[i], i));
						}
						else
						{
							alert('no populateItem specified');
						}
					}

					if(opts.rebind) {
						opts.rebind(this, data);
					}
				};
				$.ajax({
					url: opts.getUpdateUrl(),
					dataType: 'json',
					data: null,
					context: this,
					success: callback
				});
			}
			else
			{
				alert('no getUpdateUrl specified');
			}
			return $();
		});
	};

})(jQuery);


function updatePlaylists()
{
	$('._playlists').jsonUpdate();
	$('._popup_playlist').jsonUpdate();
}

function addSelectedTrackToPlaylist(playlist_id)
{
	hidePopups();
	if(application.htmlSelectedTrack) {
		$.ajax({
			url: '/ajax/add_track_to_playlist/' + playlist_id + '/' + application.htmlSelectedTrack.track_id,
			success: function()
			{
				updatePlaylist(playlist_id);
			}
		});
	}
}

function deleteObject(_object)
{
	$.ajax({
		url: '/ajax/delete_object',
		type: 'get',
		dataType: 'text',
		data: {
			"id": _object
			//"title": _newTitle
		},
		success: function(data){
			updatePlaylist(data);
			hidePopups();
		}
	});
}



function updatePlaylist(playlist_id)
{
	//alert($('.ui-seavan-playlist[rel=' + playlist_id + ']').length);
	//alert($('.ui-seavan-playlist[rel=' + playlist_id + '] ').length);
	$('.ui-seavan-playlist[rel=' + playlist_id + '] .ui-seavan-playlist-tracks').jsonUpdate();
}

function enqueueObjectToNew(_objectId, _newTitleInput) {
	//alert(application.newPlaylist.length);
	_newTitle = _newTitleInput.val();
	if(!_newTitle.length) return;
	hidePopups();
	$.ajax({
		url: '/ajax/add_object_to_new',
		type: 'post',
		dataType: 'text',
		data: {
			"id": _objectId,
			"title": _newTitle
		},
		success: function(data){
			updatePlaylists();
			application.newPlaylist.val('');
		}
	});
}

function enqueueObjectTo(_what, _where) {
	hidePopups();
	$.ajax({
		url: '/ajax/add_object_to_playlist',
		type: 'get',
		dataType: 'text',
		data: {
			"what": _what,
			"where": _where
		},
		success: function(data){
			updatePlaylist(_where);
		}
	});
}

function renamePlaylist(playlist_id, newName)
{
	hidePopups();
	$.ajax({
		url: '/ajax/rename_playlist/' + playlist_id,
		type: 'post',
		data: { "newName": newName },
		context: this,
		success: function()
		{
			updatePlaylists();
		}
	});
}

function monitorEnter(event, object, func)
{
	if(event.keyCode == '13')
	{
		func(object);
		hidePopups();
		return false;
	}
	return true;
}

function hidePopups()
{
	$r = $('._popupActive');
	$r.removeClass('_popupActive');
	$r.hide();
}

function outerClickCheckerIn()
{
	$(document).bind('click', function(e) {
		application.hideCurrentPlaylist();
		var $clicked=$(e.target); // get the element clicked
		if($clicked.is('._popup') || $clicked.parents().is('._popup')) {
		}
		else {
			hidePopups();
			$('._popupRequest').addClass('_popupActive').removeClass('_popupRequest');
		}

	});
}

function outerClickCheckerOut()
{
	$(document).unbind('click');
}

function sendPlaylistOrder($playlist)
{
	//playlist_id = $playlist.attr('rel');
	tracks = new Array();
	
	$playlist.find('.ui-seavan-playlist-track').each(
	function(index, obj)
	{
		$obj = $(obj);
		$obj.find('.ui-seavan-option-index').html(index + 1);
		rel = $(obj).attr('rel');

		tracks.push( {
			'track_id': rel,
			'position': index
		});
			
	});
	$.ajax({
		url: '/ajax/update_track_order',
		type: 'post',
		dataType: 'json',
		data: {
			'request' : $.toJSON(tracks)
		}
	});
}

function createPlaylist()
{
	val = $('#new_playlist_title').val();
	if(!val.length) return;
	$('.create_playlist_div').hide();
	$.ajax({
		url: '/ajax/create_playlist',
		type: 'post',
		data: { title: val },
		context: this,
		success: function()
		{
			updatePlaylists();
		}
	});
}

