﻿
var COLORS = ["#ccff33", "#ff0000", "#ff8800", "#008000","#000080","#800080", "#4fffff", "#f4ff44", "#5aff44", "#4470ff"];
var colorIndex = 0;
var curPolygon;
var curPolygons = new Array();
var isDrawing = false;
var POLY_SIZE_LIMIT = 300; //ha
var flagCount = 0;
var flagArray;
var deleteImmediateMode = false;

PolygonClass = function () {

    this.poly;
    this.deleted = false;
    this.info;
    this.color;
    this.name = "";
    this.plantingdate = "";
    this.gid;
    this.group;

    /*this.irrigated = "";
    this.croptype = "";*/
}

StartDrawing = function() {
    isDrawing = true;
    Select("shape_b");    
};

StopDrawing = function() {
    if(isDrawing && curPolygon) { 
        curPolygon.poly.disableEditing();
        map.removeOverlay(curPolygon.poly);        
        curPolygon = null;
    }
    
    Select("hand_b");  
    isDrawing = false; 
};

Select = function(buttonId) {
  $get("hand_b").className="unselected";
  $get("shape_b").className="unselected";
  $get(buttonId).className="selected";
};  

GetColor = function () {
  return COLORS[colorIndex++ % COLORS.length];
};


/*************Polygon Functions********************************/

NewPolygon = function () {

    //safety check
    if (isDrawing) {
        alert("Finish the current shape.");
        return false;
    }

    //check groups
    if (groupArray.length == 0) {
        groupArray.push("Default");
        currentGroup = 0;
    }

    //create new polygon
    var pClass = new PolygonClass();
    pClass.color = GetColor();
    pClass.name = "New Field " + (curPolygons.length + 1);
    pClass.group = currentGroup;
    pClass.poly = new GPolygon([], '#999999', 3, 1, pClass.color, 0.4);
    map.addOverlay(pClass.poly);

    pClass.poly.enableDrawing(options);
    pClass.poly.enableEditing({ onEvent: "mouseover" });
    pClass.poly.disableEditing({ onEvent: "mouseout" });

    curPolygon = pClass;

    //start drawing
    StartDrawing();

    GEvent.addListener(pClass.poly, "endline", function () {
        //stop drawing        
        curPolygon = null;
        StopDrawing();
        var index = PolygonClosed(pClass);
        DrawFieldList();
        ShowPolygonPopup(index);
    });
};

AddPolygonToMap = function (poly) {
    //map.removeOverlay(poly);
    map.addOverlay(poly);
    poly.enableEditing({ onEvent: "mouseover" });
    poly.disableEditing({ onEvent: "mouseout" });
};

RemovePolygonFromMap = function (poly) {
    map.removeOverlay(poly);    
};

LoadPolygon = function (pClass) {

    AddPolygonToMap(pClass.poly);
    var index = PolygonClosed(pClass);
    PolygonUpdated(index);
};

LoadPolygons = function (polys) {
    var bounds = new GLatLngBounds();
    var points;
    var curPolygon;

    ClearPolygons();
    curPolygons = new Array();
    ClearGroups();

    for (var i = 0; i < polys.length; i++) {
        points = new Array();
        for (var j = 0; j < polys[i].Points.length; j++) {
            points.push(new GLatLng(polys[i].Points[j].Latitude, polys[i].Points[j].Longitude));
            bounds.extend(new GLatLng(polys[i].Points[j].Latitude, polys[i].Points[j].Longitude));
        }

        if (polys[i].Editable) {
            var pClass = new PolygonClass();
            pClass.color = GetColor();
            pClass.name = polys[i].Name;
            pClass.plantingdate = polys[i].PlantingDate;
            pClass.gid = polys[i].Gid;
            pClass.group = polys[i].Group;

            groupArray[polys[i].Group] = polys[i].GroupName;

            //check groups
            /*var found = false;


            for (var g = 0; g < groupArray.length; g++) {
                if (groupArray[g] == polys[i].GroupName) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                groupArray.push(polys[i].GroupName);
            }*/

            /*pClass.irrigated = polys[i].Irrigated; 
            pClass.croptype = polys[i].CropType;*/
            pClass.poly = new GPolygon(points, '#999999', 3, 1, pClass.color, 0.4);
            LoadPolygon(pClass);
        }
    }
    DrawFieldList();
    map.setZoom(map.getBoundsZoomLevel(bounds));
    map.setCenter(bounds.getCenter());

};

