


/*

  Extension for OpenLayers Map Viewer Library for http://www.pegelonline.wsv.de

  Copyright (c) 2008 EES GmbH

*/

var	STATE_CLOSE = false;
var STATE_OPEN = true;
var CONTROL_CLOSE = false;
var CONTROL_EXPAND = true;

var VISIBILITY_VISIBLE = true;
var VISIBILITY_HIDDEN = false;

var ZOOM_LEVEL = 4;

var ICON_MIN_DIAMETER = 7;
var ICON_MAX_DIAMETER = 52;

var URL_GANGLINIE = "/webservices/zeitreihe/visualisierung?ansicht=einzeln&";
var URL_STAMMDATEN = "../stammdaten?"; //host, port, context-name wird so automatisch gesetzt
var URL_ARCHIV_DETAILS = "/archiv/pegelZeitreihenFrameset?";

var TITLE_ZOOM = "Mit gedrückter linker Maustaste einen Zoombereich aufziehen";
var TITLE_PAN = "Mit gedrückter linker Maustaste die Karte verschieben";

var INPUT_PEGEL_DEFAULT = "Nach Eingabe filtern";

var TAB_WIDTH = 94;
var TAB_SPACE = 4;

var BEGIN_DATE = true;
var END_DATE = false;

var PARAMETER_ZEITEBENE_SEPERATOR = "##";


/**
 * Class: PegelItems
 * holds many <Pegelitem> in one Object
 */
PegelItems = OpenLayers.Class({ 

	/**
   	 * Property: pegel
     * {Object of <Pegelitem>, indexed by pegelnummer}
     */
  	pegel: null,
  	
  	/**
	 * Property: length
     * {int}
     */
  	length: 0,
  
    
    initialize: function() {
        this.pegel = new Object();
        this.id = OpenLayers.Util.createUniqueID(this.CLASS_NAME + "_"); 
    },
    
    add: function(pegelItem) {
		if (!this.pegel[pegelItem.getPegelnummer()]) {
			this.pegel[pegelItem.getPegelnummer()] = pegelItem;
			this.length++;
		}
        
    },
    
    getElement: function(pegelNr) {
    	return this.pegel[pegelNr];
    },

	inflateIcons: function(mapObject){
		if(this.pegel){
			for (var pegelNummer in this.pegel){
    			this.pegel[pegelNummer].inflateIcon(mapObject.object.getZoom());
	    	}
		}
	},
	
	applyFilter: function(archiveFilterArray, startTime, endTime){
		if(this.pegel){
			for (var pegelNummer in this.pegel){
				this.pegel[pegelNummer].setVisibility(this.pegel[pegelNummer].match(archiveFilterArray, startTime, endTime));
	    	}
		}
	},
	
    CLASS_NAME: "PegelItems"
});

/**
 * Class: PegelItem
 * little bit tuned <OpenLayers.Feature> with some extra attributes and methods
 */
