﻿


var map, vectors, popup, polygonFeature, polygonLayer;
var selectPt, selectedFeature; //these vars are global so onPopupClose1 has access
var lat = 40.97381;
var lon = -76.95116;
var dragArray = [];
var layerArray = [];
var ptArray = [];

var decPrecision = 6;

//var out_options = {
//    'internalProjection': new OpenLayers.Projection("EPSG:900913"),
//    'externalProjection': new OpenLayers.Projection("EPSG:4326")
//};

//Initializes the Map
function init() {   //(from GL_JScript.js)

    if (getCookie() != 1) return;
    var map_options = {
        panMethod: OpenLayers.Easing.Linear.easeOut,
        panDuration: 20,
        projection: new OpenLayers.Projection("EPSG:900913"),
        displayProjection: new OpenLayers.Projection("EPSG:4326"),
        units: "m",
        numZoomLevels: 18,
        maxResolution: 156543.0339,
        maxExtent: new OpenLayers.Bounds(-20037508, -20037508,
                                                 20037508, 20037508.34)
    };


    map = new OpenLayers.Map('map', map_options);

    ////////////////////////////////////////////////////////////////////////////////////////

    // create Virtual Earth layers
    var veroad = new OpenLayers.Layer.VirtualEarth("Virtual Earth Roads", { 'type': VEMapStyle.Road, 'sphericalMercator': true });
    var veaer = new OpenLayers.Layer.VirtualEarth("Virtual Earth Aerial", { 'type': VEMapStyle.Aerial, 'sphericalMercator': true });
    var vehyb = new OpenLayers.Layer.VirtualEarth("Virtual Earth Hybrid", { 'type': VEMapStyle.Hybrid, 'sphericalMercator': true });

    // create OpenLayers layers   
    var wms = new OpenLayers.Layer.WMS("OpenLayers WMS", "http://labs.metacarta.com/wms/vmap0?", { layers: 'basic' });
    var layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik");
    var layerTah = new OpenLayers.Layer.OSM.Osmarender("Tiles@Home");
    // create Google Map layers  
    var gmap = new OpenLayers.Layer.Google("Google Streets", { numZoomLevels: 20 });
    var ghyb = new OpenLayers.Layer.Google("Google Hybrid", { type: google.maps.MapTypeId.HYBRID, numZoomLevels: 20 });
    var gsat = new OpenLayers.Layer.Google("Google Satellite", { type: google.maps.MapTypeId.SATELLITE, numZoomLevels: 22 });

    ////////////////////////////////////////////////////////////////////////////////////////////
    map.addLayers([/*gphy, */ghyb, gmap, gsat]);
    map.addLayers([vehyb, veroad, veaer]);

    //map.addLayers([/*gphy, */gmap, ghyb, gsat]);

    //map.addLayers([wms, layerMapnik, layerTah]);


    map.addControl(new OpenLayers.Control.LayerSwitcher());
    map.addControl(new OpenLayers.Control.MousePosition());

    /////controls//////

    //var lonLat = new OpenLayers.LonLat(lon, lat); //<-- DJ's orig
    var lonLat = new OpenLayers.LonLat(-91.04297, 22.54706); //<-- focus on Gulf


    lonLat.transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());

    map.setCenter(lonLat, 5);


    // add/initialize empty layers, to be populated as appropriate



    //ititPoly adds the polygon drawing layer
    initPoly();



    var x = window.parent.$('#WKTStr').attr('value');
    if (x != null && x != "") {
        if (!CheckIsMap()) {
            DrawFromWKT();
        } else {
            KML_Request();
        }
    }


    /*  var check = */




}

//Initialize the polygon layer and its controls (from: GL_JScript.js)
function initPoly() {
    polygonLayer = new OpenLayers.Layer.Vector("Search Polygon");
    polygonLayer.events.on({
        sketchcomplete: handleSketch
    });
    map.addLayer(polygonLayer);
    polygonFeature = new OpenLayers.Control.DrawFeature(polygonLayer,
                                OpenLayers.Handler.Polygon);
    map.addControl(polygonFeature);
}

//Clears the polygon
function clearPolygon() {
    if (polygonLayer) {
        $("#polygonStr").attr('value', '');   //do I use this?
        $('#polygonCheck').attr('disabled', false);
        $('#polygonCheck').attr('checked', false);
        $("#btnClearMap").css('display', 'none');
        $('#MapName').attr('value', '');

        polygonLayer.removeAllFeatures();
        //destroyPoly();
    }
}

