/* Online Geo-spatial Interface
*/

var map, layer, layer2, layer3, popup, popup1, feature;






function createRequestObject() {
    var tmpXmlHttpObject;
    if (window.XMLHttpRequest) { 
        tmpXmlHttpObject = new XMLHttpRequest();
	
    } else if (window.ActiveXObject) { 
        tmpXmlHttpObject = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return tmpXmlHttpObject;
}

var http = createRequestObject();

function makeGetRequest(request, url, param) {
    var re_quest= url + param;
    http.open(request, url + param);
    http.onreadystatechange = processResponse;
    http.send(null);
}

function processResponse() {
    if(http.readyState == 4){
        var response = http.responseText;
    }
}



function loopSelected(list)
{
  var selectedArray = new Array();
  var selObj = document.getElementById(list+'_list');
  var i;
  var count = 0;
  for (i=0; i<selObj.options.length; i++) {
    if (selObj.options[i].selected) {
      selectedArray[count] = selObj.options[i].value;
      count++;
    }
  }
 return selectedArray;
}


function toggle_live_data(show){

if (show){
  document.getElementById('horizontal_slider_holder').style.display="block";
}
 else {
  document.getElementById('amount_min').value=getFixedDate('min');
  document.getElementById('amount_max').value=getFixedDate('max');
  $j('#amount_max').css('left', -80);
  $j('#amount_max').css('left', 380);
  $j('#amount_min-minus').css('left', -10);
  $j('#amount_min-plus').css('left', 10);
  $j('#amount_max-minus').css('left', 484);
  $j('#amount_max-plus').css('left', 504);
  $j("#slider-range").slider('values', 0, 0);
  $j("#slider-range").slider('values', 1, 13);
  document.getElementById('horizontal_slider_holder').style.display="none";
 };

save_state();
}

function toggle_event_type(){


save_state();
//window.alert('tet');
//timeout = setTimeout("prepare_ajax()",'500');
}



function timed_execution(){
 var timer_value=document.getElementById('timer').value;
 var timer_timestamp=document.getElementById('timer_timestamp').value;
 if (timer_value > 0){timer_value--; } else {timer_value=document.getElementById('timer_freq').value;};
 if (timer_value==0&&document.getElementById('alerts').value=='true'){do_alarm();};
 if (timer_value==0){save_state();};
 document.getElementById('timer').value=timer_value;
// document.getElementById('timer_timestamp').value=timer_timestamp;
}





function save_state(){
/*
//get all app parameters and send them to a server
var map_status=new Array();
var extent=map.getExtent();
var extent_map=new Array();
extent_map['top']=extent['top'];
extent_map['left']=extent['left'];
extent_map['right']=extent['right'];
extent_map['bottom']=extent['bottom'];



map_status['extent']=extent_map;

// time range position
 map_status['begin']=document.getElementById('amount_min').value;
 map_status['end']=document.getElementById('amount_max').value;

if (document.getElementById('historic_data_radio').checked){map_status['live_data']=0;} else {map_status['live_data']=1;};

if (document.getElementById('non_alarm_box').checked){map_status['non_alarm']=1;} else {map_status['non_alarm']=0;};
var event_types=[];
for(i=0; i<document.getElementById('event_types').elements.length; i++){
 if (document.getElementById('event_types').elements[i].checked)
     event_types.push(document.getElementById('event_types').elements[i].value);
}

map_status['event_types']=event_types;
      var req = OpenLayers.Request.POST(
        {url: ajax_server,
	 data:OpenLayers.Util.getParameterString({content: serialize(map_status)}),
	 headers: {"Content-Type":"application/x-www-form-urlencoded; charset=utf-8"},
         callback: function (request) {
             switch (request.status) {
             case 200:
		prepare_ajax();
                 break;
             default:
             }
         }
        }
    );
*/
}


function marker_from_type(event_type){
if (event_type.toLowerCase()=='wheeled vehicles'){var file_name = 'img/events2.png';} else {var file_name = 'img/events.png';}
return file_name;
}


function clean_popups() {
//alert(map.popups.length);
     while(map.popups.length ) {
         markers.map.removePopup(map.popups[0]);
     }
  }



function put_markers(evnt){
/*
	switch (evnt['AlarmState']){
	case 'active':
		markerSize = new OpenLayers.Size(25,25);
	    	var icon = new OpenLayers.Icon('img/danger.png', markerSize);           
		break;
	case 'finished':
		markerSize = new OpenLayers.Size(20,20);
	    	var icon = new OpenLayers.Icon('img/alert.png', markerSize);           
		break;
	default:
	    markerSize = new OpenLayers.Size(10,10);
	    var icon = new OpenLayers.Icon(marker_from_type(evnt['Classification']), markerSize);           
	}
*/
	markerSize = new OpenLayers.Size(10,10);
	var icon = new OpenLayers.Icon(marker_from_type(evnt['Classification']), markerSize);           

	feature = new OpenLayers.Feature(layer, new OpenLayers.LonLat(evnt['Longitude'], evnt['Latitude']), new OpenLayers.Marker(new OpenLayers.LonLat(evnt['Longitude'], evnt['Latitude']),icon));
	marker = feature.createMarker();
	markers.addMarker(marker);

	
	marker.events.register("mouseover", marker, function(evt) {
//	window,alert('mouseover');

				if (popup != null) {
					if (!popup.visible()) {
						markers.map.removePopup(popup);
						popup.destroy();
						popup = null;
					}
				}
				if (popup == null) {
  					popup = new OpenLayers.Popup("popup", new OpenLayers.LonLat(evnt['Longitude'], evnt['Latitude']),  new OpenLayers.Size(50,50), evnt['Id'], false);
				        //popup.closeOnMove = true;
					popup.setContentHTML("<font COLOR='#003366'>" + evnt['KP'] + " - " + evnt['Classification'] + "</font>");
					popup.setBackgroundColor("#FFFFCC");
					popup.padding=0;          
					popup.setBorder("0px");
					popup.setOpacity(0.8);
                   			popup.setSize(new OpenLayers.Size(((evnt['Id'].length + evnt['Classification'].length) * 8.3),20));  //was 200,105
					markers.map.addPopup(popup);
					var px = map.getLayerPxFromLonLat(new OpenLayers.LonLat(evnt['Longitude'], evnt['Latitude']));
					if (px.x < 200){px.x=200};
					if (px.x > 800){px.x=800};
					if (px.y < 200){px.y=200};
					if (px.y > 700){px.y=800};
					popup.moveTo(px);

				} else {
					markers.map.removePopup(popup);
					popup.destroy();
					popup = null;
				}
				Event.stop(evt);

	});

	    marker.events.register("mouseout", marker, function(evt) {
				//check to see if the popup was hidden by the close box 
				//if so, then destroy it before continuing
				if (popup != null) {
						markers.map.removePopup(popup);
						popup.destroy();
						popup = null;
				}
				Event.stop(evt);
		});


	    marker.events.register("mousedown", marker, function(evt) {
//clean_popups();
			//check to see if the popup was hidden by the close box 
			//if so, then destroy it before continuing
			if (popup1 != null) {
				if (!popup1.visible()) {
					markers.map.removePopup(popup1);
					popup1.destroy();
					popup1 = null;
				}
			}
			if (popup1 == null) {
					link = "<a href=data.php?'" + evnt['Id'] + "'>&raquo; get data</a>";
				
  					popup1 = new OpenLayers.Popup("popup", new OpenLayers.LonLat(evnt['Longitude'], evnt['Latitude']),  new OpenLayers.Size(50,50), evnt['Id'], true);
				//					popup.setContentHTML("<table cellspacing=1 cellpadding=0><tr><td>Site:</td><td><b><u>" + site + "</u></b></td></tr><tr><td>Latitude:</td><td>" + lat + "</td></tr><tr><td>Longitude:&nbsp;</td><td>" + lon + "</td></tr><tr><td>&nbsp;</td><td><b>" + link + "</b></td></tr></table>");
				
// zoom to 1km radius
map.setCenter(new OpenLayers.LonLat(evnt['Longitude'], evnt['Latitude']), 10);

popup1.setContentHTML("<table cellspacing=1 cellpadding=0><tr><td><b><u>" + evnt['Classification'] + "</u></b></td></tr><tr><td>KP:"+evnt['KP']+"<br/></td></tr></table>");

popup1.setBackgroundColor("#D1E2EF");
popup1.setOpacity(0.8);
popup1.setSize(new OpenLayers.Size(170,50));  //was 200,105

				markers.map.addPopup(popup1);
				var px = map.getLayerPxFromLonLat(new OpenLayers.LonLat(evnt['Longitude'], evnt['Latitude']));
// this is wrong

				if (px.x < 200){px.x=200};
				if (px.x > 800){px.x=800};
				if (px.y < 200){px.y=200};
				if (px.y > 700){px.y=800};
				popup1.moveTo(px);

				
			} else {
				markers.map.removePopup(popup1);
				popup1.destroy();
				popup1 = null;
			}
			Event.stop(evt);
		});




}


function DHTMLSound(surl) {
document.getElementById("dummyspan").innerHTML=
"<embed src='"+surl+"' hidden=true autostart=true loop=false/>";
}

function describe_event(et, lat, lon, cont, kp){
clean_popups();
popup1 = new OpenLayers.Popup("popup", new OpenLayers.LonLat(lon, lat),  new OpenLayers.Size(50,50), et, true);
map.setCenter(new OpenLayers.LonLat(lon, lat), 10);
//popup1.setContentHTML("<table cellspacing=1 cellpadding=0><tr><td><b><u>" + et + "</u></b></td></tr><tr><td><b>" + cont + "</b><br/></td></tr></table>");
popup1.setContentHTML("<table cellspacing=1 cellpadding=0><tr><td><b><u>" + cont + "</u></b></td></tr><tr><td>KP:"+kp+"<br/></td></tr></table>");

popup1.setBackgroundColor("#D1E2EF");
popup1.setOpacity(0.8);
popup1.setSize(new OpenLayers.Size(170,50));  //was 200,105
markers.map.addPopup(popup1);
var px = map.getLayerPxFromLonLat(new OpenLayers.LonLat(lon, lat));
				if (px.x < 200){px.x=200};
				if (px.x > 800){px.x=800};
				if (px.y < 200){px.y=200};
				if (px.y > 700){px.y=800};
//				popup1.moveTo(px);

//map.setCenter(new OpenLayers.LonLat(lon, lat), 6);
}




function get_active_alerts(){
var latest="?latest=true";
      var req = OpenLayers.Request.GET(
        {url: ajax_server+latest,
         callback: function (request) {
             switch (request.status) {
             case 200:
                 var json = eval('('+request.responseText+')');
		 var completed_content_list = '';	var active_content_list='';
		 for (var j in json){
		   if (json[j]['Id']){

			put_markers(json[j]);
//window.alert("Markers");
			switch (json[j]['IsAlarm']){
			case '1':
				active_content_list=active_content_list+'<li><img src="'+marker_from_type(json[j]['Classification'])+'" width="10px" height="10px"/><img src="img/danger.png" width="15px" height="15px"><a href="javascript:describe_event('+json[j]['Id']+','+json[j]['Latitude']+','+json[j]['Longitude']+",'" + json[j]['Classification'] +"','" + json[j]['KP'] + "'"+');">'+json[j]['KP']+' : '+json[j]['Classification']+'</a></li>'+ '\n';
				break;
			default:
				completed_content_list=completed_content_list+'<li><img src="'+marker_from_type(json[j]['Classification'])+'" width="10px" height="10px"/><img src="img/events.png" width="10px" height="10px"><a href="javascript:describe_event('+json[j]['Id']+','+json[j]['Latitude']+','+json[j]['Longitude']+",'" + json[j]['Classification'] +"','" + json[j]['KP'] + "'"+');">'+json[j]['KP']+' : '+json[j]['Classification']+'</a></li>'+ '\n';
			}

		   }
		 };
		    if (active_content_list!=''){document.getElementById('permanent_active_events_content').innerHTML=active_content_list; document.getElementById('alerts').value='true';} else {document.getElementById('permanent_active_events_content').innerHTML="No events";}


                 break;
             default:
             }
         }
        }
    );
}



function restore_border(){
document.getElementById('map').style.borderStyle='solid'; 
document.getElementById('map').style.borderWidth='1px'; 
document.getElementById('map').style.borderColor='#ccc'; 
sizeme();
}


function do_alarm(){

if(document.getElementById('sound_icon').src=='http://'+window.location.hostname+'/img/sound_off_icon.gif'){
  DHTMLSound('img/sound/alarm_3.wav');
};
var border=document.getElementById('map').style.cssText;
document.getElementById('map').style.borderStyle='solid'; 
document.getElementById('map').style.borderWidth='5px'; 
document.getElementById('map').style.borderColor='red'; 
timeout = setTimeout("restore_border();",'700');
sizeme();
//window.alert(border);

}

function prepare_ajax(){
get_active_alerts();
//save_state();
var force_get='?force=true';
      var req = OpenLayers.Request.GET(
        {url: ajax_server+force_get,
         callback: function (request) {
             switch (request.status) {
             case 200:
                 var json = eval('('+request.responseText+')');
//window.alert(request.responseText);
var header_date=request.getResponseHeader("Date");
document.getElementById('timer_timestamp').value=header_date;

markers.clearMarkers();
		 var completed_content_list = '';	var finished_content_list = ''; var active_content_list='';

		 for (var j in json){
// 	window.alert(json[j]['Id']+' '+json[j]['Latitude']+''+json[j]['IsAlarm']);
		   if (json[j]['Id']){
			put_markers(json[j]);

			switch (json[j]['IsAlarm']){
			case '1':
				active_content_list=active_content_list+'<li><img src="'+marker_from_type(json[j]['Classification'])+'" width="10px" height="10px"/><img src="img/danger.png" width="15px" height="15px"><a href="javascript:describe_event('+json[j]['Id']+','+json[j]['Latitude']+','+json[j]['Longitude']+",'" + json[j]['Classification'] +"','" + json[j]['KP'] +"'"+');">'+json[j]['KP']+' : '+json[j]['Classification']+'</a></li>'+ '\n';
				break;
			case '0':
				//finished_content_list=finished_content_list+'<li><img src="'+marker_from_type(json[j]['Classification'])+'" width="10px" height="10px"/><img src="img/alert.png" width="15px" height="15px"><a href="javascript:describe_event('+json[j]['Id']+','+json[j]['Latitude']+','+json[j]['Longitude']+",'" + json[j]['Classification'] +"','" + json[j]['KP'] +"'"+');">'+json[j]['KP']+' : '+json[j]['Classification']+'</a></li>'+ '\n';
				completed_content_list=completed_content_list+'<li><img src="'+marker_from_type(json[j]['Classification'])+'" width="10px" height="10px"/><a href="javascript:describe_event('+json[j]['Id']+','+json[j]['Latitude']+','+json[j]['Longitude']+",'" + json[j]['Classification'] +"','" + json[j]['KP'] + "'"+');">'+json[j]['KP']+' : '+json[j]['Classification']+'</a></li>'+ '\n';
				break;
			default:
				completed_content_list=completed_content_list+'<li><img src="'+marker_from_type(json[j]['Classification'])+'" width="10px" height="10px"/><a href="javascript:describe_event('+json[j]['Id']+','+json[j]['Latitude']+','+json[j]['Longitude']+",'" + json[j]['Classification'] +"','" + json[j]['KP'] + "'"+');">'+json[j]['KP']+' : '+json[j]['Classification']+'</a></li>'+ '\n';
			}




/*
			if (json[j]['AlarmState']){
                        	alert_content=alert_content+json[j]['Id']+' '+json[j]['Time']+' '+json[j]['Classification'] + '\n';
				DHTMLSound('img/sound/alarm_3.wav');
			}
			else {

				alert_content_list=alert_content_list+'<li><img src="img/alert.png" width="15px" height="15px"><a href="javascript:describe_event(this);">'+json[j]['Id']+' '+json[j]['Time']+' '+json[j]['Classification']+'</a></li>'+ '\n';
				NRT_content=NRT_content+json[j]['Id']+' '+json[j]['Time']+' '+json[j]['Classification'] + '\n';
			}
*/			
		   }
		 };
/*
if (active_content_list!=''){
document.getElementById('active_events_content').innerHTML=active_content_list;
//DHTMLSound('img/sound/alarm_3.wav');
} 
else {document.getElementById('active_events_content').innerHTML='no events';};
*/
		    if (active_content_list!=''){document.getElementById('active_events_content').innerHTML=active_content_list;} else {document.getElementById('active_events_content').innerHTML='no events';};
		    //if (finished_content_list!=''){document.getElementById('finished_events_content').innerHTML=finished_content_list;} else {document.getElementById('finished_events_content').innerHTML='no events';};
		    if (completed_content_list!=''){document.getElementById('completed_events_content').innerHTML=completed_content_list;} else {document.getElementById('completed_events_content').innerHTML='no events';};;

                 break;
             default:
             }
         }
        }
    );


}



/* extract unique elements from an array */

Array.prototype.unique = function( b ) {

if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}




 var a = [], i, l = this.length;

 for( i=0; i<l; i++ ) {
//window.alert('a: '+ a + 'i ' + i + 'this ' + this[i] + 'b ' + b);
  if( a.indexOf( 
this[i], 0, b ) < 0 ) { a.push( this[i] ); } }
 return a;
};


