Tracker = function(){
	return {
		init : function(config){
			var self = this;
			this.filterValue = config.filter || {};
			$.get("/rest/shotType.php", {}, function(data){
				self.shot_types = {};
				for(var i=0; i<data.shotType.length; i++){
					self.shot_types[data.shotType[i].id] = data.shotType[i];
				}
				self.shot_types["0"] = {name: 'Free Throw'};
			}, "json");
			
			$.get("/rest/player.php", {},  function(data){
				self.players = {};
				for(var i=0; i<data.player.length; i++){
					self.players[data.player[i].id] = data.player[i];
				}
			}, "json");
			
			if($('#gameMenu').val())
				$('#gameId').val($('#gameMenu').val());
			
			if($('#gameId').get(0).value != '')
				this.list({gameId: $('#gameId').get(0).value});
		
			this.tab('add');
			
			$('#newGameLink').click(function(){
				$('#newgame').show();
			});
			
			$('#sidebar h5').click(function(){
				$('#shotform').toggle();
			});
			
			$('#shotform .cancel').click(function(){
				$('#shotform').hide();
			});
			
			$('#tabs li').click(function(){
				self.tab(this);
			});
			
			$('#newgame .cancel').click(function(){
				$('#newgame').hide();
				$('#gameMenu').get(0).selectedIndex = 0;
			});
			
			this.createFilters(this.filterValue);
			
			var s = new Sortable('players');
			
			this.initializeWorkout();
			this.workout.edit(true);
		},
		
		changeGame : function(el){
			if(el.value.match(/^[0-9]+$/)){
				$('#shotchart').show();
				$('#newgame').hide();
			} else {
				$('#shotchart').hide();
				$('#shotform').hide();
				$('#list').html('');
			}
			$('#gameId').get(0).value = el.value;
			if($('#gameId').get(0).value != '')
				this.list({gameId: $('#gameId').get(0).value});
		},
		
		changeOpponent : function(el){
			if(el.value == 'new'){
				var name = window.prompt("Enter the opponent's name.");
				if(name){
					var o = { name: name };
					$.post("/rest/opponent.php", {json: JSON.stringify(o)},  function(data){
						$(el).append('<option value="'+data.id+'">'+data.name+'</option>');
						$(el).val(data.id);
					}, "json");
				}
			}
		},
		
		changeShotType : function(el){
			if(el.value == 0){
				$('#section').val(0);
				$('#section').get(0).disabled = true;
			} else {
				$('#section').get(0).disabled = false;
			}

		},
		
		changeSection : function(el){
			if(el.value == 0){
				$('#shotTypeId').val(0);
				$('#shotTypeId').get(0).disabled = true;
			} else {
				$('#shotTypeId').get(0).disabled = false;
			}
			
		},
		
		changePlayer : function(el){
			if(el.value.match(/^[0-9]+$/)){
				$('#shotchart').show();
			} else {
				$('#shotchart').hide();
				$('#shotform').hide();
				$('#list').html('');
			}
			this.list({playerId : el.value});
		},
		
		createFilters : function(config){
			var that = this;
			Tracker.filters = new FilterSet({
				container: 'filters'
				,header: 'Filter Shots By:'
				,filter : config.filter || {gameId: ''}
				,filterList: [
					{ 
						name: 'game'
						,label: 'Game'
						,param: 'gameId'
						,renderValue: function(o){ return '('+util.renderDate(o.date)+') '+o.name; }
					}
					,{  
						name: 'player' 
						,label: 'Player'
						,param: 'playerId'
						,renderValue: function(o){ return o.firstName+' '+o.lastName; }
					}
					,{ 
						name: 'shotType'
						,label: 'Shot Type'
						,param: 'shotTypeId'
					}
					,{ 
						name: 'section'
						,data: [
							['1-8','1-8 (2PT)']
							,['9-15','9-15 (3PT)']
							,['0','Free Throw']
							,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
						]
						,expandData: true
						,label: 'Section'
					}
					,{ 
						name: 'period'
						,data: [
							['1-2','First Half']
							,['3-4','Second Half']
							,['1','1st Quarter']
							,['2','2nd Quarter']
							,['3','3rd Quarter']
							,['4','4th Quarter']
							,['5','Overtime']
						]
						,expandData: true
						,label: 'Period'
					}
					,{ 
						name: 'gameType'
						,label: 'Game Type'
						,param: 'game_gameTypeId'
					}
					,{ 
						name: 'opponent'
						,label: 'Opponent'
						,param: 'game_opponentId'
					}
				]
				,change: function(vals){
					Tracker.list(vals);
				}
			});
			Tracker.filters.init();
		},
		
		initializeWorkout : function(mode){
			this.workout = new Workout({
				change: function(filter){
				},
				onSave: function(data){
					this.edit(false);
					$('.workout-id').val(data.id);
				},
				mode: mode || 'edit'
			});
			this.workout.init();
		},
		
		initWorkout : function(mode){
			this.workout.edit(mode == 'edit');
		},
		
		changeWorkout : function(el){
			this.workout.display(el.value);
		},

		createWorkout : function(){
			this.initializeWorkout();
		},
		
		display: function(jsonStr){
			var thisMovie = function(movieName) {
			    if (navigator.appName.indexOf("Microsoft") != -1) {
			        return window[movieName]
			    }
			    else {
			        return document[movieName]
			    }
			}
			
			thisMovie('tracker').display(jsonStr);
		},
		
		displayPlayer: function(playerId){
			var p = this.players[playerId];
			return p ? ('['+p.number+'] '+p.lastName) : '[deleted player]';
		},
		
		filter : function(){
			var params = {};
			$('#filter-view select').each(function(){
				if(this.value){
					params[this.id.replace(/Filter$/,'')] = this.value;
				}
			});
			this.list(params);
		},

		setupForm : function(shot){
			$('#shotform').show();
			$('#saveShot').get(0).focus();
			$('#make').get(0).checked = shot.make;
			$('#section').get(0).value = shot.section;
			$('#shotTypeId').get(0).value = 1;
			$('#x').get(0).value = shot.x;
			$('#y').get(0).value = shot.y;
			this.changeShotType($('#shotTypeId').get(0));
			this.changeSection($('#section').get(0));
		},
		
		list : function(p){
			var self = this;
			p.dc = new Date().getTime();
			$.get("/rest/shot.php", p, function(data){
				var fg = 0, two = 0, three = 0, fgAtt = 0, threeAtt = 0, twoAtt = 0, ft = 0, ftAtt = 0;
				r = '<table width="100%">'
					+'<tr>'
					+'<th class="sort-numeric">Player</th>'
					+'<th class="sort-numeric">Section</th>'
					+'<th>Shot Type</th>'
					+'<th>Result</th>'
					+'</tr>';
				if(data.shot && data.shot.length){
					for(var i=0; i<data.shot.length; i++){
						s = data.shot[i];
						r += '<tr class="'
						 	+ (i%2 ? 'odd ' : '') 
							+ (s.make == 1 ? 'make' : 'miss') 
							+ '">'
							+'<td>'+self.displayPlayer(s.playerId)+'</td>'
							+'<td>'+(s.section == 0 ? 'Free Throw' : s.section)+'</td>'
					 		+'<td>'+self.shot_types[s.shotTypeId].name+'</td>'
							+'<td>'+ (s.make == 1 ? 'make' : 'miss') +'</td>'
						+'</tr>';
						if(s.section == 0){ ft = s.make == 1 ? ft + 1 : ft; ftAtt++; }
						else if(s.section > 8){ three = s.make == 1 ? three + 1 : three; threeAtt++;}
						else if(s.section < 9){ two = s.make == 1 ? two + 1 : two; twoAtt++; }
						fgAtt++;
					}
				} else {
					r += '<tr><td colspan="5">No shots to display.</td></tr>';
				}
				r += '</table>';
				
				var stats = '<div class="bigstats">'
					+'2PT %: <span>'+(twoAtt > 0 ? Math.round(two/twoAtt*100) : ' - ')+'</span>'
					+' 3PT %: <span>'+(threeAtt > 0 ? Math.round(three*100/threeAtt) : ' - ')+'</span>'
					+' FT %: <span>'+(ftAtt > 0 ? Math.round(ft/ftAtt*100) : ' - ')+'</span>';
				if(twoAtt > 0 && threeAtt > 0 && ftAtt > 0){
					var tot = Math.round(two/twoAtt*100)+Math.round(three/threeAtt*100)+Math.round(ft/ftAtt*100);	
				}
				stats += ' TOTAL %: <span>'+(tot ? tot : '-')+'</span>';
				stats += '</div>';
				$('#stats').html(stats);
				
				$('#list').html(r);
				var s = new Sortable('list');
				Tracker.display(JSON.stringify(data));
			}, "json");
		},

		tab : function(t){
			el = t.tagName ? $(t) : $('#tab-'+t);
			$("#tabs .active").removeClass("active");
			el.addClass("active");
			
			var id = el.attr("id").replace(/tab-/,'');
			$('.filter').hide();
			$('#filter-'+id).show();
			
			if('practice' == id || 'workouts' == id){
				$('#sidebar').hide();
				$('#shotchart').hide();
			} else {
				$('#sidebar').show();
				$('#shotchart').show();
			}
		},

		shot : function(s){
			var shot = eval("(" + s + ')');
			this.setupForm(shot);
		},

		save : function(){
			var shot = {
				playerId: $('#playerId').get(0).value,
				section: $('#section').get(0).value,
				shotTypeId: $('#shotTypeId').get(0).value,
				gameId: $('#gameId').get(0).value,
				make: $('#make').get(0).checked ? 1 : 0,
				period: $('#period').get(0).value,
				x: $('#x').get(0).value,
				y: $('#y').get(0).value
			};
			
			if(shot.section == 0 || shot.shotTypeId == 0){
				shot.shotTypeId = 0;
				shot.section = 0;
				shot.x = -100;
				shot.y = -100;
			}
	
			var self = this;
			$.post("/rest/shot.php", { json: JSON.stringify(shot) },
			  function(data){
				$('#shotform').hide();
			  	self.list({gameId: $('#gameId').get(0).value});
			  }, "text");
		}
	};
}();
