/* Copyright 2005 Camptocamp SA.
   Licensed under the GPL (www.gnu.org/copyleft/gpl.html) */

var currentFormat = '';

function hideSitFeature(event) {
  if (cw3_tools.indexOf('sitrotate') > -1){
    mainmap.removeSitFeature('map');
  }
}
function hideDxfFeature(event) {
  if (cw3_tools.indexOf('dxf_rect') > -1 || cw3_tools.indexOf('dxf_polygon') > -1 || cw3_tools.indexOf('dxf_move') > -1){
    mainmap.removeDxfFeature('map');
  }
}
function addToolSitListeners() {

  for (var i = 0; i < cw3_tools.length; i++ )    {
    if (cw3_tools[i] != 'sitrotate') {
      elt = xGetElementById(cw3_tools[i]);
      EventManager.Add(elt, 'click', hideSitFeature, false);
      elt = xGetElementById(cw3_tools[i] + "_icon");
      EventManager.Add(elt, 'click', hideSitFeature, false);
    }
    if (cw3_tools[i] != 'dxf_rect' && cw3_tools[i] != 'dxf_polygon' && cw3_tools[i] != 'dxf_move') {
      elt = xGetElementById(cw3_tools[i]);
      //EventManager.Add(elt, 'click', hideDxfFeature, false);
      elt = xGetElementById(cw3_tools[i] + "_icon");
      //EventManager.Add(elt, 'click', hideDxfFeature, false);
    }
  }
}
//EventManager.Add(window, 'load', addToolSitListeners, false);

/***** SIT tools ****/

Map.prototype.form2SitFeature = function(feature, aDisplay) {

  var marginxl = myform.sitMarginXl.value;
  var marginxr = myform.sitMarginXr.value;
  var marginyb = myform.sitMarginYb.value;
  var marginyt = myform.sitMarginYt.value;
  
  // switch the scale options list if the format has changed
  selectedFormat = xGetElementById('order_sit_format').value;
  // when arriving on the page for the first time
  if (currentFormat == '') {
    currentFormat = selectedFormat;
  }
  // if user changed the format
  if (currentFormat != selectedFormat){
    switchScale(selectedFormat);
    currentFormat = selectedFormat;
  }

  var paperx = xGetElementById('sit' + myform.order_sit_format.value + 'x').value;
  var papery = xGetElementById('sit' + myform.order_sit_format.value + 'y').value;

// landscape
  if (document.getElementById('lsp_sit').checked == true) {
    var papertmp = paperx;
	var marginltmp = marginxl;
	var marginrtmp = marginxr;
    paperx = papery;
    papery = papertmp;
	marginxl = marginyb;
	marginxr = marginyt;
	marginyb = marginltmp;
	marginyt = marginrtmp;
  }

  //var scale = myform.order_sit_scale.value.substr(2);
  var scale = myform.order_sit_scale.value;
  // IE hack because IE is a stupit shit browser
  if (scale.indexOf(':') >=0){
    scale = scale.substr(scale.indexOf(':')+1);
  }
  var sizexl = (paperx / 2 - marginxl) / 1000 * scale;
  var sizexr = (paperx / 2 - marginxr) / 1000 * scale;
  var sizeyb = (papery / 2 - marginyb) / 1000 * scale;
  var sizeyt = (papery / 2 - marginyt) / 1000 * scale;
  Logger.note(scale);

  feature.vertices = Array();
  var vertex;
  vertex = new Vertex(-sizexl, -sizeyb);
  vertex.index = 0;
  feature.vertices.push(vertex);
  vertex = new Vertex(-sizexl, sizeyt);
  vertex.index = 1;
  feature.vertices.push(vertex);
  vertex = new Vertex(sizexr, sizeyt);
  vertex.index = 2;
  feature.vertices.push(vertex);
  vertex = new Vertex(sizexr, -sizeyb);
  vertex.index = 3;
  feature.vertices.push(vertex);
  vertex = new Vertex(-sizexl, -sizeyb);
  vertex.index = 4;
  feature.vertices.push(vertex);

  aDisplay.angle = parseFloat(myform.sitMapAngle.value);
  if (isNaN(aDisplay.angle)) {
    aDisplay.angle = 0;
  }
  var cx = parseFloat(myform.sitMapCenterX.value);
  var cy = parseFloat(myform.sitMapCenterY.value);
  if (isNaN(cx) || isNaN(cy)) {
    cx = (this.extent.xmax + this.extent.xmin) / 2;
    cy = (this.extent.ymax + this.extent.ymin) / 2;
  }
  for (var i = 0; i < feature.vertices.length; i++) {
    feature.vertices[i].x = feature.vertices[i].x + cx;
    feature.vertices[i].y = feature.vertices[i].y + cy;
  }
  feature.rotate(aDisplay.angle);
}

