//-- input

var areaPoints=[];
var areaColor='';
var areaOpacity='';
var areaName='';
var areaPointsComplete=false;

function StartAreaPoints() {
  areaPointsComplete=false;
  areaPoints=[];
  // show message asking to start clicking on the first point of the area  
  ShowArea();
};

function AddAreaPoints() {
  if (!areaPointsComplete) {
    alert('Area has not been ended');
    return;
  };
  var points=[];
  for (var i=0;i<areaPoints.length-1;i++) {
    points[i]=areaPoints[i];
  };
  areaPoints=points;
  areaPointsComplete=false;
  //areaPoints=[];
  // show message asking to start clicking on the first point of the area  
  ShowArea();
};

function ReverseAreaPoints() {
  if (areaPoints.length<2) {
    alert('Not enough points to Reverse');
    return;
  };
  areaPoints.reverse();
  map.closeInfoWindow();
  ShowArea();
  AreaZoom();
  // show message stating area selection is complete  
};

function InsertAreaPointNext(ix) {
  InsertAreaPoint(areaPoints[ix],ix);
  ChangeAreaPointNext(ix);
};


function EndAreaPoints() {
  if (areaPoints.length<3) {
    alert('Not enough points to define an area');
    return;
  };
  areaPoints[areaPoints.length]=areaPoints[0];
  areaPointsComplete=true;
  ShowArea();
  // show message stating area selection is complete  
};

function InsertAreaPoint(pointIn,indexIn) {
  if (areaPointsComplete) {
    alert('Area has already been completed');
    return areaPoints;
  };
  var lon=0,lat=0, point;
  // get lon lat  
  //point=[lon,lat];
  point=pointIn;
  index=indexIn;
  if (index==null) index=areaPoints.length;
  if (index<areaPoints.length) {
    // Insert a point in the middle of the array
    var pointsTmp=[];
    for (var i=0;i<areaPoints.length;i++) {
      if (i==index) {
        pointsTmp[pointsTmp.length]=null;
      };
      pointsTmp[pointsTmp.length]=areaPoints[i];
    };
    areaPoints=pointsTmp;
  };
  areaPoints[index]=point;
  ShowArea();
  return areaPoints;
};

function RemoveAreaPoint(indexIn) {
  var index=indexIn;
  if (index!=null && index<areaPoints.length) {
    // Insert a point in the middle of the array
    var pointsTmp=[];
    for (var i=0;i<areaPoints.length;i++) {
      if (i==index) continue;
      pointsTmp[pointsTmp.length]=areaPoints[i];
    };
    areaPoints=pointsTmp;
  };
  map.closeInfoWindow();
  ShowArea();
  return areaPoints;
};

function RemoveAreaPointLink(indexIn) {
  //map.closeInfoWindow();
  RemoveAreaPoint(indexIn-1);
};

function ChangeAreaPointNextLink(indexIn) {
  map.closeInfoWindow();
  ChangeAreaPointNext(indexIn-1);
};


function SwapAreaPoint(from,to) {
  var apTmp=areaPoints[to];
  areaPoints[to]=areaPoints[from];
  areaPoints[from]=apTmp;
};

function MoveUpAreaPoint(ix) {
  SwapAreaPoint(ix,ix-1);
  ShowArea();
};
function MoveDownAreaPoint(ix) {
  SwapAreaPoint(ix,ix+1);
  ShowArea();
};

var ChangingAreaPoint=null;
function ChangeAreaPointNext(ix) {
  ChangingAreaPoint=ix;
  //alert('Not yet implemented');
};
function ChangeAreaPoint(ix,point) {
  areaPoints[ix]=point;
  ShowArea();
};

function GetAreaData () {
  var ix=IX;
  var name=document.getElementById('Name').value;
  var color=document.getElementById('Color').value;
  if (color=='') {
    color=RandomColor();
    document.getElementById('Color').value=color;
  };
  var opacity=document.getElementById('Opacity').value;
  if (opacity=='') {
    opacity=AreasDefaultOpacity;
    document.getElementById('Opacity').value=opacity;
  };
  GetTextPoints();
  var points=document.getElementById('TextPointsInput').value;
  areaName=name;
  areaColor=color;
  areaOpacity=opacity;
  var colorShowDiv=document.getElementById('AreaColorDisplay');
  if (colorShowDiv!=null)
    colorShowDiv.innerHTML='<span style="background-color: '+areaColor+' ; text-decoration:none"><font color="'+areaColor+'">[~]</font></span>'+' ';
  var noSave=!areaPointsComplete;
  document.getElementById('SaveButton').disabled=noSave;
};

