var infoWindow;

//Window resize handler for resizing map
$(document).ready(function()
{
	ResizeMap();
	$(window).resize(function() {
		ResizeMap();
	});
	infoWindow = new google.maps.InfoWindow();
});

//Resizes the map to fill the screen, minus 50 pixels for the top bar UI
function ResizeMap()
{
	$('div#map-spacer').height(50);
	var mapHeight;
	if (typeof(window.innerWidth) == 'number' ) {
		mapHeight = window.innerHeight - 50;
	}
	else {
		mapHeight = document.body.clientHeight - 50;
	}
	$('div#map-canvas').height(mapHeight);
}

//Display the login form
function ShowLoginForm()
{
	$('div.login.dialog div.feedback').text('');
	$('div.login.dialog').dialog("open");
}
//Display the signup request form
function ShowSignupForm()
{
	$('div.login.dialog').dialog("close");
	$('div.signup.dialog').dialog("open");
}
//Display the password reset request form
function ShowPasswordResetDialog()
{
	$('div.login.dialog').dialog("close");
	$('div.password.dialog').dialog("open");
}

//Attempt login
function Login()
{
	$('form#login input').attr('disabled', 'disabled');
	$('div.login.dialog div.loading').show();
	$('form#login div.feedback').html('');
	
	var login = 
	{
		"email": $('input#login-email').val(),
		"password": $('input#login-password').val()
	};
	
	//Make an async call to attempt a login
	$.ajax(
	{
		url: '/_code/DoLogin.php',
		type: 'POST',
		data: {
			"email": login.email,
			"password": login.password
		},
		cache: 'false',
		dataType: 'json',
		success: function(response)
		{
			$('form#login input').removeAttr('disabled');
			$('div.dialog.login div.loading').hide();
			
			if (response.success)
			{
				window.location.replace('/account/');
			}
			else
			{
				$('form#login div.feedback').html("<p class=\"bad\">Login failed. Make sure you are using the correct email address and password.</p>");
				$('form#login input#login-password').val('');
			}
		},
		error: function(response)
		{
			alert("There is currently a problem with the login system. Let let us know at support@youthlinkspokane.org and we will address the problem. Thanks!");
		}
	});
}

//Attempt to sign up for a new account with information provided in form#signup
function DoSignup()
{
	$('form#signup input').attr('disabled', 'disabled');
	$('div.dialog.signup div.loading').show();
	$('div.dialog.signup div.feedback').html('');
	
	var signup = 
	{
		email: $('input#signup-email').val(),
		password: $('input#signup-password').val(),
		passwordRetype: $('input#signup-password-retype').val(),
		firstName: $('input#signup-first-name').val(),
		lastName: $('input#signup-last-name').val(),
		phone: $('input#signup-phone').val(),
		position: $('input#signup-position').val(),
		employer: $('input#signup-employer').val()
	};
	
	//Make an async call to attempt a login
	$.ajax(
	{
		url: '/_code/DoSignup.php',
		type: 'POST',
		data: {
			email: signup.email,
			password: signup.password,
			passwordRetype: signup.passwordRetype,
			firstName: signup.firstName,
			lastName: signup.lastName,
			phone: signup.phone,
			position: signup.position,
			employer: signup.employer
		},
		cache: 'false',
		dataType: 'json',
		success: function(response)
		{
			$('div.dialog.signup div.loading').hide();
			
			if (response.status == 'incomplete')
			{
				$('form#signup input').removeAttr('disabled');
				$('div.dialog.signup div.feedback').html('<p>Please complete the form before submitting it. Try again.</p>');
			}
			else if (response.status == 'emailExists')
			{
				$('form#signup input').removeAttr('disabled');
				$('div.dialog.signup div.feedback').html('<p>The email address you entered is already in use. Either choose another one or contact us at <a href="mailto:support@youthlinkspokane.org">support@youthlinkspokane.org</a>.</p>');
			}
			else if (response.status == 'mismatch')
			{
				$('form#signup input').removeAttr('disabled');
				$('div.dialog.signup div.feedback').html('<p>Your requested passwords do not match. Try again.</p>');
			}
			else if (response.status == 'short')
			{
				$('form#signup input').removeAttr('disabled');
				$('div.dialog.signup div.feedback').html('<p>Your requested password was too short. Passwords must be at least 6 characters long. Try again.</p>');
			}
			else if (response.status == 'OK')
			{
				$('div.dialog.signup div.feedback').html('<p>Your signup request has been received! You will receive an email once your request has been approved, usually within 48 hours.</p>');
			}
			else {
				$('div.dialog.signup div.field').hide();
				$('form#signup input').removeAttr('disabled');
				$('div.dialog.signup div.feedback').html('<p>There was a problem submitting your request. Try again later.</p>');
			}
		},
		error: function(response)
		{
			alert("There is currently a problem with the signup system. Let let us know at support@youthlinkspokane.org and we will address the problem. Thanks!");
		}
	});
}

