$(document).ready(function(){

var map;
var gmarkers = [];
var markerInfo = [];
var locServices = [];
var flyoutDefault = $("#flyoutLocationBrowser .default").text();
var gdir;
var geocoder = null;
var addressMarker;
var dirDestinationName = "";
var dirDestinationCoord = "";

var directionsDefault = "From: Street Address, City, State";

if ($("#startAddress").val() == "") $("#startAddress").val(directionsDefault);
$("#startAddress").focus(function() {
	if ($(this).val() == directionsDefault) {
		$(this).removeClass("default");
		$(this).val("");
	}
});
$("#startAddress").blur(function() {
	if ($(this).val() == "") {
		$(this).addClass("default");
		$(this).val(directionsDefault);
	}
});

$("#getDirections").submit(function() {
	if ($("#startAddress").val() != directionsDefault) {
		$("#displayDirections").html("");
		$("#displayDirections").show();
		setDirections($("#startAddress").val(), dirDestinationName + "@" + dirDestinationCoord, "en_US");
	} else {
		gdir.clear();
		$("#displayDirections").hide();
	}
	return false;
});

$("#btnGetDirections").click(function() {$("#getDirections").submit();});
$("#startAddress").keypress(function(e) {
	if (e.which == 13) {
		e.preventDefault();
		//e.stopPropagation();
		e.cancelBubble = true;
		e.returnValue = false;
		$("#getDirections").submit();
	}
});



if (GBrowserIsCompatible()) {
	map = new GMap2(document.getElementById("mapstraction")); 
	map.setCenter(new GLatLng(32.798007,-117.150822), 12);
	map.setUIToDefault();
	
	/////////////////////////Directions
	function initialize() {
		gdir = new GDirections(map, document.getElementById("displayDirections"));
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
		GEvent.addListener(gdir, "error", handleErrors);
	}

	function setDirections(fromAddress, toAddress, locale) {
		gdir.load("from: " + fromAddress + " to: " + toAddress, {"locale": locale});
	}

	function handleErrors(){
		$("#displayDirections").html("<h2>Address Not Found</h2><p>Please enter your address in the format <em>\"street address, city, state\"</em>, or try another address.</p>");
	}

	function onGDirectionsLoad(){
		
	}

	initialize();
	///////////////////////////////////
	
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.shadow = g_HttpRelativeWebRoot + "groups/public/@sitearchitecture/documents/assets/a003276.png";
	baseIcon.iconSize = new GSize(30, 36);
	baseIcon.shadowSize = new GSize(54, 36);
	baseIcon.iconAnchor = new GPoint(15, 36);
	baseIcon.infoWindowAnchor = new GPoint(30, 2);

	function createMarker(latLongX, latLongY, locID, iconType, locationName, streetAddr, cityStateZip) {
		var imageIcon = new GIcon(baseIcon);
		
		markerInfo[locID] = [locationName, streetAddr, cityStateZip];

		if (iconType == "hospital") {
			imageIcon.image = g_HttpRelativeWebRoot + "groups/public/@sitearchitecture/documents/assets/a003259.png";
		} else if (iconType == "urgentcare") {
			imageIcon.image = g_HttpRelativeWebRoot + "groups/public/@sitearchitecture/documents/assets/a003260.png";
		} else if (iconType == "office") {
			imageIcon.image = g_HttpRelativeWebRoot + "groups/public/@sitearchitecture/documents/assets/a003261.png";
		} else {
			imageIcon.image = g_HttpRelativeWebRoot + "groups/public/@sitearchitecture/documents/assets/a003262.png";
		}

		// Set up our GMarkerOptions object
		markerOptions = {icon : imageIcon};
		var point = new GLatLng(latLongX, latLongY);
		var marker = new GMarker(point, markerOptions);
		var markerHTML = "";

		markerHTML += "<h2>" + locationName + "</h2>";
		markerHTML += "<p>";
		markerHTML += streetAddr + "<br />";
		markerHTML += "<span class=\"locBldgSuite\"></span>";
		markerHTML += cityStateZip;
		markerHTML += "<span class=\"locPhone\"></span>";
		markerHTML += "<span class=\"locFax\"></span>";
		markerHTML += "<span class=\"locURL\"></span>";
		markerHTML += "</p>";
							
		GEvent.addListener(marker, "click", function() {
			windowOptions = {maxWidth : 250};
			marker.openInfoWindowHtml(markerHTML, windowOptions);
			$(".locWrap").hide();
			$("."+locID).show();
			$("#flyoutLocationBrowser .default").text(flyoutDefault);
			$("#wrapMapDirections").show();
			dirDestinationName = locationName;
			dirDestinationCoord = latLongX + "," + latLongY;
			$("#getDirections").submit();
		});
		
		gmarkers[locID] = marker;
		$("<div class=\"locWrap " + locID + "\"><div class=\"locInfoMain\">" + markerHTML + "</div><div class=\"locInfoUnits\"></div></div>").appendTo("#mapLocationInfoDisplay");

		return marker;
	}
	
	function createLocSvc (svcTitle, svcURL, locations, serviceID) {
		var locID = "";
		$("<li class=\"mainLevel\"><a href=\"#\" class=\"active " + serviceID + "\">" + svcTitle + "</a></li>").appendTo("#locServiceList");
		
		if (locations.length > 0) {
			$("<ul class=\"subLevel\"></ul>").appendTo("#locServiceList li.mainLevel:last");
			
			for (var locCount = 0; locCount < locations.length; locCount++) {
				locID = locations[locCount][0];
				locUnitName = locations[locCount][1];
				locUnitSuite = locations[locCount][2];
				locUnitPhone = locations[locCount][3];
				locUnitFax = locations[locCount][4];
				//locUnitURL = locations[locCount][5];
				
				if (locUnitSuite != "") locUnitSuite = locUnitSuite + "<br />";
				if (locUnitPhone != "") locUnitPhone = "<br />Phone: " + locUnitPhone;
				if (locUnitFax != "") locUnitFax = "<br />Fax: " + locUnitFax;
				
				$("<li class=\"" + serviceID + "\"><a href=\"#\" class=\"" + locID + "\"><span class=\"locSvcName\">" + locUnitName + ": " + markerInfo[locID][0] + "</span><div class=\"locSvcInfo\"><h2>" + svcTitle + "</h2><span class=\"locUnitSuite\">" + locUnitSuite + "</span><span class=\"locUnitPhone\">" + locUnitPhone + "</span><span class=\"locUnitFax\">" + locUnitFax + "</span></div></a></li>").appendTo("#locServiceList ul.subLevel:last");
			}
		}
	}

	// Add Locations (Map Markers)
						
	// Main Campus
	map.addOverlay(createMarker(32.798007,-117.150822, "locMainCampus", "hospital", "North Central City (Main Campus)", "3020 Children's Way", "San Diego, CA 92123"));

	// Pharmacy
	map.addOverlay(createMarker(32.798943,-117.151092, "locPharmacy", "clinic", "North Central City (Main Campus)", "3030 Children's Way", "San Diego, CA 92123"));

	// Plaza
	map.addOverlay(createMarker(32.808484,-117.150251, "locPlaza", "office", "North Central City", "3665 Kearny Villa Road", "San Diego, CA 92123"));

	// Alexa's PLAYC
	map.addOverlay(createMarker(32.809384,-117.150765, "locAlexasPLAYC", "office", "North Central City", "3685 Kearny Villa Road", "San Diego, CA 92123"));
	
	// Family Violence Program
	map.addOverlay(createMarker(32.715589,-117.162895, "locFamViolenceProg", "clinic", "Central City", "707 Broadway Avenue", "San Diego, CA 92101"));

	// Trauma Counseling / Family Support Program
	map.addOverlay(createMarker(33.182979,-117.325486, "locTraumaCounseling1", "clinic", "North Coastal", "3142 Vista Way", "Oceanside, CA 92056"));

	// Trauma Counseling / Family Support
	map.addOverlay(createMarker(32.608082,-117.065292, "locTraumaCounseling2", "clinic", "South Bay", "1261-D Third Avenue", "Chula Vista, CA 91911"));

	// Rady Children's Solana Beach Center
	map.addOverlay(createMarker(32.993707,-117.259512, "locSolanaBeachCntr", "clinic", "North Coastal", "667 San Rodolfo Drive", "Solana Beach, CA 92075"));

	// North County Medical Center
	map.addOverlay(createMarker(33.090889,-117.079147, "locNorthCountyMC", "hospital", "North Inland", "625 West Citracado Parkway", "Escondido, CA 92025"));

	// Rady Children's North County Center
	map.addOverlay(createMarker(33.188083,-117.287497, "locNorthCountyCntr", "clinic", "North Coastal", "4120 Waring Road", "Oceanside, CA 92056"));
	
	// Rady Children's Urgent Care Center - East County
	map.addOverlay(createMarker(32.780882,-117.009776, "locUrgCareEast", "urgentcare", "East County", "5565 Grossmont Center Drive", "La Mesa, CA 91942"));
	
	// Rady Children's Urgent Care Center - Mid-City
	map.addOverlay(createMarker(32.749164,-117.101422, "locUrgCareMid", "urgentcare", "Mid-City", "4305 University Avenue", "San Diego, CA 92105"));

	// City Heights Wellness Center
	map.addOverlay(createMarker(32.747889,-117.098952, "locCityHeightsWellness", "clinic", "Mid-City", "4440 Wightman Street", "San Diego, CA 92105"));

	// C3 North Central & South Bay
	map.addOverlay(createMarker(32.800227,-117.150619, "locC3NorthCen", "clinic", "North Central City", "8010 Frost Street", "San Diego, CA 92123"));

	// C3 North Inland
	map.addOverlay(createMarker(33.14723,-117.150019, "locC3NorthInland", "clinic", "North Inland", "380 Mulberry Drive", "San Marcos, CA 92069"));
	
	// Rady Children's Behavioral Crisis Center
	map.addOverlay(createMarker(33.188967,-117.328615, "locBehavCrisis", "clinic", "North Coastal", "2125 South El Camino Real", "Oceanside, CA 92054"));

	// CSSD San Diego
	map.addOverlay(createMarker(32.776365,-117.06066, "locCSSD", "clinic", "East County", "6386 Alvarado Court", "San Diego, CA 92115"));

	// CSSD El Centro
	map.addOverlay(createMarker(32.778099,-115.569496, "locCSSDElCen", "clinic", "Imperial Valley", "1745 South Imperial Avenue", "El Centro, CA 92243"));
	
	// CSSD Encinitas
	map.addOverlay(createMarker(33.058785,-117.262784, "locCSSDEnc", "clinic", "North Coastal", "477 North El Camino Real", "Encinitas, CA 92024"));
	
	// CSSD Murrieta
	map.addOverlay(createMarker(33.557561,-117.184317, "locCSSDMurr", "clinic", "Southern Riverside", "25485 Medical Center Drive", "Murrieta, CA 92562"));

	// Polinsky Children's Center Medical Clinic
	map.addOverlay(createMarker(32.83036,-117.123026, "locPolinsky", "clinic", "North Central City", "9400 Ruffin Court", "San Diego, CA 92123"));

	// Scripps Memorial
	map.addOverlay(createMarker(32.884523,-117.225089, "locScrippsMem", "hospital", "North Central City", "9888 Genesee Avenue", "La Jolla, CA 92037"));

	// Scripps Encinitas
	map.addOverlay(createMarker(33.037751,-117.283407, "locScrippsEnc", "hospital", "North Coastal", "354 Santa Fe Drive", "Encinitas, CA 92024"));

	// Sharp Grossmont Hospital
	map.addOverlay(createMarker(32.781275,-117.007284, "locSharpGross", "hospital", "East County", "5555 Grossmont Center Drive", "La Mesa, CA 91942"));

	// Rady Children's Group Home
	map.addOverlay(createMarker(32.807456,-117.174981, "locGroupHome", "clinic", "North Central City", "3453 Aveley Place", "San Diego, CA 92111"));

	// RCPMS
	map.addOverlay(createMarker(32.812001,-117.122826, "locRCPMS", "office", "North Central City", "3860 Calle Fortunada", "San Diego, CA 92123"));

	// Rady Children's Home Health
	map.addOverlay(createMarker(32.807983,-117.147109, "locHomeHealth", "office", "North Central City", "8291 Aero Place", "San Diego, CA 92123"));

	// First 5 Healthy Development Services
	//map.addOverlay(createMarker(32.990003,-117.255007, "locFirst5NorthCoastal", "clinic", "North Coastal", "445 Marine View Avenue", "Del Mar, CA 92014"));
	
	
	// Add Location Services
	
	// Alexa's PLAYC
	var svcLocAlexasPLAYC = [];
	svcLocAlexasPLAYC.push(["locAlexasPLAYC", "Educational Programs for Autistic Spectrum Disorders", "", "858-966-8555", ""]);
	createLocSvc("Alexa's PLAYC", "", svcLocAlexasPLAYC, "svcLocAlexasPLAYC");
	
	// Chadwick Center For Children & Families
	var svcLocChadwick = [];
	svcLocChadwick.push(["locMainCampus", "Trauma Counseling, Forensic &amp; Medical Services", "Building 24", "858-966-4011", ""]);
	svcLocChadwick.push(["locFamViolenceProg", "Family Violence Program", "", "619-533-3529", ""]);
	svcLocChadwick.push(["locTraumaCounseling1", "Trauma Counseling & Family Support", "Suite 207", "760-967-7082", ""]);
	svcLocChadwick.push(["locTraumaCounseling2", "Trauma Counseling & Family Support", "", "619-420-5611", ""]);
	createLocSvc("Chadwick Center For Children & Families", "", svcLocChadwick, "svcLocChadwick");

	// Children's Care Connection (C3)
	var svcLocC3 = [];
	svcLocC3.push(["locC3NorthCen", "Developmental Services", "Suite 100", "877-8C3.KIDS", ""]);
	svcLocC3.push(["locNorthCountyCntr", "Developmental Services", "", "877-8C3-KIDS", ""]);
	svcLocC3.push(["locC3NorthInland", "Developmental Services", "Suite C", "877-8C3-KIDS", ""]);
	createLocSvc("Children's Care Connection (C3)", "", svcLocC3, "svcLocC3");

	// City Heights Wellness Center
	var svcLocCityHeightsWellness = [];
	svcLocCityHeightsWellness.push(["locCityHeightsWellness", "Wellness Services", "Suite 200", "619-321-2920", ""]);
	createLocSvc("City Heights Wellness Center", "", svcLocCityHeightsWellness, "svcLocCityHeightsWellness");

	// First 5 Healthy Development Services
	//var svcLocFirst5 = [];
	//svcLocFirst5.push(["locFirst5NorthCoastal", "Developmental Services", "Suite 120", "858-966-8235", ""]);
	//createLocSvc("First 5 Healthy Development Services", "", svcLocFirst5, "svcLocFirst5");

	// Polinsky Children's Center
	var svcLocPolinsky = [];
	svcLocPolinsky.push(["locPolinsky", "Emergency Shelter For Children Medical Clinic", "Building B", "858-514-5644", ""]);
	createLocSvc("Polinsky Children's Center", "", svcLocPolinsky, "svcLocPolinsky");

	// Rady Children's at Scripps Memorial Hospital Encinitas
	var svcLocScrippsEnc = [];
	svcLocScrippsEnc.push(["locScrippsEnc", "NICU Level II", "", "760-633-6120", ""]);
	createLocSvc("Rady Children's at Scripps Memorial Hospital Encinitas", "", svcLocScrippsEnc, "svcLocScrippsEnc");

	// Rady Children's at Scripps Memorial Hospital La Jolla
	var svcLocScrippsMem = [];
	svcLocScrippsMem.push(["locScrippsMem", "NICU Level II", "", "858-626-6282", ""]);
	createLocSvc("Rady Children's at Scripps Memorial Hospital La Jolla", "", svcLocScrippsMem, "svcLocScrippsMem");

	// Rady Children's at Sharp Grossmont Hospital
	var svcLocSharpGross = [];
	svcLocSharpGross.push(["locSharpGross", "Pediatric Medical Unit", "", "619-740-4854", ""]);
	createLocSvc("Rady Children's at Sharp Grossmont Hospital", "", svcLocSharpGross, "svcLocSharpGross");


	// Developmental Services
	var svcLocDevServices = [];
	svcLocDevServices.push(["locSolanaBeachCntr", "Autism Intervention Center, Developmental Evaluation Clinic, Speech-Language Pathology", "Suite 126", "858-793-9591", ""]);
	svcLocDevServices.push(["locNorthCountyMC", "Physical Therapy", "Suite 102", "760-294-9255", ""]);
	svcLocDevServices.push(["locNorthCountyCntr", "Audiology, Occupational Therapy, Physical Therapy, Speech-Language Pathology", "", "760-758-1620", ""]);
	createLocSvc("Rady Children's Developmental Services", "", svcLocDevServices, "svcLocDevServices");

	// Rady Children's Group Home
	var svcLocGroupHome = [];
	svcLocGroupHome.push(["locGroupHome", "Small Group Home", "", "858-541-2632", ""]);
	createLocSvc("Rady Children's Group Home", "", svcLocGroupHome, "svcLocGroupHome");

	// Rady Children's HomeCare
	var svcLocHomeHealth = [];
	svcLocHomeHealth.push(["locHomeHealth", "HomeCare Visiting & Pharmacy Services", "Suite 130", "858-966-4941", ""]);
	createLocSvc("Rady Children's HomeCare", "", svcLocHomeHealth, "svcLocHomeHealth");

	// Rady Children's Outpatient Pharmacy
	var svcLocOutPharm = [];
	svcLocOutPharm.push(["locPharmacy", "Outpatient Pharmacy Services", "First Floor", "858-966-4060", ""]);
	createLocSvc("Rady Children's Outpatient Pharmacy", "", svcLocOutPharm, "svcLocOutPharm");

	// Rady Children's Outpatient Psychiatry
	var svcLocOutPsych = [];
	svcLocOutPsych.push(["locTraumaCounseling1", "Counseling Services", "Suite 205", "760-758-1480", ""]);
	svcLocOutPsych.push(["locPlaza", "Counseling Services", "Suite 101", "858-966-5832", ""]);
	svcLocOutPsych.push(["locNorthCountyMC", "Counseling Services", "Suite 102", "858-487-9050", ""]);
	createLocSvc("Rady Children's Outpatient Psychiatry", "", svcLocOutPsych, "svcLocOutPsych");

	// RCPMS
	var svcLocRCPMS = [];
	svcLocRCPMS.push(["locRCPMS", "Management Services Organization", "Suite 200", "858-636-4300", "858-636-4319"]);
	createLocSvc("Rady Children's Physician Management Services", "", svcLocRCPMS, "svcLocRCPMS");

	// RCSSD
	var svcLocRCSSD = [];
	svcLocRCSSD.push(["locCSSD", "Allergy & Asthma", "Suite 210", "858-966-8555", ""]);
	svcLocRCSSD.push(["locCSSDElCen", "Allergy, Asthma, Ophthalmology, Otolaryngology & Rheumatology", "Suite 106", "760-353-4681", ""]);
	svcLocRCSSD.push(["locCSSDEnc", "Allergy, Asthma, Cardiology, Dermatology, Endocrinology, Neurology, Ophthalmology, Pediatric Surgery, Otolaryngology, Pulmonology, Rheumatology & Urology", "Building D, Suite 302", "760-944-5545", ""]);
	svcLocRCSSD.push(["locNorthCountyMC", "Cardiology, Gastroenterology, Rheumatology, Neurology, Urology, Endocrinology, Heomphilia Comprehensive Center", "Suite 100", "760-294-9260", ""]);
	svcLocRCSSD.push(["locNorthCountyMC", "Orthopedics", "Suite 204", "760-480-8770", ""]);
	svcLocRCSSD.push(["locNorthCountyMC", "Ophthalmology, Ear Nose & Throat (ENT) & Dermatology", "Suite 206", "760-755-7600", ""]);
	svcLocRCSSD.push(["locNorthCountyMC", "Allergy & Asthma", "Suite 206", "760-755-7650", ""]);
	svcLocRCSSD.push(["locCSSDMurr", "Allergy, Asthma, Cardiology, Endocrinology, Gastroenterology, Ophthalmology, Otolaryngology, Pulmonology, Rheumatology & Urology", "Suite 100", "951-600-1640", ""]);
	createLocSvc("Rady Children's Specialists of San Diego, a Medical Foundation", "", svcLocRCSSD, "svcLocRCSSD");

	// Urgent Care
	var svcLocUrgentCare = [];
	svcLocUrgentCare.push(["locUrgCareEast", "Urgent Care Services", "Building 2, Suite 2", "619-713-5375", ""]);
	svcLocUrgentCare.push(["locNorthCountyMC", "Urgent Care Services", "Suite 100", "760-739-1543", "760-737-0281"]);
	svcLocUrgentCare.push(["locUrgCareMid", "Urgent Care Services", "Suite 150", "619-280-2905", "619-283-1614"]);
	createLocSvc("Rady Children's Urgent Care Centers", "", svcLocUrgentCare, "svcLocUrgentCare");


	// Set up click event triggers for flyout links
	$("#locServiceList .subLevel a").click(function() {
		var locID = $(this).attr("class");
		var locServiceName = $(this).find(".locSvcName").html();
		var locServiceNameFull = locServiceName;
		var locUnitName = $(this).find(".locSvcInfo h2").html();
		var locUnitSuite = $(this).find(".locSvcInfo .locUnitSuite").html();
		var locUnitPhone = $(this).find(".locSvcInfo .locUnitPhone").html();
		var locUnitFax = $(this).find(".locSvcInfo .locUnitFax").html();
		//var locUnitURL = $(this).find(".locSvcInfo .locUnitURL").html();

		
		if (locServiceName.length > 47) locServiceName = locServiceName.substring(0, 47) + "...";
		if (locID != "") GEvent.trigger(gmarkers[locID], "click");
		
		$("." + locID + " .locInfoMain h2").html(locUnitName);	
		$("." + locID + " .locInfoMain .locBldgSuite").html(locUnitSuite);
		$("." + locID + " .locInfoMain .locPhone").html(locUnitPhone);
		$("." + locID + " .locInfoMain .locFax").html(locUnitFax);
		//$("." + locID + " .locInfoMain .locUnitURL").html(locUnitURL);

		
		$("#flyoutLocationBrowser .default").html(locServiceName);
		$("#flyoutLocationBrowser .content").hide();
		$("#flyoutLocationBrowser .default").show();
	});
	$("#flyoutLocationBrowser .default").click(function() {
		$("#flyoutLocationBrowser .default").hide();
		$("#flyoutLocationBrowser .content").show();
	});

	var locIDToLoad = $.query.get("locID");
	if (gmarkers[locIDToLoad]) {
		GEvent.trigger(gmarkers[locIDToLoad], "click");
	} else {
		GEvent.trigger(gmarkers["locMainCampus"], "click");
	}
}

});
