Weather = function()
{
	this.start();
}

function initWeather()
{
	weatherMap = new Weather();
}

google.setOnLoadCallback(initWeather);
google.load("maps", "2", {"other_params":"sensor=false"});

Weather.prototype.start = function()
{
	this.map = new google.maps.Map2(document.getElementById("map"));
	this.map.setUIToDefault();
	
	var that = this;
			
	// Register an AJAX reponder to show/hide the activity indicator 
	// when perform an ajax request.
	/*Ajax.Responders.register(
	{
		onCreate: function() 
		{
			if (Ajax.activeRequestCount > 0 && ($('ajax-activity') && $('ajax-activity').visible() === false))
			{
				$('ajax-activity').show();
			}
		},
		onComplete: function() 
		{
			if (Ajax.activeRequestCount === 0 && ($('ajax-activity') && $('ajax-activity').visible() === true))
			{
				$('ajax-activity').hide();
			}
		}
	});*/
	
	// Fire up the ajax and load the initial set of spots.
	ajax = new Ajax.Request('/ajax/get_user_lat_long/', 
	{
		method: 'get',
		onSuccess: function (transport, json) 
		{
			json = eval(transport.responseText);
			
			that.userLat = json.lat;
			that.userLong = json.long;
			that.localLevel = json.local_level;
			that.ISO2 = json.ISO2;
			that.setUpMap();
		}
	});
}

Weather.prototype.showAll = function()
{
	this.map.setCenter(new GLatLng(25, 0), 1);
}

Weather.prototype.setUpMap = function()
{
	//Auto set up on location
	//this.map.setCenter(new GLatLng(this.userLat, this.userLong), this.getInitialZoomLevel());	
	
	//Show the current region
	this.map.setCenter(new GLatLng(landingLat, landingLong), landingZoom);
		
	if (isSmallMap == false)
	{
		// Turn on scroll zooming.
		this.map.enableScrollWheelZoom(); 
		// Disable wheel scrolling if the user is over the map.
		// http://esa.ilmari.googlepages.com/scrollzoom.htm
		GEvent.addDomListener(this.map.getContainer(), "DOMMouseScroll", this.disableWheelEvent);
		this.map.getContainer().onmousewheel = this.disableWheelEvent; 
	}
	else
	{
		this.map.disableScrollWheelZoom();
	}
	
	var that = this;
	GEvent.addListener(this.map, "zoomend", function(oldZoom,newZoom) 
	{
		if (newZoom > oldZoom)
		{ 
			// When zooming with a window open, the map tends to pan it sels 
			// to the new window. To sort that, we'll just refocus on that open window
			// anwyay when zooming.
			if (that.map.getExtInfoWindow())
			{
				that.map.setCenter(that.map.getExtInfoWindow().marker_.getLatLng());
			}
		} 
		
		that.buildMapPoints();
	});

	GEvent.addListener(this.map, "moveend", function() 
	{
		that.buildMapPoints();
	});

	// Set default map type to terrain map
	this.map.setMapType(G_PHYSICAL_MAP);
	
	// Remove the types we dont want.
	this.map.removeMapType(G_HYBRID_MAP);
	this.map.removeMapType(G_PHYSICAL_MAP);
	this.map.removeMapType(G_NORMAL_MAP);
	this.map.removeMapType(G_SATELLITE_MAP);
	
	G_PHYSICAL_MAP.getMinimumResolution 	= function () { return 2 }; 
	G_NORMAL_MAP.getMinimumResolution 		= function () { return 2 }; 
	G_SATELLITE_MAP.getMinimumResolution 	= function () { return 2 }; 
	
	// And add the one we do.
	//this.map.addMapType(G_PHYSICAL_MAP);
	
	// Kick off the zoom check
	var that = this;
	
	easeZoomOut = function()
	{
		var paragraphs = that.map.getContainer().getElementsByTagName('p').length;
		
		if(paragraphs > 6)
		{
			that.map.zoomOut();
		}
	}
	
	interval = setInterval(easeZoomOut,500);
		
	this.constructIcons();
	this.buildMapPoints();
	
	//Debug, show the landing zone
	if (landingRect != "")
	{
		//This may or may not get in the way of the rollover states of items inside. It's hard to tell.
		//this.drawPoly(landingRect[0], landingRect[1], landingRect[2], landingRect[3]);
	}
	
	//Show all of the available regions - landingZoneRegions is a json object set in the main weather home page, not pulled in by ajax
	if (landingZoneRegions != null)
	{
		this.drawRegions(landingZoneRegions);
	}
	
	this.resizeMap();
}

