// ===============================================================
// CBkort version 2.x, copyright Carl Bro GIS&IT, 2006
// ===============================================================
// $Archive: /Products/CBKort2/development/2.5/standard_upgrade_01/wwwroot/WEB-INF/config/modules/standard/spatialquery/js/spatialquery.js $ 
// $Date: 5-08-09 14:58 $
// $Revision: 70 $ 
// $Author: Nsm $
// =============================================================== 


//********************************************//
//  Aktivér en søgning                        // 
//  Søgningen gemmes queryResultContainer     //
//********************************************//
var spatialquery_showOnActivate        = false;
var spatialquery_currentQueryResult    = null;

var spatialquery_currentQueryUrl       = null;
var spatialquery_currentSearchText     = '';
var spatialquery_paramHandlers         = new Array();
var spatialquery_resultlayoutHandlers  = new Array();

function spatialquery_doQuery (profilequery, queryurl, searchtext)
{
	// spatialquery_createSelectorDynamiclayer();
	
	spatialquery_currentSearchText = searchtext;
    spatialquery_currentQueryUrl = queryurl;
    
    // Get resultlayout
    var resultlayout = spatialquery_getResultLayout(profilequery);
    // Execute query and show result    
    switch (resultlayout)
    {
        case 'leftbar':
            queryurl = replaceUrlParam('page', 'spatialquery-getresult', queryurl); 
            leftbarsq_showQueryresult(queryurl,searchtext,false,false);
        break;
        case 'leftbarnoreport':
            queryurl = replaceUrlParam('page', 'spatialquery-getresult', queryurl);
            leftbarsq_showQueryresult(queryurl,searchtext,true,false);
        break;
        case 'infobox':
            infobox.query(queryurl,searchtext);
        break;
        case 'default':
        case 'report':
        default:
            var customhandler = false;
            for(var i=0;i < spatialquery_resultlayoutHandlers.length;i++)
            {
                if(spatialquery_resultlayoutHandlers[i].id == resultlayout)
                {
                    spatialquery_resultlayoutHandlers[i].handler(profilequery, queryurl);
                    customhandler = true;
                    i = spatialquery_resultlayoutHandlers.length;
                }
            }
            if(!customhandler)
            {
                queryurl = replaceUrlParam('page', 'spatialquery-getresult-html', queryurl);
                showDivBox('Info', queryurl, false, null, null, '249px', '205px');
            }
        break;
    }
}

function spatialquery_createSelectorDynamiclayer ()
{
    url =  cbKort.getServletUrl();
    url+=  "?page=spatialquery-add-selectordynlayer-from-userdatasource";
    url+=  "&profile="+cbKort.getProfile();
    url+=  "&sessionid="+cbKort.getSessionId();
	
    var request = new CBhttp();
    request.executeUrl(url, false);
	
}


function spatialquery_markAndQuery (wkt, distance, profilequery, seekAllThemes, dynamiclayer, searchtext, keepoptions)
{
    var request = new CBhttp();

    showWaitingBox(cbInfo.getString('standard.message.getting_data'));
     
    // Remove dynamic layers
    var url = cbKort.getServletUrl();
    url += "?page=spatialquery-remove-highlight-dynlayer";
    url += "&sessionid=" + cbKort.getSessionId();
    
    request.executeUrl(url, false);

    // Add new dynamic layer with the polygon
    var url =  cbKort.getFormParamAsUrl();
    url = replaceUrlParam('page', 'spatialquery-get-map-add-dynlayer-from-wkt', url);
    url = replaceUrlParam('zoomdir', '0', url);    
    url = replaceUrlParam('shape_wkt', wkt, url);    
    url = replaceUrlParam('dynamiclayer', dynamiclayer,url);    
    
    updateMapData(getMapDataRequest(url));
    
    //Foretag soegning
    url =  cbKort.getServletUrl();
    url+=  "?page=spatialquery-getresult";
    url+=  "&profilequery="+profilequery;
    url+=  "&profile="+cbKort.getProfile();
    url+=  "&wkt="+wkt;
    url+=  "&sessionid="+cbKort.getSessionId();
    url+=  "&layers="+cbKort.getLayers();
    url+=  "&distance="+distance;
    url+=  "&currentscale="+cbKort.getCurrentScale();
    if (seekAllThemes)
    {  url+= "&seek_all_themes=true";
    }
    if(!keepoptions)
        url = spatialqueryoptions.replaceOptionParams(url);
    
    for(var i=0;i < spatialquery_paramHandlers.length;i++)
    {
        var p = spatialquery_paramHandlers[i]();
        url = replaceUrlParam(p.name, p.value, url);
    }
    
    spatialquery_doQuery (profilequery, url, searchtext)
    
    hideWaitingBox();
}    