LoadPolygonForManager = function (poly) {
    var bounds = new GLatLngBounds();
    var points;
    var curPolygon;

    ClearPolygons();
    curPolygons = new Array();
    ClearGroups();

    points = new Array();
    for (var j = 0; j < poly.Points.length; j++) {
        points.push(new GLatLng(poly.Points[j].Latitude, poly.Points[j].Longitude));
        bounds.extend(new GLatLng(poly.Points[j].Latitude, poly.Points[j].Longitude));
    }

    var pClass = new PolygonClass();
    pClass.color = GetColor();
    pClass.name = poly.Name;
    pClass.plantingdate = poly.PlantingDate;
    pClass.gid = poly.Gid;
    pClass.group = 0; // poly.Group;
    groupArray.push(poly.GroupName);

    pClass.poly = new GPolygon(points, '#999999', 3, 1, pClass.color, 0.4);
    LoadPolygon(pClass);
    DrawFieldList();
    map.setZoom(map.getBoundsZoomLevel(bounds));
    map.setCenter(bounds.getCenter());

    deleteImmediateMode = true;
};

ClearPolygons = function () {

    if(curPolygons)
    {
        for(var i = 0; i < curPolygons.length; i++)
        {
            DeletePolygon(i);           
        }
        curPolygons = new Array();
        colorIndex = 0;
    } 
};

DeletePolygon = function (index) {

    //delete polygon
    if (deleteImmediateMode == true) {
        if(!confirm("Click OK to remove field from the cotton map. This action cannot be reversed!")){        
            return false;
        }
        CommonService.DeleteFieldForManager(curPolygons[index].gid, CloseFieldManager);
    }

    if (!curPolygons[index].deleted) {
        map.removeOverlay(curPolygons[index].poly);
        featureDiv.removeChild(curPolygons[index].info.div);
        curPolygons[index].deleted = true;
    }
    CheckSaveLink();
    CheckManageLinks();

};

ChangePolygonColor = function (index) {
    var newColor = GetColor();
    curPolygons[index].color =newColor;
    curPolygons[index].info.color.style.backgroundColor = newColor
    curPolygons[index].poly.setFillStyle({color: newColor, weight: 0.4});
};

PolygonClosed = function (pClass) {
    var index;
    curPolygons.push(pClass);
    index = curPolygons.length - 1;

    //update interface
    //DrawFieldList();

    /*pClass.info = AddPolygonInfo(pClass);
    $addHandler(pClass.info.name, 'click', function () { ShowPolygonPopup(index) });
    $addHandler(pClass.info.color, 'click', function () { ChangePolygonColor(index) });*/

    GEvent.bind(pClass.poly, "lineupdated", pClass.info, function () { PolygonUpdated(index) });
    GEvent.addListener(pClass.poly, "click", function (latlng, vi) { PolygonClicked(index, latlng, vi) });
    
    CheckSaveLink();
    CheckManageLinks();
    return index;
};

PolygonUpdated = function(index) {
    var area = curPolygons[index].poly.getArea();
    var num = Math.round(area / 10000);

    if (num > POLY_SIZE_LIMIT) showMessage("Polygon has exceeded maximum size of " + POLY_SIZE_LIMIT + "ha, please correct.", 2);
    if (curPolygons[index].info)    curPolygons[index].info.desc.innerHTML = "Area:&nbsp;" + num + "ha";           
}; 

PolygonClicked = function (index, latlng, vi) {
    if (typeof vi == "number") { 
        curPolygons[index].poly.deleteVertex(vi);
    } else {          
        ShowPolygonPopup(index);
    }
}; 

PolygonToString = function(polygon) {
    var polyVertices = "";
    var tmpMarker;
    
    for (var i = 0; i < polygon.getVertexCount(); i++) {
        polyVertices += polygon.getVertex(i).lat().toString() + "," +  polygon.getVertex(i).lng().toString() + ";";
    }  
    return polyVertices;
};

