////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// control browser side selection/deselection, postbacking, and dynamic document fragment replacing
// (1) this script file should be linked with resultpage
// (2) postback using Ajax, acoupled with ajax on server side
// (3) using hidden variable to remember selection, there are one hidden input for all page to remember 
//  current searchId(when user click 'MapIt' send it back to server) and each hidden for each searchResult
//  to remember each searchresult mapit selection   
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//var browser=navigator.appName ;       // browser type
var currentIndexList = new Array();   // remember current page index for each searchresult
//var hasPostbackFlag = new Array();    // for one joined node, if already postback, no need
var hasChildrenFlag = new Array();    // if has children, expend it, otherwise, do nothing
var isNav = (window.navigator.appName.toLowerCase().indexOf("netscape")>=0);
var isIE = (window.navigator.appName.toLowerCase().indexOf("microsoft")>=0);
var isIE5 = (navigator.appVersion.indexOf("MSIE 5.01")>0);	
var MAX_COL_SPAN = 50;                // const value  
var HIDDEN_ALL_FEATURE_PREFIX = "hidden_all_";
var HIDDEN_SELECTED_FEATURE_PREFIX = "hidden_selected_";
// special viewstate
var HIDDEN_XSL_DIR = "hidden_xsl_dir";
// when post back, browser will tell server the current task, could be MapIt, link postback
var CURRENT_TASK_ID = "currentTaskId";
// when mapit, browser need tell server the current search 
var CURRENT_SEARCH_ID = "currentSearchId";
// when link, postbackType = server, browser need tell server the current feature
var CURRENT_FEATURE_ID = "currentFeatureId";
// remember current selection id, when client post back 
var CURRENT_SELECTION_ID = "currentSelectionId";
// remember collepse imge url
var HIDDEN_COL_IMG = "colImg";
// remember expand image url
var HIDDEN_EXP_IMG = "expImg";

var LINK_POST_BACK = 2;
var NavigationControl = {
       callback_MoveTo:function(searchId, index)
       { 
            if(!sessionExpired)
            {
                PageMethods.MoveTo(searchId, index, ViewStateControl.getXslDir(), this.refreshSearchResult);
            }
            else
            {
                HandleSessionExpired();
            }
       },
       
       callback_MoveLast:function(searchId, totalCount)
       {
            if(!sessionExpired)
            {
              var currentIndex = CurrentIndexUtil.getCurrentIndex(searchId);
              if (currentIndex < totalCount - 1) 
                 PageMethods.MoveLast(searchId,  ViewStateControl.getXslDir(), this.refreshSearchResult);
            }
            else
            {
                HandleSessionExpired();
            }
       },
       
       callback_MoveFirst:function(searchId)
       {
            if(!sessionExpired)
            {
              var currentIndex = CurrentIndexUtil.getCurrentIndex(searchId);
              if (currentIndex > 0 ) 
                  PageMethods.MoveFirst(searchId, ViewStateControl.getXslDir(), this.refreshSearchResult);
            }
            else
            {
                HandleSessionExpired();
            }
       },
       callback_MoveFastForward:function(searchId, totalCount)
       {
            if(!sessionExpired)
            {
              var currentIndex = CurrentIndexUtil.getCurrentIndex(searchId);
              if (currentIndex < totalCount - 1) 
                 PageMethods.MoveFastForward(searchId, currentIndex, ViewStateControl.getXslDir(), this.refreshSearchResult);
            }
            else
            {
                HandleSessionExpired();
            }
       },
       callback_MoveFastBackward:function(searchId, totalCount)
       {
            if(!sessionExpired)
            {
              var currentIndex = CurrentIndexUtil.getCurrentIndex(searchId);
              if (currentIndex > 0 ) 
                 PageMethods.MoveFastBackward(searchId, currentIndex, ViewStateControl.getXslDir(), this.refreshSearchResult);
            }
            else
            {
                HandleSessionExpired();
            }
       },
       
      // refresh search result when user paging 
       refreshSearchResult:function(response)
       {
         var data = response;
         if (data != null)
         {
            var currentIndex = data.CurrentIndex;
            CurrentIndexUtil.setCurrentIndex(data.SearchId,currentIndex );
            if (data.SearchId != null && data.FeatureList != null)
            {
                    parentNode = document.getElementById(data.SearchId);
                    if (parentNode != null)
                    {
                        parentNode.innerHTML = data.FeatureList;
                    }
                     
                    // set navigation bar
                    parentNode = document.getElementById("div_" + data.SearchId);
                    if (parentNode != null)
                    {
                        parentNode.innerHTML = data.NavigationBar;
                    }
                    
                    // set original mapIt checkBox
                    var searchId = data.SearchId;
                    MapItControl.setMapItCheckBox(searchId);
                    // reset postback flag after paging, when user click join, will get joined data agian
                   // hasPostbackFlag = new Array();
            }      
         }
      } 
  }
  
