// Global variable for saving possible geocoded address 
geocodedAddress = null;
selectedLatlon = null;
selectedProvider = null;
selectedType = null;
selectedZoom = null;
selectedTextbox = null;
xmlText = null;
coordinates = new country("worldwide",0,0,1);

function activateGeocoder() { 
       // Need to call vanilla to clean up controls and the like's
       // This is actually a web-service returning the XML doc
       mCore_resetMapControls();
       var address = document.forms['latlonLocatorForm'].stringaddress.value;
       document.getElementById("mashupsoftdiv").innerHTML = "Searching/Loading..."; 
       if(address == "") { 
        alert("* " + address + " Not Found\n Suggestions: \n 1) Introduce a format like : Street, City, Country, Zip Code\n 2) Leave off street level details if you keep getting unresolvable addresses.\n 3) Use City, Country addresses and drag the marker & zoom contols \n to determine street level coordinates.");
       } else { 
       showAddress(address);
       document.Form3.stringtextbox.disabled=false;
       document.Form3.mapprovider.disabled=false;
       document.Form3.maptype.disabled=false;
       document.Form3.mapzoom.disabled=false;
       document.Form3.mapmarker.disabled=false;
       document.Form3.mapupdate.disabled=false;
       document.Form4.generatemap.disabled=true;
       }
    }

function showAddress(address) {
  var geocoder = new GClientGeocoder();
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        alert("* " + address + " Not Found\n Suggestions: \n 1) Introduce a format like : Street, City, Country, Zip Code\n 2) Leave off street level details if you keep getting unresolvable addresses.\n 3) Use City, Country addresses and drag the marker & zoom contols \n to determine street level coordinates.");
      } else {
	geocodedAddress = point;
        loadwithdrag();
      }
    }
  );
}

    function country(code,lat,lon,zoom) { 
      this.code = code;
      this.lat = lat; 
      this.lon = lon; 
      this.zoom = zoom;
    }

function load() { 
// Piggy back of load for text box message 
document.Form2.stringaddress.onblur = function()
{
  var field = document.Form2.stringaddress;
  if (field.value == '') field.value = 'Search for address';
}

document.Form2.stringaddress.onfocus = function()
{
  var field = document.Form2.stringaddress;
   if (field.value == 'Search for address') field.value = '';
}
if (document.Form2.stringaddress.value == '') document.Form2.stringaddress.value = 'Search for address';
document.Form2.stringaddress.disabled=false;
document.Form2.geocodebutton.disabled=false;
document.Form3.stringtextbox.disabled=true;
document.Form3.mapprovider.disabled=true;
document.Form3.maptype.disabled=true;
document.Form3.mapzoom.disabled=true;
document.Form3.mapmarker.disabled=true;
document.Form3.mapupdate.disabled=true;
document.Form4.generatemap.disabled=true;
}
    
