//-------------------------------------------
//javascript File Containing Map Legend functions
// Author Paul.hann@dundeecity.gov.uk date: Dec 09
//-------------------------------------------
var LLeft, origLwidth;
var LyrData,ServiceDlg, QryDlg;
var Legend;
var APLayer = "";
dojo.require("dijit.Dialog");
dojo.require("dojox.form.RangeSlider");
var ServiceDlg, LayerDlg, GridDLG, pMenu, curRec, lstGrid, curCol, curVal;
var LegendScriptLoaded = true;
dojo.require("dojox.grid.DataGrid");
var checkBoxes = [];
//dojo.require("dojox.grid._data.model");

dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dojo.data.ItemFileWriteStore");
dojo.provide('DCC.dojo');
dojo.require('dojox.data.QueryReadStore');
dojo.require('dijit.Tree');
   dojo.require("dijit.form.Button");
       dojo.require("dijit.Menu");
       dojo.require("dojox.widget.PlaceholderMenuItem");

dojo.addOnLoad(function(){

    var arrVislayers = [];
    
    dojo.declare('DCC.dojo.ChkTree', dijit.Tree, {
        _clickTarget: null,
        
        
        _createTreeNode: function(args){
            return new CU.dojo._ChkTreeNode(args);
        },
        
        
        // this.TREE_ID is the ID of the tree you're playing with
        refreshTreeDisplay: function(){
            for (var v = 0; v < myLayers.length; v++) {
            
                arrVislayers = myLayers[v].Layer.visibleLayers;
                for (var k = 0; k < arrVislayers.length; k++) {
                    if (dojo.byId('ck' + arrVislayers[k] + 's' + v) != null) {
                        dojo.byId('ck' + arrVislayers[k] + 's' + v).checked = true;
                    }
                }
            }
            
        },
        
        
        onNodeChecked: function(node){
        
            myTreeNodeChecked(node);
        },
        
        onNodeUnchecked: function(node){
            myTreeNodeUnChecked(node);
            
        },
        
        onClick: function(item, node){
            if (item.root) {
                this._onExpandoClick({
                    node: node
                 });
                 
            }
            else {
                if (!node.checkNode ) 
                    return;
                
                if (this._clickTarget && this._clickTarget.nodeName != 'INPUT') 
                    node.checkNode.checked = !node.checkNode.checked;
                
                if (node.checkNode.checked) {
                    this.onNodeChecked(node);
                }
                else {
                    this.onNodeUnchecked(node);
                }
            }
        },
        
        _onClick: function(evt){
            this._clickTarget = evt.target;
            //serviceNode
            var isroot = false;
            if (dijit.getEnclosingWidget(this._clickTarget).item.type[0] =="Service" && this._clickTarget.className == "con")
            {
                //ServiceDlg.attr("content", );
                
               
                ServiceDlg.ServiceID = dijit.getEnclosingWidget(this._clickTarget).item.ServiceId[0];
                ServiceDlg.show();
                dijit.byId("slider1").setValue(myLayers[ServiceDlg.ServiceID].Layer.opacity);
                dijit.byId("dijit_DialogUnderlay_0").hide();
                isroot = true;


            }
            //If the target was a checkbox, ignore focusing the widget
            if (this._clickTarget.className == "conB" && !isroot )
            {
                 LayerDlg.ServiceID = dijit.getEnclosingWidget(this._clickTarget).item.ServiceId[0];
                 LayerDlg.LayerID = dijit.getEnclosingWidget(this._clickTarget).item.LyerID[0];
                dojo.byId("layerTools_title").innerHTML = " Map Layer Tools - " + myLayers[LayerDlg.ServiceID].Layer.layerInfos[LayerDlg.LayerID].name;
                LayerDlg.show();
                dijit.byId("dijit_DialogUnderlay_0").hide();
                return; 
            }
            else
            {
            if (this._clickTarget.nodeName == 'INPUT' || this._clickTarget.type == 'button') {
                if (this._clickTarget.type != 'button'){
                var nodeWidget = dijit.getEnclosingWidget(this._clickTarget);
                this.onClick(nodeWidget.item, nodeWidget);
                return;
                }
                return;
            }
            }
            return this.inherited(arguments);
        }
        
        
    });
     ServiceDlg = new dijit.Dialog({
            title: "Map Service Tools",
            id: "layerCfg",
            style: "width: 400px: height:300px;",
            content: '<h3>Layer Transparency</h3><div dojoType="dijit.form.HorizontalSlider"  		onchange="SetOpacity( dojo.number.format( arguments[0]),ServiceDlg.ServiceID )"			value="1"			maximum="1"			minimum="0"			pageIncrement="100"			showButtons="true"			intermediateChanges="true"			slideDuration="500"			style="width:90%; height: 20px;"			id="slider1" jsid="slider1">				<ol dojoType="dijit.form.HorizontalRuleLabels" container="topDecoration" style="height:1.2em;font-size:75%;display:none" count="6" numericMargin="1"></ol>				<div dojoType="dijit.form.HorizontalRule" container="topDecoration" count=6 style="height:5px;"></div>				<div dojoType="dijit.form.HorizontalRule" container="bottomDecoration" count=5 style="height:5px;"></div>				<ol dojoType="dijit.form.HorizontalRuleLabels" container="bottomDecoration" style="height:1em;font-size:75%;">					<li>100%</li>					<li>50%</li>					<li>0%</li>				</ol>		</div>'
            
        });
         ServiceDlg.setAttribute('class', "tundra")
         
         LayerDlg = new dijit.Dialog({
            title: "Map layer Tools",
            id: "layerTools",
            content: '<h3 title="click to view the data table for this map layer" onclick="createGrid();" style="cursor : pointer; color : Blue"> View Data Table</h3><h3 style="color:gray"  onclick="OpenQueryDlg();"> Query Data</h3><h3 style="color:gray"> Export Data</h3><h3 style="color:gray"> Play Data over Time</h3>'
            
        });
         LayerDlg.setAttribute('class', "tundra") 
         
         GridDLG = new dijit.Dialog({
            title: "Loading...",
            id: "GridDL",
            style: "width:300px",
            //content: '<div id="grid" style="height:520px;" dojoType="dojox.grid.DataGrid" jsId="gridWidget" loadingMessage="Loading..." headerMenu="gridMenu" rowSelector="false" editable="true" autoWidth="true"></div>'
            content: '<div id="grid" style="height:520px;" dojoType="dojox.grid.DataGrid" jsId="gridWidget" loadingMessage="Loading..."  rowSelector="false" editable="true" autoWidth="true"></div>'
        });
     GridDLG.setAttribute('class', "tundra") ;
      GridDLG.setAttribute('className', "tundra") ;
      
      pMenu = new dijit.Menu({title:'Menu'});
        pMenu.addChild(new dijit.MenuItem({
            label: "Zoom here",
            onClick: function(e){zoomToRecord(e,true);}
        }));
         pMenu.addChild(new dijit.MenuItem({
            label: "Highlight on Map",
              onClick: function(e){zoomToRecord(e,false);}
        }));
       

        pMenu.startup();

      
      //GridMenu.show();
    /*ryDlg= new dijit.Dialog({
            title: "Query layer",
            id: "QryTools",
            content: '<form dojoType="dijit.layout.ContentPane" ><table><tr><td>&nbsp;</td><td>Field</td> <td>Operator</td><td> Value</td></tr> <tr> <td> &nbsp;</td><td>                <select id="fieldval1"  dojoType="dijit.form.ComboBox" name="fieldval1">                    <option></option>                </select></td>           <td >                <select  dojoType="dijit.form.ComboBox" id="Op1" name="D1">                     <option>=</option>                    <option>&gt</option>               </select></td>            <td>                <input id="Value1" type="text" /></td>        </tr>        <tr>            <td>                <select  dojoType="dijit.form.ComboBox" id="multiOperator1" name="D4">                    <option>and</option>                    <option>or</option>                </select></td>            <td>                <select  dojoType="dijit.form.ComboBox" id="fieldval1" name="D5">                   <option></option>                </select></td>            <td>                <select  dojoType="dijit.form.ComboBox" id="Op2" name="D2">                    <option>=</option>                    <option>&gt</option>                </select></td>            <td>                <input id="Value2" type="text" /></td>        </tr>    </table> <div> value:<input id="sqlval" type="text" /> </div><div> EXECUTE</div></form>'            
        });
        QryDlg.setAttribute('class', "tundra") 
        */
    dojo.declare('CU.dojo._ChkTreeNode', dijit._TreeNode, {
    
    
        setLabelNode: function(label){
        
            var cfgimg = dojo.doc.createElement('img');
            if (this.item.root || this.tree.model.store.getValue(this.item, 'type') == "Service")
            {
            cfgimg.src = "http://mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/toolbox.gif";
            cfgimg.setAttribute("width", "20");
            cfgimg.setAttribute("height", "20");
            cfgimg.setAttribute('className', "con");
             cfgimg.setAttribute('class', "con");
             cfgimg.title = "Advanced Map Service Tools";
            //cfgimg.width = "25px";
            }
            else
            {
            cfgimg.src = "http://mapsonline.dundeecity.gov.uk/DCC_GIS_Root/DCC_GIS_CONFIG/images/toolboxB.gif";
             cfgimg.setAttribute("width", "15");
             cfgimg.setAttribute("height", "15");
             cfgimg.setAttribute('className', "conB");
             cfgimg.setAttribute('class', "conB");
             cfgimg.title = "Advanced Layer Tools";
            }
            cfgimg.alt = "Advanced Tools";
       
            cfgimg.style.paddingRight = "10px";
            //dojo.isIE ? cfgimg.style.float = 'right' : cfgimg.style.cssFloat = 'right';
            
            dojo.place(cfgimg, this.labelNode, 'after');
            if (this.item.root || this.tree.model.store.getValue(this.item, 'type') == "Service") {
            
                this.expandoNodeText.parentNode.removeChild(this.expandoNodeText);
                
                return this.inherited(arguments);
            }
            
            if (this.tree.model.store.getValue(this.item, 'ImageExists') != false) {
            
                this.ServiceID = this.tree.model.store.getValue(this.item, 'ServiceId');
                
                this.Swatch = this.tree.model.store.getValue(this.item, 'swatch');
                this.type = this.tree.model.store.getValue(this.item, 'type');
                this.Layer = this.tree.model.store.getValue(this.item, 'LyerID');
                var chk = dojo.doc.createElement('input');
                chk.type = 'checkbox';
                chk.id = 'ck' + this.Layer + 's' + this.ServiceID;
              
               
                
                if (this.tree.model.store.getValue(this.item, 'swatch') != "") {
                    var img = dojo.doc.createElement('img');
                    
                    img.src = this.tree.model.store.getValue(this.item, 'swatch');
                    img.style.paddingLeft = '30px';
                    img.style.whiteSpace = 'normal';
                    dojo.isIE ? img.style.float = 'left' : img.style.cssFloat = 'left';
                    var strid = "p"+  this.Layer + 's' + this.ServiceID ;
                    var configDiv = dojo.doc.createElement('button');
                   //var configDiv = new dijit.form.Button({ label: "Click me!",
                    //} , strid  );

                    //configDiv.id= "config";
                    /*
                    configDiv.Layer = this;
                    configDiv.dojoType="dijit.form.Button";
                    configDiv.type="button";
                    configDiv.innerHTML = "Layer Config";
                    configDiv.onclick = function(){alert(1);};
                    configDiv.style.position = "relative";
                    dojo.isIE ? configDiv.style.float = 'right' : configDiv.style.cssFloat = 'right';*/
                }
                
                this.labelNode.innerHTML = '';
                
                dojo.place(chk, this.expandoNodeText, 'after');
                                
                this.labelNode.appendChild(dojo.doc.createTextNode(label));
               
                if (this.tree.model.store.getValue(this.item, 'swatch') != "") {
                    dojo.place(img, this.labelNode.parentNode, 'after');
                    //dojo.place(configDiv, this.labelNode.parentNode.parentNode, 'after');
                }
              
                this.checkNode = chk;
                
                
                
                this.checkNode.checked = (typeof this.tree.model.store.getValue(this.item, 'visible') == 'undefined' ? true : this.tree.model.store.getValue(this.item, 'visible'));
                //if ( this.tree.model.store.getValue(this.item, 'type')  == 'layer'){ this.expandoNodeText.parentNode.removeChild(this.expandoNodeText);}
                this.expandoNodeText.parentNode.removeChild(this.expandoNodeText);
            }
        }
    });
});