PegelItem = OpenLayers.Class({

	/**
	 * Property: expandedStateBar
     * {int} STATE_CLOSE | STATE_OPEN
     */
	expandedStateBar: null,
	
	/**
	 * Property: expandedStateBar
     * {int} STATE_CLOSE | STATE_OPEN
     */
	expandedStatePopup: null,
	
	/**
   	 * Property: olFeature
     * {<OpenLayers.Feature>}
     */
  	feature: null,
  	
  	iconUrl: null,
  	
	/**
	 * Property: visibility
	 * {boolean} VISIBILITY_VISIBLE | VISIBILITY_HIDDEN
	 */
	visibility: null,
  
    
    initialize: function(feature) {
        this.feature = feature;
        this.expandedStateBar = STATE_CLOSE;
        this.expandedStatePopup = STATE_CLOSE;
        this.visibility = VISIBILITY_VISIBLE;
        this.id = OpenLayers.Util.createUniqueID(this.CLASS_NAME + "_"); 
    },
    
    getPegelnummer: function() {
    	return this.feature.data['pegelNummer'];
    },
    
    getGewaesser: function() {
    	return this.feature.data['gewaesser'];
    },
    
    getGewaesserUnescaped: function() {
    	return this.feature.data['gewaesserUnescaped'];
    },
    
    getInfoHTML: function() {
    	return this.feature.data['selectionHtml'];
    },
    
    getIconUrl: function() {
    	return this.feature.marker.icon.url;
    },
    
    setIconUrl: function(url) {
    	var img = $(this.getFilenameFromUrl(url));
    	if(img.style.width != null && img.style.height != null){
    		this.feature.marker.icon.offset = new OpenLayers.Pixel(-parseInt(img.style.width)/2, -parseInt(img.style.height)/2);
    		this.feature.marker.icon.size = new OpenLayers.Size(parseInt(img.style.width), parseInt(img.style.height));
    		
    	}
    	this.feature.marker.setUrl(url);
    },
    
    /** 
     * Method: inflateIcon
     * to display bigger dots in high zoom level, we need two images for the dots
     * the method sets the icon url, depending on the zoom level
     */
    inflateIcon: function(zoomLevel){
    	if (this.feature.marker.icon) {
            var search = "small";
            var replace = "big";
            if(zoomLevel < 3){
            	search = "big";
            	replace = "small";
            } 
            this.setIconUrl(this.getIconUrl().replace(search, replace));
        }  
    },
    
    setVisibility: function(visibility) {
        this.visibility = visibility;
        this.feature.marker.icon.display(visibility); 
    },
    
    isVisible: function() {
        return this.visibility;
    },
    
    getName: function() {
    	return this.feature.data['name'];
    },
    
    getNameUnescaped: function() {
    	return this.feature.data['nameUnescaped'];
    },
    
    toggleExpandState: function() {
    	this.expandedStateBar = !this.expandedStateBar;
    	return this.expandedStateBar;
    },
    
    setExpandState: function(state) {
    	var changed = (this.expandedStateBar != state);
    	this.expandedStateBar = state;
    	return changed;
    },
    
    zoomTo: function() {
    	var zoom = map.getZoom() < ZOOM_LEVEL ?  ZOOM_LEVEL : map.getZoom();
    	map.setCenter(this.feature.lonlat, zoom);
    },
    
    getFilenameFromUrl: function(url){
    	var str = url.split("/");
    	return str[(str.length-1)].substring(0, str[(str.length-1)].lastIndexOf("."));
    },
    //W##1=1036108800000#1067817599000,W##2=1036108800000#1067731199000
    match: function(archiveFilterArray, startTime, endTime){
    	if(!archiveFilterArray)
    		return false;
    	for(var i=0; i<archiveFilterArray.length; i++) {
    		if(this.feature.data['archiveData'].indexOf(archiveFilterArray[i]) != -1 && 
    			this.isInDateRange(archiveFilterArray[i], startTime, endTime))
    			return true;
    	}
    	return false;
    },
    
    /**
     * Method: isInDateRange
     * 
     * Parameters:
 	 * messgroesse - {String} e.g. W.1 Q.2
 	 * startTime, endTime - {long} start/endtime of filter in milli
     */
    isInDateRange: function(messgroesse, startTime, endTime){
		var datum = this.feature.data['archiveData'].match(new RegExp(messgroesse + "=([-]?\\d*)#([-]?\\d*)"));
		if(datum && startTime && endTime){
			return !((startTime < parseInt(datum[1]) && endTime < parseInt(datum[1])) || (startTime > parseInt(datum[2]) && endTime > parseInt(datum[2])));
		}
		return true;
    },
    
    getMinMaxDatum: function(archiveFilterArray){
    	var datumArray = new Object();
    	var minDatum = -1;
    	var maxDatum = -1;
    	for(var i=0; i<archiveFilterArray.length; i++) {
    		if(this.feature.data['archiveData'].indexOf(archiveFilterArray[i]) != -1){
    			var datum = this.feature.data['archiveData'].match(new RegExp(archiveFilterArray[i] + "=([-]?\\d*)#([-]?\\d*)"));
    			if(datum){
					if(parseInt(datum[1]) < minDatum || minDatum == -1){
						minDatum = parseInt(datum[1]);
					}
					if(parseInt(datum[2]) > maxDatum || maxDatum == -1){
						maxDatum = parseInt(datum[2]);
					}
				}
    		}
    	}
    	return new Datum(minDatum, maxDatum);
    },
    
    getArchiveData: function(){
    	return this.feature.data['archiveData'];
    },

    /** 
     * Method: destroy
     * nullify references to prevent circular references and memory leaks
     */
    destroy: function() {

    },
    
    getArchivURL: function(){
		var url = URL_ARCHIV_DETAILS + "messstellen=" + this.getPegelnummer() + "&";
    	return url + gewaesserPegelItems.generateFilterURL();
    	
    },

    CLASS_NAME: "PegelItem"
});

/**
 * Class: PegelSelectionBar
 * handles all the stuff of selecting/deselecting a gauge and putting it in the selection 
 */