function spatialquery_getResultLayout(profilequery)
{
    var resultlayout = '';
    
    var xpath;
    if(profilequery)
    {
        xpath = '/profile/queries/spatialquery[@name="' + profilequery + '"]/@resultlayout';
        resultlayout = cbKort.getProfileParam (xpath);
    }
    
    if (resultlayout==null || resultlayout=='')
    {
       xpath = "/profile/queries/defaults/resultlayout";
       resultlayout = cbKort.getProfileParam (xpath);
    }
    
    if(resultlayout==null || resultlayout=='')
    {
       alert(cbInfo.getString('spatialquery.error.no_resultlayout_in_profile'));
    }

    return resultlayout;
}

function spatialquery_getQueryResult (queryurl, searchText) 
{
    var queryResult = new QueryResult(searchText);
    queryResult.searchURL = queryurl;
    
    var request = new CBhttp();

    var result = request.executeUrl(queryurl, false);
    
    if (result==null)
    {  return null;
    }
    
    result = result.get(0);
    var targets = result.get("targethits");

    var misc = result.get("misc");
    if (misc!=null)
    {   var col = misc.get('querystring');
        if (col!=null) 
        {  var querystring = col.getValue();
           queryResult.queryString = querystring;
        }
    }
    
    if (targets==null)
    {  // Maybe there is an extra PComposite around the result
       targets = result.get(1);
       targets = targets.get("targethits");   
    }
    
    // Løber alle targets igennem. Targets er en pcomposite.    
    
    for (var i=0; targets!=null && i<targets.size(); i++) 
    {
        var target = targets.get(i);
        	
        var targetName = '';
        var targetNumber = '';
        
        var header = '';
        var expand = true;
        var warning = null;
        var errorText = '';
            
        var i2 = 0;
            
        // Get static text elements 
        while (i2<target.size() && target.get(i2).isColumn())
        {
           var text = target.get(i2); 
           var name  = text.getName();
           var value = text.getValue();	

           if(name=="targetname")
           {  targetName = value;
           }
           else if(name=="targetnumber")
           {  targetNumber = value;
           }
           else if(name=="overskrift" || name=="header")
           {   header = value;
           } 
           else if(name=="expanded" || name=="expand")
           {
               if(value == 'false')
               {  expand = false;
               }
           }
           else if(name=="warning")
           {  warning = value;
           }
           else if(name=="errortext")
           {  errorText = value;
           }
           
           i2++;
        }   
    
        var queryResultTarget = queryResult.addTarget(targetName, targetNumber, header, expand, warning, errorText);
            
        // Løb alle hits igennem.
        while (i2<target.size() && target.get(i2).isRowList())
        {  
        	var hit = target.get(i2);

            var queryResultTargetHit = queryResultTarget.addTargetHit();

            // Løb alle værdier i et hit igennem. Hit er en rowlist.
            for(var h = 0; h < hit.size(); h++)
            {
               var presRow = hit.row(h);

               var l = presRow.column("label").getValue();
               if(l == null)
                   l = '';
               var v = presRow.column("value").getValue();
               if(v == null)
                   v = '';

               var val = 
               {  value:v,
                  label:l,
                  format:presRow.column("format").getValue()
               };
                       
               queryResultTargetHit.addValue(val);
               queryResult.lasthit = h + '_' + h;
            }   
            i2++;
        }
    }
    
    var selectors = result.get("selectors");
    
    if (selectors!=null)
    {
    	var selector = selectors.get("selector");
    	if (selector!=null)
        {  queryResult.selectorPcolId = selector.getId();
        }
    }
    
    return queryResult
}