function ShowArea() {
   GetAreaData();
//alert('ShowArea');
  DisplayMarkers();
  if (areaPointsComplete) { 
    DisplayAreaPolygon();
    AreaZoom();
   } else {
    //DisplayAreaPolygon();
    DisplayAreaPoints();
  };
  ShowPointsList();
};

function ShowPointsList() {
  // get HTML for points list
  var html=AreaPointsListHTML();
//alert(html);
  // show html
//alert(html);
  SetElementHTML('LocationsList',html);
  ShowJStext();
};
function ShowJStext () {
  var jsText='';
  if (areaPointsComplete) jsText=AreaPointsListJS();
  SetElementHTML('TripDescription',jsText);
  //document.getElementById('TextPointsInput').value=jsText;
};


function AreaPointsListHTML() {
  var html='';
  //html=html+'';
  html=html+'Area Points'+'<br/>'+'\n';
  html=html+'<input type="button" value="Re-Zoom" onClick="AreaZoom()" />'+'\n';
  html=html+'<input type="button" value="Clear" onClick="StartAreaPoints()" />'+'\n';
  html=html+'<input type="button" value="Reverse" onClick="ReverseAreaPoints()" />'+'\n';
  if (areaPointsComplete)
    html=html+'<input type="button" value="Add" onClick="AddAreaPoints()" />'+'\n'
   else
    html=html+'<input type="button" value="End" onClick="EndAreaPoints()" />'+'\n';
  html=html+'<br/>'+'\n';
  if (areaPoints.length<1) {
    html=html+'Click on the map to start entering the area borders'+'\n';
  };
  html=html+'<ol>'+'\n';
  var lon,lat,point;
  for(var i=0;i<areaPoints.length;i++) {
    point=areaPoints[i];
    lon=point.x;
    lat=point.y;
    html=html+'<li>'+'\n';


    //html=html+'<input type="button" value="-" onClick="RemoveAreaPoint('+i+')">'+'\n';

    //html=html+'<input type="button" value="þ" value0="û" onClick="ChangeAreaPoint('+i+')" style="{font-family: webdings}" />';
    //html=html+'<input type="button" value="q" onClick="ChangeAreaPoint('+i+')" style="{font-family: webdings}" />';
    html=html+'<input type="button" value="4" onClick="InsertAreaPointNext('+i+')" style="{font-family: webdings}" />';
    html=html+'<input type="button" value="q" onClick="ChangeAreaPointNext('+i+')" style="{font-family: webdings}" />';
    html=html+'<input type="button" value="5" onClick="MoveUpAreaPoint('+i+')" style="{font-family: webdings}" ';
    if (i==0) html=html+' disabled ';
    html=html+' />';
    html=html+'<input type="button" value="6" onClick="MoveDownAreaPoint('+i+')" style="{font-family: webdings}" ';
    if (i==areaPoints.length-1) html=html+' disabled ';
    html=html+' />';
    html=html+'<input type="button" value="r" onClick="RemoveAreaPoint('+i+')" style="{font-family: webdings}" />';

    html=html+'<a href="javascript:areaPointsMarkers['+i+'].openInfoWindowHtml(areaPointsMarkers['+i+'].html)">'+'\n';
    html=html+point+'\n';
    html=html+'</a>'+'\n';
    html=html+'</li>'+'\n';
  };
  html=html+'</ol>'+'\n';
  return html;
};


function AreaPointsListJS (aP) {
  var points=aP;
  if (points==null) points=areaPoints;
  if (points==null) points=[];
  var html='';
  //html=html+'';
  //html=html+'['+'\n';
  html=html+'['+' ';
  var lon,lat,point;
  for(var i=0;i<points.length;i++) {
    point=points[i];
    lon=point.x;
    lat=point.y;
    if (i>0) html=html+', '; 
    html=html+'[';
    html=html+lat;
    html=html+', ';
    html=html+lon;
    //html=html+'] '+'\n';
    html=html+'] '+' ';
    //html=html+point+'\n';
  };
  //html=html+']'+'\n';
  html=html+']'+' ';
  return html;
};

