var locations = new Array();
var homeAddress = '';
var homePoint, map, geocoder;
var lowLat, lowLng, hiLat, hiLng;
var markers = new Array();
var letterNum = 0;
var pageAddress = '';
var jsonRequest;
var newsTickNum = 0;

function createMap(mapDivId) {
    map = new GMap2($(mapDivId));
    map.setMapType(G_NORMAL_MAP);
    map.addMapType(G_SATELLITE_MAP);
    map.addControl(new GLargeMapControl3D());
    map.addControl(new GMapTypeControl());
    geocoder = new GClientGeocoder();
    if (homeAddress == '') {
        map.setCenter(new GLatLng(39.8, -98.5), 3);
    }
}

function cleanMap() {
    lowLat = '';
    lowLng = '';
    hiLat = '';
    hiLng = '';
    map.clearOverlays();
}

function resetZoom() {
	if (homePoint) {
  	sw = new GLatLng(lowLat, lowLng);
		ne = new GLatLng(hiLat, hiLng);
		var bound = new GLatLngBounds(sw, ne);
		var zoom = map.getBoundsZoomLevel(bound);
		map.setCenter(homePoint, zoom-1);
  }
	else
	{
		sw = new GLatLng(lowLat, lowLng);
		ne = new GLatLng(hiLat, hiLng);
		var bound = new GLatLngBounds(sw, ne);
		var zoom = map.getBoundsZoomLevel(bound);
		map.setCenter(new GLatLng((lowLat+hiLat)/2, (lowLng+hiLng)/2), zoom-1);
	}
}

function createHome() {
	if (homePoint) {
		makeMarker({ 'lat': homePoint.lat(), 'lng': homePoint.lng(), 'address': homeAddress, 'type': 'home' });
		map.setCenter(homePoint);
	}
}

function makeMarker(info) {
	if (info) {
		var thepoint = false;
		if ((info.lat != null) && (info.lng != null) && (info.lat != 0) && (info.lng != 0)) {
			thepoint = new GLatLng(info.lat, info.lng);
		}
		var runMark = function() {
			if (thepoint) {
				if (lowLat == '') {
			    lowLat = thepoint.lat();
			    hiLat = thepoint.lat();
			    lowLng = thepoint.lng();
			    hiLng = thepoint.lng();
				}
				else {
			    if (thepoint.lat() < lowLat) {
			        lowLat = thepoint.lat().toFloat();
			    }
			    else {
			        hiLat = thepoint.lat().toFloat();
			    }
			    if (thepoint.lng() < lowLng) {
			        lowLng = thepoint.lng().toFloat();
			    }
			    else {
			        hiLng = thepoint.lng().toFloat();
			    }
				}
				var thisIcon = new GIcon(G_DEFAULT_ICON);
				//var thisAddress = info.address + ' ' + info.city + ' ' + info.state + ' ' + info.zip;
				var iconLocation;
				var inList = true;
				switch (info.type) {
			    case 'home':
			    	inList = false;
			    	break;
			
			    default:
		        var letter = String.fromCharCode("A".charCodeAt(0) + letterNum);
		        thisIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
		        letterNum++;
				}
				var markerOptions = { icon: thisIcon };
				var marker = new GMarker(thepoint, markerOptions);
			}
			
			myLoc = new Element('div', {
				'class': 'location'
			});
			var myHTML = '<div class="info">';
			if(info.website != '')
			{
				myHTML+= '<a href="'+info.website+'">'+info.title+'</a><br/>';
			}
			else
			{
				myHTML+= info.title+'<br/>';
			}
			if(info.address != '')
			{
				myHTML+= info.address+'<br/>';
			}
			myHTML+= info.phone;
			if(info.distance != '')
			{
				myHTML+= '<div class="distance">'+info.distance+'</div>';
			}
			myHTML+= '</div>';
			myLoc.set('html', myHTML);
			if(inList)
			{
				myLoc.inject($('locations'));
			}
			
			if((info.lat != 0) && (info.lng != 0))
			{
				var myLat = new Element('span', {
					'class':'lat',
					'styles':{
						'display':'none'
					},
					'text':info.lat
				});
				var myLng = new Element('span', {
					'class':'lng',
					'styles':{
						'display':'none'
					},
					'text':info.lng
				});
				var myIcon = new Element('img', {
					'src':thisIcon.image,
					'class':'icon'
				});
				if(inList)
				{
					myLat.inject(myLoc);
					myLng.inject(myLoc);
					myIcon.inject(myLoc, 'top');
					myIcon.addEvent('click', function(){
						map.openInfoWindowHtml(new GLatLng(this.getParent().getElement('.lat').get('text'), this.getParent().getElement('.lng').get('text')), myHTML);
					});
					GEvent.addListener(marker, "click", function() { map.openInfoWindowHtml(thepoint, myHTML); });
				}
				
				map.addOverlay(marker);
			}
		}
		runMark.run();
	}
}

function makeMarkers() {
	cleanMap();
	letterNum = 0;
	$('locations').empty();
	locations.each(function(loc){
		makeMarker(loc);
	});
	if(homePoint)
	{
		createHome(homePoint);
	}
	resetZoom();
}

