/************************************************************
 * Global
 */

$(document).ready(function() {
	
	// Open Contact Form
	$(".contactme").click(function(index) {
		new_window = window.open(
				'/contact/', 
				'contact_window', 
				'width=400,height=450,location=no,scrollbars=no,toolbars=no,resizable=no');
		new_window.focus();
	});
	
	// Open url in new window
	$(".newwindow").click(function(index) {
		new_window = window.open( $(this).attr('href'), 'locWindow');
		new_window.focus();
		return false;
	});	
	
	// Right pane scrolling
	
	$(window).scroll(function () { 
		if (		$(window).scrollTop() > 300 
				&& 	$(window).scrollTop() < ($(document).height() - $('div#footer').height() - $('div.bColumn').height() - 100)
				&&  $(window).height() > $('div.bColumn').height() )
		{
			$('div.bColumn').css("margin-top", ($(window).scrollTop()-300)+"px"); 
		}		
		else if ( $(window).scrollTop() < 300 || $(window).height() < $('div.bColumn').height() )
		{
			$('div.bColumn').css("margin-top", "0px");
		}
	
	});
	
});

/************************************************************
 * SPOT FORECASTS
 */

var sf = new Array();

$(document).ready(function() {

	
	//////////////////////////////////////////////////////////////////
	// Create Spot Forecasts
	$("canvas.spot_forecast").each(function(index) {
		
		//////////////////////////////////////////////////////////////////
		// Define Variables

		var canvas = $(this)[0];
		var context = canvas.getContext("2d");
		
		var height_max = 6; // Feet
		var height_scale = 12; // Pixels

		var chartX_indent = 0.5;		
		var chartY_indent = 4.5;
		
		chart_size = $(this).attr('data-chart-size');
		duration = $(this).attr('data-duration');
		
		if (chart_size == 'large') {
			
			if (duration == 'day') {
				var time_scale = 21;
				var time_max = 24; // 1 day in hour
				var time_text_indent = 0;
			}
			else if (duration == 'week') {
				var time_scale = 3;
				var time_max = 24*7; // 7 days in hours
				var time_text_indent = 35;
			}
			else if (duration == 'weekend'){
				var time_scale = 7;
				var time_max = 24*3; // 3 days in hours
				var time_text_indent = 80;
			}
		}
		else if (chart_size == 'small') {
				
			if (duration == 'day'){
				var time_scale = 12.5;
				var time_max = 24; // 1 day in hours
				var time_text_indent = 0;
			}
			else if (duration == 'week'){
				var time_scale = 1.7857; //1.77;
				var time_max = 24*7; // 7 days in hours
				var time_text_indent = 23;
			}
			else if (duration == 'weekend'){
				var time_scale = 4.1667;
				var time_max = 24*3; // 3 days in hours
				var time_text_indent = 45;
			}
		}
		
		
		
		//////////////////////////////////////////////////////////////////
		// Load Forecast

		$.getJSON('/api/spot/forecast/'+$(this).attr('data-location')+'/?dcat='+duration+'&dval='+$(this).attr('data-date')+'&format=json', function(data) {
			
			//////////////////////////////////////////////////////////////////
			// CHART SIZE
			
			var sizeMin = data[0].size;
			var sizeMax = data[0].size;
			
			for (var i = 0; i < time_max + 1; i++)
			{
				if (data[i].size < sizeMin)
				{
					sizeMin = data[i].size;
				}
				if (data[i].size > sizeMax)
				{
					sizeMax = data[i].size;
				}
			}
			
			while (sizeMax > height_max)
			{
				height_max += 3;
			}
			$("canvas#spot_"+data[0].spot_id)[0].height = height_max*height_scale + 22;

			//////////////////////////////////////////////////////////////////
			// Tooltip
			
			sf["s"+data[0].spot_id] = data;
			$("canvas#spot_"+data[0].spot_id).mousemove( function(e) {

				var oset = $("canvas#spot_"+data[0].spot_id).offset();
				var x = e.pageX - oset.left;
				var y = e.pageY - oset.top;
				
				var loc = Math.floor(x/time_scale + 0.5);
				//var text = e.pageX+", "+oset.left+", "+e.pageY+", "+oset.top;
				var text = sf["s"+data[0].spot_id][loc].size + "ft " + sf["s"+data[0].spot_id][loc].shape_full + " <br/> " + sf["s"+data[0].spot_id][loc].hour; 
				$("div#tooltip_spot_"+data[0].spot_id).html(text);
				$("div#tooltip_spot_"+data[0].spot_id).css('top', e.pageY + 20);
				$("div#tooltip_spot_"+data[0].spot_id).css('left', e.pageX);

			})

			$("canvas#spot_"+data[0].spot_id).mouseout( function(e) {
				$("div#tooltip_spot_"+data[0].spot_id).css('top', '-100px');
			})			
			
			//////////////////////////////////////////////////////////////////
			// STICKMAN
			
			var img = new Image();
			img.onload = function(){
				context.drawImage(img, time_scale*time_max + 20 + chartX_indent, height_scale*height_max - 77 + chartY_indent);
			}
			img.src = '/static/images/stickman_80.png';
			
			//////////////////////////////////////////////////////////////////
			// FORECAST SUMMARY
						
			summaryText = sizeMin + "-" + sizeMax + " ft";
			$("div#forecast_summary_spot_"+data[0].spot_id).html(summaryText);

			//////////////////////////////////////////////////////////////////
			// GRID: Height Bars
			for (var i = 0; i <(height_max+1); i++ )
			{
				if (i%3 == 0)
				{
					context.moveTo(chartX_indent, height_max*height_scale - i*height_scale + chartY_indent);
					context.strokeStyle="#E6E7E9";
					context.lineTo(time_max*time_scale + chartX_indent, height_max*height_scale - i*height_scale + chartY_indent);
					context.stroke();
					if (i!=0)
					{
						context.font = "11px Arial";
						context.textAlign = "left";
						context.textBaseline = "middle";
						context.fillText(i+"ft", time_max*time_scale + chartX_indent + 1, height_max*height_scale - i*height_scale + chartY_indent);
					}
					
				}
			}
			
			//////////////////////////////////////////////////////////////////
			// GRID: Time Bars
			for (var i = 0; i <(time_max+1); i++)
			{
				if (duration == 'day')
				{
					if (i%6 == 0)
					{
						context.moveTo(i*time_scale + chartX_indent, chartY_indent);
						context.lineTo(i*time_scale + chartX_indent, height_max*height_scale + chartY_indent);
						context.stroke();	
						
						if (i!=0 && i!=24)
						{
							switch(i)
							{
								case 6:
									timeText = "6am";
									break;
								case 12:
									timeText = "Noon";
									break;
								case 18:
									timeText = "6pm";
									break;
							}

							context.font = "11px Arial";
							context.textAlign = "center";
							context.textBaseline = "top";
							context.fillText(timeText, i*time_scale + chartX_indent + time_text_indent, height_max*height_scale + chartY_indent + 2);							
						}						
					}
				}
				else if (duration == 'week')
				{
					if (i%24 == 0)
					{
						context.moveTo(Math.round(i*time_scale) + chartX_indent, chartY_indent);
						context.lineTo(Math.round(i*time_scale) + chartX_indent, height_max*height_scale + chartY_indent);
						context.stroke();
						
						if (i!=24*7)
						{
							to_noon = 12;
							timeText = data[i+to_noon].day;
							context.font = "11px Arial";
							context.textAlign = "center";
							context.textBaseline = "top";
							context.fillText(timeText, i*time_scale + chartX_indent + time_text_indent, height_max*height_scale + chartY_indent + 2);							
						}
					}
				}
				else if (duration == 'weekend')
				{
					if (i%24 == 0)
					{
						context.moveTo(Math.round(i*time_scale) + chartX_indent, chartY_indent);
						context.lineTo(Math.round(i*time_scale) + chartX_indent, height_max*height_scale + chartY_indent);
						context.stroke();
						
						if (i!=24*3)
						{
							timeText = data[i].day;
							context.font = "11px Arial";
							context.textAlign = "left";
							context.textBaseline = "top";
							context.fillText(timeText, i*time_scale + chartX_indent + time_text_indent, height_max*height_scale + chartY_indent + 2);							
						}						
					}					
				}				
			}	// End of: GRID: Time Bars


			
			//////////////////////////////////////////////////////////////////
			// BETA || LIVE
			
			if (data[0].live != 1)
			{	
				betaText = "BETA";
				context.font = "11px Arial";
				context.textAlign = "left";
				context.textBaseline = "top";
				context.fillText(betaText, chartX_indent + 5, chartY_indent + 15);
			}

			//////////////////////////////////////////////////////////////////
			// CHART FILL
			for (var i = 0; i < time_max + 1; i++)
			{
				var sizeOn = data[i].size;
				context.beginPath();
				context.fillStyle = getFillColor(data[i].shape);
				
				if (i != 0)
				{
					var sizeBefore = data[i-1].size;
					var avgBefore = (sizeOn + sizeBefore)/2;
					context.moveTo( Math.ceil((i-0.5)*time_scale + chartX_indent), (height_max - avgBefore)*height_scale + chartY_indent);					
				}
				else 
				{
					context.moveTo( Math.ceil(i*time_scale + chartX_indent), (height_max - sizeOn) * height_scale + chartY_indent);
				}
				
				context.lineTo( Math.ceil(i*time_scale + chartX_indent), (height_max - sizeOn)*height_scale + chartY_indent);
				
				if (i != time_max)
				{
					var sizeAfter = data[i+1].size;
					var avgAfter = (sizeOn + sizeAfter)/2;
					context.lineTo(Math.ceil((i+0.5)*time_scale + chartX_indent), (height_max - avgAfter)*height_scale + chartY_indent);
					context.lineTo(Math.ceil((i+0.5)*time_scale + chartX_indent), height_max*height_scale + chartY_indent);
				}
				else
				{
					context.lineTo(Math.ceil(i*time_scale + chartX_indent), height_max*height_scale + chartY_indent);
				}
				
				if (i != 0)
				{
					context.lineTo(Math.ceil((i-0.5)*time_scale + chartX_indent), height_max*height_scale + chartY_indent);
				}
				else
				{
					context.lineTo(Math.ceil(i*time_scale + chartX_indent), height_max*height_scale + chartY_indent);
				}
				context.fill();								
			}
			
			//////////////////////////////////////////////////////////////////
			// CHART LINE

			context.beginPath();
			context.strokeStyle = "rgb(0, 0, 0)";
			context.lineWidth = 2;
			context.lineJoin = 'round';
			context.lineCap = 'butt';
			
			for (var i = 0; i < (time_max + 1); i++)
			{				
				if (i == 0)
				{
					context.moveTo(i*time_scale + chartX_indent, height_max*height_scale - data[i].size*height_scale + chartY_indent)
				}
				else
				{

					context.lineTo(i*time_scale + chartX_indent, height_max*height_scale - data[i].size*height_scale + chartY_indent);
				}
								
			}
			context.stroke();

			//////////////////////////////////////////////////////////////////
			// DEBUG
			if ( $.cookie("debug") == 1 )
			{
				for (var i = 0; i < (time_max); i++)
				{
					if (data[i].missing_mfactor)
					{
						context.fillStyle = "Black";
						context.font = "11px Arial";
						context.textAlign = "left";
						context.textBaseline = "top";
						context.fillText(data[i].missing_mfactor, i*time_scale + chartX_indent, chartY_indent + 30);						
					}
				}
				
				
			}


			
		});	
	});
	
	
	  
});


