var request = {};
var intervalID;
var weatherVane = {};
var map = {};
var mapMarker = {};
var currentWeatherStation = '';

// window.addEvent('domready', function(){
window.addEvent('load', function(){
	if(GBrowserIsCompatible()){
		map = new GMap2(document.getElementById("terrain_gmap"));
		map.addControl(new GLargeMapControl());
		var mapCenter = new GLatLng($('current_lat').get('value'), $('current_lon').get('value'));
		map.setCenter(mapCenter, G_PHYSICAL_MAP.getMaximumResolution(), G_PHYSICAL_MAP);
		mapMarker = new GMarker(mapCenter);
		map.addOverlay(mapMarker);
		currentWeatherStation = $('weather_station').get('value');
	}
	
	/* Put the terrain wind window direction table inside the gmap so it works as an overlay */
	$('terrain_gmap').grab($('terrain_direction_table'));
	/* Hack to put the map controls on top of the table so you can actually click them */
	$('terrain_gmap').grab($('terrain_direction_table').getPrevious());

	$('terrain_gmap').grab($('terrain_map_legend'));
	$('terrain_map_legend').removeClass('hide');

	/* Setup a canvas for the weather vane */
	weatherVane = new drawing('direction',{});
	weatherVane.update(parseInt($('current_direction').value));
	terrainVane = new drawing('terrain_direction',{"show_wind_window":true});
	terrainVane.update(parseInt($('current_direction').value));

	/* Setup an ajax request object */
	request = new Request.JSON({
		url: "controller.php",
		onRequest: function(){
			// Clean out status
			$('status').innerHTML = '';
			// hide all the error marks
			$$('.error_mark').each(function(e){
				e.addClass('hide');
			});
		},
		onComplete: function(r){
			if(r.callBack){
				// If a callback was specified, execute it
				eval(r.callBack)(r);
			}
			if(r.error){
				// Show the error mark for the inputs that have issues
				r.elements.each(function(e){
					$(e+'_error_mark').removeClass('hide');
				});
				// Focus on the first errored out input
				if($(r.elements[0]) && $(r.elements[0]).focus){
					$(r.elements[0]).focus();
				}
				
				// Alert the error message
				alert(r.error_message);
				$('status').setHTML(r.error_message);
			}
		},
		onSuccess: function(){ },
		onStateChange: function(){ },
		onFailure: function(){ alert('Request Failed. Please try again later.'); }
	});
	
	if(Cookie.read('weather_station'))
		$('weather_station').setValue(Cookie.read('weather_station'));
	
	if(Cookie.read('wind_time'))
		$('wind_time').setValue(Cookie.read('wind_time'));
	
	if(Cookie.read('rider_weight'))
		$('rider_weight').setValue(Cookie.read('rider_weight'));
	
	if(Cookie.read('rider_weight_unit'))
		$('rider_weight_unit').setValue(Cookie.read('rider_weight_unit'));
		
	if(Cookie.read('wind_map_select'))
		$('wind_map_select').setValue(Cookie.read('wind_map_select'));
	
	if(Cookie.read('weather_station'))
		$('weather_chart_station').setValue(Cookie.read('weather_station'));

	if(Cookie.read('n_email'))
		$('n_email').setValue(Cookie.read('n_email'));

	
	/* cookie read returns a string, not a boolean */
	$('rapid_fire').checked = (Cookie.read('rapid_fire') == 'true');
	
	$('wind_map_select').addEvent('change', function(){
		if(this.value) $('wind_map_image').src = this.value;
	});

	$$('#weather_station, #rider_weight, #n_email').each(function(el){
		el.addEvent('blur', function(){
			Cookie.write(this.id, this.value, {duration: 365});
		});
		el.addEvent('keydown',function(event){
			var event = new Event(event);
			if(event.key == 'enter'){
				Cookie.write(this.id, this.value, {duration: 365});
			}
		});
	});

	$$('#wind_time, #rider_weight_unit, #wind_map_select').addEvent('change', function(){
		Cookie.write(this.id, this.value, {duration: 365});
	});

	$('rapid_fire').addEvent('click', function(){
		Cookie.write(this.id, this.checked, {duration: 365});
		if(this.checked){
			updateWind();
			intervalID = updateWind.periodical(3000);
		}else{
			$clear(intervalID);
		}
	});
	
	$('notification_form').addEvent('submit', function(e){
		/* Prevents the default submit event from loading a new page. */
		e.stop();
		
		/* Empty the log and show the spinning indicator. */
		$$('#n_save, #n_delete, #n_cancel').set('disabled',true);
		$('n_save').set('value','Saving...');

		this.getElements('.error').each(function(el){
			$(el).removeClass('error');
		});
		$('n_result').set('html','');

		/* Set the options of the form's Request handler. */
		this.set('send', {
			'onComplete': function(response){
				$$('#n_save, #n_delete, #n_cancel').set('disabled',false);
				$('n_save').set('value','Save');
				
				response = JSON.decode(response);

				if(response.error){
					$splat(response.elements).each(function(el){
						$(el).addClass('error');
						$(el).focus();
					});
					alert(response.error_message);
				}else if(response.success){
					$('n_result').set('html',response.success_message);
					$('existing_notifications').set('html',response.notification_list);
					
					if($('n_action').get('value') == 'remove_notification'){
						$('n_'+response.id).dispose();
						$('n_cancel').fireEvent('click');
					}else{
						$('n_id').set('value',response.id);
					}
				}else{
					$('n_result').set('html','<span class="error">There was an error saving your notification.</span>');
				}
			}
		});

		/* Send the form. */
		this.send('controller.php'); /* for some reason you have to specify the URL for IE 6 */
	});
	
	$('n_save').addEvent('click',function(e){
		$('n_action').set('value','save_notification');
	});
	
	$('n_cancel').addEvent('click',function(e){
		$('existing_notifications').getChildren().setStyle('font-weight','normal');
		$$('#n_cancel, #n_delete').set('disabled',true);
		$$('#n_cancel, #n_delete').addClass('hide');
		$$('#n_wind_value, #n_passcode, #n_id, #n_wind_duration, #n_interval').set('value','');
	});
	
	$('n_delete').addEvent('click',function(e){
		if(confirm("Are you sure you want to delete this wind watch?")){
			$('n_action').set('value','remove_notification');
		}
	});
		
	// Tabs
	$$('.tab').each(function(tab){
		$(tab).panel = $(tab.id.replace('_tab','_panel'));
		if(!tab.hasClass('selected')){
			$(tab).panel.addClass('hide');
		}else{
			$(tab).panel.removeClass('hide');
		}
	
		tab.addEvent('click',function(){ selectTab(this); });
	});

	if(window.location.hash){
		selectTab($(window.location.hash.replace('#','')+'_tab'));
	}else{
		selectTab('kite_chart_tab');
	}
	
	$('terrain_direction_table').removeClass('hide');
	// 
	$('wind_map_select').fireEvent('change');
	$('rapid_fire').fireEvent('click');
});


