var lastAddress = null;
var geocoder = null;
var mgr = null;
var addressMarker = null;
var addressPosn = null;
var bounds = null;
var locsDiv = null;
var dirElement = null;
var gdir = null;
var officeMarkers = [];
var searchFieldTxt = "Enter your location...";
var plusRegEx = /\++/g;
var defaultCenter = new GLatLng(36, -120);
var defaultZoom = 6;


function WAFFormOnLoad() {		
	if (GBrowserIsCompatible()) {
		initAISIcon();
		initMap();		
		//listAllOffices();			
		
		geocoder = new GClientGeocoder();
		
		dirElement = document.getElementById("route");
		gdir = new GDirections(map, dirElement);
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
		GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay);
		GEvent.addListener(gdir, "error", handleErrors);
		map.setCenter(defaultCenter, defaultZoom);
		//GEvent.addListener(map, "moveend",showMoveOffices());
		if (urlParams["adr"] != null) {
			setAddress(unescape(urlParams["adr"]).replace(plusRegEx,' '));
			if (urlParams["showall"] == 1) {
				showAddress(address,defaultZoom);
			} else {
				showAddress(address);	
			}			
		}
		window.setTimeout(setupOfficeMarkers, 0);
		new Accordian('locations',1,'header_highlight');
	}
}

function showAddress(addr,zoom) {
	if (addr != "" && addr != searchFieldTxt) {
		address = addr;
		if (geocoder) {
			geocoder.getLatLng(
				address,
				function(point) {
					if (!point) {
						alert(address + " not found");
					} else {
						gdir.clear();
						map.closeInfoWindow();
						if (lastAddress != null) {
							map.removeOverlay(lastAddress);
						}
						expandcontent(document.getElementById("aLocations"));
						document.getElementById("liRoute").style.display="none";
						document.getElementById("aRoute").style.display="none";
						document.getElementById("sRoute").style.display="inline";
						
						addressIcon = new GIcon();
						addressIcon.image = "http://www.google.com/intl/en_us/mapfiles/arrow.png";
						addressIcon.shadow = "http://www.google.com/intl/en_us/mapfiles/arrowshadow.png"
						addressIcon.iconSize = new GSize(39,34);
						addressIcon.shadowSize = new GSize(39,34);
						addressIcon.iconAnchor = new GPoint(19, 34); 
												
						addressPosn = point;
						addressMarker = new GMarker(point,addressIcon);
						lastAddress = addressMarker;
						//map.addOverlay(trafficInfo);
						bounds = new GLatLngBounds();
						bounds.extend(point);
						if (zoom != '' && zoom != undefined) {
							listNearOffices(false,zoom);
						} else {
							listNearOffices(true);	
						}						
						map.addOverlay(addressMarker);						
					}
				}
			);				
		}
	}
}

function setupOfficeMarkers() {
	mgr = new GMarkerManager(map);  
	for (var ol in officeLayer) {
		var olayer = officeLayer[ol];
		for (var j in olayer["places"]) {
			var place = olayer["places"][j];
			var officePosn = new GLatLng(place["posn"][0], place["posn"][1]);
			//var officeAddress = place["address"];				
			var officeStreet = place["street"];
			var officeName = place["name"];
			var officeCityStateZip = place["citystatezip"];	
			var officeMarker = createMarker(officePosn,officeStreet,officeCityStateZip,officeName);			
			officeMarkers.push(officeMarker);
		}
		mgr.addMarkers(officeMarkers, olayer["zoom"][0], olayer["zoom"][1]);
	}
	mgr.refresh();			
}

function createMarker(point,officeStreet,officeCityStateZip,officeTitle) {
	var icon = new GIcon(AISIcon);
	var marker = new GMarker(point, {title: officeTitle, icon: icon});
	//marker.infoWindowHTML = infoWindowHtml(point,officeStreet,officeCityStateZip);
	GEvent.addListener(marker,"click",officeMarkerClickHandler(officeStreet,officeCityStateZip));
	GEvent.addListener(marker,"infowindowopen",markerInfoWindowActionHandler('e'));
	GEvent.addListener(marker,"infowindowclose",markerInfoWindowActionHandler('c'))
	return marker;
}

function setAddress(newAddress) {
	address = newAddress;
	elAddress = document.getElementById("address");
	elAddress.value = newAddress;
	if (newAddress != searchFieldTxt) {
		elAddress.style.color="black";
	}
}

