{% extends 'warp_base.html' %}
{% load staticfiles %}
{% load l10n %}
{% comment %} {% endcomment %}

{% block custom_style_link %}
{% comment %} <link rel="stylesheet" href="http://openlayers.org/en/v3.7.0/resources/layout.css" />{% endcomment %}
<link rel="stylesheet" href="/static/warp/css/ol.css" />
<link rel="stylesheet" href="/static/warp/css/ol3-layerswitcher.css" />
{% endblock %}
{% block custom_style_inline %}

#progress {
    background: transparent url("/static/warp/ajax-loader.gif") no-repeat center;
    float: left;
    display: inline-block;
    width: 32px;
    height: 32px;
}

#upload {
    display: inline-block;
    padding: 4px;
}

.panel-body {
    padding: 4px 0px;
}

.fill {
    height: 100% !important;
}

htlm body {
    height: 100% !important;
}

{% endblock %}
{% block custom_js %}
<script type="text/javascript" src="/static/warp/js/ol.js"></script>
<script src="/static/warp/js/ol3-layerswitcher.js"></script>
<script src="/static/warp/js/proj4.js"></script>
{% if source.dataset %}<script src="http://epsg.io/{{ source.dataset.epsg }}.js"></script>{% endif %}
<script type="text/javascript">

var localExtent = [0, 0, {{source.img.width}}, {{source.img.height}}];
var localProjection = new ol.proj.Projection({
  code: 'georef_source',
  units: 'pixels',
  extent: localExtent
});

var indiceControllo = 1;
var controlli = [];
var syncEnable = true;

{% localize off %}
var targetExtent = [{{ source.dataset.extentLeft }}, {{ source.dataset.extentBottom }}, {{ source.dataset.extentRight }}, {{ source.dataset.extentTop }}];
{% endlocalize %}

{% if source.target %}
var exex = {{source.targetExtent}};
{% endif %}


// PD [1716014, 5023919, 1737137, 5038662];

var map_sorgente, map_destinazione;
var controllo_sorgente, controllo_destinazione;
var georef_overlay, clipSourceFeatures, clipSourceOverlay, clipTargetFeatures, clipTargetOverlay;
var messaggio_errore

{% if source.dataset.epsg = 3857 or source.dataset.epsg = 4326 %}
var targetProjection = 'EPSG:{{ source.dataset.epsg }}';
{% else %}
var targetProjection = new ol.proj.Projection({
  code: 'EPSG:{{ source.dataset.epsg }}',
  // The extent is used to determine zoom level 0. Recommended values for a
  // projection's validity extent can be found at http://epsg.io/.
  extent: targetExtent,
  //units: 'm'
});
ol.proj.addProjection(targetProjection);
{% endif %}

var geoJson_convertitore = new ol.format.GeoJSON();

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

function modalLog(){
    var log = $.ajax({
                    url: messaggio_errore,
                    async: false
                 }).responseText;

    var popupTemplate =
      '<div class="modal fade">' +
      '  <div class="modal-dialog">' +
      '    <div class="modal-content">' +
      '      <div class="modal-header">' +
      '        <button type="button" class="close" data-dismiss="modal">&times;</button>' +
      '        <h4 class="modal-title">Georeferencing report</h4>' +
      '      </div>' +
      '      <div id = "log" class="modal-body">' +
                log +
      '      </div>' +
      '      <div class="modal-footer">' +
      '        <button type="button" class="btn btn-link" data-dismiss="modal">Cancel</button>' +
      '      </div>' +
      '    </div>' +
      '  </div>' +
      '</div>';

    $(popupTemplate).modal()

};

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        console.log("AJAX_sending");
        console.log(csrftoken);
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

