﻿
var myGeomType = null; //MOVE TO DRAWING
var myCurrentShape = null; // MOVE TO DRAWING
var myPoints = new Array(); // MOVE TO DRAWING
var myDistance = 0; // UNNEEDED
var tempShape = null; //UNKNOWN
var tempPoints = null; // UNKNOWN
var tempDistance = 0; //UNKNOWN
var myCirclePoints = null; //MOVE TO DRAWING
var myBoxPoints = null; //MOVE TO DRAWING
var tempCircle = null; //MOVE TO DRAWING
var tempBox = null; //MOVE TO DRAWING
var tempLine = null;
var shapecount = 0;
var pointcount = 0;
var DrawingList;
var slLines = null //Temporary layer for adding multiple lines of polygon borders (erased when polygon is finalized
var prevPoint = null;
var currPoint = null;
var IsFor3d = false;
var CallingPage = 'DIGITAL';
var box_depressed = false;
var poly_depressed = false;
function Draw(geomType, is3d, caller){

    if (is3d) IsFor3d = true;
    if (caller != null) CallingPage = caller;

    if (geomType == 'box' && CallingPage == 'DIGITAL') {
        var HelpTitle = "Exposure Selection</br>";
        var HelpSummary = "The exposure drawing tool allows your to select exposures based on a bounding box</br>";
        var HelpText = "<b>Step 1:</b> First, left click and release a starting corner to identify a starting point. (Marked by a change to a crosshair)<br/><br/><b>Step 2:</b> Next drag an area over exposures, and complete the box with a right click on the desired ending location<br/>";
        var box_depressed = true;
    }
    else if (geomType == 'polygon') { poly_depressed = true; }
    
    myGeomType = geomType;


    DrawEventHandler(true);
    
    document.getElementById("divMap").style.cursor='crosshair';
}



function ClearDrawings(){
    drawLayer.DeleteAllShapes();
    if (CallingPage == 'DIGITAL') {
        DrawingList = document.getElementById('ctl00_Main_hdnDrawingList');
        DrawingList.value = "";
    }
    if (CallingPage == "FILM") { pushLayer.DeleteAllShapes(); } 
}

//Event for Draw, registers location on mouse move
function MouseMove(e) {

    var x = e.mapX;
    var y = e.mapY;
    pixel = new VEPixel(e.mapX, e.mapY);
    var LL = map.PixelToLatLong(pixel);
    spnCurrLat.innerText = LL.Latitude.toFixed(7);
    spnCurrLong.innerText = LL.Longitude.toFixed(7);
}

function MouseMoveDraw(e){
    var x = e.mapX;
    var y = e.mapY;
    pixel = new VEPixel(e.mapX, e.mapY);
    var LL = map.PixelToLatLong(pixel);
    spnCurrLat.innerText = LL.Latitude.toFixed(7);
    spnCurrLong.innerText = LL.Longitude.toFixed(7);
    document.getElementById("divMap").style.cursor='crosshair';
}
//Event for Draw, registers mouse click events while in Draw Mode
//Builds box if second point is finalized
function DrawPolyMouseClick(e){
    var x;
    var y;
    var LL;
    if (IsFor3d) {
        x = e.latLong.Longitude;
        y = e.latLong.Latitude;
        LL = new VELatLong(y, x);
    }
    else {
        x = e.mapX;
        y = e.mapY;
        pixel = new VEPixel(x, y);
        LL = map.PixelToLatLong(pixel);
    }
    

    if (myPoints.length == 0){
        map.DetachEvent("onmousemove", MouseMoveDraw);
        map.AttachEvent("onmousemove", DrawPolyMouseMove);
    }

    if (myGeomType == "box") { DrawBoxClick(x, y, LL); }
    else if (myGeomType == "polygon") { DrawPolyClick(x, y, LL, e.rightMouseButton); }

    document.getElementById("divMap").style.cursor = 'crosshair';
    return true;
   }
   
