jQuery(document).ready(function(){
	initMaps();
	switch ($('body').attr('id')) {
		case 'facebook-maps-directions':
		case 'maps-directions':
			initDirections();
			break;
		case 'other-locations': // hospital page
			initLocations();
			break;
		case 'directory': // corporate
		case 'unknown': // corporate
		case 'home': // facebook iframez directory
			initDirectory();
			break;
		case 'offer':
		case 'micromarket':
		case 'pawslynnwood':
			initOffer();
			break;
	}
});


var gmap, gdir, gcode, gcenter, gmgr, gxml;
function initMaps(){
	gmap = new GMap2($('#map').get(0));
	gcode = new GClientGeocoder();
	//gmap.addControl(new GSmallMapControl());
	gcenter = new GLatLng($('#map-lat').val(), $('#map-lng').val());
	gmap.setCenter(gcenter, 13);
  gmap.clearOverlays();
	gmgr = new MarkerManager(gmap);
}


function initLocations(){
	initSearch();
	if (!getQueryValue('map-zip')){
		getNearby($('#map-lat').val(), $('#map-lng').val());
	}
	else {
		$('#map-zip').val(getQueryValue('map-zip'));
		getCoords($('#map-zip').val());
	}
}

function initDirectory(){
	initSearch();
	if (getQueryValue('map-zip') != '') {
		$('#map-zip').val(getQueryValue('map-zip'));
		getCoords($('#map-zip').val());
	}
	else {
		$('#gmaps').hide();
	}
}

function initSearch(){
	$('#locator-form').submit(function(){
		getCoords($('#map-zip').val());
		$('#gmaps').show();
		return false;
	});
	
	$('#map-zip').focus(function(){
		if (this.value == '[enter city & state OR ZIP here]'){
			this.value = '';
		}
	}).blur(function(){
		if (this.value == ''){
			this.value = '[enter city & state OR ZIP here]';
		}
	});
	
}

function initOffer(){
	if (/thank\-you/.test(document.location.href)) {
		if ($('#markers-zip').length > 0) {
			getCoords($('#markers-zip').val());
		}
		if ($('#zip').length > 0) {
			getCoords($('#zip').val());
		}
	}
	else {
		getNearby();
	}
	
}





function getNearby(lat, lng){
	/**
	 * 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 glat = typeof(lat)=='undefined' ? $('#map-lat').val() : lat;
	var glng = typeof(lng)=='undefined' ? $('#map-lng').val() : lng;
	var glimit = $('#map-limit').val();
	var gfilter = $('#map-filter').val();
	var gvalue = $('#map-value').val();
	var gexclude = $('#map-exclude_current').val();
	
	gxml = $('#gmaps a:hidden').attr('href')+'map-lat='+glat+'&map-lng='+glng+'&map-filter='+gfilter+'&map-limit='+glimit+'&map-value='+gvalue;
	
	
	$.get(gxml, function(response){
		gmgr.clearMarkers();
		$('#nearby, #select-hospitals').empty();
		$('#select-hospitals').append('<option value="">Select a Hospital</option>');
		var markers = [];
		var i = 1;
		var bounds = new GLatLngBounds();
		var blue = [];
		$('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")));
			var au = this.getAttribute("au_id");
			bounds.extend(point);
			if (gexclude && i == 1){
				var red = new GIcon(G_DEFAULT_ICON);
				red.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/red/blank.png";
				var marker = new GMarker(gcenter, { icon: red });
				gexclude = false;  
			}
			else {
				blue[i] = new GIcon(G_DEFAULT_ICON);
				blue[i].image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/marker"+i+".png";
		  	var marker = new GMarker(point, { icon: blue[i] });
				var html = '<li>'
					+ '<img src="'+blue[i].image+'" alt="marker" />'
					+ '<b>' + name + '</b>';
					if (!$('#gmaps').hasClass('map-layout0') && !$('#gmaps').hasClass('map-layout1')) {
						html += ' (' + Math.round(distance*10)/10 + ' miles)'
					}
					html += '<br />' + address;
				if (!$('#gmaps').hasClass('map-layout0')) {
			  	html += '<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>';
			  }
				$('#nearby').append(html);
				if ($('#select-hospitals').length > 0) {
					var stub = $('#vetsource-link').length > 0 ? this.getAttribute('vetsource') : url+'/appt/thank-you';
					var html = '<option value="'+stub+'">'+name+'</option>';
					$('#select-hospitals').append(html);
				}
				i++;
			}
	  	GEvent.addListener(marker, 'click', function(){
	  		marker.openInfoWindowHtml('<div class="mapinfo"><b>' + name + '</b><br/>' 
					+ address + '<br />'
					+ 'Phone: ' + phone + '<br />');
	  	});
			markers.push(marker);
		});
		gmgr.addMarkers(markers, 1);
		$('#select-hospitals').removeAttr('disabled');
		$('#loading').hide();
		gmgr.refresh();
		gmap.setCenter(bounds.getCenter(), gmap.getBoundsZoomLevel(bounds));
	});
}

function getCoords(zipcode){
	gcode.getLocations(zipcode, function(response){
		if (!response || response.Status.code != 200) {
			$('#map-zip').val('ZIP Code not found');
		}
		else {
			var place = response.Placemark[0];
			getNearby(place.Point.coordinates[1], place.Point.coordinates[0]);
		}
	});
}


/**
 * Maps and directions functions
 */
function initDirections(){
	initMaps();
	gdir = new GDirections(gmap, $('#directions').get(0));
	GEvent.addListener(gdir, 'load', setDirections);
	if (!getQueryValue('start')){
		var red = new GIcon(G_DEFAULT_ICON);
		red.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/red/blank.png";
		var gmarker = new GMarker(gcenter, { icon: red });
		gmap.addOverlay(gmarker);
		GEvent.addListener(gmarker, 'click', function(){
			gmarker.openInfoWindowHtml('<div class="mapinfo"><b>' + $('.vcard .org').text() + '</b><br/>' +
			$('.vcard .adr').text() +
			'<br />' +
			$('.vcard .tel:first').text());
		});
		$('#directions-form').submit(function(){
			getDirections($('#start').val());
			return false;
		});
	}
	else {
		$('#start').val(getQueryValue('start'));
		getDirections(getQueryValue('start'));
	}


	$('#form-send').submit(function(){
		sendDirections();
		return false;
	});
	
}

// event handler for directions form submit or querystring of start=[start address]
function getDirections(start){
	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());
		}
	});
}