function appendOptionLast(option, control)
{
  var elOptNew = document.createElement('option');
  elOptNew.text = option;
  elOptNew.value = option;
  var elSel = document.getElementById(control);

  try {
    elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
  }
  catch(ex) {
    elSel.add(elOptNew); // IE only
  }
}



/* perform spatial intersection between the selection layer and WFS layers
   and highlight the optuions in relevant lists with the result of the intersection */ 
function intersect (layer_name, attribute_name, partial_list){
 var features = this.selection_layer.features;
 var features_wfs = this.eval('wfs_'+layer_name).features;
 var feat1, feat2, intersects12, intersects21;
 var parts = [];
 // reset attributes
 for(var i=0; i<features.length; ++i) {
   features[i].attributes.intersectsWith = [];
 }
 for(var i=0; i<features_wfs.length; ++i) {
   features_wfs[i].attributes.intersectsWith = [];
 }
 for(var i=0; i<features.length; ++i) {
   feat1 = features[i];
   for(var j=0; j<features_wfs.length; ++j) {
      feat2 = features_wfs[j];
      intersects12 = feat1.geometry.intersects(feat2.geometry);
      if(intersects12) {
         feat1.attributes.intersectsWith.push("f" + j);
         parts.push(feat2.attributes[attribute_name]);
      }
   }
 }
 if (partial_list){
   //if the element is not in the list - add it to the list
   for (i=0; i<parts.unique().length; ++i){

     var element_exists=false;
     for (j=0; j<document.getElementById(layer_name+"_list").length; ++j){
	 if (parts.unique()[i].toString()==document.getElementById(layer_name+"_list").options[j].value.toString()){element_exists=true;}
     }
     if (!element_exists){appendOptionLast(parts.unique()[i], layer_name+'_list') }
   }
 }
   for (i=0; i<document.getElementById(layer_name+"_list").length; ++i){
       if (parts.length>0 && parts.unique().toString().indexOf(document.getElementById(layer_name+"_list").options[i].value)!=-1){
		  document.getElementById(layer_name+"_list").options[i].selected = true;} else {
	    	  document.getElementById(layer_name+"_list").options[i].selected = false;}	
   }
} 


