/* encoder decoder */
function eSN(N) {var sN=N<<1;sN=N<0?~(sN):sN;return(eN(sN));};
function eN(N) {var eS = "", S = String, C=S.fromCharCode;while (N>=0x20) {eS+=(C((0x20|(N & 0x1f))+63));N>>=5;}eS+=(C(N+63));return eS;};
function eP(P) {L=P.length,M=Math,F=M.floor,a=0,g=0,i=0,o=0,S='';for(var q=0;q<L;q++) {var p=P[q],t=F(p.lat()*1e5),n=(p.lng()*1e5);i=t-a;o=n-g;a=t;g=n;S+=eSN(i)+eSN(o);}return S;};
function dP (E) { var L = E.length; var I = 0; var A = []; var T = 0; var G = 0; while (I < L) { var b; var S = 0; var R = 0; do { b = E.charCodeAt(I++) - 63; R |= (b & 0x1f) << S; S += 5; } while (b >= 0x20); var t = ((R & 1) ? ~(R >> 1) : (R >> 1)); T += t; S = 0; R = 0; do { b = E.charCodeAt(I++) - 63; R |= (b & 0x1f) << S; S += 5; } while (b >= 0x20); var g = ((R & 1) ? ~(R >> 1) : (R >> 1)); G += g; A.push(new GLatLng(T * 1e-5, G * 1e-5)); } return A; };

function decodeLine (E) {var L = E.length,I = 0,A = [],T = 0,N = 0;while (I < L) {var b,S = 0,R = 0;do {b = E.charCodeAt(I++) - 63;R |= (b & 0x1f) << S;S += 5;} while (b >= 0x20);var t = ((R & 1) ? ~(R >> 1) : (R >> 1));T += t;S = 0;R = 0;do {b = E.charCodeAt(I++) - 63;R |= (b & 0x1f) << S;S += 5;} while (b >= 0x20);var n = ((R & 1) ? ~(R >> 1) : (R >> 1));N += n;A.push(new GLatLng(T*1e-5, N*1e-5));} return A;};

/* defining multiplier */
var mul = [null,
 [{m:1,l:'in meters (m)&nbsp;&nbsp;&nbsp;&nbsp;',s:'m',t:'meters'},
  {m:3.2808399,l:'in feet (ft)',s:'ft',t:'feet'} ],
 [{m:1,l:'in meters (m)&nbsp;&nbsp;',s:'m',t:'meters'},
  {m:1e-3,l:'in kilometers (km)',s:'km',t:'kilometers'},
  {m:3.2808399,l:'in feet (ft)',s:'ft',t:'feet'},
  {m:1.0936133,l:'in yards (yd)',s:'yd',t:'yards'},
  {m:6.21371192e-4,l:'in miles (mi)',s:'mi',t:'miles'} ],
 [{m:1,l:'in square meters (m&sup2;)',s:'m&sup2;',t:'square meters'}, 
  {m:1e-6,l:'in square kilometers (km&sup2;)',s:'km&sup2;',t:'square kilometers'},
  {m:1e-4,l:'in hectares (ha)',s:'ha',t:'hectares'},
  {m:2.47105381e-4,l:'in acres (ac)',s:'ac',t:'acres'},
  {m:10.7639104,l:'in square feet (ft&sup2;)',s:'ft&sup2;',t:'square feet'},
  {m:1.19599005,l:'in square yards (yd&sup2;)',s:'yd&sup2;',t:'square yards'},
  {m:3.8610215e-7 ,l:'in square miles (mi&sup2;)',s:'mi&sup2;',t:'square miles'} ],
 null];