// callback to display directions returned from google
// put in #directions
function setDirections(){
	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();

	$('#directions').show();
	$('#mail-ready').html(text);
}



function sendDirections(){
	$('.error-msg', $('.pop-content')).text('');
	var text = $('.vcard').text();	
	text += $('#custom-content').html()+'\n\n';
	text += 'Turn by Turn Directions\n';
	text += $('#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 initHiddenDirections(){
	initMaps();
	gdir = new GDirections(gmap, $('#gdir').get(0));
	GEvent.addListener(gdir, 'load', setHiddenDirections);
}

function getHiddenDirections(){
	//alert('getHidden');
	
	var start = (typeof($('#addr').val()) == 'undefined' ? '' : $('#addr').val() +' ');
	start += (typeof($('#city').val()) == 'undefined' ? '' : $('#city').val() +' ');
	start += (typeof($('#state').val()) == 'undefined' ? '' : $('#state').val() +' ');
	start += $('#zip').val();
	
	gcode.getLocations(start, function(response){
		if (!response || response.Status.code != 200) {
			// error with maps api, just submit form w/o directions
			mapped = true;
			$('#HOSPITAL-form, #HOSPITAL-CAMPAIGN-form').submit();
		} else {
			if (response.Status.code == 200) {
				gdir.load('from: ' + response.Placemark[0].address + ' to: ' + $('#hospital-addr').val());
			}
			else {
				// error getting start addr, just submit form w/o directions
				mapped = true;
				$('#HOSPITAL-form, #HOSPITAL-CAMPAIGN-form').submit();
			}
		}
	});
}

function setHiddenDirections(){
	//alert(gdir.getStatus().code);
	if (gdir.getStatus().code == 200) {
  	var text = '';
  	var route = gdir.getRoute(0);
		var start = (typeof($('#addr').val()) == 'undefined' ? '' : $('#addr').val() +' ');
		start += (typeof($('#city').val()) == 'undefined' ? '' : $('#city').val() +' ');
		start += (typeof($('#state').val()) == 'undefined' ? '' : $('#state').val() +' ');
		start += $('#zip').val();
	
  	text += 'Start: ' + start + '<br />\r\n<br />\r\n';
  	for (i = 0, j = route.getNumSteps(); i < j; i++) {
  		step = route.getStep(i);
  		text += (i + 1) + '  ';
  		text += step.getDescriptionHtml();
  		text += ' (' + step.getDistance().html + ')' + '<br />\r\n';
  	}
  	text += '<br />\r\n' + 'End: ' + $('#hospital-addr').val() + '<br />\r\n';
  	text += route.getSummaryHtml() + '<br />\r\n';
  	$('#directions').val(text);
		mapped = true;
		$('#HOSPITAL-form, #HOSPITAL-CAMPAIGN-form').submit();
  }
	else {
		// error getting directions, just submit form w/o directions
		mapped = true;
		$('#HOSPITAL-form, #HOSPITAL-CAMPAIGN-form').submit();
	}
}


// google maps unload event handler
$(window).unload(function(){
	GUnload();
});