//Perform a password reset request
function RequestResetPassword()
{
	$('div.dialog.password input').attr('disabled', 'disabled');
	
	//Make an async call to attempt a login
	$.ajax(
	{
		url: '/_code/DoForgotPassword.php',
		type: 'POST',
		data: {
			email: $('div.dialog.password input#password-reset-email').val()
		},
		cache: 'false',
		dataType: 'json',
		success: function(response)
		{
			$('div.dialog.password div.loading').hide();
			
			if (response.status == 'noEmailExists')
			{
				$('div.dialog.password input').removeAttr('disabled');
				$('div.dialog.password div.feedback').html('<p>That email address does not have a YouthLink account.</p>');
			}
			else if (response.status == 'OK')
			{
				$('div.dialog.password div.feedback').html('<p>Your password reset request has been received! You should receive an email soon.</p>');
			}
			else {
				$('div.dialog.password div.field').hide();
				$('div.dialog.password input').removeAttr('disabled');
				$('div.dialog.password div.feedback').html('<p>There was a problem submitting your request. Try again later.</p>');
			}
		},
		error: function(response)
		{
			$('div.dialog.password div.feedback').html('<p>There was a problem submitting your request. Try again later.</p>');
		}
	});
}

//Gather the UI data required and pass it on to DoSearch()
function UpdateMap()
{
	var inputAge;
	var inputCost = [];
	var inputDays = [];
	var inputHour;

	var requestData = [];

	//Check and format input#stnd-search
	if(document.getElementById('stnd-search').value.replace(/\s*/, "") != "")
	{
		var inputSearch;
		
		inputSearch = document.getElementById('stnd-search').value.replace(/^\s*/, "").replace(/\s*$/, "");
		inputSearch = inputSearch.replace(/^\s*/, "")
		.replace(/\s*$/, "")
		.replace(/\s+/g, "+");

		if (inputSearch != "" && typeof inputSearch !== "undefined")
		{
			requestData.push("search=" + inputSearch);
		}
	}
	
	//Check input#stnd-age
	if(document.getElementById('stnd-age').value.replace(/\s*/, "") != "")
	{
		var inputAge = document.getElementById('stnd-age').value;
	
		if (typeof inputAge !== "undefined")
		{
			requestData.push("age=" + inputAge);
		}
	}

	//Check input#stnd-cost{n}
	var costFreeElem = document.getElementById("stnd-cost-free");
	if(costFreeElem.checked)
	{
		requestData.push("cost=free");
	}
	/* Old method for listing all costs
	for (var i = 1; i <= 6; i++)
	{
		var costElem = document.getElementById("stnd-cost" + i);
		if(costElem.checked)
		{
			inputCost.push(costElem.value);
		}
	}
	if (inputCost.length > 0)
	{
		var costString = "cost=";
		for(var ii = 0; ii < inputCost.length; ii++)
		{
			costString += (ii > 0 ? "+" : "") + inputCost[ii];
		}
		requestData.push(costString);
	}
	*/
	
	//Check input#stnd-days{n}
	for (var i = 1; i <= 7; i++)
	{
		var daysElem = document.getElementById("stnd-days" + i);
		if(daysElem.checked)
		{
			inputDays.push(daysElem.value);
		}
	}
	if (inputDays.length > 0)
	{
		var daysString = "days=";
		for(var ii = 0; ii < inputDays.length; ii++)
		{
			daysString += (ii > 0 ? "+" : "") + inputDays[ii];
		}
		requestData.push(daysString);
	}

	//Check input#stnd-hour
	if(document.getElementById('stnd-hour').value != "none")
	{
		inputHour = document.getElementById('stnd-hour').value;

		if (typeof inputHour !== "undefined")
		{
			requestData.push("time=" + inputHour);
		}
	}
		
	//Hide the update button and show the loading animation
	$('span#loading-map').show();
	$('input#stnd-submit').hide();
	
	DoSearch(requestData);
}

