/*
	This file provides an access to all data resources used by BTS
	
	Dependencies: jQuery, bam.js, bam.actionMessages.js
*/
bam.loadSync(
	bam.homePath + "bam.xml.js", 
	bam.homePath + "bam.url.js", 
	bam.homePath + "bam.validation.js", 
	bam.homePath + "bam.datetime.js",
	bam.homePath + "bam.collections.js",
	bam.homePath + "bam.ajaxHelper.js"
);
//Generic Error handler
bam.ajaxHelper.exclusive = true;
bam.ajaxHelper.ErrorHandler = function(response) {
	var code = response.code;
	var type = response.type;
	var content = response.Text;
	
	if(type == "error") {		
		switch (parseInt(code, 10)) {
			case -100: //Not logged in
				location.href = content;
				break;
			case -200: //After Lock
				alert("Today's lock time has passed. No more picks are allowed today.");
				break;
			default:
				var msg = "An error has occured, please try again.";  //content
				alert(msg);			
		}
	}
};
//Data Access Object namspace
var dao = {
	currentDate: null	
};
//Pics Data
dao.PicksData = bam.ajaxHelper.createInstance({
	url: "/mlb/fantasy/bts/pickPlayer.do",
	dataType: "xml",
	SelectedPickID: null,
	//Loads all the picks and triggers follow up function (callBack)
	//This is a mndatory method call that must immediately follow  object declaration
	Load: function(cb) {
		var that = this;
		that.makeRequest({type:"hit",team:0,v:2,m:"picks"}, function(jObj) {
			that.DataCache = jObj;
			if(!!jObj && !!jObj.response) {			
				that.ErrorHandler(jObj.response[0]);
			}
			if(typeof(cb) ==="function"){cb();}
		  });
	},
	//Returns Stats Object
	GetStats: function() {
		var stats = !!this.DataCache && this.DataCache.stats;
		if(!!stats) {
			return stats[0];
		}
		return null;
	},
	//Returns lock time
	GetLockTime: function(date) {
		var pTime;
		if(!!this.DataCache) {
			var pick = this.GetPickByDate(date);//!!this.DataCache.picks && this.DataCache.picks[0].pick;
			if(!!pick) {				
				var locktime = (!!pick.lockTime)?pick.lockTime:pick.locktime;
					pTime = bts.utils.cMil2AmPm(locktime);
			}
		}
		return pTime;
	},
	//Returns selected Pick object
	GetPick: function(idx) {
		if(!!this.DataCache) {
			var pick = !!this.DataCache.picks && this.DataCache.picks[0].pick;
			if(!!pick) {
				this.SelectedPickID = idx||0;
				return pick[this.SelectedPickID];
			}
		}
		return null;
	},
	//Returns Pick by date
	GetPickByDate: function(date) {
		if(!!this.DataCache) {
			var pick = !!this.DataCache.picks && this.DataCache.picks[0].pick;
			if(!!pick) {
				var idx = null;
				var attName = (!pick[0].gameDate)?"gamedate":"gameDate";
				idx = pick.indexOf(attName, date);
				if(idx != -1) {
					this.SelectedPickID = idx||0;
					return pick[this.SelectedPickID];
				}		
			}
		}
		return null;
	},
	//Returns a collection of all picks
	GetPicks: function() {
		if(!!this.DataCache) {
			var pick = !!this.DataCache.picks && this.DataCache.picks[0].pick;
			if(!!pick) {
				return pick;				
			}
		}
		return null;
	},
	//Returns a particular pitcher;
	GetPitcher: function(pkIdx, pId) {
		var pitcher;
		var pick = this.GetPick(pkIdx);
		if(!!pick && pick.pitcher) {		
			pitcher = pick.pitcher[pick.pitcher.indexOf(pId||0, "id")];		
		}
		return pitcher;
	}
});