var MapItControl = 
{
       // set checkbox status if user navigate back
       setMapItCheckBox:function(searchId)
       {
            if (searchId != null)
            {    
                var featureIdArray;
                // reset the value of all checkbox
                var allFeaturesNode = document.getElementById(HIDDEN_ALL_FEATURE_PREFIX + searchId);
                if (allFeaturesNode != null)
                {
                    featureIdArray = allFeaturesNode.value.split("#");
                    for(var i=0; i<featureIdArray.length; i++)
                    {
                        var checkBoxNode = document.getElementById("map_"+searchId+"_"+featureIdArray[i]);
                        if (checkBoxNode != null)
                        {
                            //checkBoxNode.setAttribute("checked", false);
                            checkBoxNode.checked = false;
                        }
                    }
                }            
                // read the value from corresponding hidden control, and set checkBox
                selectedFeaturesdNode = document.getElementById(HIDDEN_SELECTED_FEATURE_PREFIX+searchId);
                if (selectedFeaturesdNode != null)
                {
                    featureIdArray = selectedFeaturesdNode.value.split("#");
                    for(var i=0; i<featureIdArray.length; i++)
                    {
                        var checkBoxNode = document.getElementById("map_"+searchId+"_"+featureIdArray[i]);
                        if (checkBoxNode != null)
                        {
                            checkBoxNode.checked = true;
                        }
                    }
                }
                
                // set "Check All" checkbox
               MapItControl.setCheckAllBox(searchId);
            }
       },
       setCheckAllBox:function(searchId)
       {
            var chk = document.getElementById("chk_map_"+searchId);
            if (chk)
            {
                if (MapItControl.isAllChecked(searchId))  
                {
                    chk.checked=true;
                }
                else
                    chk.checked=false;    
            }
       },
       // modify the feature id buffer according to each feature check box value
       setFeatureId:function(node, searchId, featureId)
       {
             if (node != null)
             {
                MapItControl.setSelectedFeatureId(node, searchId, featureId);
                // set select all check box
                var chk = document.getElementById("chk_map_"+searchId);
                if (chk)
                {
                    if (MapItControl.isAllChecked(searchId))  
                        chk.checked=true;
                    else
                        chk.checked=false;    
                }
             }
       },
       // set the selected feature id into a buffer, thus can be post back to server once user click Map it
       setSelectedFeatureId:function(node, searchId, featureId)
       {
         if (node != null)
         {
            // read the value from corresponding hidden control
            var selectedFeatures = document.getElementById(HIDDEN_SELECTED_FEATURE_PREFIX + searchId);
            if (selectedFeatures)
            {
                var checkBoxBuffer = selectedFeatures.value;
                if (node.checked)
                {
                    if (!MapItControl.contains(checkBoxBuffer,featureId, '#'))
                        checkBoxBuffer += featureId + "#" ;
                }
                else
                {
                    if (MapItControl.contains(checkBoxBuffer,featureId, '#'))
                        checkBoxBuffer = MapItControl.removeItem(checkBoxBuffer,featureId, '#');
                }
                // reset the value of hidden control
                selectedFeatures.value = checkBoxBuffer;
            }
          }
       },
       // check whether a feature id is contained in a buffer
       contains:function(collection, item, splitChar)
       {
          var contained = false;
          var itemArray = collection.split(splitChar);
          for(var i=0; i<itemArray.length; i++)
          {
            if (itemArray[i] == item)
            {
              contained = true;
              break;
            }
          }
          return contained;
       },
       // remove a item from collection, can not use replace function here (i.e: 21#1#, if you remove '1'), 
       removeItem:function(collection, item, splitChar)
       {
          var returnCollection="";
          var itemArray = collection.split(splitChar);
          for(var i=0; i<itemArray.length; i++)
          {
            if (itemArray[i] != '' && itemArray[i] != item)  // check '', because split function create this additional item
                returnCollection += itemArray[i] + splitChar;
          }
          return returnCollection;
       },
       
         // toggle check state by map it check box state
       toggleCheckBoxonAllPages:function(searchId, switchFlag)
       {
            var allFeaturesNode = document.getElementById(HIDDEN_ALL_FEATURE_PREFIX + searchId);
            var selectedFeaturesdNode = document.getElementById(HIDDEN_SELECTED_FEATURE_PREFIX+searchId);
            if (allFeaturesNode != null && selectedFeaturesdNode!= null)
            {
                featureIdArray = selectedFeaturesdNode.value.split("#");
                if (switchFlag)   // select results on all pages
                    selectedFeaturesdNode.value = allFeaturesNode.value;
                else   // un-select results on all pages
                    selectedFeaturesdNode.value = "";
                var selectAllChk = document.getElementById("chk_map_" +searchId);
                if (selectAllChk)
                    selectAllChk.checked = switchFlag ;
                MapItControl.setAllCheckBoxes(searchId, switchFlag);
            }
       },
       
       // toggle check state by map it check box state
       toggleCheckBox:function(ctrCheckBox,searchId)
       {
            if (ctrCheckBox)
                MapItControl.setAllCheckBoxes(searchId, ctrCheckBox.checked);
       },
       setAllCheckBoxes:function(searchId, state)
       {
            var allFeatureNode = document.getElementById(HIDDEN_ALL_FEATURE_PREFIX + searchId);
            if (allFeatureNode)
            {
                if (allFeatureNode.value)
                {
                     if (state != null)
                     {
                        var featureIdArray = allFeatureNode.value.split("#");
                        for(var i=0; i<featureIdArray.length; i++)
                        {
                            var checkBoxNode = document.getElementById("map_"+searchId+"_"+featureIdArray[i]);
                            if (checkBoxNode != null)
                            {
                                checkBoxNode.checked = state;
                                MapItControl.setSelectedFeatureId(checkBoxNode, searchId, featureIdArray[i]);
                            }
                        }
                     }
                }
            }
       },
       // check whether has selected all valeus, if yess, need set "select all" check box
       isAllChecked:function(searchId)
       {
          var isSame = true;
          var allFeaturesNode = document.getElementById(HIDDEN_ALL_FEATURE_PREFIX + searchId);
          if(allFeaturesNode)
          {
            var featureIdArray = allFeaturesNode.value.split("#");
            for(var i=0; i<featureIdArray.length; i++)
            {
                var checkBoxNode = document.getElementById("map_"+searchId+"_"+featureIdArray[i]);
                if (checkBoxNode != null)
                {
                    if (!checkBoxNode.checked)
                    {
                       isSame = false;
                       break;
                    }
                }
            }
          }
          return isSame;
       },
       isNoneChecked:function(searchId)
       {
          var isSame = true;
          var allFeaturesNode = document.getElementById(HIDDEN_ALL_FEATURE_PREFIX + searchId);
          if(allFeaturesNode)
          {      
            var featureIdArray = allFeaturesNode.value.split("#");
            for(var i=0; i<featureIdArray.length; i++)
            {
                var checkBoxNode = document.getElementById("map_"+searchId+"_"+featureIdArray[i]);
                if (checkBoxNode != null)
                {
                    if (checkBoxNode.checked)
                    {
                       isSame = false;
                       break;
                    }
                }
            }
          }
          return isSame;
       },       
       // redirect to another page
       redirect:function(selectId, cmd)
       {
            if (MapItControl.isNoneChecked(selectId))
              alert("Please select feature(s) to map it");
            else  
            {
                var selectedFeatureNode = document.getElementById(HIDDEN_SELECTED_FEATURE_PREFIX + selectId);
                if (selectedFeatureNode != null)
                {
                   var taskNode = document.getElementById(CURRENT_TASK_ID); 
                   var searchIdNode = document.getElementById(CURRENT_SEARCH_ID); 
                   if (taskNode != null && searchIdNode != null)
                   {
                      taskNode.value = cmd;
                      searchIdNode.value = selectId; 
                      MapItControl.postBack();
                      taskNode.value = null;
                   }
                }
            }
       },
       
       postBack: function()
       {
            // put something in hidden valiable
            var formNodes = document.getElementsByTagName("form");
            var formNode = null;
            if (formNodes != null && formNodes.length > 0)
            {
                formNode = formNodes[0] ;
                if (formNode != null)
                {
                  //formNode.submit();
                 //Atlas 
                 UpdatePanel('MapResultonMapControl|Map|SelectionListContainer'); 
                 //Atlas
                }
            }
       }
       
   }
 
	    
