var doScrollLeft = true;
var scrollTimer = null;
var imageTimer = null;
var lastScrollLeft = 0;
var currentMarker = null;
var markersLookup = new Array();

////////////////////////////////////////////////////////////////////////////////
// VantageMarker :
////////////////////////////////////////////////////////////////////////////////
function addVantageMarker(center, title, description, altitude, foreignMarkerID, icon, directions, image) {
  var marker = new VantageMarker(center, title, description, altitude, foreignMarkerID, icon, directions, image);
  markers[marker.id] = marker;
  markersLookup[foreignMarkerID] = marker;
  marker.add()
  return marker;
}

function VantageMarker(position, title, description, altitude, foreignMarkerID, icon, directions, image) {
  Marker.call(this, position, title, description, altitude, foreignMarkerID, icon);
  this.directions = directions;
  this.image = image;
}
derive_Marker(VantageMarker.prototype);

VantageMarker.prototype.getAttributes = function() {
  var attributes = Marker.prototype.getAttributes.call(this);
  // attributes[attributes.length] = new Array('Directions', 'directions', this.directions);
  attributes[attributes.length] = new Array('Image', 'image', this.image, 'image');
  return attributes;
};


VantageMarker.prototype.viewDetails = function() {
  currentMarker = this;
  var pt = this.getPoint();
  var html ="<table class='markerViewDetails' width='410'>";
  var position = "(" + pt.x + "," + pt.y + ")";
  if (this.altitude != -9999)
    position += ' ' + this.altitude + 'm ASL';

  html += "<tr><td class='markerViewLabel'>" + this.title + "</td><tr>";
  if (this.description)
    html += "<tr><td class='markerViewText'>" + this.description + "</td><tr>";
  html += "<tr><td class='markerViewText' align=right>" + position + "</td><tr>";  
  var showImage = isValidURL(this.image)
  if (showImage) {
    html += "<tr><td colspan=2 class='markerViewImage'>";
    html += "<div id='Container'>";
    html += "<div style='display:none;' id='popupImageBox'><img height=200 id='vantageImage' alt='Image Unavailable' title='Click to start & stop scrolling' onscroll='toggleScrolling()' onclick='toggleScrolling()' src='" + this.image + "'></div>";
    html += "<div style='display:none;' id='Loading'><img src='/common/icons/loading.gif' alt='Loading...' height=47 width=48>";
    html += "<div id='div'>";

    html += "</td></tr>";
  }

  html += "</table>";

  this.gmarker.openInfoWindowHtml(html);
  if ((showImage)&&(imageTimer))
    clearTimeout(imageTimer);
  imageTimer = setTimeout("loadImage('" + this.image + "')", 100);  // Wait for loader to exist...
};

function loadImage(url) {
  var loader = document.getElementById('Loading');

  var res = cacheImage(url);
  if (res != 0) {
    var vantageImage = document.getElementById('vantageImage');
    var popupImageBox = document.getElementById('popupImageBox');
    if (loader) 
      loader.style.display = 'none';
  

    vantageImage.src = url;
    if (res == 1) { //((vantageImage.height != 0) && (vantageImage.width != 0)) {
      popupImageBox.style.display = 'block';
      startImageScrolling();
    }

  } else {
    if (loader)
      loader.style.display = 'block';
    imageTimer = setTimeout("loadImage('" + url + "')", 100);
  }
}

function scrollPopup() {
  var ob = document.getElementById('popupImageBox');
  if (!ob)
    return;

  // If we have had a manual scroll, then stop auto scrolling :
  if (lastScrollLeft != ob.scrollLeft) {
    scrollTimer = null;
    return;
  }

  if (doScrollLeft == true) {
    ob.scrollLeft += 1;
    if (ob.scrollLeft+ ob.clientWidth >= ob.scrollWidth) {
      doScrollLeft = false;
    }
  } else {
    ob.scrollLeft -= 1;
    if (ob.scrollLeft <= 0) {
      doScrollLeft = true;
    }
  }
  lastScrollLeft = ob.scrollLeft;
  scrollTimer = setTimeout("scrollPopup()", 30);
}
function toggleScrolling() {
  if (scrollTimer)
    stopImageScrolling();
  else
    startImageScrolling();
}
function startImageScrolling() {
  var ob = document.getElementById('popupImageBox');
  if (!ob)
    return;
  lastScrollLeft = ob.scrollLeft;
  scrollTimer = setTimeout("scrollPopup()", 200);
}

