
/******************************************************************************
 *
 * Purpose: AJAX (XMLHTTP) requests
 * Author:  Armin Burger
 *
 ******************************************************************************
 *
 * Copyright (c) 2003-2006 Armin Burger
 *
 * This file is part of p.mapper.
 *
 * p.mapper is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version. See the COPYING file.
 *
 * p.mapper is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with p.mapper; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 ******************************************************************************/
 
/*******************************************************************************
 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;
var g_event = false;


/**
 * GENERIC XMLHTTP FUNCTIONS
 */
function AjaxRequest()
{
    var req;
   
    //var method = "GET";
    //var nocache = true;
    
    this.init = function(){
		if (window.XMLHttpRequest) {
            try {
                req = new XMLHttpRequest();
            } catch(e) {
                req = false;
            }
        // branch for IE/Windows ActiveX version
        } 
		else if (window.ActiveXObject) {
			var version = ["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
				for (var i=0;i< version.length;i++){
					try{
						req = new ActiveXObject(version[i]);
					}
					catch(ObjException){}
				}
		}
	
	}
	
	
	this.loadXMLDoc = function(url) 
    {
        // branch for native XMLHttpRequest object
        this.init();
        if (req) {
            req.onreadystatechange = processReqChange;
            // avoid caching by adding arbitrary values
            //url += '&zxyq=' + (new Date()).getTime();
            req.open("GET", url, true);
            req.send(null);
        }
    }
	
	
	this.loadTextDoc = function(url,callback){
		this.init();
		if (req) {
            req.onreadystatechange = function(){
				if (req.readyState == 4){
					if (req.status == 200) {
						eval(callback+'(req);');
					}
				}
			};
            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 = ' + Base64.decode(req.responseText));
                eval('response = ' + req.responseText);
                if (response.method){
                    method = response.method;
                    eval(method + '(\'\',response)');
                } else {
                    //eval(Base64.decode(req.responseText));
                    eval(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);
		
		loadScaleBarImg(response.scalebarURL);
        
        
        // 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, '');
        }
        
        
        // 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();
        }

        if (varformMode == 'ruler') {
            resetRuler();
        }       
        
        //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 port = loc.port > 0 ? ':' + loc.port : '';
        var linkhref = loc.protocol + '//' + loc.hostname + port + loc.pathname + '?dg=' + dg + '&me=' + me + '&language=' + gLanguage + confpar + urlPntStrPar; 

        if (_$('current_maplink')) _$('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 {
			//alert(code);
			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;
		// mod : 21 march 09
		var GrpList = getCheckboxGroups();
        for (var i=0;i < GrpList.length;i++){
			document.getElementById(GrpList[i]).checked = false;
		}
		// end mod
		
		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];
                }
				
            }
			if (GrpList.inArray('ginput_'+l)){
				//alert('ginput_'+l);
				document.getElementById('ginput_'+l).checked = true;
			}	
        }
        
    } else {
        // Input mode
        var req = new AjaxRequest();   
        req.loadXMLDoc(tocurl);
    }   
}


function updatePartTocScale(tocurl, response) {
    // Response mode
    if (response != '') {
		var layers = response.layers;
		// mod : 21 march 09
		var GrpList = getCheckboxGroups();
        for (var i=0;i < GrpList.length;i++){
			var flag = false;
			for (var l in layers){
				if (('ginput_'+l == GrpList[i])){
					document.getElementById('ginput_'+l).checked = true;flag = true;
					break;
				}	
			}
			if (!flag) document.getElementById(GrpList[i]).checked = false;
				
		}
		// end mod
		
		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];
                }
				
            }
        }
		
		var layerstring = '&groups=' + getLayers();    
        showloading();
        var mapurl = PM_XAJAX_LOCATION + 'x_load.php?'+SID+'&process=single&zoom_type=zoomfull'+ layerstring;
        updateMap(mapurl, '');
        
    } 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').html(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);
    }
}