function myTreeNodeUnChecked(node){

    if (node.type == 'Service') {
    
        // arrVislayers = myLayers[node.ServiceID].Layer.visibleLayers;
        //myLayers[node.ServiceID].Layer.setVisibleLayers([]) ;
        myLayers[node.ServiceID].Layer.hide();
    }
    else {
        var newArray = new Array();
        arrVislayers = myLayers[node.ServiceID].Layer.visibleLayers;
        for (var k = 0; k < arrVislayers.length; k++) {
            if (node.Layer != arrVislayers[k]) {
                newArray.push(arrVislayers[k]);
            }
        }
        myLayers[node.ServiceID].Layer.setVisibleLayers(newArray);
    }
    
}

function myTreeNodeChecked(node){

    if (node.type == 'Service') {
        myLayers[node.ServiceID].Layer.show();
        //??
        //  dojo.query('ServiceID:0').forEach(function(mnode, index, arr){
        //alert(mnode);
        //});
    
    
    }
    else {
    
        arrVislayers = myLayers[node.ServiceID].Layer.visibleLayers;
        arrVislayers.push(node.Layer);
        myLayers[node.ServiceID].Layer.setVisibleLayers(arrVislayers);
    }
    
}


function CreateLayerInfo()
{

    
    //create layerinfo
    
    LyrData = new Array();
    var lyrPos = 0;
    for (var lyrid = 0; lyrid < myLayers.length; lyrid++) {
    
        if (myLayers[lyrid].SwatchPath != "") {
            var myObj = new Object();
            myObj.type = "Service";
            myObj.ServiceId = lyrid;
            myObj.LyerID = "";
            myObj.name = myLayers[lyrid].Label;
            myObj.swatch = "";
            var arrChildren = new Array();
            for (var lyr = 0; lyr < myLayers[lyrid].Layer.layerInfos.length; lyr++) {
            
                var myObjint = new Object();
                myObjint.type = "layer";
                myObjint.ServiceId = lyrid;
                myObjint.LyerID = lyr;
                myObjint.name = myLayers[lyrid].Layer.layerInfos[lyr].name;
                myObjint.ImageExists = ImageExists(myLayers[lyrid].SwatchPath + lyr.toString() + ".png");
	       //  myObjint.ImageExists = myLayers[lyrid].SwatchPath + lyr.toString() + ".png";
                myObjint.visible = myLayers[lyrid].Layer.layerInfos[lyr].defaultVisibility;
                
                myObjint.swatch = myLayers[lyrid].SwatchPath + lyr.toString() + ".png";
                var refObj = new Object();
                refObj._reference = myObjint.name;
                arrChildren[lyr] = refObj;
                LyrData[lyrPos] = myObjint;
                lyrPos++;
            }
            myObj.children = arrChildren;
            LyrData[lyrPos] = myObj;
            lyrPos++;
            
        }
    }
    
    
    
    
    
    if (typeof dojo.byId('LegendDivContents') != 'undefined' );// only create legend if there is somewhere to put it
    {
     if (dojo.byId('LegendDivContents') != null) { 
        var store = new dojo.data.ItemFileReadStore({
            data: {
                label: 'name',
                'identifier': 'name',
                items: LyrData
            }
        });
        
        var treeModel = new dijit.tree.ForestStoreModel({
            store: store,
            
            query: {
                "type": "Service"
            },
            rootId: "root",
            rootLabel: "Key",
            childrenAttrs: ["children"]
        });
    
    
       
        Legend = new DCC.dojo.ChkTree({
        model: treeModel,
        showRoot: false});
        
        var foo = dojo.place(Legend.domNode, 'LegendDivContents'); }
    }
}


