// making this a global variable so that it is accessible for
// debugging/inspecting in Firebug
var map = null;
var mapLayers = [];
var manager = new OpenLayers.Control.myWMSManager();
var Projec = "EPSG:28992";
			
//Parameter values
var mapStateUse = null;
var mapZoom = null;
var lon = null;
var lat = null;
var area = null;
var submit = null;

        
var serverList =  [
			        
			        //'http://webservice.nieuwekaart.nl/cgi-bin/nkn?',
                    //'http://wms.beeldportal.nl/beeldportal/wms?',
					'http://gdsc.nlr.nl/wms/dkln2006?',			        
					//'http://gdsc.nlr.nl/wms/lufo2005?',
			        //'http://gdsc.nlr.nl/wms/aster_all?',
					'http://www.map20.org/geoserver/wms?',
                    'http://www.rijkswaterstaat.nl/services/geoservices/overzichtskaartnl?',
                    'http://www.rijkswaterstaat.nl/services/geoservices/basispakket/grenzen?'                    
                ];
var layerList =  [
			        //'Nederland_2006', //nieuwekaart
			        'dkln2006-1m', //NLR -dkln2006
		        	//'lufo2005-1m', //NLR -lufo2005
					//'aster_all',//NLR  atelyte
                    'and_netherlands_base+and_netherlands_labels+and_netherlands_road', //map20
					'NL-prov+bebouwing+vaarwegen+rijkswegen', //rws overzicht
                    //'Netherlands+Delft+Buildings+Vegetation', //local demis
                    //'Netherlands+Delft+Buildings+Vegetation', //local demis
                    'AAA207+AAA208+AAA284+AAA206', //rws grenzen
                    
                ]; 
var serverList2 = [];
var layerList2 = [];
var selectedLayerList = [];


var lat0 = null; //Rahman
var lon0 = null; //Rahman

var click= null;

var price = null; //Rahman