function intersect_init(intersectable_layers){
   for (i=0; i<intersectable_layers.length; i=i+3){
	intersect (intersectable_layers[i],intersectable_layers[i+1], intersectable_layers[i+2]);
   }	
}



/* toggle map controls */

function toggle_control(input) {

 str = document.getElementById(input.id).src;

 document.getElementById(input.id).setAttribute('src', 'resources/images/'+input.id+'_on.png');
 document.getElementById('pan').setAttribute('src', 'resources/images/'+'pan_off.png');
 document.getElementById('zoom_in').setAttribute('src', 'resources/images/'+'zoom_in_off.png');
 document.getElementById('query').setAttribute('src', 'resources/images/'+'query_off.png');

// document.getElementById('area_selection').setAttribute('src', 'img/'+'area_selection_off.png');
// document.getElementById('delete_area').setAttribute('src', 'img/'+'delete_area_off.png');

 if (str.match('resources/images/'+input.id+'_off.png')){document.getElementById(input.id).setAttribute('src', 'resources/images/'+input.id+'_on.png');};
 switch (input.id) {
    case 'area_selection':
        toggleControls('area_select');
        toggleControls('draw_poly');
        break;
    case 'delete_area':
        toggleControls('delete_area');
        break;
    case 'zoom_in':
        toggleControls('zoom_in');
        break;
    case 'query':
        toggleControls('query_window');
        break;
    case 'pan':
        toggleControls('nav');
        break;
    default:
        toggleControls('nav');
 }
}