function createToggleLayerList(){

    //Interim function to create list of layers that can be toggled on or off.
    //this needs to be able to work with multiple map services.
    theHTML = "";
    
    //****This should be bottom up - reverse
    
    var visible = [];
    var items = [];
    for (n = (myLayers.length - 1); n > -1; n--) {
    
        theLayerInfos = myLayers[n].Layer.layerInfos;
        //Refresh so that the layer layerinfo is up to date.
        myLayers[n].Layer.refresh();
        for (var i = 0, il = theLayerInfos.length; i < il; i++) {
        
            info = theLayerInfos[i];
            
            //If dealing with a DCC_Manager layer it is an OS layer and don't want to give user option to turn on or off
            isChecked = "";
            if ((info.name.toUpperCase()).indexOf("DCC_MANAGER") == -1) {
                theStyle = "";
                type = "checkbox";
                theLabel = "<label class='toc' for='" + info.id + "'>" + info.name + "</label><br>";
                for (var p = 0; p < myLayers[n].Layer.visibleLayers.length; p++) {
                    if (info.name == theLayerInfos[myLayers[n].Layer.visibleLayers[p]].name) 
                        isChecked = "checked";
                }
            }
            else {
                theStyle = "style='display:none' ";
                type = "checkbox";
                theLabel = "";
                for (var p = 0; p < myLayers[n].Layer.visibleLayers.length; p++) {
                    if (info.name == theLayerInfos[myLayers[n].Layer.visibleLayers[p]].name) 
                        isChecked = "checked";
                }
            }
            items[i] = "<input type='" + type + "' class='list_item'" + theStyle + " " + isChecked + " id='" + n + ";" + info.id + "' onclick='updateLayerVisibility();' />" + theLabel;
            theHTML += items[i];
            
        }//end for i
    }//end for n
    return theHTML;
    
    
}
function openSideLegend(mapDiv){

    if(typeof mapDiv == "undefined"){mapDiv = "myMap" }
   Lwidth = 225;

    if (dojo.byId('LegendDiv').style.width != Lwidth + 'px') {
    
        LLeft = dojo.byId(mapDiv).style.width.substr(0,(dojo.byId(mapDiv).style.width.length - 2)) ;
        origLwidth = dojo.byId('LegendDiv').style.width.substr(0,(dojo.byId('LegendDiv').style.width.length - 2));
        dojo.animateProperty({
            node: 'LegendDiv',
            duration: 1000,
            onEnd: function(){
                dojo.byId('LegendBut').className = "LegendButIn";
                dojo.byId('LegendTitle').style.display = "block";
                dojo.byId('LegendDivContents').style.display = "block";
                dojo.byId('LegendDivContents').style.width = "220px";
                Legend.refreshTreeDisplay();
            },
            properties: {
                left: {end: LLeft - Lwidth},
                width: {end:Lwidth}
               
            }
        }).play();
        dojo.forEach((Legend.rootNode).getChildren(), function(c){
            c.tree._expandNode(c);
            //c.expandChildren(c); 
        }, this);
    }
    else {
        dojo.animateProperty({
            node: 'LegendDiv',
            duration: 1000,
            onEnd: function(){
                dojo.byId('LegendBut').className = "LegendBut";
            },
            properties: {
                width: {end: origLwidth},
                left: {end: LLeft}
            }
        }).play();
        dojo.byId('LegendDivContents').style.display = "none";
        dojo.byId('LegendTitle').style.display = "none";
        
    }
    
   }