function init(){
    //alert(document.getElementById("HiddenField1").value);
 	fakePopulateFields();
    readServerFields(); 
       
    /***
    ** Needed to extract server's capacity
    ***/
    var proxyHost = "http://10.0.0.201/scripts/proxy.py?url=";
    var proxyPath = "";
    if (location.host.match("10.0.0.201") || location.host.match("nato1")) {var proxyPath = "/scripts/proxy.py?url=";}
    else {var proxyPath = "/cgi-bin/proxy.php?url=";}
    proxyHost = "http://"+location.host+proxyPath;  
            
    //Rahman
    hideComponent();
	//alert(navigator.appVersion);
	//alert(navigator.appName);
    if (navigator.appName == "Netscape")
    {
        if (navigator.appVersion.match("Chrome") || navigator.appVersion.match("Safari"))
		{
			document.getElementById('map').offsetHeight="488px";
			document.getElementById('map').style.height="488px";
			document.getElementById('map').clientHeight="488px";
		}
		else
		{
			document.getElementById('map').style.height="488px";
		}
    }else if (navigator.appName.match("Microsoft"))
    {
        //Do nothing
        //document.getElementById('map').style.height="488px";
        //document.getElementById('map').height="488px";
    }
    	
    //map = new OpenLayers.Map('map', {theme: "example_bestanden/style.css"});
    var pos= new OpenLayers.Pixel(24, 170);

    //var maxExt = new OpenLayers.Bounds(12000, 304000, 280000, 624000); //Xmin,Ymin,Xmax,Ymax
    var maxExt = new OpenLayers.Bounds(-4100, 287800, 297100, 628100); //Xmin,Ymin,Xmax,Ymax
    if (navigator.appVersion.match("Chrome")||navigator.appVersion.match("Safari"))
	{
		var maxRes = maxExt.getHeight()/document.getElementById("map").style.height.replace("px", "");
	} else {
		var maxRes = maxExt.getHeight()/document.getElementById("map").clientHeight;
	}
    //alert("height: "+ maxExt.getHeight() +" maxRes: "+ maxRes + " clientHeight: "+ document.getElementById("map").clientHeight);
	//alert("offH "+ document.getElementById('map').offsetHeight + " styleH " + document.getElementById('map').style.height +" clientH "+ document.getElementById('map').clientHeight );
             
    map = new OpenLayers.Map('map',
		 {
			//size: sizes, //set through style 
			units: "m",
			projection:  Projec,
			maxExtent: maxExt,
			restrictedExtent: maxExt,
			resolution: maxRes,
			maxResolution: maxRes,
            controls: [
                //new OpenLayers.Control.PanZoom({position: pos}),
                new OpenLayers.Control.PanZoomBar({zoomWorldIcon: true}),
                new OpenLayers.Control.Navigation({zoomWheelEnabled: false}),
                new OpenLayers.Control.LayerSwitcher({'ascending':true, activeColor: "#3A6EA5"}),
                //new OpenLayers.Control.ScaleLine(),
                new OpenLayers.Control.ScaleBar(),
                //new OpenLayers.Control.Permalink('permalink'),
                new OpenLayers.Control.MousePosition({/*displayProjection: dispProjec,*/ numDigits: 0}),
                new OpenLayers.Control.LoadingPanel(),
                //new OpenLayers.Control.myZoomToMaxExtent({id:'culo'}),
                new OpenLayers.Control.KeyboardDefaults()
            ],
            numZoomLevels: 8   
        }
    );

    //Local Image as overview map
    var overviewlayer = new OpenLayers.Layer.WMS("Standaard", "http://www.rijkswaterstaat.nl/services/geoservices/overzichtskaartnl?", {layers: 'NL-prov', 'format':'image/gif', 'transparent':'TRUE'}, {'ratio':1, singleTile: true, isBaseLayer: true} );
    var overviewExtent = new OpenLayers.Bounds(50000,250000,300000,600000); //when the image is online with (225-180) 
    var mapOptions = { projection: Projec, units: 'm', maxExtent: overviewExtent, restrictedExtent: maxExt};
    var overviewmap = new OpenLayers.Control.OverviewMap( {layers: [overviewlayer], size: new OpenLayers.Size(230,220), minRectSize: 1, minRatio: 1000, mapOptions: mapOptions});
    map.addControl(overviewmap);

    var waiting= new OpenLayers.Layer.Image (
                    'waiting',
                    "img/waiting_image.gif",
                    maxExt,
                    new OpenLayers.Size(document.getElementById("map").style.width
                                        ,document.getElementById("map").style.height),
                    {isBaseLayer: true, displayInLayerSwitcher:false}
    );
    
    map.addLayer(waiting);
	var extent= map.getMaxExtent().toArray();
	var centre= new OpenLayers.LonLat(extent[0]+(extent[2]-extent[0])/2,extent[1]+(extent[3]-extent[1])/2);
	map.setCenter(centre,0,false, false);
	
	if (click==null)
    {
        click = new OpenLayers.Control.myClick();
        map.addControl(click);
    }
    
    /*
    *  TO BE REMOVED, only to work locally
    */
    //fakePopulateSELECTEDserver();
        
	OpenLayers.ProxyHost = proxyHost ;
	
	if (document.getElementById("selectedServer").value == "") { //first visit
	    manager.startSearch(serverList2);
	}else{  //server index found
        init2b();
	}
}

/***
**  Called if the manager finds an available server
**  -Creates layers (from the coincidences of desired & available layers)
**  -If the list is not empty calls int3 otherwise removes the selected 
**   server from the list and calls the manager again
***/
function init2(){
	
	var isBS=true; //is Base Layer flag
	mapLayers=[];
	var description=null;
	var selectedLayerDescriptions="";
	var selectedLayerNames="";
	
	var serverIndex = "";
    serverIndex = manager.ServerIndex;

	//Layer list to be shown among the selected server offer
	selectedLayerList = layerList2[serverIndex].split('+');
	
	var layersAdded = 0;
	//for all the layers searched in the server
	for (var i=0;i<selectedLayerList.length;i++){
	    //look for matches in the server capabilities
	    for (var j=0;j<manager.aWMSLayers.length;j++){
	        if (selectedLayerList[i]==manager.aWMSLayers[j].name){
	            break;
	        }			    
	    }
	    if (j<manager.aWMSLayers.length){
	        //Description = title when existent, otherwise takes the name
		    if (manager.aWMSLayers[j].title){
	            description = manager.aWMSLayers[j].title;
	        }else{
	            description = manager.aWMSLayers[j].name;
	        } 	        
	        mapLayers[layersAdded] = new OpenLayers.Layer.WMS (
	            description,
	            manager.selectedServer,
	            {layers: selectedLayerList[i], transparent: true},
	            {isBaseLayer: false, displayInLayerSwitcher:true, visible:true, 'buffer':0}
	        );
	        if (mapLayers.length>1) {
	            selectedLayerNames+="+";
	            selectedLayerDescriptions+="+";
	        }
	        selectedLayerDescriptions+=description;
	        selectedLayerNames+=selectedLayerList[i];
	        
	        if (isBS) {isBS=false;} 
	        layersAdded++;
	        log("Layer "+selectedLayerList[i]+" has been added with name:"+ description,1);
	    }else{
	        log("Desired layer "+selectedLayerList[i]+" is not available",1);
	    }		
	}
	
	if (mapLayers.length != 0) {
	    /**
	    *   Add layers
	    **/
	    addExtentLayer(map);
	    map.addLayers(mapLayers);
	    populateSelectedFields(selectedLayerNames, selectedLayerDescriptions);
	   	//alert("serverIndex set to: "+ document.getElementById("ServerIndex").value);
	    init3();
	}
	else{
	    log ("NO DESIRED LAYERS AVAILABLE!!!",1);
	    shiftServerFields(serverIndex);
	    readServerFields();
	    manager.startSearch(serverList2);
	}
}			

