//var gPolyMode = false;
var gFeatureTypeID = -1;  // type of newly create feature
var gPopupPosition;       // Location of popup
var gPopup;               // Feature data popup
var newFeatureID;         // id of newly created feature

//var polyPoints = [];
//var reasons = [];

//var geocoder = null;
//var GeoAccuracy = [];
//var ovcontrol;

////km distance for search result to be included
//var mapMaxDistanceKmForSearch = 100;

var webhost= 'www.piscesmarine.no-ip.org';

var lon = -1005709;
var lat = 6454732;//7000000;//
var zoom = 6;

var map;
//var mapextent = new OpenLayers.Bounds(-2000000, 4000000, 2000000, 9000000);

var selectedFeature;

var featureLayer;    // Layer containing user features
var markers;
var mapLayers = 'PISCES_Project_Extent';  // Comma separated list of base layers
var wmsOverlay;

function closeFeaturesForm(featureID) {
    updateFeaturesList();

    closePopup();

    // See http://openlayers.org/pipermail/users/2009-August/013111.html
//    if (featureID != undefined)
//        modifyTool.selectFeature(featureLayer.getFeatureById(featureID));
}

function closePopup() {
    if (gPopup != undefined) {
        map.removePopup(gPopup);
        gPopup.destroy();
        gPopup = null;
    }

    // Redraw features
    drawFeatures();
}

function showPopupByFeatureId(featureId) {
    var feature = featureLayer.getFeatureById(featureId);
    showPopup(feature);
}

function showPopup(feature) {
    closePopup();

    gPopupPosition = new OpenLayers.LonLat(feature.geometry.getCentroid().x, feature.geometry.getCentroid().y);
    var theDate = new Date();
    OpenLayers.loadURL('DetailsContainer.aspx', '?FeatureCode=' + feature.id, this, showPopupResponse);
}

function showPopupResponse(data) {
    if (data != undefined) {
        gPopup = new OpenLayers.Popup.FramedCloud(
                     'Feature details',
                     gPopupPosition,
                     null,
                     data.responseText,
                     null,
                     true,
                     updateFeaturesList()
                 );
        map.addPopup(gPopup);
	}
}
var wmsClone;
function initialize() {

    OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
    OpenLayers.Util.onImageLoadErrorColor = 'transparent';

    if (isIE) {
        if (getIEVersionNumber() == 6) {
            // Map does not resize properly so set a static width
            document.getElementById('map').style.width = "700";
            document.getElementById('map').style.height = "500";
        }
    }

    map = new OpenLayers.Map('map', { controls: [] });
     //map = new OpenLayers.Map('map', { controls: [] , restrictedExtent: mapextent});
    map.projection = new OpenLayers.Projection('EPSG:900913');
    map.displayProjection = new OpenLayers.Projection('EPSG:900913');
    map.units = 'metres';

    var wms = new OpenLayers.Layer.OSM.Mapnik('Mapnik', { minZoomLevel: 4, maxZoomLevel: 12, numZoomLevels: null });
    // Clone for Overview Map
    var wmsClone = wms.clone();
    //var wms = new OpenLayers.Layer.OSM.Osmarender('Osmarender');  // Alternative open layers
    wms.sphericalMercator = 'true';
    wms.transitionEffect = 'resize';

    // The following stylemap correctly colours in all features but introduces the following bug:
    // when you delete a feature if you pan the map afterwards the feature is drawn back on the map.
    // Must be caching something I assume so might be able to hack our way out of it with a few redraws, etc
//    var styleMap = new OpenLayers.StyleMap({
//        'default': new OpenLayers.Style({
//            fillColor: 'red',
//            fillOpacity: '0.4',
//            strokeColor: '#ff9933',
//            strokeWidth: 2
//        })
//    });
//    var lookup = {
//        1: { fillColor: 'red' },
//        2: { fillColor: 'blue' },
//        3: { fillColor: 'blue' },
//        4: { fillColor: 'green' },
//        5: { fillColor: 'red' },
//        6: { fillColor: 'blue' },
//        7: { fillColor: 'red' },
//        8: { fillColor: 'red' },
//        9: { fillColor: 'red' },
//        10: { fillColor: 'red' },
//        11: { fillColor: 'green' },
//        12: { fillColor: 'blue' },
//        13: { fillColor: 'blue' },
//        14: { fillColor: 'blue' },
//        15: { fillColor: 'blue' }
//    }
//    styleMap.addUniqueValueRules('default', 'featureTypeID', lookup);

    //featureLayer = new OpenLayers.Layer.Vector('FeatureLayer', { styleMap: styleMap });
    featureLayer = new OpenLayers.Layer.Vector('FeatureLayer', {isVector:true});
    // Don't think you can set the projection for a vector layer so the following does nothing.
    // Instead need to transform each feature going in/out and also on selection...hopefully I'm wrong here.
    //featureLayer.projection = new OpenLayers.Projection('EPSG:4326');

    markers = new OpenLayers.Layer.Markers("Markers");

    map.addLayers([wms, featureLayer, markers]);

    map.setCenter(new OpenLayers.LonLat(lon, lat), zoom);

    if (isIE()) {
        if (getIEVersionNumber() == 7) {
            // Map does not resize properly so set a static width
            document.getElementById('map').style.width = map.div.clientWidth;
            document.getElementById('map').style.height = map.div.clientHeight;
        }
    }

    addTools();

    drawFeatures();

    createWMSOverlay(mapLayers);
    doResize();
    map.updateSize();
}