jsonRequest = new Request.JSON({url: "./search.php", onComplete: function(results){
  if(results)
  {
  	if(results.address)
  	{
  		pageAddress = results.address;
  	}
  	if(results.lat && results.lng)
  	{
  		homePoint = new GLatLng(results.lat, results.lng);
  	}
  	else {
  		homePoint = false;
    }
  	if(results.locations)
  	{
  		locations = results.locations;
  		makeMarkers();
  	}
  	if(results.pages)
  	{
  		if($('pages'))
  		{
  			$('pages').set('html', results.pages);
  			$('pages').getElements('a').each(function(page_link){
  				page_link.addEvent('click', function(e){
  					e.stop();
  					jsonRequest.post({'address': pageAddress, 'page':page_link.get('text')});
  				});
  			});
  		}
  	}
  }
}});


window.addEvent('domready', function() {

if($('no_javascript'))
{
	$('no_javascript').getElements('.location').each(function(loc){
		var myLoc = new Object();
		myLoc.title = loc.getElement('.title').get('text');
		myLoc.address = '';
		if(loc.getElement('.address'))
		{
			myLoc.address = loc.getElement('.address').get('text');
		}
		myLoc.website = '';
		if(loc.getElement('.website'))
		{
			myLoc.website = loc.getElement('.website').get('text');
		}
		myLoc.distance = '';
		if(loc.getElement('.distance'))
		{
			myLoc.distance = loc.getElement('.distance').get('text');
		}
		myLoc.phone = loc.getElement('.phone').get('text');
		myLoc.lat = loc.getElement('.lat').get('text');
		myLoc.lng = loc.getElement('.lng').get('text');
		
		locations.push(myLoc);
	});
	
	var myPages = false;
	
	if($('pages'))
	{
		myPages = $('pages').clone(true, true);
	}
	
	$('no_javascript').dispose();
	
	var myMap = new Element('div', {
		'id': 'map'
	});
	var myLocs = new Element('div', {
		'id': 'locations'
	});
	var mySide = new Element('div', {
		'id':'sidebar'
	});
	var mySearch = new Element('form', {
		'id':'search',
		'action':'./',
		'method':'post',
		'html':'Find your nearest service location:<br/>'
	});
	var myField = new Element('input', {
		'type':'text',
		'name':'address',
		'id':'address'
	});
	var myLatLng = new Element('input', {
		'type':'hidden',
		'name':'latlng',
		'id':'latlng'
	});
	var myButton = new Element('input', {
		'type':'submit',
		'value':'go'
	});
	
	myField.inject(mySearch);
	myButton.inject(mySearch);

	mySide.inject($('page'));
	mySearch.inject(mySide);
	myLocs.inject(mySide);
	
	myLocs.setStyle('height', myLocs.getStyle('height').toInt()-mySearch.getStyle('height').toInt()-10);
	myField.setStyle('width', mySearch.getStyle('width').toInt()-20-myButton.getStyle('width').toInt());
	
	mySearch.addEvent('submit', function(e){
		e.stop();
		jsonRequest.post({'address': $('address').get('value')});
	});
	
	if(myPages)
	{
		myLocs.setStyle('height', myLocs.getStyle('height').toInt()-25);
		myPages.inject(mySide);
		myPages.getElements('a').each(function(page_link){
			page_link.addEvent('click', function(e){
				e.stop();
				jsonRequest.post({'address': pageAddress, 'page':page_link.get('text')});
			});
		});
	}
	myMap.inject($('page'));
	(new Element('div', {'class':'clear'})).inject($('page'));
	$('page').setStyles({
		'border':'2px solid #ddd'
	});
	
	createMap('map');
	makeMarkers();
}

if($('nav'))
{
	$(document.body).getElements('area').each(function(myArea){
		myArea.addEvent('mouseenter', function() {
			$('nav').className = this.get('name');
		});
		myArea.addEvent('mouseleave', function() {
			$('nav').className = myPage;
		});
	});
}

if($(document.body).getElements('.news_tick').length > 0)
{
	$(document.body).getElements('.news_tick').each(function(newsTick){
		newsTick.setStyle('opacity', '0');
		newsTick.setStyle('display', 'none');
	});
	
	var myFirst = $(document.body).getElements('.news_tick')[newsTickNum];
	myFirst.setStyle('opacity', '1');
	myFirst.setStyle('display', 'inline');
	
	var newsTicker = function()
	{
		lastTick = newsTickNum;
		newsTickNum = (newsTickNum+1);
		if(newsTickNum >= $(document.body).getElements('.news_tick').length)
		{
			newsTickNum = 0;
		}
		var myFx1 = new Fx.Tween($(document.body).getElements('.news_tick')[lastTick], {'duration':1000});
		var myFx2 = new Fx.Tween($(document.body).getElements('.news_tick')[newsTickNum], {'duration':1000});
		
		myFx1.start('opacity', '0').chain(
			function () {
				myFx1.set('display', 'none');
				myFx2.set('display', 'inline');
				myFx2.start('opacity', '1');
				newsTicker.delay(5000);
			}
		);
	}
	
	newsTicker.delay(5000);
}
	
});