//##################// VARS //##################//
var map;
var directionsMap;
var zoom;
var markerArray = [];
var markerShadowArray = [];
var infoBubble = null;
var selectedMarker;
var address;

var directionDisplay;

var docH;
var docW;
var winH;
var winW;

//##################// DOCUMENT READY //##################//

$(function(){
	// set initial page dimensions
	setDimensions();
	
	// set initial map longitude and latitude
	var lat = 0; // start latitude
	var lon = 0; // start longitude
	zoom = 1; // full zoom out
	
	// initiate object to display directions on map
	directionsDisplay = new google.maps.DirectionsRenderer();
	
	// setup main map with options
	var pos = new google.maps.LatLng(lat,lon);
	var myOptions = {
      zoom: zoom,
      center: pos,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      scrollwheel: false
    };
	map = new google.maps.Map(document.getElementById('map'), myOptions); // main map
	directionsMap = new google.maps.Map(document.getElementById('directionsMap'), myOptions); // map for displaying directions
	
	// connect directionsDisplay to directionsMap
	directionsDisplay.setMap(directionsMap);
	
	// delay hiding map for Google setup
	setTimeout("hideDirections()",1000);
});

//##################// FUNCTIONS //##################//

function hideDirections(){
	$('#directionsMap').hide();
}

function submit(){
	$('#map,#sidebarList').show(); // show main map and main sidebar if hidden
	address = $('#addressInput').val();
	$('#errorMsg').hide().children('#msg').html(""); // clear 'error' popup if needed
	$('#directionsSidebar').html(""); // clear 'directions' sidebar if needed
	if($.trim(address) != ""){
		startSpinner();
		address = address.replace("'","");
		getGeocode(address); // try to geocode address
	}
}

// add a marker to the main map and a sidebar item to the sidebar list
function addMarker(lat,lon,title,info,icon){
	var location = new google.maps.LatLng(lat,lon); // get the google LatLng object
	var infowindow = new google.maps.InfoWindow({ // create marker bubble
    	content: info
	});
	var marker = new google.maps.Marker({ // set the marker on the page with options
		map: map, 
		position: location,
		title: title,
		icon: icon
	});
	
	var bar = '<div class="sidebarBtn">'+title+'</div>'; // sidebar item header div
	bar += '<div class="sidebarInfo">'+info+'</div>'; // sidebar info div
	$('#sidebarList').append(bar); // add sidebar item to the end of the list
	var thisBar = $('#sidebarList .sidebarBtn:last');
	thisBar.click(function(){ //set click for sidebar item
		// reset zoom if 'Start!' is selected
		if(thisBar.html() == "Start!"){
			map.setZoom(zoom);
		}
		$('#map').show(); // show main map if needed
		setSelectedMarker(marker); // indicate which marker on the map is active
		if(infoBubble != null){ // if an marker bubble is open, close it
			infoBubble.close();
		}
		infoBubble = infowindow;
		//infowindow.open(map,marker); // used if a marker bubble is wanted
		map.panTo(location); // center the map on the selected marker
		var infoBar = thisBar.next('div.sidebarInfo');
		$('.sidebarInfo').not(infoBar).slideUp("fast"); // close all sidebar info divs
		$('.sidebarBtnSelected').not(thisBar).removeClass("sidebarBtnSelected").addClass("sidebarBtn");
		infoBar.slideDown("fast"); // show information
		thisBar.removeClass("sidebarBtn").addClass("sidebarBtnSelected");
		$('#sidebarList').scrollTo(thisBar,500,{
			onAfter: function(){ // re-scroll after initial scroll to make sure infoBar is in the correct position
				$('#sidebarList').scrollTo(thisBar,200);
			}
		});
	});
	
	google.maps.event.addListener(marker, 'click', function() {
		setSelectedMarker(marker);
		if(infoBubble != null){ // close sidebar info bubble if one is open
			infoBubble.close();
		}
		infoBubble = infowindow;
		//infowindow.open(map,marker); // open marker bubble
		$('.sidebarBtn,.sidebarBtnSelected').removeClass("sidebarBtnSelected").addClass("sidebarBtn");
		var infoBarItem = thisBar.next('div.sidebarInfo');
		$('.sidebarInfo').not(infoBarItem).slideUp("fast");
		thisBar.removeClass("sidebarBtn").addClass("sidebarBtnSelected");
		infoBarItem.slideDown("fast").each(function(){
			$('#sidebarList').scrollTo(thisBar,500,{ // re-scroll after initial scroll to make sure infoBar is in the correct position
				onAfter: function(){
					$('#sidebarList').scrollTo(thisBar,200);
				}
			});
		});
	});
	markerArray.push(marker); // add marker to array for other functions
}