//GeoData Generic OGI Library snippets 

var OGI = {};
OGI.Layer = {};
OGI.Control = {};
/* Override OpenLayers.Control.SelectFeature to ensure checkModifiers
   in it's handler is honoured when a feature is clicked. */

var OGI = {};
OGI.Layer = {};

// A layer class that manages the WMS and all its layers and groups
OGI.Layer.WMSGroup = OpenLayers.Class(OpenLayers.Layer.WMS, {
        
    initialize: function(name, url, groups, params, options) {
            this.groups = groups;
            params['layers'] = this.layers();
            var newArguments = [];
            newArguments.push(name, url, params, options);
            OpenLayers.Layer.WMS.prototype.initialize.apply(this, newArguments);
        },

    toggleGroup: function(name, state) 
    {
        this.groups[name]['status'] = state;
    },

    turnGroupOn: function(name) 
    {
        this.toggleGroup(name, true);
    },   

    turnGroupOff: function(name) 
    {
        this.toggleGroup(name, false);
    },   

    /* Return a list of layers that are currently turned on */
    layers: function() 
    {
        var groups = [];
        for (var name in this.groups) {
            var group = this.groups[name];
            if (!group['status']) {
                groups[group['index']] = [];
            } else {
                groups[group['index']] = group['layers'];
            }                                   
        }

        var layers = [];
        for (var i=0; i < groups.length; i++) {
            for (var j=0; j < groups[i].length; j++) {
                layers.push(groups[i][j])
            }
        }

        return layers;
    },
    
    mergeLayers: function() 
    {
        this.mergeNewParams({'LAYERS': this.layers().join(',')});
	this.params.layers = this.layers().join(',');
	this.redraw();
    },
    showBubble: function(response)

{
 	 var popup = new OpenLayers.Popup.AnchoredBubble("chicken", 
                                     this.map.getExtent().getCenterLonLat(),
                                     null,
                                     "<div style='font-size:.8em'>"+response+"</div>",
                                     null, true, null);
	 popup.setBackgroundColor("#CEE6F2");
            this.map.addPopup(popup);

},
    queryPoint: function(x, y, callback) 
    {
        // a list of queryable layers. This shouldnt be hard coded but retrieved from the server
        var queryable_layers = {'grab2005_locations': true,
				'grab2005_sand': true,
				'grab2005_gravel': true,
				'grab2005_fines': true,
				'licence_areas': true};
                                
        var query_layers = [];
        var layers = this.layers();
        for (var i=0; i < layers.length; i++ ) {
            var layer = layers[i];
            if (queryable_layers[layer]) {
                query_layers.push(layer);
            }                    
        }

        if (!query_layers.length) {
            return false;
        }
                
        var url =  this.getFullRequestString({
            REQUEST: "GetFeatureInfo",
            EXCEPTIONS: "application/vnd.ogc.se_xml",
            BBOX: this.map.getExtent().toBBOX(),
            X: x,
            Y: y,
            INFO_FORMAT: 'text/html',
            QUERY_LAYERS: query_layers.join(','),
            FEATURE_COUNT: 20,
            WIDTH: this.map.size.w,
            HEIGHT: this.map.size.h});
        OpenLayers.loadURL(url, '', this, callback, function(response) {
                alert('The point could not be queried');
            });

        return true;
    },

    /**
     * Method: destroy
     * Destroy this layer
     */
    destroy: function() {
            // for now, nothing special to do here. 
            OpenLayers.Layer.WMS.prototype.destroy.apply(this, arguments);  
        },
    
    /**
     * Method: clone
     * Create a clone of this layer
     *
     * Returns:
     * {<OGI.Layer.WMSGroup>} An exact clone of this layer
     */
    clone: function (obj) {
        
            if (obj == null) {
                obj = new OGI.Layer.WMSGroup(this.name,
                                             this.url,
                                             this.groups,
                                             this.params,
                                             this.options);
            }

            //get all additions from superclasses
            obj = OpenLayers.Layer.WMS.prototype.clone.apply(this, [obj]);

            // copy/set any non-init, non-simple values here

            return obj;
        },        

    CLASS_NAME: "OGI.Layer.WMSGroup"
    });