function getFillColor(shape)
{
	var theColor = "rgba(187, 187, 187, 0.66)"; //"#BBBBBB";
	
	
	if (shape == 'p')
	{
		theColor = "rgba(255, 0, 0, 0.66)"; //"#FF0000";
	}
	else if (shape == 'pf')
	{
		theColor = "rgba(255, 153, 0, 0.66)"; //"#FF9900";
	}
	else if (shape == 'f')
	{
		theColor = "rgba(255, 255, 0, 0.66)"; //"#FFFF00";
	}
	else if (shape == 'fg')
	{
		theColor = "rgba(153, 255, 0, 0.66)"; //"#99FF00";
	}
	else if (shape == 'g')
	{
		theColor = "rgba(0, 255, 0, 0.66)"; //"#00FF00";
	}
	
	return theColor;
	
}

/************************************************************
 * TIDE FORECASTS
 */

var tide = new Array();

$(document).ready(function() {

	//////////////////////////////////////////////////////////////////
	// Create Tide Forecast
	$("canvas.chart_tide").each(function(index) {
		
		//////////////////////////////////////////////////////////////////
		// Define Variables
		var chartX_indent = 0.5;
		var chartY_indent = 4.5;
		var height_max = 6; // Feet
		var height_scale = 12; // Pixels
		
		var width = 335;
		
		var canvas = $(this)[0];
		var context = canvas.getContext("2d");
		
		duration = $(this).attr('data-duration');
		if (duration == 'day')
		{
			var time_max = 24; // 1 day in hours
		}
		else if (duration == 'week')
		{
			var time_max = 24*7; // 7 days in hours
		}
		else if (duration == 'weekend')
		{
			var time_max = 24*3; // 3 days in hours
		}
		var time_scale = width/time_max;
		

		
		//////////////////////////////////////////////////////////////////
		// Load Forecast
		$.getJSON('/api/county/tide/'+$(this).attr('data-location')+'/?dcat='+duration+'&dval='+$(this).attr('data-date')+'&format=json', function(data) {
			
			//////////////////////////////////////////////////////////////////
			// Tooltip Text
			tide['data'] = data;
			$("canvas.chart_tide").mousemove( function(e) {
				var oset = $("canvas.chart_tide").offset();
				var x = e.pageX - oset.left;
				var y = e.pageY - oset.top;
				
				var loc = Math.floor(x/time_scale + 0.5);
				//var text = e.pageX+", "+oset.left+", "+e.pageY+", "+oset.top;
				var size = Math.round( tide['data'][loc].tide*10 )/10;
				var text = size + "ft <br/> " + tide['data'][loc].hour; 

				$("div#tooltip_tide").html(text);
				$("div#tooltip_tide").css('top', e.pageY + 20);
				$("div#tooltip_tide").css('left', e.pageX);
			})
			
			$("canvas.chart_tide").mouseout( function(e) {
				$("div#tooltip_tide").css('top', '-100px');
			})
			
						
			//////////////////////////////////////////////////////////////////
			// GRID: Height Bars
			for (var i = 0; i <(height_max+1); i++ )
			{
				if (i%3 == 0)
				{
					context.moveTo(chartX_indent, height_max*height_scale - i*height_scale + chartY_indent);
					context.strokeStyle="#E6E7E9";
					context.lineTo(time_max*time_scale + chartX_indent, height_max*height_scale - i*height_scale + chartY_indent);
					context.stroke();
					if (i!=0)
					{
						context.font = "11px Arial";
						context.textAlign = "left";
						context.textBaseline = "middle";
						context.fillText(i+"ft", time_max*time_scale + chartX_indent + 1, height_max*height_scale - i*height_scale + chartY_indent);
					}
					
				}
			}
			
			//////////////////////////////////////////////////////////////////
			// GRID: Time Bars
			for (var i = 0; i <(time_max+1); i++)
			{
				if (duration == 'day')
				{
					if (i%6 == 0)
					{
						context.moveTo(i*time_scale + chartX_indent, chartY_indent);
						context.lineTo(i*time_scale + chartX_indent, height_max*height_scale + chartY_indent);
						context.stroke();	
						
						if (i!=0 && i!=24)
						{
							switch(i)
							{
								case 6:
									timeText = "6am";
									break;
								case 12:
									timeText = "Noon";
									break;
								case 18:
									timeText = "6pm";
									break;
							}

							context.font = "11px Arial";
							context.textAlign = "center";
							context.textBaseline = "top";
							context.fillText(timeText, i*time_scale + chartX_indent, height_max*height_scale + chartY_indent + 2);							
						}						
					}
				}
				else if (duration == 'week')
				{
					if (i%24 == 0)
					{
						context.moveTo(Math.round(i*time_scale) + chartX_indent, chartY_indent);
						context.lineTo(Math.round(i*time_scale) + chartX_indent, height_max*height_scale + chartY_indent);
						context.stroke();
						
						if (i!=24*7)
						{
							to_noon = 12;
							timeText = data[i+to_noon].day;
							context.font = "11px Arial";
							context.textAlign = "center";
							context.textBaseline = "top";
							context.fillText(timeText, i*time_scale + chartX_indent + 23, height_max*height_scale + chartY_indent + 2);							
						}
					}
				}
				else if (duration == 'weekend')
				{
					if (i%24 == 0)
					{
						context.moveTo(Math.round(i*time_scale) + chartX_indent, chartY_indent);
						context.lineTo(Math.round(i*time_scale) + chartX_indent, height_max*height_scale + chartY_indent);
						context.stroke();
						
						if (i!=24*3)
						{
							timeText = data[i].day;
							context.font = "11px Arial";
							context.textAlign = "left";
							context.textBaseline = "top";
							context.fillText(timeText, i*time_scale + chartX_indent + 45, height_max*height_scale + chartY_indent + 2);							
						}						
					}					
				}				
			}	// End of: GRID: Time Bars


			
			//////////////////////////////////////////////////////////////////
			// CHART FILL
			for (var i = 0; i < time_max + 1; i++)
			{
				var sizeOn = data[i].tide;
				context.beginPath();
				context.fillStyle = "rgba(187, 187, 187, 0.66)"; //"#BBBBBB";
				
				if (i != 0)
				{
					var sizeBefore = data[i-1].tide;
					var avgBefore = (sizeOn + sizeBefore)/2;
					context.moveTo( Math.ceil((i-0.5)*time_scale + chartX_indent), (height_max - avgBefore)*height_scale + chartY_indent);					
				}
				else 
				{
					context.moveTo( Math.ceil(i*time_scale + chartX_indent), (height_max - sizeOn) * height_scale + chartY_indent);
				}
				
				context.lineTo( Math.ceil(i*time_scale + chartX_indent), (height_max - sizeOn)*height_scale + chartY_indent);
				
				if (i != time_max)
				{
					var sizeAfter = data[i+1].tide;
					var avgAfter = (sizeOn + sizeAfter)/2;
					context.lineTo(Math.ceil((i+0.5)*time_scale + chartX_indent), (height_max - avgAfter)*height_scale + chartY_indent);
					context.lineTo(Math.ceil((i+0.5)*time_scale + chartX_indent), height_max*height_scale + chartY_indent);
				}
				else
				{
					context.lineTo(Math.ceil(i*time_scale + chartX_indent), height_max*height_scale + chartY_indent);
				}
				
				if (i != 0)
				{
					context.lineTo(Math.ceil((i-0.5)*time_scale + chartX_indent), height_max*height_scale + chartY_indent);
				}
				else
				{
					context.lineTo(Math.ceil(i*time_scale + chartX_indent), height_max*height_scale + chartY_indent);
				}
				context.fill();								
			}
						
			//////////////////////////////////////////////////////////////////
			// CHART LINE

			context.beginPath();
			context.strokeStyle = "rgb(0, 0, 0)";
			context.lineWidth = 2;
			context.lineJoin = 'round';
			context.lineCap = 'butt';
			
			for (var i = 0; i < (time_max + 1); i++)
			{				
				if (i == 0)
				{
					context.moveTo(i*time_scale + chartX_indent, height_max*height_scale - data[i].tide*height_scale + chartY_indent)
				}
				else
				{

					context.lineTo(i*time_scale + chartX_indent, height_max*height_scale - data[i].tide*height_scale + chartY_indent);
				}
								
			}
			context.stroke();
		});	
	});	  
});

