
var ct = {
	c:0,
	active:'',
	orign:'',
	dest:'',
	bound:'nb',
	is_wkend:false,
	key:'',
	day:'',
	trains:null,
	departures:null,
	arrivals:null,
	stops:null,
	num_stops:null,
	init:function()
	{	
		this.num_stops = $('stop_dest').options.length - 1; // minus "please pick..."
	
		// Get any cookies
		this.setWkend();
		this.getRoute();

		// If cookie, default to that schedule & hide stops
		if ($('stop_orign').value && $('stop_dest').value) {
			this.route();
		} else {
			this.selectView('stops');
		}
		
		// UI Jonx
		$('day').innerHTML = this.is_wkend ? 'Weekend' : 'Weekday';
									
		// Set up all click events
		attr.setClick($('set_route'), 'ct.route();');
		attr.setClick($('open_schedule'), 'ct.selectView(\'times\');');
		attr.setClick($('close_schedule'), 'ct.selectView(\'ticker\');');		
		
	},
	route:function()
	{
		this.setRoute();
		this.fetchSchedule();
	},
	setRoute:function()
	{
		if ($('stop_orign').value == '' || $('stop_dest').value == '') {
			return;
		}
	
		this.orign = parseInt($('stop_orign').value);
		this.dest = parseInt($('stop_dest').value);

		if (this.orign > this.dest) {
			this.setBound('sb');
		} else {
			this.setBound('nb');
		}
		
		this.setKey();

		cookie.eat();
		cookie.bake(this.orign+':'+this.dest);
		
		if (this.active == 'times') {
			this.selectView('times');
		} else {
			this.selectView('ticker');
		}
		
		$('route').innerHTML = this.htmlTrainHeader();
	},
	getRoute:function()
	{
		var c_route = cookie.taste();
		if (c_route) {
			var stops = c_route.split(':');
		
			$('stop_orign').value = stops[0];
			$('stop_dest').value = stops[1];		
		}
	},
	setBound:function(bound)
	{
		this.bound = bound;
	},
	flip2Bound:function(bound)
	{
		if (this.bound == bound) {
			return;
		}
		
		this.setBound(bound);
		this.flipStops();
		this.route();
	},	
	flipStops:function()
	{
		var tmp = $('stop_dest').value;
		$('stop_dest').value = $('stop_orign').value;		
		$('stop_orign').value = tmp;
	},
	setWkend:function() {
		this.is_wkend = timer.isWkend();
	},
	setKey:function()
	{
		this.setWkend();
		this.key = (this.is_wkend ? 'w' : '') + this.bound;
	},	
	buildTicker:function()
	{	
		var next = this.calculateNextTrain();

		var next_html = '';
		var schedule_html = '';
		var stop_detail = '';
		
		var count = 0;
		var next_count = 0;
		
		for (x = 0; x < this.departures.length; x++) {	
			if (this.departures[x] != 0 && this.arrivals[x] != 0) {
				var wait = timer.calculateWait(this.departures[x]);
				var departs = timer.convert2TwelveHour(this.departures[x]);
				var arrives = timer.convert2TwelveHour(this.arrivals[x]);
				
				stop_detail = this.htmlStopDetail(this.trains[x],
											departs.time,
											arrives.time,
											(next && x >= next ? wait.time : null),
											(next && x >= next ? wait.inc : null),
											(count % 2 == 0));	
				
				schedule_html += stop_detail;
				
				if (x == next) {
					next_count++;
					next_html += this.htmlNextTrain(this.trains[x],
												departs.time,
												arrives.time,
												wait.time+(wait.inc == 'h' ? '<span><small>h</small></span>' : ''));
				} else if (next_count == 1) {
					next_html += '<div class="box dark">'+
									'<div class="top">'+stop_detail+'</div>';
					next_count++;
				} else if (next_count == 2) {
					next_html += '<div class="btm">'+stop_detail+'</div>'+
									'</div>';
					next_count++;
				}					

				count++;
			}
	
			setTimeout("window.scrollTo(0,1)", 1000);
			
			$('next_details').innerHTML = next_html;
			$('schedule_details').innerHTML = schedule_html;
			
			if (!next) {
				this.selectView('times');
			}
		} 
	},
	htmlTrainHeader:function()
	{
		return '<div id="stop_names" onClick="ct.selectView(\'stops\');">'+
					'<div class="orign_name">'+
							$('stop_orign').options[this.orign+1].innerHTML+
						'</div>'+
						'<div class="dest_name">'+
							$('stop_dest').options[this.dest+1].innerHTML+
						'</div>'+	
					'</div>'+
				'</div>'+
				'<div id="compass" class="'+(this.bound == 'nb' ? 'nb' : 'sb')+'">'+
					'<div id="nb_flip" class="compass_btn" onClick="ct.flip2Bound(\'nb\');"></div>'+
					'<div id="sb_flip" class="compass_btn" onClick="ct.flip2Bound(\'sb\');"></div>'+
				'</div>';
	},
	htmlNextTrain:function(train_no, departs, arrives, wait_time) 
	{
		return  '<div class="next_train">'+
					'<div class="box">'+
						'<div id="wait_time">'+
							wait_time +
						'</div>'+
						'<div id="details">'+
							'<span class="train_no">'+
								(train_no ? '#'+train_no : '') +
							'</span>'+
							'<span class="departs">'+
								departs+' <small>/ '+arrives+'</small>'+
							'</span>'+							
						'</div>'+
					'</div>'+
				'</div>';
	},		
	htmlStopDetail:function(train_no, departs, arrives, wait_time, wait_inc, odd) 
	{
		return  '<div class="row'+(odd ? ' odd' : '')+'">'+
					'<div class="col departs">'+
						departs+ ' <small>/ '+arrives+'</small>'+
					'</div>'+			
					'<div class="col wait_time">'+
						(wait_time ? wait_time+'<span class="tiny">'+wait_inc+'<span>' : '' )+
					'</div>'+														
					'<div class="col train_no">'+
						(train_no ? '<span class="tiny">#</span>'+train_no : '')+
					'</div>'+					
				'</div>';
	},
	fetchSchedule:function()
	{
		var pars = $H();
		pars['key'] = this.key;
		pars['orign'] = this.bound == 'sb' ? this.num_stops - this.orign - 1 : this.orign;
		pars['dest'] = this.bound == 'sb' ? this.num_stops - this.dest - 1 : this.dest;
		$('next_details').innerHTML = '<div class="warning">Loading...</div>';
		$('schedule_details').innerHTML = '<div class="warning">Loading...</div>';

		var setupSchedule = function(transport) {
		  	var data = transport.responseText.evalJSON();
	
			ct.departures = data.departs.split(',');
			ct.arrivals = data.arrives.split(',');
			ct.trains = data.trains.split(',');
			ct.day = data.day;

			ct.buildTicker();
		}
		
		ajax.request(setupSchedule, pars);
	},
	calculateNextTrain:function()
	{
		if (this.departures.length <= 0) {
			return false;
		}
	
		var m = timer.m;
		if (m < 10) { m = '0'+m; }
		
		var time = parseInt(timer.h+''+m);
		
		for (x = 0; x < this.departures.length; x++) {
			var depart = parseInt(this.departures[x].replace(/:/, ""));
			if (time <= depart && (this.departures[x] != 0 && this.arrivals[x] != 0)) {
				return x;
			}
		}
		
		return false;
	},
	selectView:function(id)
	{
		this.active = id;
		attr.setClass($('caltrain'), id);		
		
		return false;
	}
}