//Teams Data
dao.TeamsData = bam.ajaxHelper.createInstance({
	teamsCache: new bam.collections.Hashtable(),
	url: "/mlb/fantasy/bts/games",
	dataType: "xml",
	SelectedTeamID: null,
	//Loads all the teams and triggers follow up function (callBack)
	Load: function(date, cb) {
		dao.currentDate = date;
		var that = this;
		if(that.teamsCache.containsKey(date)) {
			that.DataCache = that.teamsCache.get(date);
			if(!!that.DataCache && !!that.DataCache.response) {			
				that.ErrorHandler(that.DataCache.response[0]);
			}
			if(typeof(cb) ==="function"){cb();}
		} else {
			this.makeRequest({type:"hit",team:0,v:2,m:"teams",gameDate:date}, function(jObj) {
				that.teamsCache.put(date, jObj);
				that.DataCache = jObj;
				if(!!that.DataCache && !!that.DataCache.response) {			
					that.ErrorHandler(that.DataCache.response[0]);
				}
				if(typeof(cb) ==="function"){cb();}
			});
		}
	},
	//Returns selected Team object by id
	GetTeam: function(id) {
		if(!!this.DataCache) {
			var team = !!this.DataCache.gameDate && this.DataCache.gameDate[0].team;
			if(!!team) {
				var idx = team.indexOf("id", id);
				this.SelectedTeamID = (idx!=-1)?idx:0;
				var _tmp = team[this.SelectedTeamID];
				_tmp.gameDate = !!this.DataCache.gameDate[0].id;
				return _tmp;
			}
		}
		return null;
	},
	//Returns a collection of all teams
	GetTeams: function() {
		if(!!this.DataCache) {
			var team = !!this.DataCache.gameDate && this.DataCache.gameDate[0].team;
			if(!!team) {			
				return team;
			}
		}
		return null;			   
	}
			
});

//Players Data
dao.PlayersData = bam.ajaxHelper.createInstance({
	playersCache: new bam.collections.Hashtable(),
	url: "/mlb/fantasy/bts/games",
	dataType: "xml",
	SelectedPlayerID: null,
	//Loads all the players and triggers follow up function (callBack)
	Load: function(tid, pid, cb) {
		var that = this;
		if(that.playersCache.containsKey(tid+":"+pid)) {
			that.DataCache = that.playersCache.get(tid+":"+pid);
			if(!!that.DataCache && !!that.DataCache.response) {
				that.ErrorHandler(that.DataCache.response[0]);
			}
			if(typeof(cb) ==="function"){cb();}
		} else {			
			this.makeRequest({type:"hit",team:0,v:2,m:"players",teamId:String(tid), pitcherId:pid, gameDate:dao.currentDate}, function(jObj) {
				that.playersCache.put(tid+":"+pid, jObj);
				that.DataCache = jObj;
				if(!!jObj && !!jObj.response) {			
					that.ErrorHandler(jObj.response[0]);
				}
				if(typeof(cb) ==="function"){cb();}
			});
		}
	},
	//Returns Header
	GetHeader: function() {
		if(!!this.DataCache) {
			return !!this.DataCache.header && this.DataCache.header[0];
		} 
		return null;
	},
	//Returns selected player object
	GetPlayer: function(id) {
		if(!!this.DataCache) {
			var players = !!this.DataCache.team && this.DataCache.team[0].player;
			if(!!players) {
				var idx = players.indexOf("id", id);
				this.SelectedPlayerID = (idx != -1)?idx:0;
				return players[this.SelectedPlayerID];
			}
		}
		return null;
	},
	//Returns a collection of all players
	GetPlayers: function() {
		if(!!this.DataCache) {
			var players = !!this.DataCache.team && this.DataCache.team[0].player;
			if(!!players) {			
				return players;
			}
		}
		return null;
	}
});