/************************************************************
 * WATER TEMPERATURE
 */


//Create the water temperature chart

$(document).ready(function() {	
	$("div.chart_water_temp").each(function(index) {
		$.getJSON('/api/county/water-temperature/'+$(this).attr('data-location')+'/', function(data) {
			$("#wtemp").html(data.fahrenheit + "&deg;F");
			$("#wsuit").html(data.wetsuit);
		});
	});
});

/************************************************************
 * WIND FORECASTS
 */

var wind = new Array();

$(document).ready(function() {

	//////////////////////////////////////////////////////////////////
	// Create Wind Forecast
	$("canvas.chart_wind").each(function(index) {
		
		//////////////////////////////////////////////////////////////////
		// Define Variables
		var height_max = 10; // MPH
		var height_scale = 8; // Pixels

		var chartX_indent = 0.5;
		var chartY_indent = 4.5 + (height_max*height_scale/2);

		var width = 335;
				
		var canvas = $(this)[0];
		var context = canvas.getContext("2d");
		
		duration = $(this).attr('data-duration');
		if (duration == 'day')
		{
			var time_max = 24; // 1 day in hours
		}
		else if (duration == 'week')
		{
			var time_max = 24*7; // 7 days in hours
		}
		else if (duration == 'weekend')
		{
			var time_max = 24*3; // 3 days in hours
		}
				
		var time_scale = width/time_max;
		
		//////////////////////////////////////////////////////////////////
		// Load Forecast
		$.getJSON('/api/county/wind/'+$(this).attr('data-location')+'/?dcat='+duration+'&dval='+$(this).attr('data-date')+'&format=json', function(data) {

			//////////////////////////////////////////////////////////////////
			// CHART SIZE
			
			var sizeMin = data[0].speed_mph;
			var sizeMax = data[0].speed_mph;
			
			for (var i = 0; i < time_max + 1; i++)
			{
				
				if (data[i].speed_mph < sizeMin)
				{
					sizeMin = data[i].speed_mph;
				}
				if (data[i].speed_mph > sizeMax)
				{
					sizeMax = data[i].speed_mph;
				}
			}

			while (sizeMax > height_max)
			{
				height_max += 5;
			}
			$("canvas.chart_wind")[0].height = height_max*height_scale + 60;
			
			//////////////////////////////////////////////////////////////////
			// Tooltip
			
			wind['data'] = data;

			$("canvas.chart_wind").mousemove( function(e) {
				var oset = $("canvas.chart_wind").offset();
				var x = e.pageX - oset.left;
				var y = e.pageY - oset.top;

				var loc = Math.floor(x/time_scale + 0.5);
				//var text = e.pageX+", "+oset.left+", "+e.pageY+", "+oset.top;
				$("div#tooltip_wind").html("From "+wind['data'][loc].direction_text+"<br/>"+wind['data'][loc].speed_mph+" mph<br/>"+wind['data'][loc].hour);
				$("div#tooltip_wind").css('top', e.pageY + 20);
				$("div#tooltip_wind").css('left', e.pageX);

			})
			
			$("canvas.chart_wind").mouseout( function(e) {
				$("div#tooltip_wind").css('top', '-100px');
			})
						
			//////////////////////////////////////////////////////////////////
			// GRID: Height Bars
			for (var i = 0; i <(height_max+1); i++ )
			{
				if (i%5 == 0)
				{
					context.moveTo(chartX_indent, height_max*height_scale - i*height_scale + chartY_indent);
					context.strokeStyle="#E6E7E9";
					context.lineTo(time_max*time_scale + chartX_indent, height_max*height_scale - i*height_scale + chartY_indent);
					context.stroke();
					if (i!=0)
					{
						context.font = "11px Arial";
						context.textAlign = "left";
						context.textBaseline = "middle";
						context.fillText(i, time_max*time_scale + chartX_indent + 1, height_max*height_scale - i*height_scale + chartY_indent -5);
						context.fillText("mph", time_max*time_scale + chartX_indent + 1, height_max*height_scale - i*height_scale + chartY_indent + 5);
					}
					
				}
			}
			
			//////////////////////////////////////////////////////////////////
			// GRID: Time Bars
			for (var i = 0; i <(time_max+1); i++)
			{
				if (duration == 'day')
				{
					if (i%6 == 0)
					{
						context.moveTo(i*time_scale + chartX_indent, chartY_indent);
						context.lineTo(i*time_scale + chartX_indent, height_max*height_scale + chartY_indent);
						context.stroke();	
						
						if (i!=0 && i!=24)
						{

							if(i == 6) {
								timeText = "6am";
							}
							else if (i == 12) {
								timeText = "Noon";
							}
							else if (i == 18) {
								timeText = "6pm";
							}

							context.font = "11px Arial";
							context.textAlign = "center";
							context.textBaseline = "top";
							context.fillText(timeText, i*time_scale + chartX_indent, height_max*height_scale + chartY_indent + 2);							
						}						
					}
				}
				else if (duration == 'week')
				{
					if (i%24 == 0)
					{
						context.moveTo(Math.round(i*time_scale) + chartX_indent, chartY_indent);
						context.lineTo(Math.round(i*time_scale) + chartX_indent, height_max*height_scale + chartY_indent);
						context.stroke();
						
						if (i!=24*7)
						{
							to_noon = 12;
							timeText = data[i+to_noon].day;
							context.font = "11px Arial";
							context.textAlign = "center";
							context.textBaseline = "top";
							context.fillText(timeText, i*time_scale + chartX_indent + 23, height_max*height_scale + chartY_indent + 2);							
						}
					}
				}
				else if (duration == 'weekend')
				{
					if (i%24 == 0)
					{
						context.moveTo(Math.round(i*time_scale) + chartX_indent, chartY_indent);
						context.lineTo(Math.round(i*time_scale) + chartX_indent, height_max*height_scale + chartY_indent);
						context.stroke();
						
						if (i!=24*3)
						{
							timeText = data[i].day;
							context.font = "11px Arial";
							context.textAlign = "left";
							context.textBaseline = "top";
							context.fillText(timeText, i*time_scale + chartX_indent + 45, height_max*height_scale + chartY_indent + 2);							
						}						
					}					
				}				
			}	// End of: GRID: Time Bars


			
			//////////////////////////////////////////////////////////////////
			// CHART FILL
			
			for (var i = 0; i < time_max + 1; i++)
			{
				var sizeOn = data[i].speed_mph;
				context.beginPath();
				context.fillStyle = "rgba(187, 187, 187, 0.66)"; //"#BBBBBB";
				
				if (i != 0)
				{
					var sizeBefore = data[i-1].speed_mph;
					var avgBefore = (sizeOn + sizeBefore)/2;
					context.moveTo( Math.ceil((i-0.5)*time_scale + chartX_indent), (height_max - avgBefore)*height_scale + chartY_indent);					
				}
				else 
				{
					context.moveTo( Math.ceil(i*time_scale + chartX_indent), (height_max - sizeOn) * height_scale + chartY_indent);
				}
				
				context.lineTo( Math.ceil(i*time_scale + chartX_indent), (height_max - sizeOn)*height_scale + chartY_indent);
				
				if (i != time_max)
				{
					var sizeAfter = data[i+1].speed_mph;
					var avgAfter = (sizeOn + sizeAfter)/2;
					context.lineTo(Math.ceil((i+0.5)*time_scale + chartX_indent), (height_max - avgAfter)*height_scale + chartY_indent);
					context.lineTo(Math.ceil((i+0.5)*time_scale + chartX_indent), height_max*height_scale + chartY_indent);
				}
				else
				{
					context.lineTo(Math.ceil(i*time_scale + chartX_indent), height_max*height_scale + chartY_indent);
				}
				
				if (i != 0)
				{
					context.lineTo(Math.ceil((i-0.5)*time_scale + chartX_indent), height_max*height_scale + chartY_indent);
				}
				else
				{
					context.lineTo(Math.ceil(i*time_scale + chartX_indent), height_max*height_scale + chartY_indent);
				}
				context.fill();								
			}
			
						
			//////////////////////////////////////////////////////////////////
			// CHART LINE
			
			context.beginPath();
			context.strokeStyle = "rgb(0, 0, 0)";
			context.lineWidth = 2;
			context.lineJoin = 'round';
			context.lineCap = 'butt';
			
			for (var i = 0; i < (time_max + 1); i++)
			{				
				if (i == 0)
				{
					context.moveTo(i*time_scale + chartX_indent, height_max*height_scale - data[i].speed_mph*height_scale + chartY_indent);
				}
				else
				{
					context.lineTo(i*time_scale + chartX_indent, height_max*height_scale - data[i].speed_mph*height_scale + chartY_indent);
				}
								
			}
			context.stroke();
			
			//////////////////////////////////////////////////////////////////
			// DIRECTION ARROWS
			
			var img = new Image();
			img.onload = function(){
				
				for (var i = 0; i <(time_max+1); i++)
				{
					if (duration == 'day')
					{
						if (i%6 == 0 && i != 0 && i != 24 )
						{
							context.save();
							context.translate(i*time_scale + chartX_indent, chartY_indent/2);
							context.rotate((data[i].direction_degrees-180) * Math.PI / 180);
							context.drawImage(img, -20, -20);
							context.restore();													
						}
					}
					else if (duration == 'week' || duration == 'weekend')
					{
						if (i%12 == 0 && i%24 != 0)
						{
							context.save();
							context.translate(i*time_scale + chartX_indent, chartY_indent/2);
							context.rotate((data[i].direction_degrees-180) * Math.PI / 180);
							context.drawImage(img, -20, -20);
							context.restore();
						}
					}
				}			
						
			}
			img.src = '/static/images/wind_arrow.png';
			
		});	
	});	  
});


