var mmap, imap;
var exml;
var yslider;
var GoogleEarth;
var mylat;
var mylon;
var currentNetworkLink = "";
var proxy = "/ogc/tntmapproxy.cgi?url=";
var isSafari = false;
var nav = navigator.userAgent;
if(nav.indexOf("Safari")){
	isSafari=true;
	}
 

 function createTabbedMarker(point,html1,label1) {
        var marker = new GMarker(point);
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowTabsHtml([new GInfoWindowTab(label1,html1)]);
        });
        return marker;
 	}


function createCookie(name,value,days) {
	var expires = "";   
	var dat;
  // days = 1;	
    if (days) {
	dat = new Date();
	dat.setTime(dat.getTime()+(days*24*60*60*1000));
	expires = "; expires="+dat.toGMTString();
    	}
    else {
	var minutes = 10;
	dat = new Date();
	dat.setTime(dat.getTime()+(minutes*60*1000));
	expires = "; expires="+dat.toGMTString();
    	}

    document.cookie = name+"="+value+expires+"; path=/ogc/maps/homepage";
	}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
	var c = ca[i];
	while (c.charAt(0)==' ') c = c.substring(1,c.length);
	if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
	}

function promptSearch(){
	$('searcher').style.display = "";
	$('promptGlass').style.display = ""; 
    	}

function searchHide(){
//	$('mapselector').style.display = "";
//	if($('subtype').options.length){
//		$('subtype').style.display="";
//		}
	$('searcher').style.display = "none";
	$('promptGlass').style.display = "none"; 
	}
function toggleSearch(){
	if($("searcher").style.display=="none"){ promptSearch(); }  
		else { 
		searchHide();
}
	//if($('promptGlass').style.display == "none"){ promptSearch();}
//	else { searchHide(); }
	}

function handleResponse(doc,err){
	    if(parseInt(err)==200) {
		    try {
			    if(doc.indexOf("500")!=0 && doc.indexOf("alert(")==-1){  
				eval(doc);
			   	 }	  
		    	}
		    catch(err) {
			 exml.mb.showMess("Unable to Connect to or parse response from geo.localsearchmaps.com",2000);
			 setTimeout("exml.mb.hideMess();",2000);
		   	 }
	    	}
    }
 
function setSubType(idx){ //invoked from subtype selector
	var v = $("subtype").options[idx].value;
	setType(parseInt(v));
	}

function selectType(idx, subtype){ //invoked from maptype selector
	var v = $("mapselector").options[idx].value;
	var mitypes = v.split(',');
	var mt = mmap.getMapTypes();
	var idx = 0;
	if(typeof subtype == "undefined"){
		subtype = mitypes.length -1;
		}
	if(mitypes.length > 1){ //show subtype if needed.
		$('subtype').options.length = 0;
		for(var i=0;i<mitypes.length;i++){
			var lan = parseInt(mitypes[i]);
			var nt = mt[lan];
			var name = nt.getName();
			var a = new Option(name,lan);
			$("subtype").options[i] = a;
			}
		$("subtype").selectedIndex = subtype;
		$("subtype").style.display = "";
		idx = parseInt(mitypes[mitypes.length-1]); //use last type in group
		}
	else {
		$("subtype").style.display = "none";
	 	idx = parseInt(v);
		}
	setType(idx);
	}

function setMyType(idx){ //generally 2D
	var mt = mmap.getMapTypes();
	var ll = mmap.getCenter();
	var bounds;
	if(typeof mt[idx].bounds == "undefined"){
		bounds =  new GLatLngBounds(new GLatLng(-90,-180),new GLatLng(90,180));
		}
	else { bounds = mt[idx].bounds; }
	if(bounds.contains(ll)){
		mmap.setMapType(mt[idx]);
		}
	else {
		mmap.setMapType(mt[idx]);
		exml.mb.showMess("Recentering on state");
		setTimeout("exml.mb.hideMess();",3000);
		mmap.setCenter(bounds.getCenter(),mmap.getBoundsZoomLevel(bounds));
		}
	}