Map.prototype.getSitFeature = function(aDisplay) {
  var feature = null;
  for (var i=0; i < this.currentLayer.features.length; i++) {
    if (this.currentLayer.features[i].id == "sit_overview") {
      feature = this.currentLayer.features[i];
    }
  }

  if (feature == null) {
    var feature = new Feature("POLYGON((0 0 1 1))");
    this.form2SitFeature(feature, aDisplay);

    feature.id = "sit_overview";
    this.currentLayer.addFeature(feature);
  }
  return feature;
}

Map.prototype.hideSitFeature = function(aDisplayName) {
  var aDisplay = this.getDisplay(aDisplayName);

  var feature = this.getSitFeature(aDisplay);
  if (aDisplay.getDisplayFeature(feature) != null) {
    if (aDisplay.currentLayer.id != 'map_drawing'){
      this.setCurrentLayer('drawing');
    }
    for (var i = 0;i < aDisplay.currentLayer.childNodes.length; i++){
      if (aDisplay.currentLayer.childNodes[i] == aDisplay.getDisplayFeature(feature)){
        aDisplay.currentLayer.removeChild(aDisplay.getDisplayFeature(feature));
        break;
      }
    }  
  }
}

Map.prototype.showSitFeature = function(aDisplayName) {
  var aDisplay = this.getDisplay(aDisplayName);

  var feature = this.getSitFeature(aDisplay);

  Logger.note('currentLayer ' + aDisplay.currentLayer.id);

  if (aDisplay.getDisplayFeature(feature) == null) {
    aDisplay.drawFeature(aDisplay.currentLayer, feature, _OFF, false);
  }
}

Map.prototype.updateSitFeature = function(aDisplayName) {
  this.hideSitFeature(aDisplayName);
  var aDisplay = this.getDisplay(aDisplayName);
  var feature = this.getSitFeature(aDisplay);
  this.form2SitFeature(feature, aDisplay);
  this.showSitFeature(aDisplayName);
  
  // deactivate submitform if feature is modified
  elt = xGetElementById('order_submit');
  if (elt){
    deactivateSubmit();
  }
}

Map.prototype.removeSitFeature = function(aDisplayName) {
  this.hideSitFeature(aDisplayName);
  var aDisplay = this.getDisplay(aDisplayName);
  var feature = this.getSitFeature(aDisplay);
  this.currentLayer.features.pop(feature);
}

Map.prototype.sitrotate = function(aDisplay) {

  this.resetMapEventHandlers();

  this.setCurrentLayer('drawing');
  this.getDisplay(aDisplay).mouseAction = new RotateFeatureTool(this.getDisplay(aDisplay));

  this.getDisplay(aDisplay).currentLayer = xGetElementById(this.getDisplay(aDisplay).id + "_" + this.getDisplay(aDisplay)._map.currentLayer.id);

  this.showSitFeature(aDisplay);

  this.onFeatureSelected = function(aFeature) {
    // hide sit_overview
    emptyForm();
  }
  this.onFeatureChange = function(aFeature) {
    // send center coords (Feature.getCentroid), angle to the form
    var center = aFeature.getCentroid();
    myform.sitMapCenterX.value = center.vertices[0].x;
    myform.sitMapCenterY.value = center.vertices[0].y;
    myform.sitMapAngle.value = this.getDisplay(aDisplay).angle;
    // deactivate submitform if feature is modified
    elt = xGetElementById('order_submit');
    if (elt){
      deactivateSubmit();
    }
  }
}

Feature.prototype.rotate = function(angle) {
  if (angle != null && angle != 0) {

    // Center
    var center = this.getCentroid();
    var cx = center.vertices[0].x;
    var cy = center.vertices[0].y;

    for (var i = 0; i < this.vertices.length; i++) {
      var vertx = this.vertices[i].x;
      var verty = this.vertices[i].y;

      // move to origin
      var x = vertx - cx;
      var y = verty - cy;

      // rotate
      var xp = x * Math.cos(angle) - y * Math.sin(angle);
      var yp = x * Math.sin(angle) + y * Math.cos(angle);

      var newx = this.vertices[i].x - x + xp;
      var newy = this.vertices[i].y - y + yp;
      this.vertices[i].x = newx;
      this.vertices[i].y = newy;
    }
  }
}

Map.prototype.dxf_rect = function(aDisplay) {

  this.resetMapEventHandlers();
  
  this.setCurrentLayer('drawing');
  this.getDisplay(aDisplay).setTool('draw.box');

  this.showDxfFeature(aDisplay);

  this.onNewFeature = function(aFeature) {
    this.getDisplay(aDisplay).clearLayer('drawing');
  };
  this.onFeatureChange = function(aFeature) {
    alert (aFeature.vertices.length);
  }
  this.onFeatureInput = function(aFeature) {
    aFeature.operation = "";
    // new feature 
    // default id is some stupid numerial value, set something more usable
    aFeature.id = 'dxfFeature';
    // remove existing feature (if exist)
    for (var i = 0; i < this.currentLayer.features.length; i++) {
      if (this.currentLayer.features[i].id == 'dxfFeature') {
        this.currentLayer.delFeature(this.currentLayer.features[i], 'dxfFeature');
      }
    }
    // add new feature
    this.currentLayer.addFeature(aFeature);
    
    this.getDisplay(aDisplay).clearLayer('drawing');
    this.getDisplay(aDisplay).drawFeature(this.getDisplay(aDisplay).currentLayer, aFeature, _OFF);
    storeDxfFeatures();
    //mainmap.geoshopRecenter(aFeature); -> Zoom auf Feature nach dem zeichnen
  };
};