/************************************************************
 * MAPS
 */

$(document).ready(function() {
	if ($('div#map_canvas').length)
	{

		var lon_min;
		var lon_max;
		
		var lat_min;
		var lat_max;
		
		var i = 0;
		
		$("canvas.spot_forecast").each(function(index) {
			if ($(this).attr('data-longitude').length && $(this).attr('data-latitude').length)
			{
				var spot_lon = parseFloat($(this).attr('data-longitude'));
				var spot_lat = parseFloat($(this).attr('data-latitude'));
									
				if (i == 0){
					lat_min = spot_lat;
					lat_max = spot_lat;
					lon_min = spot_lon;
					lon_max = spot_lon;
				}
				else {
					if (spot_lat < lat_min) { lat_min = spot_lat; }
					if (spot_lat > lat_max) { lat_max = spot_lat; }
					if (spot_lon < lon_min) { lon_min = spot_lon; }
					if (spot_lon > lon_max) { lon_max = spot_lon; }
				}
				
				i++;
				
			}
		});
		
		var lon = lon_min + ((lon_max - lon_min)/2);
		var lat = lat_min + ((lat_max - lat_min)/2);
		
		spread = Math.sqrt(Math.pow((lat_max - lat_min), 2)+Math.pow((lon_max - lon_min), 2));

		var zoom = 8;

		if (spread < 0.1594)
		{
			zoom = 12;
		}
		else if (spread < 0.3018)
		{
			zoom = 11;
		}		
		else if (spread < 0.6527)
		{
			zoom = 10;
		}
		else if (spread < 1.0342)
		{
			zoom = 9;
		}

		//alert (spread + " : " + zoom)
		var latlng = new google.maps.LatLng(lat,lon);
		var myOptions = {
			zoom: zoom,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.TERRAIN,
			panControl: true,
			panControlOptions: {
			    position: google.maps.ControlPosition.RIGHT_TOP
			},
			zoomControl: true,
			zoomControlOptions: {
			    style: google.maps.ZoomControlStyle.SMALL,
			    position: google.maps.ControlPosition.RIGHT_TOP
			},
			mapTypeControl: true,
			mapTypeControlOptions: {
			      style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
			      position: google.maps.ControlPosition.TOP_RIGHT
			},
			scaleControl: true,
			streetViewControl: false,
			overviewMapControl: false,
			scrollwheel: false
		};

		var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

		var markers = new Array();
		
		$("canvas.spot_forecast").each(function(index) {

			var spot = new google.maps.LatLng($(this).attr('data-latitude'),$(this).attr('data-longitude'));
			
			var image = new google.maps.MarkerImage('/static/images/map_marker.png',
				      new google.maps.Size(26, 26),
				      new google.maps.Point(index*30,0),
				      new google.maps.Point(26, 26));
			
			markers[index] = new google.maps.Marker({        
				position: spot, 
				map: map,
				icon: image,
				title: $(this).attr('data-name'),
				zIndex: index
			});

			google.maps.event.addListener(markers[index], 'mouseover', function() {

				markers[index].setIcon(	new google.maps.MarkerImage('/static/images/map_marker.png',
			      				new google.maps.Size(26, 26),
			      				new google.maps.Point(index*30,26),
			      				new google.maps.Point(26, 26)));
				markers[index].setZIndex(100);
					
			});
			
			google.maps.event.addListener(markers[index], 'mouseout', function() {

				markers[index].setIcon(	new google.maps.MarkerImage('/static/images/map_marker.png',
					      		new google.maps.Size(26, 26),
					      		new google.maps.Point(index*30,0),
					      		new google.maps.Point(26, 26)));
				markers[index].setZIndex(index);
				
			});
								
		});
		
		$("div.spot_forecast").each(function(index) {
			$(this).mouseover(function() {
				markers[index].setIcon(	new google.maps.MarkerImage('/static/images/map_marker.png',
	      				new google.maps.Size(26, 26),
	      				new google.maps.Point(index*30,26),
	      				new google.maps.Point(26, 26)));
				markers[index].setZIndex(100);
			});

			$(this).mouseout(function() {
				markers[index].setIcon(	new google.maps.MarkerImage('/static/images/map_marker.png',
			      		new google.maps.Size(26, 26),
			      		new google.maps.Point(index*30,0),
			      		new google.maps.Point(26, 26)));
				markers[index].setZIndex(index);
			});			
		});
		
		
		// Debug Spot Addresses
		if ( $.cookie("debug") == 1 )
		{
			$("canvas.spot_forecast").click(function(index) {
				var latlng = new google.maps.LatLng($(this).attr('data-latitude'),$(this).attr('data-longitude'));
    			var geocoder;
    			geocoder = new google.maps.Geocoder();
    			geocoder.geocode({'latLng': latlng}, function(results, status) {
    				if (results != null) {
          				alert(results[0].formatted_address);
          			}
    			});		
			});
		}
		
	}
});  // End of Maps

