
function _gt(e) { return document.getElementsByTagName(e); }
function _gi(e) { return document.getElementById(e); }
function _ce(e) { return document.createElement(e); }
function _ct(e) { return document.createTextNode(e); }

var LargeMapControl=0,SmallMapControl=1,MapTypeControl=2,ScaleControl=3,SmallZoomControl=4,OverviewMapControl=5;
function CKMap(mtype,container) {
    var map;

    this.mtype = mtype;
    if(mtype=='GMAP' && _enable_gmap) {
	map = new GMap2(container);
	map.addMapType(WMS_TOPO_MAP);
	map.enableDoubleClickZoom();
	map.enableContinuousZoom();
    }
    if(mtype=='UMAP' && _enable_umap) map = new UMap(container);
    if(mtype=='YMAP' && _enable_ymap) map = new YMap(container);

    this.map = map;
    
    this.addControl = function(c) {
	if(mtype=='GMAP') {
	    if(c==LargeMapControl) var ctrl = new GLargeMapControl();
	    if(c==SmallMapControl) var ctrl = new GSmallMapControl();
	    if(c==MapTypeControl) var ctrl = new GMapTypeControl();
	    if(c==ScaleControl) var ctrl = new GScaleControl();
	    if(c==SmallZoomControl) var ctrl = new GSmallZoomControl();
//	    if(c==OverviewMapControl) var ctrl = new GOverviewMapControl(new GSize(200, 150));
	    if(c==OverviewMapControl) var ctrl = new GOverviewMapControl(new GSize(200, 150));
	    map.addControl(ctrl);
	}
	if(mtype=='UMAP' && _enable_umap) {
	    if(c==LargeMapControl) var ctrl = U_FULL_CONTROL;
	    if(c==SmallMapControl) var ctrl = U_MINI_CONTROL;
	    if(c==MapTypeControl) var ctrl = U_TYPE_CONTROL
	    map.addControl(ctrl);
	}
	if(mtype=='YMAP' && _enable_ymap) {
	    map.addPanControl();
	    if(c==LargeMapControl) map.addZoomLong();
	    if(c==SmallMapControl) map.addZoomShort();
//	    if(c==MapTypeControl) 
	}
    }

    this.enableDragging = function() {
	if(mtype=='GMAP') map.enableDragging();
	if(mtype=='UMAP' && _enable_umap) return;
	if(mtype=='YMAP' && _enable_ymap) map.enableDragMap();
    }

    this.addListener = function(e,f) {
	if(mtype=='GMAP') GEvent.addListener(map, e, f);
	if(mtype=='UMAP' && _enable_umap) map.addListener(e,f);
	if(mtype=='YMAP' && _enable_ymap) {
	    return;
	    switch(e) {
		case 'click': event=EventsList.MouseClick; break;
		case 'moveend': event=EventsList.onPan; break;
	    }
	    _gi('msgBar').innerHTML = e + ',' + event;
	    YEvent.Capture(map,event,f);
	}
    }

    this.centerAndZoom = function(p,z) {
	if(mtype=='GMAP') map.setCenter(p,z);
	if(mtype=='UMAP' && _enable_umap) map.centerAndZoom(p,(z-7)?(z-7):0);
	if(mtype=='YMAP' && _enable_ymap) map.drawZoomAndCenter(p,z+1);
    }

    this.centerAtLatLng = function(p) {
	if(mtype=='GMAP') map.setCenter(p);
	if(mtype=='UMAP' && _enable_umap) map.centerMap(p);
	if(mtype=='YMAP' && _enable_ymap) map.drawZoomAndCenter(p,map.getZoomLevel());
    }

    this.setMapType = function(t) {
	if(mtype=='GMAP') map.setMapType(t);
	if(mtype=='UMAP' && _enable_umap) return;
	if(mtype=='YMAP' && _enable_ymap) return;
    }

    this.checkResize = function() {
	if(mtype=='GMAP') map.checkResize();
	if(mtype=='UMAP' && _enable_umap) map.refreshMap();
	if(mtype=='YMAP' && _enable_ymap) return;
    }

    this.refreshMap = function() {
	if(mtype=='GMAP') map.checkResize();
	if(mtype=='UMAP' && _enable_umap) map.refreshMap();
	if(mtype=='YMAP' && _enable_ymap) return;
    }

    this.zoomTo = function(z) {
	if(mtype=='GMAP') map.setZoom(z);
	if(mtype=='UMAP' && _enable_umap) map.zoomMap((z-7)?(z-7):0);
	if(mtype=='YMAP' && _enable_ymap) map.setZoomLevel(z+1);
    }

    this.zoomOut = function() {
	map.zoomOut();
    }

    this.zoomIn = function() {
	map.zoomIn();
    }

    this.getZoomLevel = function() {
	if(mtype=='GMAP') return map.getZoom();
	if(mtype=='UMAP' && _enable_umap) return map.getZoomLevel()+7;
	if(mtype=='YMAP' && _enable_ymap) return map.getZoomLevel()-1;
    }
    this.gz = function() {
	if(mtype=='GMAP') return map.getZoom();
	if(mtype=='UMAP' && _enable_umap) return map.getZoomLevel();
	if(mtype=='YMAP' && _enable_ymap) return map.getZoomLevel();
    }

    this.refreshMap = function() {
	if(mtype=='GMAP') return;
	if(mtype=='UMAP' && _enable_umap) map.refreshMap();
	if(mtype=='YMAP' && _enable_ymap) return;
    }

    this.getCenterLatLng = function() {
	if(mtype=='GMAP') {
	    var p = map.getCenter();
//	    p.lon = p.x;
//	    p.lat = p.y;
	    return p;
	}
	if(mtype=='UMAP' && _enable_umap) {
	    var c = map.getCenter();
	    var p = new ULatLng(c.lat(),c.lng());
//	    p.lat = c.lat();
//	    p.lon = c.lng();
	    return p;
	}
	if(mtype=='YMAP' && _enable_ymap) {
	    var p = map.getCenterLatLon();
	    p.lat = function() { return p.Lat; }
	    p.lon = function() { return p.Lon; }
	    return p;
	}
    }

    this.closeInfoWindow = function() {
	if(mtype=='GMAP') map.closeInfoWindow();
	if(mtype=='UMAP' && _enable_umap) map.closeInfoWindow();
	if(mtype=='YMAP' && _enable_ymap) map.closeInfoWindow();
    }

    this.addOverlay = function(o) {
	if(mtype=='GMAP') map.addOverlay(o);
	if(mtype=='UMAP' && _enable_umap) map.addOverlay(o);
	if(mtype=='YMAP' && _enable_ymap) map.addOverlay(o);
    }
    this.removeOverlay = function(o) {
	if(mtype=='GMAP') map.removeOverlay(o);
	if(mtype=='UMAP' && _enable_umap) map.removeOverlay(o);
	if(mtype=='YMAP' && _enable_ymap) map.removeOverlay(o);
    }

    this.LatLng = function(lat,lon) {
	if(mtype=='GMAP') {
	    var p = new GLatLng(lat,lon);
//	    p.lon = p.lng();
//	    p.lat = p.lat();
	    return p;
	}
	if(mtype=='UMAP' && _enable_umap) {
	    var p = new ULatLng(lat,lon);
//	    p.lat = p.lat();
//	    p.lon = p.lng();
	    return p;
	}
	if(mtype=='YMAP' && _enable_ymap) {
	    var p = new YGeoPoint(lat, lon);
	    p.lat = function() { return p.Lat; }
	    p.lon = function() { return p.Lon; }
	    return p;
	}
    }

    this.Marker = function(p,i,l,d,draggable) {
	if(mtype=='GMAP') {
	    if( i == undefined || i == null ) {
		var icon = new GIcon();
		icon.image = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
		icon.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
		icon.transparent = 'http://maps.yuan.cc/mm_20_trans.png';
		icon.shadowSize = new GSize(22, 20);
		icon.iconSize = new GSize(12, 20);
		icon.iconAnchor = new GPoint(6, 20);
		icon.infoWindowAnchor = new GPoint(5,1);
	    } else icon = i;
	    if(draggable==undefined || draggable==null) draggable=false;
	    if( i == undefined || i == null ) var options = { draggable: draggable, title: l, bouncy: true }
	    else var options = {
		icon: icon,
		draggable: draggable,
		title: l,
		bouncy: true
	    }
//	    var m = new GMarker(p,icon);
	    var m = new GMarker(p,options);
	    m.addListener = function(e,f) {
		GEvent.addListener(this,e,f);
	    }
	    GEvent.addListener(m,'dragstart',function() {map.closeInfoWindow();});
	    return m;
	}
	if(mtype=='UMAP' && _enable_umap) {
	    if( i == undefined ) {
		var icon = new UIcon();
		icon.image = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
		icon.iconWidth = 12;
		icon.iconHeight = 20;
		icon.iconAnchor = new UPoint(6,20);
	    } else icon = i;
	    var m = new UMarker(p,icon,l,d);
	    m.openInfoWindowHtml = m.openInfoWindow;
	    m.openInfoWindow = function(e) {
		this.openInfoWindowHtml(e.innerHTML);
	    }
	    return m;
	}
	if(mtype=='YMAP' && _enable_ymap) {
	    var m = new YMarker(p,i);
	    m.addListener = function(e,f) {
		if(e=='click') e = EventsList.MouseClick;
		YEvent.Capture(m,e,f);
	    }
	    m.openInfoWindowHtml = function(h) {
		this.openSmartWindow(h);
		map.drawZoomAndCenter(p,map.getZoomLevel());
	    }
	    m.openInfoWindow = m.openSmartWindow;
	    return m;
	}
    }

    this.Polyline = function(p,c,w,o) {
	if(mtype=='GMAP') {
	    if( w == undefined ) w = 3;
	    var lines = new Array();
	    var icon = new GIcon();
	    icon.image = 'http://labs.google.com/ridefinder/images/mm_20_yellow.png';
	    icon.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
	    icon.shadowSize = new GSize(22, 20);
	    icon.iconSize = new GSize(12, 20);
	    icon.iconAnchor = new GPoint(6, 20);
	    icon.infoWindowAnchor = new GPoint(5,1);
	    var icon2 = new GIcon(icon);
	    var p1 = new GMarker(p[0],icon);
	    var p2 = new GMarker(p[p.length-1],icon2);
	    GEvent.addListener(p1, "mouseover", function() { p1.openInfoWindowHtml(p1.html); });
	    GEvent.addListener(p2, "mouseover", function() { p2.openInfoWindowHtml(p2.html); });
	    p1.html = '<b>Start Point</b><p>'+p[0].lat()+','+p[0].lng();
	    p2.html = '<b>End Point</b><p>'+p[p.length-1].lat()+','+p[p.length-1].lng();
	    lines[lines.length] = p1;
	    lines[lines.length] = p2;
	    lines[lines.length] = new GPolyline(p,c,w,o);
	    return lines;
	}
	if( mtype=='UMAP' && _enable_umap) {	// waiting for UPolyline ..... XD
	    if( w == undefined ) w = 3;
	    var lines = new Array();
	    var icon = new UIcon();
	    icon.iconWidth = 12;
	    icon.iconHeight = 20;
	    icon.image = 'http://labs.google.com/ridefinder/images/mm_20_yellow.png';
	    var icon2 = new UIcon(icon);

	    var p1 = new UMarker(p[0],icon);
	    var p2 = new UMarker(p[p.length-1],icon2);
//	    var p1 = this.Marker(p[0],icon);
//	    var p2 = this.Marker(p[p.length-1],icon2);
	    p1.openInfoWindowHtml = p1.openInfoWindow;
	    p2.openInfoWindowHtml = p2.openInfoWindow;
	    p1.html = '<b>Start Point</b><p>'+p[0].lat()+','+p[0].lng();
	    p2.html = '<b>End Point</b><p>'+p[p.length-1].lat()+','+p[p.length-1].lng();
	    p1.addListener("click", function(e) { p1.openInfoWindowHtml(p1.html); });
	    p2.addListener("click", function(e) { p2.openInfoWindowHtml(p2.html); });
//	    p2.addListener("mouseover", function() { p2.openInfoWindow(p2.html); });
	    lines[lines.length] = p1;
	    lines[lines.length] = p2;
	    lines[lines.length] = new UPolyline(p,c,w,o);
	    return lines;
	}
	if( false && mtype=='UMAP' && _enable_umap) {
	    var markers = new Array();
	    var endpoint = new UIcon();
	    endpoint.iconWidth = 12;
	    endpoint.iconHeight = 20;
	    endpoint.image = 'http://labs.google.com/ridefinder/images/mm_20_yellow.png';
	    var icon = new UIcon();
	    icon.iconWidth = 8;
	    icon.iconHeight = 8;
	    icon.image = 'http://maps.yuan.cc/redcross.png';
	    for(var i=0;i<p.length;i++) {
		if(i==0 || i==(p.length-1) ) var pin = new UIcon(endpoint);
		else var pin = new UIcon(icon);
		var point = new ULatLng(p[i].lat,p[i].lon);
		markers[markers.length] = new UMarker(p[i],pin);
//		markers[markers.length] = new UMarker(p[i],pin,p[i].lat()+','+p[i].lng(),'');
	    }
	    markers[0].openInfoWindowHtml = markers[0].openInfoWindow;
	    markers[0].html = '<b>Start Point</b><p>'+p[0].lat()+','+p[0].lng();
	    markers[0].addListener('mouseover', function(e) {
//		markers[0].openInfoWindow(markers[0].html);
		this.openInfoWindowHtml(e.innerHTML);
	    });
	    markers[markers.length-1].openInfoWindowHtml = markers[markers.length-1].openInfoWindow;
	    markers[markers.length-1].html = '<b>End Point</b><p>'+p[p.length-1].lat()+','+p[p.length-1].lng();
	    markers[markers.length-1].addListener('mouseover', function(e) {
//		markers[markers.length-1].openInfoWindow(markers[markers.length-1].html);
		this.openInfoWindowHtml(e.innerHTML);
	    });
	    return markers;
	}
	return null;
    }

    this.Bounds = function(sw,ne) {
	if(mtype=='GMAP') {
	    var bounds = new GLatLngBounds(sw,ne);
	    return bounds;
	}
	if(mtype=='UMAP' && _enable_umap) {
	    var bounds = new UBounds(sw,ne);
	    return bounds;
	}
    }

    this.Icon = function(i) {
	if(mtype=='GMAP') {
	    var icon = new GIcon(i);
	    icon.setup = function(img,w,h,x1,y1,x2,y2) {
		this.iconSize = new GSize(w,h);
		this.image = img;
		this.iconAnchor = new GPoint(x1,y1);
		this.infoWindowAnchor = new GPoint(x2,y2);
//		icon.transparent = 'http://maps.yuan.cc/mm_20_trans.png';
		icon.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
		icon.shadowSize = new GSize(w, h);
	    }
	    return icon;
	}
	if(mtype=='UMAP' && _enable_umap) {
	    var icon = new UIcon(i);
	    icon.setup = function(img,w,h,x1,y1,x2,y2) {
		this.iconWidth = w;
		this.iconHeight = h;
		this.image = img;
	    }
	    return icon;
	}
	if(mtype=='YMAP' && _enable_ymap) {
	    var icon = new YImage();
	    icon.setup = function(img,w,h,x1,y1,x2,y2) {
		this.src = img;
		this.size = new YSize(w,h);
		this.offsetSmartWindow = new YCoordPoint(x1,y1);
	    }
	    return icon;
	}
    }

    this.getBoundsLatLng = function() {
	if(mtype=='GMAP') {
	    var bounds = map.getBounds();
	    bounds.minX = bounds.getSouthWest().lng();
	    bounds.minY = bounds.getSouthWest().lat();
	    bounds.maxX = bounds.getNorthEast().lng();
	    bounds.maxY = bounds.getNorthEast().lat();
	    return bounds;
	}
	if(mtype=='UMAP' && _enable_umap) {
	    var bounds = map.getBounds();
	    bounds.minX = bounds.getSouthWest().lng();
	    bounds.minY = bounds.getSouthWest().lat();
	    bounds.maxX = bounds.getNorthEast().lng();
	    bounds.maxY = bounds.getNorthEast().lat();
	    return bounds;
	}
	if(mtype=='YMAP' && _enable_ymap) {
	    var bounds = map.getBoundsLatLon();
	    bounds.minX = bounds.LonMin;
	    bounds.minY = bounds.LatMin;
	    bounds.maxX = bounds.LonMax;
	    bounds.maxY = bounds.LatMax;
	    return bounds;
	}
    }

    this.getBoundsZoomLevel = function(minX,minY,maxX,maxY) {
	if(mtype=='GMAP') {
	    var sw = new GLatLng(minY,minX);
	    var ne = new GLatLng(maxY,maxX);
	    var bounds = new GLatLngBounds(sw,ne);
	    return map.getBoundsZoomLevel(bounds);
	}
	if(mtype=='UMAP' && _enable_umap) {
	    var sw = new ULatLng(minY,minX);
	    var ne = new ULatLng(maxY,maxX);
	    var bounds = new UBounds(sw,ne);
	    return map.getBoundsZoomLevel(bounds)+7;
	}
    }

    this.clearOverlays = function() {
	if(mtype=='GMAP') map.clearOverlays();
	if(mtype=='UMAP' && _enable_umap) map.clearOverlays();
	if(mtype=='YMAP' && _enable_ymap) return;
    }

    this.openInfoWindowHtml = function(point, html) {
	if(mtype=='GMAP') map.openInfoWindowHtml(point,html);
	if(mtype=='UMAP' && _enable_umap) map.openInfoWindow(point,html);
	if(mtype=='YMAP' && _enable_ymap) return;
    }

    if(mtype=='GMAP') {
	if( _init_lat==0 && _init_lon==0 ) this.centerAndZoom(this.LatLng(0,0),2);
	else this.centerAndZoom(this.LatLng(_init_lat,_init_lon),_init_zoom);
    }
    if(mtype=='UMAP' && _enable_umap) {
	if( _init_lat==0 && _init_lon==0 ) this.centerAndZoom(this.LatLng(23.811243,120.952458),16);
	else this.centerAndZoom(this.LatLng(_init_lat,_init_lon),10);
    }
    if(mtype=='YMAP' && _enable_ymap) this.centerAndZoom(this.LatLng(39,-96),13)

//    this.Event = function(o,e,f) {
//	this.addListener = function
//	if(mtype=='GMAP') return new GEvent(o,e,f);
//	if(mtype=='UMAP') return new UIcon(i);
//	if(mtype=='YMAP') return new YImage();
//    }
}