var initfunc = [
/* 0 - No Tools Selected */
function() {
  $("#infodiv").html(' <-- Select tool to start').css('background-color', '#fff');
  $("#menudiv").html('');
}, 
/* 1 - Elevation */
function() {
  GEvent.clearListeners(document.map, 'click');
  GEvent.addListener(document.map, 'click', func[1]);
  document.map.clearOverlays(); 
  $("#infodiv").html('Click on the map to get elevation').highlightFade({start:'#f00',end:'#fcc', speed:'slow'});
  $("#menudiv").html('');
},        
/* 2 - Distance */
function() {
  GEvent.clearListeners(document.map, 'click');
  GEvent.addListener(document.map, 'click', func[2]);
  clearPoints();
  $("#infodiv").html('Click on the map to start measuring distance').highlightFade({start:'#f00',end:'#fcc', speed:'slow'});
  $("#menudiv").html('');  
}, 

/* 3 - Area */
function() {
  GEvent.clearListeners(document.map, 'click');
  GEvent.addListener(document.map, 'click', func[3]);
  clearPoints();$("#infodiv").html('Click on the map to start measuring area').highlightFade({start:'#f00',end:'#fcc', speed:'slow'});
  $("#menudiv").html('');
}, 

/* 4 - Cadastral */
function() { 
  GEvent.clearListeners(document.map, 'click');
  GEvent.addListener(document.map, 'click', func[4]);
  document.map.clearOverlays(); 
  $("#infodiv").html('Click on the map to get Cadastral Information').highlightFade({start:'#f00',end:'#fcc', speed:'slow'});
  $("#menudiv").html('');  
}

];  

var func = [null, 
/* 1 - Elevation */
function(overlay, point) {
  var buffer = new GLatLng((Math.floor(point.lat()*1e5)/1e5),(Math.floor(point.lng()*1e5)/1e5));  
  point = {x:buffer.x, y:buffer.y};
  $("#infodiv").html('Loading elevation...').highlightFade({start:'#ff0',end:'#ffc', speed:'slow'});
  var marker = new GMarker(point, {title:'Clicked point: ' + buffer.lat() + ', ' + buffer.lng(), clickable:false, draggable:false});
  document.map.clearOverlays();
  document.map.addOverlay(marker);
  resetAdvancedPermalink();
  document.permalink.elevation = escape(eP([buffer]));
  document.permalink.updated(); 
  xajax_getElevation(point);
}, 

/* 2 - Distance */
function(overlay, point) {
  var buffer = new GLatLng((Math.floor(point.lat()*1e5)/1e5),(Math.floor(point.lng()*1e5)/1e5));  
  point = buffer;
  document.points.push(point);  
  resetAdvancedPermalink();
  document.permalink.distance = escape(eP(document.points));
  document.permalink.updated(); 
  updateDistance(); 
}, 

/* 3 - Area */
function(overlay, point) {
  var buffer = new GLatLng((Math.floor(point.lat()*1e5)/1e5),(Math.floor(point.lng()*1e5)/1e5));  
  point = buffer;
  document.points.push(point);  
  resetAdvancedPermalink();
  document.permalink.area = escape(eP(document.points));
  document.permalink.updated(); 
  updateArea(); 
}, 

/* 4 - Cadastral */
function(overlay, point, trigger) { 
    var buffer = new GLatLng((Math.floor(point.lat()*1e5)/1e5),(Math.floor(point.lng()*1e5)/1e5));  
    point = buffer;
    resetAdvancedPermalink();
    document.permalink.cadastral = escape(eP([point]));
    document.permalink.updated(); 
    name=undefined==name?point.lat()+', '+point.lng():name;
    /*document.map.setCenter(point);*/
    var marker = new GMarker(point, {title:name,clickable:false, draggable:false});
    GEvent.clearListeners(document.map, 'click');
    document.map.clearOverlays();
    document.map.addOverlay(marker);
    var bb = document.map.getBounds(); 
    var sw = bb.getSouthWest();
    var ne = bb.getNorthEast();
    var cp = document.map.getCurrentMapType().getProjection();
    bb = sw.x + ',' + sw.y + ','+ ne.x + ',' + ne.y;
    sw = cp.fromLatLngToPixel(sw , document.map.getZoom());
    ne = cp.fromLatLngToPixel(ne , document.map.getZoom());
    var px = cp.fromLatLngToPixel(point , document.map.getZoom());
    var wx = px.x - sw.x; 
    var wy = px.y - ne.y;
    var mz = document.map.getSize();
    var url = 'http://ovc.catastro.meh.es/Cartografia/WMS/ServidorWMS.aspx?REQUEST=GetFeatureInfo&VERSION=1.1.1&SRS=EPSG:4326&BBOX='+ bb +'&WIDTH='+ mz.width +'&HEIGHT='+ mz.height +'&QUERY_LAYERS=catastro&X='+wx+'&Y='+wy;
    $("#r").remove();
    var lat = Math.round(point.lat()*1e6)/1e6;
    var lng = Math.round(point.lng()*1e6)/1e6;
    $("#infodiv").html('Clicked point: ' + lat + ', ' + lng + '. <span id="cdstrl">Please wait...</span>').highlightFade({start:'#ff0',end:'#ffc', speed:'slow'});
    $("#menudiv").html('<a href="javascript:;" onclick="javascript:initfunc[4]();">Reset</a>').highlightFade({start:'#0f0', speed:'slow'});;
    if(undefined == trigger) {
      trigger=0;
    }
    xajax_getFeatures(url, point.lat(), point.lng(), name, trigger);
}

]; 