/************************************************************
 * CAROUSEL
 */

var carousel = new Object;

$(document).ready(function() {
	if ($('div#carousel').length)
	{	
		carousel.margin_top = 0;
		carousel.i = 0;
		carousel.auto_rotate = true;
		carousel.height = 300;
		
		$('div.carousel_spot_name > a').click(function (){
			carousel.auto_rotate = false;
			//$('div#carousel > ul > li').animate({"opacity": "0.8"}, 400);
			//$('li#carousel_position_'+$(this).attr('data-index')).animate({"opacity": "1"}, 200);
			$('div#carousel > ul').animate({"margin-top": ($(this).attr('data-index')*-carousel.height)+"px"}, 500);
			
			return false;		
		});
		
		carouselTimer();
	}
});

function carouselTimer()
{
	if (carousel.auto_rotate == true)
	{	
		if (carousel.i == 5)
		{
			carousel.i = 0;
		}
		carousel.margin_top = -carousel.height*carousel.i;
		$('div#carousel > ul').animate({"margin-top": carousel.margin_top+"px"}, 500);
		carousel.timer=setTimeout("carouselTimer()",4500);
		carousel.i++;
	}
}

/************************************************************
 * SPOT DNA
 */

$(document).ready(function() {

	if ($('div.spot_dna').length) {
				
		$.getJSON('/api/spot/dna/'+$('div.spot_dna').attr('data-location')+'/', function(data) {
		
			//TIDE
			var chartX_indent = 0.5;
			var chartY_indent = 11.5;
			var height_max = 18; // Feet
			var height_scale = 12; // Pixels

			var width = 250;
			
			var base_ht = -6 		
			
			var canvas = $("canvas#spot_dna_tide")[0];
			var ctx = canvas.getContext("2d");
			
			var tide_summary = "<strong>Tide:</strong> The shaded area indicates favorable tides at this surf spot.  These include: "
			
			// TIDE GRID
			ctx.strokeStyle="#E6E7E9";
			for (var i = 0; i <(height_max+1); i++ )
			{
				if (i%3 == 0)
				{
					ctx.moveTo(chartX_indent, height_max*height_scale - i*height_scale + chartY_indent);
					ctx.lineTo(width + chartX_indent, height_max*height_scale - i*height_scale + chartY_indent);
					ctx.stroke();
					
					ctx.font = "11px Arial";
					ctx.textAlign = "left";
					ctx.textBaseline = "middle";
					ctx.fillText((i+base_ht)+"ft", width + chartX_indent + 1, height_max*height_scale - i*height_scale + chartY_indent);					
				}
			}
			
			ctx.moveTo(chartX_indent, chartY_indent);
			ctx.lineTo(chartX_indent, height_max*height_scale + chartY_indent);
			ctx.moveTo(width + chartX_indent, chartY_indent);
			ctx.lineTo(width + chartX_indent, height_max*height_scale + chartY_indent);
			ctx.stroke();
			
			// TIDE CHART LINE

			ctx.beginPath();
			ctx.strokeStyle = "rgb(0, 0, 0)";
			ctx.fillStyle = "rgba(187, 187, 187, 0.66)";
			ctx.lineWidth = 2;
			ctx.lineJoin = 'round';
			ctx.lineCap = 'butt';
						
			for (var i = 0; i < data['pr']['best'].length; i++) {
			
				var range_min = Math.round(data['pr']['best'][i]['min'])
				var range_max = Math.round(data['pr']['best'][i]['max'])

				if (i != 0 && i != (data['pr']['best'].length - 1))
				{
					tide_summary += ", ";
				}
				else if (i == (data['pr']['best'].length - 1) && data['pr']['best'].length > 1)
				{
					tide_summary += " and ";
				}
							
				if (range_min != range_max)
				{				
					ctx.moveTo(chartX_indent, height_max*height_scale - range_min*height_scale + base_ht*height_scale + chartY_indent);
					ctx.lineTo(width + chartX_indent, height_max*height_scale - range_min*height_scale + base_ht*height_scale + chartY_indent);
					ctx.lineTo(width + chartX_indent, height_max*height_scale - range_max*height_scale + base_ht*height_scale + chartY_indent);
					ctx.lineTo(chartX_indent, height_max*height_scale - range_max*height_scale + base_ht*height_scale + chartY_indent);				
					ctx.fill();

					tide_summary += "<strong>" + range_min + " to " + range_max + " ft</strong>";
				}
				else
				{
					tide_summary += range_min + " ft";
				}

				if (i == (data['pr']['best'].length - 1))
				{
					tide_summary += ".";
				}

				ctx.beginPath();
								
				ctx.moveTo(chartX_indent, height_max*height_scale - range_min*height_scale + base_ht*height_scale + chartY_indent);
				ctx.lineTo(width + chartX_indent, height_max*height_scale - range_min*height_scale + base_ht*height_scale + chartY_indent);
				
				if (range_min != range_max)
				{
					ctx.moveTo(chartX_indent, height_max*height_scale - range_max*height_scale + base_ht*height_scale + chartY_indent);
					ctx.lineTo(width + chartX_indent, height_max*height_scale - range_max*height_scale + base_ht*height_scale + chartY_indent);
				}	
				ctx.stroke();
		
			}
			
			if (data['pr']['best'].length == 0)
			{
				tide_summary = "<strong>Tide:</strong> Tide is not a primary factor influencing surf conditions at this spot.";
			}
	
			
			$('p#spot_dna_tide_summary').html(tide_summary);
			
			
			//WIND

			chartX_indent = 0.5;
			chartY_indent = 0.5;
			
			height_max = 15; // MPH
			height_scale = 8; // Pixels
			
			canvas = $("canvas#spot_dna_wind")[0];
			ctx = canvas.getContext("2d");
												
			
			
			// WIND GRID
			ctx.strokeStyle="#E6E7E9";
			for (var i = 0; i <= height_max; i++ )
			{
				if (i%5 == 0)
				{
					ctx.beginPath();
					ctx.arc(chartX_indent + (height_max*height_scale),chartY_indent + (height_max*height_scale),i*height_scale,(Math.PI/180)*(0),(Math.PI/180)*(360),false);
					ctx.stroke();
					
					if (i!=0)
					{
						ctx.font = "11px Arial";
						ctx.textAlign = "center";
						ctx.textBaseline = "middle";
						ctx.fillText(i, chartX_indent + (height_max*height_scale) + i*height_scale, chartY_indent + (height_max*height_scale) - 5);
						ctx.fillText("mph", chartX_indent + (height_max*height_scale) + i*height_scale, chartY_indent + (height_max*height_scale) + 5);
					}

				}
			}
						

			ctx.lineWidth = 2;
			ctx.lineJoin = 'round';
			ctx.lineCap = 'butt';			
			ctx.strokeStyle = "rgba(0, 0, 0, 1)";
			ctx.fillStyle = "rgba(187, 187, 187, 0.66)"; 
			
			// Wind Speed 
			var radius = 0;
			for (var i = 0; i < data['wspd']['best'].length; i++) {
				if (data['wspd']['best'][i]['max'] > radius) {
					radius = data['wspd']['best'][i]['max'];
				}
			}
			wind_speed_summary = "<strong>Wind Speed:</strong> The shaded area above indicates this break's wind speed tolerance.  Favorable conditions can occur at this spot with winds <strong>up to " + radius + " mph</strong>."
			if (radius > 15) { radius = 15; }
			if (data['wspd']['best'].length == 0) {
				wind_speed_summary = "<strong>Wind Speed:</strong> Wind speed is not a primary factor influencing surf conditions at this spot.";		
			}						
			ctx.beginPath();
			ctx.arc(chartX_indent + (height_max*height_scale),chartY_indent + (height_max*height_scale),radius*height_scale,(Math.PI/180)*0,(Math.PI/180)*360,false);
			ctx.fill();			


			// Wind Direction
			
			var wind_dir_summary = "<strong>Wind Direction:</strong> The black line indicates favorable wind directions at this break.  These include: ";
			
			for (var i = 0; i < data['wdir']['best'].length; i++) {
				ctx.beginPath();
				ctx.arc(chartX_indent + (height_max*height_scale),chartY_indent + (height_max*height_scale),height_max*height_scale,(Math.PI/180)*(data['wdir']['best'][i]['min']-90),(Math.PI/180)*(data['wdir']['best'][i]['max']-90),false);
				ctx.stroke();
				
				
				if (data['wdir']['best'][i]['max'] < data['wdir']['best'][i]['min'])
    			{
        			z = [{min:0,max:data['wdir']['best'][i]['max']}, {min:data['wdir']['best'][i]['min'],max:360}];
        		}
        		else
        		{
        			z = [{ min:data['wdir']['best'][i]['min'], max:data['wdir']['best'][i]['max']}];
        		} 
				
				for (var j = 0; j < z.length; j++) {
				
    				if (z[j]['min'] <= 0 && z[j]['max'] >= 0)
    				{
        				wind_dir_summary += '<strong>N</strong> ';
        			}
        			if (z[j]['min'] <= 45 && z[j]['max'] >= 45)
    				{
        				wind_dir_summary += '<strong>NE</strong> ';
        			}
        			if (z[j]['min'] <= 90 && z[j]['max'] >= 90)
    				{
        				wind_dir_summary += '<strong>E</strong> ';
        			}
        			if (z[j]['min'] <= 135 && z[j]['max'] >= 135)
    				{
        				wind_dir_summary += '<strong>SE</strong> ';
        			}
        			if (z[j]['min'] <= 180 && z[j]['max'] >= 180)
    				{
        				wind_dir_summary += '<strong>S</strong> ';
        			}
        			if (z[j]['min'] <= 225 && z[j]['max'] >= 225)
    				{
        				wind_dir_summary += '<strong>SW</strong> ';
        			}
        			if (z[j]['min'] <= 270 && z[j]['max'] >= 270)
    				{
        				wind_dir_summary += '<strong>W</strong> ';
        			}
        			if (z[j]['min'] <= 315 && z[j]['max'] >= 315)
    				{
        				wind_dir_summary += '<strong>NW</strong> ';
        			}
        		}
				
			}
			if (data['wdir']['best'].length == 0) {
				wind_dir_summary = "<strong>Wind Direction:</strong> Wind direction is not a primary factor influencing surf conditions at this spot.";		
			}						
			
			$('p#spot_dna_wind_summary').html(wind_speed_summary + "<br/><br/>" + wind_dir_summary);
			
			
		});
	}	  
});