//Destroy the polygon layer and its controls (from GL_JScript.js)   //do I still need this?
function destroyPoly() {
    polygonFeature.deactivate();
    map.removeLayer(polygonLayer);
    map.removeControl(polygonFeature);
    polygonFeature.destroy();
    polygonLayer.destroy();
    polygonFeature = null;
    polygonLayer = null;
}

//Handler for polygon sketch events
function handleSketch(evt) {
    var polyPoints = new Array();
    if (evt.type == 'sketchcomplete') {
        var edges = evt.feature.geometry.getVertices();
        for (var i = 0; i < edges.length; i++) {
            var pt = new OpenLayers.Geometry.Point(edges[i].x, edges[i].y);
            pt.transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
            polyPoints.push(pt);
        }

        //Close the polygon.
        polyPoints.push(polyPoints[0]);

        //Build polygon string and save it.
        var t2 = new OpenLayers.Feature;
        var FeatureCopy = evt.feature.clone();
        FeatureCopy.geometry.transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));

        var wkt = new OpenLayers.Format.WKT();
        var strWKT = wkt.write(FeatureCopy);

        window.parent.$("#WKTStr").attr('value', strWKT);
        $("#btnDrawPoly").css('display', 'block');
        $("#lblDrawPoly").css('display', 'block');

        polygonFeature.deactivate();

        $('#polygonCheck').attr('checked', false);
        $('#polygonCheck').attr('disabled', true);
        $("#btnClearMap").css('display', '');

    }
}

// Populates the polygonLayer with the polygon in WKTStr
// this function is called on init(), only if the WKTStr textbox has a value
function DrawFromWKT() {
    var out_options = {
        'internalProjection': new OpenLayers.Projection("EPSG:900913"),
        'externalProjection': new OpenLayers.Projection("EPSG:4326")
    };
    //this reads the feature
    var wkt = new OpenLayers.Format.WKT(out_options);
    var features = wkt.read(window.parent.$("#WKTStr").attr('value'));

    //This populates and zooms to the bounds, or tosses back an error if the WKT was bad (or empty)
    var bounds;
    if (features) {
        if (features.constructor != Array) {
            features = [features];
        }
        for (var i = 0; i < features.length; ++i) {
            if (!bounds) {
                bounds = features[i].geometry.getBounds();
            } else {
                bounds.extend(features[i].geometry.getBounds());
            }

        }

        //draw the map
        polygonLayer.addFeatures(features);
        map.zoomToExtent(bounds);
        $("#btnClearMap").css('display', '');
        $('#polygonCheck').attr('disabled', true);

    } else {
        alert('The data entered is not valid WKT. \n\r Please check your data and try again. ');
    }
}

/*  Function MakeGeoJSON
function DrawPoints
function onFeatureSelect1
function onPopupClose1
onFeatureUnselect1
*/





function KMLtoWKT() {
    var type = "kml";
    var in_options = {
        'internalProjection': new OpenLayers.Projection("EPSG:900913"),
        'externalProjection': new OpenLayers.Projection("EPSG:4326")
    };
    var kmlOptionsIn = OpenLayers.Util.extend({ extractStyles: false }, in_options);

    var kml = new OpenLayers.Format.KML(kmlOptionsIn);
    var features = kml.read($('#KMLStr').attr('value'));

    var FeatureCopy = features.clone();

    var wkt = new OpenLayers.Format.WKT();
    var strWKT = wkt.write(FeatureCopy);
    $('#output').attr('value', strWKT);
}


/*  Non-map functions   */
function SaveScroll() {
    $('#ScrollY').attr('value', $(window).scrollTop());
    $('#ScrollX').attr('value', $(window).scrollLeft());
}
function ScrollToResults(downTo) {
    window.scrollTo(0, downTo);
    //alert("top, downTo = " + $(window).scrollTop() + ", " + downTo.toString());
}

function clearFields() {
    $('#tbxTaxon').attr('value', '');
    $('#tbxLocation').attr('value', '');
    $('#tbxCatNum').attr('value', '');
    $('#tbxDateRange').attr('value', '');
    $('#tbxOther').attr('value', '');
    $('#WKTStr').attr('value', '');
    clearPolygon();
}

