var locations = {};
var hzipHash = '';
var wzipHash = '';
var zoomlevel = 8;
var zoomway = '';
var clocHash = [];
var gmap;
var mediaserver = 'http://media1.biola.edu/bold/';

function initFindSite() {
	$('#siteListing').replaceWith('<div id="siteFinder"><h2>Find Your Site</h2><p class="lead">To find the Bold location most convenient for you, please enter your home or work (or both) zip code.</p><form id="siteFinderForm"><p><label>Home ZIP</label><input type="text" name="homezip" /></p><p><label>Work ZIP</label><input type="text" name="workzip" /></p><p><button id="zipfind">Find It</button></p></form></div>')
	
	$('form#siteFinderForm #zipfind').click(function() {
		var homezip = $('form#siteFinderForm input[name="homezip"]').attr('value');
		var workzip = $('form#siteFinderForm input[name="workzip"]').attr('value');
		$('div#siteFinder p.lead').remove();
		if (!$('div#gmap').length) {
			mapcode = '<div id="beforemap"><p id="mapnav" class="nav"></p><p id="mapinfo">&nbsp;</p></div><div id="gmap"></div><div id="aftermap"><p class="info">Click on your preferred site.</p></div>';
			$('form#siteFinderForm').after(mapcode);
			loadMap();
		}
		loadBoldLocations(gmap, homezip, workzip);
		// reload zoom 		
		wZ = setInterval('waitZips();', 10);			
		return false;
	});			
}

function loadMap() {
  gmap = new GMap2(document.getElementById("gmap"));
  gmap.disableDragging();
  gmap.disableDoubleClickZoom();
  gmap.disablePinchToZoom();
  gmap.setCenter(new GLatLng(33.709357, -118.030068), zoomlevel);
  // return map;
}

function loadBoldLocations(map, hzip, wzip) {
  locations = {};
  hzipHash = '';
  wzipHash = '';
  clocHash = [];
  map.clearOverlays();
  GDownloadUrl("/bold/xml/boldlocation.xml", function(data) {
    var xml = GXml.parse(data);
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
      var name = markers[i].getAttribute("name");
      var address = markers[i].getAttribute("address");
      var latlng = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                              parseFloat(markers[i].getAttribute("lng")));
      var image = markers[i].getAttribute("image");
      var iSize = new GSize(markers[i].getAttribute("iw"), markers[i].getAttribute("ih"));
      var iAnchor = new GPoint(markers[i].getAttribute("ix"), markers[i].getAttribute("iy"));
      var slug = markers[i].getAttribute("slug") 
      var amap = new Array();
      var amap = markers[i].getAttribute("amap").split(',');
      for (nu in amap)
			amap[nu] = parseInt(amap[nu]);
      if (markers[i].getAttribute("zidx"))
	      zidx = parseInt(markers[i].getAttribute("zidx"));
	  else
	      zidx = '';
	  insertLocations(latlng, name, address, 'reg', image, iSize, iAnchor, amap, zidx, slug);
    }
    // geocode zips
    if (hzip) locationFromZip(hzip, 'Home'); else hzipHash = 'invalid';
	if (wzip) locationFromZip(wzip, 'Work'); else wzipHash = 'invalid';
   
  });  
}

function waitZips() {
	if ((hzipHash != '') && (wzipHash != '')) {
		processLocations(gmap);
		reloadZoom();
	}		
}

function reloadZoom() {
	$('#gmap').css('margin-top','-22px');
	var mapcode = 'Zoom: ';
	if (hzipHash != 'invalid')
		mapcode += '<a href="#" onclick="return navMap(gmap, \'home\');">To Home</a> | ';
	if (wzipHash != 'invalid')
		mapcode += '<a href="#" onclick="return navMap(gmap, \'work\');">To Work</a> | ';
	mapcode += '<a href="#" onclick="return navMap(gmap, \'out\');">Out</a>';
	if ((hzipHash != 'invalid')||(wzipHash != 'invalid')) {
		$('p#mapnav').html(mapcode);
		$('#gmap').css('margin-top','0px');
	}
	zoomlevel = 8;
  	gmap.disableDragging();
  	gmap.disableDoubleClickZoom();
  	gmap.disablePinchToZoom();
  	gmap.setCenter(new GLatLng(33.709357, -118.030068), zoomlevel);	
}

function processLocations(map) {
	clearInterval(wZ);

   // find closet locations
    if (hzipHash != 'invalid') {
 		findClosetBold(hzipHash);
    	findClosetBold(hzipHash);
	}

    resetLocationRet();

    if (wzipHash != 'invalid') {
		findClosetBold(wzipHash);    
		findClosetBold(wzipHash);    
    }
	
	if ((hzipHash!='invalid')||(wzipHash!='invalid')) {
		if (clocHash.length == 0) 
			$('p#mapinfo').removeClass('rec').text('You are more than 50 miles away.');
		else {	
			$('p#mapinfo').addClass('rec').text('= Recommended Site.');
			locations[clocHash[0].hash][0].type = 'rec';
			if (clocHash[1].hash == clocHash[0].hash)
				locations[clocHash[2].hash][0].type = 'rec';
			else
				locations[clocHash[1].hash][0].type = 'rec';					
		}
	}

    // overlay pointer 
    for (var latlngHash in locations) {
      var stores = locations[latlngHash];
      map.addOverlay(createMarker(stores));
     }	
}