function getDirections(el,officePoint,officeStreet,officeCityStateZip) {
	if (el.adr.value != "" && el.adr.value != searchFieldTxt) {
		setAddress(el.adr.value);
		setCurrQuery(el.adr.value,officePoint,officeStreet,officeCityStateZip);
		gdir.load(currQuery);
	}
}

function getElementsByName_iefix(tag, name) {
	var elem = document.getElementsByTagName(tag);
	var arr = new Array();
	for(i = 0,iarr = 0; i < elem.length; i++) {
		att = elem[i].getAttribute("name");
		if(String(att) == String(name)) {
			arr[iarr] = elem[i];
			iarr++;
		}
	}
	return arr;
}

function getMarkerByPoint(point){
	for (var m in officeMarkers) {					
		if (String(officeMarkers[m].getPoint()) == String(point)) {
			return officeMarkers[m];
		}
	}
	return null;			
}

function showMoveOffices() {
	return function() {
		var gMapBounds = map.getBounds(); 
		for (var i in officeLayer) {
			var olayer = officeLayer[i];
			for (var p in olayer["places"]) {
				var place = olayer["places"][p];
				var posn = new GLatLng(place["posn"][0], place["posn"][1]);
				var he = getElementsByName_iefix("div", posn);
				if (he.length == 1) {
					var ce = document.getElementById(he[0].id.substr(0,he[0].id.indexOf('-'))+'-content');
					if (gMapBounds.contains(posn)) {	
						he[0].style.display="block";								
					} else {
						he[0].style.display = "none";
						ce.style.display = "none";
					}
				}						
			}
		}
		var h = document.getElementById("mapTable").style.height
		if (h=="100%"){
			document.getElementById("mapTable").style.height="auto";					
		} else {
			document.getElementById("mapTable").style.height="100%";
		}
	}
}

function listNearOffices(setBounds,zoom) {			
	//var range = document.getElementById("range").value;
	var range = 10;
	var cent= addressMarker.getPoint();
	var locationsAry = new Array();
	var locationAry = new Array(6);
	
	locsDiv = document.getElementById("locations");
	
	for (var i in officeLayer) {
		var olayer = officeLayer[i];
		var nearOffices = [];
		for (var p in olayer["places"]) {
			var place = olayer["places"][p];
			var posn = new GLatLng(place["posn"][0], place["posn"][1]);
			var name = place["name"];
			var officeInfo = place["info"];
			//var officeAddress = place["address"];
			var officeStreet = place["street"];
			var officeCityStateZip = place["citystatezip"];
			var mfromcent= cent.distanceFrom(posn) ;
			locationAry = [name,posn,metersTOmiles(mfromcent),officeInfo,officeStreet,officeCityStateZip];
			locationsAry.push(locationAry);
		}
	}
	locationsAry.sort(mileageSort);
	var cnt = 0;
	
	locsDiv.innerHTML = "";
	
	for (var l in locationsAry) {
		if (locationsAry[l][2] <= range && setBounds) {
			bounds.extend(locationsAry[l][1]);
			cnt++;
		}					
		addNearOfficeDivs(l,locsDiv,locationsAry[l][0],locationsAry[l][1],locationsAry[l][2],locationsAry[l][3],locationsAry[l][4],locationsAry[l][5]);
	}
	if (cnt == 0 && setBounds) {
		bounds.extend(locationsAry[0][1]);
	}
	centerAndZoomOnBounds(zoom);
	new Accordian('locations',1,'header_highlight');
}

function officeDivClickHandler(point,officeStreet,officeCityStateZip) {
	return function() {
		//alert('officeDiveClickHandler');
		officeDivClick(point,officeStreet,officeCityStateZip);
	};
}

function officeDivClick(point,officeStreet,officeCityStateZip) {
	var el = getElementsByName_iefix("div",point)[0];
	var mkr=getMarkerByPoint(point);
	var s = el.getAttribute('s');
	var sr = el.getAttribute('sr');
	//alert('officeDivClick');
	//alert(s+'\n'+sr);
	//if ((s == 'e' && sr == undefined)||(s == 'c' && sr == 'vb')){
	if (s == 'c'){
		//alert('openinfowindow');
		//mkr.openInfoWindowHtml(mkr.infoWindowHTML);
		mkr.openInfoWindowHtml(infoWindowHtml(point,officeStreet,officeCityStateZip));
	//} else if ((s == 'c' && sr == undefined)||(s == 'e' && sr == 'vb')){
	} else {
		//alert('closeinfowindow');
		mkr.closeInfoWindow();
	}
}

