
function newNode(txt) {
  return document.createElement(txt);
}

var ZMC_inited = false;
var ZM_icns = 0;
var ZM_imgs = {};
var ZM_LocTypes = {0: gettext("Address"), 1: gettext("GeoTag"), 2: gettext("Tag"), 3:gettext("Latitude/Longitude"), 4: gettext("Airport")};
var ZM_ainput_names = [gettext("Jump to an Address, Airport Code or Place...") , gettext("SmartFilter by Labels...") ];

//Zooomr Map Types
ZM_MICRODIV_TYPE = 0;
ZM_REGDIV_TYPE = 1;

//Zooomr Map Social View Control
function ZMSVControl() {}

//Zooomr Map Tag Coder Control
function ZMCControl() {}

//Zooomr Map Record Control
function ZMRControl() {}

function ZMCStarter() {

  ZMCControl.prototype = new GControl(false,true);
  ZMCControl.prototype.initialize = function(map) {  
    var container = newNode("div");
        container.className = 'tagmap_jump_container';
    
    //Tag / Address Selector
    var radio_container = newNode("div");
        radio_container.style.display = 'none';

    var ainput_indicator = newNode("img");
        ainput_indicator.src = "http://assets2.zooomr.com/images/tidbits/refresh.gif";
        ainput_indicator.style.width = '16px';
        ainput_indicator.style.height = '16px';
        ainput_indicator.style.display = 'none';

    container.appendChild(ainput_indicator);

    var jump_radio = newNode("input");
        jump_radio.setAttribute('type','radio');
        jump_radio.setAttribute('name','lookup_typ');
        jump_radio.setAttribute('value','tag');
        jump_radio.checked = true;

    radio_container.appendChild(jump_radio);
    
    radio_container.appendChild(document.createTextNode(' Jump '));
    
    var refine_radio = newNode("input");
        refine_radio.setAttribute('type','radio');
        refine_radio.setAttribute('name','lookup_typ');
        refine_radio.setAttribute('value','addr');

    radio_container.appendChild(refine_radio);
    radio_container.appendChild(document.createTextNode(' SmartFilter '));

    //SmartFilter Area
    map._ZMap._sr_infoarea = newNode("div");

    var clear_link = newNode("a");
        clear_link.href = "javascript:void(0);"
        clear_link.innerHTML = 'Clear SmartFilter?';
        clear_link.className = "yellowlink";
        clear_link.style.display = 'none';
        clear_link.style.position = 'absolute';
        clear_link.style.right = '10px';
        
        clear_link.onclick = function () {
                                          map._ZMap._sr_infoarea.innerHTML = '';
                                          map._ZMap._opts.SmartFilter_data = '';
                                          map._ZMap.redraw();
                                          map._ZMap._ainput.value = ZM_ainput_names[1];
                                          map._ZMap._ainput.style.color = '#999';
                                          clear_link.style.display = 'none';
                                         }

    radio_container.appendChild(clear_link);

    container.appendChild(radio_container);

    //The actual input
    map._ZMap._ainput = newNode("input");
    map._ZMap._ainput.style.color = '#999';
    map._ZMap._ainput.style.fontSize = '13px';
    map._ZMap._ainput.style.fontWeight = 'bold';
    map._ZMap._ainput.style.width = '350px';

    map._ZMap._ainput.style.padding = '2px';
    map._ZMap._ainput.style.margin = '5px 0';
    
    map._ZMap._ainput.style.borderTop = '1px solid #000';
    map._ZMap._ainput.style.borderLeft = '1px solid #000';
    map._ZMap._ainput.style.borderRight = '1px solid #ccc';
    map._ZMap._ainput.style.borderBottom = '1px solid #ccc';
    
    map._ZMap._ainput.setAttribute('type','text');
    map._ZMap._ainput.setAttribute('name','geocode_input');
    map._ZMap._ainput.setAttribute('value',ZM_ainput_names[0]);
    
    container.appendChild(map._ZMap._ainput);

    container.appendChild(map._ZMap._sr_infoarea);

    //Saved Area
    var saved_infoarea = newNode("div");

    container.appendChild(saved_infoarea);

//    this.setButtonStyle_(container);

//    var green = newNode("div");
//    var blue = newNode("div");

    map.getContainer().appendChild(container);

    Event.observe(map._ZMap._ainput, 'focus', function(){map._ZMap._ainput.style.color = '#000';
                                              if (map._ZMap._ainput.value == (jump_radio.checked ? ZM_ainput_names[0] : ZM_ainput_names[1] )) {
                                                map._ZMap._ainput.value = '';
                                              }else if (map._ZMap._ainput.value.indexOf('@::') == 0) { //Looks like we've got a new cord
                                                      var the_split = map._ZMap._ainput.value.split('::');
                                                      var jData = json_parse(the_split[1]);

                                                      map._ZMap._ainput.value = jData.loc_code;
                                                      
                                                      if (map._zpoint_marker !== undefined) {
                                                        map.removeOverlay(map._zpoint_marker);
                                                        delete map._zpoint_marker;
                                                      }
                                                      
                                                      if (jump_radio.checked) {
                                                        var point = new GLatLng(jData.lat,jData.lon);

                                                        map.setCenter(point,(jData.zoom_lvl == -1 ? map.getZoom() : jData.zoom_lvl));
  
                                                        if (jData.loctyp != 2) {
                                                          if (map._zpoint_marker !== undefined) { map.removeOverlay(map._zpoint_marker); }
                                                          map._zpoint_marker = map._ZMap.buildZPointMarker(point,jData);
                                                          map._ZMap.redraw(function() { map._ZMap.ZPointMarkerHandler(map._zpoint_marker,false);});
                                                        } else {    
                                                          map._ZMap.redraw();
                                                        }

                                                      } else {
                                                        map._ZMap._sr_infoarea.innerHTML = '<h4 style="margin:0;">SmartRefining for photos tagged with &quot;' + jData.loc_code + '&quot;.</h4>';
                                                        map._ZMap._opts.SmartFilter_data = jData.loc_code;
                                                        map._ZMap.redraw(function() { clear_link.style.display = 'inline';});
                                                        
                                                        map._ZMap._ainput.blur();
                                                        
                                                        
                                                      }

                                              }}, false);

    Event.observe(map._ZMap._ainput, 'keyup', function(oEvent){ if (oEvent.keyCode == 13 && map._ZMap._ainput.value.indexOf('@::') == 0) {
                                                      var the_split = map._ZMap._ainput.value.split('::');
                                                      var jData = json_parse(the_split[1]);
                                                      map._ZMap._ainput.value = jData.loc_code;
                                                      
                                                      if (map._zpoint_marker !== undefined) {
                                                        map.removeOverlay(map._zpoint_marker);
                                                        delete map._zpoint_marker;
                                                      }
                                                      
                                                      if (jump_radio.checked) {
                                                        var point = new GLatLng(jData.lat,jData.lon);

                                                        map.setCenter(point,(jData.zoom_lvl == -1 ? map.getZoom() : jData.zoom_lvl));
  
  
                                                        if (jData.loctype != 2) {
                                                          map._zpoint_marker = map._ZMap.buildZPointMarker(point,jData);
                                                          map._ZMap.redraw(function() { map._ZMap.ZPointMarkerHandler(map._zpoint_marker,false);});
                                                        } else {    
                                                          map._ZMap.redraw();
                                                        }

                                                      } else {
                                                        map._ZMap._sr_infoarea.innerHTML = '<h4 style="margin:0;">SmartRefining for photos tagged with &quot;' + jData.loc_code + '&quot;.</h4>';
                                                        map._ZMap._opts.SmartFilter_data = jData.loc_code;
                                                        map._ZMap.redraw(function() { clear_link.style.display = 'inline';});
                                                        
                                                        map._ZMap._ainput.blur();
                                                        
                                                        
                                                      }
                                                    }}, false);

    Event.observe(map._ZMap._ainput, 'blur', function(){if (map._ZMap._ainput.value == '') {map._ZMap._ainput.style.color = '#999'; map._ZMap._ainput.value = (jump_radio.checked ? ZM_ainput_names[0] : ZM_ainput_names[1] );}}, false);
    
    var the_gogetter = new Ajax.Autocompleter(map._ZMap._ainput, 'auto_complete_area', '/z/geocodelist/', {frequency:1.2,indicator:ainput_indicator});

    Event.observe(jump_radio, 'click', function(){ map._ZMap._ainput.style.color = '#999'; map._ZMap._ainput.value = ZM_ainput_names[0]; the_gogetter.url = '/z/geocodelist/'; }, false);

    Event.observe(refine_radio, 'click', function(){ if (map._ZMap._opts.SmartFilter_data == '') { map._ZMap._ainput.style.color = '#999'; map._ZMap._ainput.value = ZM_ainput_names[1]; } else { map._ZMap._ainput.style.color = '#000'; map._ZMap._ainput.value = map._ZMap._opts.SmartFilter_data; } the_gogetter.url = '/z/geocodelist/'; }, false);


    return container;
  }
  
  // By default, the control will appear in the top left corner of the
  // map with 7 pixels of padding.
  ZMCControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(100, -3));
  }


  ZMSVControl.prototype = new GControl();
  ZMSVControl.prototype.initialize = function(map) {  
    var container = newNode("div");
    
    //Go Red!
    var redDiv = newNode("div");
        redDiv.style.display = 'inline';
    
    if (map._ZMSCRed == true) {
      var redIcon = ZM_imgs['sc']['r']['c'];
    }else{
      var redIcon = ZM_imgs['sc']['r']['o'];
    }
    
    redDiv.appendChild(redIcon);
    
    GEvent.addDomListener(redDiv, "click", function() {
      redDiv.innerHTML = '';
      if (map._ZMSCRed == true) {
        var redIcon = ZM_imgs['sc']['r']['o'];
        map._ZMSCRed = false;
      }else{
        var redIcon = ZM_imgs['sc']['r']['c'];
        map._ZMSCRed = true;
      }
      redDiv.appendChild(redIcon);
      map._ZMap.redraw();
    });

    container.appendChild(redDiv);

    //Go Green!
    var greenDiv = newNode("div");
        greenDiv.style.display = 'inline';
        
    if (map._ZMSCGreen == true) {
      var greenIcon = ZM_imgs['sc']['g']['c'];
    }else{
      var greenIcon = ZM_imgs['sc']['g']['o'];
    }
    
    greenDiv.appendChild(greenIcon);
    
    GEvent.addDomListener(greenDiv, "click", function() {
      greenDiv.innerHTML = '';
      if (map._ZMSCGreen == true) {
        var greenIcon = ZM_imgs['sc']['g']['o'];
        map._ZMSCGreen = false;
      }else{
        var greenIcon = ZM_imgs['sc']['g']['c'];
        map._ZMSCGreen = true;
      }
      greenDiv.appendChild(greenIcon);
      map._ZMap.redraw();
    });

    container.appendChild(greenDiv);

    //Go Blue!
    var blueDiv = newNode("div");
        blueDiv.style.display = 'inline';
        
    if (map._ZMSCBlue == true) {
      var blueIcon = ZM_imgs['sc']['b']['c'];
    }else{
      var blueIcon = ZM_imgs['sc']['b']['o'];
    }
    
    blueDiv.appendChild(blueIcon);
    
    GEvent.addDomListener(blueDiv, "click", function() {
      blueDiv.innerHTML = '';
      if (map._ZMSCBlue == true) {
        var blueIcon = ZM_imgs['sc']['b']['o'];
        map._ZMSCBlue = false;
      }else{
        var blueIcon = ZM_imgs['sc']['b']['c'];
        map._ZMSCBlue = true;
      }
      blueDiv.appendChild(blueIcon);
      map._ZMap.redraw();
    });

    container.appendChild(blueDiv);

    this.setButtonStyle_(container);

//    var green = newNode("div");
//    var blue = newNode("div");

    map.getContainer().appendChild(container);
    return container;
  }
  
  // By default, the control will appear in the top left corner of the
  // map with 7 pixels of padding.
  ZMSVControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 28));
  }
  
  // Sets the proper CSS for the given button element.
  ZMSVControl.prototype.setButtonStyle_ = function(button) {
    button.style.backgroundColor = "white";
    button.style.border = "1px solid black";
    button.style.textAlign = "center";
    button.style.width = "66px";
    button.style.cursor = "pointer";
  }

  //ZMap Record Control

  ZMRControl.prototype = new GControl();
  ZMRControl.prototype.initialize = function(map) {  
    var container = newNode("div");

    var innerContainer = newNode("div");
        innerContainer.style.borderStyle = 'solid';
        innerContainer.style.borderColor = '#fff #B0B0B0 #B0B0B0 #fff';
        innerContainer.style.borderWidth = '1px';
        innerContainer.style.fontSize = '12px';

        this.setRecordStyle_(innerContainer,!map._ZMRecording);
    var self = this;

    map._ZMap.recControlStyler = function(rState) {self.setRecordStyle_(innerContainer,rState);}

    GEvent.addDomListener(container, "click", function() {
      self.setRecordStyle_(innerContainer,map._ZMRecording);
      if (map._ZMRecording == true) {
        map._ZMRecording = false;
        map._ZMap.updateInfoBar(0);
      } else {
        map._ZMRecording = true;
        map.clearOverlays();
        map._ZMap.updateInfoBar(1, gettext("Select a point on the map to start GeoTagging Photos.") );
      }
      map._ZMap.redraw();
    });
  
    container.appendChild(innerContainer);
    this.setButtonStyle_(container);

//    var green = newNode("div");
//    var blue = newNode("div");

    map.getContainer().appendChild(container);
    return container;
  }
  
  // By default, the control will appear in the top left corner of the
  // map with 7 pixels of padding.
  ZMRControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(79, 28));
  }

  // Sets the proper CSS for the given record button element.
  ZMRControl.prototype.setRecordStyle_ = function(button,recording) {
    button.innerHTML = '';
    if (recording == true) {
      button.style.borderColor = '#fff #B0B0B0 #B0B0B0 #fff';
      button.style.fontWeight = '';
      button.appendChild(ZM_imgs['rec']['start']);        
      button.appendChild(document.createTextNode( ' ' + gettext("Start GeoTagging") ));
    } else {
      button.style.borderColor = '#B0B0B0 #fff #fff #B0B0B0';
      button.style.fontWeight = 'bold';
      button.appendChild(ZM_imgs['rec']['stop']);        
      button.appendChild(document.createTextNode(' Stop GeoTagging'));
    }
  }
  
  // Sets the proper CSS for the given button element.
  ZMRControl.prototype.setButtonStyle_ = function(button) {
    button.style.backgroundColor = "white";
    button.style.border = "1px solid black";
    button.style.textAlign = "center";
    button.style.cursor = "pointer";
    button.style.fontFamily = 'Arial,sans-serif';
    button.style.fontSize = 'small';
    button.style.width = '138px';
    button.style.whiteSpace = 'nowrap';
  }


}
//Zooomr Map

