/*
File : polyzone.js 
18/01/09

geolinko project
copyright : lpCom
*/


var polyZoneIntervention = null;
var polyZoneInterventionVisibility = 0;
var latlngAnnounce = null;

var locked = false;

function drawKmCircle_A(opt_options){
  var pnts = [];
  var opts = opt_options||{};
  var radius = 1*opts.radius||1;
  var step = parseInt(360/opts.nodes)||30;
  var latConv = latlngAnnounce.distanceFrom(new GLatLng(latlngAnnounce.lat()+0.1, latlngAnnounce.lng()))/100;
  var lngConv = latlngAnnounce.distanceFrom(new GLatLng(latlngAnnounce.lat(), latlngAnnounce.lng()+0.1))/100;
  for(var i=0; i<=360; i+=step)
    { 
    var pint = new GLatLng(latlngAnnounce.lat() + (radius/latConv * Math.cos(i * Math.PI/180)), 
      latlngAnnounce.lng() + (radius/lngConv * Math.sin(i * Math.PI/180)));
    pnts.push(pint);
  }
  if(opts.polygon){
    var poly = new GPolygon(pnts,
							OPT_POLY['normal']['color_line'],
							OPT_POLY['normal']['width_line'],
							OPT_POLY['normal']['opacity_line'],
							OPT_POLY['normal']['color_zone'],
							OPT_POLY['normal']['opacity_zone'],
							{clickable:false});
  }else{
    var poly = new GPolyline(pnts,
							OPT_POLY['normal']['color_line'],
							OPT_POLY['normal']['color_line'],
							OPT_POLY['normal']['opacity_line'],
							{clickable:false});
  }
  return poly;
}

/*
GLatLng.prototype.drawKmCircle =function (opt_options){//fonction abandonnée. Prob suite à intégration google API pour IP geolocalisation
  var pnts = [];
  var opts = opt_options||{};
  var radius = 1*opts.radius||1;
  var step = parseInt(360/opts.nodes)||30;
  var latConv = this.distanceFrom(new GLatLng(this.lat()+0.1, this.lng()))/100;
  var lngConv = this.distanceFrom(new GLatLng(this.lat(), this.lng()+0.1))/100;
  for(var i=0; i<=360; i+=step)
    { 
    var pint = new GLatLng(this.lat() + (radius/latConv * Math.cos(i * Math.PI/180)), 
      this.lng() + (radius/lngConv * Math.sin(i * Math.PI/180)));
    pnts.push(pint);
  }
  if(opts.polygon){
    var poly = new GPolygon(pnts,
							OPT_POLY['normal']['color_line'],
							OPT_POLY['normal']['width_line'],
							OPT_POLY['normal']['opacity_line'],
							OPT_POLY['normal']['color_zone'],
							OPT_POLY['normal']['opacity_zone'],
							{clickable:false});
  }else{
    var poly = new GPolyline(pnts,
							OPT_POLY['normal']['color_line'],
							OPT_POLY['normal']['color_line'],
							OPT_POLY['normal']['opacity_line'],
							{clickable:false});
  }
  return poly;
}
*/
function copyPolyzone(p) {
var pnts = [];
if (p) {
	for (var i=0; i<p.getVertexCount() ; i++) {
		var point = new GLatLng(p.getVertex(i).lat(), p.getVertex(i).lng());
		pnts.push(point);
		}
	return	new GPolygon(pnts,
						OPT_POLY['normal']['color_line'],
						OPT_POLY['normal']['width_line'],
						OPT_POLY['normal']['opacity_line'],
						OPT_POLY['normal']['color_zone'],
						OPT_POLY['normal']['opacity_zone'],
						{clickable:false});
	}
}

	
function getZoneBounds(p) {
var latMin=+90;
var latMax=-90;
var lngMin=+180;
var lngMax=-180;
if (p) {
	for (var i=0; i < p.getVertexCount(); i++) {
		if (p.getVertex(i).lat() <latMin) latMin=p.getVertex(i).lat();
		if (p.getVertex(i).lat() >latMax) latMax=p.getVertex(i).lat();
		if (p.getVertex(i).lng() <lngMin) lngMin=p.getVertex(i).lng();
		if (p.getVertex(i).lng() >lngMax) lngMax=p.getVertex(i).lng();
		}
	var z1 = getZoneId(latMax,lngMin);
	var z4 = getZoneId(latMin,lngMax);	
	return new Array(getZoneRow(z1),getZoneCol(z1),getZoneRow(z4),getZoneCol(z4));
	} else return null;
}


function inBounds(cB, nB) {
if (nB[0]>=cB[0] && nB[1]>=cB[1] && nB[2]<=cB[2] && nB[3]<=cB[3])
	return true;
	else return false;
}