/***
**  Called if the manager finds an available server
**  -Creates layers (from the coincidences of desired & available layers)
**  -If the list is not empty calls int3 otherwise removes the selected 
**   server from the list and calls the manager again
***/
function init2b(){
	
	mapLayers=[];
	var isBS = true;
	var selectedLayerNames=document.getElementById("selectedLayerNames").value;
	var selectedLayerDescriptions=document.getElementById("selectedLayerDescriptions").value;
	var selectedServer=document.getElementById("selectedServer").value;
	var names =  selectedLayerNames.split('+');
	var descriptions =  selectedLayerDescriptions.split('+');
	
	//add all selected layers (known to be available)
	for (var i=0;i<descriptions.length;i++){
       mapLayers[i] = new OpenLayers.Layer.WMS (
            descriptions[i],
	        selectedServer,
	        {transparent: true, layers: names[i]},
	        {isBaseLayer: false, displayInLayerSwitcher:true, visible:true, 'buffer':0}
	   );		
	   if (isBS) isBS = false;
	}
	
	if (mapLayers.length != 0) {
	    /**
	    *   Add layers
	    **/
	    addExtentLayer(map);
	    map.addLayers(mapLayers);
	    init3();
	}
	else{
	    alert("No layers available on a scanned server!");
	}
}