function updateWind(){
	request.post({action: 'update_wind', weather_station: $('weather_station').value});
}
function updateWindResponse(r){
	r.direction = parseInt(r.direction);
	
	$('current_wind').innerHTML = r.wind;
	$('current_gust').innerHTML = r.gust;
	$('terrain_map_current_wind').innerHTML = r.wind+' MPH';
	$('terrain_map_current_gust').innerHTML = r.gust+' MPH';
	
	$$("table#chart td.currentWind, table#chart td.currentGust").each(function(el){
		el.removeClass('currentWind');
		el.removeClass('currentGust');
	});
	
	$$("td.w_"+r.wind).each(function(el){
		el.addClass('currentWind');
		el.addClass('windRange');
	});
	$$("td.w_"+r.gust).each(function(el){
		el.addClass('currentGust');
	});

	$$('#direction td.currentWind').each(function(el){
		el.addClass('windRange');
		el.removeClass('currentWind');
	});

	strength = ((r.wind / 30) * .7) + .3;
	
	weatherVane.update(r.direction);
	terrainVane.update(r.direction, strength);

	/* User changed weather stations, so we have to reposition the map */
	if(r.weather_station != currentWeatherStation){
		weatherVane.history = [];
		terrainVane.history = [];
		
		currentWeatherStation = r.weather_station;
		map.setCenter(new GLatLng(r.lat, r.lon), G_PHYSICAL_MAP.getMaximumResolution(), G_PHYSICAL_MAP);
		mapMarker.setLatLng(new GLatLng(r.lat,r.lon));
	}
	
	$('updated').innerHTML = 'Updated @ ' + r.time;
}

function editNotification(notification){
	$('existing_notifications').getChildren().setStyle('font-weight','normal');
	$('n_'+notification.id).setStyle('font-weight','bold');
	
	$H(notification).each(function(value,key){
		if($('n_'+key)){
			$('n_'+key).set('value',value);
		}
	});
	$$('#n_delete, #n_cancel').set('disabled',false);
	$$('#n_delete, #n_cancel').removeClass('hide');
}

function selectTab(tab){
	var tab = $(tab);
	if(!tab) return;
	
	// Remove the selected class from all of the siblings
	$$(tab.parentNode.childNodes).each(function(sibling){
		sibling.panel.addClass('hide');
		sibling.removeClass('selected');
	});

	tab.panel.removeClass('hide');
	tab.addClass('selected');
	
	window.location.hash = tab.id.replace('_tab','');
}