$(document).ready(function(){


    // funzione per intercettare invio della form ed aggiungere alcuni campi prima del submit
    $('#fase2').submit(function(eventObj) {
        console.log("fase2");
        $('#errore').addClass("hidden");
        $('#esito').addClass("hidden");
        $('#download').addClass("hidden");
        $('#print').addClass("hidden");

        var sorgente_features = controllo_sorgente.getSource().getFeatures();
        var sorgente_json = geoJson_convertitore.writeFeatures(sorgente_features);
        var sorgente_output = JSON.stringify(sorgente_json);
        $(this).append("<input type='hidden' name='controlli_sorgente' value='"+sorgente_output+"' /> ");

        var destinazione_features = controllo_destinazione.getSource().getFeatures();
        var destinazione_json = geoJson_convertitore.writeFeatures(destinazione_features);
        var destinazione_output = JSON.stringify(destinazione_json);
        $(this).append("<input type='hidden' name='controlli_destinazione' value='"+destinazione_output+"' /> ");

        if (clipSourceOverlay.getSource().getFeatures().length > 0){
          var clip_features = clipSourceOverlay.getSource().getFeatures();
          var clip_json = geoJson_convertitore.writeFeatures(clip_features);
          var clip_output = JSON.stringify(clip_json);
        } else {
          var clip_output = "";
        }
        $(this).append("<input type='hidden' name='clip_poligono' value='"+clip_output+"' /> ");

        eventObj.preventDefault();

        var dataForm = {}
        var Form = this;

        //Gathering the Data
        //and removing undefined keys(buttons)
        $.each(this.elements, function(i, v){
                var input = $(v);
            dataForm[input.attr("name")] = input.val();
            delete dataForm["undefined"];
        });

        console.log(dataForm);
        $('#progress').removeClass("hidden");

        $.ajax({
            csrfmiddlewaretoken: '{{ csrf_token }}',
            url: '/warp/apply/',
            type: 'POST',
            data: JSON.stringify(dataForm),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            async: false,
            success: function(payload) {
                $('#progress').addClass("hidden");
                console.log(payload.valida);
                console.log(payload.esito);
                console.log(payload.dest_img);
                console.log(payload.geotiff);
                console.log(payload.img_dim);
                console.log(payload.clipSorgente);
                console.log(payload.clipDestinazione);
                console.log(payload.estensione);
                messaggio_errore = payload.esito;
                if (payload.valida){
                    georef_overlay.setExtent(payload.estensione);
                    georef_overlay.setSource(new ol.source.ImageStatic({
                          url: payload.dest_img,
                          projection: targetProjection,
                          //size: payload.img_dim,
                          imageExtent: payload.estensione
                        })
                    );
                    if (payload.clipDestinazione != ''){
                        clipTargetFeatures = new ol.Collection(new ol.format.GeoJSON().readFeatures(payload.clipDestinazione, {
                            //featureProjection: targetProjection
                        }));
                        clipTargetOverlay.setSource(new ol.source.Vector({features: clipTargetFeatures}));
                    }
                    enableDownloadPrint(payload.id,payload.geotiff);
                    $('#esito').removeClass("hidden");
                    georef_overlay.refresh({force:true});
                } else {
                    console.log("ERRORE");
                    $('#errore').removeClass("hidden");
                    $('#esito').addClass("hidden");
                    $('#download').addClass("hidden");
                    $('#print').addClass("hidden");
                    //$('#messaggio_errore').text(payload.esito);
                }
            }
        });
    });

    $( '#aggiungiControllo' ).click( function(event) {
        aggiungiControllo();
    });

    $( '#rimuoviControllo' ).click( function(event) {
        rimuoviControllo();
    });

    $( '#resetControlli' ).click( function(event) {
        if ($("#clip").hasClass( "active" )){
            resetClip();
        } else {
            resetControlli();
        }
    });

    $( '#saveControlli' ).click( function(event) {
        var correlazione = getCorrelationMatrix()
        $("<a />", {
            "download": "correlazione.json",
            "href" : "data:application/json," + encodeURIComponent(JSON.stringify(correlazione, null, '\t'))
            }).appendTo("body")
            .click(function() {
             $(this).remove()
            })[0].click()
        });

    $( '#loadControlli' ).click( function(event) {
        if ($("#upload").hasClass( "hidden" )){
            $("#upload").removeClass("hidden");
        } else {
            $("#upload").addClass("hidden");
        }
    });

    $( '#upload' ).change( function(event) {
          var reader = new FileReader();

          reader.onload = function(event) {
            var jsonObj = JSON.parse(event.target.result);
            console.log(jsonObj);
            caricaPuntiCorrelazione(jsonObj);
            $("#upload").addClass("hidden");
          }

          reader.readAsText(event.target.files[0]);$("upload").removeClass("hidden");
    });

    $( '#clip' ).click( function(event) {
        if ($("#clip").hasClass( "active" )){
            map_sorgente.removeInteraction(drawInteraction);
            map_sorgente.removeInteraction(modifyInteraction);
        } else {
            map_sorgente.addInteraction(drawInteraction);
            map_sorgente.addInteraction(modifyInteraction);
        }
    });

    $( '#errore' ).click( function(event) {
        modalLog()
    });

    $( '#esito' ).click( function(event) {
        modalLog()
    });

    $('#download').attr({target: '_blank',
                    href  : 'http://localhost/directory/file.pdf'});

    $('#alpha').on('click', function() {
        $(this).val(this.checked ? 1 : 0);
        $(this).next().text($(this).val());
    });

    console.log('doc ready');
    //$('body').addClass("fill");
    $('#map_sorgente').height($(window).height()-200);
    $('#map_destinazione').height($(window).height()-200);

    $( '#test' ).click( function(event){
    map_destinazione.getView().fit(targetExtent, map_destinazione.getSize());
    });

    $( '#test2' ).click( function(event){
{% if source.target %}
    map_destinazione.getView().fit({{source.targetExtent}}, map_destinazione.getSize());
{% endif %}
    });

});