function ZMap(container, type, loc, opts) {
  this._container = container;
  this._mtype = type;
  this._loc = loc;
  this._opts = opts || {};
  this.ov_moving = false;
  this.in_drag = false;
  this.iw_open = false;
  this.point_keys = {};

  //Check for all required options
  if (this._opts.maxitems == undefined) this._opts.maxitems = 9;
  if (this._opts.viewbarwidth == undefined) this._opts.viewbarwidth = 50;
  if (this._opts.height == undefined) this._opts.height = 513;
  if (this._opts.width == undefined) this._opts.width = 750;
  if (this._opts.cripple == undefined) this._opts.cripple = false;
  if (this._opts.limitList == undefined) this._opts.limitList = [];
  if (this._opts.SmartFilter_data == undefined) this._opts.SmartFilter_data = '';
  if (this._opts.display_size == undefined) this._opts.display_size = 0;


  if (this._mtype == ZM_MICRODIV_TYPE) {
    this._opts.viewbarwidth = 0;
    this._opts.maxitems = 0;
  }
}

ZMap.prototype.init = function(doRedraw) {

  if (ZM_icns == 0) {
    ZM_icns = {};
    this.loadIcons();
  }

  if (ZMC_inited == false) {ZMCStarter();ZMC_inited = true;}

  this._container.style.width = this._opts.width + 'px';
  this._container.style.height = this._opts.height + 'px';
  this._container.style.overflow = 'hidden';

  ZM_imgs['nodata'].style.marginTop = Math.floor(this._opts.height / 2.0) + "px";
    
  if (!doRedraw) this._container.innerHTML = '';
  var infoDivHeight = 45;
  if (this._mtype != ZM_MICRODIV_TYPE) {
    if (!doRedraw) this._infoheader = newNode('div');
    this._infoheader.style.width = (this._opts.width - 20) + 'px';
    this._infoheader.style.textAlign = 'left';
    this._infoheader.style.padding = '0 10px';
    this._infoheader.style.background = '#163869';
    this._infoheader.style.color = '#eee';
    this._infoheader.style.height = infoDivHeight + 'px';
    this._infoheader.innerHTML = '<span style="font-weight:bold;font-size:35px;">' + gettext("The World through Photos") + '</span>';
    if (!doRedraw) this._container.appendChild(this._infoheader);
  } else{
    infoDivHeight = 0;
  }

  // create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
	if (!doRedraw) this.overlayDiv = newNode("div");
  this.overlayDiv.className = 'overlay';
  this.overlayDiv.style.display = 'none';
  this.overlayDiv.style.position = 'absolute';
  this.overlayDiv.style.textAlign = 'center';
  this.overlayDiv.style.zIndex = '900';
  this.overlayDiv.style.width = this._opts.width + 'px';
  this.overlayDiv.style.height = (this._opts.height-infoDivHeight-1) + 'px';

  // create PixChooser
	if (!doRedraw) this.pixChooser = newNode("div");
  this.pixChooser.className = 'pixchooser';
  this.pixChooser.style.margin = 'auto';
  this.pixChooser.style.marginTop = '50px';
  this.pixChooser.style.width = '700px';
  this.pixChooser.style.height = '345px';

//  var alphaDiv = newNode('div');
//      alphaDiv.setAttribute('class','alpha-shadow');

  if (!doRedraw) this.overlayDiv.appendChild(this.pixChooser);
  if (!doRedraw) this._container.appendChild(this.overlayDiv);


  if (!doRedraw) this._mapdiv = newNode('div');
  this._mapdiv.style.width = (this._opts.width - this._opts.viewbarwidth) + 'px';
  this._mapdiv.style.height = (this._opts.height-infoDivHeight) + 'px';
  this._mapdiv.style.overflow = 'hidden';

  if (!doRedraw) this._container.appendChild(this._mapdiv);

 
  if (!doRedraw) this._viewbar = newNode('div');
  this._viewbar.style.margin = '0 0 0 '+(this._opts.width - this._opts.viewbarwidth)+'px';
  this._viewbar.style.height = (this._opts.height-infoDivHeight-1) + 'px';
  this._viewbar.style.width = this._opts.viewbarwidth+'px';
  this._viewbar.style.backgroundColor = '#f1f1f1';
  this._viewbar.style.textAlign = 'center';
  if (this._mtype == ZM_MICRODIV_TYPE) {   
    this._viewbar.style.display = 'none';
  }

  if (!doRedraw) this._container.appendChild(this._viewbar);

  if (doRedraw) {
    if (this._gmap) this._gmap.checkResize();
    return;
  }

  if (this._opts.width < 300) {
    var gmap_options = {mapTypes:[G_NORMAL_MAP,G_SATELLITE_MAP]};
  } else {
    var gmap_options = {mapTypes:G_DEFAULT_MAP_TYPES};
  }

  this._gmap = new GMap2(this._mapdiv,gmap_options);

  this._gmap._ZMap = this;

//  if (this._opts.cripple == true) {
//    this._gmap.disableDragging();
//  }  

  this._gmap.enableContinuousZoom();
  this._gmap.enableDoubleClickZoom();

  //Set-up social view markers
  this._gmap._ZMSCRed = true;
  this._gmap._ZMSCGreen = true;
  this._gmap._ZMSCBlue = true;

  //Set-up tag record state markers
  this._gmap._ZMRecording = false;

  //Photos to record
  this.recPool = [];
  this._recState = 0;
  this.recControlStyler = 0;
  
  if (this._opts.height > 150) {
    if (this._mtype == ZM_MICRODIV_TYPE) {
      this._gmap.addControl(new GSmallMapControl());
    }else if (this._mtype == ZM_REGDIV_TYPE) {
      this._gmap.addControl(new GLargeMapControl());
      /* var GOMC = new GOverviewMapControl();
      this._gmap.addControl(GOMC);
      var tthis = this;
      GEvent.addListener(GOMC.getOverviewMap(), "mouseover", function() {
        tthis.ov_moving = true;
      });
      GEvent.addListener(GOMC.getOverviewMap(), "mouseout", function() {
        tthis.ov_moving = false;
      });
      */

      GEvent.addListener(this._gmap, "click", function(marker, point) {
        if (tthis._gmap._ZMRecording && point) {
          tthis._gmap.clearOverlays();
          tthis._viewbar.innerHTML = '';
          var the_marker = new GMarker(point,{"icon":ZM_icns['rec']});
          tthis._gmap.addOverlay(the_marker);
          tthis._gmap.panTo(point);
          tthis.buildPixChooser();
        } else if (point) {
          
          /* if (tthis._gmap._zpoint_marker !== undefined) { tthis._gmap.removeOverlay(tthis._gmap._zpoint_marker); }
          
          tthis._gmap._zpoint_marker = tthis.buildZPointMarker(point,{});
          tthis._gmap.addOverlay(tthis._gmap._zpoint_marker);
          
          tthis.ZPointMarkerHandler(tthis._gmap._zpoint_marker,false); */
  
          //tthis._gmap.panTo(point);
        }
      });
  
  
      delete tthis;

      this._gmap.addControl(new ZMCControl());
      this._gmap.addControl(new GScaleControl());
  
    }

    this._gmap.addControl(new GMapTypeControl());

  }

  if (global_nsid != '00@Z01' && this._opts.cripple == false) {
//    this._gmap.addControl(new ZMSVControl());
    this._gmap.addControl(new ZMRControl());
  }

  this._gmap.setCenter(new GLatLng(this._loc[0],this._loc[1]),this._loc[2]);

  var tthis = this;
  GEvent.addListener(this._gmap, "dragstart", function() {
    tthis.in_drag = true;
  });

  GEvent.addListener(this._gmap, "zoomend", function() {
    tthis.in_drag = true;
  });
  
  GEvent.addListener(this._gmap, "moveend", function() {
    if ((tthis.ov_moving == true || tthis.in_drag == true) && tthis.iw_open == false) {
      tthis.redraw();
      tthis.in_drag = false;
    }
  });
  GEvent.addListener(this._gmap, "infowindowopen", function() {
    tthis.iw_open = true;
  });
  GEvent.addListener(this._gmap, "infowindowclose", function() {
    tthis.iw_open = false;
  });
  

  delete tthis;  

  this.redraw();
}