function stopImageScrolling() {
  clearTimeout(scrollTimer);
  scrollTimer = null;
}

////////////////////////////////////////////////////////////////////////////////
// EditableVantageMarker :
////////////////////////////////////////////////////////////////////////////////
function addVantageEditableMarker(center, title, description, altitude, foreignMarkerID, icon, directions, image) {
  var marker = new VantageEditableMarker(center, title, description, altitude, foreignMarkerID, icon, directions, image);
  markers[marker.id] = marker;
  marker.add()
  return marker;
}

function VantageEditableMarker(position, title, description, altitude, foreignMarkerID, icon, directions, image) {
  EditableMarker.call(this, position, title, description, altitude, foreignMarkerID, icon);
  this.directions = directions;
  this.image = image;
  this.updateMethod = "updateVantageMarkerData(" + this.id + ")";

}

derive_EditableMarker(VantageEditableMarker.prototype);

VantageEditableMarker.prototype.getAttributes = function() {
  var attributes = EditableMarker.prototype.getAttributes.call(this);
  attributes[attributes.length] = new Array('Directions', 'directions', this.directions, 'custom', '', createDirectionSelector);
  attributes[attributes.length] = new Array('Image', 'image', this.image, 'image');
  return attributes;
};


VantageEditableMarker.prototype.edit = function(title, description, latitude, longitude, altitude, directions, image) {
  // Change details for this marker   
  var pt = this.getPoint();
  this.title = title;
  this.description = description;
  this.altitude = altitude;

  if ((latitude != pt.y) || (longitude != pt.x)) {
    this.setPoint(new GLatLng(latitude, longitude));
  }
  this.status = MARKER_STATUS_MODIFIED;


  this.directions = directions;
  this.image = image;


  this.saveMarkerData();
}

VantageEditableMarker.prototype.saveMarkerData = function() {
  // Save via http the data for this marker.

  var url = baseURL;
  var marker = this;
  if (this.foreignMarkerID == -1) {
    url += 'addMarker?'
  } else {
    url += 'editMarker?markerID:int=' + this.foreignMarkerID + '&';
  }
  var pt = this.getPoint();
  var title = encodeURIComponent(this.title);
  var description = encodeURIComponent(this.description);
  var latitude = pt.y;
  var longitude = pt.x;
  var altitude = this.altitude;
  var directions = this.directions;
  var image = encodeURIComponent(this.image);

  url += 'title=' + title + '&description=' + description + '&latitude:float=' + latitude + '&longitude:float=' + longitude + '&altitude:float=' + altitude + '&directions=' + directions + '&image=' + image;

  var res = webRequest(url, username, password, false, function (res) {marker.saveMarkerDataResults(res);});
};