function NumericPointsArray2JS(points) {
  // points=numberArray [[lat,lon], [lat,lon], ...]
  var js='';
  js+='[';
  var p;
  for (var i=0;i<points.length;i++) {
    p=points[i];
    if (p==null || p.length<2) continue;
    if (i>0) js+=', ';
    js+='['+p[0]+', '+p[1]+']';
  };
  js+=']';
  return js;
};

function AreaPointsArray2Points(pointsArray) {
  //var pArray=[];
  var pArray=null;
  if (pointsArray==null || pointsArray=='') return pArray;
  pArray=[];
  var lat,lon, point;
  for (var i=0;i<pointsArray.length;i++) {
    lat=pointsArray[i][0];
    lon=pointsArray[i][1];
    point=new GLatLng(lat,lon);
    pArray[pArray.length]=point;
  };
  return pArray;
};



function ShowPoints() {
};


var areaPointsOverlay=null;
var areaPointsMarkers=[];
function DisplayAreaPoints(colorIn) {
  // convert points to pline
  //var line=new GPolyline(areaPoints);
  var color=colorIn;
  if (color==null) color=areaColor;
  if (color==null || color=='') color=RandomColor();
  var line=new GPolyline(areaPoints,color);
  // display Pline
  // display polygon
  if (areaPointsOverlay!=null)  map.removeOverlay(areaPointsOverlay);
  areaPointsOverlay=line;
  map.addOverlay(areaPointsOverlay);
};
function DisplayAreaPolygon(colorIn,opacityIn) {
  // convert points to polygon
  //var c='#00FFFF';
  //var p=new GPolygon(areaPoints,c,3, 0.7 ,c, 0.4);

  //var p=new GPolygon(areaPoints,c,3, 0.7 ,c, 0.4);
  //var polygon=new GPolygon(border,color,3, AreasDefaultBorderOpacity ,color, opacity);
  var color=colorIn;
  if (color==null) color=areaColor;
  if (color==null || color=='') color=RandomColor();
  var opacity=opacityIn;
  if (opacity==null) opacity=areaOpacity;
  if (opacity==null || opacity=='') opacity=AreasDefaultOpacity;

  var p=new GPolygon(areaPoints,color,3, AreasDefaultBorderOpacity ,color, opacity);

  // display polygon
  if (areaPointsOverlay!=null)  map.removeOverlay(areaPointsOverlay);
  areaPointsOverlay=p;
  map.addOverlay(areaPointsOverlay);
};
var PushpinAreaImageLast='transparent.png';
function DisplayMarkers() {
  for (var i=0;i<areaPointsMarkers.length;i++) {
    map.removeOverlay(areaPointsMarkers[i]);
  };
  areaPointsMarkers=[];
  var icon, text;
  for (var i=0;i<areaPoints.length;i++) {   
    //areaPointsMarkers[i]=new GMarker(areaPoints[i]);
    //map.addOverlay(areaPointsMarkers[i]);
    //GEvent.addListener(areaPointsMarkers[i], "click", function() {    areaPointsMarkers[i].openInfoWindowHtml("Marker #<b>" + i + "</b>");} );
    text=null;
    icon=null
    if (i==0) { 
      icon=PushpinAreaImageDefault;
      text='area marker';
      text+='<br/>';
      text+='<span style="background-color: '+areaColor+' ; text-decoration:none"><font color="'+areaColor+'">[~]</font></span>';
      text+=' '+areaName;
    };
    if (areaPointsComplete && i==areaPoints.length-1) {
      //icon=PushpinAreaImageDefault;
      //icon=PushpinAreaImageLast;
      icon='';
    };
    areaPointsMarkers[i]=createMarkerIx(areaPoints[i],i+1, icon, text);
    map.addOverlay(areaPointsMarkers[i]);
  };
  return areaPointsMarkers;  
};


        function createMarkerIx(point, number, iconName, extraText) {
          var icon=null;
          if (iconName!=null) {
            var thisIcon=new GIcon(G_DEFAULT_ICON);
            thisIcon.image=iconName;
            icon=thisIcon;
          };
          if (iconName=='') {
            var thisIcon=new GIcon(G_DEFAULT_ICON);
            thisIcon.image='transparent.png';
            thisIcon.iconSize = new GSize(1, 1);
            icon=thisIcon;
          };
          var marker = new GMarker(point,icon);
          var html='';
          //htm=html+"Marker #<b>" + number + "</b>"+'<br/><a href="javascript:RemoveAreaPointLink('+number+')">remove</a><br>';
          html=html+"Marker # <b>" + number + "</b>";
          if (extraText) html=html+' '+extraText;
          html=html+'<br/>';
          html=html+'<a href="javascript:RemoveAreaPointLink('+number+')">remove</a>';
          html=html+'<br/>';
          html=html+'<a href="javascript:ChangeAreaPointNextLink('+number+')">change</a>';
//alert(html);
          //htm=html+'<br/>';
          marker.html=html;
          GEvent.addListener(marker, "click", function() {
            //marker.openInfoWindowHtml("Marker #<b>" + number + "</b>");
            //marker.openInfoWindowHtml("Marker #<b>" + number + "</b>"+'<br/><a href="javascript:RemoveAreaPoint('+(number-1)+');undefined">remove</a>');
            //marker.openInfoWindowHtml("Marker #<b>" + number + "</b>"+'<br/><a href="javascript:RemoveAreaPointLink('+number+')">remove</a>');
            //marker.openInfoWindowHtml(html);
            marker.openInfoWindowHtml(marker.html);
          });
          return marker;
        }