window.app = {};
var app = window.app;

/**
 * @constructor
 * @extends {ol.interaction.Pointer}
 */
app.Drag = function() {

  ol.interaction.Pointer.call(this, {
    handleDownEvent: app.Drag.prototype.handleDownEvent,
    handleDragEvent: app.Drag.prototype.handleDragEvent,
    handleMoveEvent: app.Drag.prototype.handleMoveEvent,
    handleUpEvent: app.Drag.prototype.handleUpEvent
  });

  /**
   * @type {ol.Pixel}
   * @private
   */
  this.coordinate_ = null;

  /**
   * @type {string|undefined}
   * @private
   */
  this.cursor_ = 'pointer';

  /**
   * @type {ol.Feature}
   * @private
   */
  this.feature_ = null;

  /**
   * @type {string|undefined}
   * @private
   */
  this.previousCursor_ = undefined;

};
ol.inherits(app.Drag, ol.interaction.Pointer);

/**
 * @param {ol.MapBrowserEvent} evt Map browser event.
 * @return {boolean} `true` to start the drag sequence.
 */
app.Drag.prototype.handleDownEvent = function(evt) {
  var map = evt.map;

  var feature = map.forEachFeatureAtPixel(evt.pixel,
      function(feature, layer) {
        return feature;
      },
      null,
      function(layer) {
        return layer === controllo_sorgente || layer === controllo_destinazione;
      });

  if (feature) {
    this.coordinate_ = evt.coordinate;
    this.feature_ = feature;
  }

  return !!feature;
};

/**
 * @param {ol.MapBrowserEvent} evt Map browser event.
 */
app.Drag.prototype.handleDragEvent = function(evt) {

  var map = evt.map;

  var feature = map.forEachFeatureAtPixel(evt.pixel,
      function(feature, layer) {
        return feature;
      },
      null,
      function(layer) {
        return layer === controllo_sorgente || layer === controllo_destinazione;
      });

  var deltaX = evt.coordinate[0] - this.coordinate_[0];
  var deltaY = evt.coordinate[1] - this.coordinate_[1];

  var geometry = /** @type {ol.geom.SimpleGeometry} */
      (this.feature_.getGeometry());
  geometry.translate(deltaX, deltaY);

  this.coordinate_[0] = evt.coordinate[0];
  this.coordinate_[1] = evt.coordinate[1];
};

/**
 * @param {ol.MapBrowserEvent} evt Event.
 */
app.Drag.prototype.handleMoveEvent = function(evt) {
  if (this.cursor_) {
    var map = evt.map;
    var feature = map.forEachFeatureAtPixel(evt.pixel,
        function(feature, layer) {
          return feature;
      },
      null,
      function(layer) {
        return layer === controllo_sorgente || layer === controllo_destinazione;
        });
    var element = evt.map.getTargetElement();
    if (feature) {
      if (element.style.cursor != this.cursor_) {
        this.previousCursor_ = element.style.cursor;
        element.style.cursor = this.cursor_;
      }
    } else if (this.previousCursor_ !== undefined) {
      element.style.cursor = this.previousCursor_;
      this.previousCursor_ = undefined;
    }
  }
};

/**
 * @param {ol.MapBrowserEvent} evt Map browser event.
 * @return {boolean} `false` to stop the drag sequence.
 */
app.Drag.prototype.handleUpEvent = function(evt) {
  this.coordinate_ = null;
  this.feature_ = null;
  return false;
};

