var zipIcon = new GIcon();
zipIcon.image = '../images/markers/image.png';
zipIcon.printImage = '../images/markers/printImage.gif';
zipIcon.mozPrintImage = '../images/markers/mozPrintImage.gif';
zipIcon.iconSize = new GSize(20,34);
zipIcon.shadow = '../images/markers/shadow.png';
zipIcon.transparent = '../images/markers/transparent.png';
zipIcon.shadowSize = new GSize(37,34);
zipIcon.printShadow = '../images/markers/printShadow.gif';
zipIcon.iconAnchor = new GPoint(10,34);
zipIcon.infoWindowAnchor = new GPoint(10,0);
zipIcon.imageMap = [13,0,15,1,16,2,17,3,18,4,18,5,19,6,19,7,19,8,19,9,19,10,19,11,19,12,19,13,18,14,18,15,17,16,16,17,15,18,14,19,14,20,13,21,13,22,12,23,12,24,12,25,12,26,11,27,11,28,11,29,11,30,11,31,11,32,11,33,8,33,8,32,8,31,8,30,8,29,8,28,8,27,8,26,7,25,7,24,7,23,6,22,6,21,5,20,5,19,4,18,3,17,2,16,1,15,1,14,0,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,1,5,1,4,2,3,3,2,4,1,6,0];

var customIcons = [];
    customIcons.zip = zipIcon;

// Remove Duplicate Elements from Cities Array
function removeDuplicates (cities) {
	var comparisonArray = [];
	first:for (var i = 0; i < cities.length; i++) {
		for (var j = 0; j < comparisonArray.length; j++) {
			if (comparisonArray[j] === cities[i]) {
				continue first;
			}	
		}
		comparisonArray[comparisonArray.length] = cities[i];
	}
	return comparisonArray;
}

function createMarker(point, name, address, address2, doctors, orthodontic, city, state, zip, note) {
	var marker = new GMarker(point);
	    return marker;
}

// Alphabetical Sorting

function alphabetical(a, b) {
	var A = a["location"].toLowerCase();
	var B = b["location"].toLowerCase();
	if (A < B) {
		return -1;
	} else if (A > B) {
		return 1;
	}
	else {
		return 0;
	}
}

// Retrieve form on-click
function showDirForm () {
	$('#dir-link').detach();
	$('#dir-form').css('visibility', 'visible');
	return false;
}

function stripy () {
	var tbodys = $("tbody.stripy");
	for (var i = 0, tbLength = tbodys.length; i < tbLength; i += 1) 
	{
		var rows = tbodys[i].getElementsByTagName("tr");
		for (var j = 1, rLength = rows.length; j < rLength;)
		{
			if ($(rows[j]).hasClass("locLabel")) {
				j += 1;
			}
			else {
				$(rows[j]).addClass("altRow");
				j += 2;
			}
		}
	}
}

function mapScroll() {
	var x = $("#map-canvas").offset().top - 100;
	$('html,body').animate({scrollTop: x}, 500);
}

// Ensuring that the marker generated with user-input is always prominent
function importanceOrder (marker,b) {
	return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance*1000000;
}