//Update locations object, followed by a call to UpdateMarkers() to redraw the map
function DoSearch(requestData)
{
	ClearLocations();
	$('div#search-feedback').fadeOut(250);
	//CREATE QUERY STRING FROM requestData ARRAY OF QUERY ELEMENTS
	var requestDataString = "";
	for (var i = 0; i < requestData.length; i++)
	{
		requestDataString += (i > 0 ? "&" : "") + requestData[i];
	}
	
	$.ajax(
	{
		url: '/_code/DoSearch.php?' + requestDataString,
		type: 'GET',
		cache: 'false',
		dataType: 'json',
		success: function(response)
		{
			locations = response.locations;
			UpdateMarkers();
			$('span#loading-map').hide();
			$('input#stnd-submit').show();
			//If no results are returned show the search suggestion dialog
			if(response.locations.length < 1)
			{
				$('div#search-feedback').html('<p style="margin-top: 0;"><em>There are no results for your search</em>. You could try one or more of the following to improve your search results:</p><ol><li>Try searching with fewer or different keywords</li><li>Use less filtering options like age, cost and times</li><li>Try the singular or plural form of keywords</li></ol><p style="margin-bottom: 0;"><a href="#" onclick="$(\'div#search-feedback\').fadeOut(500);">close</a></p>');
				$('div#search-feedback').fadeIn(250);
			}
		},
		error: function(response)
		{
			alert("There was a problem performing the location lookup. Let us know at support@youthlinkspokane.org and we will address the problem. Thanks!");
			UpdateMarkers();
			$('span#loading-map').hide();
			$('input#stnd-submit').show();
		}
	});
}

//Process the collection of `locations` object and re-draw the markers on the map
function UpdateMarkers()
{
	for (var i = 0; i < locations.length; i++)
	{
		//Add a google.maps.marker to each element in the array of locations
		locations[i].marker = new google.maps.Marker(
		{
			position: new google.maps.LatLng(locations[i].point.lat, locations[i].point.lng),
			title: locations[i].name,
			map: mapLocator
		});
		
		google.maps.event.addListener(locations[i].marker, 'click', ShowInfoWindowCallback(locations[i]));
	}
	//Set the viewport to fit the markers. Slight delay to allow initial viewport load
	setTimeout(function() { AdjustMapBounds(); }, 100);
}

//Callback function provides closure for infoWindow opening and closing for multiple locations
function ShowInfoWindowCallback(location)
{
	return function() {
		ShowInfoWindow(location);
	};
}

