// JavaScript Document

document.writeln('<script language="javascript" type="text/javascript" src="/betting/js/templates.js"></script>');


PaddockTips = Class.create({
					
		initialize: function ()
		{			
			this.debug = false;
									
			// vars
			this.dataUrl = "/betting/ajax_services/get_all_assoc.asp";
			this.paddockTipsUrl = "/betting/ajax_services/get_bruits.asp";	
			
			this.racesUrl = "/betting/ajax_services/next_races.asp";
			this.meetingsUrl = "/betting/ajax_services/next_meetings.asp";			
			
			this.data = null;
			this.paddockTipsData = null;
						

			this.meetings = 
			    {ctnr: null, 
				 title: null, 
				 dataCtnr: null, 
				 treeCtnr: null,
				 rows: Array(), 
				 loading: null, 
				 hidden: false, 
				 buttons: {today: null, tomorrow: null}
				};
			this.paddockTips = 
			    {ctnr: null, 
				 title: null, 
				 dataCtnr: null, 				 
				 rows: Array(), 
				 loading: null, 
				 hidden: true				
				};	
				
			// next meetings, next races
			this.nextRacesRows = Array();
			this.races_limit = 38;
			this.meetings_limit = 36;
			
			this.nextMeetingsRows = Array();	
			this.nextRacesCtnr = null;
			this.nextMeetingsCtnr = null;			
			
			this.racesData = null;
			this.meetingsData = null;			// next meetings
				
			this.templates = null;
			this.templateList = [
				{name: "loading", url: "/betting/templates/loading.asp"},
				{name: "meeting", url: "/betting/templates/meeting.asp"},
				{name: "paddock_tips_row", url: "/betting/templates/paddock_tips_row.asp"},
				{name: "paddock_tips_header", url: "/betting/templates/paddock_tips_header.asp"},	
				{name: "paddock_tips_none", url: "/betting/templates/paddock_tips_none.asp"},					
				{name: "nextmeetinglink", url: "/betting/templates/link_next_meeting.asp"},
				{name: "nextracelink", url: "/betting/templates/link_next_race.asp"}					
				];				
			

			this.selectedDay = null;
			this.selectedDayString = "Today";
			this.selectedMeeting = null;			
			
			this.paddockTipsRequest = null;	
			
			document.observe("dom:loaded", this.handleDomLoaded.bind(this));
		},
		
		
		handleDomLoaded: function (evt)
		{			
			this.meetings.ctnr = $('MeetingsCtnr');
			this.meetings.title = $('MeetingsTitle');
			this.meetings.dataCtnr = $('Meetings');
			this.meetings.buttons.today = $('MeetingOption_Today');
			this.meetings.buttons.tomorrow = $('MeetingOption_Tomorrow');
			
			this.paddockTips.ctnr = $('TipsCtnr');
			this.paddockTips.title=$('TipsTitle');
			this.paddockTips.dataCtnr=$('Tips');	
			
			this.paddockTips.ctnr.style.display = "none";
			
			this.nextRacesCtnr = $('NextRacesListCtnr');
			this.nextMeetingsCtnr = $('NextMeetingsListCtnr');	
			
			this.meetings.treeCtnr = $('MeetingsTree');
			
			this.templates = new Templates(this.templateList);
			this.templates.loadedCallback = this.templatesLoaded.bind(this);
			
			this.addEventListeners();			
		},

		addEventListeners: function ()
		{
			Element.observe(this.meetings.title, "click", this.toggleMeetings.bind(this));
			Element.observe(this.meetings.treeCtnr, "click", this.toggleMeetings.bind(this));
			//Element.observe(this.runners.title, "click", this.toggleRunners.bind(this));
			Element.observe(this.meetings.buttons.today, "click", this.showTodayMeetings.bind(this));
			Element.observe(this.meetings.buttons.tomorrow, "click", this.showTomorrowMeetings.bind(this));						
		},
		
		templatesLoaded: function ()
		{
			this.meetings.loading = document.createElement("div");
			this.meetings.loading.innerHTML = this.templates.getTemplate("loading");
			this.meetings.ctnr.appendChild(this.meetings.loading);		
			
			this.getData();
			this.loadRacesData();
			this.loadMeetingsData();			
		},		
		
		getData: function ()
		{
			var requestOptions = {}
			requestOptions.onSuccess = this.handleDataRequestSuccess.bind(this);
			requestOptions.onFailure = this.handleDataRequestFailure.bind(this);
			
			new Ajax.Request(this.dataUrl, requestOptions);
		},	
		
		handleDataRequestSuccess: function (response)
		{		 
		
		  
			this.data = response.responseText.evalJSON(true);
			this.showTodayMeetings(null);			
		},
		handleDataRequestFailure: function (response)
		{ 
			if(this.debug)
				alert(response.responseText);
		},		
		
		showTodayMeetings: function(evt)
		{
			this.selectedDay = this.data.today;
			this.selectedDayString = "Today";
			this.updateButtonStates("today");		
			this.hidePaddockTips();
			this.clearPaddockTips();
			this.showMeetings();
			this.selectFirstMeeting();
		},		
		showTomorrowMeetings: function(evt)
		{
			this.selectedDay = this.data.tomorrow;
			this.selectedDayString = "Tomorrow";
			this.updateButtonStates("tomorrow");
			this.hidePaddockTips();
			this.clearPaddockTips();
			this.showMeetings();
			this.selectFirstMeeting();
		},		
		
		updateButtonStates: function(day)
		{
			if(day == "tomorrow")
			{
				this.meetings.buttons.today.removeClassName("MeetingOption_Active");
				this.meetings.buttons.today.addClassName("MeetingOption_Inactive");	
				this.meetings.buttons.tomorrow.removeClassName("MeetingOption_Inactive");
				this.meetings.buttons.tomorrow.addClassName("MeetingOption_Active");	
			}
			else
			{
				this.meetings.buttons.tomorrow.removeClassName("MeetingOption_Active");
				this.meetings.buttons.tomorrow.addClassName("MeetingOption_Inactive");	
				this.meetings.buttons.today.removeClassName("MeetingOption_Inactive");
				this.meetings.buttons.today.addClassName("MeetingOption_Active");					
			}
		},
		
		showMeetings: function()
		{									
			
			if(this.meetings.loading != null) {
				this.meetings.ctnr.removeChild(this.meetings.loading);
				this.meetings.loading = null;
			}						
	
	
			this.clearMeetings();									
			
			
			for(var i=0; i < this.selectedDay.length; i++) 
			{				
				var meet = this.selectedDay[i];
				var template = new Template(this.templates.getTemplate("meeting"));				
				if(meet.info != undefined) 
				{
					var meettime;
					try
					{
						var parts = meet.info.time.split(":");
						meettime = Number.pad(parts[0], 2, 0) + ":" + Number.pad(parts[1], 2, 0);
					}
					catch(e)
					{
						meettime = meet.info.time;
					}					
					
					var templateData = 
					     {number: Number.pad(i+1, 2, 0), 
						  name: meet.info.hippodrome, 
						  country: meet.info.country,
						  time: meettime,
						  numofraces: meet.races.length + " Race" + (meet.races.length == 1 ? "" : "s")
						 };
					
					var row = document.createElement("div");
					row.innerHTML = template.evaluate(templateData);
					Element.observe(row, "click", this.handleMeetingSelect.bind(this, meet.info.id));
					//Element.observe(row, "mouseover", this.handleMouseOver.bind(this, row));
					//Element.observe(row, "mouseout", this.handleMouseOut.bind(this, row));		
					Element.observe(row, "mouseover", this.handleMouseOver.bind(this, row));
					Element.observe(row, "mouseout", this.handleMouseOut.bind(this, row));	
					
					if(i % 2 == 0) 
					{
						row.addClassName("meeting-row-alt");
						Element.observe(row, "mouseover", this.handleMouseOver.bind(this, row, "meeting-row-alt"));
						Element.observe(row, "mouseout", this.handleMouseOut.bind(this, row, "meeting-row-alt", meet.info.id));						
					}		
					else
					{
						Element.observe(row, "mouseover", this.handleMouseOver.bind(this, row, null));
						Element.observe(row, "mouseout", this.handleMouseOut.bind(this, row, null, meet.info.id));							
					}								
		
					this.meetings.dataCtnr.appendChild(row);
				
					
					this.meetings.rows.push(row);																			
					
				}
			}
			
			
			//if(qsMeetingId != "") {
			//	this.handleMeetingSelect(qsMeetingId);
			//	qsMeetingId = "";
			//}
			
		},		
		
		clearMeetings: function()
		{		
			while(this.meetings.rows.length > 0) {
				var row = this.meetings.rows.pop();
				row.stopObserving();
				this.meetings.dataCtnr.removeChild(row);
			}
			this.selectedMeeting = null;
		},	
		
		selectFirstMeeting: function ()
		{
			try
			{
			  if(this.selectedDay[0].info.id > 0)
			     this.handleMeetingSelect(this.selectedDay[0].info.id);
			} catch(e) {}
		},
		handleMeetingSelect: function (meetingId)
		{
			
			var meetingsArr = this.selectedDay;			
			

			//if (this.debug) 
			//   alert(meetingsArr.toJSON());			
			
			for(var i=0; i<meetingsArr.length; i++) 
			{				
				if(meetingId == meetingsArr[i].info.id) 
				{					
					this.selectedMeeting = meetingsArr[i];
					
					this.meetings.rows[i].addClassName("selected");
					if(this.meetings.rows[i].childNodes.length >= 2)
						this.meetings.rows[i].childNodes[1].addClassName("selected");
				}
				else {
					this.meetings.rows[i].removeClassName("selected");	
					if(this.meetings.rows[i].childNodes.length >= 2)
						this.meetings.rows[i].childNodes[1].removeClassName("selected");					
				}
			}
			
			//this.hideDataCtnr(this.meetings);
			this.loadPaddockTips();
		},		
				
		handleMouseOver: function (obj)
		{
			try
			{			
				obj.addClassName("bet-mouse-over");									
			
			    
				// if (! obj.hasClassName("selected"))
				if (obj.className.indexOf("selected") < 0)
			    {	
				
					var sel = $(this.getElementListByClassName(obj,"selections")[0]);
				
					sel.addClassName("bet-mouse-over");	
				
					//alert(obj.getElementsByClassName("selections")[0].className);							
				
					
					var fields = this.getElementListByClassName(obj, "tdstyle");					
					for(var i=0;i < fields.length;++i)
					{
						field = $(fields[i]);
						field.addClassName("bet-mouse-over");
					}
				}
			}
			catch (e) 
			{
				if(this.debug)
				  alert(e.description);
			}				
		},
		
		
		handleMouseOut: function (obj, addclass, id)
		{
			try
			{				
				if(addclass != null) 
				{
				   if(!
					  (
					    addclass == "meeting-row-alt" && 
  					    this.selectedMeeting != null && 
					    this.selectedMeeting.info != null &&
					    this.selectedMeeting.info.id == id					   
					  )
					   
					 ) 
				   {
				      obj.addClassName(addclass);	
				   }
					 
				}
				obj.removeClassName("bet-mouse-over");
				var selectionNode = $(this.getElementListByClassName(obj, "selections")[0]);
				if (obj.childNodes != undefined &&
					// selectionNode.hasClassName("bet-mouse-over")
					(selectionNode.className.indexOf("selected") < 0)
					)
			    {									
							   	
					selectionNode.removeClassName("bet-mouse-over");											
					
					var fields = (this.getElementListByClassName(obj,"tdstyle"));
					for(var i=0;i < fields.length;++i)
					{
						field = $(fields[i]);
  				        fields[i].removeClassName("bet-mouse-over");									
					}
				}
			}
			catch (e) 
			{
			}
		},		
		
		
		
		
		loadPaddockTips: function() 
		{		
	
			this.hidePaddockTips();
	      	this.clearPaddockTips();
			this.paddockTips.loading = document.createElement("div");   
			this.paddockTips.loading.innerHTML = this.templates.getTemplate("loading"); 
			this.paddockTips.ctnr.appendChild(this.paddockTips.loading);			
			
			this.paddockTips.ctnr.style.display = "block";

			var requestOptions = {};
			requestOptions.onSuccess = this.handlePaddockTipsRequestSuccess.bind(this);
			requestOptions.onFailure = this.handlePaddockTipsRequestFailure.bind(this);
			requestOptions.method = "post";		
			
			if(this.selectedDayString == "Tomorrow")
			{
				/*
			   var tomorrow = new Date();
			   tomorrow.setDate(tomorrow.getDate()+1);
			   var date = tomorrow.getFullYear() + "-0" + (tomorrow.getMonth()+1) + "-" + tomorrow.getDate();
			   */
			   requestOptions.parameters = {date: 1}					
			}
			
								
				
			this.paddockTipsRequest = new Ajax.Request(this.paddockTipsUrl, requestOptions);	
	
				/*
				var requestOptions = {}
				requestOptions.onSuccess = this.handleRaceDetailsRequestSuccess.bind(this);
				requestOptions.onFailure = this.handleRaceDetailsRequestFailure.bind(this);
				requestOptions.method = "post"
				requestOptions.parameters = {rid: this.selectedMeeting.races[i].info.id}
			
				this.raceDetailsRequest = new Ajax.Request(this.raceDetailsUrl, requestOptions);				
				*/
		},
		
		handlePaddockTipsRequestSuccess : function(response)
		{				
			//alert(response.responseText);
			this.paddockTipsData = response.responseText.evalJSON(false);   

			this.showPaddockTips();
		},
		handlePaddockTipsRequestFailure : function(response)
		{  
		},
		
		showPaddockTips: function()
		{		
		   var tipsNumber = 0;
		
		  // alert(this.selectedMeeting.races[0].runners[3].id);
			this.showDataCtnr(this.paddockTips); 
						
			if(this.paddockTips.loading != null) {
				this.paddockTips.ctnr.removeChild(this.paddockTips.loading);
				this.paddockTips.loading = null;
			}
		
			 this.clearPaddockTips();			
			 
			 var template0 = new Template(this.templates.getTemplate("paddock_tips_header"));						
			
			var now = new Date();
			var day = todayText;
			if(this.selectedDayString == "Tomorrow")
			{
				day = tomorrowText;
				now.setDate (now.getDate() + 1);
			}
			var datenow = dayNames[now.getDay()] + ", " + monthNames[now.getMonth()] + " " + now.getDate() + ", " + now.getFullYear();
			 
			
				var template0Data =
				  { TodayTomorrow: day,
				    Datenow: datenow,
					MeetingName: this.selectedMeeting.info.hippodrome				  
				  };
				var row0 = document.createElement("div");
				$(row0).innerHTML = template0.evaluate(template0Data);
				
				this.paddockTips.dataCtnr.appendChild(row0);
			    this.paddockTips.rows.push(row0);			 
			 
			 
			 var template = new Template(this.templates.getTemplate("paddock_tips_row"));			 									
			 			 
			 for(var i = 0;i < this.paddockTipsData.bruits.length;++i)
			 {								 
				var tip = this.paddockTipsData.bruits[i];	
				var runnernum = "";
				var runnername = "";
				
				if(tip.meetingID != this.selectedMeeting.info.id)
				   continue;
								
				
				for(var j = 0;j < this.selectedMeeting.races.length;++j)
			 	{
					 if(this.selectedMeeting.races[j].info.id == tip.raceId)
					 {  
						 var curr_runners = this.selectedMeeting.races[j].runners;
						 for(var k = 0;k < curr_runners.length;++k)
						 {
							 if(curr_runners[k].id == tip.runnerID)
							 {								 
								 runnernum = curr_runners[k].number;
								 runnername = curr_runners[k].name;
								 break;
							 }
						 }
						 break;
					 }
			 	}
			 	
				// alert(runnernum + " - " + runnername);
				
				var templateData =
				  { raceNumber: tip.raceNumber,
				    raceName: tip.raceName,
					runnerNumber: runnernum,
					runnerName: runnername,
					paddockTip: tip.text
				  };
				var row = $(document.createElement("div"));
				row.innerHTML = template.evaluate(templateData);
				
				this.paddockTips.dataCtnr.appendChild(row);
			    this.paddockTips.rows.push(row);
				++tipsNumber;
			    if(tipsNumber%2 == 1)
			    {
				    row.addClassName("paddock-tips-row-alt");
			    }					
			 }			 
			 if(tipsNumber == 0)
			 {
				 var template1 = new Template(this.templates.getTemplate("paddock_tips_none"));
				 var row1 = $(document.createElement("div"));
				 var data = {paddockTipsErrorText: paddockTipsErrorText};
				 row1.innerHTML = template1.evaluate(data);				 
				 this.paddockTips.dataCtnr.appendChild(row1);
				 this.paddockTips.rows.push(row1);
				 row1.addClassName("paddock-tips-row-alt");
			 }
			 
		 			 
		},

		showDataCtnr: function (which)
		{
			which.dataCtnr.style.display = "block";
			if(which.rows != undefined && which.rows.length > 0) {
				for(var i=0; i < which.rows.length; i++) {
					which.rows[i].style.display = "block";
				}
			}
			which.hidden = false;
			if (this.meetings!= null && this.meetings == which)
			{
  			   which.treeCtnr.removeClassName("title-row-closed");			
  			   which.treeCtnr.addClassName("title-row-opened");			
			}
		},
		hideDataCtnr: function (which)
		{
			if(which.rows != undefined && which.rows.length > 0) {
				for(var i=0; i < which.rows.length; i++) 
				{					
					which.rows[i].style.display = (which.rows[i].hasClassName("selected"))? "block": "none";
				}
			}
			else {
				which.dataCtnr.style.display = "none";
			}
			which.hidden = true;
			// update tree states
			if (this.meetings!= null && this.meetings == which)
			{			
				which.treeCtnr.removeClassName("title-row-opened");			
 				which.treeCtnr.addClassName("title-row-closed");				
			}
		},
		clearPaddockTips: function()
		{			
			while(this.paddockTips.rows.length > 0) 
			{
				var row = this.paddockTips.rows.pop();				
				this.paddockTips.dataCtnr.removeChild(row);
			}		
		},
		hidePaddockTips: function()
		{
			this.paddockTips.ctnr.style.display = "none";
		},
		
		toggleMeetings: function (evt)
		{
			if(this.meetings.hidden)
				this.showDataCtnr(this.meetings);
			else this.hideDataCtnr(this.meetings);
		},	
		
		
		loadRacesData: function ()
		{
			
			
			var requestOptions = {}
			requestOptions.onSuccess = this.handleRacesDataRequestSuccess.bind(this);
			requestOptions.onFailure = this.handleRacesDataRequestFailure.bind(this);
			requestOptions.method = "post"
			new Ajax.Request(this.racesUrl, requestOptions);
			
		},
		
		
		handleRacesDataRequestSuccess: function (response)
		{							  
			// empty json: {"races": [""], "meetings": [""]} 
			this.racesData = response.responseText.evalJSON(false);	
			this.showRaces();
		},
		handleRacesDataRequestFailure: function (response)
		{
			
		},
		
		
		showRaces: function ()
		{		
				
			// alert(JSON.stringify(this.races));
			this.nextRacesCtnr.innerHTML = "";
			
			// handle erroneous inputs 
			var raceDisplayed = false;	
						
			try  
			{			  
			  for(var i = 0; i < 5; i++) 
			  {
				//alert("loop: " + i);
				
				var row = document.createElement("div");
				
				var info = this.racesData.races[i];
											
				
				var timeParts = /[0-9]{4}-[0-9]{2}-[0-9]{2} ([0-9]{2}):([0-9]{2}):[0-9]{2}/.exec(info.start);
				var time = timeParts[1] + "h" + timeParts[2];
				var text = time + " &nbsp; " + info.name;						
						
				row.innerHTML = (text.length <= this.races_limit)? text: "<a title='" + text + "' class='tooltip'>" + 
				                text.substring(0, this.races_limit) + "...</a>";													


				
				this.nextRacesCtnr.appendChild(row);
				row = $(row);
				this.nextRacesRows.push(row);			
				raceDisplayed = true;

				row.addClassName("list-row");
				if(i % 2 == 1) 
				{
					row.addClassName("list-row-alt");
				}
				
				Element.observe(row, "mouseover", this.handleRaceOver.bind(this, i));
				Element.observe(row, "mouseout", this.handleRaceOut.bind(this, i));
				Element.observe(row, "click", this.handleRaceClick.bind(this, i));
			  }				  
			}
			catch(e)
			{ 								
				if (!raceDisplayed)
				{
					var row = document.createElement("div");
					row.innerHTML = "<p class='BoxError'>" + noRacesError + 
					                "</p>";
					this.nextRacesCtnr.appendChild(row);
					
				}
				
			}
			
			
			
			/*
			this.races.moreBtn.href = this.templates.getTemplate("nextracelink") + "?m=" + this.racesData.races[0].meetingID + "&r=" + this.racesData.races[0].id;
			this.races.flashBtn.href = this.templates.getTemplate("nextracelink") + "?m=" + this.racesData.races[0].meetingID + "&r=" + this.racesData.races[0].id + "&flash=1";
			*/
		},
		
		handleRaceOver: function (index)
		{
			this.nextRacesRows[index].addClassName("list-row-over");
		},
		handleRaceOut: function (index)
		{
			this.nextRacesRows[index].removeClassName("list-row-over");
		},
		handleRaceClick: function (index)
		{
			document.location.href = this.templates.getTemplate("nextracelink") + "?m=" + this.racesData.races[0].meetingID + "&r=" + this.racesData.races[0].id;
		},
		
		loadMeetingsData: function ()
		{
			var requestOptions = {}
			requestOptions.onSuccess = this.handleMeetingsDataRequestSuccess.bind(this);
			requestOptions.onFailure = this.handleMeetingsDataRequestFailure.bind(this);
			requestOptions.method = "post"
			new Ajax.Request(this.meetingsUrl, requestOptions);
		},
		
		
		
		
		handleMeetingsDataRequestSuccess: function (response)
		{	

			this.meetingsData = response.responseText.evalJSON(false);
			this.showNextMeetings();
		},
		handleMeetingsDataRequestFailure: function (response)
		{		
		},
					
		showNextMeetings: function ()
		{
			this.nextMeetingsCtnr.innerHTML = "";
			// handle erroneous inputs 
			var meetingDisplayed = false;
			try  
			{				
			  for(var i = 0; i < 5; i++) 
			  {
				var row = document.createElement("div");
				//Object.reveal(this.meetings.data[i]);
				var info = this.meetingsData[i];
				
				var timeParts = /([0-9]{2}):([0-9]{2}):[0-9]{2}/.exec(info.time);
				var time = timeParts[1] + "h" + timeParts[2];
				
				var text = time + " &nbsp; " + info.hippodrome + " (" + info.country + ")";
				
				row.innerHTML = (text.length < this.meetings_limit)? text : 
				                "<a title='" + text + "' class='tooltip'>" + text.substring(0, this.meetings_limit) + "...</a>";
				
				this.nextMeetingsCtnr.appendChild(row);
				row = $(row);
				this.nextMeetingsRows.push(row);
				
				meetingDisplayed = true;

				row.addClassName("list-row");
				if(i % 2 == 1) {
					row.addClassName("list-row-alt");
				}
				
				Element.observe(row, "mouseover", this.handleMeetingOver.bind(this, i));
				Element.observe(row, "mouseout", this.handleMeetingOut.bind(this, i));
				Element.observe(row, "click", this.handleMeetingClick.bind(this, i));
			  }
			}
			catch(e)
			{
				if (!meetingDisplayed)
				{
					var row = document.createElement("div");
					row.innerHTML = "<p class='BoxError'>" + noMeetingsError + 
					                "</p>";
					this.nextMeetingsCtnr.appendChild(row);
					
				}				
			}
			
			this.meetings.moreBtn.href = this.templates.getTemplate("nextmeetinglink");
		},
		
		handleMeetingOver: function (index)
		{
			this.nextMeetingsRows[index].addClassName("list-row-over");
		},
		handleMeetingOut: function (index)
		{
			this.nextMeetingsRows[index].removeClassName("list-row-over");
		},
		handleMeetingClick: function (index)
		{
			document.location.href = this.templates.getTemplate("nextmeetinglink") + "?m=" + this.meetingsData[index].id + "&d=" + this.meetingsData[index].todayTomorrow;
		},
	getElementListByClassName: function(obj, class_name)
	{ 
	  try
	  {
		  var ret = obj.getElementsByClassName(class_name);
		  return ret;
	  }
	  catch(e)
	  {
		  
		  var docList = obj.getElementsByTagName('*');
		  var arr0 = new Array();
		  var reg = new RegExp("(?:^|\\s)"+class_name+"(?:\\s|$)");
		  for(var i=0;i<docList.length;++i)
		  {
		     if(reg.test(docList[i].className) )
			 {
			   arr0[arr0.length] = docList[i];
			 }
		  }

	  return arr0;
	  
	}	
  }					
			

	});

paddock_tips = new PaddockTips();




