// get machine name
var hostName = document.location.host;
// build the URL
var GetCapabilitiesURL = "http://" + hostName + "/"+ top.VirtualDir +"/jsp/getCapabilities.jsp";
var GetFeatureInfoURL = "http://" + hostName + "/"+ top.VirtualDir +"/jsp/getFeatureInfo.jsp";
var GetMapURL = "http://" + hostName + "/"+ top.VirtualDir +"/jsp/getMap.jsp";

//which request type: getCapabilities, getMap, getFeatureInfo
var RequestMode;

// current extent vars
var minx;
var miny;
var maxx;
var maxy;

// identify extent vars
var minxId;
var minyId;
var maxxId;
var maxyId;

// borswercheck
var isNS, isNS6;

// size of map image in pixels - will be updated dynamically
var mWidth;
var mHeight;

// NOTICE: no server communication needed!
// -> all required parameters are available in global variables
function getCapabilities (layer) {

        // set zoom level
        //alert("ZoomLevel: " + zoomLevel + "\nLayer: " + layer);
        currentZoomLevel = 1;

  	    setLayers(layer);
	    displayZoomLevel();

	    // mark the seleted zoom level
	    markZoomLevel(currentZoomLevel);

	    //get the initial bounding box
	    minx = top.startMinx;
	    maxx = top.startMaxx;

	    // calculate upp of the map
	    var upp = Math.abs(minx-maxx) / mWidth;
        // center coords of the requested map
        var yCenter = (parseFloat(top.startMaxy) + parseFloat(top.startMiny)) /2;
	    miny = yCenter - (upp * mHeight) /2;
	    maxy = yCenter + (upp * mHeight) /2;
	    top.startMiny = miny;
	    top.startMaxy = maxy;

	    // get bounding box for the overview
	    setOverviewBoundingBox();
}

//getmap
function getMap(mapServerPreProcess, ignoreRequestPreProcess){

    // do a javascriptfunction before requesting a map
    if (!(ignoreRequestPreProcess) && zoomLevelMapRequestPreprocess.length > 0){
        var theFunction = new Function (zoomLevelMapRequestPreprocess);
        theFunction();
    }

    var theRequest = writeRequest("GetMap", mapServerPreProcess);
    sendToServer(GetMapURL,theRequest,2);
}

// getfeatureinfo
function getFeatureInfo(){
  var theRequest = writeRequest("GetFeatureInfo");
  sendToServer(GetFeatureInfoURL,theRequest,3);
}

//getprint map
function getPrintMap(){
    var theRequest = writeRequest("GetPrintMap");
    sendToServer(GetMapURL,theRequest,4);
}

function sendToServer(theURL,theRequest,theType, theJsFunction) {
    // show wait gif
    displayRetrieving();
	//set the request-type and send request to server
	RequestMode = theType;

	var thePostForm = PostFrame.document.forms[0];
	thePostForm.action = theURL;
	thePostForm.Request.value = theRequest;
	if (typeof (theJsFunction) != 'string') { theJsFunction= 'parent.processResponse();'; }
	thePostForm.JavaScriptFunction.value = theJsFunction;

	thePostForm.submit();
}


// write request dependent on request-type
function writeRequest(RequestType, Value){
  var sRequest = '';
  if (RequestType == "GetCapabilities") {
    sRequest = sRequest + 'RequestType=GetCapabilities,';
  }
  else if (RequestType == "GetMap") {

    checkZoomLevel();
    checkBBoxSize();   // check the requested bounding box
    checkAspectRatio();

    var theLayers = getSelectedLayers ();   // get selected Layers

    sRequest = sRequest + 'RequestType=GetMap;';
    sRequest = sRequest + 'minx='+ minx +';';
    sRequest = sRequest + 'miny='+ miny +';';
    sRequest = sRequest + 'maxx='+ maxx +';';
    sRequest = sRequest + 'maxy='+ maxy +';';
    sRequest = sRequest + 'width='+ mWidth +';';
    sRequest = sRequest + 'height='+ mHeight +';';
    sRequest = sRequest + 'layers='+ theLayers + ';';
    sRequest = sRequest + 'objects='+ aObjectIDsToShow.join(",")+ ';';
    sRequest = sRequest + 'withoutMap=' + bRequestWithoutMap;

    if (Value){
        // replace = by %3D
        Value = Value.replace(/=/g,"%3D");
        sRequest = sRequest + ';preProcess='+ Value;
    }
  }
  else if (RequestType == "GetPrintMap") {

    var theLayers = getSelectedLayers ();   // get selected Layers
    sRequest = sRequest + 'RequestType=GetMap;';
    sRequest = sRequest + 'minx='+ thePrintMapWindow.minxPrint +';';
    sRequest = sRequest + 'miny='+ thePrintMapWindow.minyPrint +';';
    sRequest = sRequest + 'maxx='+ thePrintMapWindow.maxxPrint +';';
    sRequest = sRequest + 'maxy='+ thePrintMapWindow.maxyPrint +';';
    sRequest = sRequest + 'layers='+ theLayers+';';
    sRequest = sRequest + 'objects='+ aObjectIDsToShow.join(",")+';';
    sRequest = sRequest + 'width='+ thePrintMapWindow.mapWidthPrint +';';
    sRequest = sRequest + 'height='+ thePrintMapWindow.mapHeightPrint +';';
    sRequest = sRequest + 'withoutMap=' + bRequestWithoutMap;
  }
  else if (RequestType == "GetFeatureInfo") {
	sRequest = sRequest + 'RequestType=GetFeatureInfo';
  }
    return sRequest;
}