function loadwithdrag() { 
// Piggy back of load for text box message 
document.Form2.stringaddress.onblur = function()
{
  var field = document.Form2.stringaddress;
  if (field.value == '') field.value = 'Search for address';
}

document.Form2.stringaddress.onfocus = function()
{
  var field = document.Form2.stringaddress;
   if (field.value == 'Search for address') field.value = '';
}
if (document.Form2.stringaddress.value == '') document.Form2.stringaddress.value = 'Search for address';

     // Start countries
     var ctyus = new country("ctyus",37.50972584293751,-96.943359375,4);
     var ctyuk = new country("ctyuk",53.69670647530323,-1.58203125,5);
     var ctycanada = new country("ctycanada",54.7246201949245,-101.953125,4);
     var ctyaustria = new country("ctyaustria",47.234489635299184,13.64501953125,7);
     var ctyaustralia = new country("ctyaustralia",-29.075375179558346,137.28515625,4);
     var ctybelgium = new country("ctybelgium",50.80593472676908,4.405517578125,7);
     var ctybrazil = new country("ctybrazil",-11.092165893502,-51.50390625,4);
     var ctychina = new country("ctychina",30.977609093348686,105.1171875,4);
     var ctydenmark = new country("ctydenmark",55.52863052257191,11.689453125,6);
     var ctyfinland = new country("ctyfinland",64.47279382008166,26.54296875,4);
     var ctyfrance = new country("ctyfrance",46.92025531537451,2.5927734375,5);
     var ctygermany = new country("ctygermany",51.86292391360244,10.2392578125,5);
     var ctyhongkong = new country("ctyhongkong",22.39071391683855,114.19189453125,8);
     var ctyitaly = new country("ctyitaly",42.74701217318067,13.359375,5);
     var ctyjapan = new country("ctyjapan",36.52729481454624,137.98828125,4);
     var ctynetherlands = new country("ctynetherlands",52.26815737376817,5.3173828125,6);
     var ctynorway = new country("ctynorway",61.01572481397616,8.525390625,5);
     var ctyportugal = new country("ctyportugal",39.50404070558415,-8.1298828125,6);
     var ctysingapore = new country("ctysingapore",1.4939713066293239,103.4912109375,5);
     var ctysouthkorea = new country("ctysouthkorea",36.59788913307022,127.96875,5);
     var ctyspain = new country("ctyspain",40.38002840251183,-3.8232421875,5);
     var ctysweden = new country("ctysweden",60.326947742998414,15.29296875,4);
     var ctyswitzerland = new country("ctyswitzerland",46.98025235521883, 8.0419921875,6);
     var ctytaiwan = new country("ctytaiwan",23.845649887659352,120.948486328125,7);
     var worldwide = new country("worldwide",0,0,1);
     // var box = document.forms['latlonLocatorForm'].country;
     // var targetpoint = eval(box.options[box.selectedIndex].value);
     if(geocodedAddress == null) { 
         // document.getElementById("latitudelongitude").innerHTML = "(" + targetpoint.lat + ", " + targetpoint.lon + ")";
     } else { 
        // document.getElementById("latitudelongitude").innerHTML = "" + geocodedAddress + "<br/> [ " + document.forms["latlonLocatorForm"].stringaddress.value + " ]";
     }
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("mashupsoftdiv"));
	var center = new GLatLng(0,0);
	if(geocodedAddress == null) { 
        // center  = new GLatLng(targetpoint.lat,targetpoint.lon);
        // map.setCenter(center,targetpoint.zoom);
        } else { 
        center = geocodedAddress;
	selectedLatlon = center.toString().replace(/\(/g,"").replace(/\)/g,"").replace(/\ /g,"");
        map.setCenter(center,10);
	}
        map.addControl(new GMapTypeControl());

        var marker = new GMarker(center, {draggable: true});


        GEvent.addListener(marker, "dragstart", function() {
          map.closeInfoWindow();
        });

        GEvent.addListener(marker, "dragend", function() {
          coordinates = marker.getPoint();
   	  selectedLatlon = coordinates.toString().replace(/\(/g,"").replace(/\)/g,"").replace(/\ /g,"");
	  marker.openInfoWindowHtml("[ Customize text box ]");
          document.Form3.stringtextbox.value = 'Customize text box';
          //marker.openInfoWindowHtml(coordinates.toString());
          //document.getElementById("latitudelongitude").innerHTML = coordinates.toString();
          var currentZ = map.getZoom();
          if(currentZ <= 4) { 
          map.setCenter(coordinates,4);
          }
         });

        GEvent.addListener(marker, "click", function() {
          coordinates = marker.getPoint();
	  marker.openInfoWindowHtml("[ Customize text box ]");
          document.Form3.stringtextbox.value = 'Customize text box';
          //marker.openInfoWindowHtml(coordinates.toString());
         });

        map.addOverlay(marker);
        map.enableDoubleClickZoom();
        map.enableContinuousZoom();
        // map.setMapType(map.getMapTypes()[0]);
        map.addControl(new GLargeMapControl());
        // map.addControl(new GOverviewMapControl());
        // Place latitude/longitude and description address in window 
	if(geocodedAddress == null) { 
        coordinates = marker.getPoint();
        marker.openInfoWindowHtml("[ " + box.options[box.selectedIndex].innerHTML + "]");
        document.Form3.stringtextbox.value = box.options[box.selectedIndex].innerHTML;
	} else { 
        coordinates = marker.getPoint();
        marker.openInfoWindowHtml("[ "  + document.forms["latlonLocatorForm"].stringaddress.value + " ] <br/> <span style='font-size:small'><i>Tip: Drag me if I'm not <br/> in the exact position you want</span>");
        document.Form3.stringtextbox.value = document.forms["latlonLocatorForm"].stringaddress.value;
	}
      }
      // Reset geocoded address for new calls.
      geocodedAddress = null;
}

function checkProvider() { 
  var mapProvider = document.Form3.mapprovider.value;
  var mapType = document.Form3.maptype.value;
  if (mapType == 'birdseye' && mapProvider != 'msn') { 
    alert('Birdseye view only available for MSN maps');
    document.Form3.maptype.value = 'hybrid';
  }
}