function DrawBoxClick(x, y, LL) {
    if (myPoints.length >= 1) 
    {
        myPoints[1] = LL;
    }
    else 
    {
        myPoints.push(LL);
        GetHelp('EXSEL2');
    }
    
    if (myPoints.length > 1){
        try{
            map.DetachEvent("onmousemove", DrawPolyMouseMove);
            map.DetachEvent("onclick", DrawPolyMouseClick);
            map.AttachEvent("onclick", CenterMapOnClick);
            
            if(tempBox != null) { drawLayer.DeleteShape(tempBox); }
        }
        catch (err){
            alert(err);
        }
        
        myCurrentShape = "shape" + shapecount;
      
        
        myCurrentShape = new VEShape(VEShapeType.Polygon, myBoxPoints);

        //Add points to expList
        DrawingList = document.getElementById('ctl00_Main_hdnDrawingList');
        if (DrawingList.value != "") { DrawingList.value = DrawingList.value + "&"; }
        for (i = 0; i < myBoxPoints.length; i++) {
            DrawingList.value = DrawingList.value + myBoxPoints[i].Latitude + "," + myBoxPoints[i].Longitude + ",";
        }
        DrawingList.value = DrawingList.value.slice(0, DrawingList.value.length - 1)
       
        var box = document.getElementById("imgBoxSelection");
        box.src = box.src.replace('clicked.png', '.png'); 
       
        //document.getElementById("txtShapeDetails").value = "Perimeter: " + myDistance + " km";
        //Call function to retrieve exposures in bound of drawn shape
       var strProjId = GetProjId();
       if(strProjId != ""){
             KeyView.ImageRetrievalService.GetExposuresInBox(myBoxPoints[0].Latitude, myBoxPoints[0].Longitude, myBoxPoints[2].Latitude, myBoxPoints[2].Longitude, strProjId, map.GetZoomLevel(),GetRadioValue('rdoSelection'), false, GetExposuresEval);
       } 
       
        else{
            alert("No Project is currently selected");
            myPoints = [];
            return false;
        }

        //Add finished box
        myCurrentShape.HideIcon();
        drawLayer.AddShape(myCurrentShape);
       
        shapecount = shapecount + 1;
       
        //reset myPoints
        myPoints.length = 0;
        myPoints = [];
        //Reset default mouse events
        map.DetachEvent("onclick", DrawPolyMouseClick);
        map.AttachEvent("onmousemove", MouseMove);
        
    }
    
}
   
   
   
   
   
   
   
   function DrawPolyClick(x, y, LL, RightClick) {
       myPoints.push(LL);
       currPoint = LL;
       var addLine;
       var NoPoints = false;

       if (RightClick) {
           if (myPoints.length > 2) {
               slLines.DeleteAllShapes();
               DrawEventHandler(false);
               map.DeleteShapeLayer(slLines);

               //Build final polygon
               myCurrentShape = new VEShape(VEShapeType.Polygon, myPoints);
               myCurrentShape.HideIcon();

               if (CallingPage == 'AIRMAG' || CallingPage == 'FILM') {
                   numDrawings.value = parseInt(numDrawings.value) + 1;
                   myCurrentShape.SetTitle(String(numDrawings.value));
               }

               drawLayer.AddShape(myCurrentShape);

               if (CallingPage == "DIGITAL") {
                   //Add points to expList
                   DrawingList = document.getElementById('ctl00_Main_hdnDrawingList');
                   if (DrawingList.value != "") { DrawingList.value = DrawingList.value + "&"; }
                   for (i = 0; i < myPoints.length; i++) {
                       DrawingList.value = DrawingList.value + myPoints[i].Latitude + "," + myPoints[i].Longitude + ",";
                   }
                   DrawingList.value = DrawingList.value.slice(0, DrawingList.value.length - 1)


                   var strProjId = GetProjId();
                   if (strProjId != "") {
                       KeyView.ImageRetrievalService.GetExposuresInPolygon(myCurrentShape.GetPoints(), strProjId, map.GetZoomLevel(), GetRadioValue('rdoSelection'), GetExposuresEval);
                   }

                   else {
                       alert("No Project is currently selected");
                       NoPoints = true;
                   }

                   myPoints.length = 0;
                   myPoints = [];
                   currPoint = null;
                   prevPoint = null;
                   
                   var poly = document.getElementById("imgPolySelection");
                   poly.src = poly.src.replace('clicked.png', '.png');
                   
                   poly_depressed = false;

                  
                   
               }
               else if (CallingPage == "AIRMAG") {
                   currShape_id = myCurrentShape.GetID();
                   var currId = 0;
                   if (currProjId.value != "") { currId = parseInt(currProjId.value); }

                   KeyView.AirMagAjax.GetAirMagProjFromSelection(myCurrentShape.GetPoints(), currId, ProjectSelectionCallBack);

                   myPoints.length = 0;
                   myPoints = [];
                   currPoint = null;
                   prevPoint = null;

                   var poly = document.getElementById("imgPolySelection");
                   poly.src = poly.src.replace('clicked.png', '.png');

                   if (NoPoints) { return false; }
               }
               else if (CallingPage == "FILM") {
                   currShape_id = myCurrentShape.GetID();
                   var currId = 0;
                   if (currProjId.value != "") { currId = parseInt(currProjId.value); }
                   KeyView.FilmAjax.GetFilmProjFromSelection(myCurrentShape.GetPoints(), currId, ProjectSelectionCallBack);

                   myPoints.length = 0;
                   myPoints = [];
                   currPoint = null;
                   prevPoint = null;

                   var poly = document.getElementById("imgPolySelection");
                   poly.src = poly.src.replace('clicked.png', '.png');

                   if (NoPoints) { return false; }

                   else { return false; }

               }
           }
       }
       else {


           if (CallingPage == 'DIGITAL') { GetHelp('CLOSEPOLY'); } 
           if (myPoints.length == 1) {
               prevPoint = LL;
               slLines = new VEShapeLayer();
               map.AddShapeLayer(slLines);
           }
           else {
               var pointList = new Array(prevPoint, currPoint);
               addLine = new VEShape(VEShapeType.Polyline, pointList);
               addLine.HideIcon();
               slLines.AddShape(addLine);

           }
           prevPoint = currPoint;
       }
           return false;
 
 
}   