/***
**  Called if there are layer created at the end of init2
**  -Creates drawing layers & selecting controls
**  -Manages form submision options
***/
function init3()
    {   
        
    /**
    *   Server found, deactivate waiting tile
    **/                    
    var l = map.getLayersByName("waiting");
    l[0].setVisibility(false);
       
    /**
    *	Vector Layer and controler
    **/
    var ol_vectors = new OpenLayers.Layer.Vector("Drawings",{displayInLayerSwitcher:false});          
    
    var degrees = 45.0;
    var rad = degrees * Math.PI / 180;
    var desiredArea= 4*Math.pow(10,6); // Desired minimum area in square meters (4sqkm)
    var fixedRadius = Math.sqrt(desiredArea/2); // => radius needed
    var drawingControls = {
		fixedPolygon: new OpenLayers.Control.DrawFeature(ol_vectors,OpenLayers.Handler.RegularPolygon,{id: "fixedSquareControl", handlerOptions: {radius: fixedRadius, persist: true}}),
		//regularPolygon: new OpenLayers.Control.DrawFeature(ol_vectors,OpenLayers.Handler.RegularPolygon,{id: "regularPolygonControl",handlerOptions: {snapAngle: degrees}}),           
		//mySquare: new OpenLayers.Control.DrawFeature(ol_vectors,OpenLayers.Handler.mySquare,{id: "mySquare"}),    				   
		irregularPolygon: new OpenLayers.Control.DrawFeature(ol_vectors,OpenLayers.Handler.RegularPolygon,{id: "irregularPolygonControl",handlerOptions: {irregular: true, persist: true}})
    }
    
    drawingControls.irregularPolygon.handler=new OpenLayers.Handler.RegularPolygon(drawingControls.irregularPolygon, 
												{done: function(geometry){
													selectionDrawCheck(geometry, this); //this is the DrawFeature 
												}}, 
												drawingControls.irregularPolygon.handlerOptions); 
    drawingControls.fixedPolygon.handler=new OpenLayers.Handler.RegularPolygon(drawingControls.fixedPolygon, 
												{done: function(geometry){
													selectionDrawCheck(geometry, this); //this is the DrawFeature 
												}}, 
												drawingControls.fixedPolygon.handlerOptions); 
              
    //The id is not set in the constructor 
    drawingControls.fixedPolygon.id="fixedPolygon";
    drawingControls.irregularPolygon.id="irregularPolygon";
        
    //Add controlers to the map
    for (var key in drawingControls){
		map.addControl(drawingControls[key]);
    }

    /**
    *	Add Layers to the Map
    **/
	map.addLayer(ol_vectors);   

    //Read URL parameters and put it lon,lat variables            
    readParameters();

    /**
    *	Box Layer and marker
    **/
    drawingControls["irregularPolygon"].deactivate();
    if (submit=="draw")
    {
        drawingControls["irregularPolygon"].activate();
    }
    if (document.getElementById("HiddenField2").value != "") 
    {
        alert(document.getElementById("HiddenField2").value);
        if (document.getElementById("HiddenField2").value.substr(0, 5) == "FOUT:") {
            if (submit != null && document.getElementById("HiddenField1").value != "select=draw")
            //enough with one to know if it is a default map or a search
            {
                //Set map centre
                followCoordenades(5);
            }
            else {
                var extent = map.getMaxExtent().toArray();
                var res = map.getMaxResolution();
                //alert("the extent is: "+ res);
                var centre = new OpenLayers.LonLat(extent[0] + (extent[2] - extent[0]) / 2, extent[1] + (extent[3] - extent[1]) / 2);
                //alert("the center is: "+ centre.lon+ " , "+centre.lat);
                map.setCenter(centre, 0, false, false);
            }
            click.activate();
            if (document.getElementById("HiddenLon") != null)
                document.getElementById("HiddenLon").readOnly = true;
            if (document.getElementById("HiddenLat") != null)
                document.getElementById("HiddenLat").readOnly = true;
            return;
        }
    }
    if (submit=="draw")
    {
        drawingControls["irregularPolygon"].activate();
        if (document.getElementById("HiddenField1").value != "select=draw" && area!=null)
        {
            var ol_box = new OpenLayers.Layer.Boxes("Boxes",{displayInLayerSwitcher:false});
            var boxBounds = new OpenLayers.Bounds(lon, lat0, lon0, lat);
            var box = new OpenLayers.Marker.Box(boxBounds);
            box.events.register("click", box, function () {selectionAreaCheck(this, ol_box)});
            ol_box.addMarker(box);
            map.addLayer(ol_box);
            showComponent();
        }
    }

    else if (submit == "Area1" || submit == "Area2"){       
		var ol_box = new OpenLayers.Layer.Boxes("Boxes",{displayInLayerSwitcher:false});
		var boxBounds = getBoxBounds();
		//var boxBounds = new OpenLayers.Bounds(lon-2000, lat-2000, lon+2000, lat+2000);
		var box = new OpenLayers.Marker.Box(boxBounds);
		//box.events.register("click", box, selectionAreaCheck(box));
		box.events.register("click", box, function () {selectionAreaCheck(this, ol_box)});
		ol_box.addMarker(box);
		map.addLayer(ol_box);
		//alert("Click the box to accept/cancel the selection");	
        showComponent();
    }
          
    else if (submit == "Coord")
    {
		var ol_box = new OpenLayers.Layer.Boxes("Boxes",{displayInLayerSwitcher:false});
		var boxBounds = getBoxBounds();
		var box = new OpenLayers.Marker.Box(boxBounds);
		box.events.register("click", box, function () {selectionAreaCheck(this, ol_box)});
		ol_box.addMarker(box);
		map.addLayer(ol_box);
		//alert("Click the box to accept/cancel the selection");	
        showComponent();
    }
    
    if (mapStateUse=="yes")
    {
        followCoordenades(mapZoom);
        document.getElementById("saveMapStateUse").value= "no";
        
    }
	else if (submit != null && document.getElementById("HiddenField1").value != "select=draw") 
	//enough with one to know if it is a default map or a search
	{
		//Set map centre
	    followCoordenades(5);
	}
	else
	{
		var extent= map.getMaxExtent().toArray();
		var res= map.getMaxResolution();
		//alert("the extent is: "+ res);
		var centre= new OpenLayers.LonLat(extent[0]+(extent[2]-extent[0])/2,extent[1]+(extent[3]-extent[1])/2);
		//alert("the center is: "+ centre.lon+ " , "+centre.lat);
		map.setCenter(centre,0,false, false);
	}
	
	if (click==null)
    {
        click = new OpenLayers.Control.myClick();
        map.addControl(click);
    }
    click.activate();
    if (submit != "locate")
        //document.form1.HiddenField1.value = "";
    if (document.getElementById("HiddenLon") != null)
        document.getElementById("HiddenLon").readOnly = true;
    if (document.getElementById("HiddenLat") != null)
        document.getElementById("HiddenLat").readOnly = true;
        //alert("ClientHeight: "+ document.getElementById("map").clientHeight);
    if (document.getElementById("map_OpenLayers_ViewPort") != null)
    {
        var element = document.createElement("div");
        element.id = "copyright";
        if (document.getElementById("selectedServer").value.match("map20"))
        {
            element.innerHTML = "&copy; 2008 AND";
        } else if (document.getElementById("selectedServer").value.match("gdsc.nlr.nl/wms/dkln2006")) 
        {
            element.innerHTML = "&copy; 2006 Eurosense (niet-recente foto)";
        }
        else if(document.getElementById("selectedServer").value.match("rijkswaterstaat"))
        {
            element.innerHTML = "&copy; 2008 Rijkswaterstaat";
        }
        else if(document.getElementById("selectedServer").value.match("gdsc.nlr.nl/wms/lufo2005"))
        {
            element.innerHTML = "&copy; 2005 Aerodata/NLR/GDSC";
        }
		else if(document.getElementById("selectedServer").value.match("gdsc.nlr.nl/wms/aster_all"))
        {
            element.innerHTML = "&copy; 2005 ASTRA/NLR/GDSC";
        }
        element.style.zIndex = document.getElementById(map.getControlsByClass("OpenLayers.Control.MousePosition")[0].id).style.zIndex;
        document.getElementById("map_OpenLayers_ViewPort").appendChild(element);
    }
}

