var baseURL = null;

var CATMANAGE_LOAD_FULL;
var CATMANAGE_SHOW_BBOX;
var CATMANAGE_SHOW_OVERVIEW; 
var CATMANAGE_NOOFRESULTS;

var lon = 0;
var lat = 0;
var zoom = 1;
var map, layer;
var box;
var mapSRS = "EPSG:4326";
var editor;

function initOpenLayers(){
        map = new OpenLayers.Map( 'map', {
        projection: new OpenLayers.Projection( mapSRS ),
        units: "m",
        //maxResolution: 156543.0339,
        //maxExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34),
        //maxExtent: new OpenLayers.Bounds(-5.19, 45.72, 15.29, 56.25), //Germany
        maxExtent: new OpenLayers.Bounds(-180, -90, 180, 90), //Germany
        allOverlays: true
      } );

    //layer = new OpenLayers.Layer.OSM();
    //layer = new OpenLayers.Layer.Google("Google Streets", {visibility: true});
    //layer = new OpenLayers.Layer.VirtualEarth("Shaded", {type: VEMapStyle.Shaded}); //requires EPSG:4326
    layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", "http://vmap0.tiles.osgeo.org/wms/vmap0?", {layers: 'basic'} );
    //layer = new OpenLayers.Layer.WMS( "DTK2500", "http://gdz.bkg.bund.de/wms_dtk2500?", {layers: '0', format: 'image/png', transparent: 'true'} ); //requires EPSG:4326
    map.addLayer(layer);
    map.addLayer( boxes );
    map.setCenter(new OpenLayers.LonLat(lon, lat), zoom);
    map.addControl( new OpenLayers.Control.LayerSwitcher() );
    map.addControl(new OpenLayers.Control.MousePosition());
}
    

function init() {
    var s = window.location.href;
    var idx = s.lastIndexOf( "/" );
    baseURL = s.substring( 0, idx+1 ) + "control?";
    loadSpatialExtents();	            
}

function loadSpatialExtents() {
	submitGetRequest( baseURL + "action=getSpatialExtents", 
	    
        function(result) {
            // inline function definition
            var spatialExtents = JSON.parse( result, null );
            
            var select = getElement( "geogrDescription" );
            //remove all entries
            select.innerHTML = "";
            for ( var i = 0; i < spatialExtents.length; i++) {
                appendOption( select, spatialExtents[i]['name'], spatialExtents[i]['id'] );             
            }
        }, 
        
        null, true );
}

function searchMetadata() {
    var bean = new function() {
        this.action = 'searchMetadata';
        this.freeText = getElement( 'FREETXT' ).value;
        this.from = '1000-01-01';
        this.to = '3000-12-31';
        if ( getElement( 'CB_TIME' ).checked ) {
        	this.from = getElement( 'date1' ).value;
        	this.to = getElement( 'date2' ).value;
        }
        if ( getElement( 'CB_SPATIAL' ).checked ) {
            this.geogrID = getSelectedValue( 'geogrDescription' );
        }
    }                
    try {                    
        submitPostRequest( baseURL, searchMetadataHandling, JSON.stringify( bean ), null, true );
    } catch( e ) {
        alert( e );
    } 
    getElement( 'WAIT' ).style.visibility = 'visible';
}

function pageing(page) {
    
    var bean = new function() {
        this.action = 'pageing';
        this.counter = '' + page;                    
    }
    try {                    
        submitPostRequest( baseURL, searchMetadataHandling, JSON.stringify( bean ), null, true );
    } catch( e ) {
        alert( e );
    } 
    getElement( 'WAIT' ).style.visibility = 'visible';
}