Weather.prototype.resizeMap = function()
{
	//We don't dynamically resize the map in weather like we do in local...
	
	//var mapHeight = document.viewport.getHeight()-($('headWrapper').getHeight() + $('mapHead').getHeight() + 60);
	//if ($('msg-message').visible())
	//{
	//	mapHeight = mapHeight - $('msg-message').getHeight();
	//}
	//$('map').setStyle({height: 300 +'px'});
}

Weather.prototype.getInitialZoomLevel = function()
{
	var zoomLevel = this.MIN_ZOOM_LEVEL;
	
	if (this.localLevel == 'country')
	{
		zoomLevel = 5;
		
		// Because the US, China, Australia and Canada are so big, we need to make an exception and zoom further out to take it in.
		if (this.ISO2 == 'US' || this.ISO2 == 'CN' || this.ISO2 == 'CA' || this.ISO2 == 'AU')
		{
			zoomLevel = 4;	
		}
		
		// Well russial is just extra huge. Zoom even further out.
		if (this.ISO2 == 'RU')
		{
			zoomLevel = 3;	
		}
		
	}
	else if (this.localLevel == 'local')
	{
		zoomLevel = 9;	
	}
	
	return zoomLevel;	
}

Weather.prototype.constructIcons = function()
{
	this.baseUserIcon = new GIcon();
	this.baseUserIcon.shadow = MPORA.globalVars.static_base_url+"resources/images/site/user_pin_shaddow.png";
	this.baseUserIcon.iconSize = new GSize(42,32);
	this.baseUserIcon.shadowSize = new GSize(42, 32);
	this.baseUserIcon.iconAnchor = new GPoint(9, 32);
	this.baseUserIcon.infoWindowAnchor = new GPoint(51,0);
	this.baseUserIcon.infoShadowAnchor = new GPoint(13, 28);	
	
	this.baseSpotIcon = new GIcon();
	this.baseSpotIcon.shadow = MPORA.globalVars.static_base_url+"resources/images/site/spot_shaddow.png";
	this.baseSpotIcon.iconSize = new GSize(56,35);
	this.baseSpotIcon.shadowSize = new GSize(56,35);
	this.baseSpotIcon.iconAnchor = new GPoint(17,35);
	this.baseSpotIcon.infoWindowAnchor = new GPoint(50,0);
}

// Take input data from various sources (ajax, inline etc) and use it to add markers, and HTML windows to the map.
// point = lat/long object.
// htmlSrc = html plaintext source for the overlay window
// maxZoomLevel/minZoomLevel set the max/min zoom levels that this marker will appear at. 
Weather.prototype.addExistingPoint = function(opts, id)
{
	minZoomLevel = opts.minZoomLevel || this.MIN_ZOOM_LEVEL;
	
	// Some sort of spot pin.
	var spotIcon = new GIcon(this.baseSpotIcon);
	spotIcon.image = MPORA.globalVars.static_base_url+'resources/images/site/'+opts.spot_type+'_spot.png';

	var marker = new GMarker(opts.point, {icon:spotIcon});
	var that = this;
	
	GEvent.addListener(marker, 'click', function()
	{ 
		marker.openExtInfoWindow
		(
			that.map,
			"spot-local-infowindow",
			opts.htmlSrc,
			{beakOffset: 2}
		);
	});
	this.clusterPoints.push(marker);
	return marker;
}
	
// Returns the latlong object required by google, given the lat/long as floats.
Weather.prototype.getLatLong = function(lat, long)
{
	return new GLatLng(lat, long);
} 

// This function stops the default browser mouse wheel scroll action
// http://esa.ilmari.googlepages.com/scrollzoom.htm
Weather.prototype.disableWheelEvent = function(e)
{
	if (!e)
	{
		e = window.event;
	}
	
	if (e.preventDefault)
	{
		e.preventDefault()
	}
	
	e.returnValue = false;
}

Weather.prototype.buildMapPoints = function(opt_opts)
{	
	// Get the bubble html and populate some vars.
	this.getBubbleHtml_();

	//var opts = (opt_opts == null) ? {} : opt_opts;

	//var showUserPins 	= (opts.showUserPins == null) 	? this.getUserPinStatus()  	: opts.showUserPins;
	//var showFriendPins 	= (opts.showFriendPins == null) ? this.getFriendPinStatus()	: opts.showFriendPins;
	//var spotType 		= (opts.spotType == null) 		? this.getCategory() 		: opts.spotType;
		
	this.getSpots();
}