function setType(idx) { 
	var mt = mmap.getMapTypes();
	var isArc = false;
 	if(mt[idx].getName().match(/USDA Color/i)){
		isArc = true
		}
	lastmaptype = mt[idx];
	if((mmap.getCurrentMapType() == G_SATELLITE_3D_MAP) && (!isArc)) {
		currentNetworkLink = mt[idx].networklink;
		alert(currentNetworkLink);
		if(GoogleEarth && (typeof currentNetworkLink != "undefined" && currentNetworkLink!="")) {
			if(currentOverlay){
				GoogleEarth.getFeatures().removeChild(currentOverlay);
				}
			currentOverlay = GoogleEarth.parseKml(currentNetworkLink);
			GoogleEarth.getFeatures().appendChild(currentOverlay);
			}
		exml.mb.showMess("Recentering on state");
		setTimeout("exml.mb.hideMess();",3000);
		var bounds = mt[idx].bounds;
		mmap.setCenter(bounds.getCenter(),mmap.getBoundsZoomLevel(bounds));
		showSelectedType(idx);
		}
	else { setMyType(idx); }

}
function showSelectedType(idx){
	var ms = $("mapselector");
	var mslen = ms.options.length;
	var found = false;
	var groupidx = 0;
	var mt = mmap.getMapTypes();
	var maptype = mt[idx];
	for(var m = 0; m<mslen; m++){
		if(maptype.grouptitle == ms.options[m].text){
			groupidx = m;
		 	m = mslen;
			}
		}

	$("mapselector").selectedIndex = groupidx;
	var v = $("mapselector").options[groupidx].value;
	var mitypes = v.split(',');
	var mt = mmap.getMapTypes();
	if(mitypes.length > 1){
		$('subtype').options.length = 0;
		var st = mitypes.length - 1;
		for(var i=0;i<mitypes.length;i++){
			var lan = parseInt(mitypes[i]);
			var nt = mt[lan];
			var name = nt.getName();
			if(lan == idx){
				st = i;
				}
			var a = new Option(name,lan);
			$("subtype").options[i] = a;
			}
		$("subtype").selectedIndex =  st;
		$("subtype").style.display = "";
		var idx = parseInt(mitypes[mitypes.length-1],10);
		}
	else {
		$("subtype").style.display = "none";
	 	var idx = parseInt(v);
		}

	}

function showIt(t){
	if(!t)t = 300;
	setTimeout(function(){ showSelectedType(mmap.getCurrentMapType());},t);
	}

function newMapType(maptype){
	var mt = mmap.getMapTypes();
	var mtidx = (mt.length - 1);
	var ms = $("mapselector");
	var mslen = ms.options.length;
	var found = false;
	for(var m = 0; m<mslen; m++){
		if(maptype.grouptitle == ms.options[m].text){
			ms.options[m].value += ","+mtidx;
			found = true;
		 	m = mslen;
			}
		}
	if(!found){
		var nomen = maptype.getName();
		if(nomen == "Hybrid")nomen = "Google Satellite";
		if(maptype.grouptitle && maptype.grouptitle != "undefined"){
			nomen = maptype.grouptitle;
			}
		var aleph = new Option(nomen,mtidx);
		$("mapselector").options[mslen] = aleph;
		}
	}

function getEarthInstanceCB(obj) {
    GoogleEarth = obj;
    $('geb').style.display='';
    if(GoogleEarth){
    	GoogleEarth.getLayerRoot().enableLayerById(GoogleEarth.LAYER_BUILDINGS, true);
    	GoogleEarth.getLayerRoot().enableLayerById(GoogleEarth.LAYER_BORDERS, true);
	GoogleEarth.getLayerRoot().enableLayerById(GoogleEarth.LAYER_ROADS, true); 
	}
    else {
	if(document.all) mmap.setMapType(G_SATELLITE_3D_MAP);
	}
    }
var currentOverlay;
var lastmaptype;
function updateType(){
	if(mmap.getCurrentMapType() == G_SATELLITE_3D_MAP){
		if(GoogleEarth && currentNetworkLink) {
			if(currentOverlay){
				GoogleEarth.getFeatures().removeChild(currentOverlay);
				}
			currentOverlay = GoogleEarth.parseKml(currentNetworkLink);
			GoogleEarth.getFeatures().appendChild(currentOverlay);
			}
		}
	else {
		currentNetworkLink =  mmap.getCurrentMapType().networklink;
		}
	updateIt();
}

function setMap3D() {
	if(mmap.getCurrentMapType() != G_SATELLITE_3D_MAP){
		mmap.setMapType(G_SATELLITE_3D_MAP);
		$('geb').style.background = "silver";
	 
		}
	else {
	if(!lastmaptype){ lastmaptype = G_HYBRID_MAP }
		mmap.setMapType(lastmaptype);
		$('geb').style.background = "none";
		}
	return false;
	}

function setMap2D() {
 	if(!lastmaptype){ lastmaptype = G_HYBRID_MAP }
 	mmap.setMapType(lastmaptype);
	$('geb2').style.background = "silver";
	$('geb').style.background = "none";
	return false;
	}