// initial geocode for address input
function getGeocode(address){
	var geocoder = new google.maps.Geocoder(); // geocode instance
	
	geocoder.geocode( { 'address': address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) { // if a geocode was returned successfully
			deleteOverlays(); // delete any previous markers and shadows
			if(infoBubble != null){ // close any bubbles that may have been open
				infoBubble.close();
			}
			var latLng = results[0].geometry.location; // extract the google LatLng object
			var rad = $('#rad').val(); // determine selected radius and set zoom level
			switch(rad){
				case '10':
					zoom = 11;
					break;
				case '25':
					zoom = 10;
					break;
				case '50':
					zoom = 9;
					break;
				case '100':
					zoom = 7;
					break;
			}
			
			map.setCenter(latLng); // center map on initial address
			map.setZoom(zoom); // zoom to appropriate level
			
			var pos = new convertLatLng(latLng); // extract latitude and longitude from LatLng object
			var lat = pos.lat;
			var lon = pos.lon;
						
			var icon = 'http://www.orangeparents.org/wp-content/themes/orange_parents/images/personPin.png'; // set initial icon
			var content = "<div>Search radius of "+rad+' miles starting at:</div><div>'+address+"</div>"; // information panel
			addMarker(lat,lon,"Start!",content,icon); // add the marker
			setSelectedMarker(null); // clear any previously selected marker
			locateChurches(lat,lon); // proceed to do search on nearby churches
		} else {
			errorMsg("Results were not successful for the following reason: " + status); // error if initial address was not found
			stopSpinner();
		}
	});
}

// search for churches within selected radius of initial address
function locateChurches(lat,lon){
	var url = "http://www.orangeparents.org/wp-content/themes/orange_parents/locateChurches.php";
	var prod = $('#product').val();
	var rad = $('#rad').val(); // radius
	var params = "lat="+lat+"&lon="+lon+"&prod="+prod+"&rad="+rad;
	$.post(url,params,function(reply){ // send ajax request
		var churches = new Array();
		locations = reply.split(':|:');
		if(locations.length > 1){ // if locations were found
		
			// set shadows for locations
			for(var i=0;i<locations.length;++i){
				var loc = locations[i]
				if($.trim(loc) != ""){
					var icon = 'http://www.orangeparents.org/wp-content/themes/orange_parents/images/orangeShadow.png';
					var latLonArray = loc.split('-|-');
					var newLat = latLonArray[0];
					var newLon = latLonArray[1];
					var title = latLonArray[2];
					var info = latLonArray[3];
					var location = new google.maps.LatLng(newLat,newLon);
					var marker = new google.maps.Marker({ // set the marker on the page with options
						map: map, 
						position: location,
						title: title,
						icon: icon
					});
					markerShadowArray.push(marker); // add shadow to array for other functions
				}
			}
			
			// set pins for locations
			for(var i=0;i<locations.length;++i){
				var loc = locations[i]
				if($.trim(loc) != ""){
					var icon = 'http://www.orangeparents.org/wp-content/themes/orange_parents/images/orangePin.png';
					var latLonArray = loc.split('-|-');
					var newLat = latLonArray[0];
					var newLon = latLonArray[1];
					var title = latLonArray[2];
					var info = latLonArray[3];
					addMarker(newLat,newLon,title,info,icon); // add the marker to the map
				}
			}			
		} else {
			errorMsg("No results found for search area.");
		}
		stopSpinner();
	});
}

// removes all shadows and pins
function deleteOverlays() {
	if (markerArray.length) {
		for (var i=0;i<markerArray.length;++i){
			markerArray[i].setMap(null);
		}
		//markerArray.length = 0;
		markerArray = [];
	}
	if (markerShadowArray.length) {
		for (var j=0;j<markerShadowArray.length;++j){
			markerShadowArray[j].setMap(null);
		}
		//markerShadowArray.length = 0;
		markerShadowArray = [];
	}
	$('#sidebarList').html("");
}