function openSideLegendD(dir, mapDiv){

    if(typeof mapDiv == "undefined"){mapDiv = "myMap" }
   Lwidth = 250;
   
   

    if (dojo.byId('LegendDiv').style.width != Lwidth + 'px') {
    
        if (dojo.byId(mapDiv).style.width != "100%"){
          LLeft = dojo.byId(mapDiv).style.width.substr(0,(dojo.byId(mapDiv).style.width.length - 2)) ;
        }
        else
        {
          LLeft = MapConfig.width;
        
        }
        if (dir == 'L') {endpos = LLeft - Lwidth} else {endpos = LLeft}
        
        origLwidth = dojo.byId('LegendDiv').style.width.substr(0,(dojo.byId('LegendDiv').style.width.length - 2));
        dojo.animateProperty({
            node: 'LegendDiv',
            duration: 1000,
            onEnd: function(){
            
               try{ dojo.byId('LegendBut').className = "LegendButIn";}
               catch (error){}
                dojo.byId('LegendTitle').style.display = "block";
		if (typeof dojo.byId('LegendClose') != 'undefined')
			{     dojo.byId('LegendClose').style.display = "block";}
                dojo.byId('LegendDivContents').style.display = "block";
                dojo.byId('LegendDivContents').style.width = Lwidth - 5 + "px";
                Legend.refreshTreeDisplay();
            },
            properties: {
                left: {end: endpos},
                width: {end:Lwidth}
               
            }
        }).play();
        dojo.forEach((Legend.rootNode).getChildren(), function(c){
            c.tree._expandNode(c);
            //c.expandChildren(c); 
        }, this);
    }
    else {
        dojo.animateProperty({
            node: 'LegendDiv',
            duration: 1000,
            onEnd: function(){
                try{dojo.byId('LegendBut').className = "LegendBut";}
                catch (error){}
            },
            properties: {
                width: {end: origLwidth},
                left: {end: LLeft}
            }
        }).play();
        dojo.byId('LegendDivContents').style.display = "none";
        dojo.byId('LegendTitle').style.display = "none";
	if (typeof dojo.byId('LegendClose') != 'undefined'){
        dojo.byId('LegendClose').style.display = "none";}
        
    }
    
   }   
   function ImageExists(imgPath){
    dojo.xhrGet({
        url: "/forms/jQproxy.php?imageFile=" + imgPath,
        sync: true,
        load: function(response, ioArgs){
        
            return true;
        },
        error: function(response, ioArgs){
        
            return false;
        },
        preventCache: true,
        handleAs: "xml"
    });
   
    
}function SetOpacity($, val){
        
  myLayers[val].Layer.setOpacity($)
  
   
    }

    function $(o)
    {
     return dojo.byId(o);
    }
    
    function createGrid()
    {
    GridDLG.show();
     dojo.query(".dojoxGridMasterMessages").forEach(function(node, index, arr){
      node.style.display = "block";
  });

    
    
    dojo.byId("GridDL_title").innerHTML = myLayers[LayerDlg.ServiceID].Layer.layerInfos[LayerDlg.LayerID].name;
    try{ LayerDlg.hide();}
    catch(error) {}
    

    document.body.style.cursor = 'wait';
    dojo.xhrGet({
    url: "/forms/jQproxy.php?myurl=http://mapsonline.dundeecity.gov.uk/ArcGIS/rest/services/" + myLayers[LayerDlg.ServiceID].Label + "/MapServer/" + LayerDlg.LayerID + "/query&where=OBJECTID>0&f=json",
    load: function(response, ioArgs){
    
    
    var idfld = response.displayFieldName;
    lstGrid = response;
    var strfeat = "[";
  featData = new Array();
  cellsval = "[";
    for (var t=0;t< response.features.length;t++)
   // for (var t=0;t< 37;t++)
    {
      
      //strfeat = ""
      if (t > 0 && t < response.features.length){strfeat += ",";}
      strfeat += "{";
      
       for (att in response.features[t].attributes)
       {
          strfeat +=    '"' + att + '" : "' +   response.features[t].attributes[att] + '", ' ;
          if (t == 0)
          {

           cellsval += "{field:'" + att +"', name: '" + att + "'},";
          }
          
      }
      strfeat = strfeat.substring(0, strfeat.length - 2);   
      strfeat += "}";
      
      //featData[t] = strfeat;
    
    }
    cellsval = cellsval.substring(0, cellsval.length - 1);
    cellsval += "]";
    strfeat += "] ";
    cells = dojo.fromJson(cellsval);
    var view = {cells:cells};
      //gridWidget.setModel(model);
    gridWidget.setStructure([view]);
  
var newStore = new dojo.data.ItemFileWriteStore ({data: { 
  items: dojo.fromJson(strfeat)
      
}});


    //gridWidget._clearData();
     // var dataForGrid = [['Location',2],['Location',2],['Description',2],['Location',2],['Location',2]];
      gridWidget.setAttribute('class', "tundra") ;
      gridWidget.setAttribute('className', "tundra") ;
      //var model = new dojox.grid.DataGrid.Table(null, dataForGrid);
     // var cells = [{field:"PROPERTY_NAME", name: "PROPERTY_NAME"},{field:"status", name: "status"}];

      gridWidget.setStore(newStore);
      gridWidget.selectable = true;
      
      
      dojo.query(".dojoxGridMasterMessages").forEach(function(node, index, arr){
      node.style.display = "none";
  }); 
    try{  dijit.byId("dijit_DialogUnderlay_0").hide();}
    catch(error) {}

      document.body.style.cursor = 'default';
      return response;
    },
    error: function(response, ioArgs){
      alert("An error occurred, with response: " + response);
      document.body.style.cursor = 'default';
      return response;
    },
    handleAs: "json"
  });   
  
  //pMenu.targetNodeIds = ["gridWidget"];
    
     dojo.connect(gridWidget, "onRowContextMenu", gridRowClick);
    dojo.connect(gridWidget, "onHeaderContextMenu", popContextHeader);
    
    


    
    }
    function loc(data) {
      return data[0];
    }
    function OpenQueryDlg()
    {
    
    QryDlg.show();
    }
    /*
    function createQuery()
    {
    
       dojo.byId("sqlval").value = dojo.byId("fieldval1").value + " " + dojo.byId("Op1").value + " " + dojo.byId("Value1").value;
    
    }*/

    function gridRowClick(e)
    {
    curRec = e;
    pMenu.targetNodeIds =  e.cellNode;
    pMenu._openMyself(e);
    
    }
    
    function zoomToRecord(e, zoomto)
    {
    
   
    showResults(lstGrid, curRec.rowIndex, zoomto);
  
    }
    
    function showResults(results, pos, zoomto){
    var totalExtent ;
    var gType = results.geometryType;
    
    clearAllGraphics();
   
        var curFeature = results.features[pos];
        graphic = new esri.Graphic(curFeature);
        
        switch (gType) {
            case "esriGeometryPoint":
                var symbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, 5, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 2), new dojo.Color([255, 0, 0, 0.25]));
                totalExtent = new esri.geometry.Extent(parseFloat(graphic.geometry.x) - factor, parseFloat(graphic.geometry.y) - factor, parseFloat(graphic.geometry.x) + factor, parseFloat(graphic.geometry.y) + factor, myMap.spatialReference)  ;
                break;
            case "esriGeometryPolyline":
                var symbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASH, new dojo.Color([255, 0, 0]), 1);
                totalExtent =  graphic.geometry.getExtent() ;
                break;
            case "esriGeometryPolygon":
                //var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_NONE, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASHDOT, new dojo.Color([255,0,0]), 2), new dojo.Color([255,255,0,0.25]));
                var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 2), new dojo.Color([255, 0, 0, 0.25]));
                totalExtent =  graphic.geometry.getExtent() ;
                break;
        }
        graphic.setSymbol(symbol);
        
        zoomListner = dojo.connect(myMap, "onExtentChange", function(){
                 
                myMap.graphics.add(graphic);
               
                dojo.disconnect(zoomListner);
               
            });       
        
        
        
        
        
    
    if (zoomto){
    myMap.setExtent(totalExtent.expand(2), true);
    }
    myMap.resize();
    myMap.reposition();
    
}