//Event for draw, handles drawing/filling and saving pre-shapes while mouse is moving in draw mode (after first point)
function DrawPolyMouseMove(e){
    if(tempo == 0) { tempo = 1; return false; }
    else if(tempo == 1) { tempo = 2; return false; }
    
    tempo = 0;
    var LL = map.PixelToLatLong(new VEPixel(e.mapX, e.mapY));

    tempPoints = myPoints.slice(0, myPoints.length);

    if (myGeomType == 'box') {
        tempPoints[1] = LL;
    }
    else if (myGeomType == 'polygon') {
        tempPoints.push(LL);
    } 
    try{

        if (tempLine != null) { slLines.DeleteShape(tempLine); }
        //if (tempShape != null) { drawLayer.DeleteShape(tempShape); }
        if (tempBox != null) { drawLayer.DeleteShape(tempBox); }
    }
    catch (err){
    }

    
        if (tempPoints.length == 2 && (myGeomType == "box" || myGeomType == "square")) {
            GetBox(LL);
            tempBox = new VEShape(VEShapeType.Polygon, myBoxPoints);
            tempBox.HideIcon();
            drawLayer.AddShape(tempBox);
        }
        else if (myGeomType == "polygon") {
            var pointList = new Array(prevPoint, LL);
            tempLine = new VEShape(VEShapeType.Polyline, pointList);
            tempLine.HideIcon();
            slLines.AddShape(tempLine);
        }
   
    
}

