/**
 * @author Russ Tennant (russ@i2rd.com)
 * @require prototype.js
 */

if(typeof cms_gmap == 'undefined') {
cms_gmap = true;

var gm_bi, gm_si, gm_cw, gm={}, gm_ds;

gm_getText = function(node, element, className) {
	var el = gm_getByClass(node, element, className)[0];
	if(el) return el.innerHTML;
	else return el;
};

gm_getDirections = function(gmap, map) {
	var dir = gm_getByClass(map.parentNode, "code", "marker_directions")[0];
	if(!dir) return null;
	var sa, go, back, th, gd;
	sa = gm_getText(dir, "dfn", "dir_startaddress");
	go = gm_getText(dir, "dfn", "dir_goaction");
	back = gm_getText(dir, "dfn" ,"dir_back");
	th = gm_getText(dir, "dfn", "dir_tohere");
	gd = gm_getText(dir, "dfn", "dir_getdirections");
	if(sa && go && back  && th && gd) {
		return new gm_Directions(gmap, map, gd, th, back, go, sa);
	}else{
		return null;
	}
};
gm_openInfoWindowN = function(mapId, index){
	var x = gm[mapId];
	if(x){
		gm_openInfoWindow(x["infoWindows"][index], x["markers"][index]);
	}
};
gm_openInfoWindow = function(infoWindow, marker){
	if(gm_cw){
		gm_cw.close();
		if(gm_cw.iw === infoWindow){ // Click to close/open (toggle)
			gm_cw=null;
			return;
		}
	}
	var is=infoWindow.getContent().style;
	is.visibility="hidden";
	is.display="block";
  	infoWindow.open(marker.getMap(), marker);
  	marker.setZIndex(1000);
  	is.visibility="visible";
  	gm_cw = {iw:infoWindow, m:marker, close:function(){this.iw.close();this.m.setZIndex(null);}};
};
gm_Directions = function(gmap, map, getDir, toHere, back, go, startAddr) {
	if(!gm_ds) gm_ds = new google.maps.DirectionsService();
	this.getDir = getDir;
	this.toHere = toHere;
	this.back = back;
	this.go = go;
	this.startAddr = startAddr;
	this.dirDiv = gm_getByClass(map.parentNode, "div", "directions")[0];
	this.gdirections =  new google.maps.DirectionsRenderer();
	this.gdirections.setMap(gmap);
	this.gdirections.setPanel(this.dirDiv);

};
gm_createElement = function(en) {
    	var ns, de = document.documentElement;
    	ns = (de ? de.namespaceURI : false);
    	if (ns) { return document.createElementNS(ns, en);} 
    	else { return document.createElement(en); }
};
gm_Directions.prototype = {
	setup: function(marker, latlng, tt, info) {
		var ui = gm_createElement("div");
		ui.className = "directions_control1";
		var span = gm_createElement("span");
		span.className="label";
		span.appendChild(document.createTextNode(this.getDir));
		ui.appendChild(span);
		var a = gm_createElement("a");
		a.href = "javascript:void(0);";
		a.appendChild(document.createTextNode(this.toHere));
		ui.appendChild(a); 
		
		var toForm = gm_createElement("div");
		span = gm_createElement("span");
		span.appendChild(document.createTextNode(this.getDir));
		toForm.appendChild(span);
		span = gm_createElement("span");
		span.appendChild(document.createTextNode(this.toHere));
		toForm.appendChild(span); 
		var div = gm_createElement("div");
		div.className = "start_address";
		div.appendChild(document.createTextNode(this.startAddr));
		toForm.appendChild(div);
		var form = gm_createElement("form");
		toForm.appendChild(form);
		var sa = gm_createElement("input");
		sa.setAttribute("type", "text");
		sa.setAttribute("name", "saddr");
		form.appendChild(sa);
		var da = gm_createElement("input");
		da.setAttribute("type", "hidden");
		da.setAttribute("name", "daddr");
		da.setAttribute("value", latlng.lat() + "," + latlng.lng());
		form.appendChild(da);
		var input = gm_createElement("input");
		input.setAttribute("type", "submit");
		input.setAttribute("value", this.go);
		form.appendChild(input);
		
		var info2 = info.cloneNode(true);
		info2.appendChild(toForm);
		info.appendChild(ui);
		var infoWindow = new google.maps.InfoWindow({content: info2});
		var m = marker;
		google.maps.event.addDomListener(a, 'click', function(evt){
			gm_openInfoWindow(infoWindow, m);
            return false;
		});
		var me = this;
		google.maps.event.addDomListener(form, "submit", function(evt){
            gm_stopEvent(evt);
			me.dirDiv.parentNode.style.display = "block";
			var request = {
		        origin:sa.value, 
		        destination:da.value,
		        travelMode: google.maps.DirectionsTravelMode.DRIVING
		    };
		    gm_ds.route(request, function(response, status) {
		      if (status == google.maps.DirectionsStatus.OK) {
		        me.gdirections.setDirections(response);
		      } else {
		    	alert("Unable to get directions: " + status);
		      }
		      if(gm_cw) gm_cw.close();
		    });
		});
	}
};

gm_stopEvent = function(evt) {
  evt = evt || window.event;
  if(!evt) return;
  if(evt.preventDefault)evt.preventDefault();
  if(evt.stopPropagation)evt.stopPropagation();
  evt.cancelBubble = true;
  evt.returnValue = false;
  evt.stopped = true;
};
gm_createMarker = function(gmap, latLong, markerURL, tooltip, info, directions) {
  var marker, infoWindow, icon = gm_bi;
  if(markerURL) icon = new google.maps.MarkerImage(markerURL);
  if(tooltip) {tooltip = tooltip.replace("&amp;", "&");}
  marker = new google.maps.Marker({icon:icon, shadow:gm_si, title:tooltip, position: latLong, map: gmap});
  if(info) {
	infoWindow = new  google.maps.InfoWindow({  
		  content: info
	});
	google.maps.event.addListener(marker, "click", function() {
		gm_openInfoWindow(infoWindow, marker);
	});
	google.maps.event.addListener(infoWindow, "closeclick", function() {
		if(gm_cw) gm_cw.close();
		gm_cw=null;
	});
    if (directions) directions.setup(marker, latLong, tooltip, info);
  }
  return {marker:marker, infoWindow: infoWindow};
};
gm_getConfig = function(el) {
	if (typeof el == 'string') el = document.getElementById(el);
	if (!el) return {};
	var e = el.childNodes, b = {};
	for (var n=0, mx=e.length; n<mx; n++) if(e[n].className)b[e[n].className] = e[n].innerHTML;
	return b;
};
// Implemented like this to support google's way of doing ajax maps
gm_loaded=false;
gm_load=function(url) {
  if(gm_loaded)return;
  gm_loaded=true;
  var s = document.createElement('script'); 
  s.src = url;
  document.body.appendChild(s); 
};
gm_queue=[];
gm_resize=false;
gm_init = function(){
	gm_bi = new google.maps.MarkerImage(
			"/resources/all/docroot/cms/icons/gmap/number_markers/blank.png",
			new google.maps.Size(20, 34),
			null,
			new google.maps.Point(9, 34),
			null);
	gm_si = new google.maps.MarkerImage(
			"/resources/all/docroot/cms/icons/gmap/number_markers/shadow50.png",
			new google.maps.Size(37, 34),
			null,
			new google.maps.Point(10, 34),
			null);

	if(gm_queue.length==0) return;

	var div,i=0,ib=gm_queue.length,nq=gm_queue;
	gm_queue=[];
	while((div=nq.shift()) && i< ib) {
		i++;
		if(gm_isVisible(div))
			gm_initMap(div);
		else
			gm_queue.push(div);
	}
	if(gm_queue.length>0) {
		if(gm_resize) 
			clearTimeout(gm_resize);
		gm_resize=setTimeout(gm_init, 250);
		return;
	}
	if(gm_resize) {
		for(var divId in gm) {
			if(gm.hasOwnProperty(divId)) {
				google.maps.event.trigger(gm[divId]["map"], 'resize');
			}
		}
	}
};
gm_isVisible = function(el){
	if(!el || !el.style){return true;}
	var s = el.style;
    if(s.display == 'none' || s.visibility == 'hidden' ){return false;}
    return gm_isVisible(el.parentNode);
};
gm_initMap = function(div) {
    if(typeof div == 'string') div = document.getElementById(div);
    var vis = gm_isVisible(div);
    if(typeof google == 'undefined' || typeof google.maps == 'undefined' || !vis){
    	gm_queue.push(div);
    	if(!vis){gm_resize=setTimeout(gm_init, 250);}
    	return;
    }
    if(false /*Compatibility Check*/){
        gm_mapNotSupported(div); 
        return;
    }
	var exposed={}, bounds = new google.maps.LatLngBounds(), markers=[], infoWindows=[], 
		gmap, directions, lng, lat, tooltip, info, markerURL, dfn, mapCfg, configs, cfg,
		map = document.getElementById(div.id + "_map");
	mapCfg = gm_getConfig(gm_getByClass(div, "code", "map_config")[0]);
	if(mapCfg.mapWidth) {map.style.width = mapCfg.mapWidth;}
	if(mapCfg.mapHeight) {map.style.height = mapCfg.mapHeight;}
	gmap = new google.maps.Map(map);
	directions = gm_getDirections(gmap, map);
	// get content and variables for each placemark
	configs = gm_getByClass(div, "code", "gm_map_data");
	gm[div.id]=exposed;
	exposed["markers"] = markers;
	exposed["infoWindows"] = infoWindows;
	while( (cfg = configs.pop()) ) {
		markerURL = lat = lng = info = dfn = null;
		markerURL = gm_getText(cfg, "dfn", "marker");
		info = gm_getText(cfg, "dfn", "marker_info");
		if(info) {info = document.getElementById(info);}
		tooltip = gm_getText(cfg, "dfn", "marker_tooltip");
		dfn = gm_getText(cfg, "dfn", "coordinates");
		if(dfn) {
			dfn = dfn.split(",");
			lng = dfn[0];
			lat = dfn[1];
		}
		if(!(lat && lng)) {
			// missing lat and lng
			continue;
		}
		bounds.extend(dfn=new google.maps.LatLng(lat, lng));
		dfn=gm_createMarker(gmap, dfn, markerURL, tooltip, info, directions);
		markers[configs.length] = dfn.marker;
		infoWindows[configs.length] = dfn.infoWindow;
	}
	var options = {
		center: bounds.getCenter(),
		zoom: 6,
		mapTypeId: mapCfg.mapTypeId ? google.maps.MapTypeId[mapCfg.mapTypeId] : google.maps.MapTypeId.ROADMAP
	};
	configs = ['mapTypeControl', 'navigationControl','scaleControl', 'streetViewControl'];
	for(lat=0; dfn=configs[lat]; lat++){
		if(mapCfg[dfn]) options[dfn]=mapCfg[dfn]=="true";
	}
	if(mapCfg.navStyle){
		options.navigationControlOptions={style:google.maps.NavigationControlStyle[mapCfg.navStyle]};
	}
	gmap.setOptions(options);
	if(mapCfg.maxZoom){
		mapCfg.maxZoom=parseInt(mapCfg.maxZoom);
		google.maps.event.addListenerOnce(gmap, "zoom_changed", function() {
			if(gmap.getZoom() > mapCfg.maxZoom)
				gmap.setZoom(mapCfg.maxZoom); 
		});
	}
	gmap.fitBounds(bounds);
	gm[div.id]["map"] = gmap;
};
gm_getByClass = function(start, element, className){
    var list = (start || document).getElementsByTagName(element);
    var i, el, found = [], rx = new RegExp("(?:^|\s)" + className + "(?:$|\s)");
    for(i=0; (el = list[i]); i++) {
        if((el.className || "").match(rx)) found.push(el);
    }
    return found;
};
gm_mapNotSupported = function(div) {
	var map = document.getElementById(div.id + "_map");
	var noScript = map.getElementsByTagName("noscript")[0];
	for(var h = 0; h < noScript.childNodes.length; h++) {
		map.appendChild(noScript.childNodes[h]);
	}
};

gm_scan = function() {
	var i, el, list = gm_getByClass(document, "div", "googlemap");
	for(i=0; (el = list[i]); i++) {
		gm_initMap(el);
	}
};

}//End conditional eval