var controlInteractions = ol.interaction.defaults().extend([new app.Drag()]);
var drawInteraction, modifyInteraction, clipInteractions;

function enableDownloadPrint(id, geotiff){
    var filename = geotiff.split('/').pop().split('#')[0].split('?')[0];
    $('#download').removeClass("hidden");
    $('#download').attr("href", geotiff);
    $('#download').attr("download", filename);
    $('#print').removeClass("hidden");
    $('#print').attr("href", "/warp/print/"+id+"/");
    $('#errore').addClass("hidden");
}

function aggiungiControllo(){
    var newControlSorgente = new ol.Feature({
            geometry: new ol.geom.Point(map_sorgente.getView().getCenter()),
            indice: controlli.length+1
        });
    var newControlDestinazione = new ol.Feature({
            geometry: new ol.geom.Point(map_destinazione.getView().getCenter()),
            indice: controlli.length+1
        });
    controllo_sorgente.getSource().addFeature( newControlSorgente );
    controllo_destinazione.getSource().addFeature( newControlDestinazione );
    controlli.push([newControlSorgente,newControlDestinazione]);
}

function caricaControllo(coord){
    var newControlSorgente = new ol.Feature({
            geometry: new ol.geom.Point(coord[0]),
            indice: controlli.length+1
        });
    var newControlDestinazione = new ol.Feature({
            geometry: new ol.geom.Point(coord[1]),
            indice: controlli.length+1
        });
    controllo_sorgente.getSource().addFeature( newControlSorgente );
    controllo_destinazione.getSource().addFeature( newControlDestinazione );
    controlli.push([newControlSorgente,newControlDestinazione]);
}

function rimuoviControllo(){
        if ( controlli.length > 0 ) {
            ultimoControllo = controlli[controlli.length-1];
            controllo_sorgente.getSource().removeFeature(ultimoControllo[0]);
            controllo_destinazione.getSource().removeFeature(ultimoControllo[1]);
            controlli.pop();
            return true
        } else {
            return false
        }
    }

function resetControlli(){
        var ctrl = true;
        while (ctrl) {
            ctrl = rimuoviControllo();
        }
    }

function resetClip(){
      clipSourceFeatures = new ol.Collection();
      clipSourceOverlay.setSource(new ol.source.Vector({features: clipSourceFeatures}));
      initInteractions(clipSourceFeatures);

      try {
        map_sorgente.removeInteraction(drawInteraction);
        map_sorgente.removeInteraction(modifyInteraction);
      } catch(e){}

      map_sorgente.addInteraction(drawInteraction);
      map_sorgente.addInteraction(modifyInteraction);
      clipTargetFeatures = new ol.Collection();
      clipTargetOverlay.setSource(new ol.source.Vector({features: clipTargetFeatures}));
    }

function caricaPuntiCorrelazione(listaPunti) {
        resetControlli();
        for (var i = 0; i < listaPunti.length; i++) {
            caricaControllo(listaPunti[i]);
        }
        extent = controllo_destinazione.getSource().getExtent();
        {% if source.target %}
        map_destinazione.getView().fit(extent, map_destinazione.getSize());
        {% endif %}
    }

function initInteractions(features){
        drawInteraction = new ol.interaction.Draw({
            features: features,
            type: /** @type {ol.geom.GeometryType} */ ("Polygon")
        });

        modifyInteraction = new ol.interaction.Modify({
            features: features,
            // the SHIFT key must be pressed to delete vertices, so
            // that new vertices can be drawn at the same position
            // of existing vertices
            deleteCondition: function(event) {
                return ol.events.condition.shiftKeyOnly(event) &&
                ol.events.condition.singleClick(event);
            }
        });
    }

//extent: An array of numbers representing an extent: [minx, miny, maxx, maxy]



function getCorrelationMatrix(){
    var sorgente_features = controllo_sorgente.getSource().getFeatures();
    var sorgente_json = JSON.parse(geoJson_convertitore.writeFeatures(sorgente_features));
    var destinazione_features = controllo_destinazione.getSource().getFeatures();
    var destinazione_json = JSON.parse(geoJson_convertitore.writeFeatures(destinazione_features));
    //console.log (destinazione_json);

    var correlazione = [];
    for (var i = 0; i < destinazione_json.features.length; i++) {
        correlazione.push([[],[]]);
    }
    //console.log (correlazione);
    for (var i = 0; i < destinazione_json.features.length; i++) {
        correlazione[sorgente_json.features[i].properties.indice-1][0] = sorgente_json.features[i].geometry.coordinates;
        correlazione[destinazione_json.features[i].properties.indice-1][1] = destinazione_json.features[i].geometry.coordinates;
    }
    //console.log (correlazione);
    return correlazione;
}