function load() {
	if (GBrowserIsCompatible()) {
	
		var instructions = "<div id=\"map-instructions\"><p>Please see below for an informational list of Jefferson Dental locations near you. Clicking on a location in the list below will pan the map to its corresponding marker and an information box with details about the location will appear which includes the address and telephone number. Click on the <strong><em>Get Driving Directions</em></strong> link, then enter your starting address to view detailed driving directions to your chosen location.</p><p>Click on a marker on the map to learn more information about that location. You can also use the map control located in the upper-left corner of the map to scroll (click the arrows) and zoom in or out (plus or minus button).</p><p>You may also enter your zip code in the <strong>Find A Clinic</strong> form near the top-right of the page, and then click the <strong><em>Search Now</em></strong> button to help find the location nearest you.</p></div>";
		
		var instructionsSP = "<div id=\"map-instructions\"><p>Hay una lista informativa de Jefferson Dental Clinics con las ubicaciónes más cerca de usted. Al hacer clic en una ubicación en la lista de abajo se mueve el mapa a su marcador correspondiente y un cuadro de información con detalles sobre la ubicación aparecerá con la dirección y número de teléfono. Haga clic en el vínculo Obtener direcciones para llegar, a continuación, escriba la dirección de salida para ver instrucciones detalladas para llegar a la ubicación elegida.</p><p>Haga clic en un marcador en el mapa para obtener más información acerca de ese lugar. Usted también puede usar el mapa de control ubicado en la esquina superior izquierda del mapa para desplazarse (clic en las flechas) y acercar o alejar (botón más o menos).</p><p>También puede introducir su código postal en la Encuentra una Clínica de encontrar una forma en la parte superior derecha de la página y, a continuación, haga clic en el botón Buscar ahora para ayudar a encontrar la ubicación más cercana a usted.</p></div>";

		if (document.getElementsByTagName('html')[0].getAttribute('lang') === 'mx') {
			instructions = instructionsSP;
		};
		$("h1").after(instructions);
		$('#map-instructions').after('<div id="map-canvas"></div>');
		
		//Determining which genxml file to use
		var genxmlFile = "../phpsqlajax_genxml2.php";
		var mapArea = $("#mapArea").val();
		switch (mapArea) {
			case "houston":
				genxmlFile = "../phpsqlajax_genxml2houston.php";
			break;
			case "dallas":
				genxmlFile = "../phpsqlajax_genxml2dallas.php";
			break;
			default:
				genxmlFile = "../phpsqlajax_genxml2.php";
		}
		
        var map = new GMap2(document.getElementById("map-canvas"));
        GDownloadUrl(genxmlFile, function(data) {
        
			var bounds = new GLatLngBounds();
			
			var locArr = [];
			var locLabels = [];
			var xml = GXml.parse(data);
			var markers = xml.documentElement.getElementsByTagName("marker");
			var location;
			var name;
			var i = markers.length;
			
			// Creating each individual marker
			while (i--) {
				name = markers[i].getAttribute("name");
				var address = markers[i].getAttribute("address");
				var address2 = markers[i].getAttribute("address2");
				var doctors = markers[i].getAttribute("doctors");
				var orthodontic = markers[i].getAttribute("orthodontic");
				var city = markers[i].getAttribute("city");
				var state = markers[i].getAttribute("state");
				var zip = markers[i].getAttribute("zip");
				var phone = markers[i].getAttribute("phone");
				var note = markers[i].getAttribute("note");
				var notesp = markers[i].getAttribute("notesp");
				
				if (document.getElementsByTagName('html')[0].getAttribute('lang') === 'mx') {
					note = notesp;
				};
				
				var image = markers[i].getAttribute("image");
				var label = markers[i].getAttribute("label");
				var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
				
				// Variables for outgoing Google Maps link
				var queryStr = parseFloat(markers[i].getAttribute("lat")) + "," + parseFloat(markers[i].getAttribute("lng")) + "(" + address + " " + city + ", " + state + " " + zip + ")";
				var gMapLink = '<a class="directions-link" target="_blank" href="' + 'http://maps.google.com/maps?q=' + queryStr + '" + "title="Click to Get Directions">Get Directions</a>';
				var gMapLinkSP = '<a class="directions-link" target="_blank" href="' + 'http://maps.google.com/maps?q=' + queryStr + '" + "title="Haga clic en el vínculo Obtener Conducir llegar">Obtener Conducir llegar</a>';
				
				if (document.getElementsByTagName('html')[0].getAttribute('lang') === 'mx') {
					gMapLink = gMapLinkSP;
				};
				
				// Creating a marker
				var marker = createMarker(point, name, address, address2, city, state, zip);
				map.addOverlay(marker);
				bounds.extend(point);
							
				// Storage of location attributes for assembling results
				locArr[i] = {location: name, address: address, address2: address2, city: city, state: state, zip: zip, doctors: doctors, phone: phone, note: note, notesp: notesp, image: image, label: label, orthodontic: orthodontic, point: point, queryStr: queryStr, gLink: gMapLink, marker: marker};
				locLabels[i] = locArr[i].label;	
			}
			
			if (document.getElementsByTagName('html')[0].getAttribute('lang') === 'mx') {
				locArr.note = locArr.notesp;
			}
			
			locArr.sort(alphabetical);
			
			// Generate content for each marker InfoWindow	
			for (var j = 0; j < locArr.length; j+=1) {
				if (locArr[j].address2) {
					addr2 = "<br />" + locArr[j].address2;
				}
				else {
					addr2 = '';
				}
				if (document.getElementsByTagName('html')[0].getAttribute('lang') === 'mx') {
					locArr[j].message = '<table width="300" id="marker-text"><tr><td width="90"><img id="location-image" src="/assets/images/locations/' + locArr[j].image + '" /></td><td width="210" style="white-space:nowrap;"><span id="loc-name">' + locArr[j].location + '</span><br />' + locArr[j].address + addr2 + '<br />' + locArr[j].city + ", " + locArr[j].state + " " + locArr[j].zip + '<br /><span id="loc-phone">' + locArr[j].phone + '</span></td></tr><tr>' + '<td colspan="2"><a id="dir-link" href="#" onclick="showDirForm()\; return false\;">Obtener Direcciones</a></td></tr><tr><td colspan="2"><form style="visibility: hidden;" id="dir-form" target="_blank" method="get" action="http://maps.google.es/maps"><input id="saddr" name="saddr" type="text" maxlength="40" size="40" value="Ingrese su dirección de partida aquí." /><input type="hidden" name="daddr" id="daddr" value="' + locArr[j].queryStr + '" /><input type="submit" class="submit" value="Llegar" /></form></td></tr></table>';
				}
				else {
					locArr[j].message = '<table width="300" id="marker-text"><tr><td width="90"><img id="location-image" src="/assets/images/locations/' + locArr[j].image + '" /></td><td width="210" style="white-space:nowrap;"><span id="loc-name">' + locArr[j].location + '</span><br />' + locArr[j].address + addr2 + '<br />' + locArr[j].city + ", " + locArr[j].state + " " + locArr[j].zip + '<br /><span id="loc-phone">' + locArr[j].phone + '</span></td></tr><tr>' + '<td colspan="2"><a id="dir-link" href="#" onclick="showDirForm()\; return false\;">Get Driving Directions</a></td></tr><tr><td colspan="2"><form style="visibility: hidden;" id="dir-form" target="_blank" method="get" action="http://maps.google.com/maps"><input id="saddr" name="saddr" type="text" maxlength="40" size="40" value="Enter your starting address here." /><input type="hidden" name="daddr" id="daddr" value="' + locArr[j].queryStr + '" /><input type="submit" class="submit" value="Get Directions" /></form></td></tr></table>';
				}
			}
			
			// Sort locations in alphabetical order
			var labelsArr = removeDuplicates(locLabels).sort();			
			var sortedLocs = [];
			var sortedZip = [];
			
			for (i = 0; i < labelsArr.length; i++) {
				var labelKey = labelsArr[i];
				sortedLocs[labelKey] = [];
				for (j = 0; j < locArr.length; j++) {
					if (locArr[j].label === labelsArr[i]) {
						sortedLocs[labelKey].push(locArr[j]);					
					}			
				}
			}
			
			// Print table headers
			if (document.getElementsByTagName('html')[0].getAttribute('lang') === 'mx') {
				$('#map-canvas').after('<table id="loc-list"><thead><tr><td colspan="7"><p><i>* Marque el nombre de la ubicaci&oacute;n m&aacute;s cerca de usted para aprender m&aacute;s concerniente esa cl&iacute;nica.</i></p></td></tr><tr><th>Nombre</th><th>Direccion</th><th>Dentists</th><th>Ortodoncia</th><th class="phone">Telefonico</th><th class="notes">Notas</th><th class="directions">Instrucciones</th></tr></thead><tbody class="stripy"></tbody></table>');
			} 
			else {
				$('#map-canvas').after('<table id="loc-list"><thead><tr><td colspan="7"><p><i>* Click on the name of the location nearest you to read more information about that clinic.</i></p></td></tr><tr><th>Name</th><th>Address</th><th>Dentists</th><th>Orthodontics</th><th class="phone">Phone</th><th class="notes">Notes</th><th class="directions">Directions</th></tr></thead><tbody class="stripy"></tbody></table>');
			}
			
			//Initializing variables for sorting locations
			var locationCounter = 0;
			var sortedMarkers = [];	
			var labelHeaderCounter = 0;
			
			/*if (sortedLocs['Corporate Offices']) {
			
				var locationCounter = 1;
			
				// Corporate Office Location Output
				corpLocation = '<div id="location0" class="corpLoc"><img src="assets/images/locations/corporate-offices-large.jpg" alt="" class="floatleft" /><ul><li class="loc-name">' + sortedLocs["Corporate Offices"][0].location + '</li><li>' + sortedLocs["Corporate Offices"][0].address + '</li><li>' + sortedLocs["Corporate Offices"][0].city + ", " + sortedLocs["Corporate Offices"][0].state + " " + sortedLocs["Corporate Offices"][0].zip + '</li><li class="loc-phone">' + sortedLocs["Corporate Offices"][0].phone + '</li><li>' + sortedLocs["Corporate Offices"][0].note + '</li><li>' + sortedLocs["Corporate Offices"][0].gLink + '</li></ul></div>'
			
				$(corpLocation).appendTo("#map-instructions");
				
				//Excluding Corporate Offices location from Table Output
				sortedMarkers[0] = sortedLocs["Corporate Offices"][0].marker;
				locArr[0] = sortedLocs["Corporate Offices"][0];
				delete sortedLocs["Corporate Offices"];
			
				delete sortedZip["76010"];
			}*/			
				
			var headerLabels = [];
			
			for (key in sortedLocs) {
				headerLabels.push(key);
			}
			
			for (name in sortedLocs) {
				if (name != "length") {
					var labelHeader = '<tr class="locLabel"><td colspan="7">' + headerLabels[labelHeaderCounter] + '</td></tr>';
					$(labelHeader).appendTo("#loc-list tbody");
					labelHeaderCounter += 1;
					for (j = 0; j < sortedLocs[name].length; j+=1) {	
						//Sorting each marker
						sortedMarkers[locationCounter] = sortedLocs[name][j].marker;
					
						if (sortedLocs[name][j].address2) {
							addr2 = "<br />" + sortedLocs[name][j].address2;
						}
						else {
							addr2 = '';
						}
						
 //+ sortedLocs[name][j].location.replace(/\s+/g, '-').toLowerCase() + '.html">
						
						location = '<tr class="loc-result" id="location' + locationCounter + '"><td class="loc-name"><a style="text-decoration:underline; display:block; color:#000000;" href="http://www.jeffersondentalclinics.com/' + sortedLocs[name][j].location.replace(/\s+/g, '-').toLowerCase() + '.html">' + sortedLocs[name][j].location + '</a></td><td class="loc-addr">' + sortedLocs[name][j].address + addr2 + '<br /><span class="addr-last">' + sortedLocs[name][j].city + ", " + sortedLocs[name][j].state + " " + sortedLocs[name][j].zip + '</span></td><td class="loc-doctors">' + sortedLocs[name][j].doctors + '</td><td class="loc-ortho"><img id="checkIcon" src="../assets/images/' + sortedLocs[name] [j].orthodontic + '"/></td><td class="loc-phone">' + sortedLocs[name][j].phone + '</td><td>' + sortedLocs[name][j].note + '</td><td class="g-link">' + sortedLocs[name][j].gLink + '</td></tr>';
						//Resort the locations as we go along so the Marker Information matches up with the locations sorted according to labels.
						locArr[locationCounter] = sortedLocs[name][j];
						$(location).appendTo("#loc-list tbody");
						locationCounter +=1;
					}
				}
			}
			
			// Label String for Get Directions Input Field in InfoWindow
			var searchStr = "Enter your starting address here.";
			var searchStrSP = "Ingrese su dirección de partida aquí.";
			
			if (document.getElementsByTagName('html')[0].getAttribute('lang') === 'mx') {
				searchStr = searchStrSP;
			}
			
			// Form Label Handling 			
			$('#saddr').live('focusin', function() {
				if ($(this).attr("value") === searchStr) {
					$('#saddr').attr("value", "");
				}
			});
			$('#saddr').live('focusout', function() {
				if ($(this).attr("value") === "") {
					$('#saddr').attr("value", searchStr);
				}
			});
			
			// Applying events to each marker
			$(sortedMarkers).each(function (i, marker) {
				GEvent.addListener(marker, 'click', function() {
				displayPoint(marker, i);
				});
				$("#location" + i).click(function () {
					$(".active-loc").toggleClass("active-loc");
					$(this).toggleClass("active-loc");
					mapScroll();
					displayPoint (marker, i);
				});
			});
			
			map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
			map.addControl(new GSmallMapControl());
			
			$(".loc-result").hover(function () {
				$(this).addClass("loc-hover");
			}, function () {
				$(this).removeClass("loc-hover");
			});
			
			stripy();
			
			// Pan to the location on GMap when location is clicked
			function displayPoint (marker, index) {
				map.panTo(marker.getLatLng());
				marker.openInfoWindowHtml(locArr[index].message);
			}
		});
	}
}
//function checkLogo(){
	//var greenCheck = document.getElementById("checkIcon");
	//greenCheck.style.display = "none";
//}

$(document).ready(function () {
	load();
	$("img#checkIcon").css("display","none");
});