function max(x,y) {if (x>y) return x; else return y;}
function min(x,y) {if (x<y) return x; else return y;}
function extendBounds(cB, nB) {
	return new Array(min(nB[0],cB[0]), min(nB[1],cB[1]), max(nB[2],cB[2]), max(nB[3],cB[3]));
}

function getDeltaBounds() {
var newBounds = getZoneBounds(polyZoneIntervention);
var dataBounds = '';
var extBounds;
//if (currentBounds && newBounds[0]==currentBounds[0] && newBounds[1]==currentBounds[1] && newBounds[2]==currentBounds[2] && newBounds[3]==currentBounds[3]) return null; /* no change*/
if (currentBounds && inBounds(currentBounds, newBounds)) return null;/* no change*/
if (currentBounds && !inBounds(currentBounds, newBounds)) {
	extBounds = extendBounds(currentBounds, newBounds);
	dataBounds = '&minusnrow='+currentBounds[0]+'&minusncol='+currentBounds[1]+'&minussrow='+currentBounds[2]+'&minusscol='+currentBounds[3];
	}
	else extBounds = newBounds;
dataBounds += '&nrow='+extBounds[0]+'&ncol='+extBounds[1]+'&srow='+extBounds[2]+'&scol='+extBounds[3];
currentBounds=extBounds;
return dataBounds;	
}

function listenerPolyzone() {
	var b_new = getZoneBounds(polyZoneIntervention);
	var b_prev = getZoneBounds(savePoly);	
	if (!inBounds(b_new, b_prev)) {
		if (mode==1) display_tabMHO(latlngAnnounce, polyZoneIntervention);
		savePoly = copyPolyzone(polyZoneIntervention);
		}
		else {
			if (polyZoneIntervention.getArea() > MAX_SEARCH_AREA) {
				jAlertWarning(ALERT_FORM_MESS9, '');
				deletePolyzone(polyZoneIntervention);				
				setPreviousPolyzone();
				}
				else {
					savePoly = copyPolyzone(polyZoneIntervention);
					if (mode==1) showServices();
					}
			}
}

function movePolyzone(p, from, to) {
var pnts = [];
var deltaLat = to.lat() - from.lat();
var deltaLng = to.lng() - from.lng();
if (p) {
	for (var i=0; i<p.getVertexCount() ; i++) {
		var point = new GLatLng(p.getVertex(i).lat()+deltaLat, p.getVertex(i).lng()+deltaLng);
		pnts.push(point);
		}
	var newp = 	new GPolygon(pnts,
						OPT_POLY['normal']['color_line'],
						OPT_POLY['normal']['width_line'],
						OPT_POLY['normal']['opacity_line'],
						OPT_POLY['normal']['color_zone'],
						OPT_POLY['normal']['opacity_zone'],
						{clickable:false});
	map.addOverlay(newp);							
	if (polyZoneIntervention.isHidden()) hidePolyzone(newp); else enablePolyzone(newp);
	deletePolyzone(polyZoneIntervention);
	polyZoneIntervention = newp;
	GEvent.addListener(newp, "lineupdated", function(){listenerPolyzone();});						
	}
}

function setPreviousPolyzone() {
  polyZoneIntervention = savePoly;
  map.addOverlay(polyZoneIntervention);
  polyZoneIntervention.enableEditing();
  GEvent.addListener(polyZoneIntervention, "lineupdated", function(){listenerPolyzone();}); 
  savePoly = copyPolyzone(polyZoneIntervention);
}


/***********************************************************************************************************/
function poly_contains(poly, point) {
        var j=0;
        var oddNodes = false;
        var x = point.lng();
        var y = point.lat();
		
		var count=poly.getVertexCount();
        for (var i=0; i < poly.getVertexCount(); i++) {
          j++;
	  
          if (j == poly.getVertexCount()) {j = 0;}
		  var iLat = poly.getVertex(i).lat();
		  var jLat = poly.getVertex(j).lat();
		  var iLng = poly.getVertex(i).lng();
		  var jLng = poly.getVertex(j).lng();

          if ((( iLat < y) && (jLat >= y))
          || ((jLat < y) && (iLat >= y))) {
			var calcul = iLng + (y - iLat) / (jLat-iLat) *  (jLng - iLng);
            if ( calcul <x ) {
              oddNodes = !oddNodes
            }
          }
        }
        return oddNodes;
}
/*
GPolygon.prototype.Contains = function(point) {//fonction abandonnée. Prob suite à intégration google API pour IP geolocalisation
        var j=0;
        var oddNodes = false;
        var x = point.lng();
        var y = point.lat();
		
		var count=this.getVertexCount();
        for (var i=0; i < this.getVertexCount(); i++) {
          j++;
	  
          if (j == this.getVertexCount()) {j = 0;}
		  var iLat = this.getVertex(i).lat();
		  var jLat = this.getVertex(j).lat();
		  var iLng = this.getVertex(i).lng();
		  var jLng = this.getVertex(j).lng();

          if ((( iLat < y) && (jLat >= y))
          || ((jLat < y) && (iLat >= y))) {
			var calcul = iLng + (y - iLat) / (jLat-iLat) *  (jLng - iLng);
            if ( calcul <x ) {
              oddNodes = !oddNodes
            }
          }
        }
        return oddNodes;
}
*/