//calculate distance
function getDistance(p1, p2) {
    p1Lat = latLonToRadians(p1.Latitude);
	p1Lon = latLonToRadians(p1.Longitude);
	
	p2Lat = latLonToRadians(p2.Latitude);
	p2Lon = latLonToRadians(p2.Longitude);	
	
	var R = 6371; // earth's mean radius in km
	var dLat  = p2Lat - p1Lat;
	var dLong = p2Lon - p1Lon;
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(p1Lat) * Math.cos(p2Lat) * Math.sin(dLong/2) * Math.sin(dLong/2);
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
	var disKm = R * c;
	var disMiles = disKm * 0.6214;	
	return (disMiles);
}

function UpdateDistance(X, Y, Distance) {
    var divDistance = document.getElementById("divDistance")
    divDistance.style.top = (Y - 10);
    divDistance.style.left = X;
    myDistance = Math.round(Distance * 1000) / 1000;

    divDistance.innerText = "Perimeter: " + Distance + "m";
    
}

//convert lat/long in degrees to radians
function latLonToRadians(point) {
	return point * Math.PI / 180;	
}

function GetBox(LL){
    var StartLat = (myPoints[0].Latitude);
    var StartLon = (myPoints[0].Longitude);
    var EndLat = LL.Latitude;
    var EndLon = LL.Longitude;
    //Dim new Squarepoints array
    myBoxPoints = new Array();
    
    //Calculate the other two corners for the square
        var p3 = new VELatLong(0,0);
        var p2 = new VELatLong(0,0);
        if(myGeomType == "box"){
            p2.Latitude = StartLat;
            p2.Longitude = EndLon;
            p3.Latitude = EndLat;
            p3.Longitude = StartLon;
            myBoxPoints.push(myPoints[0]);
            myBoxPoints.push(p3);
            myBoxPoints.push(LL);
            myBoxPoints.push(p2);
        }
        else if (myGeomType == "pixelsquare"){
        
        }
        else if (myGeomType == "latlonsquare"){ //square
            var p4 = new VELatLong(0,0)
            var LatDiff
            var LonDiff
            var Diff
            var blnUp = false;
            var blnLeft  = false;
            
            //Find Difference in Latitude & Longitude (checks for reverse box drawing)
            if(StartLat > EndLat) { 
                LatDiff = StartLat - EndLat;
                blnUp = false; 
            }
            else{ 
                LatDiff = EndLat - StartLat;
                blnUp = true;
            }
            
            if(StartLon > EndLon){ 
                LonDiff = StartLon - EndLon; 
                blnLeft = true;
                
            }
            else { 
                LonDiff = EndLon - StartLon; 
                blnLeft = false;
            }
             
            if(LatDiff > LonDiff){ //Latitude difference is greater, build square off latitude measurement
               if (blnLeft == true){ Diff = (Math.abs(LonDiff)) * -1; }
               else { Diff = Math.abs(LonDiff); }
              
               p3.Longitude = myPoints[0].Longitude;
               p2.Latitude = myPoints[0].Latitude;
               p3.Latitude = LL.Latitude;
               p4.Latitude = LL.Latitude;
               p2.Longitude =  myPoints[0].Longitude + Diff;
               p4.Longitude =  myPoints[0].Longitude + Diff;
            }
            else{
               if (blnUp == false) { Diff = (Math.abs(LonDiff)) * -1; }
               else { Diff = Math.abs(LonDiff); }
               p2.Latitude = myPoints[0].Latitude;
               p2.Longitude = LL.Longitude;
               p3.Longitude = myPoints[0].Longitude;
               p4.Longitude = LL.Longitude;
               p3.Latitude = myPoints[0].Latitude + Diff;
               p4.Latitude = myPoints[0].Latitude + Diff;      
            }
           
            
            
            myBoxPoints.push(myPoints[0]);
            myBoxPoints.push(p3);
            myBoxPoints.push(p4);
            myBoxPoints.push(p2);
        }
        box_depressed = false;
return myBoxPoints;
}
//Sets infobox,, disabled
function SetInfo(){
    myCurrentShape.SetTitle(document.getElementById("txtShapeTitle").value);
    myCurrentShape.SetDescription(document.getElementById("txtShapeDetails").value + "<br><a href='javascript:Delete(\"" + myCurrentShape.GetID() + "\")'>Delete</a>");

    myPoints = new Array();
    tempPoints = null;
    myDistance = 0;
    tempDistance = 0;
    
    var dummy = document.getElementById("divShapeInfo").style.visibility = "hidden";
    document.getElementById("txtShapeTitle").value = "";
    document.getElementById("txtShapeDetails").value = "";
}
//Delete specific shape
function Delete(shape){
    var delShape = drawLayer.GetShapeByID(shape);
    drawLayer.DeleteShape(delShape);
}