var JoinControl =       
{
         // params: joinId , send to server, then return back, just for remember current node
       callback_Join:function(node, searchId, rootFeatureId, originRowId, joinId)
       {
            if (node != null)
            {
                 if(!sessionExpired)
                 {
                    // if not postback yet, postback
                    if (!this.hasPostBack(node.id))
                    {
                         // set the flag
                      //  JoinControl.setPostbackFlag(originRowId, joinId);
                        PageMethods.GetHtmlForEachJoin(node.id, searchId, rootFeatureId, originRowId, joinId, ViewStateControl.getXslDir(), this.getJoinRows);
                        
                    }
                    else   // hide or show
                        this.toggleChildren(node,originRowId,joinId);
                 }
                 else
                    {
                        HandleSessionExpired();
                    }
                        
            }
       },
       // user click "join" button, callback to server, 
       getJoinRows:function(response)
       {
          var data = response;
          if (data != null)
          {
            // 
            var joinedNode = document.getElementById(data.CurrentNodeId);
            if (joinedNode != null)
            {
               var htmlString = data.FeatureList;
               if (htmlString != null)
                    htmlString = StringUtil.trim(htmlString);
               // if has children, set the flag
               if (htmlString != null && htmlString != "")
               {
                JoinControl.setChildrenFlag(data.FeatureId,data.JoinId);
                // set innerText
                var trNode =  joinedNode.parentNode.parentNode;
                var tbodyNode = trNode.parentNode;
                var tr =document.createElement("TR");
                var td =document.createElement("TD");
                var div = document.createElement("DIV");
                // put a div here for compatiable with FireFox and netscape   
                div.setAttribute("align","left");
                div.innerHTML = htmlString;
                td.appendChild(div);
                td.setAttribute("colSpan", MAX_COL_SPAN);
                tr.appendChild(td);
                tr.id = "tr_"+ data.CurrentNodeId;
                if (trNode.nextSibling == null)
                    tbodyNode.appendChild(tr);
                else     
                    tbodyNode.insertBefore(tr, trNode.nextSibling);
                joinedNode.value = StringUtil.changeToMinusSign(joinedNode);
               }
            }
          }
       },

       // after postback, set this flag  
//       setPostbackFlag:function(originRowId,joinId)
//       {
//            if (originRowId != null)
//            {
//                hasPostbackFlag[hasPostbackFlag.length] = originRowId+"_"+joinId;
//            }
//       },
         // after postback, set this flag , all join which has children will be on list 
       setChildrenFlag:function(originRowId,joinId)
       {
            if (originRowId != null)
            {
                hasChildrenFlag[hasChildrenFlag.length] = originRowId+"_"+joinId;
            }
       },
       // check this joined node has already get data from server
       hasPostBack:function(joinNodeId)
       {
            var postBack = false;
            if (document.getElementById("tr_"+ joinNodeId))
                postBack = true;
            return postBack;
       },
       // check this joined node has children
       //hasChildren:function(joinNode)
       hasChildren:function(originRowId,joinId)
       {
            var has = false;
            if (originRowId != null)
            {
                for (var i = 0 ; i <  hasChildrenFlag.length; i++)
                {
                    if (hasChildrenFlag[i] == originRowId+"_"+joinId)
                    {
                        has = true;
                        break;
                    }
                }
            }
            return has;
            
       },

      // toogle the children,  if display then hide them, if hidden then show them
      // joinNode = buttton with joined name
      toggleChildren:function(joinNode, featureId, joinId)
      {
	     if (joinNode != null )
         { 
                if (JoinControl.hasChildren(featureId,joinId))
                {
				    var trElem = joinNode.parentNode.parentNode;
				    if (trElem != null)
				    {
					        var trNodeSibling = trElem.nextSibling;
					        if(trNodeSibling != null)
					        {
					       	    if ( trNodeSibling.style.display == "inline" ||
					       	         trNodeSibling.style.display == "block" ||
					       	         trNodeSibling.style.display == "" )
					       	    {
    					            trNodeSibling.style.display= "none";
					                joinNode.value = StringUtil.changeToPlusSign(joinNode);
    					        }
					            else
					            {
    					            joinNode.value = StringUtil.changeToMinusSign(joinNode);
    					            // using style.display="" can control properly on IE and FireFox
    					            // no test on Netscape
    					            
    					            
//    					            trNodeSibling.style.display= "inline";
//    					            trNodeSibling.style.display= "block";
    					            trNodeSibling.style.display= "";
//					                if (isIE || isIE5)
//					                    trNodeSibling.style.display= "inline";
//					                else    
//					                    trNodeSibling.style.display= "block";
					            }
					        }
				    }
			   }
		  }
	  }
  }    
  
  var StringUtil = 
  {
      trim:function(str)
      {
          return str.replace(/^\s*|\s*$/g,"");
      },
      
      changeToMinusSign:function(joinNode)
      {
         if (joinNode)
         {
           var img = document.getElementById(HIDDEN_EXP_IMG);
           if (img)
            joinNode.src=img.value;
         }
      },
      
      changeToPlusSign:function(joinNode)
      {
        if (joinNode)
        {
           var img = document.getElementById(HIDDEN_COL_IMG);
           if (img)
            joinNode.src=img.value;
        }
      }
  }