PegelSelectionBar = OpenLayers.Class({
	
	/**
	 * Property: selectionArray
	 * {Array} mit Pegelnummern
	 */
	selectionArray: null,
	length: 0,
	
	infoDiv: null,

    initialize: function() {
    	this.selectionArray = new Object();
        this.id = OpenLayers.Util.createUniqueID(this.CLASS_NAME + "_"); 
    },
    
    /** 
     * Method: addItem
     * adds a gauge to the selection if there are not more than 6 
     */
    addItem: function(pegelNr) {
    	if(this.length < 6){
    		this.selectionArray[pegelNr] = pegelItems.getElement(pegelNr);
    		this.length++;
    		this.addTabDiv(pegelNr);
    		return true;
    	}
    	return false;
    },
    
    /** 
     * Method: addTabDiv 
     * adds a tab to the pegelAuswahl-div with the name of the gauge 
     * and the controls close and expand
     */
    addTabDiv: function(pegelNr) {
    	var selectionDiv = OpenLayers.Util.createDiv("selectionDiv_" + pegelNr, null, 
    												null, 
                                                    null, "relative", null,
                                                    null);
   		$('pegelAuswahl').appendChild(selectionDiv);
   		selectionDiv.innerHTML = this.selectionArray[pegelNr].getName();
   		selectionDiv.className = "pegelSelection";
   		selectionDiv.style.width = TAB_WIDTH + "px";
   		if(this.length == 1){
   			selectionDiv.style.marginLeft = TAB_SPACE - 1 + "px";
   		} else {
   			selectionDiv.style.marginLeft = TAB_SPACE + "px";
   		}
   		selectionDiv.appendChild(this.createControlDiv(pegelNr, CONTROL_CLOSE));
   		selectionDiv.appendChild(this.createControlDiv(pegelNr, CONTROL_EXPAND));
    },
    
    /** 
     * Method: removeItem
     * deletes the gauge from the selection and removes the tabDiv 
     */
    removeItem: function(pegelNr) {
    	delete this.selectionArray[pegelNr];
    	this.length--;
    	this.closeInfoDiv(pegelNr);
    	this.removeDiv(pegelNr);
    },
    
    removeDiv: function(pegelNr) {
    	if($('selectionDiv_' + pegelNr)){
   			$('pegelAuswahl').removeChild($('selectionDiv_' + pegelNr));
    	}
    },
    
    /** 
     * Method: createControlDiv
     * creates a div either with the close or with the expand graphic
     * adds an eventlistener
     */
    createControlDiv: function(pegelNr, control){
    	var size = new OpenLayers.Size(10,10);
        var img = (control == CONTROL_CLOSE) ? "../../img/map/openlayers/close.png" : "../../img/map/openlayers/expand_open.gif";
        var suffix = (control == CONTROL_CLOSE) ? "close" : "expand";
		/* OpenLayers.Util.createAlphaImageDiv doesn't work in this case (problem with ie6)*/
        var controlImg =  OpenLayers.Util.createDiv("selectionDiv_" + pegelNr + "_" + suffix, null, 
    												null, 
                                                    size, "absolute", null,
                                                    null);
        controlImg.appendChild(this.createImgNode("selectionDiv_" + pegelNr + "_" + suffix+ "_innerImage", img));
        controlImg.style.right = "1px";
		controlImg.style.cursor = "pointer";
		

        controlImg.events = new OpenLayers.Events(pegelNr, controlImg);
        if(control == CONTROL_CLOSE){
	        controlImg.events.register('mousedown', pegelSelection, pegelSelection.changeItem);
	        controlImg.style.top = "1px";
        } else {
        	controlImg.events.register('mousedown', pegelSelection, pegelSelection.expandItem);
	        controlImg.style.bottom = "-1px";
        }
        
        return controlImg;
    },
    
    createImgNode: function (id, src){
    	var img = new Image();
    	img.id = id;
    	img.src = src;
    	return img;
    },
    
    /** 
     * Method: changeItem
     */
    changeItem: function(evt) {
    	var pegelNr = evt.object;
    	OpenLayers.Event.stop(evt);
    	/* remove item from selection */
    	if(this.isInSelection(pegelNr)){
    		this.removeItem(pegelNr);
    		this.toggleMarkerIcon(pegelNr, true);
    	/* max. amount of items reached */
    	} else if (!this.addItem(pegelNr)){
    		this.openAlertPopup();  
    		return;
    	/* add item to selection */
    	} else {
    		this.toggleMarkerIcon(pegelNr, false);	
    	}
		this.toggleControlLinks();
		
    },
    
    /** 
     * Method: openAlertPopup
     * opens popup with message, that only 6 gauges can be selected 
     */
    openAlertPopup: function (){
    		var size = new OpenLayers.Size(280, 100);
    		var sizeMap = new OpenLayers.Size($('openLayersMap').style.width, $('openLayersMap').style.height);
    		var greyLayer = OpenLayers.Util.createDiv("greyLayer", null, null, 
	                                                    null, "absolute", null,
	                                                    null);
	        var alertPopup = OpenLayers.Util.createDiv("alertPopup", null, size, 
	                                                    null, "absolute", null,
	                                                    null);
	        alertPopup.style.top = (sizeMap.h - size.h)/2 + "px";
	        alertPopup.style.left = (sizeMap.w - size.w)/2 + "px";
			var p = document.createElement("p");
	        p.innerHTML = "Sie k&ouml;nnen h&ouml;chstens 6 Pegel ausw&auml;hlen.";
	        alertPopup.appendChild(p);
	        var button = document.createElement("input");
	        button.id = "alertOk";
	        button.type = "button";
	        button.value = "OK";
	        alertPopup.appendChild(button);
	        
	        $('mapContainer').insertBefore(alertPopup, $('openLayersMap'));
	        $('mapContainer').insertBefore(greyLayer, $('openLayersMap'));
	        OpenLayers.Event.observe(button, "click", OpenLayers.Function.bindAsEventListener(this.closeAlertPopup, this));
    },
    
    closeAlertPopup: function(evt) {
		$('mapContainer').removeChild($('alertPopup'));
		$('mapContainer').removeChild($('greyLayer'));
    },
    
    /** 
     * Method: toggleMarkerIcon
     * if the gauge is selected, change the icon 
     */
    toggleMarkerIcon: function(pegelNr, selectionOff) {
		
		var search = ".png";
    	var replace = "_select.png";
		if(selectionOff){
    		search = "_select.png";
    		replace = ".png";
		}
		pegelItems.getElement(pegelNr).setIconUrl(pegelItems.getElement(pegelNr).getIconUrl().replace(search, replace));
    },
    
    /** 
     * Method: toggleControlLinks
     * turn the links of, if there is nothing to show 
     */
    toggleControlLinks: function(){
    	if(this.isEmpty()){
    		if(!IS_ARCHIVE){
	    		$('control_ganglinie').className = "inactiveLink";
	    		$('control_ganglinie').removeAttribute("target");
				$('control_ganglinie').removeAttribute("href");
    		}
    		$('control_stammdaten').className = "inactiveLink";
			$('control_stammdaten').removeAttribute("target");
			$('control_stammdaten').removeAttribute("href");
    	} else{
    		if(!IS_ARCHIVE){
	    		$('control_ganglinie').className = "link";
				$('control_ganglinie').target="ganglinie";
				$('control_ganglinie').href = this.getUrl(URL_GANGLINIE, 'pegelnummer');
				
				$('control_stammdaten').href = this.getUrl(URL_STAMMDATEN, 'pegelnr');
    		} else {
				$('control_stammdaten').href = this.getUrl(URL_ARCHIV_DETAILS, 'messstellen') + "&" + gewaesserPegelItems.generateFilterURL();
    		}
			$('control_stammdaten').className = "link";
			$('control_stammdaten').target="stammdaten";
			
    	}
    },
    
    zoomToItem: function(evt) {
    	var pegelNr = evt.object;
		this.selectionArray[pegelNr].zoomTo(); 
		OpenLayers.Event.stop(evt);
    },
    
    /** 
     * Method: expandItem
     * open or close the popup under the tab  
     */
    expandItem: function(evt) {
    	var pegelNr = evt.object;
    	if(this.selectionArray[pegelNr].toggleExpandState() == STATE_CLOSE){
    		this.closeInfoDiv(pegelNr);
    	} else {
			this.openInfoDiv(pegelNr);
			if(IS_ARCHIVE){
				$('pegelbar_details_' + pegelNr).target="_blank";
				$('pegelbar_details_' + pegelNr).href = pegelItems.getElement(pegelNr).getArchivURL();
			}	
			this.resizeInfoDiv(pegelNr);
    	}
		OpenLayers.Event.stop(evt);
    },
    
    /** 
     * Method: closeInfoDiv
     * close the popup under the tab  
     */
    closeInfoDiv: function(pegelNr) {
    	($('selectionDiv_' + pegelNr + '_expand_innerImage')).src = "../../img/map/openlayers/expand_open.gif";
		if(this.infoDiv && this.infoDiv.id == "poInfo_" + pegelNr){
			$('mapContainer').removeChild(this.infoDiv);
			this.infoDiv = null;
		}
    },
    
    /** 
     * Method: openInfoDiv
     * open the popup under the tab  
     */
    openInfoDiv: function(pegelNr) {
    	($('selectionDiv_' + pegelNr + '_expand_innerImage')).src = "../../img/map/openlayers/expand_close.gif";
    	this.createInfoDiv(pegelNr, new OpenLayers.Size(200,175));
    	
    },
    /** 
     * Method: createInfoDiv
     * creates and displays the popup under the tab  
     */
	createInfoDiv: function (pegelNr, size){
		if(!this.infoDiv){
			this.infoDiv = OpenLayers.Util.createDiv("poInfo_" + pegelNr, null, size, 
	                                                    null, "absolute", null,
	                                                    null);
			var sizeChild = new OpenLayers.Size(size.w - 10, size.h - 10);
	        var infoShadowDiv = OpenLayers.Util.createDiv("poInfo_shadow", null, sizeChild, 
	                                                    null, null, null,
	                                                    null);
	        this.infoDiv.appendChild(infoShadowDiv);
	        
	        var infoDivContent = OpenLayers.Util.createDiv("poInfo_content", null, sizeChild, 
	                                                    null, null, null,
	                                                    null);
	        infoDivContent.innerHTML = this.selectionArray[pegelNr].getInfoHTML();
	        this.infoDiv.appendChild(infoDivContent);
	        $('mapContainer').appendChild(this.infoDiv);
		} else {
			this.resetOtherExpandedStates(pegelNr);
			this.infoDiv.id = "poInfo_" + pegelNr;
			$('poInfo_content').innerHTML = this.selectionArray[pegelNr].getInfoHTML();
		}
		var selectElement = $('infoPegelItem_' + pegelNr);
		selectElement.events = new OpenLayers.Events(pegelNr, selectElement);
        selectElement.events.register('mousedown', pegelSelection, pegelSelection.changeItem);
        
        var zoomElement = $('zoomToPegelItem_' + pegelNr);
		zoomElement.events = new OpenLayers.Events(pegelNr, zoomElement);
        zoomElement.events.register('mousedown', pegelSelection, pegelSelection.zoomToItem);

		        	
		this.infoDiv.style.left = this.calculatePositionX(pegelNr) + "px";
		this.infoDiv.style.top = "24px";
		this.infoDiv.style.zIndex = "1500";
	},
	
	/** 
     * Method: resizeInfoDiv
     * if the content is bigger than the popup, resize it  
     */
	resizeInfoDiv: function(pegelNr) {
		if($('poInfo_' + pegelNr).firstChild){
			var size = new OpenLayers.Size(parseInt($('poInfo_content').firstChild.offsetWidth), 
										 	parseInt($('poInfo_content').firstChild.offsetHeight));
			if(size.w > parseInt($('poInfo_content').style.width)){
				$('poInfo_' + pegelNr).style.width = size.w + 20 + "px";
				$('poInfo_shadow').style.width = size.w + 10 + "px";
				$('poInfo_content').style.width = size.w + 10 + "px";
			}
			
			
			if(size.h > parseInt($('poInfo_content').style.height)){
				$('poInfo_' + pegelNr).style.height = size.h + 20 + "px";
				$('poInfo_shadow').style.height = size.h + 10 + "px";
				$('poInfo_content').style.height = size.h + 10 + "px";
			} 
		}
	},
	calculatePositionX: function(pegelNr) {
		return ($('selectionDiv_' + pegelNr)).offsetLeft;
		//return this.getIndex(pegelNr)*(TAB_WIDTH + (TAB_SPACE + 2)) + TAB_SPACE;	
	},
	
	/** 
     * Method: resetOtherExpandedStates
     * close other popups  
     */
    resetOtherExpandedStates: function(pegelNr){
    	for (var pegelNummer in this.selectionArray){
    		if (pegelNummer != pegelNr) {
    			if(this.selectionArray[pegelNummer].setExpandState(STATE_CLOSE))
    				($('selectionDiv_' + pegelNummer + '_expand_innerImage')).src = "../../img/map/openlayers/expand_open.gif";
    		} 
    	}
    },
    
    getIndex: function(pegelNr) {
    	var index = 0;
    	for (var pegelNummer in this.selectionArray){
    		if (pegelNummer == pegelNr) {
    			break;
    		}
    		index++;
    	}
    	return index;
    },
    
    isInSelection: function(pegelNr) {
    	return this.selectionArray[pegelNr]; 
    },
    
    isEmpty: function() {
    	return this.length == 0; 
    },
    
    getUrl: function(url, parameterName){
    	for (var pegelNummer in this.selectionArray){
    			url += parameterName + '=' + pegelNummer + '&';
    	}
    	return url.substring(0, url.length-1);
    },
    
    setDetailLinks: function(){
    	if(IS_ARCHIVE)
	    	for (var pegelNummer in this.selectionArray){
				if($('pegelbar_details_' + pegelNummer)){
					$('pegelbar_details_' + pegelNummer).target="_blank";
					$('pegelbar_details_' + pegelNummer).href = pegelItems.getElement(pegelNummer).getArchivURL();
				}	
	    	}
    },

	setStammdatenLink: function(){
    	if(IS_ARCHIVE)
			$('control_stammdaten').href = this.getUrl(URL_ARCHIV_DETAILS, 'messstellen') + "&" + gewaesserPegelItems.generateFilterURL();
    },
    CLASS_NAME: "PegelSelectionBar"
});

