var gm = GMap2.prototype;
var gi = GIcon.prototype;
var wm = null;

// the document initilization function
$(document).ready(function () {
	wm = new GMap2(document.getElementById("weathermap"));
	wm._init();
	add_points();
	wm._add_markers(wm.markers);
	// TODO: remove this as an ajax call and add it to the controller
	// cart_preview();

	// a is link, f is function to trigger
	var href_list = new Array();
	href_list[0] = {
		a : '.cart_link',
		f : add_to_cart
	}
	$('body').click(function(event) {
		for (l in href_list) {
			var h = href_list[l];
			if ($(event.target).is(h.a)) {
				h.f(event);
				return false;
			}
		}
	});

	$('.minicart_product').livequery(function() {
		$(this).hover(
			function() {
				$('#'+this.id.replace('link', 'desc')).show();
			},
			function () {
				$('#'+this.id.replace('link', 'desc')).hide();
			}
		);
	});

});

// this is called in the html_bubble.thtml view
var load_meta = function(e) {
	var t = (e.target) ? e.target : e.srcElement
	$('#weather_meta').html($('#please_wait').html());
	$.post(t.href, null, function(data) {
		$('#weather_meta').html(data);
		attach_datepicker();
	});
}

var add_to_cart = function(e) {
	var t = (e.target) ? e.target : e.srcElement
	$('#cart_preview').html($('#please_wait').html());
	$.post(t.href, null, function(data) {
		$('#cart_preview').html(data);
	});
}

// attach the jquery ui datepicker to the correct elements
function attach_datepicker() {
	var sday = $("#startday").html();
	var smonth = $("#startmonth").html();
	var syear = $("#startyear").html();
	var eday = $("#endday").html();
	var emonth = $("#endmonth").html();
	var eyear = $("#endyear").html();
	eday = Number(eday) + 1;
	var dateOptions = { 
		yearRange: syear+':'+eyear, 
		minDate: new Date(syear, smonth - 1, sday),
		maxDate: new Date(eyear, emonth - 1, eday),
		defaultDate: new Date(syear, smonth - 1, sday)
	}

	$('#searchTabs > ul').tabs({
		selected: 0,
		show: function(e, ui) {
			var sel = $(this).data('selected.tabs');
			$('#meta_results').html($('#meta'+sel).html());
		}
	});
  $('.datefield').datepicker(dateOptions);
	$('.datefield').submit(function() {
		return false;
	});
	$('.datefield').keydown(function(e) {
		$(this).datepicker("hide");
		if (e.keyCode == 13) {
			$(this).blur(); // force blur so change is not triggered twice
			$(this).change();
		 	return false; // this causes safari not to try and submit a form, which causes a page reload
		}  
	});
  $('.datefield').change(find_weather);
}

var find_weather = function() {
	var $tabs = $('#searchTabs > ul').tabs();
	var sel = $tabs.data('selected.tabs');
	if (sel == 1) {
		var ds = $('#searchDatestart').datepicker("getDate");
		var de = $('#searchDateend').datepicker("getDate");
		// set the minimum end date to the same day as the start date
		$('#searchDateend').datepicker("disable");
		$('#searchDateend').datepicker("change", { minDate: ds, defaultDate: ds });
		$('#searchDateend').datepicker("enable");
		if (!ds || !de) { return; }
	}
	// the value of this element is read by the php handler
	$('#searchSelectedTab').val(sel); 
	$('#meta_results').html($('#please_wait').html());
	$.post('/weather/search_meta', $('#meta_form').serialize(), function(data) {
		$('#meta'+sel).html(data); // this div is hidden
		// display the content of the correct hidden div
		$('#meta_results').html($('#meta'+sel).html());
	});
}

function map_goto() {
	var v  = {'location': $("#weatherAddress").val() };
	$.post("/weather/locate/", v, function(data) {
		// Unserialize JSON data
		eval("data = "+data);
		if (data['error']) {
			alert(data['error']);
		} else {
			var r = $("#weatherRadius").val();
			if (r > 0) {
				var z = wm._getZoomLevel(data['lat'], data['lng'], r);
				wm.mgr.clearMarkers(); // clear existing markers
				wm._getSearchMarkers(new GLatLng(data['lat'], data['lng']), r);
				wm._drawCircle(data['lat'], data['lng'], r);
			} else {
				var z = 9;
			}
			wm.setCenter(new GLatLng(data['lat'], data['lng']), z);	
		}
	});
}