// remeber searchId and currentIndex pair
// format: searchId,current#searchId,current#
 var CurrentIndexUtil=
 {
     setCurrentIndex:function(searchId, currentIndex)
     {
       if(searchId != null && currentIndex != null)
       {
            this.removePair(searchId);
            var position = this.getEmptyPosition();
            if (position == -1)
                position = 0 ;
            currentIndexList[position] = new Array(searchId, currentIndex);
        }
     },
     
     getCurrentIndex:function(searchId)
     {
        var index = -1;
        if (searchId != null)
        {
            for (var i=0; i <currentIndexList.length; i++)
            {
                if (currentIndexList[i] != null && 
                    currentIndexList[i][0] != null &&
                    currentIndexList[i][0] == searchId)
                {
                    index = currentIndexList[i][1];
                    break;
                }
            }
        }
        return index;
     },
     
     removePair:function(searchId)
     {
        if (searchId != null)
        {
            var compare = true;
            for (var i=0; i <currentIndexList.length; i++)
            {
                if (compare)
                {
                    if (currentIndexList[i][0] == searchId)
                    {
                        if (i < currentIndexList.length - 1) // if not the last one
                        {
                            currentIndexList[i][0] = currentIndexList[i+1][0];
                            currentIndexList[i][1] = currentIndexList[i+1][1];
                        }
                        compare = false;
                    }
                }
                else
                {
                    currentIndexList[i][0] = currentIndexList[i+1][0];
                    currentIndexList[i][1] = currentIndexList[i+1][1];
                }
            }
            if (!compare)
            {
                var position = currentIndexList.length - 1;
                if (position >= 0)
                {
                    currentIndexList[position][0] = null;
                    currentIndexList[position][1] = null;
                    currentIndexList[position] = null;
                }
            }
         }
       },
        
        // somehow, dynamic array can not shrink, 
       getEmptyPosition:function()
       {
            var index = -1;
            for (var i=0; i <currentIndexList.length; i++)
            {
                if (currentIndexList[i] == null)
                {
                   index = i;
                   break;
                }
            }
            return index ;
        }
  }

  var ViewStateControl = {
      getXslDir:function()
      {
         var node = document.getElementById(HIDDEN_XSL_DIR);
         if (node != null)
          return node.value;
      }
  } 

  var LinkControl = {
//      getParameterValue: function(queryParameter)  
//      {
//        var queryValue = null;
//        if (queryParameter != null)
//        {
//           
//        }
//        return queryValue;
//      },
      
      
      linkPostBack: function(searchId, featureId,selectionItemId)
      {
      
           var taskNode = document.getElementById(CURRENT_TASK_ID); 
           var featureIdNode = document.getElementById(CURRENT_FEATURE_ID);
           var searchIdNode = document.getElementById(CURRENT_SEARCH_ID);
           var selectionIdNode = document.getElementById(CURRENT_SELECTION_ID);
           if (taskNode != null && featureIdNode != null && searchIdNode != null && selectionIdNode != null)
           {
              taskNode.value = LINK_POST_BACK;
              featureIdNode.value = featureId; 
              searchIdNode.value = searchId;
              selectionIdNode.value = selectionItemId;
              MapItControl.postBack();
           }
           
          //SearchResultControl.LinkPostBack(searchId, featureId, selectionItemId);
      },
      
      
      // used in xsl, when user click  a hyperlink  or image 
      // theoretically, target could be anything, but this function  check _new  rather than others like _top, _self, _blank, _parent
      navigation: function(target, targetUrl, queryParameter)
      {
        //alert('navigation target:' + target + ',targetUrl:' + targetUrl + ',queryParameter:' + queryParameter);
        // queryParameter is just parameter name, app need find out the value according to this parameter
//        var url = targetUrl ;
//        var queryValue = LinkControl.getParameterValue(queryParameter);
//        if (queryValue != null)
//         url += "?" + queryParameter + "=" + queryValue;
        var url = targetUrl + "?" + queryParameter
        if (target == '_new')
           window.open(url, target);
        else
           location.replace(url);
      }
  }
 /* 
 var ToolTip = {
      show: function(node) 
      {
	    if (node != null)
	    {
	        node.style.display = "block" ;
	        node.style.display = "inline" ;
	    }
    },
    
      hide: function (node) {
	    if (node != null)
	    {
	        node.style.display = "none";
	    }
    }
 }     
 */
 
 function ViewReports(searchId)
 {
    if(searchId != null)
    {   
      var url = '/Webpages/Reports/Reports.aspx?FUNCTIONALITY=RESULTS&SEARCHID=' + searchId; 
           if (window.NGServerUrl)
            {
               url = NGServerUrl()+ url;        
            }
         
         
         if (window.HandleReportsFrame)
          {
            HandleReportsFrame(url);
          }
         else
          {
           var reportWindow = window.open(url,"reportWin","toolbar=no, directories=no, location=no, status=yes, menubar=no, resizable=yes, scrollbars=yes, width=400, height=200");    
          }
        
        }
    } 
 
 //returns the <protocol>//hostname/pathname
//function NGServerUrl()
//{
//    var protocol = window.location.protocol;
//    var theHost = window.location.hostname;
//    var port = window.location.port;
//    var path = window.location.pathname;   
//    path = path.substring(0, path.indexOf("/", 1));
//    
//    var newUrl = protocol + "//" + theHost + ":" + port + path;
//    return newUrl;	
//}