/*********************************************************************************
 Copyright (c) 2003-2006 Armin Burger
 
 Permission is hereby granted, free of charge, to any person obtaining 
 a copy of this software and associated documentation files (the "Software"), 
 to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 and/or sell copies of the Software, and to permit persons to whom the Software 
 is furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included 
 in all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 
 FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR OR 
 COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 
 IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 
 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 --------------------------------------------------------------------------------
 
 EXAMPLES FOR XMLHTTP TAKEN FROM DREW MCLELLAN ON
 http://www.xml.com/pub/a/2005/02/09/xml-http-request.html
 with additional ideas/concepts from 
 Chirp Internet: www.chirp.com.au
 
**********************************************************************************/

var xn = 0;
var maploading = false;



/**
 * GENERIC XMLHTTP FUNCTIONS
 */
function AjaxRequest()
{
    var req;
   
    //var method = "GET";
    //var nocache = true;
    
    this.loadXMLDoc = function(url) 
    {
        // branch for native XMLHttpRequest object
        if (window.XMLHttpRequest) {
            try {
                req = new XMLHttpRequest();
            } catch(e) {
                req = false;
            }
        // branch for IE/Windows ActiveX version
        } else if (window.ActiveXObject) {
            try {
                req = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(e) {
                try {
                    req = new ActiveXObject("Microsoft.XMLHTTP");
                } catch(e) {
                    req = false;
                }
            }
        }
        
        if (req) {
            req.onreadystatechange = processReqChange;
            // avoid caching by adding arbitrary values
            //url += '&zxyq=' + (new Date()).getTime();
            req.open("GET", url, true);
            req.send(null);
        }
    }
    
    
    var processReqChange = function()
    {
        // only if req shows "complete"
        if (req.readyState == 4) {
            // only if "OK"
            //if (req.status == 0 || req.status == 200) {
            if (req.status == 200) {
                // processing statements go here
                eval('response = ' + req.responseText);
                method = response.method;
                
                eval(method + '(\'\',' + req.responseText + ')');
                
            } else {
                
            }
        }
    }
}



/*==================================================================================================*/


/******************************************
 * P.MAPPER-RELATED XMLHTTP FUNCTIONS
 ******************************************/

/**
 * For loading/updating the MAP
 */
function updateMap(url, response) {
    var loadObj = document.getElementById("loading");

    if (response != '') {     
        // Response mode
        // Reload application when PHP session expired
        var sessionerror = response.sessionerror;
        if (sessionerror == 'true') {
           errormsg = localeList['sessionExpired']; 
           //alert(errormsg);
           window.location.reload();
           return false;
        }
        
        var rBxL = response.refBoxStr.split(',');
        //var refW = response.refW;
        //var refH = response.refH;
        minx_geo = parseFloat(response.minx_geo);
        maxy_geo = parseFloat(response.maxy_geo);
        xdelta_geo = parseFloat(response.xdelta_geo);
        ydelta_geo = parseFloat(response.ydelta_geo);
        var geo_scale = response.geo_scale;
        var urlPntStr = response.urlPntStr;
        
        // Load new map image
        loadMapImg(response.mapURL);
        
        
        // Check if TOC has to be updated
        var tocStyle = response.tocStyle;
        var refreshToc = eval(response.refreshToc);
        refreshToc = true;
        if (refreshToc) {
            var tocurl = PM_XAJAX_LOCATION + 'x_toc_update.php?' + SID;
            updateTocScale(tocurl, '');
        }
        
        //alert(geo_scale);
        
        // Scale-related activities
        writescale(geo_scale);
        setSlider(geo_scale);
        pMap_setMapScale(geo_scale);
        
        
        // Reference image: set DHTML objects
        setRefBox(rBxL[0], rBxL[1], rBxL[2], rBxL[3]);
        
        // reset cursor
        setCursor(false);
        
        // Update SELECT tool OPTIONs in case of 'select' mode
        var varformMode = $("varform").mode.value;
        //alert(varformMode);
        if (varformMode == 'nquery' || varformMode == 'iquery') {
            var selurl = PM_XAJAX_LOCATION + 'x_select.php?'+ SID + '&activegroup=' + getSelectLayer() ;
            updateSelectTool(selurl, '');
        }
        
        // If measure was active, delete all emasure elements
        if (varformMode == 'measure') resetMeasure();
        
        
        //Update map link
        var dg = getLayers();
        var maxx_geo = xdelta_geo + minx_geo;
        var miny_geo = maxy_geo - ydelta_geo;
        var me = minx_geo + ',' + miny_geo + ',' + maxx_geo + ',' + maxy_geo;
        var confpar = config.length > 0 ? '&config=' + config : '';
        var urlPntStrPar = urlPntStr.length > 1 ? '&up=' + urlPntStr : '';
        var loc = window.location;
        var linkhref = loc.protocol + '//' + loc.hostname + loc.port + loc.pathname + '?dg=' + dg + '&me=' + me + '&language=' + gLanguage + confpar + urlPntStrPar; 

        $('current_maplink').href = linkhref;
         
    } else {
        // Input mode
        //if (maploading == false) {
            maploading = true;
            loadObj.style.visibility = "visible";
            var req = new AjaxRequest();   
            req.loadXMLDoc(url);
        //}
    }   
}

/**
 * Substitution for .innerHTML = ...
 */
function setInnerHTML(elementId , html){
	var el = $('toc');
	el.innerHTML = html; 
    evalInnerJS(el);
}

function evalInnerJS(element) {
	var scripts = element.getElementsByTagName('script');
	var code;
	for (var i = 0; i < scripts.length; i++) {
		code =	scripts[i].innerHTML ? scripts[i].innerHTML : 
			scripts[i].text ? scripts[i].text : 
			scripts[i].textContent;
		try {
			eval(code);
		} catch(e) {
			alert(e);
		}
	}
}


/**
 * Update the TOC 
 */
function updateToc(tocurl, response) {
    if (response != ''){     
        // Response mode
        var tocHTML = response.tocHTML;        
                        
        setInnerHTML('toc',tocHTML);        
        legendContainer.legTxt = tocHTML;
        
        var tocurl = PM_XAJAX_LOCATION + 'x_toc_update.php?' + SID;
        //window.setTimeout("updateTocScale(tocurl, ''))", 300);
        updateTocScale(tocurl, '');
        
    } else {
        // Input mode
        var req = new AjaxRequest();   
        req.loadXMLDoc(tocurl);
    }   
}


/**
 * Update toc applying different styles to visible/not-visible layers
 */
function updateTocScale(tocurl, response) {
    // Response mode
    if (response != '') {
        var layers = response.layers;
        
        for (var l in layers) {
            var spanList = document.getElementsByTagName('span');
            var sl = spanList.length;
            for (var s=0; s<sl; s++) {
                var spanObj = spanList[s];                 
                if (spanObj.id.indexOf( 'spxg_' + l) != -1) {
                    spanObj.className = layers[l];
                }
            }
        }
        
    } else {
        // Input mode
        var req = new AjaxRequest();   
        req.loadXMLDoc(tocurl);
    }   
}



/**
 * Show legend over MAP
 */
function showMapLegend(tocurl, response) {
    if (response != ''){     
        // Response mode
        var tocHTML = response.tocHTML;
       // alert(tocHTML);       
        var legDiv = $('maplegend');                
        //alert("legDiv = "+legDiv);
        setInnerHTML('maplegend',tocHTML);
        legDiv.style.visibility = 'visible';
    } else {
        // Input mode
        var req = new AjaxRequest();   
        req.loadXMLDoc(tocurl);
    }   
}


/**
 * Swap from TOC to LEGEND view
 */
function swapLegend(tocurl, response) {
    //alert(tocurl);
    if (response != ''){     
        // Response mode
        var tocHTML = response.tocHTML;
        var legDiv = $('toclegend');
        var tocDiv = $('toc');        
        setInnerHTML('toc',tocHTML);
        //legDiv.style.visibility = 'visible';
        //tocDiv.style.visibility = 'hidden';
    } else {
        // Input mode
        var req = new AjaxRequest();   
        req.loadXMLDoc(tocurl);
    }   
}



/** 
 * For SELECT tool 
 */
function updateSelectTool(selurl, response) {
    if (response != ''){     
        // Response mode
        var selStr = response.selStr;
        $('bottomMapFrame').innerHTML = selStr;
    } else {
        // Input mode
        var req = new AjaxRequest();   
        req.loadXMLDoc(selurl);
    }   
}


/**
 * Update layer options list for selection/iquery
 */
function updateSelLayers(mapurl, response) {
    if (response != ''){     
        // Response mode
        var sellayers = response.sellayers;
        
        // Update SELECT tool OPTIONs in case of 'select' mode
        var vMode = $("varform").mode.value;
        if (vMode == 'nquery' || vMode == 'iquery') {
            var selurl = PM_XAJAX_LOCATION + 'x_select.php?'+ SID + '&activegroup=' + getSelectLayer() ;
            updateSelectTool(selurl, '');
        }
        
    } else {
        // Input mode
        var req = new AjaxRequest();   
        req.loadXMLDoc(mapurl);
    }
}


/**
 * Add point of interest to map
 */
function addPOI(digitizeurl, response) {
    if (response != ''){     
        // Response mode
        var txt = response.retvalue;
        changeLayersDraw();
        
    } else {
        // Input mode
        var req = new AjaxRequest();   
        req.loadXMLDoc(digitizeurl);
    }
}


/**
 * Get query results and display them by parsing the JSON result string 
 */
function getQueryResult(qurl, response) {
    if (response != ''){     
        // Response mode
        var mode = response.mode;
        var queryResult = response.queryResult;
        
        if (mode != 'iquery') {
            if (infoWin == 'window') {
                openResultwin('info.phtml?'+SID);
            } else {
                $('infoFrame').innerHTML = parseJSON(queryResult, infoWin);
            }
        } else {
            // Display result in DIV and postion it correctly
            showIQueryResults(queryResult);
        }

    } else {
        // Input mode
        var req = new AjaxRequest();   
        req.loadXMLDoc(qurl);
    }   
}


/**
 * Export query result 
 */
function exportQueryResults(url, response) {
    if (response != ''){     
        // Response mode
        //var mode = response.mode;

    } else {
        // Input mode
        var req = new AjaxRequest();   
        req.loadXMLDoc(url);
    }   
}



/**
 * Export query result 
 */
function addWMS(url, response) {
    if (response != ''){     
        // Response mode
        //var mode = response.mode;
        
        initToc();
        
    } else {
        // Input mode
        var req = new AjaxRequest();   
        req.loadXMLDoc(url);
    }   
}