// GPolyline = function() { this.type = 'GPolyline'; }
// GEvent = new Object();
// GEvent.addListener = function(target, event, handler) {
//     target.addListener(event,handler);
// }


function Dd_to_DMm(x,ll) {

    if(x>=0) sign = 1;
    else sign = -1;
    x = Math.abs(x);
    d1 = Math.floor(x);
    d2 = x-d1;

    var y = new Object();
    y.d = d1;
    y.m = d2*60;
    y.m = Math.round(y.m*1000)/1000;
    y.sign = sign;

    if(ll=='lat' && sign==1) str = 'N';
    if(ll=='lat' && sign==-1) str = 'S';
    if(ll=='lon' && sign==1) str = 'E';
    if(ll=='lon' && sign==-1) str = 'W';

    str += y.d + unescape('%BA') + ' ' + y.m + '\'';

    return str;
}

function DMm_to_Dd(x) {

    var DMm,sign,a,d,m,y;

    DMm = /^([NEWSnews]) *(\d+)[^\d]+([\d\.]+)'?$/;
    a = DMm.exec(x);

    if(!a) {
	alert('Invalid coordinate format');
	return 'N/A';
    }
    if( a[1]=='N' || a[1]=='E' || a[1]=='n' || a[1]=='e') sign = 1;
    else sign = -1;

    d = 1*a[2];
    m = 1*a[3];

//    alert(sign + ', ' + d + ', ' + m);
    y = sign*(d + m/60);
    return y;
}