var attr = {
	setAtt:function(obj, att, val)
	{
		obj.setAttribute(att, val);
	},
	setClass:function(obj, val) 
	{
		this.setAtt(obj, 'class', val);
	},
	addClass:function(obj, val)
	{
		this.setClass(obj, obj.className + ' ' + val);
	},
	rmClass:function(obj, val)
	{
		this.setClass(obj, obj.className.replace(val, ""));
	},
	hasClass:function(obj, val)
	{
		return obj.className.search(val) >= 1;
	},
	setClick:function(obj, val) 
	{
		this.setAtt(obj, 'onClick', val+'return false;');
	}
}

var cookie = {
	name:'ct_route_20100503_01',
	getName:function()
	{
		return this.name + (ct.is_wkend ? '_wkend' : '');	
	},
	bake:function(value)
	{
		var name = this.getName();
	
		var date = new Date();
		date.setTime(date.getTime()+(365*24*60*60*1000));
		
		var expires = "; expires="+date.toGMTString();

		document.cookie = name+"="+value+expires+"; path=/caltrain/";
	},
	taste:function()
	{
		var name = this.getName();
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	},
	eat:function()
	{
		var name = this.getName();
	
		this.bake(name,"",-1);
	}
}

var ajax = {
	q:'ajax/caltrain.php',
	data:null,
	request:function(onSuccessFunction, pars) 
	{
		var url = this.q+this.buildPars(pars);
		
		new Ajax.Request(url, {
		  method: 'get',
		  onSuccess: onSuccessFunction
		});
	},
	buildPars:function(pars) 
	{
		var c = 0;
		var qp = '?';
		pars.each(function(pair) {
			qp += (c > 0 ? '&' : '') + pair.key + '=' + pair.value;
			c++;
		});
		
		return qp;
	}
}

