/**
* WIYBY Enhancements 2007
* 
* WIYBY RELEASE 13.1
*
* Author : ESRI(UK)
* Date : 10/12/2007
* 
* Copyright Environment Agency 2007 - not to be distributed
* or used without explicit permission from the Environment Agency
*/


/**
 * @requires OpenLayers/Layer/Grid.js
 * @requires OpenLayers/Tile/Image.js
 * 
 * Class: WiybyMapLayer
 * Based on OpenLayers.Layer.WMS
 * 
 * Inherits from:
 *  - <OpenLayers.Layer.Grid>
 */
WiybyMapLayer = OpenLayers.Class(OpenLayers.Layer.Grid, {
    

    resolutions: [],
    
    numZoomLevels: 5,
	
	/**
     * To ensure good performance buffer is set to 0 for now
     */
    buffer : 0,
    
        
    /**
     * Property: reproject
     * *Deprecated*. See http://trac.openlayers.org/wiki/SpatialMercator
     * for information on the replacement for this functionality. 
     * {Boolean} Try to reproject this layer if its coordinate reference system
     *           is different than that of the base layer.  Default is true.  
     *           Set this in the layer options.  Should be set to false in 
     *           most cases.
     */
    reproject: false,
 
    /**
     * APIProperty: isBaseLayer
     * {Boolean} Default is true
     */
    isBaseLayer: true,
    
    //WIYBY 12.3 - CPH
    //Added singlTile and ratio properties to support single tiling workaround 
     /**
     * APIProperty: singleTile
     * {Boolean} Moves the layer into single-tile mode, meaning that one tile 
     *     will be loaded. The tile's size will be determined by the 'ratio'
     *     property. When the tile is dragged such that it does not cover the 
     *     entire viewport, it is reloaded.
     */
    singleTile: true,

    /** APIProperty: ratio
     *  {Float} Used only when in single-tile mode, this specifies the 
     *          ratio of the size of the single tile to the size of the map.
     */
    ratio: 1.0,
 
    /**
     * Constructor: WiybyMapLayer
     * Create a new WiybyMapLayer layer object
     */
    initialize: function(name, url, params, options) {
        var newArguments = [];
        //uppercase params
        params = OpenLayers.Util.upperCaseObject(params);
        newArguments.push(name, url, params, options);
        OpenLayers.Layer.Grid.prototype.initialize.apply(this, newArguments);
        OpenLayers.Util.applyDefaults(
                       this.params, 
                       OpenLayers.Util.upperCaseObject(this.DEFAULT_PARAMS)
                       );


        //layer is transparent        
        if (this.params.TRANSPARENT && 
            this.params.TRANSPARENT.toString().toLowerCase() == "true") {
            
            // unless explicitly set in options, make layer an overlay
            if ( (options == null) || (!options.isBaseLayer) ) {
                this.isBaseLayer = false;
            } 
        }
        
		//console.log("WiybyMapLayer.initialize() - initialized layer");
    },    

    /**
     * Method: destroy
     * Destroy this layer
     */
    destroy: function() {
        // for now, nothing special to do here. 
        OpenLayers.Layer.Grid.prototype.destroy.apply(this, arguments);  
    },

    
    /**
     * Method: clone
     * Create a clone of this layer
     *
     * Returns:
     * {<WiybyMapLayer>} An exact clone of this layer
     */
    clone: function (obj) {
        
        if (obj == null) {
            obj = new WiybyMapLayer(this.name,
                                           this.url,
                                           this.params,
                                           this.options);
        }

        //get all additions from superclasses
        obj = OpenLayers.Layer.Grid.prototype.clone.apply(this, [obj]);

        // copy/set any non-init, non-simple values here

        return obj;
    },    
    
    /**
     * Method: getURL
     * Return a WIYBY query string for this layer
     *
     * Parameters:
     * bounds - {<OpenLayers.Bounds>} A bounds representing the bbox for the
     *                                request.
     *
     * Image width and height removed from here for now - fix this, make sure 
     * same in OpenLayers.Map options
     * 
     * Returns:
     * {String} A string with the layer's url and parameters and also the
     *          passed-in bounds and appropriate tile size specified as 
     *          parameters.
     * 
     */
    getURL: function (bounds) {
        
        bounds = this.adjustBounds(bounds);
        
        var imageSize = this.getImageSize(); 
        var scale = this.map.getZoom();

       	return this.getFullRequestString(
                     {ep: "ajaxmap",
					  topic: topicName,
                      layerGroups: selectedLayerGroupsString,
                      minx: bounds.left,
                      maxx: bounds.right,
                      miny: bounds.bottom,
                      maxy: bounds.top,
                      scale : scale
                      });
                      
    },

    /**
     * Method: addTile
     * addTile creates a tile, initializes it, and adds it to the layer div. 
     *
     * Parameters:
     * bounds - {<OpenLayers.Bounds>}
     * 
     * Returns:
     * {<OpenLayers.Tile.Image>} The added OpenLayers.Tile.Image
     */
    addTile:function(bounds,position) {
        return new OpenLayers.Tile.Image(this, position, bounds, 
                                         null, this.tileSize);
    },

    /**
     * APIMethod: mergeNewParams
     * 
     * WMS Layer Uppercased params - WIYBY does not need this
     * Once params have been changed, we will need to re-init our tiles.
     * 
     * Parameters:
     * newParams - {Object} Hashtable of new params to use
     */
    mergeNewParams:function(newParams) {
        //removed so that new params are not uppercased
        //var upperParams = OpenLayers.Util.upperCaseObject(newParams);
        //var newArguments = [upperParams];
        OpenLayers.Layer.Grid.prototype.mergeNewParams.apply(this, 
                                                             newParams);
    },

    /** 
     * Method: getFullRequestString
     * Combine the layer's url with its params and newParams. 
     *   
     *     Add the SRS parameter from projection -- this is probably
     *     more eloquently done via a setProjection() method, but this 
     *     works for now and always.
     *
     * Parameters:
     * newParams - {Object}
     * 
     * Returns:
     * {String} 
     */
    getFullRequestString:function(newParams) {

        return OpenLayers.Layer.Grid.prototype.getFullRequestString.apply(
                                                    this, arguments);
    },
    
    isNearOriginalLocation:function(){
    	
    	var contains = false;
    	
    	//only test the location X,Y if the original location is not already an X,Y
    	var pattern = /:/i;
   		var gazetteerOrigLocation = dojo.byId('originalLocation').value;
    	if ( gazetteerOrigLocation.length > 0 && !pattern.test(gazetteerOrigLocation))
    	{
    		var originalX = dojo.byId('originalX').value;
    		var originalY = dojo.byId('originalY').value;
    		var originalPoint = new OpenLayers.Geometry.Point(originalX, originalY);

    		var mapBounds = map.getExtent();	
    	
    		contains = mapBounds.contains(originalX, originalY, true);	
    	}

    	return contains;
    },
    
    updateMapHeader:function(evt){
		
		var headerTitleElement = dojo.byId('mapheadertitle');
		var x = ((map.getExtent().right - map.getExtent().left )/2) + map.getExtent().left;
    	var y = ((map.getExtent().top - map.getExtent().bottom )/2) + map.getExtent().bottom;
		
		//WIYBY 12.1 CPH
		//Update the redraw map form if we move outside the bounds of the original location
		var isOriginalLocation = wiyby.isNearOriginalLocation();
		if (isOriginalLocation)
		{
			headerTitleElement.innerHTML = dojo.byId('originalLocation').value;
		}
		else
		{
			
			headerTitleElement.innerHTML = "X: " + formatNumberWithCommas(Math.round(x)) + ";Y: " + formatNumberWithCommas(Math.round(y));
		}
		
		
		var headerScaleElement = dojo.byId('wiybyscale');
		
		//WIYBY 13.1 GR - round of to nearest hundred to avoid values like 5002,10001 etc
		var roundedValue = roundToNearestHundred(Math.round(map.getScale())); 
		headerScaleElement.innerHTML = "1:" + formatNumberWithCommas(roundedValue);
		
    }    ,
    
    	//WIYBY 12.5 GR - bookmarking - START
    updateURL:function(evt){

		var x = ((map.getExtent().right - map.getExtent().left )/2) + map.getExtent().left;
    	var y = ((map.getExtent().top - map.getExtent().bottom )/2) + map.getExtent().bottom;
    	var scale = map.getZoom();
    	
    //   	window.alert("X IS "+x +"Y IS " + y);
    	window.location.hash="x="+Math.round(x)+"&"+"y="+Math.round(y)+"&"+"lg="+selectedLayerGroupsString+"&"+"scale="+(scale+1);
   
   	},
    	//WIYBY 12.5 GR - bookmarking - END
	
	// WIYBY 12.6 GR - Scale Dependent Visible Layers - START
    updateLegend:function()
    {
    	var currentScale = map.getZoom();
    //	alert("disabling non visible layer groups for scale "+ currentScale);
    	setLayerGroupCheckboxForScale( currentScale );
    },
	// WIYBY 12.6 GR - Scale Dependent Visible Layers - END
		
    CLASS_NAME: "WiybyMapLayer"
}


);