function translateExtent(sourceExtent,direction){
        var correlazione = getCorrelationMatrix();
        console.log(correlazione[0][direction[0]][0],correlazione[0][direction[0]][1]);
        console.log(correlazione[0][direction[1]][0],correlazione[0][direction[1]][1]);
        var sourceXMinDiff = correlazione[0][direction[0]][0] - sourceExtent[0];
        var sourceXMaxDiff = sourceExtent[2] - correlazione[0][direction[0]][0];
        var sourceYMinDiff = correlazione[0][direction[0]][1] - sourceExtent[1];
        var sourceYMaxDiff = sourceExtent[3] - correlazione[0][direction[0]][1];
        var sourceDeltaX = correlazione[1][direction[0]][0] - correlazione[0][direction[0]][0];
        var sourceDeltaY = correlazione[1][direction[0]][1] - correlazione[0][direction[0]][1];
        var destDeltaX = correlazione[1][direction[1]][0] - correlazione[0][direction[1]][0];
        var destDeltaY = correlazione[1][direction[1]][1] - correlazione[0][direction[1]][1];
        var ratioDeltaX = destDeltaX/sourceDeltaX;
        var ratioDeltaY = destDeltaY/sourceDeltaY;
        var destXMinDiff = sourceXMinDiff * ratioDeltaX;
        var destXMaxDiff = sourceXMaxDiff * ratioDeltaX;
        var destYMinDiff = sourceYMinDiff * ratioDeltaY;
        var destYMaxDiff = sourceYMaxDiff * ratioDeltaY;
        var destExtent = [correlazione[0][direction[1]][0]-destXMinDiff, correlazione[0][direction[1]][1]-destYMinDiff, correlazione[0][direction[1]][0]+destXMaxDiff, correlazione[0][direction[1]][1]+destYMaxDiff]
        console.log (sourceExtent);
        console.log (destExtent);
        return destExtent;
}

function syncSourceView() {
        if (controllo_sorgente.getSource().getFeatures().length > 1 && syncEnable && document.getElementById('autopan').checked){
            console.log("syncSourceview",syncEnable);
            var dest_extent = map_destinazione.getView().calculateExtent(map_destinazione.getSize());
            var source_extent = map_sorgente.getView().calculateExtent(map_sorgente.getSize());
            console.log("PRE",dest_extent,source_extent)
            map_sorgente.getView().fit(translateExtent(dest_extent,[1,0]), map_sorgente.getSize());
            syncEnable = false;
            var dest_extent = map_destinazione.getView().calculateExtent(map_destinazione.getSize());
            var source_extent = map_sorgente.getView().calculateExtent(map_sorgente.getSize());
            console.log("POST",dest_extent,source_extent)
            setTimeout(function(){ syncEnable = true; }, 200);
        }
}

function syncDestView() {
        if (controllo_sorgente.getSource().getFeatures().length > 1 && syncEnable && document.getElementById('autopan').checked){
            console.log("syncDestview",syncEnable);
            var dest_extent = map_destinazione.getView().calculateExtent(map_destinazione.getSize());
            var source_extent = map_sorgente.getView().calculateExtent(map_sorgente.getSize());
            console.log("PRE",dest_extent,source_extent)
            console.log(source_extent,translateExtent(source_extent,[0,1]));
            map_destinazione.getView().fit(translateExtent(source_extent,[0,1]), map_destinazione.getSize());
            syncEnable = false;
            var dest_extent = map_destinazione.getView().calculateExtent(map_destinazione.getSize());
            var source_extent = map_sorgente.getView().calculateExtent(map_sorgente.getSize());
            console.log("POST",dest_extent,source_extent)
            setTimeout(function(){ syncEnable = true; }, 200);
        }

}