ZMap.prototype.loadIcons = function () {
  
  //Zooomr Icons
  ZM_icns['pcard'] = new GIcon();
  ZM_icns['pcard'].image = "http://assets2.zooomr.com/images/tidbits/googig_icon.png";
  ZM_icns['pcard'].shadow = "http://assets2.zooomr.com/images/tidbits/googig_shadow.png";
  ZM_icns['pcard'].iconSize = new GSize(35, 44);
  ZM_icns['pcard'].shadowSize = new GSize(46, 44);
  ZM_icns['pcard'].iconAnchor = new GPoint(17, 44);
  ZM_icns['pcard'].infoWindowAnchor = new GPoint(20, 1);

  ZM_icns['red_ovrly'] = new GIcon();
  ZM_icns['red_ovrly'].image = "http://assets2.zooomr.com/images/tidbits/tagmap_red_ovrly.png";
  ZM_icns['red_ovrly'].iconSize = new GSize(25, 25);
  ZM_icns['red_ovrly'].iconAnchor = new GPoint(12, 39);
  ZM_icns['red_ovrly'].infoWindowAnchor = new GPoint(20, 5);
  
  ZM_icns['blue_ovrly'] = new GIcon();
  ZM_icns['blue_ovrly'].image = "http://assets2.zooomr.com/images/tidbits/tagmap_blue_ovrly.png";
  ZM_icns['blue_ovrly'].iconSize = new GSize(25, 25);
  ZM_icns['blue_ovrly'].iconAnchor = new GPoint(12, 39);
  ZM_icns['blue_ovrly'].infoWindowAnchor = new GPoint(20, 5);

  ZM_icns['green_ovrly'] = new GIcon();
  ZM_icns['green_ovrly'].image = "http://assets2.zooomr.com/images/tidbits/tagmap_green_ovrly.png";
  ZM_icns['green_ovrly'].iconSize = new GSize(25, 25);
  ZM_icns['green_ovrly'].iconAnchor = new GPoint(12, 39);
  ZM_icns['green_ovrly'].infoWindowAnchor = new GPoint(20, 5);


  ZM_icns['rec'] = new GIcon();
  ZM_icns['rec'].image = "http://assets2.zooomr.com/images/tidbits/mm_20_selected.png";
  ZM_icns['rec'].shadow = "http://assets2.zooomr.com/images/tidbits/mm_20_shadow.png";
  ZM_icns['rec'].iconSize = new GSize(12, 20);
  ZM_icns['rec'].shadowSize = new GSize(22, 20);
  ZM_icns['rec'].iconAnchor = new GPoint(6, 20);
  ZM_icns['rec'].infoWindowAnchor = new GPoint(5, 1);

  ZM_icns['point'] = new GIcon();
  ZM_icns['point'].image = "http://assets2.zooomr.com/images/tidbits/geo_arrow.png";
  ZM_icns['point'].shadow = "http://assets2.zooomr.com/images/tidbits/geo_arrowshadow.png";
  ZM_icns['point'].iconSize = new GSize(39, 34);
  ZM_icns['point'].shadowSize = new GSize(39, 34);
  ZM_icns['point'].iconAnchor = new GPoint(11, 34);
  ZM_icns['point'].infoWindowAnchor = new GPoint(11, 4);


  //Zooomr Images
  ZM_imgs['nodata'] = newNode('img');
  ZM_imgs['nodata'].src = "http://assets2.zooomr.com/images/tidbits/smartset_delete_red.gif";

  ZM_imgs['sc'] = {r:{},g:{},b:{}};
  //Red
  ZM_imgs['sc']['r']['c'] = newNode('img');
  ZM_imgs['sc']['r']['c'].src = "http://assets2.zooomr.com/images/tidbits/socialcircle_rings_r.png";
  ZM_imgs['sc']['r']['c'].border = '0';
  ZM_imgs['sc']['r']['o'] = newNode('img');
  ZM_imgs['sc']['r']['o'].src = "http://assets2.zooomr.com/images/tidbits/socialcircle_rings_ro.png";
  ZM_imgs['sc']['r']['o'].border = '0';
  //Green
  ZM_imgs['sc']['g']['c'] = newNode('img');
  ZM_imgs['sc']['g']['c'].src = "http://assets2.zooomr.com/images/tidbits/socialcircle_rings_g.png";
  ZM_imgs['sc']['g']['c'].border = '0';
  ZM_imgs['sc']['g']['o'] = newNode('img');
  ZM_imgs['sc']['g']['o'].src = "http://assets2.zooomr.com/images/tidbits/socialcircle_rings_go.png";
  ZM_imgs['sc']['g']['o'].border = '0';
  //Blue
  ZM_imgs['sc']['b']['c'] = newNode('img');
  ZM_imgs['sc']['b']['c'].src = "http://assets2.zooomr.com/images/tidbits/socialcircle_rings_b.png";
  ZM_imgs['sc']['b']['c'].border = '0';
  ZM_imgs['sc']['b']['o'] = newNode('img');
  ZM_imgs['sc']['b']['o'].src = "http://assets2.zooomr.com/images/tidbits/socialcircle_rings_bo.png";
  ZM_imgs['sc']['b']['o'].border = '0';

  ZM_imgs['rec'] = {};
  //Red
  ZM_imgs['rec']['start'] = newNode('img');
  ZM_imgs['rec']['start'].src = "http://assets2.zooomr.com/images/tidbits/recording_start.gif";
  ZM_imgs['rec']['start'].border = '0';
  ZM_imgs['rec']['start'].style.verticalAlign = 'bottom';
  ZM_imgs['rec']['stop'] = newNode('img');
  ZM_imgs['rec']['stop'].src = "http://assets2.zooomr.com/images/tidbits/recording_stop.gif";
  ZM_imgs['rec']['stop'].border = '0';
  ZM_imgs['rec']['stop'].style.verticalAlign = 'bottom';
}