function spatialquery_removedynlayer()
{
    showWaitingBox();
    cbKort.removeSearchResults('dynlayer_remove_user');
}

//********************************************//
//  Håndtering af flere søgeresultater        //
//  Et søgeresultat kan gemmes og hentes frem //
//********************************************//


function spatialquery_getQueryResultTargetHit (targetId,targetHitId)
{
    return spatialquery_currentQueryResult.targets[targetId].targetHits[targetHitId];
}


function spatialquery_showSearchElementInMap()
{
    var res = spatialquery_currentQueryResult;
    if (res!=null)
    {  var pcolid = res.selectorPcolId;
       var displaybuffer = '25+pct!400+minimum';    
       spatialquery_showInMap(pcolid, displaybuffer);    
    }
}

function spatialquery_showInMap(pcolid, displaybuffer)
{
    showWaitingBox();
    setTimeout('spatialquery_showInMapExecute("'+pcolid+'","'+displaybuffer+'")',100);
}

function spatialquery_showInMapExecute(pcolid, displaybuffer)
{
    if(!displaybuffer)
        displaybuffer = '25+pct!400+minimum';
    
    var request = new CBhttp();

    var url = cbKort.getServletUrl();
    url += "?page=spatialquery-remove-highlight-dynlayer";
    url += "&sessionid=" + cbKort.getSessionId();

    request.executeUrl(url, false);


    var url = cbKort.getServletUrl();
    url += "?page=spatialquery-add-dynlayer-from-pcolid";
    if(pcolid) //case: found object
    {
        url += "&savename=last_sq_result";
        url += "&pcolid=" + pcolid;
    }
    else  //case: selector object
    {
        url += "&savename=spatialquery_selectors";
    }
    url += "&dynamiclayer=user*"; 
    url += "&append=false";
    url += "&sessionid=" + cbKort.getSessionId();

    request.executeUrl(url, false);

    var url = cbKort.getFormParamAsUrl();
    url = replaceUrlParam('page','spatialquery-get-map-zoom-to-datasource',url);
    url = replaceUrlParam('datasource','userdatasource',url);
    url = replaceUrlParam('displaybuffer',displaybuffer,url);
    url = replaceUrlParam('zoomdir','0',url);
    // create map 
    updateMapData(getMapDataRequest(url));

    hideWaitingBox();
}

//********************************************//
//  Dan rapport                               //
//********************************************//
function spatialquery_printReport(url, searchtext, page, targetlist, includeheader) 
{
    if (targetlist!=null && targetlist!='')
    {
        url = replaceUrlParam('sessionid', cbKort.getSessionId(), url);
        url = replaceUrlParam('page', page, url);
        url = replaceUrlParam('targetlist', targetlist, url);
        url = replaceUrlParam('stext_base64', encode64(searchtext), url);
        url = replaceUrlParam('dato', formatDate(new Date(), "dd-MM-yyyy"), url);
        url = replaceUrlParam('includeheader', includeheader, url);
        url = replaceUrlParam('seek_all_themes', "true", url);
        for(var i=0;i < spatialquery_paramHandlers.length;i++)
        {
            var p = spatialquery_paramHandlers[i]();
            url = replaceUrlParam(p.name, p.value, url);
        }
        //window.open(url, 'report', 'toolbar=no,location=no,directories=no,status=yes,menubar=yes,resizable=yes,scrollbars=yes,width=800,height=500,left=50,top=50');
        postToTarget(url);
    }
    else
        alert (cbInfo.getString('spatialquery.report.morethanone'));
}

//********************************************//
//  Param registration                        //
//  register a handler to return name and     //
//  value (see example)                       //
//********************************************//
function spatialquery_registerParamHandler(handler)
{
    spatialquery_paramHandlers[spatialquery_paramHandlers.length] = handler;
}
/*
function spatialquery_example()
{
    return {name:'paramname',value:'myvalue'};
}
spatialquery_registerParamHandler(spatialquery_example);
*/