function findClosetBold(zipHash) {
	// find the closet bold and mark the location green.
	var target = zipHash;
	var distance = 80467; // 50 miles	
	var tempHash = ''
	for (var latlngHash in locations) {
		var store = locations[latlngHash][0];
		if (store.type == 'reg') {
			var tempd = store.latlng.distanceFrom(locations[target][0].latlng);
			if (tempd < distance) {
				distance = tempd;
				tempHash = latlngHash;
			}			
		}		
	}
	if (tempHash != '') {
		pushCloseLoc(tempHash, distance);
		locations[tempHash][0].type = 'rep';
	}
}

function resetLocationRet() {
	for (loc in locations) {
		if (locations[loc][0].type == 'rep')
			locations[loc][0].type = 'reg';
	}
}

function pushCloseLoc(hash, distance) {
	var inserted = false;
	var locloc = {hash:　hash, distance: distance};
	if (clocHash.length == 0) {
		clocHash.push(locloc);
	} else {		
		for (cloc in clocHash) {
			if ((!inserted)&&(clocHash[cloc].distance > distance)) {
				clocHash.splice(cloc, 0, locloc);
				inserted = true;
			}
		}
		if ((!inserted)&&(clocHash.length == 1)) clocHash.push(locloc);
	}
}

function locationFromZip(zip, hw) {
  var geocoder = new GClientGeocoder();
  geocoder.getLatLng(
	zip, function(point) {
		if (point) {
			if (hw == 'Home')
				hzipHash = locationHash(point);
			else
				wzipHash = locationHash(point);			
			insertLocations(point, hw, '', 'user', 'home', new GSize(26,31), new GPoint(7, 31), new Array(),'', '');			
		} else {
			if (hw == 'Home')
				hzipHash = 'invalid';
			else
				wzipHash = 'invalid';		
		}		  			
	}
  );
}

function insertLocations(latlng, name, address, type, image, iSize, iAnchor, amap, zidx, slug) {
    var store = {latlng: latlng, name: name, address: address, type: type, image: image, iSize: iSize, iAnchor: iAnchor, amap: amap, zidx: zidx, slug: slug};
    var latlngHash = locationHash(latlng);
	if (locations[latlngHash] == null) {
      locations[latlngHash] = []
    }
    locations[latlngHash].push(store);
}

function locationHash(latlng) {
    var latlngHash = (latlng.lat().toFixed(6) + "" + latlng.lng().toFixed(6));
    latlngHash = latlngHash.replace(".","").replace(".", "").replace("-","");
	return latlngHash;
}



function createMarker(stores) {
  var store = stores[0]; 
  //var newIcon = MapIconMaker.createMarkerIcon({width: 32, height: 32, primaryColor: store.color});
  var newIcon = new GIcon();
  if (store.type == 'rec')
  	newIcon.image = mediaserver+'images/markers/' + store.image + '_s.png';
  else
	newIcon.image = mediaserver+'images/markers/' + store.image + '.png';
  newIcon.iconSize = store.iSize;
  if (store.amap.length > 0) {
　　	newIcon.transparent = mediaserver+'images/markers/' + store.image + '_t.png';
  	newIcon.imageMap = store.amap;
  }
  newIcon.iconAnchor = store.iAnchor;
  var marker; 
  if (store.zidx != '') {
  	 marker = new GMarker(store.latlng, {icon: newIcon, zIndexProcess: function() { return store.zidx; }});
  } else if (store.type == 'user')
     marker = new GMarker(store.latlng, {icon: newIcon, clickable: false});
  else
	 marker = new GMarker(store.latlng, {icon: newIcon}); 
  GEvent.addListener(marker, 'click', function() {
	 //window.location='/bold/?ys='+ store.slug;
	var d = new Date();
    $('#gmap').append('<div class="screen">&nbsp;</div><div class="loading">&nbsp;</div>');
  	 $('#yoursite').load('/bold/?r='+ d.getTime() +'&ys='+store.slug, function() {
		$('#gmap div.screen').remove();
		$('#gmap div.loading').remove();		
		$('#siteFinder').hide();
		$('#yoursite').show();
		accordionOpen('#yoursite');
		$('#yoursite h2').click(function() {
			accordionOpen($(this).parent());
		});		
     });
  });    
  return marker;
}

function navMap(map, action) {
	switch(action) {
		case 'out':
		    if (zoomlevel > 9) {
				map.zoomOut(new GLatLng(33.709357, -118.030068), true);
			} else {
				map.setZoom(8);
				map.panTo(new GLatLng(33.709357, -118.030068));
			}
			break;
		case 'home':
			if ((hzipHash != 'invalid') && (zoomlevel < 15)) {
				if (zoomway != 'home') {
					map.setZoom(8);
					map.panTo(new GLatLng(33.709357, -118.030068));
				}
				map.zoomIn(locations[hzipHash][0].latlng, true, true);
				zoomway = 'home';
			}
			break;
		case 'work':
			if ((wzipHash != 'invalid') && (zoomlevel < 15)) {
				if (zoomway != 'work') {
					map.setZoom(8);
					map.panTo(new GLatLng(33.709357, -118.030068));
				}				
				map.zoomIn(locations[wzipHash][0].latlng, true, true);
				zoomway = 'work';
			}
			break;
	}
	zoomlevel = map.getZoom();
	if (zoomlevel == 8)
		map.disableDragging();
	else
  		map.enableDragging();
	return false;
}