ZMap.prototype.buildZSmartInfoWindow = function(the_data) {
    var content = newNode("div");
        content.style.textAlign = "left";



    var type = newNode("h2");
        type.innerHTML = ZM_LocTypes[the_data['loctype']] + ':';
        type.style.marginTop = '0';

    content.appendChild(type);


    var line_one = newNode("h3");
        line_one.innerHTML = the_data['line_one'];
        line_one.style.marginTop = '0';

    content.appendChild(line_one);

    if (the_data['line_two']) {
      var line_two_three = newNode("p");
          line_two_three.innerHTML = the_data['line_two'] + "<br />" + (the_data['line_three'] ? the_data['line_three'] : '' );

      content.appendChild(line_two_three);
    }
    
    if (global_nsid != '00@Z01') {
      var default_loc = newNode("a");
      var save_loc = newNode("a");
    }
    
    var span = this._gmap.getBounds().toSpan()

    var link_loc = newNode("a");
        link_loc.innerHTML = '<img src="http://assets2.zooomr.com/images/tidbits/link_000.gif" style="vertical-align:bottom;" border="0" /> Link to this Location';
        link_loc.href = _site_root + "world/?z=" + this._gmap.getZoom() + "&ll=" + the_data.lat + "," + the_data.lon + "&spn=" + span.lat() + "," + span.lng() + "&t=" + this._gmap.getCurrentMapType().getUrlArg();
        
    content.appendChild(link_loc);

    content.appendChild(newNode("br")); //BR

    var glink_loc = newNode("a");
        glink_loc.innerHTML = '<img src="http://assets2.zooomr.com/images/tidbits/google_g_sm.gif" style="vertical-align:middle;" border="0" /> View this location on Google Maps';
        glink_loc.href = "http://maps.google.com/maps?ie=UTF8&z=" + this._gmap.getZoom() + "&ll=" + the_data.lat + "," + the_data.lon + "&spn=" + span.lat() + "," + span.lng() + "&t=" + this._gmap.getCurrentMapType().getUrlArg() + "&om=1";
        
    content.appendChild(glink_loc);


    var nearby_loc = newNode("a");
        nearby_loc.innerHTML = '';

    return content;

}

ZMap.prototype.buildZPointMarker = function(point,the_data) {    
    var the_marker = new GMarker(point, {icon:ZM_icns['point'],title:"(Hint: You can drag me!)",clickable:!this._opts.cripple,draggable: true});
        the_marker.nearByLoaded = false;
        the_marker.the_data = the_data;
        the_marker.selected_tab = 0;

    var self = this;

    GEvent.addListener(the_marker, "click", function() { self.ZPointMarkerHandler(the_marker,false); } );

    GEvent.addListener(the_marker, "dragstart", function() {
        the_marker.selected_tab = self._gmap.getInfoWindow().getSelectedTab();
        self._gmap.closeInfoWindow();
    });


    GEvent.addListener(the_marker, "dragend", function() { self.ZPointMarkerHandler(the_marker,true); });



  return the_marker;

}