Weather.prototype.drawRegions = function(regionList)
{
	//(swLat, swLong, neLat, neLong)
	var that = this;
	jQuery.each(regionList, function(i, region) {
		var polygon = that.drawPoly(region['nw_lat'], region['se_long'], region['se_lat'], region['nw_long']);			  
	
		GEvent.addListener(polygon,"mouseover",function() { 
			polygon.setStrokeStyle({color:"#ff0000", weight:4, opacity:0.8});
			polygon.redraw(true);
		});
		
		GEvent.addListener(polygon,"mouseout",function() { 
			polygon.setStrokeStyle({color:"#ff0000", weight:1, opacity:0.0});
			polygon.redraw(true);
		});
		
		GEvent.addListener(polygon,"click",function() { 
			polygon.setStrokeStyle({color:"#215fff", weight:4, opacity:0.5});
			polygon.redraw(true);
			document.location = mainUrl + region['url_name'] + '/';
		});
	});
}

Weather.prototype.getFriendPinStatus = function()
{
	return ($('my_friends_spots') && $('my_friends_spots').hasClassName('my_friends_pin_selected')) ? true : false;
}

Weather.prototype.getUserPinStatus = function()
{
	return ($('my_spots') && $('my_spots').hasClassName('my_spots_pin_selected')) ? true : false;
}

Weather.prototype.getCategory = function()
{
	return $F('categories');
}

Weather.prototype.getBubbleHtml_ = function()
{	
	var that = this;
	
	if (!this.spotBubbleHtml_)
	{
		new Ajax.Request('/ajax/get_bubble_html/', 
		{
			method: 'get',
			onSuccess: function (transport) 
			{
				that.spotBubbleHtml_ = transport.responseText;
			}
		});	
	}
}

Weather.prototype.getSpots = function(phrase)
{
	// Get the map points.
	var bounds = this.map.getBounds();
	
	// Cancel any previous request..
	if (this.ajaxPoints)
	{
		this.ajaxPoints.transport.abort();
	}
	
	this.clusterPoints = [];
	var that = this;
	
	var ajaxURL = '';
	var regionBounds = bounds.getNorthEast().lat()+'/'+bounds.getSouthWest().lng()+'/'+bounds.getSouthWest().lat()+'/'+bounds.getNorthEast().lng()+'/';
	if (phrase == null)
	{
		if (weatherType == 'surf')
		{
			ajaxURL = '/ajax/get_surf_brakes_in_region/' + regionBounds;
		}
		else
		{
			ajaxURL = '/ajax/get_snow_spots_in_region/' + regionBounds;
		}
	}
	else
	{
		if (weatherType == 'surf')
		{
			ajaxURL = '/ajax/search_surf_brakes/' + regionBounds + phrase + '/';
		}
		else
		{
			ajaxURL = '/ajax/search_snow_spots/' + regionBounds + phrase + '/';
		}
	}	
	
	// Fire up the ajax and load the initial set of spots.
	this.ajaxPoints = new Ajax.Request(ajaxURL,
	{
		method: 'get',
		onSuccess: function (transport, json) 
		{
			json = eval(transport.responseText);
			var jsonLen = json.length;
			if ( jsonLen > 0)
			{			
				if (phrase != null)
				{
					var searchFeedback = jQuery("#search_feedback");
					if (searchFeedback.length > 0)
					{
						jQuery(searchFeedback).html(searchFound);
					}	
				}
				for (i=0; i < jsonLen; i++)
				{
					var bubbleHtml = '';
					bubbleHtml = new Template(that.spotBubbleHtml_);	
								
					// Eval the template and get the final html.
					//WTF? The json names are all different...
					if (weatherType == 'surf')
					{
						spot_type = "surfing";	
						that.addExistingPoint({point:that.getLatLong(json[i].lat, json[i].lng), htmlSrc:bubbleHtml.evaluate(json[i]), spot_type:spot_type}, json[i].id);
					} else {
						spot_type = "snow";
						that.addExistingPoint({point:that.getLatLong(json[i].spot_lat, json[i].spot_long), htmlSrc:bubbleHtml.evaluate(json[i]), spot_type:spot_type}, json[i].id);
					}
					
					
				}
				
				if (!that.cluster)
				{
					that.cluster=new ClusterMarker(that.map, { fitMapToMarkers:false} );
				}
				
				that.cluster.removeMarkers();
				that.cluster.addMarkers(that.clusterPoints);
				that.cluster.refresh();	
				that.map.closeExtInfoWindow();
				
				that.resizeMap();
				if (that.clusterPoints.length >= 200)
				{
					//new Effect.Appear('msg-message', {duration:0.5, afterFinish:function(){ that.resizeMap(); }});
				}
				else
				{
					//new Effect.Fade('msg-message', {duration:0.5, afterFinish:function(){ that.resizeMap(); }});	
				}
			}
			else
			{
				//Zoom out, search again
				//that.showAll();
				var searchFeedback = jQuery("#search_feedback");
				if (searchFeedback.length > 0)
				{
					jQuery(searchFeedback).html(searchNotFound);
				}
			}
		}
	});
}