//Returns Results data (endDate is optional, it sets the last date in the list and 10 positions back from it)
dao.ResultsData = bam.ajaxHelper.createInstance({
	url: "/mlb/fantasy/bts/pickPlayer.do",
	dataType: "xml",
	SelectedPickID: null,
	//Loads all the picks and triggers follow up function (callBack)
	Load: function(endDate, cb) {
		var that = this;
		var ed = !!endDate && bam.datetime.parseShortDate(endDate);
		var endDateStr = (bam.object.typeOf(ed) != "date")?bam.datetime.DateTime(new Date()).toShortDate():endDate;
		this.makeRequest({type:"hit",team:0,v:2,m:"results",to:endDateStr}, function(jObj) {
			that.DataCache = jObj;
			if(!!jObj && !!jObj.response) {			
				that.ErrorHandler(jObj.response[0]);
			}
			if(typeof(cb) ==="function"){cb();}
		});									   
	},
	//Navigates back in time starting the date passed as "date" parameter
	ScrollUp: function(date, cb) {
		var that = this;
		this.DataCache = {};
		this.SelectedPickID = null;
		this.makeRequest({type:"hit",team:0,v:2,m:"results",gameDate:date,"scroll":"up"}, function(jObj) {
			that.DataCache = jObj;
			if(!!jObj && !!jObj.response) {			
				that.ErrorHandler(jObj.response[0]);
			}
			if(typeof(cb) ==="function"){cb();}
		});	
	},
	//Navigates forward in time starting the date passed as "date" parameter
	ScrollDown: function(date, cb) {
		var that = this;
		this.DataCache = {};
		this.SelectedPickID = null;
		this.makeRequest({type:"hit",team:0,v:2,m:"results",gameDate:date,"scroll":"down"}, function(jObj) {
			that.DataCache = jObj;
			if(!!jObj && !!jObj.response) {			
				that.ErrorHandler(jObj.response[0]);
			}
			if(typeof(cb) ==="function"){cb();}
		});	
	},
	//Returns Stats Object
	GetStats: function() {
		var stats = !!this.DataCache && this.DataCache.stats;
		if(!!stats) {
			return stats[0];
		}
		return null;
	},
	//Returns selected Pick object
	GetPick: function(idx) {
		if(!!this.DataCache) {
			var pick = !!this.DataCache.picks && this.DataCache.picks[0].pick;
			if(!!pick) {
				this.SelectedPickID = idx||0;
				return pick[this.SelectedPickID];
			}
		}
		return null;
	},
	//Returns Pick by date
	GetPickByDate: function(date) {
		if(!!this.DataCache) {
			var pick = !!this.DataCache.picks && this.DataCache.picks[0].pick;
			if(!!pick) {
				var idx = null;
				var attName = (!pick[0].gameDate)?"gamedate":"gameDate";
				idx = pick.indexOf(attName, date);
				if(idx != -1) {
					this.SelectedPickID = idx||0;
					return pick[this.SelectedPickID];
				}		
			}
		}
		return null;
	},
	//Returns first Pick object
	GetFirstPick: function() {
		if(!!this.DataCache) {
			return this.GetPick(0);		
		}
		return null;
	},
	//Returns last Pick object
	GetLastPick: function() {
		if(!!this.DataCache && !!this.DataCache.picks) {
			var _last = this.DataCache.picks[0].pick.length - 1;
			return this.GetPick(_last);
		}
		return null;
	},
	//Returns a collection of all picks
	GetPicks: function() {
		if(!!this.DataCache) {
			var pick = !!this.DataCache.picks && this.DataCache.picks[0].pick;
			if(!!pick) {
				return pick;
			}
		}
		return null;
	}
});

//This object retrieves Stats data associated with results pick
dao.StatsData = bam.ajaxHelper.createInstance({
	url: "/mlb/fantasy/bts/games",
	dataType: "xml",
	SelectedTeamID: null,
	Load: function(date, cb) {
		var that = this;	
		this.makeRequest({type:"hit",team:0,v:2,m:"picksStats",gameDate:date}, function(jObj) {
			that.DataCache = jObj;
			if(!!jObj && !!jObj.response) {			
				that.ErrorHandler(jObj.response[0]);
			}
			if(typeof(cb) ==="function"){cb();}
		});
	},
	GetStats: function() {
		var stats = !!this.DataCache && this.DataCache.pickStat;
		if(!!stats) {
			return stats;
		}
		return null;
	}
});

//This Object handles saving pick selection
dao.PicksProcessor = bam.ajaxHelper.createInstance({
	url: "/mlb/fantasy/bts/pickPlayer.do",
	dataType: "xml",
	type: "post",
	PlayerID: null,
	Save: function(date, cb) {
		var that = this;	
		this.makeRequest({type:"hit",v:2,m:"make_pick",gameDate:date},{team: 0, pid: that.PlayerID}, function(jObj) {		
			if(!!jObj && !!jObj.response) {
				that.ErrorHandler(jObj.response[0]);
			}
			if(typeof(cb) ==="function"){cb();}
		});						   
	}
});