function updateIt(){
	var ctr = mmap.getCenter();
	createCookie("lat",ctr.lat());
	createCookie("lng",ctr.lng());
	var z = mmap.getZoom();
	createCookie("zoom",z);
	var mtype = mmap.getCurrentMapType();
	var mt = mmap.getMapTypes();
	for(var t =0;t<mt.length;t++){
		if(mt[t] == mtype){
			createCookie("mtype",t);
			break;
			}
		}
	}

function syncCookie(){
	var lat = parseFloat(readCookie("lat"));
	if(lat){
		var lng = parseFloat(readCookie("lng"));
		var zoom = parseInt(readCookie("zoom"));
		mmap.setCenter(new GLatLng(lat,lng),zoom);
		syncMapType();
		return true;
		}
	return false;
	}

function syncMapType(){
	var t = parseInt(readCookie("mtype"));
	if(t!="undefined" && typeof t != "undefined"){
		var mt = mmap.getMapTypes();
		if(mt.length >= t+1){
			mmap.setMapType(mt[t]);
			showSelectedType(t);
			}
		else {
			setTimeout("syncMapType();",100);
			}
		}
	}

function getFormattedLocation() {
    if (google.loader.ClientLocation.address.country_code == "US" &&
      google.loader.ClientLocation.address.region) {
      return google.loader.ClientLocation.address.city + ", " 
          + google.loader.ClientLocation.address.region.toUpperCase();
    } else {
      return  google.loader.ClientLocation.address.city + ", "
          + google.loader.ClientLocation.address.country_code;
    }
}

function showOnMap(lat,lon,place,region,country){
	if(lat){
			mylat = lat;
			mylon = lon;
			mmap.setCenter(new GLatLng(lat,lon),13);
			var sform = document.forms.sform;
 			if(sform){
				sform.search.value = place+" "+region+" "+country;
				}
			}
	}

var geo;


    // ====== Array for decoding the failure codes ======
    var reasons=[];
     
      function initMap() {
	
	reasons[G_GEO_SUCCESS]            = "Success";
      	reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address";
      	reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address";
      	reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address";
      	reasons[G_GEO_BAD_KEY]            = "Bad Key";
	reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries";


	geo = new GClientGeocoder(); 
	      
    	if(self.location.href == top.location.href){
	      $('fullscreen').style.display = "none";
		}

    mmap=new GMap2(document.getElementById("map"),{draggableCursor: 'crosshair', draggingCursor: 'move'});
    mmap.getMapTypes().length=0;
     
    GEvent.addListener( mmap, 'addmaptype',newMapType);
    G_HYBRID_MAP.bounds = new GLatLngBounds(new GLatLng(-90,-180),new GLatLng(90,180));
    mmap.addMapType(G_HYBRID_MAP);
   	
    var center = new GLatLng(40.812023,-96.702454);
    var zoom = 10;
    if (google.loader.ClientLocation) {
     		center = new GLatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
		var sform = document.forms.sform;
 		if(sform){
			sform.search.value = getFormattedLocation();
			}
		}

   mmap.setCenter(center,zoom,G_HYBRID_MAP);
     	
      if(!navigator.userAgent.match(/iPhone|iPod/i)){
	mmap.enableContinuousZoom();  
     	}
   
    yslider = new YSliderControl();
    yslider.initialize(mmap);
    syncCookie();
  

    var ttop= Math.round((YSLIDERLENGTH/MAXZOOM*12));
    yslider.slide.top =  ttop;
    yslider.knob.style.top = ttop+"px";
    exml = new GeoXml("exml", mmap, "groupedstates.kml", {"sortbyname":false, "nozoom" :true, "quiet":true, "iwwidth":205, "doMapTypes":true});
     if (google.loader.ClientLocation) {
	    //	exml.mb.showMess("Centering map based on client ip address");
     		}
    exml.parse(); 
    var lat = readCookie("lat");
   
     GEvent.addListener( mmap, 'zoomend', updateIt );
     GEvent.addListener( mmap, 'moveend',updateIt );
     GEvent.addListener( mmap, 'maptypechanged',updateType );

     if(navigator.userAgent.match(/iPhone|iPod/i)){
	 imap = new iPhone(mmap); 
    	 }
     else {
	mmap.enableDoubleClickZoom();
	GEvent.addDomListener(mmap.getContainer(), "DOMMouseScroll", wheelblock);
	mmap.enableScrollWheelZoom();
     	mmap.getContainer().onmousewheel = wheelblock; 
     	}
     setTimeout("exml.mb.hideMess();",8000);
     
	if(typeof hideAddressBar !="undefined"){
     	setTimeout("hideAddressBar();",3000);
     	}

	if(google.gears) {
	try {
    	var geolocation = google.gears.factory.create('beta.geolocation');
    	geolocation.getCurrentPosition(foundYou, errorCallback,
                                   { enableHighAccuracy: true,
                                     gearsRequestAddress: true });
 	 } catch (e) {
		//alert('Error using Geolocation API: ' + e.message);
   	 	exml.mb.showMess('Error using Geolocation API: ' + e.message,6000);
   		 return;
	  }
	}


    }