function addExtentLayer(map) {
    // give the features some style
    var styles = new OpenLayers.StyleMap({
        "default": {
            fillColor: "#3A6EA5", //Webpage blue
            //fillColor: "#42782F", //Green    
            fillOpacity: 1,
            strokeWidth: 0,
            strokeColor: "#000000"
        }
    });

    var vectors = new OpenLayers.Layer.Vector("DKLN 2011 Extent", {
        displayInLayerSwitcher: true,
        strategies: [new OpenLayers.Strategy.Fixed()],
        protocol: new OpenLayers.Protocol.HTTP({
            //url: "img/prov.kml",
            url: "img/DKLN2011Extent_RD.KML",
            format: new OpenLayers.Format.KML()
        }),
        // give the features some style
        styleMap: styles
    });

    map.addLayer(vectors); 
}

//Read the parameters from the URL and put them in a variable named the same
//IMPORTANT: problems with text values? it seams that name must be equal to value
function readParameters()
{
	/*var att = location.search.substring(1).split("&");
	//log(location.search.substring(1), 1);
    */
    var att = document.getElementById("HiddenField1").value.split("&");
    mapStateUse = document.getElementById("saveMapStateUse").value;
    if (mapStateUse == "yes")
    {
        lon= parseInt(document.getElementById("saveMapStateLon").value.split('.')[0].split(',')[0]);
        lat= parseInt(document.getElementById("saveMapStateLat").value.split('.')[0].split(',')[0]);
        mapZoom= parseInt(document.getElementById("saveMapStateZoom").value);
    }else 
    {
        for (a in att){
            //replaces "," or "%2C" by a dot
            var aux = att[a].replace(/(,)|(%2C)/,'.');
            //log("aux: "+aux,1);
            var pos = aux.indexOf("=");
            var value = aux.slice(pos+1);
        	
            if (aux.match("lon")){
                lon = parseInt(value);
            }else if (aux.match("lat")){
                lat = parseInt(value);
            }
        }
    }
    
    for (a in att){
        //replaces "," or "%2C" by a dot
        var aux = att[a].replace(/(,)|(%2C)/,'.');
        //log("aux: "+aux,1);
        var pos = aux.indexOf("=");
        var value = aux.slice(pos+1);
		
        if (aux.match("area")){
	        area = parseFloat(value);
        }else if (aux.match("locate")|| aux.match("select")){
	        submit = value;
	        //log("button: "+ submit,1);
        }else if (aux.match("nol")){ //Rahman
            lon0 = parseInt(value);
        }else if (aux.match("tal")){ // Rahman
            lat0 = parseInt(value);
        }else if (aux.match("price")){ // Rahman
            price = parseInt(value);
        }else{
	        //log("chungo",1);
        }
    }
}


