var scrollingInterval = null;
function scrollToTop() {
	if (document.body.scrollTop>110 || document.documentElement.scrollTop>110) 
		window.scrollBy(0,-30);
	else
		window.clearInterval(scrollingInterval);
}

(function($) {
	var practices;		// Object with Practice data
	var practiceDivs;
	var markers;
	var map;
	var detailsDiv;
	var maskDiv;
	var directions;
	var current;
	var physicians;
	var pageTitle;
	var directionsInputDefault = 'from this address';
	
	function setupMap() {
		map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(41.58668835697237, -86.21246337890625), 9);
        map.addControl(new GSmallMapControl);
        map.addControl(new GMapTypeControl);
		directions = new GDirections(map);
		GEvent.addListener(directions,"error", function() { $('#directions-steps').html('<p>We\'re sorry.  There has been an error with your request. Please try again.</p>'); });
		GEvent.addListener(directions,"load", function() {
			setTimeout(onLoadDirections, 1);
		});
	}	  
	
	function loadLocations(data) {
		practices = data.practices;
		markers = new Array();
		map.clearOverlays();
		var k = 0;
		$(practices).each(function(i,p) {
			$(p.locations).each(function(j,l) {
				l.marker = createMarker(l,k,p.name);
				l.markerIndex = k;
				markers.push(l.marker);
				k++;
			});
		});
	}
	
	function createMarker(info, index, practice) {
		var point = new GLatLng(info.lat, info.lng);
		var baseIcon = new GIcon;
        baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        baseIcon.iconSize = new GSize(20, 34);
        baseIcon.shadowSize = new GSize(37, 34);
       	baseIcon.iconAnchor = new GPoint(9, 34);
        baseIcon.infoWindowAnchor = new GPoint(9, 2);
        baseIcon.infoShadowAnchor = new GPoint(18, 25);

		if (index>=26) index = index-26;
		var letter = String.fromCharCode("A".charCodeAt(0) + index);
		var letteredIcon = new GIcon(baseIcon);
		letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
		markerOptions = { icon: letteredIcon };
		
		$(practiceDivs[index]).css({ position:'relative' }).animate({ marginLeft:'30px' }, 400, function() {
			$('<img src="'+letteredIcon.image+'" alt="'+info.office+'" />').prependTo(this).hide().css({ position:'absolute', left:'-30px', top:0 }).fadeIn();
		}).css({ cursor:'pointer', display:'block' }).click(function() { map.panTo(marker.getLatLng()); });
		
		var windowHtml = '<strong>'+practice+'</strong><br />'+info.office+'<br />'+info.address_1+'<br />'+(info.address_2.length ? info.address_2+'<br />' : '')+info.city+', '+info.state+' '+info.zip;		
		var marker = new GMarker(point, markerOptions);
		
		if(!info.lat || !info.lng) {
			var geo = new GClientGeocoder();
			var a = info.address_1+', '+info.address_2+', '+info.city+', '+info.state+', '+info.zip;
		
			geo.getLatLng(a, function(p) {
				if(p!=null) {
					marker.setPoint(p);
					GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(windowHtml); });
					map.addOverlay(marker);
				} 
			});
		} else {
			marker.setPoint(point);
			GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(windowHtml); });
			map.addOverlay(marker);
		}
		return marker;
	}
	
	function setupMenu() {
		directions = new GDirections(map);
		GEvent.addListener(directions,"error", function() { alert('error'); });
		GEvent.addListener(directions,"load", function() {
			var fun = function() { onLoadDirections(); };
			setTimeout(fun, 1);
		});
		
		var html = 	'<form>';
		html +=		'	<fieldset>';
		html +=		'		<h4>Get Directions</h4>';
		html +=		'		<input id="mapFrom" type="text" class="text" value="'+directionsInputDefault+'" /><br />';
		html +=		'		<select id="mapTo"></select>';
		html +=		'	</fieldset>';
		html +=		'</form>';
		html += 	'<div id="directions-steps"></div>';
		
		var rightDiv = $('<div id="mapParent"></div>').appendTo('#body');
		$('#map').appendTo(rightDiv).css({ position:'absolute', top:0, left:0, zIndex:2 });
		$('<div id="directions">'+html+'</div>').appendTo(rightDiv).css({ position:'absolute', top:0, left:0, width:350, zIndex:1 }).find('form').submit(getDirections).end().find('select').change(getDirections)
		if ($.browser.msie && $.browser.version == '6.0') $('#directions select').hide();
		handleDirectionsInput();
		
		maskDiv = $('<div id="locationsMask"></div>').appendTo('#body').css({ height:$('#locations').height()+10 })
		animateDiv = $('<div id="locationsParent"></div>').appendTo(maskDiv);
		$('#locations').appendTo(animateDiv);
		detailsDiv = $('<div id="locations-description"></div>').appendTo(animateDiv);
	}
	
	function handleDirectionsInput() {
		$('#directions input').focus(function() { if(this.value == directionsInputDefault) this.value = ''; }).blur(function() { if(!this.value) this.value = directionsInputDefault; });
	}
	
	function getDirections() {
		directions.load("from: "+$('#mapFrom').attr('value')+" to: "+$('#mapTo').val(), { getSteps:true });
		return false;	
	}
	
	function onLoadDirections() {
		pageTracker._trackPageview('/locations/'+current.url+'/directions');
		
		$(markers).each(function(i,m) {
			m.hide();						 
		});
		var html = '';
		for (var i=0; i<directions.getNumRoutes(); i++) {
			var route = directions.getRoute(i);
			var geocode = route.getStartGeocode();
			var point = route.getStep(0).getLatLng();

			html += routeDistance(route.getDistance().html+" (about "+route.getDuration().html+")");
			html += waypoint(point, geocode.address);
		
			html += '<table id="steps"><tbody>';
			for (var j=0; j<route.getNumSteps(); j++) {
				var step = route.getStep(j);
				html += detail(step.getLatLng(), j+1, step.getDescriptionHtml(), step.getDistance().html, j%2)
			}
			html += '</tbody></table>';
			html += topoint(route.getStep(j-1).getLatLng(), geocode.address);			
		}
		$('#directions-steps').slideUp(200, function() { $(this).html(html).slideDown(); })
	}
	
	function waypoint(point, address) {
		var target = '"'+"globalMap.showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))" +'"';
		var h = '<table id="origin"><tr onclick="'+target+'">';
		h += '		<td>';
		h += ' 			<img src="http://maps.google.com/intl/en_us/mapfiles/marker_greenA.png">'
		h += '		</td>';
		h += ' 		<td style="vertical-align: middle; width: 100%;">';
		h += '			<strong>'+address+'</strong>';
		h += ' 		</td>';
		h += ' 	</tr></table>';
		return h;
	}
	
	function routeDistance(dist) {
		var h = '<div id="route-distance">Distance: ' + dist + '</div>';
		return h;
	}
	
	function detail(point, num, description, dist, oddRow) {
		var target = '"'+"globalMap.showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))" +'"';
		var h = '<tr '+(oddRow ? '' : 'class="even" ')+'onclick='+target+'>';
		h += '		<td>'+num+'</td>';
		h += '		<td>'+description+'</td>';
		h += '		<td>'+dist+'</td>';
		h += '	</tr>';
		return h;
	}
	
	function topoint(point) {
		var target = '"'+"globalMap.showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))" +'"';
		var h = '	<table id="destination"><tr onclick='+target+'>';
		h += '			<td>';
		h += ' 				<img src="http://maps.google.com/intl/en_us/mapfiles/marker_greenB.png">'
		h += '			</td>';
		h += ' 			<td style="vertical-align:top; width: 100%;">';
		var loc = current.locations[$('#mapTo').attr('selectedIndex')];
		h += 			'<strong>'+current.name+'</strong><br />'+loc.address_1+'<br />'+(loc.address_2 ? loc.address_2+'<br />' : '')+loc.city+', '+loc.state+' '+loc.zip;
		h += ' 			</td>';
		h += ' 		</tr></table>';
		return h;
	}
	
	function hackDetails() {
		$('.practice a').each(function() { $(this).text($(this).text()+' and Directions'); }).click(function() { 
			scrollingInterval=window.setInterval("scrollToTop()",2);
			var found = false;
			var url = this.href.substr(this.href.lastIndexOf('/')+1);
			$(practices).each(function(i,p) {
				if(!found && p.url == url) { found = true; current = p; }
			});
			$(animateDiv).animate({ left:-310 });
			$('#directions').each(function() {
				var html = '';
				$(current.locations).each(function(i,l) {
					var add = (l.lat && l.lng ? l.lat+','+l.lng : l.address_1+', '+l.address_2+', '+l.city+', '+l.state+', '+l.zip);
					html += '<option value="'+add+'">'+l.office+'</option>';								   
				});
				$(this).find('select').find('option').remove().end().html(html);
				$(detailsDiv).html(getPracticeDetails()).find('a:last').click(backToList);
				if($(detailsDiv).height()+50>$(maskDiv).height()) $(maskDiv).animate({ height:$(detailsDiv).height()+50 });
				if(current.locations.length>1 && (!$.browser.msie || $.browser.version != '6.0')) $('#mapTo').show();	
				else $('#mapTo').hide();
			}).animate({ top:400 }, function () { if($.browser.msie && $.browser.version == '6.0') $('#mapTo').show(); });
			return false; 
		});
	}
	
	function getPracticeDetails() {
		$(markers).each(function(i,m) {
			m.hide();						 
		});
		document.title = current.name.replace(/&amp;/g, '&')+' | '+pageTitle;
		pageTracker._trackPageview('/locations/'+current.url);
		
		var html =	'<h4>'+current.name+'</h4>';
		html +=		(current.description ? current.description : '');
		html +=  	'<div class="practice">';
		$(current.locations).each(function(i,l) {
			markers[l.markerIndex].show();
			html += '	<p class="location" style="position: relative; margin-left: 30px; cursor: pointer; display: block;">';
			html += '	<img src="http://www.google.com/mapfiles/marker'+String.fromCharCode("A".charCodeAt(0)+l.markerIndex)+'.png" alt="'+l.office+'" style="display: inline; position: absolute; left: -30px; top: 0pt;" />';
			html +=	'		<strong>'+l.office+'</strong><br />';
			html +=			l.address_1+'<br />'+(l.address_2 ? l.address_2+'<br />' : '')+l.city+', '+l.state+' '+l.zip+(l.web ? '<br /><a href="http://'+l.web+'">'+l.web+'</a>' : '');
			html +=			l.phone ? '<br />'+l.phone : '';
			html +=			(l.relay_phone ? '<br /><a href="https://www.i711.com/i711v2/ctc.html?refid=but.1.0&phone='+l.relay_phone+'" onClick="window.open(this, \'callwindow\', \'width=750, height=450, scrollbars=no\'); return false;"><img class="relay-button" src="/images/text-relay-button.jpg" border="0" /></a>' : '');
			html +=	'	</p>';
		});
		html += '</div>';
		html +=		(current.web ? '<p>Website: <a href="http://'+current.web+'" target="_blank">'+current.web+'</a></p>' : '');
				
		var docs = '';
		$(physicians).each(function(i,p) {
			var found = false;
			$(p.locations).each(function(j,l) {
				if(!found && l.practice==current.id) {
					docs += '<a href="/physicians/'+p.url+'">'+p.first_name+' '+(p.middle_initial ? p.middle_initial+'. ' : '')+p.last_name+(p.name_suffix ? ', '+p.name_suffix : '')+'</a><br />';
					found = true;
				}
			});
		});
		var files = ''
		$(current.files).each(function(i,f) {
			files += '<a class="file" href="/files/'+f.file+'" target="_blank">'+f.name+'</a><br />';
		});
		if(docs || files) {
			html +=		'<div class="locations-doctors">';	
			if(docs) html += '<h3>Physicians</h3><p>'+docs+'</p>';
			if(files) html += '<h3>Files</h3><p>'+files+'</p>';
			html +=		'</div>';
		}
		html +=		'<p><a href="#">&lt; Back to Locations</a></p>'
		return html;
	}
	
	function backToList() {
		document.title = pageTitle;
		pageTracker._trackPageview('/locations/');
		
		directions.clear();
		map.returnToSavedPosition();
		$(markers).each(function(i,m) {
			m.show();						 
		});
		$(animateDiv).animate({ left:30 }, 400, function() { $('#locations-description').html(''); });
		$('#directions-steps').slideUp('normal', function() { 
			if($.browser.msie && $.browser.version == '6.0') $('#mapTo').hide();
			$('#directions').animate({ top:0 }); 
		});
		return false;	
	}
	
	function getPageTitle() {
		var t = document.title;
		t = t.split(' | ');
		pageTitle = t[t.length-2]+' | '+t[t.length-1];
	}
		  
	$(document).ready(function() {
		getPageTitle();
		practiceDivs = $('.location');
		setupMenu();
		hackDetails();
		setupMap();
		$.getJSON('ajax-data.php', { action:'practices' }, loadLocations);
		$.getJSON('ajax-data.php', { action:'physicians' }, function(data) { physicians = data.physicians; });
	});
})(jQuery);