Map.prototype.dxf_polygon = function(aDisplay) {
  this.resetMapEventHandlers();
   
  this.getDisplay(aDisplay).setTool('draw.poly');
  this.onNewFeature = function(aFeature) {
    this.getDisplay(aDisplay).clearLayer('drawing');
  };
  this.onFeatureInput = function(aFeature) {
    aFeature.operation = "";
    // new feature
    // default id is some stupid numerial value, set something more usable
    aFeature.id = 'dxfFeature';
    // remove existing feature (if exist)
    for (var i = 0; i < this.currentLayer.features.length; i++) {
      if (this.currentLayer.features[i].id == 'dxfFeature') {
        this.currentLayer.delFeature(this.currentLayer.features[i], 'dxfFeature');
      }
    }
    // add new feature
    this.currentLayer.addFeature(aFeature);
    this.getDisplay(aDisplay).clearLayer('drawing');
    this.getDisplay(aDisplay).drawFeature(this.getDisplay(aDisplay).currentLayer, aFeature, _OFF);

    storeDxfFeatures();
    mainmap.geoshopRecenter(aFeature);
  };
};

Map.prototype.dxf_move = function(aDisplay) {
  this.resetMapEventHandlers();
  this.getDisplay(aDisplay).setTool('move');
  this.onFeatureChange = function(aFeature) {
    storeDxfFeatures();
    updateFeatureCoords();
  }
  this.onFeatureSelected = function(aFeature) {
  }
};

Map.prototype.getDxfFeature = function(aDisplay) {
  var feature = null;
  for (var i=0; i < this.currentLayer.features.length; i++) {
    //if (this.currentLayer.features[i].id != 'pdf_overview'){
    if (this.currentLayer.features[i].id == 'dxfFeature'){
      feature = this.currentLayer.features[i];
    }    
  }
  if (feature == null) {
    // rebuild feature from wkt !
    try {
    	featureGeom
    }
    catch (e){
      return false;
    }
    if (featureGeom != '') {
      var feature = new Feature(featureGeom);
      feature.id = 'dxfFeature';

      this.currentLayer.addFeature(feature);
    } else {
      return false;
    }
  }
  return feature;
}

Map.prototype.showDxfFeature = function(aDisplayName) {
  var aDisplay = this.getDisplay(aDisplayName);

  var feature = this.getDxfFeature(aDisplay);

  Logger.note('currentLayer ' + aDisplay.currentLayer.id);

  if (aDisplay.getDisplayFeature(feature) == null) {
    aDisplay.drawFeature(aDisplay.currentLayer, feature, _OFF, false);
  }
}

Map.prototype.hideDxfFeature = function(aDisplayName) {
  var aDisplay = this.getDisplay(aDisplayName);

  var feature = this.getDxfFeature(aDisplay);
  if (aDisplay.getDisplayFeature(feature) != null) {
    if (aDisplay.currentLayer.id != 'map_drawing'){
      this.setCurrentLayer('drawing');
    }
    for (var i = 0;i < aDisplay.currentLayer.childNodes.length; i++){
      if (aDisplay.currentLayer.childNodes[i] == aDisplay.getDisplayFeature(feature)){
        aDisplay.currentLayer.removeChild(aDisplay.getDisplayFeature(feature));
        break;
      }
    }  
  }
}

Map.prototype.removeDxfFeature = function(aDisplayName) {
  this.hideDxfFeature(aDisplayName);
  var aDisplay = this.getDisplay(aDisplayName);
  var feature = this.getDxfFeature(aDisplay);

  this.currentLayer.delFeature(feature, 'dxfFeature');
}

/**
 * Fills the feature form input with the edited features of the current layer
 */
storeDxfFeatures = function() {
  var feature;
  var nbFeatures = mainmap.currentLayer.features.length;
  var fId = getCurrentDisplayedFeatureId();
  for (var i = 0; i < nbFeatures; i++) {
    if (mainmap.currentLayer.features[i].id == fId) {
      feature = mainmap.currentLayer.features[i];
      break;
    }
  }

  document.getElementById('dxf_feature').value = feature.getWKT();

  deactivateSubmit();
  return true;
};

/**
 * return the id of the feature currently displayed
 * only work as long as only one feature is displayed at once !
 */
function getCurrentDisplayedFeatureId () {
  var aDisplay = mainmap.getDisplay('map');
  var fId = '';
  for (var i = 0;i < aDisplay.currentLayer.childNodes.length; i++){
    fId = aDisplay.currentLayer.childNodes[i].id;
  }
  if (fId.length > 4){
    fId = fId.substr(4);
  }
  return fId;
}