function searchMetadataHandling(result) {
    getElement( 'WAIT' ).style.visibility = 'hidden';
	if ( result.indexOf( ".ExceptionBean" ) > -1 ) {
	    openException( JSON.parse( result ).message, 'E R R O R' );
	} else {                    
	    var tmp = JSON.parse( result, null );
	    var resultList = tmp[0];
	    getElement( 'NOOFRESULTS' ).innerHTML = tmp[1] + CATMANAGE_NOOFRESULTS;      
	    markPageing( tmp[2] );  
	    var s = '<hr>';
	    var t1 = CATMANAGE_EDITMETADATSET;
	    var t2 = CATMANAGE_LOADMDTEMPLATE;
	    for ( var i = 0; i < resultList.length; i++) {
	        s += '<table border="0" width="630px" cellspacing="2">';        
	        s += '<tr><td width="15px"/><td width="500px">';
	        s += '<b>* ' + resultList[i].title + '</b><br></br>';
	        s += '<font size="-1">' + resultList[i].abstr.substr( 0, 70 ) + ' ...</font><br>';
	        s += 'last update: ' + resultList[i].modified + '<br>';
	        s += '<table border="0"><tr>';
	        s += '<td><a class="button" ';
	        s += 'href="javascript:loadFullMetadataSet(\'' + resultList[i].id + '\', ';
	        s += '\'' + resultList[i].csw + '\' )">';
	        s += CATMANAGE_LOAD_FULL + '</a></td><td width="5"></td>';
	        s += '<td>';
	        s += '<a class="button" href="javascript:showBBOX( \'' + resultList[i].bbox + '\' )">';
	        s += CATMANAGE_SHOW_BBOX + '</a>';
	        s += '</td>';
	        if ( editor == true && resultList[i].hierarchyLevel != 'service' ) {
	            s += '<td>';
	            s += '<a href="md_editor.jsp?action=edit&id=' + resultList[i].id + '" class="toolbarItem" title="' + t1 + '"><img border="0" src="./images/page_white_edit.png"/></a>';
	            s += '</td>';
	            s += '<td>';
	            s += '<a href="md_editor.jsp?action=new&id=' + resultList[i].id + '" class="toolbarItem" title="' + t2 + '"><img border="0" src="./images/page_code.png"/></a>';
	            s += '</td>';
	        }
	        s += '</tr></table>';
	        s += '</td><td width="15"></td>';                       
	        s += '<td width="100">';
	        if ( resultList[i].overview ) {
	            s += '<img width="120" height="120" alt="" src="' + resultList[i].overview + '">';
	        } else {
	            s += CATMANAGE_SHOW_OVERVIEW; 
	        }
	        s += '</td></tr></table><hr>';                        
	    } 
	    getElement( 'RESULTTABLE' ).innerHTML = s;
	    getElement( 'PAGEING1' ).style.visibility = 'visible';
	}
}

 

function markPageing(page) {
    var i = 0;
    while ( getElement( 'PAGE_TOP_' + i ) != null ) {
    	getElement( 'PAGE_TOP_' + i ).style.border = "#99BBE8 1px solid";
        i++;
    }
    
	getElement( 'PAGE_TOP_' + page ).style.border = "#fe5215 1px solid";
}

function loadFullMetadataSet(id, csw) {
    var bean = new function() {
        this.action = 'loadFullMetadataSet';
        this.ID = id;
        this.CSW = csw;
        this.FORMAT = "HTML";
    }
    try {                    
        submitPostRequest( baseURL, loadFullMetadataSetHandling, JSON.stringify( bean ), null, true );
    } catch( e ) {
        alert( e );
    } 
}

function loadFullMetadataSetHandling(result) {
    if ( result.length < 50 ) {
        alert( "ERROR: could not access full metadata set" );
        return;
    }                
	getElement( 'fullMDFrame' ).innerHTML = result;
	getElement( 'fullMDFrame' ).style.visibility = 'visible';
	getElement( 'fullMDFrame' ).style.background = '#FFFFFF';
}

function closeFullMD() {
	getElement( 'fullMDFrame' ).style.visibility = 'hidden';
}

function getAsXML(id, csw) {
	var bean = new function() {
        this.action = 'loadFullMetadataSet';
        this.ID = id;
        this.CSW = csw;
        this.FORMAT = "XML";
    }
    try {                    
        submitPostRequest( baseURL, loadFullMetadataSetHandling, JSON.stringify( bean ), null, true );
    } catch( e ) {
        alert( e );
    } 
}