function processResponse(){

  switch(RequestMode) {

    //response is from a GetCapabilities request
	case 1:
		break

	//response is from a getMap request
	case 2:

	    var theMapURL = "";
	    var theScaleURL = "";

	    // if no new map is requested take old one
	    if (bRequestWithoutMap) {
	        bRequestWithoutMap = false;
	        theMapURL =  MapFrame.document.getElementById("theMapImage").src;
	        theScaleURL = MapFrame.document.getElementById("theScaleImage").src;
	    }
	    else {
		    theMapURL = getImageURL();
		    theScaleURL = getScaleURL();
		}

        //if mode is panning  show temporarely a blank pixel
        if ( toolMode == 3) {
           MapFrame.document.getElementById("theMapImage").src ='img/websis.gif';
        }

		// make sure the image is at the top left after panning
		var theMap = MapFrame.document.getElementById("theMapDiv");
		theMap.style.left = 0;
        theMap.style.top = 0;

        theMap.width= mWidth;
        theMap.height= mHeight;

        if (aObjectIDsToShow.length > 0 || aSymbols.length > 0 || bRewriteMap){
            if (aObjectIDsToShow.length > 0) {
                // get Symbols from post-frame
                getSymbols();
            }

            // write map frame with symbols
            writeMapWithSymbols(theMapURL, theScaleURL);
        }

        // opera workaround
        MapFrame.document.getElementById("theMapImage").src = theMapURL;
        MapFrame.document.getElementById('theScaleImage').src = theScaleURL;

	    //extract the current envelope and update the extent variables
	    var theBoundingBox = getBoundingBox();

	    minx = theBoundingBox[0];
	    miny = theBoundingBox[1];
	    maxx = theBoundingBox[2];
	    maxy = theBoundingBox[3];

	    // show overview box
	    displayOverviewBox();


	    // highlight symbol if existing
	    if (aHighlightSymbols.length > 0){
	        highlightSymbol();
	    }

	    // reset the button to attribute mode
	    if (top.switchToFeatureInfo == 1) {
	        clickFunction ('identify');
	    }
	    break;

	case 3:
	    displayAttributeData(theReply);
	    break;

	case 4: //response is from a getPrintMap request
	    var theMapURL = "";
	    var theScaleURL = "";

	    //extract the image URL
		theMapURL = getImageURL();
		theScaleURL = getScaleURL();

		if (aObjectIDsToShow.length > 0){
            // get Symbols from post-frame
            getSymbols();
        }

        thePrintMapWindow.document.getElementById("theMap").innerHTML = writeMapDiv(theMapURL,theScaleURL, thePrintMapWindow.minxPrint, thePrintMapWindow.minyPrint, thePrintMapWindow.maxxPrint, thePrintMapWindow.maxyPrint, thePrintMapWindow.mapWidthPrint, thePrintMapWindow.mapHeightPrint,"print");

	    break;
	}
	hideRetrieving();
}

function getBoundingBox() {

	var theBoundingBox = new Array();
    var thePostForm = PostFrame.document.forms[0];

    //get the bounding box
    theBoundingBox = thePostForm.BoundingBox.value.split(';');

	return theBoundingBox;
}

function getImageURL() {

	var thePostForm = PostFrame.document.forms[0];
    var theURL = thePostForm.mapURL.value;

	return theURL;
}

function getScaleURL() {

	var thePostForm = PostFrame.document.forms[0];
    var theScaleURL = thePostForm.scaleURL.value;

	return theScaleURL;
}

function redraw () {
    // refresh the map
    getMap();
}

function showInMap (llX, llY, urX, urY, showPin, layer, theID, theGroupID) {

    var layerToShow = new Array();

    // set the new extends
    minx = parseFloat(llX);
    miny = parseFloat(llY);
    maxx = parseFloat(urX);
    maxy = parseFloat(urY);

    // mark layer if defined
    if (layer && layer != "null"){
        checkZoomLevel();   // check the requested bounding box

        if (layer.length > 0 && layer !='undefined' && typeof(LLFrame) != 'undefined'){
            // find the different layers
            layerToShow = layer.split(',');
            // get layerlist
            theLayerList = LLFrame.document.LLForm.LayerList;
            theLayerList.selectedIndex = -1;

            for (j=0; j< layerToShow.length; j++){
                if ((layerToShow[j]-1) <= theLayerList.length ){
                    theLayerList.options[(layerToShow[j]-1)].selected = true;
                }
            }

        }
    }

    // if symbols is already blinking stop timer
	stopBlinkTimer();

    // add id of group to show the symbols
    if (theGroupID){
        addSymbol(theGroupID);
    }
    else if(theID) {
        addSymbol(theID);
    }

    // add id to array -> higlighting is processed after map-rquest
    aHighlightSymbols[0] = theID;

    // show pin
    if (showPin == 1) {
        displayPin (parseFloat((minx+maxx)/2), parseFloat((maxy+miny)/2));
        //alert('Show the Pin');
    }

    // request the new map
    getMap();
}

function displayRetrieving(){
    MapFrame.document.getElementById("retrieving").style.visibility="visible";
}

function hideRetrieving(){
    MapFrame.document.getElementById("retrieving").style.visibility="hidden";
}