VantageEditableMarker.prototype.saveMarkerDataResults = function(res) {
  if ((!res) || (res.nodeName != 'markers')) {
    window.alert('Results invalid : ' + res);
    return;
  }

  var count = 0;
  for (var i=0; i < res.childNodes.length; i++) {
    var r = res.childNodes[i];
    if (r.nodeType == 1) { // Object.
      if (count > 0) {
	window.alert('ERROR :Too many results from save of one object');
	return;
      }
      count += 1;
      this.foreignMarkerID = r.getAttribute('id');
      this.title = r.getAttribute('title');
      this.description = r.getAttribute('description');
      this.latitude = parseFloat(r.getAttribute('latitude'));
      this.longitude = parseFloat(r.getAttribute('longitude'));
      this.setPoint(new GLatLng(this.latitude, this.longitude));
      this.altitude = parseFloat(r.getAttribute('altitude'));
      this.directions = r.getAttribute('directions');
      this.image = r.getAttribute('image');

      var customVantageIcon = vantageIcon;
      var iconURL = r.getAttribute('icon_url');
      var shadowURL = r.getAttribute('shadow_url');
      if (iconURL && shadowURL) {
	customVantageIcon = new GIcon(vantageIcon);
	customVantageIcon.image =  iconURL;
	customVantageIcon.shadow = shadowURL;
      }
      this.properties = {draggable: true, title: this.title, icon: customVantageIcon, bouncy:false, dragCrossMove:false};
      this.recreate();
    }
  }
}
function updateVantageMarkerData(id) {
  
  var title = document.getElementById('edit_title').value;
  if (title == '') {
    window.alert('You must at least enter a title for this marker.');
    return;
  }

  var description = document.getElementById('edit_description').value;
  var latitude = parseFloat(document.getElementById('edit_latitude').value);
  var longitude = parseFloat(document.getElementById('edit_longitude').value);
  var altitude = parseFloat(document.getElementById('edit_altitude').value);

  var directions = document.getElementById('edit_directions').value;
  var image = document.getElementById('edit_image').value;

  var marker = markers[id];

  var doRecreateMarker = false;
  if (marker.title != title)
    doRecreateMarker = true;

  marker.edit(title, description, latitude, longitude, altitude, directions, image);
  map.closeInfoWindow();
  
  if (doRecreateMarker) 
    marker.recreate() //Marker(id); // For some reason this needs to be done separate, when the info window is closed...

}

var directionSelectorRadius = 32;
var baseDirectionSelectorImg = '/vantage_markers/selectorImage?imageRadius:int=' + directionSelectorRadius + '&directions=';
function createDirectionSelector(value) {
  currentAngles = value;
  html = "<table border=0 cellpadding=0 cellspacing=0><tr>";
  html += "<td><map name='selector_map'><area href='' shape='circle' coords='" + directionSelectorRadius + "," + directionSelectorRadius + "," + directionSelectorRadius + "' onclick='selectDirection(event); return false;'></map><img id='directionSelector' src='" + baseDirectionSelectorImg + currentAngles + "' border=0 usemap='#selector_map'></td>\n";
  html += "<td class='markerEditNotes'>Select angles starting from the top and working<br> in a clockwise direction.  Click reset to start again.<br><a href='' onclick='resetDirections();return false;'>Reset</a></td></tr>\n";
  html += "<tr><td colspan=2><input id='edit_directions' type='text' name='directions' value='" + currentAngles + "'></td></tr></table>\n";
  return html;
}

////////////////////////////////////////////////////////////////////////////////
// Direction Selector Methods, used in the popup :
////////////////////////////////////////////////////////////////////////////////
var currentAngles = '';
function selectDirection(event) {
      var target = event.target; // Firefox
      if (!target)
	target = event.srcElement; // IE
      var offsets = findPos(target);

      var x = event.clientX - offsets[0] - directionSelectorRadius;
      var y = -(event.clientY - offsets[1] - directionSelectorRadius);

      //var x = event.clientX - ob.offsetLeft - directionSelectorRadius;
      //var y = -(event.clientY - ob.offsetTop - directionSelectorRadius);
      var angle = Math.round(Math.atan2(x, y)*57.2957795);
      if (angle <0) angle += 360;

      currentAngles = currentAngles?(currentAngles + ',' + angle):angle;

      var ob = document.getElementById('directionSelector');
      ob.src = baseDirectionSelectorImg + currentAngles;
      ob = document.getElementById('edit_directions');
      ob.value = currentAngles;
}
function resetDirections() {
      currentAngles = '';
      var ob = document.getElementById('directionSelector');
      ob.src = baseDirectionSelectorImg + currentAngles;
      ob = document.getElementById('edit_directions');
      ob.value = currentAngles;
}