ZMap.prototype.ZPointMarkerHandler = function(the_marker,indrag) {
    
    the_marker.nearByLoaded = false;      
    
    var point = the_marker.getPoint();
    
    if (indrag || the_marker.the_data.loctype === undefined) the_marker.the_data = {loctype:3,lat:point.y,lon:point.x,line_one:point.y.toString().substr(0,10) + ", " + point.x.toString().substr(0,10)};
    
    var nearByDiv = newNode('div');
        nearByDiv.innerHTML = gettext("Loading...");
//        nearByDiv.style.height = '100px';
//        nearByDiv.style.width = '250px';
    var self = this;
    var nearByFunc = function(doselect) {
      if (doselect) self._gmap.getInfoWindow().selectTab(1);
    
      if (the_marker.nearByLoaded == true) return;
    
      the_marker.nearByLoaded = true;
    
//!      var url = '/lm_bubble.awe';
//!      var pars = 'data='+JSON.stringify({'action':'nearbyview','lat':point.y,'lon':point.x});
//!      new Ajax.Updater(nearByDiv, url, {method:'post', postBody:pars,asynchronous:true,evalScripts:true});
    
    }
    
    // Our info window content
    var infoTabs = [new GInfoWindowTab(ZM_LocTypes[the_marker.the_data.loctype], this.buildZSmartInfoWindow(the_marker.the_data)),
                    new GInfoWindowTab("Nearby", nearByDiv, nearByFunc)];
    
    if (indrag) {
      setTimeout(function() { the_marker.openInfoWindowTabs(infoTabs,{selectedTab:the_marker.selected_tab}); if (the_marker.selected_tab == 1) { nearByFunc(false); }
                            },1000);
    } else {
      the_marker.openInfoWindowTabs(infoTabs,{selectedTab:the_marker.selected_tab});
      if (the_marker.selected_tab == 1) { nearByFunc(false); }
    }
    
}


ZMap.prototype.buildZGIMarker = function(point,src) {
  var icon = new GIcon();
  icon.image = src;
  icon.iconSize = new GSize(25, 25);
  icon.iconAnchor = new GPoint(12, 39);
  icon.infoWindowAnchor = new GPoint(0, 12);
  var marker = new GMarker(point, {"icon":icon,"clickable":false});
//  GEvent.addListener(marker, "click", function() {
//    parent.location = url;
//  });
  return marker;
}

ZMap.prototype.getInfoWindowNode = function(key) {
  try {

  var the_data = this.point_keys[key];

  if (!the_data.infoWindowNode) {
    the_data.infoWindowNode = newNode("div");
    the_data.infoWindowNode.className = "photo-info-window";
        
    the_data.bodyNode = newNode("div");
    the_data.bodyNode.className = "body";

    if (this._opts.display_size == 1) {
      the_data.bodyNode.style.width= "518px";
      the_data.bodyNode.style.height= "270px";
    } else {
      the_data.bodyNode.style.height = '100px';
      the_data.bodyNode.style.width = '350px';
    }

    if (the_data.pids.length == 1) { the_data.bodyNode.marginBottom = '0'; }

    the_data.bodyNode.innerHTML = gettext("Loading...");
    the_data.infoWindowNode.appendChild(the_data.bodyNode);
    
    var controllerNode = newNode("div");
    controllerNode.className = "controller";
    if (the_data.pids.length > 1) {
      var self = this;
      
      var prevNode = newNode("span");
      prevNode.className = "button";
      prevNode.innerHTML = "&laquo;";
      prevNode.onclick = function() {
        self.displayPhoto(the_data.key,the_data.currentPhotoIndex - 1);
        return false;
      }
      controllerNode.appendChild(prevNode);
      
      the_data.statusNode = newNode("span");
      the_data.statusNode.className = "status";
      controllerNode.appendChild(the_data.statusNode);

      var nextNode = newNode("span");
      nextNode.className = "button";
      nextNode.innerHTML = "&raquo;";
      nextNode.onclick = function() {
        self.displayPhoto(the_data.key,the_data.currentPhotoIndex + 1);
        return false;
      }
      controllerNode.appendChild(nextNode);
      
    } else {
      controllerNode.style.display = "none";
    }
    the_data.infoWindowNode.appendChild(controllerNode);
    
    the_data.verbsNode = newNode("verbs");
    the_data.infoWindowNode.appendChild(the_data.verbsNode);
  }
  
  this.displayPhoto(key, 0);
  
  return the_data.infoWindowNode;

  } catch (e) {
    window.console.log(e);
  }

}

ZMap.prototype.displayPhoto = function(key,index,do_refresh) {
  try {
    var the_data = this.point_keys[key];

    if (the_data.pids.length == 0) {
      this.redraw();
      return;
    }    

    index = (index + the_data.pids.length) % the_data.pids.length;
  
    if (index == the_data.currentPhotoIndex && !do_refresh) return;
  
    the_data.currentPhotoIndex = index;
    
    if (the_data.pids.length > 1) {
      the_data.statusNode.innerHTML = (index + 1) + "/" + the_data.pids.length;
    } else if (the_data.pids.length == 1 && the_data.statusNode !== undefined) {
      the_data.statusNode.parentNode.style.display = 'none';
    }

  
    
//    this.linkNode.href = the_data.url;
//    this.titleNode.innerHTML = the_data.title;

    var url = '/z/geobubble/' + the_data.pids[index]['ownerurl'] + '/' + the_data.pids[index].id + '/';
    var pars = 'ds=' + this._opts.display_size;
    new Ajax.Updater(the_data.bodyNode, url, {method:'post', postBody:pars,asynchronous:true,evalScripts:true});

    var tthis = this;

    the_data.verbsNode.innerHTML = '<img border="0" src="http://assets2.zooomr.com/images/silk/'+(the_data.pids[index].ispublic == 1 ? 'lock_open' : (the_data.pids[index].isfamily || the_data.pids[index].isfriend ? 'shield' : 'lock') )+'.png"/><!-- <a href="'+_site_root+'photos/'+the_data.pids[index].ownerurl+'/'+the_data.pids[index].id+'/near-by" target="_blank"><img border="0" src="http://assets2.zooomr.com/images/silk/world_nearby.png" /></a> --> <a href="'+_site_root+'z/photos/zoom/'+the_data.pids[index].id+'/size-8/" target="_blank" class="iconlink"><img src="http://assets2.zooomr.com/images/silk/magnifier.png" border="0" /></a> ';
    if (the_data.pids[index].owner == global_nsid) {
      var deleteImg = newNode("img");
          deleteImg.src = "http://assets2.zooomr.com/images/silk/cross.png";
          deleteImg.style.cursor = 'pointer';
          deleteImg.onclick = function() {tthis.deleteGeoTag(key,index);}

      the_data.verbsNode.appendChild(deleteImg);
    }

    the_data.verbsNode.appendChild(document.createTextNode(' '));

    var sizerImg = newNode("img");
        sizerImg.src = "http://assets2.zooomr.com/images/silk/arrow_" + (this._opts.display_size == 1 ? 'in' : 'out' ) + ".png";
        sizerImg.style.cursor = 'pointer';
        sizerImg.onclick = function() {tthis._opts.display_size = !tthis._opts.display_size;
                                       var iw = tthis._gmap.getInfoWindow();

                                       if (tthis._opts.display_size == 1) {
                                         the_data.bodyNode.style.width= "518px";
                                         the_data.bodyNode.style.height= "270px";
                                       } else {
                                         the_data.bodyNode.style.height = '100px';
                                         the_data.bodyNode.style.width = '350px';
                                       }

                                       the_data.bodyNode.innerHTML = '';

                                       tthis.displayPhoto(the_data.key,the_data.currentPhotoIndex,true);
                                       tthis._gmap.closeInfoWindow();
                                       the_data.marker.openInfoWindowTabs(iw.getTabs());
                                       delete iw;
                                       }
    delete tthis;
    the_data.verbsNode.appendChild(sizerImg);



  } catch (e) {
    //window.console.log('displayPhoto' + e);
  }
}