function officeMarkerClickHandler(officeStreet,officeCityStateZip) {
	return function() {
		//alert('officeMarkerClickHandler');
		var thisPoint = this.getPoint();		
		//this.openInfoWindowHtml(this.infoWindowHTML);
		this.openInfoWindowHtml(infoWindowHtml(thisPoint,officeStreet,officeCityStateZip));
		selectLocationHeader(thisPoint);
	};
}

function markerInfoWindowActionHandler(action) {
	return function() {
		//alert('markerInfoWindowActionHandler\n'+action);
		var thisPoint = this.getPoint();
		selectLocationHeader(thisPoint,action);
	}
}

function selectLocationHeader(point,action) {	
	var fireOnThis = getElementsByName_iefix("div",point);
	if (fireOnThis.length == 1) {
		fireOnThis = fireOnThis[0];
		var s = fireOnThis.getAttribute('s');
		//alert('selectLocationHeader\n'+s+'\n'+action);
		if (s != action) {
			if (isIE) {
				fireOnThis.fireEvent("onclick");
			} else {
				var evObj = document.createEvent('MouseEvents');
				evObj.initEvent( 'click', true, true );
				fireOnThis.dispatchEvent(evObj);
			}
		}
	}
}

function addNearOfficeDivs(count,container,name,position,miles,officeInfo,officeStreet,officeCityStateZip) {
	var headerDiv = document.createElement('div');
	var nameDiv = document.createElement('div');
	var mileageDiv = document.createElement('div');
	var contentDiv = document.createElement('div');
	var contentChildDiv = document.createElement('div');
	var printAnchor = document.createElement('a');
	var addressDiv = document.createElement('div');
	
	headerDiv.setAttribute("id","location" + count + "-header",0);
	headerDiv.className="accordion_headings";
	//alert('g handler');
	addEvent(headerDiv, "click", officeDivClickHandler(position,officeStreet,officeCityStateZip));
	headerDiv.setAttribute("name",position,0);
	headerDiv.setAttribute("s","c");
	headerDiv.style.display='block';
	
	nameDiv.className="officeName";
	nameDiv.innerHTML = name;
	mileageDiv.className="officeMileage";
	if (miles >= 0) {
		mileageDiv.innerHTML += " " + Math.round(miles*10)/10 + " mi";
	}
	
	contentDiv.setAttribute("id","location" + count + "-content");
		
	printAnchor.setAttribute("href","Javascript:printMap('" + position + "','" + name + "','" + officeStreet + "','" + officeCityStateZip + "');");
	printAnchor.className="printOfficeMap"
	printAnchor.innerHTML="Print";
	
	addressDiv.innerHTML=officeStreet + "<br/>" + officeCityStateZip;
	addressDiv.style.marginBottom="7px";
	
	contentChildDiv.className="accordion_child";
	contentChildDiv.appendChild(printAnchor);
	contentChildDiv.appendChild(addressDiv);
	contentChildDiv.innerHTML+=officeInfo;	
	
	headerDiv.appendChild(nameDiv);
	headerDiv.appendChild(mileageDiv);
	container.appendChild(headerDiv);
	
	contentDiv.appendChild(contentChildDiv);	
	container.appendChild(contentDiv);
}

function centerAndZoomOnBounds(zoom){
	if (zoom != '' && zoom != undefined) {
		var center = defaultCenter;
		var newZoom = zoom;
	} else {
		var center = bounds.getCenter();
		var newZoom = map.getBoundsZoomLevel(bounds);
	}	
	if (map.getZoom() != newZoom){
		map.setCenter(center, newZoom);
	}else{
		map.setCenter(center);
	}
}
		
function metersTOmiles(meters) {
	return meters * 0.000621371192;
}

function mileageSort(a,b) {
	return a[2] - b[2];
}

function onGDirectionsLoad(){
	document.getElementById("liRoute").style.display="inline"
	document.getElementById("aRoute").style.display="inline";
	document.getElementById("sRoute").style.display="none";
	dirElement.innerHTML = "<a class=\"printDirections\" href=\"http://maps.google.com/maps?f=q&hl=en&q=" + currPrintQuery + "&ie=UTF8&z=" + map.getZoom() + "&pw=2\" target=\"_blank\">Print</a>";
	if (lastAddress != null) {		
		map.removeOverlay(lastAddress);
	}
	addressMarker=gdir.getMarker(0);
	bounds=gdir.getBounds();
	listNearOffices(false);
}