GetAllPolygonsAsString = function() {
    var polys = "";
    
    for(var i = 0; i < curPolygons.length; i++)
    {
        if(!curPolygons[i].deleted)
        {
            polys += curPolygons[i].name + "$" + PolygonToString(curPolygons[i].poly) + "|";
        }   
    }
    if (polys != "") polys = polys.substr(0, polys.length - 1);
    
    return polys;
};

GetAllPolygons = function () {
    var polys = new Array();

    for (var i = 0; i < curPolygons.length; i++) {
        if (!curPolygons[i].deleted) {
            var p = new Polygon();
            p.Points = new Array();
            for (var j = 0; j < curPolygons[i].poly.getVertexCount(); j++) {
                p.Points[j] = new Point();
                p.Points[j].Latitude = curPolygons[i].poly.getVertex(j).lat().toString();
                p.Points[j].Longitude = curPolygons[i].poly.getVertex(j).lng().toString();
            }
            p.Name = curPolygons[i].name;
            p.PlantingDate = curPolygons[i].plantingdate;
            p.Gid = curPolygons[i].gid;
            p.Group = curPolygons[i].group;
            p.GroupName = groupArray[curPolygons[i].group];            
            p.Editable = true;
            polys.push(p)
        }
    }
    return polys;
}; 

ValidPolygonCount = function() {
    var count = 0;
    
    for(var i = 0; i < curPolygons.length; i++)
    {        
        if(!curPolygons[i].deleted)
        {            
            count++;
        }
    } 
    return count;
};

/*****************************/

SelectFieldManager = function () {
    GEvent.addListener(map, "click", function (overlay, latlng) {
        SelectFieldAtLocation(overlay, latlng);
    });
    map.getDragObject().setDraggableCursor("pointer");
};

UpdateFieldManager = function () {

    deleteImmediateMode = false;

    CommonService.UpdateFieldsForManager(GetAllPolygons(), UpdateFieldManagerCallback);
};

UpdateFieldManagerCallback = function (result) {
    CloseFieldManager();
};

CloseFieldManager = function () {
    ClearPolygons();
    ClearGroups();
    DrawFieldList();
    var updateFieldLink = $get("updateFieldLink");
    var cancelFieldLink = $get("cancelFieldLink");
    updateFieldLink.style.display = "none";
    cancelFieldLink.style.display = "none";
    
    deleteImmediateMode = false;
};

SelectFieldAtLocation = function (overlay, latlng) {
    GEvent.clearListeners(map, "click");
    map.getDragObject().setDraggableCursor("url(http://maps.gstatic.com/intl/en_us/mapfiles/openhand_8_8.cur)");

    if(latlng)   CommonService.SelectFieldAtLocation(latlng.lat(), latlng.lng(), SelectFieldAtLocationCallback);
};

SelectFieldAtLocationCallback = function (poly) {
    if (poly == null) {
        showMessage("No field found",2);  
    }
    else {
        //alert("Field is " + poly.Name);
        var updateFieldLink = $get("updateFieldLink");
        var cancelFieldLink = $get("cancelFieldLink");
        updateFieldLink.style.display = "";
        cancelFieldLink.style.display = "";
        LoadPolygonForManager(poly);
    }
};

FlagModeOn = function () {
    flagCount = 0;
    flagArray = new Array();

    GEvent.addListener(map, "click", function (overlay, latlng) {
        NewFlag(overlay, latlng);
    });
    map.getDragObject().setDraggableCursor("pointer");
};

FlagModeOff = function () {
    var flaggedFieldsDiv = $get("flaggedFieldsDiv");
    if (flaggedFieldsDiv) {        

        while (flaggedFieldsDiv.childNodes[0]) {
            flaggedFieldsDiv.removeChild(flaggedFieldsDiv.childNodes[0]);
        }

    }
    if (flagArray) {
        for (var i = 0; i < flagArray.length; i++) {
            map.removeOverlay(flagArray[i]);
        }
    }
    GEvent.clearListeners(map, "click");
    map.getDragObject().setDraggableCursor("url(http://maps.gstatic.com/intl/en_us/mapfiles/openhand_8_8.cur)");
};