function checkFields() {
    //set lables
    $('#lblDateRange').css('display', '');
    $('#lblDRError').css('display', 'none');
    $('#lblWKTStr').css('display', '');
    $('#lblWKTError').css('display', 'none');
    $("#WKTaddlInfo").css("color", "");
    $("#WKTaddlInfo").html("<small>You may use the map below to draw a polygon.<br /> Doing so will populate this field.</small>");

    //check that at least one field is populated
    var tx = $('#tbxTaxon').attr('value');
    var loc = $('#tbxLocation').attr('value');
    var cat = $('#tbxCatNum').attr('value');
    var dr = $('#tbxDateRange').attr('value');
    var oth = $('#tbxOther').attr('value');
    var wkt = $('#WKTStr').attr('value');
    if ((tx == null || tx == "") &&
                    (loc == null || loc == "") &&
                    (cat == null || cat == "") &&
                    (dr == null || dr == "") &&
                    (oth == null || oth == "") &&
                    (wkt == null || wkt == "")) { // if all fields are blank, display error message
        $('#lblExecute').attr('value', 'Please enter at least one valid search term.');
        $('#lblExecute').css('display', '');
        return false;
    }

    //check Date Range
    var re = new RegExp("\\d\\d\\d\\d-\\d\\d\\d\\d");
    if (dr != null && dr != "") { //if the field isn't empty
        if (!dr.match(re)) { //check it for formatting
            $('#lblDateRange').css('display', 'none');
            $('#lblDRError').css('display', '');
            return false; //don't go to server if bad formatting  
        }
    }

    //check WKTStr
    if (wkt != null && wkt != "" && !CheckIsMap()) {
        var inProj = new OpenLayers.Projection("EPSG:900913");
        var exProj = new OpenLayers.Projection("EPSG:4326");
        var format = new OpenLayers.Format.WKT({ internalProjection: inProj, externalProjection: exProj });
        var features = format.read(wkt); 
        if (!features) {
            $("#WKTaddlInfo").css("color", "Red");
            $("#WKTaddlInfo").html("WKT formt incorrect. Please check your data and try again.");
            return false;
        }
        //support up to 250 verticies or 10000 characters; at 12 decimal places, 250 verticies is ~8500 characters.
        if (($('#WKTStr').val().length > 10000) || (features.geometry.getVertices().length > 250)) {
            $("#WKTaddlInfo").css("color", "Red");
            $("#WKTaddlInfo").html("Your polygon is more complex than this interface supports.  Please simplify your polygon.");
            return false;
        }
    }

}

//An ajax script for loading the institution codes from InstitutionCode.htm
function loadInstitutionCodes() {
    $('#CatNumContent').empty().html('<b>Loading</b><img alt="Loading..." src="images/ajax-loader.gif" style="width: 128px; height: 15px; padding-top:20px;" />');
    $.ajax({
        url: 'InstitutionCode.htm',
        dataType: 'html',
        success: function(data) {
            $('#CatNumContent').html(data);
        }
    });
}

function loadTaxaSearchResults(taxa) {
    $('#TaxaContent').empty().html('<b>Loading</b><img alt="Loading..." src="images/ajax-loader.gif" style="width: 128px; height: 15px; padding-top:20px;" />');
    $.ajax({
        url: 'Family.aspx',
        data: 't=' + taxa,
        dataType: 'html',
        timeout: 5000,
        success: function(data) {
            $('#TaxaContent').html(data);
        },
        error: function(objAJAXRequest, strError, errorThrown) {
            if (strError == "timeout") {
                $('#TaxaContent').html("The ITIS webservice is taking too long to respond. <br/><br/>" +
            "Click <a href='http://www.itis.gov/advanced_search.html' target='_blank'>here</a> " +
            "to go the ITIS website to perform your search directly.");
            } else {
                $('#TaxaContent').html("Error!  Type: " + strError + "<br/>Message: " + errorThrown);
            }
        }
    });
}

