﻿
var OSLayers = [];
var OSVectorLayers = [];
var OSSelectCtrl;
var OSSelectedFeature;
var OSPopup;

function OSgetMap(div, eventListeners, options) {
    var mapOptions;
    var newMap;

    if (options) {
        mapOptions = options;
    } else {
        mapOptions = {
            maxExtent: new OpenLayers.Bounds(472000, 228000, 502000, 258000),
            restrictedExtent: new OpenLayers.Bounds(472000, 228000, 502000, 258000),
            units: "metres",
            projection: "EPSG:27700",
            minResolution:0.15,
            maxResolution:32
        };
    }
    if (eventListeners) {
        mapOptions.eventListeners = eventListeners;
    }
    
    newMap = new OpenLayers.Map(div, mapOptions);
    
    //Base layers
    OSLayers.push(
        new OpenLayers.Layer.WMS(
            "50k",
            "http://www.getmapping.com/iedirectimage/getmappingwms.aspx?login=smaynard311&password=haze59&country=os", 
            {layers: 'OneTo50KMapping', isBaseLayer: true},
            {attribution:"© Crown copyright. All rights reserved. Licence no. LA100019593"}
            )
    );

    
    OSLayers.push(
        new OpenLayers.Layer.WMS(
            "10k",
            "http://www.getmapping.com/iedirectimage/getmappingwms.aspx?login=smaynard311&password=haze59&country=os", 
            {layers: 'OneTo10KMapping', isBaseLayer: true},
            {attribution:"© Crown copyright. All rights reserved. Licence no. LA100019593"}
            )
    );
    
    
    
      //Styles for pin vector features
    var defPinStyle = new OpenLayers.Style({
        externalGraphic: "/images/markers/${defGraphic}", 
        graphicWidth:13, 
        graphicHeight:13
    });
    var selPinStyle = new OpenLayers.Style({
        externalGraphic: "/images/markers/${selGraphic}"
    });
  
    var myPinStyle = new OpenLayers.StyleMap({
        'default': defPinStyle,
        'select': selPinStyle
    });
    
    //Styles for polygon vector features
    var defStyle = new OpenLayers.Style({
        strokeColor: "black",
        strokeWidth: 3,
        strokeOpacity: 1, 
        fillOpacity: 0.3,                                                  
        fillColor:"${colourCode}"
    });
 
   //Styles for Boundaries 
    var BoundaryStyle = new OpenLayers.Style({
        strokeColor:"${colourCode}",
        strokeWidth: "${strokeWidth}",
        strokeOpacity: 1
    });
 
    var selStyle = new OpenLayers.Style({
        fillOpacity: 0.6
    });
  
    var myStyle = new OpenLayers.StyleMap({
        'default': defStyle,
        'select': selStyle
    });
    
    var myStyle2 = new OpenLayers.StyleMap({
        'default': BoundaryStyle
    });
    
    
    var styles3 = new OpenLayers.StyleMap({
                "default": {
                    graphicName: "${type}",
                    pointRadius: "${radius}",
                    fillColor: "red",
                    fillOpacity: 0.3
                },
                "select": {
                    graphicName: "${type}",
                    pointRadius: "${radius}",
                    fillColor: "red",
                    fillOpacity: .8
                }
            });

    
    
    //Vector layers   
    OSVectorLayers.push(
        new OpenLayers.Layer.Vector("Vector Layer", {styleMap: myStyle})
    );
      var pinLayer = new OpenLayers.Layer.Vector("Pins Layer", {styleMap: styles3})
    OSVectorLayers.push(pinLayer);
    
    OSVectorLayers.push(
        new OpenLayers.Layer.Vector("Vector Boundary Layer", {styleMap: myStyle2}) 
    );
    newMap.addLayers(OSLayers);
    newMap.addLayers(OSVectorLayers);
    
    //Copyright notice
    var ctrlAttr = newMap.getControlsBy('displayClass', 'olControlAttribution');
    if (ctrlAttr.length > 0) {
        //ctrlAttr[0].moveTo(new OpenLayers.Pixel(0, newMap.getSize().h - 50));
        //ctrlAttr[0].displayClass = 'olControlAttributionOverride';
        //ctrlAttr[0].draw();
        ctrlAttr[0].destroy();
    }
    newMap.addControl(new OpenLayers.Control.Attribution({displayClass: 'olControlAttributionOverride'}));

   
    //Select control for vector layer
    OSSelectCtrl = new OpenLayers.Control.SelectFeature(
            OSVectorLayers,
            {
                clickout: true
                ,onSelect: mapSelectHandler
                ,onUnselect: mapUnselectHandler
                ,callbacks: {dblclick: mapDblClickHandler}
                ,multiple: true
                ,toggle: false
            }
        );
    

    newMap.addControl(OSSelectCtrl);
    OSSelectCtrl.handlers.feature.stopDown = false;
    OSSelectCtrl.handlers.feature.stopUp = false;
    OSSelectCtrl.handlers.feature.stopClick = false;
    OSSelectCtrl.activate();
    
     //Box Select
    OSSelectByBoxCtrl = new OpenLayers.Control.SelectFeature(
            OSVectorLayers[1],
            {
                clickout: true
                ,onSelect: mapGroupSelectHandler
                ,onUnselect: mapGroupUnselectHandler
                ,multiple: true
                ,box: true
            }
        );
    
    newMap.addControl(OSSelectByBoxCtrl);
    
    //Control to toggle box selection
    OSbtnBox = new OpenLayers.Control.Button({
                        displayClass: "btnBox", 
                        trigger: OStoggleBoxSelect
                   });
    var OSctrlPanel = new OpenLayers.Control.Panel({
                      });
    OSctrlPanel.addControls([OSbtnBox])                      
    newMap.addControl(OSctrlPanel);
    
    return newMap;
    
}