// 
//
function WMSCreateMap( name, copyright, baseUrl, layer, minResolution, maxResolution, urlArg ) { 
    var tileLayer = new GTileLayer( new GCopyrightCollection( copyright ), minResolution, maxResolution ); 
    tileLayer.baseUrl = baseUrl; 
    tileLayer.layer = layer; 
    tileLayer.getTileUrl = WMSGetTileUrl; 
    tileLayer.getCopyright = function () { return copyright; }; 
    var tileLayers = [ tileLayer ]; 
//    return new GMapType( tileLayers, G_SATELLITE_MAP.getProjection(), name, { errorMessage: _mMapError, urlArg: 'o' } ); 
    return new GMapType( tileLayers, G_SATELLITE_MAP.getProjection(), name, { errorMessage: '', urlArg: 'o' } ); 
}

function WMSGetTileUrl( tile, zoom ) { 
    var southWestPixel = new GPoint( tile.x * 256, ( tile.y + 1 ) * 256 ); 
    var northEastPixel = new GPoint( ( tile.x + 1 ) * 256, tile.y * 256 ); 
    var southWestCoords = G_NORMAL_MAP.getProjection().fromPixelToLatLng( southWestPixel, zoom ); 
    var northEastCoords = G_NORMAL_MAP.getProjection().fromPixelToLatLng( northEastPixel, zoom ); 
    var bbox = southWestCoords.lng() + ',' + southWestCoords.lat() + ',' + northEastCoords.lng() + ',' + northEastCoords.lat(); 
    return this.baseUrl + '?VERSION=1.1.1&REQUEST=GetMap&LAYERS=' + this.layer + '&STYLES=&SRS=EPSG:4326&BBOX=' + bbox + '&WIDTH=256&HEIGHT=256&FORMAT=image/jpeg&BGCOLOR=0xCCCCCC&EXCEPTIONS=INIMAG-E'; 
} 

var WMS_TOPO_MAP = WMSCreateMap( 'Topo', 'Imagery by USGS / Web Service by TerraServer', 'http://www.terraserver-usa.com/ogcmap6.ashx', 'DRG', 4, 17, 't' ); 
var WMS_DOQ_MAP = WMSCreateMap( 'DOQ', 'Imagery by USGS / Web Service by TerraServer', 'http://www.terraserver-usa.com/ogcmap6.ashx', 'DOQ', 4, 18, 'o' );