function popContextHeader(e)
{
curCol=e.cell.field;


var sellist = dojo.byId('cFilter')

while(sellist.childNodes.length>0) {sellist.removeChild(sellist.childNodes[0])}


var optn = document.createElement("OPTION");
    optn.text =  'all';
    optn.value =  'all';
     sellist.options.add(optn);
    optn1 = document.createElement("OPTION");
    optn1.text =  'blank';
    optn1.value = 'blank';
    sellist.options.add(optn1);
    optn2 = document.createElement("OPTION");
    optn2.text =  'not blank';
    optn2.value = 'not blank';
    sellist.options.add(optn2);
    optn3 = document.createElement("OPTION");
    optn3.text =  'null';
    optn3.value = 'null';
    sellist.options.add(optn3);
    
    
 dojo.forEach(gridWidget.store._arrayOfAllItems, function(cell, index){
    optn = document.createElement("OPTION");
    optn.text =  eval("cell."  + curCol );
    optn.value =  optn.text;
    sellist.options.add(optn);

    //options += "<option>" +  eval("cell."  + curCol ) + "</option>";
});
   
     //dojo.byId('cFilter').innerHTML = dojo.byId('cFilter').innerHTML + options;

}

function gridWfilter(col , val)
{


if (val == 'all')
{
  strva = "gridWidget.filter({ '"+col+"' : '*'});";
}
else if (val == 'null')
{
  strva = "gridWidget.filter({ '"+col+"' : 'null'});";
}
else if (val == 'blank')
 { strva = "gridWidget.filter({ '"+col+"' : ''});";}
else if (val == 'not blank')
 { strva = "gridWidget.filter({ '"+col+"' : '[^]+'});";}
else
{ 
  strva = "gridWidget.filter({ '"+col+"' : '" + val + "'});";
}
eval (strva);
//gridWidget.setQuery({ col : val});
//gridWidget.filter({"PARC_NO_1":"20d-52"});

}