//********************************************//
//  Resultlayout registration                 //
//  register a handler to run the query       //
//********************************************//
function spatialquery_registerResultlayoutHandler(id, handler)
{
    spatialquery_resultlayoutHandlers[spatialquery_resultlayoutHandlers.length] = {id:id,handler:handler};
}




//********************************************//
//  Spatialqueryoptions handling              //
//  register a handler to run the query       //
//********************************************//
function Spatialqueryoptions()
{
    this.buffer = null;
    this.target = null; // containing targetset, targetsetfile and seekallthemes
    this.targetid = null;
    this.dialog = null;
}
Spatialqueryoptions.prototype.check = function()
{
    if(this.buffer == null)
        this.buffer = 0;
    if(this.target == null)
        this.setTarget();
}
Spatialqueryoptions.prototype.getBuffer = function()
{
    if(this.buffer == null)
        this.buffer = 0;
    return this.buffer;
}
Spatialqueryoptions.prototype.setBuffer = function(buffer)
{
    this.buffer = buffer;
}
Spatialqueryoptions.prototype.getTarget = function()
{
    if(this.target == null)
        this.setTarget();
    return this.target;
}
Spatialqueryoptions.prototype.setTarget = function()
{
    var url = cbKort.getServletUrl();
    url += "?page=targetselector-get-config";
    url += "&targetselector="+cbKort.getProfile();
    url += "&sessionid=" + cbKort.getSessionId();
    this.target = cbhttp_getRequestJSON(url);
    if(!this.target || !this.target.targetset)
    {
        url = replaceUrlParam('targetselector', 'default', url);            
        this.target = cbhttp_getRequestJSON(url);
    }
    for (var i=0;i<this.target.targetset.length;i++)
    {
        if(this.target.targetset[i].defaultselected=='true')
            this.targetid = this.target.targetset[i].name;
    }
}
Spatialqueryoptions.prototype.getTargetset = function(name)
{
    for (var i=0;i<this.target.targetset.length;i++) 
    {
        var tname = this.target.targetset[i].name || 'ts'+i;
        if(tname == name)
            return {
                targetset:this.target.targetset[i].targetname || false,
                targetsetfile:(this.target.targetset[i].targetsetfile || false),
                seekallthemes:(this.target.targetset[i].seekallthemes=='false' ? false : true)
            }
    }
    return false;
}
Spatialqueryoptions.prototype.setTargetset = function(name)
{
    if(this.getTargetset(name))
        this.targetid = name;
}
Spatialqueryoptions.prototype.getOptionDialogContent = function(useparent)
{
    this.check();
    var displayname = (this.target.displayname || cbInfo.getString('spatialquery.options.dialog.targetselectortext'));
    
    var h =' <table class="divtable" style="width:100%;padding:3px;">' +
           '  <tr><td>'+cbInfo.getString('spatialquery.options.dialog.buffer')+'</td><td align="right"><input id="spatialquryoption_buffer" style="width:50px;text-align:right;" value="'+this.buffer+'" onchange="'+ (useparent ? 'parent.' : '') +'spatialqueryoptions.setBuffer(this.value);"/></td></tr>' +
           '  <tr><td colspan="2">' +
           '   <div>'+displayname+'</div>' +
           '   <select class="spatialquryoption_target" style="width:100%" onchange="'+ (useparent ? 'parent.' : '') +'spatialqueryoptions.setTargetset(this.options[this.options.selectedIndex].value);">';
            for (var i=0;i<this.target.targetset.length;i++) 
            {
                var tname = this.target.targetset[i].name || 'ts'+i;
                var tdisplayname = this.target.targetset[i].displayname || tname;
                var tdefault = (this.targetid==tname ? true : false);
                h += '    <option value="'+tname+'"'+ (tdefault ? ' selected="selected"' : '') +'>'+tdisplayname+'</option>';
            }
       h+= '   </select>' +
           '  </td></tr>' +
           ' </table>';
    return h;
}
Spatialqueryoptions.prototype.replaceOptionParams = function(url)
{
    this.check();
    
    var selectedtarget = this.getTargetset(this.targetid);
    url = replaceUrlParam('distance', this.buffer || 0, url);

    if(selectedtarget.targetset)
        url = replaceUrlParam('targetset', selectedtarget.targetset, url);
    
    var s = selectedtarget.targetsetfile;
    if(selectedtarget.targetsetfile) {
        selectedtarget.targetsetfile = selectedtarget.targetsetfile.replace(/\\/g,'/');
        url = replaceUrlParam('targetsetfile', selectedtarget.targetsetfile, url);
    }
    
    if(selectedtarget.seekallthemes)
        url = replaceUrlParam('seek_all_themes', 'true', url);
    else
        url = replaceUrlParam('seek_all_themes', '', url);

    return url;
}