function clearPoints() {
  document.points = new Array();
  document.map.clearOverlays();
}

function updateDistance() {
  if(1 == document.points.length) {
    document.map.clearOverlays();
    document.map.addOverlay(new GMarker(document.points[0], ICONS['start'], true));
    $("#infodiv").html('Please click one or more points to measure distance').highlightFade({start:'#ff0',end:'#ffc', speed:'slow'});;
    $("#menudiv").html('<a href="javascript:;" onclick="javascript:clearPoints();">Clear</a>');
  } else {
    document.map.clearOverlays();
    document.map.addOverlay(new GMarker(document.points[0], ICONS['start'], true));
    document.map.addOverlay(new GMarker(document.points[document.points.length - 1], ICONS['end'], true));
    var track = new GPolyline(document.points);
    document.map.addOverlay(track,'#09c', 4, 0.5);
    showDistance(track.Distance());
    $("#menudiv").html('<a href="javascript:;" onclick="javascript:removeLastDistance();">Remove Last</a> | <a href="javascript:;" onclick="javascript:initfunc[2]();">Clear</a>');
  }
}
function removeLastDistance() {
  document.points.pop();
  resetAdvancedPermalink();
  document.permalink.elevation = escape(eP(document.points));
  document.permalink.updated(); 
  updateDistance();
}

function updateArea() {
  if(1 == document.points.length) {
    document.map.clearOverlays();
    document.map.addOverlay(new GMarker(document.points[0], ICONS['start'], true));
    $("#infodiv").html('Please click two or more points to measure area').highlightFade({start:'#ff0',end:'#ffc', speed:'slow'});;
    $("#menudiv").html('<a href="javascript:;" onclick="javascript:clearPoints();">Clear</a>');
  } else if(2 == document.points.length) {
    document.map.clearOverlays();
    document.map.addOverlay(new GMarker(document.points[0], ICONS['start'], true));
    document.map.addOverlay(new GMarker(document.points[document.points.length - 1], ICONS['end'], true));
    var track = new GPolygon(document.points,'#09c', 4, 1,'#c9f',0.5);
    document.map.addOverlay(track);
    document.map.addOverlay(new GPolyline([document.points[0], document.points[document.points.length-1]]),'#09c', 2, 0.5);
    $("#infodiv").html('Please click one or more points to measure area').highlightFade({start:'#ff0',end:'#ffc', speed:'slow'});;
    $("#menudiv").html('<a href="javascript:;" onclick="javascript:removeLastArea();">Remove Last</a> | <a href="javascript:;" onclick="javascript:initfunc[3]();">Clear</a>');
  } else {
    document.map.clearOverlays();
    document.map.addOverlay(new GMarker(document.points[0], ICONS['start'], true));
    document.map.addOverlay(new GMarker(document.points[document.points.length - 1], ICONS['end'], true));
    var track = new GPolygon(document.points,'#09c', 4, 1,'#c9f',0.5);
    document.map.addOverlay(track);
    document.map.addOverlay(new GPolyline([document.points[0], document.points[document.points.length-1]]),'#09c', 2, 0.5);
    showArea(track.Area());
    $("#menudiv").html('<a href="javascript:;" onclick="javascript:removeLastArea();">Remove Last</a> | <a href="javascript:;" onclick="javascript:initfunc[3]();">Clear</a>');    
  }
}
function removeLastArea() {
  document.points.pop();
  resetAdvancedPermalink();
  document.permalink.elevation = escape(eP(document.points));
  document.permalink.updated(); 
  updateArea();
}

