// ===============================================================
// CBkort version 2.x, copyright Carl Bro GIS&IT, 2006
// ===============================================================
// $Archive: /Products/CBKort2/development/2.6/standard/wwwroot/WEB-INF/config/modules/standard/multiselect2/js/multiselect.js $ 
// $Date: 27-09-11 12:09 $
// $Revision: 32 $ 
// $Author: Nsm $
// =============================================================== 

   var multiselect_globalCbHttp  = null;

            
   function Multiselect () 
   {
      this.dialogPage               = "multiselect-show-selectbox";
      this.getSavedLocateResultPage = "multiselect-read-datasource";
   
      this.startextent = null;

      this.multiselect = null;      
      this.selectors = new Array();
      this.nselectors = 0;

      this.divBoxWidth = '245px';
      this.divBoxHeight = '250px';

      this.baseQueryUrl = null;
      this.queryUrl = null;
      
      this.actionParams = new Array();
      
      this.actionHandler= null;
      this.auxActionHandler= null;      
      this.autoActionHandler= null;    
      
      this.useQuery = false;
      this.useAutoAction = true;
      
      this.seekAllThemes = "true";
      
      this.searchtext = '';
      
      this.isAutoActionDone = false;

      this.divBoxTop;
      this.divBoxLeft;
      
      this.autoAction = false;
      this.topPos = -1;
      
      this.dynLayerName = 'userdatasource';
      this.gui = null;
      
      this.cache = [];
   }
   
   // *************************************************************
   //  Globals
   // *************************************************************

   var multiselect = new Multiselect();
   
   // *************************************************************
   //  Reset
   // *************************************************************
   
   Multiselect.prototype.reset = function () 
   {
      this.startextent = null;

      this.multiselect = null;      
      this.selectors = new Array();
      this.nselectors = 0;

      this.divBoxWidth = '245px';
      this.divBoxHeight = '270px';

      this.queryUrl = this.baseQueryUrl;

      this.actionParams = new Array();

      this.actionHandler= null;
      this.auxActionHandler= null;
      this.autoActionHandler= null;      

      this.closeOnExit = true;

      this.seekAllThemes = "true";   
      
      this.isAutoActionDone = false;         
   }
   
   // *************************************************************
   //  Initialize a new multiselect
   // *************************************************************
   
   Multiselect.prototype.initDo = function 
   (  multiselect_, 
      title_, 
      width_, 
      height_,
      actionHandler_,
      auxActionHandler_,
      autoActionHandler_,
      useQuery_,
      useAutoAction_,
      closeOnExit_,
      left_,
      top_
   )
   {  this.useQuery = useQuery_;
      this.useAutoAction = useAutoAction_;
      this.init (multiselect_, title_, width_, height_, actionHandler_, auxActionHandler_, autoActionHandler_, left_, top_);
      this.closeOnExit = closeOnExit_;
   }

   Multiselect.prototype.initFind = function 
   (  multiselect_, 
      title_, 
      width_, 
      height_ 
   )
   {  this.useQuery = false;
      this.init (multiselect_, title_, width_, height_, this.locate, null, this.locate);
      this.closeOnExit = true;
   }

   Multiselect.prototype.initFindWithQuery = function 
   (  multiselect_, 
      title_, 
      width_, 
      height_ 
   )
   {  this.useQuery = true;
      this.init (multiselect_, title_, width_, height_, this.locate, this.query, this.locate);
      this.closeOnExit = true;
   }


   Multiselect.prototype.initQuery = function 
   (  multiselect_, 
      title_, 
      width_, 
      height_ 
   )
   {  this.useQuery = true;
      this.init (multiselect_, title_, width_, height_, this.query, null, this.locate);
      this.closeOnExit = true;
   }
           
   Multiselect.prototype.init = function 
   (  multiselect_, 
      title_, 
      width_, 
      height_, 
      actionHandler_,
      auxActionHandler_,
      autoActionHandler_,
      left_,
      top_
   )
   {
      this.reset();
      
      this.divBoxLeft = (cbKort.mapX+10)+'px';
      if(left_)
          this.divBoxLeft = left_;
      this.divBoxTop = (cbKort.mapY+10)+'px';
      if(top_)
          this.divBoxTop = top_;

      this.startextent = cbKort.getExtentAsString();

      if (width_!=null)
      {  this.divBoxWidth = width_;
      }
      
      if (height_!=null)
      {  this.divBoxHeight = height_;
      }
      
      this.multiselect       = multiselect_;      
      this.baseQueryUrl      = cbKort.getFormParamAsUrl();
      this.queryUrl          = this.baseQueryUrl;

      this.actionHandler     = actionHandler_;
      this.auxActionHandler  = auxActionHandler_;
      this.autoActionHandler = autoActionHandler_;

      var useAutoAction = "true";
      if (!this.useAutoAction) 
      {  useAutoAction = "false";
      }
      
      var useAuxAction  = (this.auxActionHandler != null);

      var useQuery      = "false";
      if (this.useQuery) 
      {  useQuery = "true";
      }

      var profile = cbKort.getProfile();
      var sessionid = getSessionId();
        
      var src = '/cbkort?page='+this.dialogPage+'&profile='+profile+'&multiselectname='+this.multiselect+'&sessionid='+sessionid+'&autoaction='+useAutoAction+'&auxaction='+useAuxAction+'&query='+useQuery;
      
      showDivBox(title_, src, true, this.divBoxLeft, this.divBoxTop, this.divBoxWidth, this.divBoxHeight);
   }  

   // *************************************************************
   //  Add new selector
   // *************************************************************
   Multiselect.prototype.addSelector = function 
   (   name,
       text, 
       postVar, 
       displayVar, 
       processText, 
       nullDisplayText, 
       exceptionText, 
       queryParams,
       locate,
       spatialQueryParams
   )
   {
       this.nselectors++;
       this.selectors[this.selectors.length] = 
       {  name:name, 
          text:text, 
          postvar:postVar, 
          displayvar:displayVar, 
          processtext:processText, 
          nulldisplaytext:nullDisplayText, 
          exceptiontext:exceptionText, 
          queryparams:queryParams,
          locate:locate,
          spatialQueryParams:spatialQueryParams
       };
   }
   
   // *************************************************************
   //  Simple setters
   // *************************************************************

   Multiselect.prototype.setActionParameters = function(params)
   {
      this.actionParams = params;
   }

   Multiselect.prototype.setSeekAllThemes = function(allThemes)
   {
      this.seekAllThemes = allThemes;
   }

   Multiselect.prototype.setSearchText = function(searchtext)
   {
      this.searchtext = searchtext;
   }

   Multiselect.prototype.setAutoActionDone = function(isDone)
   {
      this.isAutoActionDone = isDone;
   }


   // *************************************************************
   //  Simple getters
   // *************************************************************       
       
   Multiselect.prototype.getSelectorCount = function()
   {  return this.nselectors;
   }

   Multiselect.prototype.getSelector = function(index)
   {
       return this.selectors[index];
   }

   Multiselect.prototype.getProcessText = function (index)
   {
       if (index<this.nselectors)
          return this.getSelector(index).processtext;
       else
          return "";   
   }    

   Multiselect.prototype.getNullDisplayText = function (index)
   {
       if (index<this.nselectors)
          return this.getSelector(index).nulldisplaytext;
       else
          return "";   
   }    

   Multiselect.prototype.getExceptionText = function (index)
   {
       if (index<this.nselectors)
          return this.getSelector(index).exceptiontext;
       else
          return "";   
   }    
   
   Multiselect.prototype.isCloseOnExit = function ()
   {
       return this.closeOnExit;
   }    
   
   Multiselect.prototype.getSearchText = function()
   {
      return this.searchtext;
   }
   
   // *************************************************************
   //  Actions
   // *************************************************************

   Multiselect.prototype.doAction = function (postValue)
   {  this.actionHandler(postValue);
   }

   Multiselect.prototype.doAuxAction = function (postValue)
   {  this.auxActionHandler(postValue);
   }

   Multiselect.prototype.doAutoAction = function (postValue)
   {  this.autoActionHandler(postValue);
      this.isAutoActionDone = true;  
   }
   
   Multiselect.prototype.locate = function (postValue)
   {
       if (!this.autoAction) {
           this.locatePos (this.topPos);
       }
       return;
       //
       
       
      var url = this.getActionUrl (postValue);

      url = replaceUrlParam('mapext', 'lastcreatedlayer', url);
      showWaitingBox();
      setHelperframeSrc(url);  
   }

   Multiselect.prototype.getSelectWKT = function (pos) {
      var key = '';
      for (var i=0;i<=pos;i++) {
          if (key!='') {
              key+='___';
          }
          key+=this.selectors[i].currentPostValue;
      }

      var buffer = 0;
      if (this.selectors[pos].locate.displaybuffer) {
          buffer = this.selectors[pos].locate.displaybuffer;
      }
      if (this.selectors[pos].locate.type && this.selectors[pos].locate.type.toUpperCase() == 'WKT') {
         return {wkt:this.selectors[pos].currentPostValue,buffer:buffer};
      } else {
         for (var i=0;i<this.cache.length;i++) {
             if (this.cache[i].key == key) {
                 // use cached wkt
                 return {wkt:this.cache[i].wkt,buffer:buffer};
             }
         }
         if (this.selectors[pos].locate.params) {
             var url = this.getLocateUrl (pos,this.selectors[pos].currentPostValue);
             var cbHttp  = new CBhttp();
             showWaitingBox (cbInfo.getString("standard.message.getting_data") + "...");
             // call server to get wkt
             var pComp = cbHttp.executeUrl(url, false);
             if (pComp!=null && pComp.isPComposite()) {
                 var rowList = pComp.get(0);
                 var wkt = [];
                 for (var i=0;i<rowList.size();i++) {
                     var row = rowList.row(i);
                     if (row!=null) {  
                         var tmpwkt = row.column('shape_wkt').getValue();
                         if (tmpwkt) {
                             wkt.push (tmpwkt)
                         }
                     }
                 }
                 if (wkt.length > 0) {
                     this.cache.push ({key:key,wkt:wkt});
                     hideWaitingBox ();
                     return {wkt:wkt,buffer:buffer};
                 }
             }
             hideWaitingBox ();
         }
      }
      return null;
   }

   Multiselect.prototype.locatePos = function (pos)
   {
      cbKort.log ('Multiselect.locatePos () - ',pos);
      this.gui.diableAuxactionButton (true);
      cbKort.dynamicLayers.remove (this.dynLayerName);
      if (this.selectors[pos].locate) {
         var selectWKT = this.getSelectWKT (pos);
         if (selectWKT && selectWKT.wkt != null) {
            var drawoptions = {
               styles: {
                  fillColor: "#FF0000",
                  fillOpacity: 0.5,
                  pointRadius: 6,
                  strokeColor: "#FF0000",
                  strokeOpacity: 0.5,
                  strokeWidth: 3
               }
            };
            if (this.selectors[pos].locate.styles) {
                 drawoptions.styles = this.selectors[pos].locate.styles;
            }
            if (this.selectors[pos].locate.showlabel && this.selectors[pos].locate.showlabel == 'true') {
            	drawoptions.styles.label = this.searchtext;
            }
            if(!(selectWKT.wkt instanceof Array)) {
                 selectWKT.wkt = [selectWKT.wkt];
            }
            this.feature = [];
            for (var i=0;i<selectWKT.wkt.length;i++) {
                cbKort.dynamicLayers.addWKT ({name:this.dynLayerName,wkt:selectWKT.wkt[i],style:drawoptions.styles});
            }
            cbKort.dynamicLayers.zoomTo (this.dynLayerName,selectWKT.buffer);
            this.gui.diableAuxactionButton (false);
            var obj = {
            	pos: pos,
            	style: drawoptions.styles,
            	multiselect: this
            };
            obj = SpatialMap.Util.extend (obj,selectWKT);
            cbKort.log ('Multiselect.locatePos () - Located - ',obj);
            cbKort.events.fireEvent ('MULTISELECT_FEATURE_LOCATED',obj);
         }
      }
   }

   Multiselect.prototype.query = function (postValue)
   {
      if (this.topPos > -1) {
          var selectWKT = this.getSelectWKT (this.topPos);
          if (selectWKT) {
              wkt = selectWKT.wkt;
              //TODO: Use dynamic layer to query with 
              
              if (typeof wkt == 'array') {
                  wkt = wkt [0];
              }
              var actionurl = this.getActionUrl (postValue);
              actionurl = replaceUrlParam('wkt',wkt, actionurl);
              
              if (this.selectors[this.topPos].spatialQueryParams) {
                  for(var i=0;i < this.selectors[this.topPos].spatialQueryParams.length;i++) {
                     actionurl = replaceUrlParam(this.selectors[this.topPos].spatialQueryParams[i].name, this.selectors[this.topPos].spatialQueryParams[i].value, actionurl);
                  }
              }
        
              profilequery = getUrlParamAdv('profilequery',actionurl);
              var page = getUrlParamAdv('page',actionurl);
              
              if ( ! this.isAutoActionDone && page!=null && page!="")
              {
                 var cbHttp  = new CBhttp();
                 var pComp = cbHttp.executeUrl(actionurl, false);          
              }
              
              if(this.isCloseOnExit())
              {  closeDivBox();
              }
        
              actionurl = spatialqueryoptions.replaceOptionParams(actionurl);
            
              for(var i=0;i < spatialquery_paramHandlers.length;i++)
              {
                 var p = spatialquery_paramHandlers[i]();
                 actionurl = replaceUrlParam(p.name, p.value, actionurl);
              }
        
              setTimeout('spatialquery_doQuery ("'+profilequery+'", "'+actionurl+'", "'+this.searchtext+'");',100);
          }
      }
   }

   // *************************************************************
   //  Get selection list
   // *************************************************************

   Multiselect.prototype.getSelectionList = function (index, postValue)
   { 
      this.selectionListHandler = null;
      
      var sel = this.getSelector(index);

      var url = this.getSelectionListQueryUrl (index, postValue);
 
      var cbHttp  = new CBhttp();
       
      var pComp = cbHttp.executeUrl(url, false);
      
      var selArray = null;

      if (pComp!=null && pComp.isPComposite() )
      {  var rowList = pComp.get(0);
         selArray = this.createSelectionList (sel, pComp);
      }   
    
      return selArray;              
   }

   Multiselect.prototype.getSelectionListAsync = function (index, postValue, selectionListHandler)
   { 
      var sel = this.getSelector(index);

      var url = this.getSelectionListQueryUrl (index, postValue);
 
      multiselect_globalCbHttp  = new CBhttp();
       
      multiselect_globalCbHttp.executeUrlAsync (url, false, selectionListHandler);
   }

   Multiselect.prototype.createSelectionList = function (selector, pComp)
   { 
      var rowList = pComp.get(0);

      var selArray = null;

      if (rowList != null && rowList.isRowList() )
      {  
         selArray = new Array();
         for (var rowIx=0; rowIx < rowList.size(); rowIx++)
         {
            var row = rowList.row(rowIx);
            if (row!=null)
            {  var rowArray = new Array();
               var column1 = row.column(selector.postvar);
               var column2 = row.column(selector.displayvar);
            
               if (column1==null)
               {  throw new Error ("Postvariable '" + selector.postvar + "' missing in input");
               }

               if (column2==null)
               {  throw new Error ("Displayvariable '" + selector.displayvar + "' missing in input");
               }

               var displayValue = column1.getValue();
               if (displayValue==null)
               {  displayValue = "";
               }
               
               var id = column2.getValue();
               if (id==null)
               {  id = "";
               }
           
               rowArray = {id:id,disp:displayValue}
               selArray[rowIx] = rowArray;
            }   
         }
      }
      
      // *** Skal først testes
      // selArray.sort (Multiselect_sortAscendingIgnoreCase);
      return selArray;              
   }

       
   // *************************************************************
   //  Private methods
   // *************************************************************

   Multiselect.prototype.getSelectionListQueryUrl = function (index, postValue)
   {  
      // Add queryparams to url.

      var strUrl = this.queryUrl;
      var pArray = this.selectors[index].queryparams;

      if (pArray!=null)
      {
         var pName=null;
         var pValue=null;
         for(var i=0;i<pArray.length;i++)
         {
            pName=pArray[i].name;
            pValue=pArray[i].value;     
            strUrl = replaceUrlParam(pName, encodeURIComponent(pValue), strUrl);
         }
      }   

      // Replace / add postvar and postvalue

      var sel = this.getSelector(index);

      if (index>0 && postValue!=null)
      {
         var postVar = this.getSelector(index-1).postvar;
         var lastBox = 'kode'+(index-1);
         strUrl = replaceUrlParam (postVar, encodeURIComponent(postValue), strUrl);
      }
    
      strUrl = replaceUrlParam("jdaf.error.xslt", "", strUrl);
      strUrl = replaceUrlParam("jdaf.error.contenttype", "text/xml", strUrl);
    
      this.queryUrl = strUrl;
    
      return this.queryUrl;
   }   
   
   Multiselect.prototype.getActionUrl = function (postValue)
   {
      var url = this.queryUrl;
      url = replaceUrlParam('layers', cbKort.getLayers(), url);

      if (this.actionParams!=null)
      {
         var pName=null;
         var pValue=null;
         for (var i=0; i<this.actionParams.length; i++)
         {
            pName=this.actionParams[i].name;
            pValue=this.actionParams[i].value;     
            url = replaceUrlParam (pName, encodeURIComponent(pValue), url);
         }
      }   
    
      var postVar = this.selectors[this.selectors.length-1].postvar;
      url = replaceUrlParam(postVar, encodeURIComponent(postValue), url);

      url = replaceUrlParam("jdaf.error.xslt", "", url);
      url = replaceUrlParam("jdaf.error.contenttype", "text/xml", url);

      return url;
   }   
   
   Multiselect.prototype.getLocateUrl = function (pos,postValue)
   {
      var url = this.queryUrl;
      url = replaceUrlParam('page', 'multiselect-getfeatures', url);
      if (this.selectors[pos].locate && this.selectors[pos].locate.params) {
         for (var name in this.selectors[pos].locate.params) {
            url = replaceUrlParam (name, encodeURIComponent(this.selectors[pos].locate.params[name]), url);
         }
      }   
    
      var postVar = this.selectors[pos].postvar;
      url = replaceUrlParam(postVar, encodeURIComponent(postValue), url);

      url = replaceUrlParam("jdaf.error.xslt", "", url);
      url = replaceUrlParam("jdaf.error.contenttype", "text/xml", url);
      
      return url;
   }
   
   Multiselect.prototype.setAutoAction = function (autoAction)
   {
       this.autoAction = autoAction;
   }
   
   Multiselect.prototype.setTopPos = function (pos)
   {
       this.topPos = pos;
   }
   
   Multiselect.prototype.setCurrentPostValue = function (pos,postValue)
   {
      if (postValue) {
          this.selectors[pos].currentPostValue = postValue;
      }
   }
     
   Multiselect.prototype.setGui = function (gui)
   {
       this.gui = gui;
   }

  //
  // Helper function
  //
  
  function Multiselect_sortAscendingIgnoreCase (a, b)
  {
     var v1 = a.disp.toLowerCase(); 
     var v2 = b.disp.toLowerCase();
     if (v1>v2) return 1;
     if (v2<v1) return -1;
     return 0; 
  }
  