function AddDrawingsToVE()
{
    var SavedBox = null;
    var DrawingList = document.getElementById('ctl00_Main_hdnDrawingList').value;
    var aryDrawings = DrawingList.split('&');
    var aryPoints;
    var point;
    
    for (i=0;i<aryDrawings.length;i++)
    {
        aryPoints = aryDrawings[i].split(',');
        for (k=0;k<aryPoints.length;k= k+2)
        {
           point = new VELatLong(aryPoints[k], aryPoints[k + 1]);
           myPoints.push(point);
        }
        SavedBox = new VEShape(VEShapeType.Polygon, myPoints);
        SavedBox.HideIcon();
        drawLayer.AddShape(SavedBox);
        myPoints = [];
    }

}

function ScanForExpsInSavedDrawings()
{
    if(blnNeedScan == true){
        var shapecount = drawLayer.GetShapeCount();
        var pts;
        var strProjId = GetProjId();
        for (var i = 0; i < cofunt; i++)
            {
               shape = layer.GetShapeByIndex(i);
               pts = shape.GetPoints();
               KeyView.ImageRetrievalService.GetExposuresInBox(pts[0].Latitude, pts[0].Longitude, pts[2].Latitude, pts[2].Longitude, strProjId, map.GetZoomLevel(),GetRadioValue('rdoSelection'), true, GetExposuresEval);
            }
            blnNeedScan = false;
    }
}

function DrawEventHandler(EnterDraw) {
    if (CallingPage == "DIGITAL") {
        if (EnterDraw) {
            map.DetachEvent("onclick", CenterMapOnClick);
            map.AttachEvent("onclick", DrawPolyMouseClick);
            map.DetachEvent("onmousemove", MouseMove);
            map.AttachEvent("onmousemove", MouseMoveDraw);
        }
        else {
            map.DetachEvent("onmousemove", DrawPolyMouseMove);
            map.AttachEvent("onmousemove", MouseMove);
            map.DetachEvent("onclick", DrawPolyMouseClick);
            map.AttachEvent("onclick", CenterMapOnClick);
        }
    }
    else if (CallingPage == "AIRMAG") {
        if (IsFor3d) {
            if (EnterDraw) {
                map.DetachEvent("onmousedown", CheckDrag)
                map.DetachEvent("onmouseup", CheckDrag);
                map.DetachEvent("onmouseover", ShapeHandler);
                map.AttachEvent("onmousedown", DrawPolyMouseClick);
            }
            else {
                map.DetachEvent("onmousedown", DrawPolyMouseClick);
                map.AttachEvent("onmousedown", CheckDrag)
                map.AttachEvent("onmouseup", CheckDrag);
                map.AttachEvent("onmouseover", ShapeHandler);
            }
        }
        else {
            if (EnterDraw) {

            }
            else {

            }
        }
    }
    else if (CallingPage == "FILM") {
        if (IsFor3d) {
            if (EnterDraw) {
                map.DetachEvent("onmousedown", CheckDrag)
                map.DetachEvent("onmouseup", CheckDrag);
                map.DetachEvent("onmouseover", ShapeHandler);
                map.AttachEvent("onmousedown", DrawPolyMouseClick);
            }
            else {
                map.DetachEvent("onmousedown", DrawPolyMouseClick);
                map.AttachEvent("onmousedown", CheckDrag)
                map.AttachEvent("onmouseup", CheckDrag);
                map.AttachEvent("onmouseover", ShapeHandler);
            }
        }
        else {
            if (EnterDraw) {

            }
            else {

            }
        }
    }
}
