page.replace_html :sidebar_title, t('export.start_rjs.export')
page.replace_html :sidebar_content, :partial => 'start'
page << <<EOJ
  var vectors;
  var box;
  var markerLayer;
  var markerControl;

  function startExport() {
    vectors = new OpenLayers.Layer.Vector("Vector Layer", {
      displayInLayerSwitcher: false
    });
    map.addLayer(vectors);

    box = new OpenLayers.Control.DrawFeature(vectors, OpenLayers.Handler.RegularPolygon, { 
      handlerOptions: {
        sides: 4,
        snapAngle: 90,
        irregular: true,
        persist: true,
        callbacks: { done: endDrag }
      }
    });
    map.addControl(box);

    map.events.register("moveend", map, mapMoved);
    map.events.register("changebaselayer", map, htmlUrlChanged);

    openSidebar({ onclose: stopExport });

    if (map.baseLayer.name == "Mapnik") {
      $("format_mapnik").checked = true;
    } else if (map.baseLayer.name == "Osmarender") {
      $("format_osmarender").checked = true;
    }

    formatChanged();
    setBounds(map.getExtent());

    $("viewanchor").className = "";
    $("exportanchor").className = "active";
  }

  function stopExport() {
    $("viewanchor").className = "active";
    $("exportanchor").className = "";

    clearBox();
    clearMarker();
    map.events.unregister("moveend", map, mapMoved);
    map.events.unregister("changebaselayer", map, htmlUrlChanged);
    map.removeLayer(vectors);
  }

  function boundsChanged() {
    var epsg4326 = new OpenLayers.Projection("EPSG:4326");
    var bounds = new OpenLayers.Bounds($("minlon").value,
                                       $("minlat").value,
                                       $("maxlon").value,
                                       $("maxlat").value);
 
    bounds.transform(epsg4326, map.getProjectionObject());

    map.events.unregister("moveend", map, mapMoved);
    map.zoomToExtent(bounds);

    clearBox();
    drawBox(bounds);

    validateControls();
    mapnikSizeChanged();
  }

  $("maxlat").onchange = boundsChanged;
  $("minlon").onchange = boundsChanged;
  $("maxlon").onchange = boundsChanged;
  $("minlat").onchange = boundsChanged;

  function startDrag() {
    $("drag_box").innerHTML="#{I18n.t('export.start_rjs.drag_a_box')}";

    clearBox();
    box.activate();
  };

  $("drag_box").onclick = startDrag;

  function endDrag(bbox) {
    var bounds = bbox.getBounds();

    map.events.unregister("moveend", map, mapMoved);
    setBounds(bounds);
    drawBox(bounds);
    box.deactivate();
    validateControls();

    $("drag_box").innerHTML = "#{I18n.t('export.start_rjs.manually_select')}";
  }

  function startMarker() {
    $("add_marker").innerHTML='#{I18n.t('export.start_rjs.click_add_marker')}';

    if (!markerLayer) {
      markerLayer = new OpenLayers.Layer.Vector("",{
        displayInLayerSwitcher: false,
        style: { 
          externalGraphic: OpenLayers.Util.getImagesLocation() + "marker.png",
          graphicXOffset: -10.5,
          graphicYOffset: -25, 
          graphicWidth: 21,
          graphicHeight: 25
        } 
      });
      map.addLayer(markerLayer);

      markerControl = new OpenLayers.Control.DrawFeature(markerLayer, OpenLayers.Handler.Point);
      map.addControl(markerControl);

      markerLayer.events.on({ "featureadded": endMarker });
    }

    markerLayer.destroyFeatures();
    markerControl.activate();

    return false;
  }

  $("add_marker").onclick = startMarker;

  function endMarker(event) {
    markerControl.deactivate();

    $("add_marker").innerHTML = "#{I18n.t('export.start_rjs.change_marker')}";
    $("marker_inputs").style.display = "block";
    
    var epsg4326 = new OpenLayers.Projection("EPSG:4326");
    var epsg900913 = new OpenLayers.Projection("EPSG:900913");
    var geom = event.feature.geometry.clone().transform(epsg900913, epsg4326);

    $("marker_lon").value = geom.x.toFixed(5);
    $("marker_lat").value = geom.y.toFixed(5);

    htmlUrlChanged(); 
  }

  function clearMarker() {
    $("marker_lon").value = "";
    $("marker_lat").value = "";
    $("marker_inputs").style.display = "none";
    $("add_marker").innerHTML = "#{I18n.t('export.start_rjs.add_marker')}";

    if (markerLayer) { 
      markerControl.destroy();
      markerLayer.destroy();
      markerLayer = null;
      markerControl = null;
    }
  }  

  function mapMoved() {
    setBounds(map.getExtent());
    validateControls();
  }

  function setBounds(bounds) {
    var epsg4326 = new OpenLayers.Projection("EPSG:4326");
    var decimals = Math.pow(10, Math.floor(map.getZoom() / 3));

    bounds = bounds.clone().transform(map.getProjectionObject(), epsg4326);

    $("minlon").value = Math.round(bounds.left * decimals) / decimals;
    $("minlat").value = Math.round(bounds.bottom * decimals) / decimals;
    $("maxlon").value = Math.round(bounds.right * decimals) / decimals;
    $("maxlat").value = Math.round(bounds.top * decimals) / decimals;

    mapnikSizeChanged();
    htmlUrlChanged();
  }

  function clearBox() {
    vectors.destroyFeatures();
  }

  function drawBox(bounds) {
    var feature = new OpenLayers.Feature.Vector(bounds.toGeometry());

    vectors.addFeatures(feature);
  }

  function validateControls() {
    var bounds = new OpenLayers.Bounds($("minlon").value, $("minlat").value, $("maxlon").value, $("maxlat").value);

    if (bounds.getWidth() * bounds.getHeight() > #{APP_CONFIG['max_request_area']}) {
      $("export_osm_too_large").style.display = "block";
    } else {
      $("export_osm_too_large").style.display = "none";
    }

    var max_scale = maxMapnikScale();

    if ($("format_osm").checked && bounds.getWidth() * bounds.getHeight() > #{APP_CONFIG['max_request_area']}) {
      $("export_commit").disabled = true;
    } else if ($("format_mapnik").checked && $("mapnik_scale").value < max_scale) {
      $("export_commit").disabled = true;
    } else {
      $("export_commit").disabled = false;
    }

    $("mapnik_max_scale").innerHTML = roundScale(max_scale);
  
    var max_zoom = maxOsmarenderZoom();

    for (var o = 0; o < $("osmarender_zoom").options.length; o++) {
      var option = $("osmarender_zoom").options[o];

      if (option.value > max_zoom) {
        option.disabled = true;
      } else {
        option.disabled = false;
      }
    }

    if ($("osmarender_zoom").options.selectedIndex + 4 > max_zoom) {
      $("osmarender_zoom").options.selectedIndex = max_zoom - 4;
    }
  }

  function htmlUrlChanged() {
    var bounds = new OpenLayers.Bounds($("minlon").value, $("minlat").value, $("maxlon").value, $("maxlat").value);
    var layerName = map.baseLayer.name.toLowerCase();
    var url = "http://#{SERVER_URL}/export/embed.html?bbox=" + bounds.toBBOX() + "&layer=" + layerName;
    var markerUrl = "";

    if ($("marker_lat").value && $("marker_lon").value) {
      markerUrl = "&mlat=" + $("marker_lat").value + "&mlon=" + $("marker_lon").value;
      url += "&marker=" + $("marker_lat").value + "," + $("marker_lon").value;
    } 
    
    var html = '<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="'+url+'" style="border: 1px solid black"></iframe>';
   
    // Create "larger map" link
    var center = bounds.getCenterLonLat();
    var epsg4326 = new OpenLayers.Projection("EPSG:4326");
    var epsg900913 = new OpenLayers.Projection("EPSG:900913");

    bounds.transform(epsg4326, epsg900913);
    var zoom = map.getZoomForExtent(bounds);
    
    var layers = getMapLayers();

    html += '<br /><small><a href="http://#{SERVER_URL}/?lat='+center.lat+'&lon='+center.lon+'&zoom='+zoom+'&layers='+layers+markerUrl+'">'+"#{html_escape_unicode(I18n.t('export.start_rjs.view_larger_map'))}"+'</a></small>';

    $("export_html_text").value = html;

    if ($("format_html").checked) {
      $("export_html_text").select();
    }
  }

  function formatChanged() {
    $("export_commit").style.display = "inline";

    if ($("format_osm").checked) {
      $("export_osm").style.display = "inline";
    } else {
      $("export_osm").style.display = "none";
    }

    if ($("format_mapnik").checked) {
      $("mapnik_scale").value = roundScale(map.getScale());
      $("export_mapnik").style.display = "inline";
    } else {
      $("export_mapnik").style.display = "none";
    }

    if ($("format_osmarender").checked) {
      var zoom = Math.min(map.getZoom(), maxOsmarenderZoom());

      $("osmarender_zoom").options.selectedIndex = zoom - 4;
      $("export_osmarender").style.display = "inline";
    } else {
      $("export_osmarender").style.display = "none";
    }

    if ($("format_html").checked) { 
      $("export_html").style.display = "inline";
      $("export_commit").style.display = "none";
      $("export_html_text").select();
    } else {
      $("export_html").style.display = "none";
      clearMarker();
    }
        
    validateControls();
  }

  $("format_osm").onclick = formatChanged;
  $("format_mapnik").onclick = formatChanged;
  $("format_osmarender").onclick = formatChanged;
  $("format_html").onclick = formatChanged;

  function maxMapnikScale() {
    var bounds = new OpenLayers.Bounds($("minlon").value, $("minlat").value, $("maxlon").value, $("maxlat").value);
    var epsg4326 = new OpenLayers.Projection("EPSG:4326");
    var epsg900913 = new OpenLayers.Projection("EPSG:900913");

    bounds.transform(epsg4326, epsg900913);

    return Math.floor(Math.sqrt(bounds.getWidth() * bounds.getHeight() / 0.3136));
  }

  function mapnikImageSize(scale) {
    var bounds = new OpenLayers.Bounds($("minlon").value, $("minlat").value, $("maxlon").value, $("maxlat").value);
    var epsg4326 = new OpenLayers.Projection("EPSG:4326");
    var epsg900913 = new OpenLayers.Projection("EPSG:900913");

    bounds.transform(epsg4326, epsg900913);

    return new OpenLayers.Size(Math.round(bounds.getWidth() / scale / 0.00028),
                               Math.round(bounds.getHeight() / scale / 0.00028));
  }

  function maxOsmarenderZoom() {
    var bounds = new OpenLayers.Bounds($("minlon").value, $("minlat").value, $("maxlon").value, $("maxlat").value);
    var xzoom = Math.LOG2E * Math.log(2000 * 1.40625 / bounds.getWidth());
    var ymin = bounds.bottom * Math.PI / 180;
    var ymax = bounds.top * Math.PI / 180;
    var yzoom = Math.LOG2E * (Math.log(2000 * 2 * Math.PI) - Math.log(Math.log((Math.tan(ymax) + 1 / Math.cos(ymax)) / (Math.tan(ymin) + 1 / Math.cos(ymin)))))

    return Math.min(Math.floor(Math.min(xzoom, yzoom)), 17);
  }

  function roundScale(scale) {
    var precision = 5 * Math.pow(10, Math.floor(Math.LOG10E * Math.log(scale)) - 2);

    return precision * Math.ceil(scale / precision);
  }

  function mapnikSizeChanged() {
    var size = mapnikImageSize($("mapnik_scale").value);

    $("mapnik_image_width").innerHTML = size.w;
    $("mapnik_image_height").innerHTML = size.h;
  }

  function mapnikScaleChanged() {
    mapnikSizeChanged();
    validateControls();
  }

  $("mapnik_scale").onchange = mapnikScaleChanged;

  startExport();
EOJ