Spatialqueryoptions.prototype.showOptionDialog = function()
{
    if(!this.dialog)
    {
        this.dialog = new Dialog(cbInfo.getString('spatialquery.options.dialogtitle'));
        var h = '<table class="divtable" style="width:100%">' +
                '    <tr> ' +
                '      <td colspan="2"><span id="optionsdialog_options"></span></td>' +
                '    </tr>' +
                '    <tr style="height:5px"><td></td></tr>' +
                '    <tr align="right">' +
                '        <td colspan="2">' +
                '            <button class="menubutton" onclick="spatialqueryoptions.dialog.hideDialog();">'+cbInfo.getString('standard.button.close')+'</button>' +
                '        </td>' +
                '    </tr>' +
                '</table>';
        this.dialog.addContentHTML(h);
    }
    getElement('optionsdialog_options').innerHTML = spatialqueryoptions.getOptionDialogContent();
    this.dialog.showDialog();
}

var spatialqueryoptions = new Spatialqueryoptions();









var reportselector_result;
function getReportselector(e)
{
    e.options.length = 0;
    if(!reportselector_result)
    {
        var url = cbKort.getServletUrl();
        url += "?page=reportselector-get-config";
        url += "&reportselector="+cbKort.getProfile();
        url += "&sessionid=" + cbKort.getSessionId();
        reportselector_result = cbhttp_getRequestJSON(url);
        if(!reportselector_result || !reportselector_result.template)
        {
            url = replaceUrlParam('reportselector', 'default', url);            
            reportselector_result = cbhttp_getRequestJSON(url);
        }
    }
    for (var i=0;i<reportselector_result.template.length;i++) 
    {
        var displayname = reportselector_result.template[i].displayname;
        var page = reportselector_result.template[i].page;
        var defaultselected = (reportselector_result.template[i].defaultselected=='true' ? true : false);
        e.options[e.options.length] = new Option(displayname,page,defaultselected,defaultselected);
    }
    return;
}





















