var CustomPlaylist = Class.create();
CustomPlaylist.prototype = {
	id: '',
	module_id: '',
	name: '',
	playlist: null,
  updated: null,
	topic_ids: null,
	
	initialize: function( s_id ){
		this.id = s_id;
	},
	
	// TODO: there seem to be problems "saving" with all topics included
	save: function( ){
		// whack the playlist to conserve cookie space
		this.playlist = null;
		this.updated = new Date().toLocaleString();
		CookieHelper.setCookie( ('cp' + this.id), escape(Object.toJSON(this)), 365, null );
	}
	
}; // end CustomPlaylist

CustomPlaylist.get_custom_playlists = function( ){
	var rv = [];
	var json_strings = CookieHelper.getCookieValues( /^cp.*/ );
	for( var i=0; i<json_strings.length; i++ ){
		var json = unescape( json_strings[i] );
		var o = json.evalJSON( true );
		// turn everything back into their actual objects...
		var cp = Object.extend( new CustomPlaylist(), o );
		// this bit is technically obsolete -- we now only save
		// the topic ids when we save to conserve cookie space
		if( cp.playlist ){
			cp.playlist = Object.extend( new Playlist(), cp.playlist );
			if( cp.playlist.topics ){
				var topics = [];
				for( var n=0; n < cp.playlist.topics.length; n++ ){
					topics.push( Object.extend(new Topic(), cp.playlist.topics[n]) );
				}
				cp.playlist.topics = topics;
			}
		}
		else if( cp.topic_ids ){
			var module = hcom.presentation.getModule( cp.module_id );
			if( module ){
				var topics = [];
				var num_topics = cp.topic_ids.length;
				for( var n=0; n<num_topics; n++ ){
					var topic = module.getTopic( cp.topic_ids[n] );
					if( topic ){
						topics.push( topic );
					}
					else {
						alert( 'Topic ' + topic_ids[n] + ' could not be found.' );
					}
				}
				cp.playlist = new Playlist( 'default', topics );
			}
			else {
				alert( 'Module ' + cp.module_id + ' could not be found.' );
			}
		}
		else {
			cp.playlist = new Playlist( 'default', [] );
		}
		rv.push( cp );
	}
	return rv;
};

CustomPlaylist.delete_playlist = function( id ){
	CookieHelper.eraseCookie( 'cp' + id );
};

CustomPlaylist.find = function( id ){
	var rv = null;
	var playlists = CustomPlaylist.get_custom_playlists();
	for( var i=0; i<playlists.length; i++ ){
		cp = playlists[i];
		if( cp.id == id ){
			rv = cp;
			break;
		}
	}
	return rv; 
};