//Creates HTML content for the infoWindow according to the location information
function CreateInfoWindowHTML(location)
{
	//Create a google.maps.infoWindow for each marker. Add each infoWindow to the array of locations
	var infoWindowHTML = "<div class=\"infoWindow\">\n";
	infoWindowHTML += "<div class=\"organization\"><span>Operated by:</span>" + location.organization.name + "</div>\n";
	if (typeof(account) != "undefined")
	{
		infoWindowHTML += "<div class=\"options\"><a href=\"#\" onclick=\"EditLocation(" + location.id + ");\">Edit</a></div>\n";
	}
	infoWindowHTML += "<div class=\"address\">" + location.address.street + "<br />" + location.address.city + ", " + location.address.state + " " + location.address.zip + "</div>\n";
	if (location.uri.length > 0)
	{
		infoWindowHTML += "<div class=\"uri\"><a href=\"http://" + location.uri + "\">http://" + location.uri + "</a></div>\n";
	}
	infoWindowHTML += "<div class=\"days\"><span>Open:</span>";
	if (location.times.opening == location.times.closing)
	{
		infoWindowHTML += "All day";
	}
	else
	{
		if (location.times.opening == 0)
		{
			infoWindowHTML += "Midnight";
		}
		else if (location.times.opening == 12)
		{
			infoWindowHTML += "Noon";
		}
		else
		{
			infoWindowHTML += (location.times.opening > 12 ? location.times.opening - 12 + "pm" : location.times.opening + "am");
		}
		infoWindowHTML += " to ";
		if (location.times.closing == 0)
		{
			infoWindowHTML += "Midnight";
		}
		else if (location.times.closing == 12)
		{
			infoWindowHTML += "Noon";
		}
		else
		{
			infoWindowHTML += (location.times.closing > 12 ? location.times.closing - 12 + "pm" : location.times.closing + "am");
		}
	}
	infoWindowHTML += " on ";
	if (location.days.length == 7)
	{
		infoWindowHTML += "every day";
	}
	else
	{
		for (var ii = 0; ii < location.days.length; ii++)
		{
			infoWindowHTML += (ii > 0 ? ", " : "") + location.days[ii].abbrev;
		}
	}
	infoWindowHTML += "</div>\n";
	if (location.ages.min == 0 && location.ages.max == 21)
	{
		infoWindowHTML += "<div class=\"ages\"><span>Ages:</span>All ages</div>\n";
	}
	else
	{
		infoWindowHTML += "<div class=\"ages\"><span>Ages:</span>" + location.ages.min + " to " + location.ages.max + "</div>\n";
	}
	infoWindowHTML += "<div class=\"cost\"><span>Cost:</span>" + location.cost.name + "</div>\n";
	infoWindowHTML += "<div class=\"desc\">" + location.description + "</div>\n";
	infoWindowHTML += "</div>\n";
	return infoWindowHTML;
}

//Open the infoWindow for the location provided
function ShowInfoWindow(location)
{
	if (infoWindow)
	{
		infoWindow.close();
	}
	var infoWindowHTMLTabs = "";
	var infoWindowHTMLContent = "";
	for (var i = 0; i < locations.length; i++)
	{
		if ((locations[i].point.lat == location.point.lat) && (locations[i].point.lng == location.point.lng))
		{
			infoWindowHTMLTabs += "<li><a href=\"#infoWindowTab-" + locations[i].id + "\"><span>" + locations[i].name + "</span></a></li>";
			infoWindowHTMLContent += "<div id=\"infoWindowTab-" + locations[i].id + "\">" + CreateInfoWindowHTML(locations[i]) + "</div>";
		}
	}
	//Order of infoWindow and tabs creation prevents IE7 bug where tabs cannot be created if the infoWindow DOM element is still hidden
	infoWindow = new google.maps.InfoWindow();
	infoWindow.open(mapLocator, location.marker);
	infoWindow.setContent("<div id=\"infoWindowTabs\"><ul>" + infoWindowHTMLTabs + "</ul>" + infoWindowHTMLContent + "</div>");
	$("div#infoWindowTabs").tabs();
}

//Adjusts the bounds of the map viewport to fit markers
function AdjustMapBounds()
{
	if(locations.length == 1)
	{
		mapLocator.setCenter(locations[0].marker.getPosition());
		mapLocator.setZoom(16);
	}
	else if(locations.length > 1)
	{
		var mapBounds = mapLocator.getBounds();
		var updateBounds = false;
		for (var i = 0; i < locations.length; i++)
		{
			if(!mapBounds.contains(locations[i].marker.getPosition()))
			{
				mapBounds.extend(locations[i].marker.getPosition());
				updateBounds = true;
			}
		}
		if(updateBounds)
		{
			mapLocator.fitBounds(mapBounds);
		}
	}
}