/************************************************************
 * SWEET SPOT
 */

$(document).ready(function() {

	if ($('div.search_zone').length) {
	
		$("div.search_zone ul li.search_spot_result").live("click", function() {
				$("div#search_forecast_pane > div").html($(this).html());
				var offset = $(this).offset();
				$("div#search_forecast_pane").css("top", offset.top-300);
				
				$("a.close_pane").click( function() {
						$("div#search_forecast_pane").css("top", "-415px");
				});
        });
					
		$("div.search_zone ul").each(function(index) {
			$.getJSON('/api/spot/forecast/search/?min_latitude='+$(this).attr('data-latitude-min')+'&max_latitude='+$(this).attr('data-latitude-max')+'&dval='+$(this).attr('data-date'), function(data) {
					
				if (data.length) {
				
					var theHtml = "";
					for (var i = 0; i < data.length; i++) {
						theHtml = theHtml + "<li class='search_spot_result' data-spot-id='"+data[i]['spot_id']+"' data-dval='"+data[0]['dval']+"'>"+data[i]['spot_name']+"</li>";
					}
					
					var ul_id = data[0]['dval']+"_"+String(data[0]['min_latitude']*1000);
					$("ul#"+ul_id).hide().html(theHtml).fadeIn('slow');

				}
			});
		});
	}
});