OGI.Layer.AreaSelection = OpenLayers.Class(OpenLayers.Layer.Vector, {

    initialize: function(name, uri, options) {
            var newArguments = [];
            newArguments.push(name, options);
            this.uri = uri;
            this.wkt = new OpenLayers.Format.WKT();
            OpenLayers.Layer.Vector.prototype.initialize.apply(this, newArguments);
//            this.loadAreas();
        },

    loadAreas: function() {
            var layer = this;
            makeGetRequest('GET',layer.uri,'');
            new OpenLayers.Ajax.Request(layer.uri, {method: 'get',
                        requestHeaders: ['Accept', 'text/plain'],
                        onSuccess: function (request) {
                        var features = [], feature;
                        var areas = request.responseText.split("\n");
                        for (var i=0; i<(areas.length-1); ++i) {
                            var wkt_in = areas[i].split(':');
                            feature = layer.wkt.read(wkt_in[1]);

                            if (feature) {
                                feature.fid = wkt_in[0];
                                features.push(feature);
                            } else {
                                alert('Bad WKT: ' + wkt_in[1]);
                            }
                        }
                        layer.addFeatures(features);
                    },
                        onFailure: function (request) {
                        alert('Sorry - there is a problem creating your area selections');
                    }
            });
        },

    deleteSelection: function() {
            var del_fids = [];
            var features = this.selectedFeatures;
            for (var i=0; i < features.length; i++) {
                del_fids.push(features[i].fid);
            }

            if (!del_fids.length) {
                return;
            }
                        
            var body = del_fids.join(',');
            var layer = this;

            new OpenLayers.Ajax.Request(layer.uri, {method: 'delete',
                        postBody: body,                               
                        parameters: {},
                        onSuccess: function() {
                        layer.removeFeatures(features);
                    },
                        onFailure: function() {
//                        layer.removeFeatures(features);
//perform Ajax request
if(body){		    makeGetRequest('DELETE',layer.uri,'/'+body);
                    layer.removeFeatures(features);}

                        //alert('Sorry - there is a problem removing your selection');
                    }}
                ); 

        },

    addFeatures: function(features, options) {

	    var helpSlider = document.getElementById('layersDiv');        
	    var layer = this;
            var fid_features = [];
            var non_fid_features = [];
            var new_arguments = [];

            for (var i=0; i < features.length; i++) {
                var feature = features[i];
                if (feature.fid) {
                    fid_features.push(feature);
                } else {
                    non_fid_features.push(feature);
                }       
            }
            if (non_fid_features.length) {
                // can only process one feature at the moment; this should be changed
                var feature = non_fid_features[0];
//var polygonFeature = new OpenLayers.Feature.Vector(linearRing, null, null);
//window.alert(feature.geometry);
/*
var coord_count=document.getElementById('coords');
coord_count.value=coord_count.value+'\n'+feature.geometry;
*/
                new_arguments.push(non_fid_features, options);
               OpenLayers.Layer.Vector.prototype.addFeatures.apply(layer, new_arguments);
intersect_init(intersectable_layers);
/*                new OpenLayers.Ajax.Request(layer.uri, {method: 'post',
                            postBody: layer.wkt.write(feature),
                            onSuccess: function(transport) {
                            feature.fid = transport.responseText;
                            new_arguments.push([feature], options);
                            OpenLayers.Layer.Vector.prototype.addFeatures.apply(layer, new_arguments);
                        },
                            onFailure: function() {
                            alert('Sorry - there is a problem adding the area');
                        }}
                    );
*/


            } else {
                new_arguments.push(fid_features, options);
		//window.alert(fid_features);
                OpenLayers.Layer.Vector.prototype.addFeatures.apply(this, new_arguments);
            }       
        },
        
    /**
     * Method: destroy
     * Destroy this layer
     */
    destroy: function() {
            // for now, nothing special to do here. 
//            OpenLayers.Layer.Vector.prototype.destroy.apply(this, arguments);  
        },

    
    /**
     * Method: clone
     * Create a clone of this layer
     *
     * Returns:
     * {<OGI.Layer.AreaSelection>} An exact clone of this layer
     */
    clone: function (obj) {
        
            if (obj == null) {
                obj = new OGI.Layer.AreaSelection(this.name,
                                                  this.uri,
                                                  this.options);
            }

            //get all additions from superclasses
            obj = OpenLayers.Layer.Vector.prototype.clone.apply(this, [obj]);

            // copy/set any non-init, non-simple values here

            return obj;
        },        

    CLASS_NAME: "OGI.Layer.AreaSelection"
    });