/**
 * Class: PegelFilter
 * handles all the stuff of filtering gauges by name or river
 */
PegelFilter = OpenLayers.Class({
    
    gewaesserArray: null,
    
    isArchive: null,
    
    parameter: null,
  	
  	zeitebenen: null,
  
    initialize: function(isArchive, parameter, zeitebenen) {
    	this.gewaesserArray = new Object();
    	if(isArchive)
			this.isArchive = isArchive;
    	this.lastEvent = 0;
        this.id = OpenLayers.Util.createUniqueID(this.CLASS_NAME + "_"); 
    },

	add: function(pegelItem) {
		if (!this.gewaesserArray[pegelItem.getGewaesserUnescaped()]) 
			this.gewaesserArray[pegelItem.getGewaesserUnescaped()] = new Object();
		if(!this.gewaesserArray[pegelItem.getGewaesserUnescaped()][pegelItem.getPegelnummer()])
				this.gewaesserArray[pegelItem.getGewaesserUnescaped()][pegelItem.getPegelnummer()] = pegelItem;
    },
    
    /** 
     * Method: initPegelFilter
     * sort rivers by name, add eventlisteners and fill the gauges/rivers in the dropdowns 
     */
    initPegelFilter: function() {
		var selectGewaesser = $('select_gewaesser');
		var selectPegel = $('select_pegel');
		var inputPegel = $('input_pegel');
		var gewaesserNameArray = new Array();
		
		
			
		for(var gewaesser in this.gewaesserArray) {
			if(this.gewaesserArray && gewaesser){
				gewaesserNameArray.push(gewaesser);
			}
		}
		gewaesserNameArray.sort();
		
		inputPegel.value = INPUT_PEGEL_DEFAULT;
		
		selectGewaesser.options[selectGewaesser.length] = new Option("Alle Gewässer", "all");
		
		
		OpenLayers.Event.observe(selectGewaesser, "change", OpenLayers.Function.bindAsEventListener(this.filterGewaesser, this));
		OpenLayers.Event.observe(selectPegel, "dblclick", OpenLayers.Function.bindAsEventListener(this.handlePegellistEvents, this));
		OpenLayers.Event.observe(selectPegel, "keydown", OpenLayers.Function.bindAsEventListener(this.handlePegellistEvents, this));
		OpenLayers.Event.observe(selectPegel, "focus", OpenLayers.Function.bindAsEventListener(this.handlePegellistEvents, this));
		OpenLayers.Event.observe(inputPegel, "click", OpenLayers.Function.bindAsEventListener(this.focusInput, this));
		OpenLayers.Event.observe(inputPegel, "keyup", OpenLayers.Function.bindAsEventListener(this.filterGewaesser, this));
		
		for(var index=0; index < gewaesserNameArray.length; index++) {
			selectGewaesser.options[selectGewaesser.length] = new Option(gewaesserNameArray[index], gewaesserNameArray[index]);
		}
		this.fillPegelInFastSelection();
		//pegelonlineSelection.maximizeControl();

    },
    
    
    initArchiveFilter: function(parameter, zeitebene) {
		if(this.isArchive){
			this.parameter = parameter;
			this.zeitebenen = zeitebene;
			var parameterFieldset = $('fieldset_parameter');
			var zeitebeneFieldset = $('fieldset_zeitebene');
			var i = 0;
			for (var value in this.parameter){
				var spanElem = document.createElement("span");
//				if(i % 2 == 0)
//					spanElem.className = "checkboxleft";
//				else 
//					spanElem.className = "checkboxright";
				
				var inputElem = document.createElement("input");
		        inputElem.id = "input_parameter_" + value;
		        inputElem.name = "parameter";
		        inputElem.type = "checkbox";
		        inputElem.value = value;
		        //inputElem.checked = true;
		        inputElem.defaultChecked = true;
		        var labelElem = document.createElement("label");
		        labelElem.htmlFor = "input_parameter_" + value;
		        labelElem.appendChild(document.createTextNode(this.parameter[value].getBezeichnung()));
		        spanElem.appendChild(inputElem);
		        spanElem.appendChild(labelElem);
//		        parameterFieldset.appendChild(inputElem);
//		        parameterFieldset.appendChild(labelElem);
		        parameterFieldset.appendChild(spanElem);
		        zeitebeneFieldset.appendChild(document.createTextNode(" "));
		        OpenLayers.Event.observe(inputElem, "click", OpenLayers.Function.bindAsEventListener(this.filterArchive, this));
		        i++;
			}
			i = 0;
			for (var value in this.zeitebenen){
				var spanElem = document.createElement("span");
//				if(i % 2 == 0)
//					spanElem.className = "checkboxleft";
//				else   
//					spanElem.className = "checkboxright";
//					
				var inputElem = document.createElement("input");
		        inputElem.id = "input_zeitebenen_" + value;
		        inputElem.name = "zeitebenen";
		        inputElem.type = "checkbox";
		        inputElem.value = value; 
		        //inputElem.checked = true;
		        inputElem.defaultChecked = true;
		        var labelElem = document.createElement("label");
		        labelElem.htmlFor = "input_zeitebenen_" + value;
		        labelElem.appendChild(document.createTextNode(this.zeitebenen[value].getBezeichnung()));
		        spanElem.appendChild(inputElem);
		        spanElem.appendChild(labelElem);
//		        zeitebeneFieldset.appendChild(inputElem);
//		        zeitebeneFieldset.appendChild(labelElem);
				zeitebeneFieldset.appendChild(spanElem);
				zeitebeneFieldset.appendChild(document.createTextNode(" "));
		        OpenLayers.Event.observe(inputElem, "click", OpenLayers.Function.bindAsEventListener(this.filterArchive, this));
		        i++;
			}
			
			OpenLayers.Event.observe($('date-begin'), "keyup", OpenLayers.Function.bindAsEventListener(gewaesserPegelItems.filterArchive, gewaesserPegelItems));
			OpenLayers.Event.observe($('date-begin'), "change", OpenLayers.Function.bindAsEventListener(gewaesserPegelItems.filterArchive, gewaesserPegelItems));
			OpenLayers.Event.observe($('date-begin-mm'), "change", OpenLayers.Function.bindAsEventListener(gewaesserPegelItems.filterArchive, gewaesserPegelItems));
			OpenLayers.Event.observe($('date-begin-dd'), "change", OpenLayers.Function.bindAsEventListener(gewaesserPegelItems.filterArchive, gewaesserPegelItems));
			OpenLayers.Event.observe($('date-end'), "change", OpenLayers.Function.bindAsEventListener(gewaesserPegelItems.filterArchive, gewaesserPegelItems));
			OpenLayers.Event.observe($('date-end'), "keyup", OpenLayers.Function.bindAsEventListener(gewaesserPegelItems.filterArchive, gewaesserPegelItems));
			OpenLayers.Event.observe($('date-end-mm'), "change", OpenLayers.Function.bindAsEventListener(gewaesserPegelItems.filterArchive, gewaesserPegelItems));
			OpenLayers.Event.observe($('date-end-dd'), "change", OpenLayers.Function.bindAsEventListener(gewaesserPegelItems.filterArchive, gewaesserPegelItems));
			
			OpenLayers.Event.observe($('uebersicht-link'), "click", OpenLayers.Function.bindAsEventListener(this.showTable, this));
		}
		
    },
    
    
    focusInput: function(){
    	if($('input_pegel').value == INPUT_PEGEL_DEFAULT){
    		$('input_pegel').value = "";
    	}
    	$('input_pegel').focus();
    },
    
    /** 
     * Method: fillPegelInFastSelection
     * put gauges in their dropdown 
     */
    fillPegelInFastSelection: function(gewaesser){
    	var selectPegel = $('select_pegel');
    	while (selectPegel[0]) {
    		selectPegel.options[0] = null;
    	}
    	
    	for (var pegelNummer in pegelItems.pegel){
    		if(this.isInGewaesser(gewaesser, pegelNummer) && this.isInFilter(pegelNummer) && pegelItems.pegel[pegelNummer].isVisible()){
    			selectPegel.options[selectPegel.length] = new Option(pegelItems.pegel[pegelNummer].getNameUnescaped(), pegelNummer);
    		}
    	}
    	
    },
    /**
     * Method: fillGewaesserInFastSelection
     * is called after every archive filter action and goes
     * through all pegelitems to get the rest of the rivers
     * and put them in the river dropdown
     */
    
    fillGewaesserInFastSelection: function(){
    	var gewaesserNameArray = new Array();
    	var gewaesserNameObject = new Object();
		var selectGewaesser = $('select_gewaesser');
		
		if(pegelItems.pegel){
			for (var pegelNummer in pegelItems.pegel){
    			if(pegelItems.pegel[pegelNummer].isVisible() && !gewaesserNameObject[pegelItems.pegel[pegelNummer].getGewaesserUnescaped()])
    				gewaesserNameObject[pegelItems.pegel[pegelNummer].getGewaesserUnescaped()] = pegelItems.pegel[pegelNummer].getGewaesserUnescaped();
	    	}
	    	
	    	for (var gewaesser in gewaesserNameObject){
	    		gewaesserNameArray.push(gewaesser);
	    	}
		}
		gewaesserNameArray.sort();
		
		while (selectGewaesser[0]) {
    		selectGewaesser.options[0] = null;
    	}
		selectGewaesser.options[selectGewaesser.length] = new Option("Alle Gewässer", "all");
		for(var index=0; index < gewaesserNameArray.length; index++) {
			selectGewaesser.options[selectGewaesser.length] = new Option(gewaesserNameArray[index], gewaesserNameArray[index]);
		}
    },
    
    /** 
     * Method: isInFilter
     * does the gauge match the filter criterion? 
     */
    isInFilter: function (pegelNummer){
    	var inputPegel = $('input_pegel').value;
    	if(inputPegel == INPUT_PEGEL_DEFAULT || inputPegel == "")
    		return true;
    	return (pegelItems.pegel[pegelNummer].getNameUnescaped().toLowerCase().indexOf(inputPegel.toLowerCase()) == 0);
    },
    
   /** 
     * Method: isInFilter
     * is the gauge at the river? 
     */
    isInGewaesser: function (gewaesser, pegelNummer){
    	if((!gewaesser || gewaesser == "all"))
    		return true;
    	return (this.gewaesserArray[gewaesser] && this.gewaesserArray[gewaesser][pegelNummer]);
    	
    },
    
    filterGewaesser: function(evt) {
		this.fillPegelInFastSelection($('select_gewaesser').value);
    },
    
    showTable: function(evt) {
		var fenster = window.open("","small","width=780,height=400,top=50,left=50,toolbar=no,menubar=no,location=no,hotkeys=no,resizable=yes,scrollbars=yes,dependent=yes,status=no");
		with (fenster.document) {
		    open();
		    writeln("<html><head><title>Archiv-&Uuml;bersicht-Gesamt</title></head>");
		    writeln("<body style='background-color:white; font-family:Arial,Helvetica,sans-serif; color:#000000'>");
		    writeln("<p style='font-size:14px; font-weight:bold'>Aktuelle Wasserst&auml;nde</p>");
		    writeln("<table border='1' cellspacing='0' cellpadding='3' style='background-color:#FFFFFF; font-size:12px'>");
		    writeln("<tr style='font-weight:bold; background-color:#CCCCCC'><th>Pegelname</th>" + 
		    	"<th>Gew&auml;sser</th><th>Parameter</th><th>Zeitebene</th><th>Startdatum</th><th>Enddatum</th></tr>");
		
		    for (var gewaesser in this.gewaesserArray){
		    	for (var pegelnr in this.gewaesserArray[gewaesser]){
			    	if(pegelItems.pegel[pegelnr].match(this.generateSelectedParameterZeitebenen(), this.generateDate(BEGIN_DATE), this.generateDate(END_DATE))){
				    	writeln("<tr>");    	
						writeln("<td style='border:silver 1px solid'>" + pegelItems.pegel[pegelnr].getName() + "</td>");
						writeln("<td style='border:silver 1px solid'>" + pegelItems.pegel[pegelnr].getGewaesser() + "</td>");
						writeln("<td style='border:silver 1px solid'>" + this.getSelectedParameter(pegelItems.pegel[pegelnr].getArchiveData()) + "</td>");
						writeln("<td style='border:silver 1px solid'>" + this.getSelectedZeitebene(pegelItems.pegel[pegelnr].getArchiveData()) + "</td>");
						var datum = pegelItems.pegel[pegelnr].getMinMaxDatum(this.generateSelectedParameterZeitebenen());				
						writeln("<td style='border:silver 1px solid'>" + datum.getStartDatumFormatted() + "</td>");
						writeln("<td style='border:silver 1px solid'>" + datum.getEndDatumFormatted() + "</td>");
						writeln("</tr>");
			    	}
			    	
		    	}
    		}
		    writeln("</table></body></html>");
		    close();    
		}
    fenster.focus();
    },
    
    filterArchive: function(evt) {
    	pegelItems.applyFilter(this.generateSelectedParameterZeitebenen(), this.generateDate(BEGIN_DATE), this.generateDate(END_DATE));
		var target = evt.target ? evt.target : evt.srcElement;
		if(target.name.indexOf("parameter") > -1 || target.name.indexOf("zeitebene") > -1){
			this.setArchiveLinks();
		}
    	this.fillPegelInFastSelection($('select_gewaesser').value);
    	this.fillGewaesserInFastSelection();
    	//pegelItems.pegel[582730].setVisibility()
		//this.fillPegelInFastSelection($('select_gewaesser').value);
    },
    /**
     * sets the detail link target in the open popups and in the pegelbarselection
     */
    setArchiveLinks: function(){
    	for(var index=0; index < map.popups.length; index++) {
    		if(map.popups[index].getMouseEventType() == "mousedown" && map.popups[index].visible()){
    			var pegelNr = map.popups[index].feature.data.pegelNummer;
    			$('mousedown_details_' + pegelNr).target="_blank";
				$('mousedown_details_' + pegelNr).href = pegelItems.getElement(pegelNr).getArchivURL();	
    		}
    	}	
    	pegelSelection.setDetailLinks();
    	pegelSelection.setStammdatenLink();
    },
    
    generateFilterURL: function(){
    	var url = "";
    	for (var value in gewaesserPegelItems.parameter){
	        if($('input_parameter_' + value).checked)
	        	url += "parameter=" + value + "&";
    	}
    	for (var value in gewaesserPegelItems.zeitebenen){
	        if($('input_zeitebenen_' + value).checked)
	        	url += "zeitebenen=" + value + "&";
    	}
    	return url.substring(0, url.length-1);
    },
    
    generateDate: function(beginEnd) {
    	var idPrefix = "date-end";
    	var hour = 23;
    	var minuteSecond = 59;
    	if(beginEnd == BEGIN_DATE){
    		idPrefix = "date-begin";
    		hour = 0;
    		minuteSecond = 0;	
    	}
		var date = new Date($(idPrefix).value,  $(idPrefix + '-mm').value - 1,  $(idPrefix + '-dd').value, hour, minuteSecond, minuteSecond);
    	//var date = datePickerController.getDatePicker(idPrefix).date;
    	
//    	date.setHours(hour);
//    	date.setMinutes(minuteSecond);
//    	date.setSeconds(minuteSecond);
//    	
    	return date.getTime();
    	//if($(idPrefix + 'dd') && $(idPrefix + 'mm') && $(idPrefix + 'dd') && $(idPrefix + 'dd').value != -1
    	//var date = new Date(Jahr, Monat, Tag, Stunden, Minuten, Sekunden);
    	
    },
    
    getSelectedParameter: function(archiveData) {
    	var ret = "";
    	for (var value in this.parameter){
	        if($('input_parameter_' + value).checked && archiveData.indexOf(value + PARAMETER_ZEITEBENE_SEPERATOR) != -1)
	        	ret += value + ", ";
    	}
    	return ret.substring(0, ret.length-2);
    },
    
    getSelectedZeitebene: function(archiveData) {
    	var ret = "";
    	for (var value in this.zeitebenen){
	        if($('input_zeitebenen_' + value).checked && archiveData.indexOf(PARAMETER_ZEITEBENE_SEPERATOR + value + "=") != -1)
	        	ret += ZEITEBENE_ARCHIV[value].getBezeichnung() + ", ";
    	}
    	return ret.substring(0, ret.length-2);
    },
    
    generateSelectedParameterZeitebenen: function() {
    	var selectedParamArray = new Array();
    	var selectedZeitebenenArray = new Array();
    	
    	for (var value in this.parameter){
	        if($('input_parameter_' + value).checked)
	        	selectedParamArray.push(value);
    	}
    	
    	for (var value in this.zeitebenen){
	        if($('input_zeitebenen_' + value).checked)
	        	selectedZeitebenenArray.push(value);
    	}
    	
    	if(selectedParamArray.length != 0 && selectedZeitebenenArray != 0){
	    	var returnArray = new Array();
	    	for(var i=0; i<selectedParamArray.length; i++) {
	    		for(var ii=0; ii<selectedZeitebenenArray.length; ii++) {
	    			returnArray.push(selectedParamArray[i] + PARAMETER_ZEITEBENE_SEPERATOR + selectedZeitebenenArray[ii]);
	    		}	
	    	}
	    	return returnArray;
    	}
    	
    	return null;
    },
    
    handlePegellistEvents: function(evt) {
		var target = evt.target || evt.srcElement;
		if(evt.type == "dblclick" || (evt.type == "keydown" && (evt.charCode || evt.keyCode) == OpenLayers.Event.KEY_RETURN)){
			if(pegelItems.getElement(target.value)){
				pegelItems.getElement(target.value).zoomTo();
			}
		} else if (evt.type == "focus"){
			if (target.options.length == 1)
    			target.options[0].selected = true;
		}
    },
    CLASS_NAME: "PegelFilter"
});

