var map;
var path;
  	  
//==========================================
//================ logic ===================

function dropMarker(id) {
  var marker;
  if (marker = markers.getMarkerById(id)) {
    markers.deleteMarker(marker);
    marker.destroy();
  }
  for(i=0;i<markers.length;i++) {
    markers[i].setNum(i+1);
  }
  if (window.event) {
    window.event.returnValue = false;
    window.event.cancelBubble = true;
  }
  return(false);
}

function showInfo(id) {
  var marker;
  if (marker = markers.getMarkerById(id)) {
    marker.showInfo();
  }
  if (window.event) {
    window.event.returnValue = false;
    window.event.cancelBubble = true;
  }
  return(false);
}


function findAddress() {
  var elem = document.getElementById("txtDestination");
  if (elem && elem.value) {
    var geo = new GClientGeocoder();

    var reasons=[];
    reasons[G_GEO_SUCCESS]            = "Success";
    reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
    reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
    reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
    reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
    reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
    reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";

    document.getElementById("btnGo").value="Searching...";
    document.getElementById("btnGo").disabled=true;

    geo.getLocations(elem.value, function (result) { 
      // If that was successful
      if (result.Status.code == G_GEO_SUCCESS) {
        // How many resuts were found
        if (result.Placemark.length > 1) alert("More then one geographic location found, the first is used.");
        // Loop through the results, placing markers
        for (var i=0; i<result.Placemark.length; i++) {
          var p = result.Placemark[0].Point.coordinates;
          markers.addMarker(0,markers.length+1,'','','','',p[1],p[0]);
          markers[markers.length-1].showForm();
          map.panTo(new GLatLng(p[1],p[0]));
        }
      }
      // ====== Decode the error status ======
      else {
        var reason="Code "+result.Status.code;
        if (reasons[result.Status.code]) {
          reason = reasons[result.Status.code]
        } 
        alert('Could not find "'+elem.value+ '" ' + reason);
      }
      document.getElementById("btnGo").value="Go";
      document.getElementById("btnGo").disabled=false;
    });
  }
}

function forgot() {
  var elem = document.getElementById("txtEmail");
  if (elem && elem.value) {
    open('travelmap.php?action=forgot&email='+encodeURI(elem.value),'_blank','directories=0,height=150,width=400,location=0,menubar=0,status=0,toolbar=0');
  } else alert('Please enter your EmailID first');
  if (window.event) {
    window.event.returnValue = false;
    window.event.cancelBubble = true;
  }
  return(false);
}

function saveMapState() {
  var center = map.getCenter();
  document.getElementById("map_center_lat").value = center.lat();
  document.getElementById("map_center_lng").value = center.lng();
  document.getElementById("map_zoom").value = map.getZoom();
  return(true);
}

//============= markers Array ==============
var markers = new Array();
var lastId = 1;

Array.prototype.getMarkerById = function(id) {
  for(i=0;i<this.length;i++) {
    if (this[i].id == id) {
      return(this[i]);
    }
  }
  return(false);
}

Array.prototype.deleteMarker = function(marker) {
  for(i=0;i<this.length;i++) {
    if (this[i] == marker) {
      markers.splice(i,1);
      return(true);
    }
  }
  if (path) this.drawPath();
  return(false);
}

Array.prototype.addMarker = function(id,num,ShortTitleDesc,DateFrom,DateTo,TextDesc,x,y,inactive) {
  var marker = new Marker(new GLatLng(x,y),(this.length+1),inactive);
  if (id) {
    marker.id = id;
    marker.overlay.markerId = id;
  }
  marker.setNum(num);
  marker.ShortTitleDesc = ShortTitleDesc;
  marker.DateFrom = DateFrom;
  marker.DateTo = DateTo;
  marker.TextDesc = TextDesc;
  this[this.length] = marker;
  return(true);
}

Array.prototype.drawPath = function() {
  if (path) map.removeOverlay(path);
  var points = [];
  for(i=0;i<this.length;i++) {
    points[i] = new GLatLng(this[i].lat,this[i].lng);
  }
  path = new GPolyline(points, '#3b27cf', 4, 0.5);
  map.addOverlay(path);
  return(true);
}

//============== Marker class ==============
function Marker(point, num, inactive) {
  this.lat = point.lat();
  this.lng = point.lng();
  this.id = lastId++;
  this.num = num;

  this.ShortTitleDesc = '';
  this.DateFrom = '';
  this.DateTo = '';
  this.TextDesc= '';

  this.overlay = new GMarker(point);
  this.overlay.markerId = this.id;
  map.addOverlay(this.overlay);

  var lbl = new ELabel(point,this.num,"marker_num",new GSize(-3*(""+this.num).length,-19));
  map.addOverlay(lbl);
  this.lbl = lbl;
  
  if (! inactive) {
    GEvent.addListener(this.overlay, "dblclick", function() {
      dropMarker(this.markerId);
    });
  }
}

Marker.prototype.getBlockHtml = function() {
  var html = block_html;
  for(prop in this) {
    if ((typeof(this[prop]) == 'number') || (typeof(this[prop]) == 'string')) {
      var re = new RegExp("this_"+prop,"ig");
      html = html.replace(re,this[prop]);
    }
  }
  return(html);
}