function Areasearch()
{
    this.dialog;
    this.dialogWidth = '215px';
    this.drawer;
    this.wkt;
}
Areasearch.prototype.init = function()
{
    var opts = {
        "silent":"true"
    }; 
    CBMapDrawer_drawPolygon(this,opts);
    
    this.showDialog();
}
Areasearch.prototype.createDialog = function()
{
    if(!this.dialog)
    {
        this.dialog = new Dialog(cbInfo.getString('spatialquery.sqarea.dialogtitle'),areasearch.close);
        var h = '<table class="divtable">' +
                '    <tr align="left">' +
                '        <td colspan="2">'+cbInfo.getString('spatialquery.sqarea.hint')+'</td>' +
                '    </tr>' +
                '    <tr> ' +
                '      <td colspan="2"><span id="areasearch_options"></span></td>' +
                '    </tr>' +
                '    <tr style="height:5px"><td></td></tr>' +
                '    <tr align="right">' +
                '        <td colspan="2">' +
                '            <button class="menubutton" id="areasearchOKbutton" onclick="areasearch.search();">'+cbInfo.getString('standard.button.ok')+'</button>' +
                '            <button class="menubutton" onclick="areasearch.init();">'+cbInfo.getString('standard.button.reset')+'</button>' +
                '        </td>' +
                '    </tr>' +
                '</table>';
        this.dialog.setDialogWidth(this.dialogWidth);
        this.dialog.addContentHTML(h);
    }
    getElement('areasearch_options').innerHTML = spatialqueryoptions.getOptionDialogContent();
}
Areasearch.prototype.showDialog = function()
{
    this.createDialog();
    this.dialog.showDialog();
}
Areasearch.prototype.closeDialog = function()
{
    this.dialog.hideDialog();
    this.close();
}
Areasearch.prototype.close = function()
{
    if(cbmapdrawer_currentDrawer)
        cbmapdrawer_currentDrawer.dialogCancel();
}
Areasearch.prototype.search = function()
{
    if(cbmapdrawer_currentDrawer)
    {
        cbmapdrawer_currentDrawer.drawOK();
        if(!this.wkt)
            return;
    }
    this.closeDialog();

    var distance      = '0';
    var searchtext    = cbInfo.getString('spatialquery.sqarea.searchtext');
    var profilequery  = 'areasearch';
    var dynamiclayer  = 'userpolygon';

    spatialquery_markAndQuery (this.wkt, distance, profilequery, true, dynamiclayer, searchtext)
}
Areasearch.prototype.onDrawSuccess = function(CBMapDrawer)
{
    this.wkt = CBMapDrawer.getWKT();
}
var areasearch = new Areasearch();




function Searchlast()
{
    this.dialog;
}
Searchlast.prototype.init = function()
{
    this.showDialog();
}
Searchlast.prototype.createDialog = function()
{
    if(!this.dialog)
    {
        this.dialog = new Dialog(cbInfo.getString('spatialquery.lastdisplayed.dialogtitle'));
        var h = '<table class="divtable" style="width:100%">' +
                '    <tr align="left">' +
                '        <td colspan="2">'+cbInfo.getString('spatialquery.lastdisplayed.hint')+'</td>' +
                '    </tr>' +
                '    <tr> ' +
                '      <td colspan="2"><span id="searchlast_options"></td>' +
                '    </tr>' +
                '    <tr style="height:5px"><td></td></tr>' +
                '    <tr align="right">' +
                '        <td colspan="2">' +
                '            <button class="menubutton" onclick="searchlast.search();">'+cbInfo.getString('standard.button.ok')+'</button>' +
                '            <button class="menubutton" onclick="searchlast.closeDialog();">'+cbInfo.getString('standard.button.cancel')+'</button>' +
                '        </td>' +
                '    </tr>' +
                '</table>';
        this.dialog.addContentHTML(h);
    }
    getElement('searchlast_options').innerHTML = spatialqueryoptions.getOptionDialogContent();
}
Searchlast.prototype.showDialog = function()
{
    this.createDialog();
        
    this.dialog.showDialog();
}
Searchlast.prototype.closeDialog = function()
{
    this.dialog.hideDialog();
}
Searchlast.prototype.search = function()
{
    showWaitingBox(cbInfo.getString('standard.message.getting_data'));
    
    this.closeDialog();
    
    var url = cbKort.getServletUrl();
    url+=  "?page="+getResultPage();
    url+=  "&layers="+cbKort.getLayers()
    url+=  "&profile="+cbKort.getProfile();
    url+=  "&profilequery=userdatasource";
    url+=  "&sessionid="+cbKort.getSessionId();
    url+=  "&currentscale="+cbKort.getCurrentScale();

    url = spatialqueryoptions.replaceOptionParams(url);
    
    for(var i=0;i < spatialquery_paramHandlers.length;i++)
    {
        var p = spatialquery_paramHandlers[i]();
        url = replaceUrlParam(p.name, p.value, url);
    }

    spatialquery_doQuery("userdatasource", url, cbInfo.getString('spatialquery.lastdisplayed.searchtext'), null);
    
    hideWaitingBox();
}
var searchlast = new Searchlast();