function updateMashup() { 
// Lost track of latitude/longitude, tell user to reload/re-search
if (selectedLatlon == null || selectedLatlon == "0,0") { 
 alert('Ups, we lost track of the location your trying to plot\n Please try again.');
 return false;
}
selectedProvider = document.Form3.mapprovider.value;
selectedType = document.Form3.maptype.value;
selectedTextbox = document.Form3.stringtextbox.value;
selectedZoom = document.Form3.mapzoom.value;
selectedIcon = document.Form3.mapmarker.value;
xmlText="<mashupsoft>";
xmlText=xmlText+"<mappoint>";
xmlText=xmlText+"<keywordid>Point</keywordid>";
xmlText=xmlText+"<address>" + selectedLatlon + "</address>";
xmlText=xmlText+"<textWindow><tab><title><![CDATA[*]]></title>";
xmlText=xmlText+"<content><![CDATA[" + selectedTextbox + " ]]></content>";
xmlText=xmlText+"</tab></textWindow>";
if(parseInt(""+selectedIcon+"") > 0) { xmlText=xmlText+"<icon>customicon</icon>"; }
xmlText=xmlText+"</mappoint>";
xmlText=xmlText+"<globalsettings>";
xmlText=xmlText+"<provider>" + selectedProvider + "</provider>";
xmlText=xmlText+"<maptype>" +  selectedType + "</maptype>";
xmlText=xmlText+"<zoom>" +  selectedZoom + "</zoom>";
xmlText=xmlText+"</globalsettings>";
if(parseInt(""+selectedIcon+"") > 0) { 
xmlText=xmlText+"<icons><icon><name>customicon</name><url>http://my.mashupsoft.com/icons/" + selectedIcon +".png</url><height>20</height><width>12</width><shadowUrl>http://my.mashupsoft.com/icons/shadow.png</shadowUrl><shadowHeight>20</shadowHeight><shadowWidth>22</shadowWidth></icon></icons>";
}
xmlText=xmlText+"<controls>";
xmlText=xmlText+"<control name=\"large\"></control>";
xmlText=xmlText+"<control name=\"provider\"><position>bottomleft</position><xoffset>5</xoffset><yoffset>45</yoffset></control>";
xmlText=xmlText+"</controls>";
xmlText=xmlText+"</mashupsoft>";

var newDataFile = XMLnewDocument(xmlText);

// var mapPointTag = document.createElement("mappoint");
// newDataFile.appendChild(mapPointTag);

//var serializer = new XMLSerializer();
//var xml = serializer.serializeToString(newDataFile);
//alert(newDataFile);
mashupsoft_updateMashupWithXmlDom(newDataFile)

// Let the user generate map, activate button 
document.Form4.generatemap.disabled=false;
document.getElementById("plsupdate").innerHTML = "";
}

function XMLnewDocument(xmlString) {
  if (document.implementation && document.implementation.createDocument) {
    var parser=new DOMParser();
    var doc=parser.parseFromString(xmlString,"text/xml");
    return doc;
  } else { // This is the IE way to do it
    // Create an empty document as an ActiveX object
    // If there is no root element, this is all we have to do
    var doc = new ActiveXObject("MSXML2.DOMDocument");
    doc.loadXML(xmlString);
    return doc;
  }
}

function generateMashup() { 
if (document.Form3.stringtextbox.value == 'Customize text box' || document.Form3.stringtextbox.value == '')  { 
 alert('Please update Text Box with a value');
 return false;
}
updateMashup();
document.Form3.stringtextbox.disabled=true;
document.Form3.mapprovider.disabled=true;
document.Form3.maptype.disabled=true;
document.Form3.mapzoom.disabled=true;
document.Form3.mapmarker.disabled=true;
document.Form3.mapupdate.disabled=true;
document.Form2.stringaddress.disabled=true;
document.Form2.geocodebutton.disabled=true;
document.Form4.generatemap.disabled=true;
var d1 = new Date();
var epochdate = parseInt(d1.getTime()/1000);
pars='xml='+xmlText+'&date='+epochdate;
saveMapId(epochdate);
new Ajax.Request('/maps/createlivelink', {
  method: 'get',
  parameters: pars, 
  onSuccess: function(transport){
    var response = transport.responseText || "no response text";
    document.getElementById("mappoints").innerHTML=response;
    // Call load() once again to reset for a new search	
    mCore_resetMapControls();
    load();
    alert("Map point added to your list!\nClick on link, embed or GPX to see your map!");
  },
   onFailure: function(){ } //alert('Something went wrong...')
});
}

function updateMapPoints() { 
 // Updated section with maps
 // Call the server, and get the updated list
 new Ajax.Request('/maps/updatemappoints', {
   method: 'get',
   onSuccess: function(transport){
      var response = transport.responseText || "no response text";
      document.getElementById("mappoints").innerHTML=response;
   },
   onFailure: function(){ } //alert('Something went wrong...')
  });
}

function selectEmbed(id) {
// first set focus
document.getElementById(id).focus();
// select all contents
document.getElementById(id).select();

}

addLoadEvent(load);
addUnloadEvent(GUnload);