function init(){


    function controlStyle(feature) {
        //console.log(feature.get('indice'));
        var style = new ol.style.Style ({
            image: new ol.style.Icon( ({
              anchor: [0.5, 1],
              anchorXUnits: 'fraction',
              anchorYUnits: 'fraction',
              opacity: 0.8,
              src: '{{settings.STATIC_URL}}warp/marker_'+feature.get('indice')+'.png'
            }))
          });
        return [style]
    }


    controllo_sorgente =  new ol.layer.Vector({
      source: new ol.source.Vector({
            projection: localProjection,
          }),
      style: controlStyle
    })

    controllo_destinazione =  new ol.layer.Vector({
      source: new ol.source.Vector({
            projection: targetProjection
          }),
      style: controlStyle,
      title: 'Correlation markers',
    })


    //clip sorgente overlay
    {% if source.clipSorgente %}
    var geojsonObject = {{source.clipSorgente|safe}};
    clipSourceFeatures = new ol.Collection( new ol.format.GeoJSON().readFeatures(geojsonObject));//, {
        //featureProjection: localProjection
    //});

    {% else %}
    clipSourceFeatures = new ol.Collection();
    {% endif %}
    clipSourceOverlay = new ol.layer.Vector({
      source: new ol.source.Vector({features: clipSourceFeatures}),
      style: new ol.style.Style({
        fill: new ol.style.Fill({
          color: 'rgba(255, 255, 255, 0.2)'
        }),
        stroke: new ol.style.Stroke({
          color: '#ffcc33',
          width: 3
        }),
        image: new ol.style.Circle({
          radius: 7,
          fill: new ol.style.Fill({
            color: '#ffcc33'
          })
        })
      })
    });

    initInteractions(clipSourceFeatures);{% if not source.clipSorgente %}{% endif %}

    map_sorgente = new ol.Map({
      interactions: controlInteractions,
      layers: [
        new ol.layer.Image({
          source: new ol.source.ImageStatic({
            attributions: [
              new ol.Attribution({
                html: '<h3>{{source.attribution}}ss</h3>'
              })
            ],
            url: '{{source.img.url}}?dum='+getRandomInt(1000000,9999999).toString(),
            projection: localProjection,
            imageExtent: localExtent
          })
        }),
        clipSourceOverlay,
        controllo_sorgente
      ],
      target: 'map_sorgente',
      view: new ol.View({
        projection: localProjection,
        center: ol.extent.getCenter(localExtent),
        zoom: 2
      })
    });


    //clip destinazione overlay
      {% if source.clipDestinazione %}
      var geojsonObject = {{source.clipDestinazione|safe}};
      clipTargetFeatures = new ol.Collection( new ol.format.GeoJSON().readFeatures(geojsonObject, {
          //featureProjection: targetProjection
      }));
      {% else %}
      clipTargetFeatures = new ol.Collection();
      {% endif %}
      clipTargetOverlay = new ol.layer.Vector({
        source: new ol.source.Vector({features: clipTargetFeatures}),
        title: 'clipping polygon',
        style: new ol.style.Style({
          fill: new ol.style.Fill({
            color: 'rgba(255, 255, 255, 0.2)'
          }),
          stroke: new ol.style.Stroke({
            color: '#ffcc33',
            width: 3
          }),
          image: new ol.style.Circle({
            radius: 7,
            fill: new ol.style.Fill({
              color: '#ffcc33'
            })
          })
        })
      });

    console.log(clipTargetOverlay.getExtent());


    georef_overlay =
          new ol.layer.Image({
            title: 'georeferenced image',
{% if source.target %}
            source: new ol.source.ImageStatic({
              url: '{{source.target}}',
              size: {{source.targetSize}},
              projection: targetProjection,
              imageExtent: {{source.targetExtent}},
              attributions: [new ol.Attribution({
                html: '{{source.note|escapejs}}'
              })]
            })
{% endif %}
          });



    map_destinazione = new ol.Map({
      interactions: ol.interaction.defaults().extend([new app.Drag()]),
      layers: [
{{ source.dataset.baselayer | escape | safe }}

          georef_overlay,
          clipTargetOverlay,
          controllo_destinazione
      ],
      controls: ol.control.defaults().extend([
        //new ol.control.ScaleLine(),
        new ol.control.MousePosition(),
        new ol.control.OverviewMap()
      ]),
      target: 'map_destinazione',
      view: new ol.View({
        projection: targetProjection,
        center: ol.extent.getCenter(targetExtent),
        zoom: 22
      })
    });

{% if not source.target %}
    map_destinazione.getView().fit(targetExtent, map_destinazione.getSize());
{% else %}
    map_destinazione.getView().fit({{source.targetExtent}}, map_destinazione.getSize());
    enableDownloadPrint({{source.id}}, "{{source.download}}");
{% endif %}

    map_destinazione.on('moveend', syncSourceView);
    map_sorgente.on('moveend', syncDestView);
    map_destinazione.on('zoomend', syncSourceView);
    map_sorgente.on('zoomend', syncDestView);

    var layerSwitcher = new ol.control.LayerSwitcher({
        tipLabel: 'Legend' // Optional label for button
    });
    map_destinazione.addControl(layerSwitcher);

{% if source.correlazione %}
    caricaPuntiCorrelazione(JSON.parse('{{source.correlazione}}'));
{% endif %}


}