NewFlag = function (overlay, latlng) {

    if (flagCount > 0) {
        showMessage("Flag limit reached. Please save to continue.",2);
    }
    else {
        if (latlng) {
            var flaggedFieldsDiv = $get("flaggedFieldsDiv");
            flagCount += 1;

            if (flaggedFieldsDiv) {
                //write details
                var nameCell = document.createElement("div");
                flaggedFieldsDiv.appendChild(nameCell);
                nameCell.className = "nameDiv";
                nameCell.innerHTML = "Flag " + flagCount + " [" + latlng.lat() + ", " + latlng.lng() + "]";
            }

            var flagIcon = new GIcon();
            flagIcon.image = "Images/flag_red.png";
            flagIcon.shadow = "http://chart.apis.google.com/chart?chst=d_map_pin_shadow";
            flagIcon.shadowSize = new GSize(22, 16);
            flagIcon.iconAnchor = new GPoint(6, 14);
            flagIcon.infoWindowAnchor = new GPoint(5, 1);
            markerOptions = { icon: flagIcon };
            var tmpOv = new GMarker(latlng, markerOptions);
            map.addOverlay(tmpOv);
            flagArray.push(tmpOv);
        }
    }
};

LoadFlagLocation = function (lat, lon) {
    var latlng = new GLatLng(lat, lon, true);

    var flagIcon = new GIcon();
    flagIcon.image = "Images/flag_red.png";
    flagIcon.shadow = "http://chart.apis.google.com/chart?chst=d_map_pin_shadow";
    flagIcon.shadowSize = new GSize(22, 16);
    flagIcon.iconAnchor = new GPoint(6, 14);
    flagIcon.infoWindowAnchor = new GPoint(5, 1);
    markerOptions = { icon: flagIcon };
    var tmpOv = new GMarker(latlng, markerOptions);
    map.addOverlay(tmpOv);

    if (flagArray) {
        for (var i = 0; i < flagArray.length; i++) {
            map.removeOverlay(flagArray[i]);
        }
    }
    flagArray = new Array();
    flagArray.push(tmpOv);

    map.setZoom(11);
    map.setCenter(latlng);
};

/******************************
* Modal Popup
******************************/
ShowPolygonPopup = function (index) {
    var paddockName = $get("paddockName");
    var plantingDateInput = $get($get("plantingdateid").value);
    var fieldSelectRow = $get("fieldSelectRow");
    var fieldGroupSelect = $get("fieldGroupSelect");
    var savePaddockData = $get("savePaddockData");
    var popupBehavior = $find('paddockInfoBehaviour');

    paddockName.value = curPolygons[index].name;
    plantingDateInput.value = curPolygons[index].plantingdate;

    if (groupArray.length > 1) {
        fieldSelectRow.style.display = "";
        fieldGroupSelect.length = 0;

        //populate field groups
        for (var i = 0; i < groupArray.length; i++) {
            var op = new Option(groupArray[i], i);
            fieldGroupSelect.options[fieldGroupSelect.options.length] = op;
        }

        fieldGroupSelect.selectedIndex = curPolygons[index].group;
    } else {
        fieldSelectRow.style.display = "none";
    }

    $clearHandlers(savePaddockData);
    $clearHandlers(paddockName);

    $addHandler(savePaddockData, 'click', function () { HidePolygonPopup(index) });
    $addHandler(paddockName, 'keypress', function (e) { PolygonPopupKeyPress(e, index) });

    popupBehavior.show();
    paddockName.focus();
    paddockName.select();
};

HidePolygonPopup = function (index) {
    var paddockName = $get('paddockName');
    var plantingDateInput = $get($get("plantingdateid").value);
    var popupBehavior = $find('paddockInfoBehaviour');
    var fieldSelectRow = $get("fieldSelectRow");
    var fieldGroupSelect = $get("fieldGroupSelect");

    curPolygons[index].name = paddockName.value;
    if ( curPolygons[index].info) curPolygons[index].info.name.innerHTML = paddockName.value;
    curPolygons[index].plantingdate = plantingDateInput.value;

    if (groupArray.length > 1) {        

        //if changed
        if (curPolygons[index].group != fieldGroupSelect.value) {
            curPolygons[index].group = fieldGroupSelect.value;
            DrawFieldList();
        }
    }

    PolygonUpdated(index);
    popupBehavior.hide();
};

PolygonPopupKeyPress = function (e,index) {
    if(e){
        if (e.charCode == 13) HidePolygonPopup(index);
    }else{
        if (event.keyCode == 13) HidePolygonPopup(index);
    }
};