function updateMenu(mapurl,response){
	if (response != ''){
		var rhtml = response.value;
		var Cookie = new Cookies();
		if (Cookie.getCookie("mapAccess") != "public" && Cookie.getCookie("mapAccess") != ""){
			$("#cellLeft").html(rhtml);
			initMapMenu();
		}
	}
	else{
		var req = new AjaxRequest();
		req.loadXMLDoc(mapurl);
	}
}

function updateMapPart(parturl,response){
	if (response != ''){
		getListMenu();
		//initMapPath();
		
		var rhtml = response.value;
		$("#cellLeft").html(rhtml);	
		
		
		var tocHTML = response.tocHTML;        
        setInnerHTML('toc',tocHTML);
		
		var tocurl = PM_XAJAX_LOCATION + 'x_toc_update.php?part=update' + SID;
        updatePartTocScale(tocurl, '');
		
	}
	else{
		var req = new AjaxRequest();
		req.loadXMLDoc(parturl);
	}
}


/**
 * 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);
    }
}

function getQueryPrint(printUrl, response) {
    if (response != ''){     
        // Response mode
        var txt = response.value;
        $('#printZone').html(txt);
        
    } else {
        // Input mode
        var req = new AjaxRequest();   
        req.loadXMLDoc(printUrl);
    }
}


function getLog4Auth(log4url,response){
	if (response != ''){
        // Response mode
        var txt = response.value;
        $('#log4AuthZone').html(txt);
		if (response.log ==  "out")
			location.reload(true);	
	}
	else {
		var req = new AjaxRequest();
		req.loadXMLDoc(log4url);
	}
}

function getSearch(searchurl,response){
	if (response != ''){
        // Response mode
        var txt = response.value;
        $('#SearchZone').html(txt);
	}
	else {
		var req = new AjaxRequest();
		req.loadXMLDoc(searchurl);
	}
}

function getQueryDownload(downloadUrl,response){
	if (response != ''){
		var rhtml = response.value;
		$('#downloadZone').html(rhtml);
	}
	else{
		var req = new AjaxRequest();
		req.loadXMLDoc(downloadUrl);
	}
}


/**
 * 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;
		var addQueryResult = response.addQueryResult;
        
        if (mode != 'iquery') {
            if (infoWin == 'window') {
                openResultwin('info.phtml?'+SID);
            } else {
				//alert('level 1');
                //
				var cookie = new Cookies();
				if (cookie.getCookie("mapAccess") != ""){
					if (cookie.getCookie("mapAccess") != "public") {
						showProcDialog('Identify Information of Map',"MIPRIdentifyPanel","infoZone");
						$('#infoZone').html(parseJSON(queryResult,addQueryResult, infoWin));
					}	
					else {
						$('#XDMInfoPopup').html(getShortDescription(queryResult,addQueryResult,infoWin));
						var posXY = new Array(posX, posY);
						whiteBalloon.showTooltip(g_event,'load:infoPopup',posXY);
					}
				}
				else{
					$('#XDMInfoPopup').html(getShortDescription(queryResult,addQueryResult,infoWin));
					var posXY = new Array(posX, posY);
					whiteBalloon.showTooltip(g_event,'load:infoPopup',posXY);
				}
                //sortables_init();
                //ts_alignTables();
           }
        } else {
            // Display result in DIV and postion it correctly
            showIQueryResults(queryResult);
        }

    } else {
        // Input mode
		//alert(qurl);
        var req = new AjaxRequest();   
        req.loadXMLDoc(qurl);
    }   
}


function getSearchResult(qurl, response) {
    if (response != ''){     
        // Response mode
        var mode = response.mode;
        var queryResult = response.queryResult;
		var addQueryResult = response.addQueryResult;
        var depQueryResult = response.depQueryResult;
		
        if (mode != 'iquery') {
            if (infoWin == 'window') openResultwin('info.phtml?'+SID);
            else {
				showProcDialog('Map Search Result',"MIPRIdentifyPanel","infoZone");
				$('#infoZone').html(parseSearchResult(queryResult,addQueryResult,depQueryResult, infoWin));
           }
        } else {
            // Display result in DIV and postion it correctly
            showIQueryResults(queryResult);
        }

    } else {
        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);
    }   
}


function getInfoText(req){
	$('#infoZone').html(req.responseText);
}