ZMap.prototype.buildZBlankMarker = function(point,the_data) {
    var blank_ovrly = new GIcon();
        blank_ovrly.image = "http://assets2.zooomr.com/images/tidbits/blank.gif";
        blank_ovrly.iconSize = new GSize(25, 25);
        blank_ovrly.iconAnchor = new GPoint(12, 39);
        blank_ovrly.infoWindowAnchor = new GPoint(20, 5);
    
    var blank_marker = new GMarker(point, {"icon":blank_ovrly,"title":the_data.title,"clickable":true});
    
    var tthis = this;
    GEvent.addListener(blank_marker, "click", function() {
  try {
      tthis.clicked_marker = blank_marker;

      the_data.allPhotosLoaded = false;      
      the_data.miniMapLoaded = 0;

      if (tthis._opts.cripple) {
        parent.location = '/photos/' + the_data['ownerurl'] + '/' + the_data.id + '/';
      } else {
        tthis._gmap.closeInfoWindow();
  
        var mapDiv = newNode('div');
            mapDiv.style.width = '100%';
            mapDiv.style.height = '100%'; //'150px';
  
        miniMapFunc = function() {
          tthis._gmap.getInfoWindow().selectTab(1);
          if (the_data.miniMapLoaded != 0) return;
          the_data.miniMapLoaded = new GMap2(mapDiv);
          var go_zoom = tthis._gmap.getZoom() + 2;
          if (go_zoom > 17) { go_zoom = 17; }
          the_data.miniMapLoaded.setCenter(blank_marker.getPoint(), go_zoom);
          the_data.miniMapLoaded.addControl(new GSmallMapControl());
          the_data.miniMapLoaded.addControl(new GMapTypeControl());
        }
  
        // Our info window content
        var infoTabs = [new GInfoWindowTab(ZM_LocTypes[1], tthis.getInfoWindowNode(the_data.key)), new GInfoWindowTab("miniMap", mapDiv,miniMapFunc)];
        
        if (0 > 1) {
  
          var allPhotosDiv = newNode('div');
              allPhotosDiv.innerHTML = gettext("Loading...");
    
          var allPhotosFunc = function() {
            tthis._gmap.getInfoWindow().selectTab(2);
    
            if (the_data.allPhotosLoaded == true) return;
    
            the_data.allPhotosLoaded = true;
    
            var url = '/z/geoinfobubble/' + the_data['ownerurl'] + '/' + the_data.id + '/';
//            var pars = 'data='+JSON.stringify({'action':'allview','oids':the_data.pids});
            new Ajax.Updater(allPhotosDiv, url, {method:'post', postBody:pars,asynchronous:true,evalScripts:true});
    
          }
  
  
          infoTabs[infoTabs.length] = new GInfoWindowTab('All Photos', allPhotosDiv,allPhotosFunc)
        }
        if (global_nsid != '00@Z01') {
          var addFunc = function() {
            tthis._gmap.closeInfoWindow();
            tthis._gmap.panTo(point);
            tthis._viewbar.innerHTML = '';
            tthis.buildPixChooser();
          }
          infoTabs[infoTabs.length] = new GInfoWindowTab( gettext("Add") + ' (+)', newNode('div'),addFunc)
        }
  
        the_data.marker = blank_marker;
  
        blank_marker.openInfoWindowTabs(infoTabs)
      }
  } catch (e) {
    window.console.log(e);
  }

//      var bubble_div = newNode('div');
//      bubble_div.innerHTML = 'Loading...';
//      bubble_div.setAttribute('id','lightmapbubble_'+pid);
//      blank_marker.openInfoWindow(bubble_div);
    });

  return blank_marker;

}

ZMap.prototype.buildZSocialMarker = function(point,oid) {

  if (global_nsid != oid) {
//    if (_ZGLOBAL['social_circle'][oid] === undefined) {
      var ovr_marker = new GMarker(point, {"icon":ZM_icns['red_ovrly'],"clickable":false});
//    }else{
//      var ovr_marker = new GMarker(point, {"icon":ZM_icns['blue_ovrly'],"clickable":false});
//    }
  }else{
    var ovr_marker = new GMarker(point, {"icon":ZM_icns['green_ovrly'],"clickable":false});
  }

  return ovr_marker;

}

ZMap.prototype.build_gridkey = function( data ) {
  var mapSpan = this._gmap.getBounds().toSpan()
  
  latGridSize = mapSpan.y / 10;
  lngGridSize = mapSpan.x / 10;
  
  nLatGrids = Math.floor(180 / latGridSize) + 1;
  nLngGrids = Math.floor(360 / lngGridSize) + 1;

  iGuessed = Math.floor( (data['latitude']+90) / latGridSize );
  jGuessed = Math.floor( (data['longitude']+180) / lngGridSize );
  
  return iGuessed * nLngGrids + jGuessed;
}

ZMap.prototype.process_incoming = function (in_data) {
  this._viewbar.innerHTML = '';
  this._gmap.clearOverlays();

  this._displayednum = in_data['photos']['photo'].length;
  this._totalnum = in_data['photos']['total'];
  var data = in_data['photos']['photo'];

  if (this._gmap._ZMRecording == true) {
    zloader.disable();
    return;
  }

  this.point_keys = {};

  if (data.length == 0) {
    this._viewbar.appendChild(ZM_imgs['nodata']);
    zloader.disable();
    return;
  }
  
  for(j=0;j<data.length;j++) {
    data[j].currentPhotoIndex = -1;
    data[j].allPhotosLoaded = false;
    data[j].miniMapLoaded = 0;
    data[j].pids = [ data[j] ];
    data[j].key = this.build_gridkey( data[j] );4

    if (this.point_keys[ data[j].key ]) {
      this.point_keys[ data[j].key ].pids[ this.point_keys[ data[j].key ].pids.length ] = data[j];
    } else {
      this.point_keys[ data[j].key ] = data[j];
    }
  }
  
  for (dkey in this.point_keys) {
    //GMap time                
    var point = new GLatLng(this.point_keys[dkey].latitude, this.point_keys[dkey].longitude);
    this._gmap.addOverlay(new GMarker(point, {"icon":ZM_icns['pcard'],"clickable":false}));
    this._gmap.addOverlay(this.buildZGIMarker(point, _photo_root + this.point_keys[dkey].id + '_' + this.point_keys[dkey].secret + '_s.jpg' ));

    this.point_keys[dkey].nop = this.point_keys[dkey].pids.length - 1

    if (this.point_keys[dkey].nop > 0) {
      var num_ovrly = new GIcon();
          num_ovrly.image = "http://assets2.zooomr.com/images/tidbits/the_dots_plus"+(this.point_keys[dkey].nop <= 9 ? String(this.point_keys[dkey].nop) : '' )+".png";
          num_ovrly.iconSize = new GSize(25, 25);
          num_ovrly.iconAnchor = new GPoint(12, 39);
      
      this._gmap.addOverlay(new GMarker(point, {"icon":num_ovrly,"clickable":false}));
    }
    
    if (global_nsid) {
      this._gmap.addOverlay(this.buildZSocialMarker(point,this.point_keys[dkey].owner));
    }
    
    this._gmap.addOverlay(this.buildZBlankMarker(point,this.point_keys[dkey]));

  }
  zloader.disable();
}

ZMap.prototype.updateInfoBar = function (num,message) {
  if (this._mtype != ZM_MICRODIV_TYPE) {
    this._recState = num;
    if (num == 0) {
      this._infoheader.innerHTML = '<span style="font-weight:bold;font-size:35px;">' + gettext("The World through Photos") + '</span>';
    } else {
      this._infoheader.innerHTML = '<div style="font-weight:bold;padding-top:8px;font-size:25px;">' + num + ') ' + message + '</div>';
      new Effect.Pulsate(this._infoheader, {delay:0.25});
    }
  }
}

ZMap.prototype.cancelPixChooser = function() {
  if (this._gmap._ZMRecording) {
    this._gmap.clearOverlays();
    this.updateInfoBar(1, gettext("Select a point on the map to start GeoTagging Photos.") );
  } else {
    this.updateInfoBar(0);
  }
  this.displayPixChooser(false);
}