// sets selected marker indicator
function setSelectedMarker(selected){
	if(selectedMarker){
		selectedMarker.setMap(null);
	}
	if(selected != null && selected.icon != 'http://www.orangeparents.org/wp-content/themes/orange_parents/images/personPin.png'){
		selectedMarker = new google.maps.Marker({
			map: map, 
			position: selected.position,
			title: selected.title,
			icon: 'http://www.orangeparents.org/wp-content/themes/orange_parents/images/greenPin.png'
		});
	}
}

// shows directions map for selected church
function directions(destination){
	startSpinner();
	var directionsService = new google.maps.DirectionsService(); // initiate google directions object
	directionsService.route({origin: address, destination: destination, travelMode: 'DRIVING'}, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) { // successful response
			$('#map,#sidebarList').hide(); // hide main map and church list
			$('#directionsMap').show();
			directionsDisplay.setDirections(response); // send directions object to map
			var steps = new Array();
			steps = response.routes[0].legs[0].steps;
			var directions = '';
			for(var i=0;i<steps.length;++i){
				directions += '<div class="sidebarDirections">'+steps[i].instructions+'</div>'; // add each direction div
			}
			var backBtn = '<div class="sidebarBtnSelected" id="backToList" onclick="backToList();">&laquo; Back to List</div>'; // create button to return to main map
			var printBtn = '<div style="text-align: center; margin-top: 3px;"><button onclick="window.open(\'http://maps.google.com?saddr='+escape(address)+'&daddr='+escape(destination)+'\',\'_blank\');">View in Google Maps</button></div>'; // create button to open in google maps
			$('#directionsSidebar').html(directions).prepend(backBtn).append(printBtn); // all components to directions sidebar
			stopSpinner();
		} else {
			stopSpinner();
		}
	});
}

// convert google LatLng back into lat and lon vars
function convertLatLng(latLng){
	var latLngString = latLng.toString();
	latLngString = latLngString.replace('(','');
	latLngString = latLngString.replace(')','');
	latLngString = latLngString.replace(' ','');
	var latLngArray = new Array();
	latLngArray = latLngString.split(',');
	this.lat = latLngArray[0];
	this.lon = latLngArray[1];
}

// initial document and window dimensions - also called on resize of body
function setDimensions(){
	docH = $(document).height();
	docW = $(document).width();
	winH = $(window).height();
	winW = $(window).width();
	
	// set map content area height
	$('#mapbody').height($('#map').height() + 150);
	
	// set directions map to mimic main map size
	var mainMap = $('#map');
	$('#directionsMap').height(mainMap.height()).width(mainMap.width());
	// set directions map to mimic main map position on page
	var sideM = (mainMap.width()+20)
	var mapPos = mainMap.position();
	var sideT = mapPos.top;
	$('#sidebarList,#directionsSidebar').css("left",sideM+"px").css("top",sideT+"px");
	$('#legend').css("left",(sideM - 370)+"px").css("top",(sideT - 111)+"px");
}

// error message
function errorMsg(msg){
	var errorMsg = $('#errorMsg');
	errorMsg.children('#msg').html(msg);
	//var mapPos = $('#map').position();
	//var mapL = mapPos.left;
	//var mapT = mapPos.top;
	//var mapW = $('#map').width();
	//var mapH = $('#map').height();
	//var posL = (mapL + ((mapW - errorMsg.width()) / 2));
	//var posT = (mapT + ((mapH - errorMsg.height()) / 2));
	
	var posL = ((docW - errorMsg.width()) / 2);
	var posT = ((winH - errorMsg.height()) / 2);
	errorMsg.show().css("left",posL+"px").css("top",posT+"px");
}

// clear and close 'error' popup
function closeErrorMsg(){
	$('#errorMsg').hide().children('#msg').html("");
}

// clear and close directions and go back to list
function backToList(){
	$('#map,#sidebarList').show();
	$('#directionsMap').hide();
	$('#directionsSidebar').html("");
}

// spinner functions
function startSpinner(){
	var spinr = $('#spinner');
	//var mapPos = $('#mapContent').position();
	//var mapL = mapPos.left;
	//var mapT = mapPos.top;
	//var mapW = $('#mapContent').width();
	//var mapH = $('#mapContent').height();
	//var posL = (mapL + ((mapW - spinr.width()) / 2));
	//var posT = (mapT + ((mapH - spinr.height()) / 2));
	
	var posL = ((docW - spinr.width()) / 2);
	var posT = ((winH - spinr.height()) / 2);
	spinr.show().css("left",posL+"px").css("top",posT+"px");
}
function stopSpinner(){
	$('#spinner').hide();
}