function inZone(latlng, polygone) {
	if (polygone && latlng) return poly_contains(polygone, latlng);
	else return false;
}

function hidePolyzone(p) {
	if (p) {
		p.hide();
		p.disableEditing();
	}
}

function enablePolyzone(p) {
	if (p) {
		p.show();
		p.enableEditing();
	}	
}

function deletePolyzone(p) {
if (p) {
	p.hide();
	p.disableEditing();	
	p = null; /* suffisant ? */
	}
}

function createPolyzone(xml) {
	if (xml) {
		polyZoneIntervention = xmlToPolyzone(xml, 'normal');
		}
		else {
			polyZoneIntervention = drawKmCircle_A({radius:document.getElementById('searchBeam').value, polygon: true});		
			}		
	savePoly = copyPolyzone(polyZoneIntervention);
	map.addOverlay(polyZoneIntervention);
	polyZoneIntervention.enableEditing();
	GEvent.addListener(polyZoneIntervention, "lineupdated", function(){listenerPolyzone();});	
}

function polyzoneToXml() {
var xml='';
if(polyZoneIntervention){	
	xml ='<polyzone>';
    var len = polyZoneIntervention.getVertexCount()||0;
    for(var i=0; i<len; i++){
		xml+='<point>';
		var point = polyZoneIntervention.getVertex(i);
		xml+='<lat>'+point.lat()+'</lat>';
		xml+='<lng>'+point.lng()+'</lng>';
		xml+='</point>';
		}	
	xml+='</polyzone>';
	}
return xml
}

function xmlToPolyzone(xml, color_mode) {
var latlng = [];
	if (!xml) return null;
	for (var i=0 ; i<xml.getElementsByTagName('point').length ; i++) {
		var point = xml.getElementsByTagName('point')[i];
		var lat = point.getElementsByTagName('lat')[0].firstChild.nodeValue*1;
		var lng = point.getElementsByTagName('lng')[0].firstChild.nodeValue*1;
		latlng.push(new GLatLng(lat, lng));
		}
	return	new GPolygon(latlng,
						OPT_POLY[color_mode]['color_line'],
						OPT_POLY[color_mode]['width_line'],
						OPT_POLY[color_mode]['opacity_line'],
						OPT_POLY[color_mode]['color_zone'],
						OPT_POLY[color_mode]['opacity_zone']);
}


function lockSearchZone() {
locked=true;
document.getElementById('minusBeamId').disabled = true;
document.getElementById('plusBeamId').disabled = true;
document.getElementById('setBeamId').disabled = true;
}

function unlockSearchZone() {
document.getElementById('minusBeamId').disabled = false;
document.getElementById('plusBeamId').disabled = false;
document.getElementById('setBeamId').disabled = false;
locked=false;
}

function setBeamSearchArea() {
if (locked) return false; else lockSearchZone();
if (drawKmCircle_A({radius:document.getElementById('searchBeam').value, polygon: true}).getArea() > MAX_SEARCH_AREA) {
	jAlertWarning(ALERT_FORM_MESS9, '');
	unlockSearchZone();
	}
	else {
		deletePolyzone(polyZoneIntervention);
		createPolyzone();
		if (mode==1) showServices(); else unlockSearchZone();
		}
if (mode!=2) setMode(1);		
}

function plusBeamSearchArea() {
if (locked) return false; else lockSearchZone();
var r=document.getElementById('searchBeam').value*1 + INC_BEAM;
if (drawKmCircle_A({radius:r, polygon: true}).getArea() > MAX_SEARCH_AREA) {
	jAlertWarning(ALERT_FORM_MESS9, '');
	unlockSearchZone();
	}
	else {
		document.getElementById('searchBeam').value = r;
		deletePolyzone(polyZoneIntervention);
		createPolyzone();
		if (mode==1) showServices(); else unlockSearchZone();
		}
if (mode!=2) setMode(1);
}

function minusBeamSearchArea() {
if (locked) return false; else lockSearchZone();
var r=document.getElementById('searchBeam').value*1 - INC_BEAM;
if (r>0) {
	document.getElementById('searchBeam').value = r;
	deletePolyzone(polyZoneIntervention);
	createPolyzone();
	if (mode==1) display_tabMHO(latlngAnnounce, polyZoneIntervention);
	}
unlockSearchZone();
if (mode!=2) setMode(1);
}