ZMap.prototype.buildPixChooser = function() {
  this.pixChooser.innerHTML = '';
  this.updateInfoBar(2, gettext("Select photos you would like to GeoTag:") );
  var self = this;

  var cancelImg = newNode("img");
      cancelImg.src = "http://assets2.zooomr.com/images/tidbits/window_closer_black.gif";
      cancelImg.setAttribute('style','float:right;margin:4px;cursor:pointer;z-index:9000;');
      cancelImg.border = '0';
      cancelImg.onclick = function() {self.cancelPixChooser();}

  this.pixChooser.appendChild(cancelImg);


  var streamChooserDiv = newNode("div");
      streamChooserDiv.setAttribute('class','innerPixchooser');
      streamChooserDiv.style.width = '230px';
      streamChooserDiv.style.height = '275px';
      streamChooserDiv.style.position = 'absolute';
      streamChooserDiv.style.padding = '10px';

  //The actual input
  var ainput = newNode("input");

// <input style="color: #333; font-size: 10px; padding: 0" type="text" name="q" value="" size="30">

  ainput.style.color = '#000';
  ainput.style.fontSize = '13px';
  ainput.style.fontWeight = 'bold';
  ainput.style.width = '220px';

  ainput.style.padding = '2px';
  
  ainput.style.borderTop = '1px solid #000';
  ainput.style.borderLeft = '1px solid #000';
  ainput.style.borderRight = '1px solid #ccc';
  ainput.style.borderBottom = '1px solid #ccc';
  
  ainput.setAttribute('type','text');
  ainput.setAttribute('value',gettext("Refine by Tags"));
  
  streamChooserDiv.appendChild(ainput);


  var photosDiv = newNode("div");

  streamChooserDiv.appendChild(photosDiv);


  Event.observe(ainput, 'focus', function(){if (ainput.value == gettext("Refine by Tags")) {
                                              ainput.value = '';
                                            }}, false);

  Event.observe(ainput, 'blur', function(){if (ainput.value == '') {ainput.value = gettext("Refine by Tags");}}, false);



//    new Ajax.Autocompleter(ainput, 'auto_complete_area', '/geocode_list.awe?photo_id='+String(-1), {frequency:0.7});
  
  this.pixChooser.appendChild(streamChooserDiv);

  var streamSelectedDiv = newNode("div");
      streamSelectedDiv.setAttribute('class','innerPixchooser');
      streamSelectedDiv.innerHTML = '<h1 style="margin:0;">Selected Photos</h1>';
      streamSelectedDiv.style.width = '393px';
      streamSelectedDiv.style.height = '285px';
      streamSelectedDiv.style.marginLeft = '275px';
      streamSelectedDiv.style.padding = '5px 10px';

  var innerStreamSelectedDiv = newNode("div");
//      innerStreamSelectedDiv.style.overflow = 'auto';

  streamSelectedDiv.appendChild(innerStreamSelectedDiv);

  this.pixChooser.appendChild(streamSelectedDiv);

  var mapDiv = newNode("div");
      mapDiv.setAttribute('class','innerPixchooser');
      mapDiv.style.width = '233px';
      mapDiv.style.height = '275px';
      mapDiv.style.display = 'none';
      mapDiv.style.padding = '10px';
      mapDiv.style.marginLeft = '435px';
      mapDiv.innerHTML = 'bob';

  this.pixChooser.appendChild(mapDiv);


  Event.observe(ainput, 'keyup', function(oEvent){self.getdataForPixChooser(1,ainput,photosDiv,innerStreamSelectedDiv);}, false);

  this.getdataForPixChooser(1,ainput,photosDiv,innerStreamSelectedDiv);

//<input type="submit" onclick="contacts.savecontact('1148782764_5315','add','addcontactform')" class="reg_button" value="OK!"/>
//<input type="submit" onclick="new Effect.BlindUp('addcontactform');" value="CANCEL"/>

  var buttonDiv = newNode("div");
      buttonDiv.style.width = '690px';
      buttonDiv.style.margin = '5px 0';
      buttonDiv.style.textAlign = 'right';

	var cancelInput = newNode("input");
      cancelInput.setAttribute('class','cancel_button');
      cancelInput.setAttribute('type','button');
      cancelInput.setAttribute('value','CANCEL');
      cancelInput.onclick = function() {self.cancelPixChooser();}

  buttonDiv.appendChild(cancelInput);

  buttonDiv.appendChild(document.createTextNode(' '));

	var goBackInput = newNode("input");
      goBackInput.setAttribute('class','cancel_button');
      goBackInput.setAttribute('type','button');
      goBackInput.setAttribute('value','START OVER');
      goBackInput.onclick = function() {self.recPool = [];self.buildPixChooser();}

  buttonDiv.appendChild(goBackInput);

  buttonDiv.appendChild(document.createTextNode(' '));

	this.greenInput = newNode("input");
  this.greenInput.setAttribute('class','reg_button');
  this.greenInput.setAttribute('type','button');
  this.greenInput.setAttribute('value','CONTINUE');
  if (this.recPool.length == 0) {
    this.greenInput.setAttribute('disabled','true');
  }
  this.greenInput.onclick = function () {self.confirmPixChooser(streamChooserDiv,streamSelectedDiv,mapDiv);}

  buttonDiv.appendChild(this.greenInput);

  this.pixChooser.appendChild(buttonDiv);


  var success	= function(t){
    var data = json_parse(t.responseText)['photos']['photo'];
    for (k=0;k<data.length;k++) {
      innerStreamSelectedDiv.appendChild(self.drawimgForPixChooser(data[k],'highlight_red',ainput,photosDiv,innerStreamSelectedDiv, 1));
    }
    zloader.disable();
  }

  zloader.enable();

  ZAPI.callMethodJSON( 'zooomr.photos.search', {query: ' "query:limitto=' + this.recPool.join(',') + '"', per_page: 100, page: 1}, {onSuccess:success})
//!    var url = '/objnfo.awe';
//!    var pars = 'data='+JSON.stringify({'action':'gp','oid':this.recPool[k],'get':'src,pid'});
//!    var myAjax = new Ajax.Request(url, {method:'post', postBody:pars, onSuccess:success});



  this.displayPixChooser(true);
}

ZMap.prototype.confirmPixChooser = function(streamChooserDiv,streamSelectedDiv,mapDiv) {
  var self = this;
  streamChooserDiv.style.display = 'none';
  streamSelectedDiv.style.position = 'absolute';
  streamSelectedDiv.style.margin = '10px';
  mapDiv.style.display = 'block';

  //Drag Map
  var temp_map = new GMap2(mapDiv);
  temp_map.setCenter(this._gmap.getCenter(),this._gmap.getZoom());
  var the_marker = new GMarker(temp_map.getCenter(),{"icon":ZM_icns['rec'],"clickable":false});
  temp_map.addOverlay(the_marker);
  temp_map.disableDragging();

  //Change Buttons
  this.greenInput.setAttribute('value','YES, GEOTAG THESE PHOTOS');
  this.greenInput.onclick = function () {self.savePixChooser();}

  this.updateInfoBar(3,'Is this exactly where you would like to GeoTag these photos?');
}

ZMap.prototype.savePixChooser = function() {

  var self = this;
  var success	= function(t) {
      zloader.disable();
  }

  for (var j=0;j<this.recPool.length;j++) {
    zloader.enable();
    ZAPI.callMethodJSON( 'zooomr.photos.geo.setlocation', {photo_id: this.recPool[j], lat:this._gmap.getCenter().lat(), lon:this._gmap.getCenter().lng(), accuracy: this._gmap.getZoom() }, {onSuccess:success, asynchronous: false})
  }

  self.recPool = [];
  self._gmap._ZMRecording = false;
  self.recControlStyler(true);
  self._gmap.clearOverlays();
  self.redraw();
  self.displayPixChooser(false);
  self.updateInfoBar(0);

//!  var url = '/objnfo.awe';
//!  var pars = 'data='+JSON.stringify({'action':'sgt','oid':this.recPool.join(','),'ll':this._gmap.getCenter().lng()+','+this._gmap.getCenter().lat()});
//!  new Ajax.Request(url, {method:'post', postBody:pars, onSuccess:success});
}