function AreaZoom() {
  var bounds = new GLatLngBounds();
  for (var i=0;i<areaPoints.length;i++) {
    bounds.extend(areaPoints[i]); 
  };
  map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds)); 
};



/* map to get point clicked
        GEvent.addListener(map, "click", function(overlay, point) {
          if (overlay) {
            map.removeOverlay(overlay);
          } else {
            map.addOverlay(new GMarker(point));
          }
        });
*/

var areaPointOverlays=[];
function PointFromMap(overlay,point) {
  if (overlay) return;  
  /*
  if (overlay) {
    map.removeOverlay(overlay);
  } else {
    map.addOverlay(new GMarker(point));
  };
  */
//alert(point);
  //InsertAreaPoint(point);
  ProcessInputPoint(point);
  ShowArea();
};

function ProcessInputPoint(point) {
  if (ChangingAreaPoint!=null && ChangingAreaPoint>=0) {  
    ChangeAreaPoint(ChangingAreaPoint,point); 
    ChangingAreaPoint=null;
   } else {
    InsertAreaPoint(point);
  };
};



function ShowMainAddress(address) {
  if (address==null) { 
    address=document.getElementById("MainAddress").value;
   } else {
    document.getElementById("MainAddress").value=address;
  };
  SetCentre(address);
};

function AddMainAddress(address) {
  if (address==null) { 
    address=document.getElementById("MainAddress").value;
   } else {
    document.getElementById("MainAddress").value=address;
  };
  SetCentre(address,true);
};



function SetCentre(address,add) {
  //alert(address);
  var lat=null,lon=null, pCentre=null;
  geocoder.getLatLng(
    address,
    function(point) {
      var where=point;
      //LocationsUseLatLon[ix]=true;
      if (!point) {
        //LocationsUseLatLon[ix]=false;
 	if (lon==null || lat==null) {
	  lat=0;
	  lon=0;
  	  pCentre='NOPOINT';
	  window.status='Zone Main Address: '+'NO MAP: '+address;
  	  //ShowLocationsPath(Locations.length);
  	  //-SetZoneCenter(zoneIx,pointsCount);
          alert('Cannot locate:\n'+address);
           return;
         } else {
	};
	where=new GLatLng(lat,lon);
       } else { 
        //LocationsUseLatLon[ix]=true;
	lon=where.x;
    	lat=where.y;
      };

	//pCentre=where;
        //alert('Zones Main address'+' '+' : '+where.x+' , '+where.y+' : '+address);
        window.status='address'+' '+' : '+where.x+' , '+where.y+' : '+address;
        map.setCenter(where);
  
        if (add!=null) PointFromMap(null,where);
  
    }
  );
}




//-- /input
