/**
 * @author anthony byram
 * @version 0.2-beta
 */

Location = function(lat, lng, name) {
	this.lat = lat;
	this.lng = lng;
	this.name = name;
}

Location.prototype = {
	setLat:function(lat) {
		this.lat = lat;
	},
	setLng:function(lng) {
		this.lng = lng;
	},
	setName:function(name) {
		this.name = name;
	}
}

WeatherCompare = function(address1, address2) {
	this.location1 = null;
	this.location2 = null;
	this.data = null;
	this.maxt = null;
	this.mint = null;
	this.gmap = new Map("map");
	weather_compare = this;

	this.view = function(){
		return new WeatherCompareView(this.data);
	}
}

WeatherCompare.prototype = {
	
	update : function(address1, address2, mint, maxt) {
		weather_compare = this;
		weather_compare.gmap.clearMarkers();
		weather_compare.setMinT(mint);
		weather_compare.setMaxT(maxt);
		this.gmap.addMarkersByAddress(Array(address1, address2), function(map) {


			weather_compare.getLocations(map);
			weather_compare.compare();
		});
	},
	
	setLocation1: function(location) {
		this.location1 = location;
	},
	
	setLocation2: function(location) {
		this.location2 = location;
	},
	
	getLocations: function(map) {
		this.location1 = map.locations[0];
		this.location2 = map.locations[1];
	},
	
	setMinT: function(mint) {
		this.mint = mint;
	},
	
	setMaxT: function(maxt) {
		this.maxt = maxt;
	},
	
	compare: function() {
		weather_compare = this;
		formStartLoading("#compareAddForm", "Comparing and Loading weather data...");
		$.getJSON( "/weather/compare/"+this.location1.lat+"/"+this.location1.lng+"/"+this.location2.lat+"/"+this.location2.lng+"/"+this.maxt+"/"+this.mint+".json", null, function(data){
			weather_compare.data = data;
			weather_compare.view();
		});
	}
}

WeatherCompareView = function(data) {
	this.div = $("#weather-compare");
	this.setData(data);
	this.compare();
}

WeatherCompareView.prototype = {
	
	setData:function(data) {
		this.data = data;
	},
	
	compare:function() {
		this.emptyTable();
		for (var i = 0; i < this.data.length; i++) {
			var row = this.data[i];
			this.addRow(row.date, row.location1.maxt+"/"+row.location1.mint, row.location2.maxt+"/"+row.location2.mint, row.location1.min_status+"/"+row.location2.min_status, row.location1.max_status+"/"+row.location2.max_status);
		}
			stripeTables();
			this.colorCodeTable();
			formDoneLoading("#compareAddForm");
			$.scrollTo("#weather-compare", 400);
			
	},
	
	emptyTable: function() {
		this.div.children("table").children("tbody").remove();
	},
	
	addRow: function(date, location1, location2, min_status, max_status) {
		var row = "<tr><td>"+date+"</td>"+
						"<td>"+location1+"</td>"+
						"<td>"+location2+"</td>"+
						"<td>"+min_status+"</td>"+
						"<td>"+max_status+"</td></tr>";
		$("#weather-compare table").append(row);
	},
	
	colorCodeTable: function() {
		$("#weather-compare table tbody tr td").each(function (i){
			var text = $(this).html();
			if(text.search(/ok/) > -1) {
				$(this).addClass("status-ok");
			}
			if(text.search(/too\scold/) > -1) {
				$(this).addClass("status-too-cold");
			}
			if(text.search(/too\shot/) > -1) {
				$(this).addClass("status-too-hot");
			}
		});
	}
}

function Map(div) {
	this.div = document.getElementById(div);
	this.compatible = function() { return GBrowserIsCompatible();}
	this.geocoder = new GClientGeocoder();
	
	this.initialize();
	
	
	if (this.compatible) {
		this.Gmap = new GMap2(this.div);
		this.Gmap.addControl(new GLargeMapControl());
		this.Gmap.addControl(new GMapTypeControl());
		this.Gmap.setCenter(new GLatLng(37.4419, -122.1419), 2);

	} else {
		
	}
}