Weather.prototype.drawPoly = function (swLat, swLong, neLat, neLong)
{
	var polygon = new GPolygon([
	new GLatLng(swLat, swLong),
	new GLatLng(swLat, neLong),
	new GLatLng(neLat, neLong),
	new GLatLng(neLat, swLong),
	new GLatLng(swLat, swLong)
	], "#ff0000", 1, 0.0, "#ff0000", 0.0, {clickable:true});
	this.map.addOverlay(polygon);
	return(polygon);
}

/* Weather send to friend
-----------------------------------------------------*/
var mapSearchOpen;

jQuery(document).ready(function() {
    initWeatherSearch();
	initEmailToFriend();
	initSubscribeToAlert();
	initEmbedCode();
});

var sendToFriend = 
{
	toggleForm : function()
	{
		Effect.toggle('email-to-friend-container', 'slide');
	},
	
	submitForm : function()
	{
		//form = $('send-to-friend');
		
		$('email-form').hide();
		$('email-error').hide();
		$('email-status').show();
	
		new Ajax.Request($('send-to-friend').action, 
		{
	  		method: 'post',
			parameters: Form.serialize('send-to-friend', true),
	  		onSuccess: function(transport) 
			{
				json = eval(transport.responseText);
 
				sendToFriend.updateForm(json);
				
				$('email-status').hide();
				$('email-form').show();
				
		  	}
		});	
	}, 
	
	updateForm : function(json)
	{
		if (json.error)
		{
			$('email-error').update(json.error);
			$('email-error').show();
		}
		else if (json.status == 'sent')
		{
			$('email-form').update('<div style="text-align:center;font-size:13px;font-weight:bold;">Thanks, your email has been sent!</div>');			
			Effect.toggle('email-to-friend-container', 'slide', { delay: 3 } );
		}
		
		$('email-status').hide();
 
	}
	
}

function initEmbedCode()
{
	jQuery('#embed.navItem a').click(function()
	{
		jQuery('#embedCode').slideToggle(300);
		return false;
	});
	
	jQuery('#embedCode #cancel').click(function()
	{
		jQuery('#embedCode').slideToggle(300);
		return false;
	});
	jQuery('#embed_code').click(function()
	   {
		   this.focus();
		   this.select();
	   });
}

function initEmailToFriend() {
	if (jQuery('#email-to-friend-link')) 
	{
		jQuery('#email-to-friend-link').click(function()
		{
			sendToFriend.toggleForm();
			return false;
		});
		
		jQuery('#email-to-friend-container #cancel').click(function()
		{
			sendToFriend.toggleForm();
			return false;
		});
		
		if (jQuery('#send-to-friend'))
		{
			jQuery('#send-to-friend').submit(function()
			{
				sendToFriend.submitForm();
				return false;
			});
		}
	}
}

function initSubscribeToAlert()
{
	jQuery('#subscribe-to-alert').click( function() {
		var isLoggedIn = jQuery('#isLoggedIn').val();
		
		if (isLoggedIn == "1")
		{
			var id = jQuery('#spotId').val();
			var type = jQuery('#type').val();
			if (type == "surf") {
				jQuery("#alertStatus").load("/ajax/add_surf_forecast_sub/" + id + "/");
			} else {
				jQuery("#alertStatus").load("/ajax/add_snow_forecast_sub/" + id + "/");
			}
		} else {
			var logInURL = jQuery('#logInURL').val();
			document.location = (logInURL);
		}
		
		return false;
	})	
}

function initWeatherSearch()
{
	mapSearchOpen = false;
	jQuery("#spotSearchWrapper").hide();
	jQuery("#toggleMapSearch").click( function() { toggleMapSearch(); });
	jQuery("#spotSearchGo").click( function() { weatherMap.getSpots( jQuery("#spotSearch").val() ); });
}

function toggleMapSearch()
{
	if (mapSearchOpen) {
		jQuery("#spotSearchWrapper").hide();
		mapSearchOpen = false;
	} else {
		jQuery("#spotSearchWrapper").show();
		mapSearchOpen = true;
	}
}

/* Dropdown list functions */
jQuery(document).ready(function() {
    if (jQuery('#global_and_region').length > 0)
	{
		jQuery('#global_and_region').change(function () 
		{ 
			var formVal = jQuery('#global_and_region option:selected').val();
			
			if (formVal)
			{
				window.location = formVal;
			}
		});
	}
	
	if (jQuery('#country_and_brakes').length > 0)
	{
		jQuery('#country_and_brakes').change(function () 
		{ 
			var formVal = jQuery('#country_and_brakes option:selected').val();
			
			if (formVal)
			{
				window.location = formVal;
			}
		});
	}
});