//Given the center and area of the selection it calculate the bounds [Xmin,Ymin,Xmax,Ymax]
function getBoxBounds(){
    var bounds = null;
    if (submit == "Area1" || submit == "Area2")
    {
	    var delta = (Math.sqrt(area)/2)*1000; //transated to meters
	    //log("area: "+area+" delta: "+delta, 1);
	    bounds = new OpenLayers.Bounds(lon-delta, lat-delta, lon+delta, lat+delta);
	}
	else if(submit == "Coord") // Rahman
	{
	    bounds = new OpenLayers.Bounds(lon, lat0, lon0, lat);
	}
	return bounds;
}


//Called when a Draw Feature is "done"
function selectionDrawCheck(geometry, control)
{
	var Xmin,Ymin,Xmax,Ymax;
	var bounds = geometry.getBounds();
	//log("geometry is: "+ geometry, 0);
	//log("bounds are: "+ bounds, 1);
	//log("Map bounds are: "+ map.maxExtent, 1);
	var alertStr = "";
	//Checking bounds inside the map
	if (!checkAreaInMap(bounds))
	{
		alert("Area out of the map!!! Try again, please");
		control.handler.clear();
		return false;
	}
	
	//Calculating area and cheking area constrains
	//log("Area: "+ geometry.getArea()/Math.pow(10,6), 1);
	var areaInSqkm = geometry.getArea()/Math.pow(10,6);
	
	var maxSize = 0;
	if (location.pathname.match("foto")== null)
	    maxSize = 50;
	else
	    maxSize = 800;
	    	    
    //3D DATA
    if (areaInSqkm > maxSize) { //too big
	    alert("Geselecteerde gebied is te groot! Neem contact op met iDelft BV: info@idelft.nl");
	    control.handler.clear();
	    return false;
    }else if ((bounds.right-bounds.left<800)|| //to slender or small
				    (bounds.top-bounds.bottom<800)){ 
	    alert("Geselecteerde gebied is te smal. Minimum breedte of hoogte is 800 meter.");
	    control.handler.clear();
	    return false;		
    }/*else if (areaInSqkm < 4) { //too small area
	    alertStr="Gebied is klein: u kunt voor hetzelfde orderbedrag een gebied van 4 km2 bestellen. ";
    }*/
	
	
	var decision = confirm(alertStr+"Wilt u doorgaan met rechthoek ("+bounds.left.toFixed(0)+","+bounds.top.toFixed(0)+") en ("+
	                            bounds.right.toFixed(0)+","+bounds.bottom.toFixed(0)+")?");		
	if (decision) {
	    document.getElementById("HiddenField1").value = "lon=" + bounds.left + "&lat=" + bounds.top + "&nol=" + bounds.right + 
	                                        "&tal=" + bounds.bottom + "&area=" + geometry.getArea()/Math.pow(10,6) + "&select=draw";
	    document.form1.submit();
		return true;
	}
	else{
		control.handler.clear();
		return false;
	}

}

//Called when a box is selected in orther to accept/cancel selection
function selectionAreaCheck(box, layer)
{
	//this.setBorder("yellow");
	box.setBorder("yellow");
	if (!checkAreaInMap(box.bounds))
	{
		alert("Area out of the map!!! Try again, please");
		layer.removeMarker(box);
		return false;
	}
	return true;
}

//Checking bounds inside the map
function checkAreaInMap(bounds){		
	if ((bounds.left < map.maxExtent.left) || (bounds.bottom < map.maxExtent.bottom) ||
	   (bounds.right > map.maxExtent.right) || (bounds.top > map.maxExtent.top))
	{
		return false;
	}		
	return true;
}

//Gives the initial estimation of the information price
function calculatePrice (area) {
	var price = area*42*1.25;
	if (price < 210) {return 210;}
	else {return price;} 
}