OGI.Handler = {};
/* Override OpenLayers.Handler.Polygon to prevent drawing when the
   shift key has been pressed */
//replaced Handler.Polygon with Handler.Box
OGI.Handler.PolygonSelect = OpenLayers.Class(OpenLayers.Handler.Polygon, {

    initialize: function(control, callbacks, options) {

            OpenLayers.Handler.Polygon.prototype.initialize.apply(this, arguments);
        },

  
    mousedown: function(evt)     {


        if (!this.drawing && evt['shiftKey']) {
window.alert ("Shift active");
            return true;
        }
        OpenLayers.Handler.Polygon.prototype.mousedown.apply(this, [evt]);
        return false;
    },
    
    CLASS_NAME: "OGI.Handler.PolygonSelect"
    });


OGI.Control = {};
OGI.Control.QueryWindow = 
  OpenLayers.Class(OpenLayers.Control, {

    activeColor: "darkblue",
    layerStates: null,
    layersDiv: null,
    baseLayersDiv: null,
    baseLayers: null,
    dataLbl: null,
    dataLayersDiv: null,
    dataLayers: null,
    minimizeDiv: null,
    maximizeDiv: null,
    ascending: true,
    initialize: function(options) {
        OpenLayers.Control.prototype.initialize.apply(this, arguments);
        this.layerStates = [];
    },

    /**
     * APIMethod: destroy 
     */    
    destroy: function() {
        
        OpenLayers.Event.stopObservingElement(this.div);

        OpenLayers.Event.stopObservingElement(this.minimizeDiv);
        OpenLayers.Event.stopObservingElement(this.maximizeDiv);
        OpenLayers.Control.prototype.destroy.apply(this, arguments);
    },

    draw: function() {
        OpenLayers.Control.prototype.draw.apply(this);

        // create layout divs
        this.loadContents();

        // set mode to minimize
        if(!this.outsideViewport) {
            this.hideControl();
        }

        // populate div with current info

        return this.div;
    },


    maximizeControl: function(e) {

        //HACK HACK HACK - find a way to auto-size this layerswitcher
	this.div.style.display = "block";
        this.div.style.width = "25em";      //box width
        this.div.style.height = "";

        this.showControls(false);

        if (e != null) {
            OpenLayers.Event.stop(e);                                            
        }
    },
    
    minimizeControl: function(e) {
	this.div.style.display = "block";
        this.div.style.width = "0px";
        this.div.style.height = "0px";

        this.showControls(true);

        if (e != null) {
            OpenLayers.Event.stop(e);                                            
        }
    },

    hideControl: function(e) {

	this.div.style.display = "none";

        this.showControls(true);

        if (e != null) {
            OpenLayers.Event.stop(e);                                            
        }
    },


    /**
     * Method: showControls
     * Hide/Show all LayerSwitcher controls depending on whether we are
     *     minimized or not
     * 
     * Parameters:
     * minimize - {Boolean}
     */
    showControls: function(minimize) {

        this.maximizeDiv.style.display = minimize ? "" : "none";
        this.minimizeDiv.style.display = minimize ? "none" : "";

        this.layersDiv.style.display = minimize ? "none" : "";
    },
    
    /** 
     * Method: loadContents
     * Set up the labels and divs for the control
     */
    loadContents: function() {

        //configure main div
        this.div.style.position = "absolute";
        this.div.style.top = "250px";
        this.div.style.right = "0px";
        this.div.style.left = "";
        this.div.style.fontFamily = "sans-serif";
        this.div.style.fontWeight = "bold";
        this.div.style.marginTop = "3px";
        this.div.style.marginLeft = "3px";
        this.div.style.marginRight = "5px";
        this.div.style.paddingRight = "5px";
        this.div.style.marginBottom = "3px";
        this.div.style.fontSize = "smaller";   
        this.div.style.color = "white";   
        this.div.style.backgroundColor = "transparent";
    

        // layers list div        
        this.layersDiv = document.createElement("div");
        this.layersDiv.id = "queryDiv";
        this.layersDiv.style.paddingTop = "5px";
        this.layersDiv.style.paddingLeft = "10px";
        this.layersDiv.style.paddingBottom = "5px";
        this.layersDiv.style.paddingRight = "3px";
        this.layersDiv.style.backgroundColor = this.activeColor;
	this.layersDiv.style.fontSize="12px";
	this.layersDiv.style.textAlign="center";
        this.layersDiv.innerHTML="Query results<br/>";

        // had to set width/height to get transparency in IE to work.
        // thanks -- http://jszen.blogspot.com/2005/04/ie6-opacity-filter-caveat.html
        //
        this.layersDiv.style.width = "100%";
        this.layersDiv.style.height = "100%";


        this.baseLbl = document.createElement("div");
        this.baseLbl.id = "queryDivcontent";
        this.baseLbl.style.marginTop = "3px";
        this.baseLbl.style.marginLeft = "10px";
        this.baseLbl.style.marginRight = "10px";
        this.baseLbl.style.marginBottom = "3px";
	this.baseLbl.style.textAlign="left";
	this.baseLbl.style.fontSize="10px";
	this.baseLbl.innerHTML="";

        
        this.baseLayersDiv = document.createElement("div");
        this.baseLayersDiv.style.paddingLeft = "10px";
                     

        this.dataLbl = document.createElement("div");
        this.dataLbl.style.marginTop = "3px";
        this.dataLbl.style.marginLeft = "3px";
        this.dataLbl.style.marginRight = "3px";
        this.dataLbl.style.marginBottom = "3px";
        
        this.dataLayersDiv = document.createElement("div");
        this.dataLayersDiv.style.paddingLeft = "10px";
        this.dataLayersDiv.style.paddingRight = "3px";

        if (this.ascending) {
            this.layersDiv.appendChild(this.baseLbl);
            this.layersDiv.appendChild(this.baseLayersDiv);
            this.layersDiv.appendChild(this.dataLbl);
            this.layersDiv.appendChild(this.dataLayersDiv);
        } else {
            this.layersDiv.appendChild(this.dataLbl);
            this.layersDiv.appendChild(this.dataLayersDiv);
            this.layersDiv.appendChild(this.baseLbl);
            this.layersDiv.appendChild(this.baseLayersDiv);
        }    
 
        this.div.appendChild(this.layersDiv);

        OpenLayers.Rico.Corner.round(this.div, {corners: "tl bl",
                                        bgColor: "transparent",
                                        color: this.activeColor,
                                        blend: false});

        OpenLayers.Rico.Corner.changeOpacity(this.layersDiv, 0.65);

        var imgLocation = OpenLayers.Util.getImagesLocation();
        var sz = new OpenLayers.Size(18,18);        

        // maximize button div
        var img = imgLocation + 'layer-switcher-maximize.png';
        this.maximizeDiv = OpenLayers.Util.createAlphaImageDiv(
                                    "OpenLayers_Control_MaximizeDiv", 
                                    null, 
                                    sz, 
                                    img, 
                                    "absolute");
        this.maximizeDiv.style.top = "5px";
        this.maximizeDiv.style.right = "0px";
        this.maximizeDiv.style.left = "";
        this.maximizeDiv.style.display = "none";
        OpenLayers.Event.observe(this.maximizeDiv, "click", 
            OpenLayers.Function.bindAsEventListener(this.maximizeControl, this)
        );
        
        this.div.appendChild(this.maximizeDiv);

        // minimize button div
        var img = imgLocation + 'layer-switcher-minimize.png';
        var sz = new OpenLayers.Size(18,18);        
        this.minimizeDiv = OpenLayers.Util.createAlphaImageDiv(
                                    "OpenLayers_Control_MinimizeDiv", 
                                    null, 
                                    sz, 
                                    img, 
                                    "absolute");
        this.minimizeDiv.style.top = "5px";
        this.minimizeDiv.style.right = "0px";
        this.minimizeDiv.style.left = "";
        this.minimizeDiv.style.display = "none";
        OpenLayers.Event.observe(this.minimizeDiv, "click", 
            OpenLayers.Function.bindAsEventListener(this.minimizeControl, this)
        );

        this.div.appendChild(this.minimizeDiv);
    },
    
    /** 
     * Method: ignoreEvent
     * 
     * Parameters:
     * evt - {Event} 
     */
    ignoreEvent: function(evt) {
        OpenLayers.Event.stop(evt);
    },

    /** 
     * Method: mouseDown
     * Register a local 'mouseDown' flag so that we'll know whether or not
     *     to ignore a mouseUp event
     * 
     * Parameters:
     * evt - {Event}
     */
    mouseDown: function(evt) {
        this.isMouseDown = true;
        this.ignoreEvent(evt);
    },

    /** 
     * Method: mouseUp
     * If the 'isMouseDown' flag has been set, that means that the drag was 
     *     started from within the LayerSwitcher control, and thus we can 
     *     ignore the mouseup. Otherwise, let the Event continue.
     *  
     * Parameters:
     * evt - {Event} 
     */
    mouseUp: function(evt) {
        if (this.isMouseDown) {
            this.isMouseDown = false;
            this.ignoreEvent(evt);
        }
    },

    CLASS_NAME: "OGI.Control.QueryWindow"
});