function getAsPDF(id, csw) {
	var s = baseURL + "action=loadFullMetadataSet&format=PDF&id=" + id + "&csw=" + csw;
	var fiw = window.open( s ,"Report" ,"width=750,height=600,left=100,top=100,scrollbars=yes" );
    fiw.focus();
}

function findServices(id, csw) {
	var bean = new function() {
        this.action = 'findServices';
        this.resourceIdentifier = id;
        this.CSW = csw;
    }
    try {                    
        submitPostRequest( baseURL, findServicesHandling, JSON.stringify( bean ), null, true );
    } catch( e ) {
        alert( e );
    }         
}

function findServicesHandling(result) {
	if ( result.length < 50 ) {
        alert( "ERROR: could not access full metadata set" );
        return;
    }                
    getElement( 'fullMDFrame' ).innerHTML = result;
    getElement( 'fullMDFrame' ).style.visibility = 'visible';
    getElement( 'fullMDFrame' ).style.background = '#FFFFFF';
}

function showBBOX(bbox) {
	var tmp = bbox.split ( ' ' );
    var bounds = new OpenLayers.Bounds(tmp[0], tmp[1], tmp[2], tmp[3]);
    if ( mapSRS != "EPSG:4326" ) {
        bounds.transform( new OpenLayers.Projection( "EPSG:4326" ),
                          new OpenLayers.Projection("EPSG:900913") );
    } 
    map.zoomToExtent( bounds );                        
    map.setCenter( bounds.getCenterLonLat());
	if ( box != null ) {
	    boxes.removeMarker( box );
	}
    box = new OpenLayers.Marker.Box( bounds );                                
    boxes.addMarker( box );                
}

function reset() {
    getElement( 'FREETXT' ).value = '';
    getElement( 'CB_SPATIAL' ).checked = false;
    getElement( 'CB_TIME' ).checked = false;
    getElement( 'RESULTTABLE' ).innerHTML = '';
    getElement( 'PAGEING1' ).style.visibility = 'hidden';
    getElement( 'NOOFRESULTS' ).innerHTML = '';
    getElement( 'date1' ).value = '';
    getElement( 'date2' ).value = '';
}

function openCalender() {
	window.open( "select_timestamp.jsp", "sqlselect", "width=300,height=350,left=150,top=200,scrollbars=no,resizable=no" );
}

function openCapabilities(dcp, type) {
	if ( dcp.charAt(dcp.length-1) == '?' || dcp.charAt(dcp.length-1) == '&' ) {
        dcp += 'request=GetCapabilities';
    } else if ( dcp.indexOf( '?' ) > -1  ) {
    	dcp += '&request=GetCapabilities';
    } else {
    	dcp += '?request=GetCapabilities';
    } 
    if ( type.toLowerCase().indexOf( 'view' ) > -1 ) {
         
        window.open( dcp + '&service=WMS', 'Capabilities', "width=600,height=600,left=100,top=100" );
    }
}

function maximizeMap() {
    var mapFrame = getElement( 'MapFrame' );
    mapFrame.style.top = '90px';
    mapFrame.style.left = '0px';
    mapFrame.style.width = '680px';
    mapFrame.style.height = '700px';
    mapFrame.style.marginLeft = '0px';
    map.zoomIn();      
    getElement( 'normalizeMap' ).style.visibility = 'visible';          
    getElement( 'maximizeMap' ).style.visibility = 'hidden';
}

function normalizeMap() {
	var mapFrame = getElement( 'MapFrame' );
    mapFrame.style.top = '150px';
    mapFrame.style.left = '0px';
    mapFrame.style.width = '300px';
    mapFrame.style.height = '350px';
    mapFrame.style.marginLeft = '690px';
    map.zoomOut();
    getElement( 'normalizeMap' ).style.visibility = 'hidden';
    getElement( 'maximizeMap' ).style.visibility = 'visible';
}