function reset_map() {
	wm._deleteCircle();
	wm.mgr.clearMarkers();
	wm._add_markers(wm.markers);
	wm._recenter();
}

function cart_preview() {
	var t = '#cart_preview';
	var url = '/ajax/store/shopping_carts/minicart';
	$.get(url, function(data) {
		$(t).html(data);
	});
}

function ap(n, lat, lng, zoom, type) {
	wm.points[n] = new GLatLng(lat, lng);
	// create an array of markers for each zoom level
	if (!wm.markers[zoom]) {
		wm.markers[zoom] = new Array();
	}
	var i = wm.markers[zoom].length;
	var icon;
	switch(type) {
		case 's': icon = wm.iconG; break;
		case 'su': icon = wm.iconB; break;
		default: icon = wm.iconR;
	}
	wm.markers[zoom][i] = new GMarker(wm.points[n], icon);
	// icon needs to be saved to the point so it can be retrieved
	// in _getSearchMarkers
	wm.points[n].icon = icon;
	wm.markers[zoom][i].id = n;
	GEvent.addListener(wm.markers[zoom][i], "click", markerEvent);
}

var markerEvent = function() {
	if (this.html) { 
		this.openInfoWindowHtml(this.html); 
	} else {
		var m = this;
		$.get("/weather/html_bubble/"+m.id, function(data) {
			m.html = data;
			m.openInfoWindowHtml(m.html);
		});
	}
}

// takes a point and a radius and finds the zoom level
// that contains a circle defined by them
gm._getZoomLevel = function(lt, ln, r)
{
	var deg = Number(r)/69.172;
	var sw = new GLatLng(lt-deg, ln-deg);
	var ne = new GLatLng(lt+deg, ln+deg);
	var bnds = new GLatLngBounds(sw, ne);

	return this.getBoundsZoomLevel(bnds);
}

gm._getSearchMarkers = function(center, d)
{
	var r = d*1.609344*1000;
	if (this.sMarkers[3]) {
		while (this.sMarkers[3].pop()) { ; }
	} else {
		this.sMarkers[3] = new Array();
	}
	var j = 0;
	for (i in this.points) {
		if (center.distanceFrom(this.points[i]) < r) {
			j = this.sMarkers[3].length;
			this.sMarkers[3][j] = new GMarker(this.points[i], this.points[i].icon);
			this.sMarkers[3][j].id = i;
			GEvent.addListener(this.sMarkers[3][j], "click", markerEvent);
		}
	}
	this.mgr.clearMarkers();
	this._add_markers(this.sMarkers);
}

// adds markers to the map
// m is an array of arrays
// the index of the top level array is the zoomlevel in which to display
// that array of markers
gm._add_markers = function(m) {
	for (i in m) {
		this.mgr.addMarkers(m[i], i);
	}
	this.mgr.refresh();
}

// deletes a radius circle and frees the memory
gm._deleteCircle = function() {
	if (this.mapCircle) {
		this.removeOverlay(this.mapCircle);
		delete this.mapCircle;
	}
}

gm._drawCircle = function(lat, lng, rad) {
	var r = rad*1.609344;
	// this._deleteCircle();
	this.mapCircle = new BDCCCircle(new GLatLng(lat, lng), r, "#ef5f10", 3, 0.5, false);
	this.addOverlay(this.mapCircle);
}

gm._init = function() {
	var m = this;
	m._recenter();
	m.addControl(new GLargeMapControl());
	m.addControl(new GMapTypeControl());
	m.addMapType(G_PHYSICAL_MAP);
	m.mgr = new MarkerManager(wm);
	m.points = {};
	m.markers = {};
	m.sMarkers = {};
	m.iconR = new GIcon();
	m.iconR._init('mm_20_red.png');
	m.iconG = new GIcon();
	m.iconG._init('mm_20_green.png');
	m.iconB = new GIcon();
	m.iconB._init('mm_20_blue.png');
}

// recenters the map above the continental US
gm._recenter = function() {
	this.setCenter(new GLatLng(39.50, -96.35), 3);
}

gi._init = function(image) {
	var i = this;
	i.image = 'http://labs.google.com/ridefinder/images/'+image;
	i.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
	i.iconSize = new GSize(12, 20);
	i.shadowSize = new GSize(22, 20);
	i.iconAnchor = new GPoint(6, 20);
	i.infoWindowAnchor = new GPoint(5, 1);
}