//Clear the locations object array
function ClearLocations()
{
	infoWindow.close();
	for(i in locations)
	{
		locations[i].marker.setMap(null);
	}
	locations = [];
}

//Display the infoWindow for the requested locationId
function AccntShowLoc(locationId)
{
	for(i in locations)
	{
		if (locations[i].id == locationId)
		{
			google.maps.event.trigger(locations[i].marker, 'click');
		}
	}
}

//Load bus routes via JSON call. Avoids loading bus routes on document.ready event and unnecessary overhead.
function LoadBusRoutes()
{
	$('div.drop-down.bus-routes a.load-routes').hide();
	$('div.drop-down.bus-routes div#bus-routes').show();
	$('div.drop-down.bus-routes div.loading').show();
	//Make an async call to get JSON data for bus route numbers
    $.ajax(
	{
		url: '/_code/GetAllBusRoutes.php',
		type: 'GET',
		cache: 'false',
		dataType: 'json',
		success: function(allRoutes)
		{
			totalBusRoutes = allRoutes.routes.length;
			for (var i = 0; i < allRoutes.routes.length; i++)
			{
				//For each returned route number create a new route
				GetRoute(allRoutes.routes[i]);
			}
		}
	});	
}

//Gets a bus route and adds it to the busRoutes array
//routeNumber: int, The number of the bus route to pull route data for
function GetRoute(routeNumber)
{
	//Make an async call to get JSON data for a bus route
	$.ajax(
	{
		url: '/_code/GetBusRoute.php?route=' + routeNumber,
		type: 'GET',
		cache: 'false',
		dataType: 'json',
		success: function(singleRoute)
		{
			//Create an array of points for the route path
			var pathPoints = [];
			//Add a Google Maps LatLng for each of the points returned by the async JSON call
			for (var i = 0; i < singleRoute.points.length; i++)
			{
				pathPoints.push(new google.maps.LatLng(singleRoute.points[i].lat, singleRoute.points[i].lng));
			}
			//Create a temporary JSON object containing route data, including the number and the path (a Google Maps PolyLine)
			var tempRoute =
			{
				"number": singleRoute.shortName,
				"path": new google.maps.Polyline(
				{
					map: null,
					clickable: false,
					strokeColor: "#" + singleRoute.color,
					strokeWeight: 4,
					strokeOpacity: 1.0,
					path: pathPoints
				})
			};
			$("div#bus-routes div#bus-route-container-" + singleRoute.shortName).show();
			//Add the temporary JSON object to the array of bus routes
			busRoutes.push(tempRoute);
			if (busRoutes.length == totalBusRoutes)
			{
				$('div.drop-down.bus-routes div.loading').hide();
				$('div.drop-down.bus-routes div.all').show();
			}
		}
	});
}
//Toggle the display of a bus route
function ToggleBusRoute(routeNumber)
{
	for (var i = 0; i < busRoutes.length; i++)
	{
		if (busRoutes[i].number == routeNumber)
		{
			if ($('input#bus-route-' + routeNumber).attr('checked'))
			{
				busRoutes[i].path.setMap(mapLocator);
			}
			else
			{
				busRoutes[i].path.setMap(null);
			}
		}
	}
}
//Show all bus routes
function ShowAllBusRoutes()
{
	$('div#bus-routes input').each(function() {
		$(this).attr('checked', 'checked');
		ToggleBusRoute($(this).val());
	});
}
//Hide all bus routes
function HideAllBusRoutes()
{
	$('div#bus-routes input').each(function() {
		$(this).removeAttr('checked');
		ToggleBusRoute($(this).val());
	});
}

//Display the terms of use and site disclaimer
function ShowTerms()
{
	$('div.terms.dialog').dialog('open');
}