Map.prototype = {
	markers:new Array(),
	displayReady: false,
	addMarkersByAddress:function(addresses, call) {
		var markers = this.markers;
		var map = this;
		var i=0;
		var j=0;
		for(i=0; i < addresses.length; i++) {
			var address = addresses[i];
			this.geocoder.getLatLng(address, function(point) {
				formStartLoading("#compareAddForm", "Getting locations...");
				if (point) {
					
					map.locations[markers.length] = new Location(point.lat(), point.lng(), addresses[j]);
					//markers[markers.length] =  point;
					map.addMarker(point);
					if( (j+1) == addresses.length) {
						map.markers = markers;
						map.displayMarkers();
						call(map);
					}
				} else {
					console.warn("Could not find address");
				}
				j++;
			});
		}
	},
	
	addMarker: function(point) {
		this.markers[this.markers.length] = point;
		this.markersCount = this.markers.length;
	},
	
	clearMarkers:function() {
		this.initialize();
		this.Gmap.clearOverlays();
	},
	
	displayMarkers:function() {
		this.Gmap.clearOverlays();
		for(i=0; i < this.markers.length; i++) {
			this.Gmap.addOverlay(this.createMarker(this.markers[i], i));
		}
		this.centerMap();
	},
	
	createMarker: function(point, n) {
		var marker = new GMarker(point);
		var map = this;
        GEvent.addListener(marker,'mouseover',function(){
                marker.openInfoWindowHtml(map.locations[n].name);
        });
        return marker; 
	},
	
	removeMarkers:function() {
		delete this.markers;
		this.markers = Array();
	},
	
	centerMap: function() {
		var bounds = new GLatLngBounds();
		for (var i=0; i< this.markers.length; i++) {
			bounds.extend(this.markers[i]);
		}
		this.Gmap.setZoom(this.Gmap.getBoundsZoomLevel(bounds));
		this.Gmap.setCenter(bounds.getCenter());
	},
	
	initialize: function() {
		this.locations = [];
		this.locationsCount = 0;
		this.locationsReady = true;
		
		this.markers = [];
		this.markersCount = 0;
		this.markersReady = true;
	}

}

var error = function(msg) {
	$("#console").append("<p class='error'>"+msg+"</p>");
}

var clear_console = function() {
	$("#console").children().remove();
}

var formInputMessage = function(formElement, msg) {
	$(formElement).parent().children(".message").remove();
	$(formElement).parent().append("<p class=message>"+msg+"</p>");
}

var formInputClearMessages = function() {
	$(".input .message").remove();
}

var formStartLoading = function(form, message) {
	var submit = $(form).children(".submit");
	submit.children("input").hide();
	submit.children(".loading").remove();
	var loading_bar = $("<div class=loading><p>"+message+"</p><img src=/img/loading-bar.gif/></div>");
	submit.append(loading_bar);
}

var formDoneLoading = function(form) {
	var submit = $(form).children(".submit");
	submit.children(".loading").remove();
	submit.children("input").show();
}

var stripeTables = function() {
	$("table tbody tr:even").addClass('alt');
}



$(document).ready(function(){
	$("#map").css("width", $("#maincontent").css("width"));
	var weather = new WeatherCompare();
	var gmap = weather.gmap;

	$(window).resize(function(){
		$("#map").css("width", $("#maincontent").css("width"));
		weather.gmap.Gmap.checkResize();
	});

	
	$("#compareAddForm").submit( function() {
		return false;
	});
	$("#compareAddForm .submit input").click( function(){
				
		var validForm = true;
		formInputClearMessages();
		var formElements = ["#compareLocation-1", "#compareLocation-2", "#compareMinTemp", "#compareMaxTemp"];
		
		for(formElement in formElements) {
			element = formElements[formElement];
			if($(element).val() == "" || $(element).val() == null) {
				var label = $(element).parent().children("label").html();
				label = label.slice(0,-2)
				formInputMessage(element, label+" cannot be left blank.");
				var validForm = false;
			}
		}
		
		if (validForm) {
			var location1 = $("#compareLocation-1").val();
			var location2 = $("#compareLocation-2").val();
			var mint = $("#compareMinTemp").val();
			var maxt = $("#compareMaxTemp").val();
			weather.update(location1, location2, mint, maxt);
		}
		$(this).parent().children(".loading").remove();
		$(this).show();
		return false;
	});
	
	
});