//Controls the drawing controlers
//Activates the selected in the HTML radio element and deactivate the rest
function drawFeatureSelect(element){
	var drawControls = map.getControlsByClass("OpenLayers.Control.DrawFeature");
	for (var key in drawControls) { drawControls[key].deactivate();}
	if (element.value != "none") { 	map.getControl(element.value).activate();}
}

//Sets the center of the map on the desired coordenades
//zoom factor as a parameter
function followCoordenades(zoomFactor)
{
    if (lon0 == null || lat0 == null){//(submit != "Coord" && submit != "draw"){ 
	    if (lon!=null && lat != null )
	    {
	        var coordenades = new OpenLayers.LonLat(lon, lat);
	        map.setCenter(coordenades, zoomFactor , false, false);
	    }
	}
	else{  // Rahman 
	    var coordenades = new OpenLayers.LonLat((lon+lon0)/2, (lat+lat0)/2); 
	    map.setCenter(coordenades, zoomFactor , false, false);	 
	}
}


/**
*   No sense in this version
**/      
function log(msg, index)
{
	if (index == 0)
	{
		//document.getElementById("output").innerHTML = msg + "\n";	
	}else{
		//document.getElementById("output").innerHTML += msg + "\n";	
	}
}

//Rahman
function click_deactivate()
{
    click.deactivate();
}  

//Rahman    
function inputGetFocus(thisObj)
{
    if (thisObj.style.color != "Black"){
        thisObj.value = "";
        thisObj.style.color = "Black";   
    }
}

//Rahman
function inputLoseFocus(thisObj,str)
{
    thisObj.value = str;
    thisObj.style.color = "Silver";   
}

//Rahman
function showComponent()
{
     document.getElementById('mapInfo').style.visibility='visible'; 
     document.getElementById('final').style.visibility='visible'; 
}

//Rahman
function hideComponent()
{
    document.getElementById('mapInfo').style.visibility='hidden'; 
    document.getElementById('final').style.visibility='hidden'; 
}

//Rahman
function standardImg_click()
{
    if (document.getElementById('standaardHelp_pnl').style.visibility == true)
        document.getElementById('standaardHelp_pnl').style.visibility='hidden'; 
    else
        document.getElementById('standaardHelp_pnl').style.visibility='visible'; 
}

function fakePopulateFields(){
    for (var i=0; i<3; i++){
        var s = document.getElementById("Server"+(i+1));
        s.value = serverList[i];
        var l = document.getElementById("layers"+(i+1));
        l.value = layerList[i];           
    }       
}

function readServerFields(){
    for (var i=0; i<3; i++){
        var s = document.getElementById("Server"+(i+1));
        serverList2[i]=s.value;
        var l = document.getElementById("layers"+(i+1));
        layerList2[i] = l.value;           
    }      
}

function shiftServerFields(index){
    if (index>=0 && index<3){
        if (index < 2){
            document.getElementById("Server"+(index+1)).value = document.getElementById("Server"+(index+2)).value;
            document.getElementById("layers"+(index+1)).value = document.getElementById("layers"+(index+2)).value;
            if (index==0){ //first entry, need of a second shift
                document.getElementById("Server"+(index+2)).value = document.getElementById("Server"+(index+3)).value;
                document.getElementById("layers"+(index+2)).value = document.getElementById("layers"+(index+3)).value;
            }
        }
        //the 3rd entry must be removed
        document.getElementById("Server3").value = "";
    }else{
        alert("ServerIndex in a impossible value: "+index);
    }
}

function populateSelectedFields(selectedLayerNames, selectedLayerDescriptions){
    //set the current server in position 1
    document.getElementById("selectedServer").value= manager.selectedServer;
    document.getElementById("selectedLayerNames").value= selectedLayerNames;
    document.getElementById("selectedLayerDescriptions").value= selectedLayerDescriptions;
}

function saveMapState(){
    var ll = map.getCenter();
    document.getElementById("saveMapStateLon").value= ll.lon;
    document.getElementById("saveMapStateLat").value= ll.lat;
    document.getElementById("saveMapStateZoom").value= map.getZoom();
    document.getElementById("saveMapStateUse").value= "yes";
}

function fakePopulateSELECTEDserver()
{
    document.getElementById("selectedServer").value= serverList[0];
    document.getElementById("selectedLayerNames").value= layerList[0];
    document.getElementById("selectedLayerDescriptions").value= "0";   
}