</script>
{% endblock %}
{% block onload %} {% if source %}onload="init()"{% endif %}{% endblock %}
{% block titolo %}{{ dataset.epsg }}Georeferencing {% if source %}{{source.attribution}}{% endif %}{% endblock %}
{% block menu %}
<li>
<a href="/warp/{{ dataset }}">dataset {{ dataset }} detail</a>
</li>
<li>
<a href="/warp/viewdataset/{{ dataset }}">dataset {{ dataset }} overview</a>
</li>
{% endblock %}
{% block contenuto %}


{% if not source %}
<div id="master" class="container fill">
    <div class="row-fluid fill">
            {% if errore %}<div class="alert alert-warning"><strong>ERROR:</strong>{{errore}}</div>{% endif %}
            <form id="fase1" role="form" action="/warp/newimage/{{ dataset }}/" method="post"  enctype="multipart/form-data">
                {% csrf_token %}
                <div class="form-group">
                    <label for="titolo">Image name</label>
                    {{form.titolo}}
                    <label for="note">Notes</label>
                    {{form.note}}
                    <label for="sorgente">Source image file</label><br/>
                    <span class="btn btn-default btn-file">
                        {{form.sorgente}}
                    </span>
                </div>
                <button type="submit" class="btn btn-default">Load</button>
            </form>
  </div>
</div>
{% else %}
<div id="master" class="container-fluid fill">
    <div class="row-fluid fill">

        <div class="col-md-12 fill">
            {% if errore %}<div class="alert alert-warning"><strong>ERROR:</strong>{{errore}}</div>{% endif %}

                    <!-- <div class="panel panel-default fill"> -->

                            <form id="fase2" class="form-inline" role="form" method="post">
                                <input type="hidden" name="id" value="{{source.id}}">
                                <a class="btn btn-default" id="aggiungiControllo" role="button">Add</a>
                                <a class="btn btn-default" id="rimuoviControllo"  role="button">Remove</a>
                                <a class="btn btn-default" data-toggle="button" id="clip"   role="button">Clip</a>
                                <a class="btn btn-danger" id="resetControlli"   role="button">Reset</a>
                                <a class="btn btn-default" id="saveControlli"   role="button">Save</a>
                                <a class="btn btn-default" id="loadControlli"   role="button">Load</a>
                                <a class="btn btn-default hidden" id="test"   role="button">test</a>
                                <a class="btn btn-default hidden" id="test2"   role="button">test</a>
                                <label class="checkbox-inline"><input id="alpha" name="alpha" type="checkbox" value="0">Transparency</label>
                                <input class="btn btn-default hidden" type="file" id="upload" />
                                <div class="pull-right">
                                    <a id="errore"  class="hidden btn btn-warning" role="button">Loading error</a>
                                    <a id="esito"  class="hidden btn btn-success" role="button">Georeferencing report</a>
                                    <a id="download" class="hidden btn btn-success" role="button">Download</a>
                                    <a id="print" class="hidden btn btn-success" target="_blank" href="#" role="button">Print</a>
                                    <div class="hidden" id="progress"></div>
                                    <button type="submit" class="btn btn-primary">Georeference</button>
                                </div>
                            </form>


                    <div class="panel-body">
                        <div class="panel panel-default col-md-6">
                            <div class="panel-body">
                                <div id="map_sorgente" class=""></div>
                            </div>

                        </div>

                        <div class="panel panel-default col-md-6">
                            <div class="panel-body">
                                <div id="map_destinazione"></div>
                            </div>
                        </div>
                        <label class="checkbox-inline"><input id="autopan" name="alpha" type="checkbox" value="0">Auto pan/zoom</label>
                    </div>
                <!-- </div> -->
        </div>
  </div>
</div>
{% endif %}
{% endblock %}
{% block piedipagina %}{% endblock %}