ZMap.prototype.deleteGeoTag = function(key,index) {
  var the_data = this.point_keys[key];

  var self = this;
  var success	= function(t) {
      the_data.pids.splice(index,1);
      the_data.currentPhotoIndex = -1;
      self.displayPhoto(key,0);
      zloader.disable();
  }

  zloader.enable();
  ZAPI.callMethodJSON( 'zooomr.photos.geo.removelocation', {photo_id: the_data.pids[index].id}, {onSuccess:success})
}

ZMap.prototype.displayPixChooser = function(show) {
  if (show) {
    this.overlayDiv.show();
  } else {
    this.overlayDiv.style.display = 'none';
    this.pixChooser.innerHTML = '';
  }
}

ZMap.prototype.getdataForPixChooser = function(page_num,ainput,photoContainer,streamSelectedDiv) {
try {

  var tthis = this;

  //Get Object Data:    
	var success	= function(t) {
    try {
    photoContainer.innerHTML = '';
    //Parse Data
    var this_page = json_parse(t.responseText)['photos'];
    //Load Page Nav
    var navDiv = newNode("div");
        navDiv.setAttribute('class','pcPageNav');

    if (this_page.pages == 0) {
      navDiv.appendChild(document.createTextNode( gettext("No photos were found.") ));
    } else {

      var prevNav = newNode("a");
          prevNav.href = "javascript:void(0);";
          prevNav.onclick = function() {if (page_num-1 > 0) { tthis.getdataForPixChooser(page_num-1,ainput,photoContainer,streamSelectedDiv);} else { tthis.getdataForPixChooser(this_page.pages,ainput,photoContainer,streamSelectedDiv); }}
          prevNav.innerHTML = '&laquo;';
  
      navDiv.appendChild(prevNav);
  
      var placeNav = newNode("span");
          placeNav.innerHTML = this_page.page+'/'+this_page.pages+' ('+this_page.total+')';
  
      navDiv.appendChild(placeNav);
  
  
      var nextNav = newNode("a");
          nextNav.href = "javascript:void(0);";
          nextNav.onclick = function() {if (this_page.pages-this_page.page > 0) {tthis.getdataForPixChooser(page_num+1,ainput,photoContainer,streamSelectedDiv);} else { tthis.getdataForPixChooser(1,ainput,photoContainer,streamSelectedDiv); }}
          nextNav.innerHTML = '&raquo;';
  
      navDiv.appendChild(nextNav);

    }

    photoContainer.appendChild(navDiv);

    for (k=0;k<this_page['photo'].length;k++) {
      photoContainer.appendChild(tthis.drawimgForPixChooser(this_page['photo'][k],'highlight',ainput,photoContainer,streamSelectedDiv, this_page.page));
    }
    
    zloader.disable();
    } catch (e) {
    console.log(e);
    }
	}

  delete tthis;

  var tag_data = ainput.value;
  if (tag_data == gettext("Refine by Tags")) {
    tag_data = '';
  }

//	var pars = 'data='+JSON.stringify({"action":"gtps","limit_list":this.recPool,"uid":global_nsid,"tags":tag_data,"page":page_num,"perpage":16});
//	alert(pars);
  ZAPI.callMethodJSON( 'zooomr.photos.search', {query: "query:owner=" + global_nsid + (this.recPool.length ? ' "query:exclude=' + this.recPool.join(',') + '" ' : ' ') + tag_data, per_page: 16, page: page_num}, {onSuccess:success})
  zloader.enable();
} catch (e) {
  //window.console.log(e);
}

}

ZMap.prototype.drawimgForPixChooser = function(photo_data,h_mode,ainput,photoContainer,streamSelectedDiv, page_num) {
  var self = this;
  var testImg = newNode("img");
      testImg.setAttribute('class',h_mode);
      testImg.src = _photo_root + photo_data.id + '_' + photo_data.secret + '_s.jpg'; //photo_data.src;
      testImg.style.padding = '2px';
      testImg.style.margin = '1px';
      testImg.style.height = '50px';
      testImg.style.width = '50px';
      testImg.onclick = function() {
                                      if (self._recState < 3) {
                                        if (h_mode == 'highlight') {
                                          self.modRecPool('add',photo_data.id);
                                          streamSelectedDiv.appendChild(self.drawimgForPixChooser(photo_data,'highlight_red',ainput,photoContainer,streamSelectedDiv, 1));
                                          this.parentNode.removeChild(this);
                                        } else {
                                          this.parentNode.removeChild(this);
                                          self.modRecPool('del',photo_data.id);
                                        }
                                        self.getdataForPixChooser(page_num,ainput,photoContainer,streamSelectedDiv);
                                      }
                                    }

  return testImg

}

ZMap.prototype.modRecPool = function (mode,what) {
  if (mode == 'add') {
    this.recPool[this.recPool.length] = what;
  } else if (mode == 'del') {

    for (j=0;j<this.recPool.length;j++) {
      if (this.recPool[j] == what) {
        this.recPool.splice(j,1);
        break;
      }
    }
  }
  if (this.recPool.length > 0) {
    this.greenInput.removeAttribute('disabled');
  } else {
    this.greenInput.setAttribute('disabled','true');
  }
}

ZMap.prototype.redraw = function (afterFunc) {
  this._viewbar.innerHTML = '';
  this._gmap.closeInfoWindow();

  if (this._gmap._ZMRecording == true) return;

  //this._viewbar.appendChild(ZM_imgs['loading']);
  zloader.enable();
  
  var tthis = this;

  //Get Object Data:    
	var success	= function(t) {
    tthis.process_incoming( json_parse(t.responseText) );

    if (tthis._gmap._zpoint_marker !== undefined) { tthis._gmap.addOverlay(tthis._gmap._zpoint_marker); }
    
    /*if (tthis._sr_infoarea) {
    
      if (tthis._opts.SmartFilter_data != '') {
        tthis._sr_infoarea.innerHTML = '<h4 style="margin:0;">Displaying ' + tthis._displayednum + ' photos tagged with &quot;' + tthis._opts.SmartFilter_data + '&quot;.</h4>';
      } else {
        tthis._sr_infoarea.innerHTML = '<h4 style="margin:0;">Displaying ' + tthis._displayednum + ' of ' + tthis._totalnum + ' photos worldwide.</h4>';
      }
    
    } */
    
    if (afterFunc) afterFunc();
	}

  delete tthis;

  var mapBounds    = this._gmap.getBounds();
  var mapBounds_sw = mapBounds.getSouthWest();
  var mapBounds_ne = mapBounds.getNorthEast();

//  var mapSpan      = mapBounds.toSpan()
//      mapSpan      = [mapSpan.y,mapSpan.x]

  ZAPI.callMethodJSON( 'zooomr.photos.search', {query: this._opts.SmartFilter_data + ' "geo:bbox='+mapBounds_sw.y+','+mapBounds_sw.x+','+mapBounds_ne.y+','+mapBounds_ne.x+'" geo:zoom=' + this._gmap.getZoom(), per_page: 50, extras: 'geo,owner_url'}, {onSuccess:success});

//	var pars = 'data='+JSON.stringify({a:'locpull',sr_data:this._opts.SmartFilter_data,sc_r:this._gmap._ZMSCRed,sc_g:this._gmap._ZMSCGreen,sc_b:this._gmap._ZMSCBlue,zoom:this._gmap.getZoom(),bounds:[mapBounds_sw,mapBounds_ne],spn:mapSpan,"limit_list":this._opts.limitList});

//	alert(pars);
//	new Ajax.Request(url, {method:'post', postBody:pars, onSuccess:success});
  
}

function zmap_test() {
  
  amap = new ZMap($('message'),1,[37.4000367437,-122.098156214,10],{"maxitems":9,"viewbarwidth":50,"height":515,"width":800});
  amap.init();

}