Workout = function(config){
	if(!config) config = {};
	return {
		url: '/rest/workout.php'
		,container: config.container || 'workout'
		,onSave: config.onSave
		,mode: config.mode || 'display'
		,players: config.players || []
		,init : function(){
			var that = this;
			$.get('/rest/player.php',this.params,function(data){
				that.players = data.player;
			},'json');
			
			$('#'+this.container).html('<div class="filter-fields"></div>');
			this.filters = new FilterList({
				container: this.container
				,header: '<div style="float:right; margin: 1px 0 0" class="edit">'
							+'<input type="button" class="workout-save" value="Save Workout"/>'
							+'<input type="button" class="workout-delete" value="Delete"/>'
							+'<a href="javascript:Tracker.workout.edit(false)" class="workout-cancel">Cancel</a>'
						+'</div>'
						+'<span style="float:right" class="display">'
							+'<a href="javascript:Tracker.workout.edit(true)">Edit</a>'
							+'<a href="javascript:Tracker.workout.showPlayers(true)">Send To Players</a>'
						+'</span>'
						+'<span class="edit">'
						+'Workout Name: <input class="workout-name"/>'
						+'</span>'
						+'<span class="display workout-title"></span>'
						+'<input type="hidden" class="workout-id"/>'
						+'<div style="clear: both;"></div>'
				,name: 'drill'
				,renderDetails: function(vals){
					if(vals) return vals.description;
				}
				,renderValue: function(o){ return '['+o.level+'] '+o.title; }
				,values: ['']
				,change: config.onChange
				,onRender: config.callback
			});
			this.filters.init();
			
			$('#'+this.container+' .workout-save').click(function(){
				that.save();
			});
			$('#'+this.container+' .workout-delete').click(function(){
				that.remove();
			});
		},
		
		display: function(id){
			this.edit(false);
			var that = this;
			if(id){
				$.get(this.url, {id: id, drills: true}, function(data){
					that.setValues(data['workout'][0]);
					that.edit(false);
				}, "json");
			}
		},
		
		showPlayers : function(on){
			$('#workout-players').remove();
			if(on){
				var html = '<div id="workout-players">';
				html += '<h4>Send workout to players:</h4>';
				html += '<p>';
				for(var i=0; i<this.players.length; i++){
					html += '<input type="checkbox" name="player_id" value="'+this.players[i].id+'"/>';
					html += '<label class="cbx">'+this.players[i].firstName+' '+this.players[i].lastName+'</label>';
				}
				html += '<br/>';
				html += '<input type="checkbox" name="cc" value="coach"/>';
				html += '<label class="cbx"><strong>Also send me a copy</strong></label>';
				html += '</p>';
				html += '<h4>Add a note:</h4>';
				html += '<p><textarea name="note" rows="4" cols="90"/></p>';
				html += '<p><input type="button" class="workout-send" value="Send Workout" onclick="Tracker.workout.send()"/></p>';
				html += '</div>';
				$('#workout .filter-fields').after(html);
			}
		},

		edit: function(on){
			if(on === undefined) on = (this.mode == 'edit');
			$('#workout .'+(on ? 'edit' : 'display')).show();
			$('#workout .'+(!on ? 'edit' : 'display')).hide();
			this.mode = on ? 'edit' : 'display';
			$('#workout .filter-wrap select').attr('disabled',!on);
			$('#workout .workout-delete')[on && this.getValues().id ? 'show' : 'hide']();
			$('#workout .workout-cancel')[on && this.getValues().id ? 'show' : 'hide']();
			this.showPlayers(false);
			if(on && !this.filters.values.length){
				this.filters.newFilter();
			}
		},

		refreshMenu: function(id){
			var that = this;
			$.get(this.url, {order: 'name'}, function(data){
				var html = '<option value="">Select a workout:</option>';
				html += '<option value="">------------------------</option>';
				for(var i=0; i<data.workout.length; i++){
					html += '<option value="'+data.workout[i].id+'">'+data.workout[i].name+'</option>';
				}
				$('#workoutMenu').html(html);
				$('#workoutMenu').val(id);
			},'json');
		},

		send: function(){
			var that = this;
			var o = this.getValues();
			
			$.post('email-workout.php', {
					workout: JSON.stringify(o)
					,cc: $('#workout [name=cc]').length && $('[name=cc]').get(0).checked
					,note: $('#workout [name=note]').val()
				}, function(data){
				$('#workout-players').html('<h4>Workout sent to ' + data.join(", ")+'.</h4>');
			},"json");
		},

		save: function(){
			var that = this;
			var o = this.getValues();
			$.post(this.url, {json: JSON.stringify(o)}, function(data){
				if(!$('.workout-id').val()) $('.workout-id').val(data.id);
				that.setValues(o);
				if(that.onSave) that.onSave(data);
				that.refreshMenu(data.id);
			}, "json");
		},

		remove: function(){
			var that = this;
			var o = this.getValues();
			$.post(this.url, {"delete": JSON.stringify(o)}, function(data){
				$('#workout').empty();
				that.refreshMenu();
			});
		},
		
		setValues : function(vals){
			$('.workout-name').val(vals.name);
			$('.workout-title').html(vals.name);
			$('.workout-id').val(vals.id);
			var filter = [];
			for(var i=0; i<vals.drills.length; i++){
				if(!isNaN(vals.drills[i]))
					filter.push(vals.drills[i]);
				else if(vals.drills[i].id)
					filter.push(vals.drills[i].id)
			}
			this.filters.setFilter(filter);
			this.edit();
		},

		getValues : function(){
			var filter = this.filters.getFilter();
			var drills = [];
			for(var i=0; i<filter.length; i++){
				drills.push({
					id: filter[i]
				});
			}
			var players = [];
			$('#workout :checkbox').each(function(){
				if(this.checked && !isNaN(this.value))
					players.push({
						id: this.value
					});
			});
			return {
				id: $('.workout-id').val()
				,name: $('.workout-name').val()
				,drills: drills
				,players: players
			};
		}
	}
};