Marker.prototype.showForm = function() {
  var blocks = document.getElementById('blocks');
  var block = document.getElementById('block_'+this.id);
  if (!block) {
    block = document.createElement("DIV");
    block.id = 'block_'+this.id;
    block.style.border = 'solid 1px black';
    block.style.width = '100%';
    block.style.marginBottom = '10px';
    block.innerHTML = this.getBlockHtml();
    blocks.appendChild(block);
  } else {
  }
}

Marker.prototype.showInfo = function() {
  this.overlay.openInfoWindowHtml(this.TextDesc,{maxWidth:200});
}

Marker.prototype.setNum = function(num) {
  this.num = num;
  this.lbl.setContents(num);
  var elem = document.getElementById('num_'+this.id);
  if (elem) elem.innerHTML = this.num;
  if (elem = document.getElementById('Number_'+this.id)) elem.value = this.num;
}

Marker.prototype.destroy = function() {
  map.removeOverlay(this.lbl);
  map.removeOverlay(this.overlay);
  var block = document.getElementById('block_'+this.id);
  if (block) {
    block.parentNode.removeChild(block);
  }
}


//================= ELabel ========================


function ELabel(point, html, classname, pixelOffset, percentOpacity, overlap) {
  // Mandatory parameters
  this.point = point;
  this.html = html;
  
  // Optional parameters
  this.classname = classname||"";
  this.pixelOffset = pixelOffset||new GSize(0,0);
  if (percentOpacity) {
    if(percentOpacity<0){percentOpacity=0;}
    if(percentOpacity>100){percentOpacity=100;}
  }
  this.percentOpacity = percentOpacity;
  this.overlap=overlap||false;
} 

ELabel.prototype = new GOverlay();

ELabel.prototype.initialize = function(map) {
  var div = document.createElement("div");
  div.style.position = "absolute";
  div.innerHTML = '<div class="' + this.classname + '">' + this.html + '</div>' ;
  map.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(div);
  this.map_ = map;
  this.div_ = div;
  if (this.percentOpacity) {        
    if(typeof(div.style.filter)=='string'){div.style.filter='alpha(opacity:'+this.percentOpacity+')';}
    if(typeof(div.style.KHTMLOpacity)=='string'){div.style.KHTMLOpacity=this.percentOpacity/100;}
    if(typeof(div.style.MozOpacity)=='string'){div.style.MozOpacity=this.percentOpacity/100;}
    if(typeof(div.style.opacity)=='string'){div.style.opacity=this.percentOpacity/100;}
  }
  if (this.overlap) {
    var z = GOverlay.getZIndex(this.point.lat());
    this.div_.style.zIndex = z;
  }
}

ELabel.prototype.remove = function() {
  this.div_.parentNode.removeChild(this.div_);
}

ELabel.prototype.copy = function() {
  return new ELabel(this.point, this.html, this.classname, this.pixelOffset, this.percentOpacity, this.overlap);
}

ELabel.prototype.redraw = function(force) {
  var p = this.map_.fromLatLngToDivPixel(this.point);
  var h = parseInt(this.div_.clientHeight);
  this.div_.style.left = (p.x + this.pixelOffset.width) + "px";
  this.div_.style.top = (p.y +this.pixelOffset.height - h) + "px";
}

ELabel.prototype.show = function() {
  this.div_.style.display="";
}

ELabel.prototype.hide = function() {
  this.div_.style.display="none";
}

ELabel.prototype.setContents = function(html) {
  this.html = html;
  this.div_.innerHTML = '<div class="' + this.classname + '">' + this.html + '</div>' ;
  this.redraw(true);
}

ELabel.prototype.setPoint = function(point) {
  this.point = point;
  if (this.overlap) {
    var z = GOverlay.getZIndex(this.point.lat());
    this.div_.style.zIndex = z;
  }
  this.redraw(true);
}

ELabel.prototype.setOpacity = function(percentOpacity) {
  if (percentOpacity) {
    if(percentOpacity<0){percentOpacity=0;}
    if(percentOpacity>100){percentOpacity=100;}
  }        
  this.percentOpacity = percentOpacity;
  if (this.percentOpacity) {        
    if(typeof(this.div_.style.filter)=='string'){this.div_.style.filter='alpha(opacity:'+this.percentOpacity+')';}
    if(typeof(this.div_.style.KHTMLOpacity)=='string'){this.div_.style.KHTMLOpacity=this.percentOpacity/100;}
    if(typeof(this.div_.style.MozOpacity)=='string'){this.div_.style.MozOpacity=this.percentOpacity/100;}
    if(typeof(this.div_.style.opacity)=='string'){this.div_.style.opacity=this.percentOpacity/100;}
  }
}

ELabel.prototype.getPoint = function() {
  return this.point;
}
ELabel.prototype.U = function() {
  return this.point;
}
ELabel.prototype.V = function() {
  return this.point;
}
ELabel.prototype.W = function() {
  return this.point;
}
ELabel.prototype.X = function() {
  return this.point;
}
ELabel.prototype.Y = function() {
  return this.point;
}
ELabel.prototype.Z = function() {
  return this.point;
}