function isIE() {
    var ua = navigator.userAgent;
    var MSIEOffset = ua.indexOf("MSIE ");

    if (MSIEOffset == -1)
        return false;
    else
        return true;
}

function getIEVersionNumber() {
    var ua = navigator.userAgent;
    var MSIEOffset = ua.indexOf("MSIE ");

    if (MSIEOffset == -1)
        return 0;
    else
        return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));
}


var ie7normalwidth;
var ie7expandedwidth;

function resizePanel() {
    var leftPanelDiv;
    var mapToolsDiv;
    var mapDiv;
    var ExpandMapImage;
    var ContractMapImage;
    var ExpandContractMapLabel;
    var leftPanel;
    var rightBGDiv;
    var tabsBottomDiv;
    var northarrow;
    var position;
    
    leftPanelDiv = document.getElementById('leftPanel');
    mapToolsDiv = document.getElementById('mapTools');
    mapDiv = document.getElementById('map');
    northArrowDiv = document.getElementById('north_arrow');
    ExpandMapImage = document.getElementById('ExpandMapImage');
    ContractMapImage = document.getElementById('ContractMapImage');
    ExpandContractMapLabel = document.getElementById('ExpandContractMapLabel');

     

    rightBGDiv = document.getElementById('rightBG');
    tabsBottomDiv = document.getElementById('tabsBottom');

    if (leftPanelDiv != null && mapToolsDiv != null)
    {
        if (leftPanelDiv.style.zIndex == '-1')
        {
            // Show left panel and contract map

            
            //dojo.style("north_arrow", "left", "430px");
            
            
            
            leftPanelDiv.style.zIndex= '1';
            leftPanelDiv.style.visibility = 'visible';
            rightBGDiv.style.visibility = 'visible';
            tabsBottomDiv.style.visibility = 'visible';
            // Hide relevant expand/contract map image and alter text
            ExpandMapImage.style.zIndex = '1';
            ContractMapImage.style.zIndex = '0';
            ExpandContractMapLabel.textContent = 'View larger map';
            ExpandContractMapLabel.innerText = 'View larger map';
            northArrowDiv.style.marginLeft = '365px';
            mapToolsDiv.style.marginLeft = '365px';
            mapDiv.style.marginLeft = '365px';
            mapDiv.style.marginBottom = '0px';
            doResize();
	    map.updateSize();
           
            if (isIE()) {
	                   if (getIEVersionNumber() == 7) {
	                  
	                       // Map does not resize properly so set a static width
	                      // document.getElementById('map').style.width = '100%';
	                      dojo.style("map", "height", map.div.clientHeight + "px");
	                      dojo.style("map", "width", dojo.style("mapTools", "width") + "px");
	                     // alert(ie7normalwidth + "px");
	                      // document.getElementById('map').style.height = map.div.clientHeight;
	                     //  alert(map.div.clientHeight);
	   
	                   }
             }
           
           
           
        }
        else {
            // Hide tool panel and expand map
           
            //dojo.style("north_arrow", "left", "90px");
         
           
            
            
            leftPanelDiv.style.zIndex = '-1';
            leftPanelDiv.style.visibility = 'hidden';
            rightBGDiv.style.visibility = 'hidden';
            tabsBottomDiv.style.visibility = 'hidden';
            // Hide relevant expand/contract map image and alter text
            ExpandMapImage.style.zIndex = '0';
            ContractMapImage.style.zIndex = '1';
            ExpandContractMapLabel.textContent = 'View smaller map';
            ExpandContractMapLabel.innerText = 'View smaller map';
            mapToolsDiv.style.marginLeft = '10px';
            northArrowDiv.style.marginLeft = '10px';
            mapDiv.style.marginLeft = '10px';
            mapDiv.style.marginBottom = '0px';
            //dojo.style("map", "margin-left", "0px");
            if (isIE()) {
                if (getIEVersionNumber() == 7) {
                
                
               
                    // Map does not resize properly so set a static width
                   // document.getElementById('map').style.width = '100%';
                   dojo.style("map", "height", map.div.clientHeight + "px");
                   dojo.style("map", "width", dojo.style("mapTools", "width") + "px");
                   // document.getElementById('map').style.height = map.div.clientHeight;
                  //  alert(map.div.clientHeight);

                }
            }
	    doResize();
            map.updateSize();
            
        }
    }
}