function showElevation(x,y,z) {
   var t = $("#tool")[0].value;
   var m = $("#mul")[0].value;
   $("#infodiv").html('Elevation of the Clicked Point [ '+y+' , '+x+' ] is <span id="z'+z+'" class="iV">' + (Math.round(mul[t][m].m * z * 100)/100) + '</span> <span id="iS">' + mul[t][m].t + '</span>').highlightFade({start:'#0f0',end:'#cfc', speed:'slow'});;
}

function showDistance(d) {
   var t = $("#tool")[0].value;
   var m = $("#mul")[0].value;
   $("#infodiv").html('Track length: <span id="z'+d+'" class="iV">' + (Math.round(mul[t][m].m * d * 100)/100) + '</span> <span id="iS">' + mul[t][m].t + '</span>').highlightFade({start:'#0f0',end:'#cfc', speed:'slow'});;
} 

function showArea(a) {
   var t = $("#tool")[0].value;
   var m = $("#mul")[0].value;
   $("#infodiv").html('Polygon area: <span id="z'+a+'" class="iV">' + (Math.round(mul[t][m].m * a * 100)/100) + '</span> <span id="iS">' + mul[t][m].t + '</span>').highlightFade({start:'#0f0',end:'#cfc', speed:'slow'});;
} 

function PermalinkBuilder() {
   this.getParams = function(){
      var buffer = '?lat='+this.lat+'&lng='+this.lng;
          buffer += (this.zoom)      ? '&z=' + this.zoom       :'';
          buffer += (this.type)      ? '&t=' + this.type       :'';
          
          buffer += (this.elevation) ? '&e=' + this.elevation  :'';
          buffer += (this.distance)  ? '&d=' + this.distance   :'';
          buffer += (this.area)      ? '&a=' + this.area       :'';
          buffer += (this.cadastral) ? '&c=' + this.cadastral  :'';
          buffer += (this.q)         ? '&q=' + this.q          :'';
          
          buffer += (this.addStreet) ? '&as=' + this.addStreet  :'';
          buffer += (this.addTown)   ? '&at=' + this.addTown    :'';
          buffer += (this.addProv)   ? '&ap=' + this.addProv    :'';
          
          buffer += (this.goLat)     ? '&gt=' + this.goLat      :'';
          buffer += (this.goLng)     ? '&gl=' + this.goLng      :'';
          
          buffer += (this.ref)       ? '&r=' + this.ref        :'';
          
          buffer += (this.ppPro)     ? '&pr=' + this.ppPro      :'';
          buffer += (this.ppMun)     ? '&pm=' + this.ppMun      :'';
          buffer += (this.ppPo)      ? '&po=' + this.ppPo       :'';
          buffer += (this.ppPa)      ? '&pa=' + this.ppPa       :'';            
   return buffer;      
   }
}

function resetAdvancedPermalink() {
    delete document.permalink.elevation;
    delete document.permalink.distance;
    delete document.permalink.area;
    delete document.permalink.cadastral;
    delete document.permalink.q;
    delete document.permalink.addStreet;
    delete document.permalink.addTown;
    delete document.permalink.addProv;
    delete document.permalink.goLat;
    delete document.permalink.goLng;
    delete document.permalink.ref;
    delete document.permalink.ppPro;
    delete document.permalink.ppMun;
    delete document.permalink.ppPo;
    delete document.permalink.ppPa;    
}

$(function() {
  $("#tool").bind('change', function() {
  if(this.value > 0) {
    $(".M").hide().jqmHide();
    if(mul[this.value]) {
	  $("#mul").html(TrimPath.processDOMTemplate("jst_option", {ops:mul[this.value]})).find('option')[0].selected = true;
	  $("#mul").show();	 
    } else {
      $("#mul").hide();
    } 
  } else {
    document.map.clearOverlays();
    GEvent.clearListeners(document.map, 'click');
	$("#mul").hide();
  }
  initfunc[this.value]();
  $("#mul").bind('change', function() {
    var t = $("#tool")[0].value;
    var m = $("#mul")[0].value;
    var z = parseFloat($("#infodiv span.iV")[0].id.substr(1));
    $("#infodiv span.iV").html(Math.round(mul[t][m].m * z * 100)/100);
    $("#iS").html(mul[t][m].t);
  });
 });
 initfunc[0]();
});