//KML map functions
function DrawFromKML(data) {
    var out_options = {
        'internalProjection': new OpenLayers.Projection("EPSG:900913"),
        'externalProjection': new OpenLayers.Projection("EPSG:4326")
    };
    var kml = new OpenLayers.Format.KML(out_options);
    var features = kml.read(data);

    var bounds;
    if (features) {
        if (features.constructor != Array) {
            features = [features];
        }
        for (var i = 0; i < features.length; ++i) {
            if (!bounds) {
                bounds = features[i].geometry.getBounds();
            } else {
                bounds.extend(features[i].geometry.getBounds());
            }

        }
        polygonLayer.removeAllFeatures();
        //draw the map
        polygonLayer.addFeatures(features);
        map.zoomToExtent(bounds);
        $("#btnClearMap").css('display', '');
        $('#polygonCheck').attr('disabled', true);
    } else {
        alert('The the map you selected could not be located. \n\r Please check your data and try again. ');
    }
}

function KML_Request() {    //kmlURL
    $('#Loading').css('height', '15px');
    $('#Loading').css('display', 'block');    
    $.ajax({
        url: 'PolyLookup/KMLs/txts/' + window.parent.$('#KML').attr('value') + '.txt',
        success: function(data) {
            $('#Loading').css('display', 'none');
            $('#Loading').css('height', '0px');
            DrawFromKML(data);
            if ($('#MapExpand').attr('value') != 'Open') {
                $("#aDrawMap").click();
            }
        },
        error: function(request) {
            alert(request.status + "::" + request.responseText);
        }
    });
}

function CheckIsMap() {
    if (window.parent.$('#MapName').attr('value').match(window.parent.$('#WKTStr').attr('value'))) {
        return true;
    } else {
        return false;
    }
}

//'Forward/Next' function in Map menu
function ForwardMapNav(menu) {    
    $.ajax({
        url: 'PolyLookup/PolyLookups.aspx',
        data: 'm=' + menu,
        dataType: 'html',
        success: function(data) {
            $("#PolyContent").stop().animate({
            left: "-=250px",
                duration: 200
            },
                function() {
                    $("#PolyContent").css("left", "250px");
                    $("#PolyContent").html(data);
                    $("#PolyContent").animate({
                    left: "-=250px",
                        queue: true,
                        duration: 200,
                        easing: 'easeOutCubic'
                    });
                }
            );  //close animate
        } //close success
    });   //close ajax
}    //close function

//'Back'function in Map menu
function BackMapNav(menu) {
    $.ajax({
        url: 'PolyLookup/PolyLookups.aspx',
        data: 'm=' + menu,
        dataType: 'html',
        success: function(data) {
            $("#PolyContent").stop().animate({
            left: "+=250px",
                duration: 200
            },
                function() {
            $("#PolyContent").css("left", ("-250px"));
                    $("#PolyContent").html(data);
                    $("#PolyContent").animate({
                    left: "+=250px",
                        queue: true,
                        duration: 200,
                        easing: 'easeOutCubic'
                    });
                }
            );  //close animate
        } //close success
    });   //close ajax
}   //close function

function MapNav_click(name, id, kml) {
    try {
        $("#WKTStr").attr("value", name);
        $("#MapName").attr("value", name);
        $("#MapID").attr("value", id);
        $("#KML").attr("value", kml);
        $("#selPoly").click();
        KML_Request();
    }
    catch (err) {
        alert(err);
    }
}

function PopulateLocation() {
    var strState = $('#tbxState').value;
    var strCounty = $('#tbxCounty').value;
    var strOut = "";
    if ($("#tbxContinent").val()) {
        strOut += "ContinentOcean:" + $('#tbxContinent').val();
    }
    if ($("#tbxCountry").val()) {
        if (strOut.length > 0) {
            strOut += ", ";
        }
        strOut += "Country:" + $("#tbxCountry").val();
    }
    if ($("#tbxState").val()) {
        if (strOut.length > 0) {
            strOut += ", ";
        }
        strOut += "StateProvince:" + $("#tbxState").val();
    }
    if ($("#tbxCounty").val()) {
        if (strOut.length > 0) {
            strOut += ", ";
        }
        strOut += "County:" + $("#tbxCounty").val();
    }
    $('#tbxLocation').attr('value', strOut);
}

function CloseOtherDivs(openingDiv) {
    //collection of divs
    var divs = {
        "Location": "#selLocation",
        "Institution Code": "#selCatNum",
        "Map Search": "#selPoly"
    };

    //check the other divs - if open, then close (via click)
    $.each(divs, function(key, value) {
        if (key != openingDiv) {
            if ($(value).text() == "<<") {
                $(value).click();
            }
        }
    });
}