function OSsetCenter(theMap, x, y, z) {
    theMap.setCenter(new OpenLayers.LonLat(x, y), z);
}

function OSsetBase(theMap, index) {
    if (index < OSLayers.length) {
        theMap.setBaseLayer(OSLayers[index]);
    }
    //need to show watermark for 10k layer
    wmDiv = $("watermarkDiv");
   if (index == 1) {
        wmDiv.style.display = 'block';
   } else {
        wmDiv.style.display = 'none';
   }
}

function OSgetBounds(theMap) {
    var currentSize = theMap.getSize();
    return {SW: theMap.getLonLatFromViewPortPx (new OpenLayers.Pixel(0,currentSize.h)), 
        NE: theMap.getLonLatFromViewPortPx (new OpenLayers.Pixel(currentSize.w,0))
    };
}

function OSgetZoom(theMap) {
    return theMap.getZoom();
}

function OSVectorFeatureFromWKT(theWKT, additionalAttributes) {
    var wktFormatter = new OpenLayers.Format.WKT(); 
    var newFeature = wktFormatter.read(theWKT);
    newFeature.attributes = additionalAttributes;
    return newFeature;
}

function OSaddVectorFeatureFromWKT(index, theWKT, additionalAttributes) {
    var wktFormatter = new OpenLayers.Format.WKT(); 
    var newFeature = wktFormatter.read(theWKT);
    newFeature.attributes = additionalAttributes;
    OSVectorLayers[index].addFeatures([newFeature]);   
}

function OSaddVectorFeatures(index, newFeatures) {
    //console.log("add features", newFeatures.length);
    OSVectorLayers[index].addFeatures(newFeatures);     
}

function OSdestroyVectorFeatures(index, killFeatures) {
    //console.log("destroy features", killFeatures.length);
    OSVectorLayers[index].destroyFeatures(killFeatures);     
}


function OSclearVectorLayer(index) {
    //console.log("OSclearVectorLayer")
    OSremoveInfoPopup(null);
    OSVectorLayers[index].destroyFeatures();
}

function OSshowInfoPopup(theMap, feature, content) {
    //console.log("OSshowInfoPopup");
    OSSelectedFeature = feature;
    OSPopup = new OpenLayers.Popup.AnchoredBubble(feature.attributes.locationID, 
                             //feature.geometry.getBounds().getCenterLonLat(),
                             theMap.getLonLatFromPixel(OSSelectCtrl.handlers.feature.down),
                             new OpenLayers.Size(400, 380),
                             content,
                             null,
                             true, 
                             OSonPopupClose);
    OSPopup.panMapIfOutOfView = true;
    feature.popup = OSPopup;
    theMap.addPopup(OSPopup, true);
}

function OSshowInfoPopupSized(theMap, feature, content, width, height) {
    //console.log("OSshowInfoPopupSized");
    OSSelectedFeature = feature;
    OSPopup = new OpenLayers.Popup.AnchoredBubble(feature.attributes.locationID, 
                             //feature.geometry.getBounds().getCenterLonLat(),
                             theMap.getLonLatFromPixel(OSSelectCtrl.handlers.feature.down),
                             new OpenLayers.Size(width, height),
                             content,
                             null,
                             true, 
                             OSonPopupClose);
    OSPopup.panMapIfOutOfView = true;
    feature.popup = OSPopup;
    theMap.addPopup(OSPopup, true);
}

function OSonPopupClose(evt) {
 
    try{
    
        OSSelectCtrl.unselect(OSSelectedFeature);
        OSSelectedFeature = '';
    } catch(e){}
}



function OSremoveInfoPopup(feature) {
 
    if (OSPopup && OSPopup!=null) {
        map.removePopup(OSPopup);
        OSPopup.destroy();
        OSPopup = null;
    }
}

function OSgetFeatureClickPos(theMap) {
    return theMap.getLonLatFromPixel(OSSelectCtrl.handlers.feature.down)
}

function OStoggleBoxSelect(forceDeactivate) {
    if (OSbtnBox.active||forceDeactivate) {
        OSbtnBox.deactivate();
        OSSelectCtrl.activate();
        OSSelectByBoxCtrl.deactivate();
    } else {
        OSbtnBox.activate();
        OSSelectCtrl.deactivate();
        //clear prev selection if any
        OSSelectByBoxCtrl.unselectAll();
        OSSelectByBoxCtrl.activate();
    }
}