var timer = {
	t:"",
	h:"",
	m:"",
	s:"",
	now:"",
	day:"",
	ampm:"",
	time:"",
	update:"",
	tick:function()
	{
		this.now = new Date();	
		this.day = this.now.getDay();

		this.h = this.now.getHours();
		this.m = this.now.getMinutes();
		this.s = this.now.getSeconds();
	
		if (ct && this.update && (this.s == 0 || (this.update != this.h+":"+this.m))) {
			if (this.isWkend() != ct.is_wkend) {
				alert('Loading '+(this.isWkend() ? 'Weekend' : 'Weekday')+' Schedule...');
				location.reload(true);
			} else {
				ct.buildTicker();
			}
		}

		var tt = this.convert2TwelveHour(this.h+":"+this.m);

		$('time').innerHTML = '<strong>'+tt.h+':'+tt.m+'</strong>'+tt.ampm;
		attr.setClass($('dot'), (this.s % 2 == 0 ? 'light' : ''));

		this.update = this.h+":"+this.m;		
		this.t = setTimeout("timer.tick()", 1000);		
	},
	isWkend:function()
	{
		return this.day == 0 || this.day >= 6;
	},
	convert2TwelveHour:function(time)
	{	
		var t = this.parseTime(time);
		var ampm = (t.h >= 12) ? 'p' : 'a';
		
		t.h = (t.h == 0) ? 12 : (t.h > 12 ? t.h - 12 : t.h);
		
		return {"time":t.h+':'+t.m,
				"h":t.h,
				"m":t.m,
				"ampm":ampm};
	},	
	calculateWait:function(time)
	{
		var t = this.parseTime(time,true);

		var wh = parseInt(t.h) - this.h;		
		var wm = parseInt(t.m) - this.m;
		
		if (wh > 0 && wm < 0) {
			wh -= 1;
			wm += 60;
		}

		var wait = '';
		
		if (wh > 0) {
			var dec = Math.round((wm / 60)*10);
			
			wait = wh+'.'+(dec >= 10 ? 9 : dec);
		} else if (wm >= 0) {
			wait = '<span>0</span><span id="colon">:</span>'+(wm < 10 ? '<span>0</span>':'')+wm;
		}
		
		return {"time":wait,"inc":(wh > 0 ? 'h':'m')};		
	},	
	parseTime:function(time){
		var t = time.split(':');
		var h = parseInt(t[0]);
		var m = parseInt(t[1]);
		
		if (m < 10) {
			m = "0"+""+m;
		}
		
		return {"h":h,"m":m};
	},
	init:function()
	{
		if ($('time') && this.t == "") {
			this.tick();
		}
	}
}

function init() {
	window.scrollTo(0,1);
	timer.init();
	ct.init();
}


init();