function query_results(e){

            var url =  wms1.getFullRequestString({
                            REQUEST: "GetFeatureInfo",
                            EXCEPTIONS: "application/vnd.ogc.se_xml",
                            BBOX: wms1.map.getExtent().toBBOX(),
                            X: e.xy.x,
                            Y: e.xy.y,
                            INFO_FORMAT: 'text/html',
                            QUERY_LAYERS: wms1.params.LAYERS,
                            REDIUS:2,
                            WIDTH: wms1.map.size.w,
                            HEIGHT: wms1.map.size.h});
            OpenLayers.loadURL(url, '', this, setHTML);

}




function toggleControls(state){
 for (var key in this.area_controls) {
                var control = this.area_controls[key];
		control.deactivate();
}

var control = this.area_controls[state];
control.activate();

if (state=='query_window'){

//map.events.register('click', map, query_results);
//map.events.unregister('click', map, query_results);
    map.events.register('click', map, function (e) {
            var url =  wms1.getFullRequestString({
                            REQUEST: "GetFeatureInfo",
                            EXCEPTIONS: "application/vnd.ogc.se_xml",
                            BBOX: wms1.map.getExtent().toBBOX(),
                            X: e.xy.x,
                            Y: e.xy.y,
                            INFO_FORMAT: 'text/html',
                            QUERY_LAYERS: get_all_visible_layers('query').join(','),
                            REDIUS:2,
                            WIDTH: wms1.map.size.w,
                            HEIGHT: wms1.map.size.h});

            OpenLayers.loadURL(url, '', this, setHTML);

            Event.stop(e);
});

}

if (state=='draw_poly'){var control2 = this.area_controls['area_select']; control2.activate();}
}
