var gmap, gdir, gcode, gcenter, gmgr;

var redIcon = new GIcon(G_DEFAULT_ICON);
redIcon.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/red/blank.png";

var blueIcon = [];
for (i = 1; i < 11; i++) {
	blueIcon[i] = new GIcon(G_DEFAULT_ICON);
	blueIcon[i].image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/marker"+i+".png";
}

function initMaps(){
	if (VCAhospitalId != '1121949') {
  	gmap = new GMap2($('#map').get(0));
  	gdir = new GDirections(gmap, $('#directions').get(0));
  	gcode = new GClientGeocoder();
  	
  	gmap.addControl(new GSmallMapControl());
  	gmap.clearOverlays();
  	if ($('#lat').val() !== '' && $('#lng').val() !== '') {
  		//var place = response.Placemark[0];
				gcenter = new GLatLng($('#lat').val(), $('#lng').val());
				gmap.setCenter(gcenter, 13);
				var gmarker = new GMarker(gcenter, {
					icon: redIcon
				});
				gmap.addOverlay(gmarker);
				//$('#end').val(place.address);
				GEvent.addListener(gmarker, 'click', function(){
					gmarker.openInfoWindowHtml('<div class="mapinfo"><b>' + $('.vcard .org').text() + '</b><br/>' +
					$('.vcard .adr').text() +
					'<br />' +
					$('.vcard .tel:first').text());
				});
				if ($('ul').is('#nearby')) {
					getNearby();
				}
			}
			else {
				$('#end').val('Address not found').removeAttr('readonly');
			}
			
			$('#get-directions').click(function(){
				getDirections();
				return false;
			});
			$('#send-directions').click(function(){
				sendDirections();
				return false;
			});
			GEvent.addListener(gdir, 'load', setDirections);
		}
}	

function getCookie(key){
  var pairs = document.cookie.split(';'), val = false;
  for (var i=0, j=pairs.length; i<j; i++) {
    var n = pairs[i].split("=");
    if (n.length == 2){
      var k = unescape(n[0].replace(/^\s+|\s+$/g,""));
      var v = unescape(n[1].replace(/\+/g, " "));
      if (key == k) { val = v; }
    }
  }
  return val;
}


function getDirections(){
	gcode.getLocations($('#start').val(), function(response){
		if (!response || response.Status.code != 200) {
			$('#start').val('Address not found');
		} else {
			gmap.clearOverlays();
			$('#start').val(response.Placemark[0].address);
			
			gdir.load('from: '+$('#start').val()+' to: '+$('#end').val());
		}
	});
}

function setDirections(){
	$('#directions').show();
	var text = '';
	var route = gdir.getRoute(0);
	text += 'Start: '+ $('#start').val()+'\n\n';
	for (i=0, j=route.getNumSteps(); i<j; i++){
		step = route.getStep(i);
		text += (i+1)+'  ';
		text += step.getDescriptionHtml();
		text += ' ('+step.getDistance().html+')'+'\n';
	}
	text += '\n'+'End: '+ $('#end').val()+'\n';
	text += route.getSummaryHtml();
	$('#mail-ready').html(text);
}

function getNearby(){
	/**
	 * markers.xml (to be generated from addresses in ams) format
	 * <markers>
	 *   <marker name="My VCA Hospital" address="1521 1st Ave, Seattle, WA" phone="1-234-567-8901" shortname="myvca" lat="47.608940" lng="-122.340141" />
	 * <markers>
	 * @param {Object} response
	 */
	var loading = $('<img />').attr({src: '/img/ajax-loader.gif', id:'loading'}).css({position:'absolute', left:'187px', top:'150px'});
	$('#map').append(loading);
	$.get($('#markers').val()+'?lat='+gcenter.lat()+'&lng='+gcenter.lng(), function(response){
		gmgr = new MarkerManager(gmap);
		var markers = [];
		var bounds = new GLatLngBounds();
		var i = 0;
		$('marker', response).each(function(){
	    var name = this.getAttribute("name");
	    var address = this.getAttribute("address");
	    var phone = this.getAttribute("phone");
	    var distance = this.getAttribute("distance");
	    var url = 'http://'+window.location.host+'/'+this.getAttribute("shortname");
	    var point = new GLatLng(parseFloat(this.getAttribute("lat")), parseFloat(this.getAttribute("lng")));
			bounds.extend(point);
			if (i>0){
		  	var marker = new GMarker(point, { icon: blueIcon[i] });
				$('#nearby').append('<li>'
						+ '<img src="'+blueIcon[i].image+'" alt="marker" />'
						+ '<b>' + name + '</b>'
						+ ' (' + Math.round(distance*10)/10 + ' miles)<br/>' 
						+ address + '<br />'
						+ 'Phone: ' + phone + '<br />'
						+ '<a href="' + url + '/maps-directions.html" target="_blank" class="external">Map &amp; Driving Directions</a><br />'
						+ '<a href="' + url + '" target="_blank" class="external">Official Website</a></li>');
		  	GEvent.addListener(marker, 'click', function(){
		  		marker.openInfoWindowHtml('<div class="mapinfo"><b>' + name + '</b><br/>' 
						+ address + '<br />'
						+ 'Phone: ' + phone + '<br />'
						+ '<a href="' + url + '/maps-directions.html" target="_blank" class="external">Map &amp; Driving Directions</a><br />'
						+ '<a href="' + url + '" target="_blank" class="external">Official Website</a></div>');
		  	});
				markers.push(marker);
			}
			i++;
		});
		gmgr.addMarkers(markers, 1);
		$('#loading').hide();
		gmgr.refresh();
		gmap.setCenter(bounds.getCenter(), gmap.getBoundsZoomLevel(bounds));
	});
}


function sendDirections(){
	$('.error-msg', $('.pop-content')).text('');
	var text = $('.vcard').text();	
	text += cleanString($('#custom-content').html())+'\n\n';
	text += 'Turn by Turn Directions\n';
	text += cleanString($('#mail-ready').html());
	var email = $('input[type=text]', $('.pop-content')).val();
	if (!/^[A-Z0-9._+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(email)){
		$('.error-msg', $('.pop-content')).text('Please use a valid email format, eg. abc@xyz.com.');
		return false;
	} 
	var pop = $('.pop-content');
	//alert(text);
	$.post('/tools/mail-directions.php', {
			email: $('#email', pop).val(), 
			optin: $('#optin', pop).is(':checked') ? 1 : 0,
			ipaddress: $('#ipaddress', pop).val(),
			useragent: $('#useragent', pop).val(),
			hospitalid: $('#hospitalid', pop).val(),
			token: $('#token', pop).val(),
			message: escape(text) 
		}, function(data){
			pop.empty().html(data);
	});
}

function cleanString(str){
	return str.replace(/<([A-Z][A-Z0-9]*)\b[^>]*>(.*?)<\/\1>/ig, '$2').replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&');
}	

	

$('body').unload(function(){
	GUnload();
});