Parameter = OpenLayers.Class({

  	id: null,
  	
  	bezeichnung: null,
  
    
    initialize: function(id, bezeichnung) {
        this.id = id;
		this.bezeichnung = bezeichnung;
    },
    
    getBezeichnung: function(){
    	return this.bezeichnung;
    },
    
    getId: function(){
    	return this.id;
    },
    /** 
     * Method: destroy
     * nullify references to prevent circular references and memory leaks
     */
    destroy: function() {

    },

    CLASS_NAME: "Parameter"
});

Zeitebene = OpenLayers.Class({

  	id: null,
  	
  	bezeichnung: null,
  
    
    initialize: function(id, bezeichnung) {
        this.id = id;
		this.bezeichnung = bezeichnung;
    },
    
    getBezeichnung: function(){
    	return this.bezeichnung;
    },
    
    getId: function(){
    	return this.id;
    },
    /** 
     * Method: destroy
     * nullify references to prevent circular references and memory leaks
     */
    destroy: function() {

    },

    CLASS_NAME: "Zeitebene"
});

Datum = OpenLayers.Class({
	startDatum: null,
	endDatum: null,
	
	initialize: function(startDatum, endDatum) {
        this.startDatum = startDatum;
		this.endDatum = endDatum;
    },
    
    getStartDatumFormatted: function(){
    	if(this.startDatum != -1){
    		return this.formatDate(new Date(this.startDatum));
    	}
    },
    
    getEndDatumFormatted: function(){
    	if(this.endDatum != -1){
    		return this.formatDate(new Date(this.endDatum));
    	}
    	
    },
    
    formatDate: function(date){
    	return (date.getDate()<10 ? "0" : "") + date.getDate() + "." + (date.getMonth()<9 ? "0" : "") + 
    	(date.getMonth()+1) + "." + date.getFullYear();
    },
    CLASS_NAME: "Datum"
	
});
/*** 
	Dynamischer Inhalt (muss hier unten stehen, da sonst die Klassen Parameter und zeitebene noch nicht da sind)
	
	Block wird nicht ausgewertet wenn Servlet AddDynamicContentToOlJavascriptExtensionsServlet nicht mit URL des Archivbereichs aufgerufen wird
	und damit Model null ist (siehe web.xml)
****/