function foundYou(p) {
    var address = p.gearsAddress.city + ', '
                  + p.gearsAddress.region + ', '
                  + p.gearsAddress.country + ' ('
                  + p.latitude + ', '
                  + p.longitude + ')';
       //var gothere = prompt ("Do you wish to view "+address, true);
	//if(gothere) {
 		exml.mb.showMess("Locating view at "+address,10000);
		var center = new GLatLng(p.latitude,p.longitude);
   		mmap.setCenter(center,13);
	//	}
  	}

     function errorCallback(p) {
	exml.mb.showMess("Unable to locate user - defaulting to MicroImages home",1000);
  	}

    function wheelblock(e) {
	if (!e){ e = window.event }
		if (e.preventDefault){ e.preventDefault() }
		e.returnValue = false;
		}
     

// ====== Create a Client Geocoder ======
   
 

function locate(nsearch) {
	searchHide();
	if(!nsearch){
         	var sform = document.forms.sform;
 		if(sform){
			nsearch = sform.search.value;
			}
		}
	var p;
	if(!nsearch){ return; }
	$("subtype").style.display = "none";
	if(nsearch.indexOf("http")==0){ /* --- look for kml to load --- */
		var t = nsearch.split('/');
		loadKML(nsearch,t[t.length-1],false);
		return;
		}
	// ====== Perform the Geocoding ======   
   	var locsearch = nsearch;	
        geo.getLocations(locsearch, function (result) { 
            // If that was successful
            if (result.Status.code == G_GEO_SUCCESS) {
	    var mess = $("message");
	      mmap.clearOverlays();
	      if(mess){ mess.innerHTML = "Found " +result.Placemark.length +" results"; }
	      // Loop through the results, placing markers
              for (var i=0; i<result.Placemark.length; i++) {
                p = result.Placemark[i].Point.coordinates;
		var point = new GLatLng(p[1],p[0]);
		var marker = createTabbedMarker(point,"<span>"+locsearch+"</span>", "Address");	
                mmap.addOverlay(marker);
              }
		
	      var z = result.Placemark[0].AddressDetails.Accuracy;
	      var country = result.Placemark[0].AddressDetails.Country.CountryNameCode;
	      //alert(result.Placemark[0].AddressDetails.toJSONString()); 
	      var an;
	      if(country == "US"){
	        an = result.Placemark[0].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
	      	}
	      if(country != "US" || an == "HI" || an == "AK" || an == "Alaska" || an == "Hawaii"){
		    var gi = $("mapselector").selectedIndex;
		    if(gi>1){
			if(mmap.getCurrentType() != G_SATELLITE_3D_MAP){
	      			mmap.setMapType(G_HYBRID_MAP);
				}
	      		showSelectedType(0);
	      		}
	      	}
	      else {
		    
		      var cn = mmap.getCurrentMapType().id;
		      if(!cn)cn = "-----------";
		      if(console){ console.log(cn.substring(4,6)+" "+an); }
		      if(cn.substring(4,6) != an){
			var mt = mmap.getMapTypes();
			for(var m=mt.length-1;m >1; m--){
					var tit = mt[m].id;
					if(an == tit.substring(4,6) || an == mt[m].grouptitle ){
						if(mmap.getCurrentMapType() != G_SATELLITE_3D_MAP){
							mmap.setMapType(mt[m]);
							}
						else {
							currentNetworkLink =  mt[m].networklink;
							if(GoogleEarth && currentNetworkLink) {
								if(currentOverlay){
									GoogleEarth.getFeatures().removeChild(currentOverlay);
									}
								currentOverlay = GoogleEarth.parseKml(currentNetworkLink);
								GoogleEarth.getFeatures().appendChild(currentOverlay);
								}
							}
						showSelectedType(m);
					 	break;p
						}
					}
		        	}
	         	}
	      if(z == 9) { z = 0; }
	      var zoom =  1 + 2 * parseInt(z,10);
	      mmap.setCenter(new GLatLng(p[1],p[0]),zoom);
	      exml.mb.showMess("Search successful");
	      setTimeout("exml.mb.hideMess();",3000);
              
            }
            /* ====== Decode the error status ====== */
            else {
		var reason = "";
		if(typeof reasons[result.Status.code]!= "undefined" ) {reason = reasons[result.Status.code]; }
		exml.mb.showMess("<center>Problem occured in search<br />Google Search Returned "+reason+" </center>", 3000);			 
               }
          }
	); }

