    var foundLocation = 0;
    var mapContext,dataLatLon = null; 
    var latlngThai;
    var waypoints = []; 
    var dataType,dataDriverName,dataBrandName;
    var myData,myProvince,myDataNum,myDataStatus,myCheckMessage,myDataPoint,myRoute,myjobListBox = [];
    var dataProvince,dataBoxNumber = [];
    var poiMessage = [];        
    var messagetext,datetime,messagestatus;
    var addressToGeoCode,geocoder;
    var logLat;
    var logLon;
    var mapControl,realtimeTracking; 
    var map=null;
    var jobListBox,jobList,stateList,tracking = []; 
    var deviceID,plateNumber,BoxID,jobNumber;
    var addPlatePanel,addShipmentPanel,manageShipmentPanel,addPointForm,configForm,StatusForm,jobbAddForm,configForm,batteryForm,mapAddForm,mapForm,addMemForm,queueForm,directionForm;
    var map,gdir,groute,polyOptions;   
    var IconWhere,IconCarSelect,IconCarOff,IconCarOff0,IconCarOff1,IconCarOff2,IconCarOff3,IconPlace,IconA,IconB,Icon0,Icon1,Icon2,Icon3,Icon4,Icon5,Icon6,Icon7,Icon8,Icon9,Icon10;
    var Start_marker,Stop_marker,markerCarNow,currentMarker,markerWhere,place_marker,A_marker,B_marker,current_marker,caroff_marker0,caroff_marker1,caroff_marker2,caroff_marker3,caroff_marker4,inorigin_marker,atorigin_marker,loading_marker,outorigin_marker,ondelivery_marker,indest_marker,atdest_marker,offloading_marker,outdest_marker,delivered_marker = null;//Marker  
    var latInOrigin,lonInOrigin,latAtOrigin,lonAtOrigin,latLoading,lonLoading,latOndelivery,lonOndelivery,latOutOrigin,lonOutOrigin;
    var latInDest,lonInDest,latAtDest,lonAtDest,latOffloading,lonOffloading,latDelivered,lonDelieredv,latOutDest,latOutDest;
    var htmlAddPlace,htmlInOrigin,htmlAtDest,htmlAtOrigin,htmlLoading,htmlOnDelivery,htmlOutOrigin,htmlInDest,htmlOffLoading,htmlDelivered,htmlOutDest,htmlCar;//---OpenInfoWinDow---//
    var Boxid_job,Plate_job,Jobid_job,Dest_job,Origin_job,Status_job;
    var ChangeStatus = ['เข้าต้นทาง','อยู่ที่ต้นทาง','เริ่มขึ้นสินค้า','เสร็จสิ้นการขึ้นสินค้า','เข้าปลายทาง','อยู่ที่ปลายทาง','เริ่มลงสินค้า','เสร็จสิ้นการลงสินค้า'];
    var myState = ['Clear','InOrigin','AtOrigin','Loading','On-Delivery','InDest','AtDest','Off-Loading','Delivered'];
    var myRadius = [100,200,300,400,500];
    var myStateSelect = ['จบงานแล้ว','อยู่ระหว่างปฎิบัติงาน','งานที่อยู่ในคิว'];
    var StatusNow,JobNow,PlateNow,BoxNow;
    var polyButton,pbarBattery ;
    var nameUser,provider; 
    var myMap = null;
    var localSearch = null;
    var myQueryControl = null;
    var radiusPlace="250";
    var logMessage,logtimeadd,logdateadd,logDirection,logAltitude,logLatLon,logSpeed,logGpsTime,lastAjaxtime,lastTimeBox,checkGPS; 
    var logLogTime,logLat,logLon,logSpeed,logDirection,logAltitude,lastAjaxtime,lastTime,lastTimeBox,logGpsTime,logGSM,logGPS;  
    var countCenmap = 0 ; 
    var countRoute;
    var countPlaceMarker = 0;
    var carpoint =0 ;
    var disRoute = [];
    var loaddingJob;  
    var nameStatusGPS,nameStatusBox;
    var numBox = [];
    var iBox = 0;
    var boxNum,numStatusBox,numStatusGPS,numBoxMoveTo,numPlateMoveTo;
    var latHere,lonHere,latHereA,lonHereA,latHereB,lonHereB,A_latlon,B_latlon = null;
    var clickrowPoi;
    var valJobList = 0; 
    var jobSelect;
    var isPolylineErr;
    var isCheckJson = false;  
    var isMapContext,isPolyline=false; 
    var polyline=null;
    var baseIcon = new GIcon();
    var pointIcon = new GIcon();
    var carIcon = new GIcon();
    var progressJobWin,progressBoxWin,progressAddJobWin,progressAddConfigWin,progressChangeStateWin,progressPlace,progressLoad;
    var htmlCarOff = [];
    var caroff_marker =  [];
    var offcar_latlon =  [];   
    var markerpoi_array = [];
    var htmlpoi = [];
    var IconCar = new GIcon();
    var isOrigin,isDest = false;
    var destPoint,originPoint;
    var countCarOn,countCarOff;
    var markerpoi,markercar; 
    var jobShipment,plateShipment,boxShipment,statusShipment,originShipment,destShipment,latoriginShipment,lonoriginShipment,latdestShipment,londestShipment;
    var COLORS = [["red", "#ff0000"], ["orange", "#ff8800"], ["green","#008000"],["blue", "#000080"], ["purple", "#800080"]];
    var options = {};
    var lineCounter_ = 0;
    var shapeCounter_ = 0;
    var markerCounter_ = 0;
    var colorIndex_ = 0;
    var featureTable_;
    var dataHead;
    var map,timer;
    var chosen = [];
    var saved = []; 
    var layers = [
     { name: "Pano", obj: new GLayer("com.panoramio.all") },
     { name: "Tube", obj: new GLayer("com.youtube.all") },
     { name: "Wiki", obj: new GLayer("org.wikipedia.en") }
    ];
    var boxInBox,plateInBox ;
    var colorJobIDInBox;
    var closeManagePanel=0;  
    //-------------Travel-----------------//
    var markerHuman;
    var overlayInstance = null;
    var client;
    var lastMarkerLocation;
    var panorama;
    var mapT;
    //---------------RouteExt-----------//
    var newMarkers = [];
    var latLngs = [];
    var icons = [];    
    //----------------ControlSpeed--------------------//
    var MySpeedAlert = ['60 km/h','70 km/h','80 km/h','90 km/h','100 km/h','120 km/h','130 km/h','140 km/h','150 km/h','160 km/h','170 km/h'];
    //---------------------------------User---------------------------------//   
    var fovMarker; 
    var fovIcon = new GIcon(G_DEFAULT_ICON);
    var iconSize = 150; 

    var pano;
    var svClient;
    var route;
    var vertices;
    var vertexMap;
    var stepToVertex;
    var stepMap;
    var currentLatLng;
    var panoMetaData;
    var close = false;
    var bearing;
    var nextBearing;
    var nextVertexId;
    var nextVertex;
    var progressArray;
    var progressDistance;
    var currentStep;
    var carMarker;
    var selectedStep = null;
    var driving = false;
    var advanceTimer = null;
    var advanceDelay = 1;
    var customerJob;
    var geoQuery;

    //---------------------test car---------------------//
    var dirn = new GDirections();
    var step = 5; // metres
    var tick = 100; // milliseconds
    var poly;
    var eol;
    var car = new GIcon();
          car.image="caricon.png"
          car.iconSize=new GSize(32,18);
          car.iconAnchor=new GPoint(16,9);
    var marker;
    var k=0;
    var stepnum=0;
    var speed = "";   

    function Ajax_user(){
        var user_url = "http://dev2.dxplace.com/dx1/index.php/demo/json_user/"+nameUser;
        var userMessage=new Array();
        $.getJSON(user_url,function(p){ 
            for(i=0;i<p.userMessage.length;i++){                                         
                 var temp_userMessage = new Array();  
                        temp_userMessage[0] = p.userMessage[i].BoxID;
                        temp_userMessage[1] = p.userMessage[i].NameUser;
                        userMessage[i] =temp_userMessage;                
            }
            setDataNum(userMessage);
            nameUser = userMessage[0][1];  
            var dataHeadUser = '<img src="/images/user.png" > : <font color="red"><b> '+nameUser+'</b></font>';
            $('#dataHeaduid').html(dataHeadUser); 
        });
    }
    function setDataNum(boxNum){
         myDataNum = boxNum; 
         datanumStore.loadData(myDataNum); 
    } 
    //---------------------------------Point---------------------------------//       
    function Ajax_point(){
        var poi_url = "http://dev2.dxplace.com/dx1/index.php/demo/json_point/"+nameUser;
        $.getJSON(poi_url,function(p){ 
            for(i=0;i<p.poiMessage.length;i++){                                         
                 var temp_poiMessage = new Array();  
                        temp_poiMessage[0] = p.poiMessage[i].poiuserID;
                        temp_poiMessage[1] = p.poiMessage[i].poiuserAccount;
                        temp_poiMessage[2] = p.poiMessage[i].poiuserPlace;
                        temp_poiMessage[3] = p.poiMessage[i].poiuserLat;
                        temp_poiMessage[4] = p.poiMessage[i].poiuserLon;
                        temp_poiMessage[5] = p.poiMessage[i].poiuserTime;
                        temp_poiMessage[6] = p.poiMessage[i].poiuserNum;  
                        temp_poiMessage[7] = p.poiMessage[i].autoID; 
                        temp_poiMessage[8] = p.poiMessage[i].poiuserRadius;
                        temp_poiMessage[9] = "<b>ชื่อสถานที่ : </b>"+temp_poiMessage[2]+" <br><b>ละติจูด : </b>"+temp_poiMessage[3]+" <br><b>ลองติจูด : </b>"+temp_poiMessage[4]+" <br><b>รัศมีแจ้งเตือน : </b>"+temp_poiMessage[8]+" <br><b>เวลาอัพเดต : </b>"+temp_poiMessage[5]; 
                        poiMessage[i] =temp_poiMessage;                
            }
            setTimeout("setDataPoint()",5000);
        });      
    }
    function setDataPoint(){
         myDataPoint = poiMessage; 
         pointStore.loadData(myDataPoint); 
         if(myDataPoint.length>0){
                for(i=0 ; i<myDataPoint.length ; i++){
                    if(markerpoi){
                        map.removeOverlay(createMarkerPoi(placepoi,i));
                    }
                     if(map!=null){
                        var placepoi = new GLatLng(myDataPoint[i][3],myDataPoint[i][4]); 
                        map.addOverlay(createMarkerPoi(placepoi,i)); 
                     }
                 } 
            } 
    }      
    //----------------------------Create Point-------------------------------//  
      function createMarkerPoi(point, i) {
          var htmlpoi = "<font size=-1><b>ชื่อผู้ใช้ :</b>"+myDataPoint[i][1]+"&nbsp;&nbsp;<b>ชื่อสถานที่ :</b> "+myDataPoint[i][2]+"<br><b>ละติจูด :</b> "+myDataPoint[i][3]+"<br><b>ลองติจูด :</b>"+myDataPoint[i][4]+"&nbsp;&nbsp;<b><br>รัศมีแจ้งเตือน :</b>"+myDataPoint[i][7]+"</font>";  
        
            markerpoi  = new GMarker(point,{icon: IconPlace}); 
            GEvent.addListener(markerpoi, "click", function() {
                map.setCenter(new GLatLng(myDataPoint[i][3],myDataPoint[i][4]), 17); 
                map.openInfoWindowHtml(map.getCenter(),htmlpoi);  
                highlightCurrentMarker(markerpoi,i); 
            }); 
            GEvent.addListener(markerpoi, "mouseover", function() {
                highlightCurrentMarker(markerpoi,i);    
            });
            return markerpoi; 
        }    
                         
    //---------------------------------CheckStatus---------------------------------//       
    function Ajax_checkStatus(){
       var status_url = "http://dev2.dxplace.com/dx1/index.php/demo/json_checkStatus/"+nameUser;
               if (window.XMLHttpRequest) {
                    xmlReq = new XMLHttpRequest();
                } else {
                    xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
                }
                xmlReq.onreadystatechange = callBack_checkStatus;
                xmlReq.open("GET", status_url, true);
                xmlReq.send(null);   
    }
    function callBack_checkStatus(){
        if (xmlReq.readyState == 4) {
                    if (xmlReq.status == 200) {
                        //alert(xmlReq.responseText);
                        var statusMessage=new Array();
                        p = eval( "(" + xmlReq.responseText + ")" );   
                        for(i=0;i<p.statusMessage.length;i++){     
                             var temp_statusMessage = new Array();  
                                    temp_statusMessage[0] = p.statusMessage[i].BoxID;
                                    temp_statusMessage[1] = p.statusMessage[i].StatusBox;  
                                    temp_statusMessage[2] = p.statusMessage[i].StatusGPS;
                                    temp_statusMessage[3] = p.statusMessage[i].Battery;
                                    temp_statusMessage[4] = p.statusMessage[i].FixLat; 
                                    temp_statusMessage[5] = p.statusMessage[i].FixLon;  
                                    temp_statusMessage[6] = p.statusMessage[i].GPSTime;   
                                    temp_statusMessage[7] = p.statusMessage[i].GSMON; 
                                    temp_statusMessage[8] = p.statusMessage[i].GPSON;
                                    temp_statusMessage[9] = p.statusMessage[i].JobActive; 
                                    temp_statusMessage[10] = p.statusMessage[i].Status;
                                    temp_statusMessage[11] = p.statusMessage[i].Origin; 
                                    temp_statusMessage[12] = p.statusMessage[i].Dest;
                                    temp_statusMessage[13] = p.statusMessage[i].Plate;
                                    temp_statusMessage[14] = p.statusMessage[i].NumAll; 
                                    temp_statusMessage[15] = p.statusMessage[i].NumQueue;
                                    temp_statusMessage[16] = p.statusMessage[i].NumDelivered; 
                                    temp_statusMessage[17] = p.statusMessage[i].NumActive;
                                    temp_statusMessage[18] = temp_statusMessage[1]+"  "+temp_statusMessage[2];   // GSM-GPS
                                    temp_statusMessage[19] = temp_statusMessage[11]+"-"+temp_statusMessage[12];  //Origin-Dest
                                    temp_statusMessage[20] = temp_statusMessage[16]+"/"+temp_statusMessage[15]+"/"+temp_statusMessage[14]; //NumStatus
                                    temp_statusMessage[21] = p.statusMessage[i].Customer_JobID; 
                                    temp_statusMessage[22] = p.statusMessage[i].Direction;
                                    temp_statusMessage[23] = p.statusMessage[i].Speed;
                                    temp_statusMessage[24] = p.statusMessage[i].Altitude;
                                    temp_statusMessage[25] = p.statusMessage[i].Monitor;
                                    temp_statusMessage[26] = p.statusMessage[i].Acinput;
                                    temp_statusMessage[27] = "</font color=black><b>"+temp_statusMessage[21]+"</b></font>&nbsp;|&nbsp;<font color=blue><b>"+temp_statusMessage[10]+"</b></font>&nbsp;|&nbsp;<font color=green><b>"+temp_statusMessage[17]+"<b></font>"; //JobActive        
                                    if(temp_statusMessage[7]==0){textGSM='Offline';}else{textGSM='Online';}
                                    if(temp_statusMessage[8]==0){textGPS='Offline';}else{textGPS='Online';} 
                                    temp_statusMessage[28] = "<b>กล่องหมายเลข : </b>"+temp_statusMessage[0]+"<b>  ทะเบียนรถ : </b>"+temp_statusMessage[13]+
                                                            "<br><b>ใบงานปัจจุบัน : </b>"+temp_statusMessage[21]+"<b>  สถานะ : </b>"+temp_statusMessage[10]+
                                                            "<br><b>ต้นทาง : </b>"+temp_statusMessage[11]+"<b>  ปลายทาง : </b>"+temp_statusMessage[12]+
                                                            "<br><b>ตำแหน่งล่าสุด ละติจูด : </b>"+temp_statusMessage[4]+
                                                            "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>ลองติจูด : </b>"+temp_statusMessage[5]+
                                                            "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>รัศมี : </b>"+temp_statusMessage[22]+  
                                                            "<br><b>สถานะกล่อง GSM : </b>"+textGSM+"<b>  GPS : </b>"+textGPS;
                                    
                                    statusMessage[i] =temp_statusMessage;
                        }
                        window.setTimeout("Ajax_checkStatus()", 10000); 
                        setDataCheckStatus(statusMessage);
                    }else{
                        setTimeout("Disconnect()",10000);   
                    }
        }
    }     
    function Disconnect(){
            Ext.MessageBox.alert('Connection',"คุณหลุดจากการเชื่อมต่อกับระบบ");  
            Ajax_checkStatus(); 
    }                                                         
    function setDataCheckStatus(statusMessage){
         myDataStatus = statusMessage; 
         statusStore.loadData(myDataStatus);    
         countCarOn = 0;
         countCarOff = 0;
             
             for(i=0 ; i<myDataStatus.length ; i++){
                 if(markercar){
                    map.removeOverlay(createMarkerCar(carpoint,i));
                 }
                     if(map!=null){ 
                        if(carpoint=='undefined' && i==iBox){
                
                        }else { 
                            var carpoint = new GLatLng(myDataStatus[i][4],myDataStatus[i][5]); 
                            map.addOverlay(createMarkerCar(carpoint,i));  
                        }
                     }
                 }                                                                        
    } 
    //---------------------------Create Car--------------------------------//
    function createMarkerCar(point,i){
            
            var carDegree = myDataStatus[i][22]; 
            var CAR_NUM_ICONS = 16;
            var CAR_ANGULAR_RES = 360/CAR_NUM_ICONS;
            if (carDegree < 0) {
               carDegree += 360;
            }
            carImageNum = Math.round(carDegree/CAR_ANGULAR_RES) % CAR_NUM_ICONS;
            if(myDataStatus[i][7]==1){
                carImageUrl = "http://dev2.dxplace.com/dx1/images/CarGreen/car_green" + carImageNum + ".png";
                IconCarOn   = new GIcon(carIcon,carImageUrl,null,null); 
                countCarOn +=1;
                markercar  = new GMarker(point,IconCarOn);  
            }else{
                carImageUrl = "http://dev2.dxplace.com/dx1/images/CarRed/car_red" + carImageNum + ".png";
                IconCarOff   = new GIcon(carIcon,carImageUrl,null,null); 
                countCarOff +=1; 
                markercar  = new GMarker(point,IconCarOff);  
            }    
            markercar.setLatLng(point);    
            GEvent.addListener(markercar, "click", function() {
                goCarSelect(i);    
            }); 
          return markercar;
    }   
    function goCarSelect(i){ 
        var htmlcar = "<font size=-1 ><b>หมายเลขกล่อง :</b></font><font size=-1 >&nbsp;"+myDataStatus[i][0]+"</font>&nbsp;&nbsp;"
                        +"<font size=-1 ><b>ทะเบียน :</b></font><font size=-1 >&nbsp;"+myDataStatus[i][13]+"</font>"
                        +"<br><font size=-1 ><b>หมายเลขงานปัจจุบัน :</b></font><font size=-1 >&nbsp;"+myDataStatus[i][9]+"</font>&nbsp;&nbsp;"
                        +"<font size=-1 ><b>สถานะปัจจุบัน :</b></font><font size=-1 >&nbsp;"+myDataStatus[i][10]+"</font>"
                        +"<br><font size=-1 ><b>ต้นทาง :</b></font><font size=-1 >&nbsp;"+myDataStatus[i][11]+"</font>&nbsp;&nbsp;"
                        +"<font size=-1 ><b>ปลายทาง :</b></font><font size=-1 >&nbsp;"+myDataStatus[i][12]+"</font>&nbsp;&nbsp;" 
                        +"<br><font size=-1 ><b>ละติจูด :</b></font><font size=-1 >&nbsp;"+myDataStatus[i][4]+"</font>&nbsp;&nbsp;"
                        +"<font size=-1 ><b>ลองติจูด :</b></font><font size=-1 >&nbsp;"+myDataStatus[i][5]+"</font>&nbsp;&nbsp;"      
                        +"<br><font size=-1 ><b>พิกัดล่าสุดเมื่อ :</b></font><font size=-1 >"+myDataStatus[i][6]+"</font>" 
                        +"<br><font size=-1 ><b>ความเร็ว :</b></font><font size=-1 >&nbsp;"+myDataStatus[i][23]+"</font>&nbsp;&nbsp;"
                        +"<font size=-1 ><b>ทิศทาง :</b></font><font size=-1 >&nbsp;"+myDataStatus[i][22]+"</font>&nbsp;&nbsp;" 
                        +"<font size=-1 ><b>ความสูง :</b></font><font size=-1 >&nbsp;"+myDataStatus[i][24]+"</font>&nbsp;&nbsp;";
            pbarBattery.show();
            $('#statusBoxid').html(myDataStatus[i][25]);
            if(myDataStatus[i][26]==1){
                pbarBattery.updateProgress(1, myDataStatus[i][3]);
            }else{
                pbarBattery.updateProgress((myDataStatus[i][3])/100, "Battery "+myDataStatus[i][3]+"%");
            }
        map.setCenter(new GLatLng(myDataStatus[i][4],myDataStatus[i][5]), 17);
        map.openInfoWindowHtml(map.getCenter(),htmlcar);
        
    }
    function setDataBox(BoxNum){
        dataBoxNumber = dataBoxNumber;
    }
    function checkCenter(){
        if($('#followCarid').is(':checked') && iBox!=0){  
            goCarSelect(iBox);
        }else{
            
        }  
        window.setTimeout("checkCenter()",10000);   
    }
    //---------------------------------Province---------------------------------//       
    function Ajax_province(){
        var province_url = "http://dev2.dxplace.com/dx1/index.php/demo/json_getProvince/"+nameUser;
        province=new Array();
        $.getJSON(province_url,function(p){ 
            for(i=0;i<p.province.length;i++){                                         
                 var temp_province = new Array();  
                        temp_province[0] = p.province[i].Province;   
                        temp_province[1] = p.province[i].ProvinceLat; 
                        temp_province[2] = p.province[i].ProvinceLon;
                        temp_province[3] = p.province[i].ProvinceRadius;
                        temp_province[4] = temp_province[0]+":"+temp_province[1]+":"+temp_province[2]+':'+temp_province[3];
                        province[i] =temp_province;                
            }
            setProvince(province); 
        });            
    }
    function setProvince(province){
         myProvince = province; 
         provinceStore.loadData(myProvince); 
    } 
    //-----------------------------------JobList-----------------------//
    function Ajax_jobList(){
        var jobList_url = "http://dev2.dxplace.com/dx1/index.php/demo/json_jobList/"+deviceID; 
        var jobListTmp = new Array(); 
        $.getJSON(jobList_url, function(p){
            for(i=0;i<p.jobList.length;i++){      
                var temp_jobList = new Array();  
                temp_jobList[0] = p.jobList[i].AutoID; 
                temp_jobList[1] = p.jobList[i].BoxID;
                temp_jobList[2] = p.jobList[i].Plate;
                temp_jobList[3] = p.jobList[i].JobID;   
                temp_jobList[4] = p.jobList[i].Origin; 
                temp_jobList[5] = p.jobList[i].Dest; 
                temp_jobList[6] = p.jobList[i].LatOrigin; 
                temp_jobList[7] = p.jobList[i].LonDest;    
                temp_jobList[8] = p.jobList[i].RadiusOrigin;
                temp_jobList[9] = p.jobList[i].LatDest; 
                temp_jobList[10] = p.jobList[i].LonDest;    
                temp_jobList[11] = p.jobList[i].RadiusDest;
                temp_jobList[12] = p.jobList[i].Status;
                temp_jobList[13] = p.jobList[i].NumRow;
                temp_jobList[14] = p.jobList[i].Customer_JobID;
                temp_jobList[15] = "<b>หมายเลขกล่อง : </b>"+temp_jobList[1]+"<b>&nbsp;&nbsp;ทะเบียน : </b>"+temp_jobList[2]+"<br><b>ใบงานหมายเลข : </b>"+temp_jobList[14]+"<b>&nbsp;&nbsp;สถานะสิ้นสุด : </b>"+temp_jobList[12];
                jobListTmp[i] =temp_jobList;                            
            } 
            jobList= new Array();
            jobList = jobListTmp;
            set_jobList_data(jobList);   
            setJobList(jobList);    
        }); 
    } 
    function setJobList(jobList){
            Boxid_job = jobList[jobNumber][1];
            Plate_job = jobList[jobNumber][2];
            Jobid_job = jobList[jobNumber][3];
            //-----------------SetBoxNow-----------------//
            BoxNow = jobList[0][1]; 
            StatusNow = jobList[0][12];
            JobNow = jobList[0][3];
            PlateNow = jobList[0][2];
            if(StatusNow=='Clear'){
                StatusNow ='-';
                JobNow = '-';
                PlateNow = '-';
                BoxNow = '-';
            }
            var joblistTitle = '<b>รายการใบงาน</b>';
            $('#joblistid').html(joblistTitle); 
            //------------------------loadQueue---------------------//
            htmlQ = '<iframe width="800px" id="queueFrame" src="http://dev2.dxplace.com/dx1/index.php/demo/job_hist/'+deviceID+'" scrolling="0" frameborder="0" height="500"></iframe>';
            $('#queueBoxid').html('<font color=red>'+deviceID+'</font>'); 
            $('#queuePanelid').html(htmlQ); 
    }
    function set_jobList_data(jobListData){
        myData = jobListData;           
        jobListStore.loadData(myData);    
    } 
    //-----------------------------------StateList-----------------------//
    function Ajax_stateList(jobID){
        var stateList_url = "http://dev2.dxplace.com/dx1/index.php/demo/json_stateList/"+jobID; 
        var stateListTmp = new Array(); 
        $.getJSON(stateList_url, function(p){
            for(i=0;i<p.stateList.length;i++){      
                var temp_stateList = new Array();  
                temp_stateList[0] = p.stateList[i].AutoID; 
                temp_stateList[1] = p.stateList[i].JobID;   
                temp_stateList[2] = p.stateList[i].TimeNewActiveJob;
                temp_stateList[3] = p.stateList[i].TimeInOrigin;
                temp_stateList[4] = p.stateList[i].TimeAtOrigin; 
                temp_stateList[5] = p.stateList[i].TimeLoading; 
                temp_stateList[6] = p.stateList[i].TimeOutOrigin; 
                temp_stateList[7] = p.stateList[i].TimeOnDelivery;
                temp_stateList[8] = p.stateList[i].TimeInDest;
                temp_stateList[9] = p.stateList[i].TimeAtDest; 
                temp_stateList[10] = p.stateList[i].TimeOffLoading; 
                temp_stateList[11] = p.stateList[i].TimeOutDest; 
                temp_stateList[12] = p.stateList[i].TimeDelivered; 
                temp_stateList[13] = p.stateList[i].LatInOrigin;
                temp_stateList[14] = p.stateList[i].LonInOrigin;
                temp_stateList[15] = p.stateList[i].LatAtOrigin;
                temp_stateList[16] = p.stateList[i].LonAtOrigin;
                temp_stateList[17] = p.stateList[i].LatLoading;
                temp_stateList[18] = p.stateList[i].LonLoading;
                temp_stateList[19] = p.stateList[i].LatOnDelivery;
                temp_stateList[20] = p.stateList[i].LonOnDelivery;
                temp_stateList[21] = p.stateList[i].LatOutOrigin;
                temp_stateList[22] = p.stateList[i].LonOutOrigin;
                temp_stateList[23] = p.stateList[i].LatInDest;
                temp_stateList[24] = p.stateList[i].LonInDest;
                temp_stateList[25] = p.stateList[i].LatAtDest;
                temp_stateList[26] = p.stateList[i].LonAtDest;
                temp_stateList[27] = p.stateList[i].LatOffLoading;
                temp_stateList[28] = p.stateList[i].LonOffLoading;
                temp_stateList[29] = p.stateList[i].LatDelivered;
                temp_stateList[30] = p.stateList[i].LonDelivered;
                temp_stateList[31] = p.stateList[i].LatOutDest;
                temp_stateList[32] = p.stateList[i].LonOutDest; 
                temp_stateList[33] = p.stateList[i].TimeAll;  
                temp_stateList[34] = p.stateList[i].TimeOrigin;  
                temp_stateList[35] = p.stateList[i].TimeDest;  
                temp_stateList[36] = p.stateList[i].Customer_JobID;
                stateListTmp[i] =temp_stateList;                            
            } 
            stateList= new Array();
            stateList = stateListTmp;
            setStateList(stateList);
        }); 
    } 
    
    function setStateList(stateList){
        jobSelect = stateList[0][1];
        var pickuptitle = 'Pickup ( ใบงานหมายเลข : '+customerJob+')';
        var deliveredtitle = 'Delivery ( ใบงานหมายเลข :  '+customerJob+')';
        $('#pickupid').html(pickuptitle);
        $('#deliveredid').html(deliveredtitle);
        $('#timeallid').html(stateList[0][33]);
        $('#timeoriginid').html(stateList[0][34]);
        $('#timedestid').html(stateList[0][35]);
        
        //--------------------------UpdateTimeArray-----------//
            myPickup = [
                ['จุดที่ 1 เข้าต้นทาง(InOrigin)',stateList[0][3]],
                ['<font color=blue>จุดที่ 2 อยู่ที่ต้นทาง(AtOrigin)</font>','<font color=blue>'+stateList[0][4]+'</font>'],
                ['<font color=blue>จุดที่ 3 เริ่มขึ้นสินค้า(Loading)</font>','<font color=blue>'+stateList[0][5]+'</font>'],
                ['<font color=blue>จุดที่ 4 เสร็จสิ้นการขึ้นสินค้า(On-Delivery)</font>','<font color=blue>'+stateList[0][7]+'</font>'],
                ['จุดที่ 5 ออกจากต้นทาง(OutOrigin)',stateList[0][6]]
            ];
            myDelivery = [
                ['จุดที่ 6 เข้าปลายทาง(InDest)',stateList[jobNumber][8]],
                ['<font color=red>จุดที่ 7 อยู่ที่ปลายทาง(AtDest)</font>','<font color=red>'+stateList[0][9]+'</font>'],
                ['<font color=red>จุดที่ 8 เริ่มลงสินค้า(Off-Loading)</font>','<font color=red>'+stateList[0][10]+'</font>'],
                ['<font color=red>จุดที่ 9 เสร็จสิ้นการลงสินค้า(Delivered)</font>','<font color=red>'+stateList[0][12]+'</font>'],
                ['จุดที่ 10 ออกจากปลายทาง(OutDest)',stateList[0][11]]
            ];
            storePickup.loadData(myPickup);
            storeDelivery.loadData(myDelivery);
            htmlInOrigin = "<font size=-1><b>จุดที่ :</b></font><font size=-1 color=red> 1</font><font size=-1>&nbsp;&nbsp;<b>สถานะงาน :</b> </font><font size=-1 color=red>เข้าต้นทาง<br></font><font size=-1><b>เวลา :</b></font><font size=-1 color='red'> "+stateList[0][3]+"</font>";
            htmlAtOrigin = "<font size=-1><b>จุดที่ :  </b></font><font size=-1 color=red> 2</font><font size=-1>&nbsp;&nbsp;<b>สถานะงาน :</b> </font><font size=-1 color=red>อยู่ที่ต้นทาง<br></font><font size=-1><b>เวลา :</b></font><font size=-1 color='red'>"+stateList[0][4]+"</font>"; 
            htmlLoading= "<font size=-1><b>จุดที่ :  </b></font><font size=-1 color=red> 3</font><font size=-1>&nbsp;&nbsp;<b>สถานะงาน :</b> </font><font size=-1 color=red>เริ่มขึ้นสินค้า<br></font><font size=-1><b>เวลา :</b></font><font size=-1 color='red'>"+stateList[0][5]+"</font>";  
            htmlOnDelivery = "<font size=-1><b>จุดที่ :  </b></font><font size=-1 color=red> 4</font><font size=-1>&nbsp;&nbsp;<b>สถานะงาน :</b> </font><font size=-1 color=red>เสร็จสิ้นการขึ้นสินค้า<br></font><font size=-1><b>เวลา :</b></font><font size=-1 color='red'>"+stateList[0][7]+"</font>"; 
            htmlOutOrigin = "<font size=-1><b>จุดที่ :  </b></font><font size=-1 color=red> 5</font><font size=-1>&nbsp;&nbsp;<b>สถานะงาน :</b> </font><font size=-1 color=red>ออกจากต้นทาง<br></font><font size=-1><b>เวลา :</b></font><font size=-1 color='red'>"+stateList[0][6]+"</font>";   
            htmlInDest = "<font size=-1><b>จุดที่ :  </b></font><font size=-1 color=red> 6</font><font size=-1>&nbsp;&nbsp;<b>สถานะงาน :</b> </font><font size=-1 color=red>เข้าปลายทาง<br></font><font size=-1><b>เวลา :</b></font><font size=-1 color='red'>"+stateList[0][8]+"</font>"; 
            htmlAtDest = "<font size=-1><b>จุดที่ :  </b></font><font size=-1 color=red> 7</font><font size=-1>&nbsp;&nbsp;<b>สถานะงาน :</b> </font><font size=-1 color=red>อยู่ที่ปลายทาง<br></font><font size=-1><b>เวลา :</b></font><font size=-1 color='red'>"+stateList[0][9]+"</font>"; 
            htmlOffLoading = "<font size=-1><b>จุดที่ :  </b></font><font size=-1 color=red> 8</font><font size=-1>&nbsp;&nbsp;<b>สถานะงาน :</b> </font><font size=-1 color=red>เริ่มลงสินค้า<br></font><font size=-1><b>เวลา :</b></font><font size=-1 color='red'>"+stateList[0][10]+"</font>";  
            htmlDelivered = "<font size=-1><b>จุดที่ :  </b></font><font size=-1 color=red> 9</font><font size=-1>&nbsp;&nbsp;<b>สถานะงาน :</b> </font><font size=-1 color=red>เสร็จสิ้นการลงสินค้า<br></font><font size=-1><b>เวลา :</b></font><font size=-1 color='red'>"+stateList[0][12]+"</font>"; 
            htmlOutDest = "<font size=-1><b>จุดที่ :  </b></font><font size=-1 color=red> 10</font><font size=-1>&nbsp;&nbsp;<b>สถานะงาน :</b> </font><font size=-1 color=red>ออกจากปลายทาง<br></font><font size=-1><b>เวลา :</b></font><font size=-1 color='red'> "+stateList[0][11]+"</font>";    
            //-------------------IconStae OnMap-----------------------//
                if(inorigin_marker) map.removeOverlay(inorigin_marker);
                if(atorigin_marker) map.removeOverlay(atorigin_marker);
                if(loading_marker) map.removeOverlay(loading_marker);
                if(outorigin_marker) map.removeOverlay(outorigin_marker); 
                if(ondelivery_marker) map.removeOverlay(ondelivery_marker);
                if(indest_marker) map.removeOverlay(indest_marker);
                if(atdest_marker) map.removeOverlay(atdest_marker);
                if(offloading_marker) map.removeOverlay(offloading_marker);
                if(outdest_marker) map.removeOverlay(outdest_marker);
                if(delivered_marker) map.removeOverlay(delivered_marker);
            //--------InOrigin--------------// 
            if(stateList[0][3]!=0){ 
               map.addOverlay(inorigin_marker,Icon0);
               var inorigin_latlon = new GLatLng(stateList[0][13],stateList[0][14]);
               inorigin_marker.setLatLng(inorigin_latlon,{draggable: true}); 
               GEvent.addListener(inorigin_marker,"click", function() {
                    map.openInfoWindowHtml(inorigin_latlon, htmlInOrigin);
               });
            }
            //------AtOrigin--------------//
            if(stateList[0][4]!=0){
               map.addOverlay(atorigin_marker,Icon1); 
               var atorigin_latlon = new GLatLng(stateList[0][15],stateList[0][16]); 
               atorigin_marker.setLatLng(atorigin_latlon,{draggable: true});
               GEvent.addListener(atorigin_marker,"click", function() {
                    map.openInfoWindowHtml(atorigin_latlon, htmlAtOrigin);
               });      
            }
            //------Loading--------------//
            if(stateList[0][5]!=0){
                map.addOverlay(loading_marker,Icon2);
                var loading_latlon = new GLatLng(stateList[0][17],stateList[0][18]);   
                loading_marker.setLatLng(loading_latlon); 
                GEvent.addListener(loading_marker,"click", function() {
                    map.openInfoWindowHtml(loading_latlon, htmlLoading);
               });    
            }
            //------OutOrigin--------------//
            if(stateList[0][6]!=0){
                map.addOverlay(outorigin_marker,Icon4); 
                var outorigin_latlon = new GLatLng(stateList[0][21],stateList[0][22]); 
                outorigin_marker.setLatLng(outorigin_latlon);
                GEvent.addListener(outorigin_marker,"click", function() {
                    map.openInfoWindowHtml(outorigin_latlon, htmlOutOrigin);
               });      
            }
            //------OnDelivery--------------//
            if(stateList[0][7]!=0){
                map.addOverlay(ondelivery_marker,Icon3); 
                var ondelivery_latlon = new GLatLng(stateList[0][19],stateList[0][20]);
                ondelivery_marker.setLatLng(ondelivery_latlon);  
                GEvent.addListener(ondelivery_marker,"click", function() {
                    map.openInfoWindowHtml(ondelivery_latlon, htmlOnDelivery);
               });    
            }
            //------InDest--------------//
            if(stateList[0][8]!=0){
                map.addOverlay(indest_marker,Icon5); 
                var indest_latlon = new GLatLng(stateList[0][23],stateList[0][24]); 
                indest_marker.setLatLng(indest_latlon); 
                GEvent.addListener(indest_marker,"click", function() {
                    map.openInfoWindowHtml(indest_latlon, htmlInDest);
               });     
            }
            //------AtDest--------------//
            if(stateList[0][9]!=0){
                map.addOverlay(atdest_marker,Icon6);
                var atdest_latlon = new GLatLng(stateList[0][25],stateList[0][26]); 
                atdest_marker.setLatLng(atdest_latlon); 
                GEvent.addListener(atdest_marker,"click", function() {
                    map.openInfoWindowHtml(atdest_latlon, htmlAtDest);
               });      
            }
            //------OffLoading--------------//
            if(stateList[0][10]!=0){
                map.addOverlay(offloading_marker,Icon7);
                var offloading_latlon = new GLatLng(stateList[0][27],stateList[0][28]);  
                offloading_marker.setLatLng(offloading_latlon); 
                GEvent.addListener(offloading_marker,"click", function() {
                    map.openInfoWindowHtml(offloading_latlon, htmlOffLoading);
               });    
            }
            //------Delivered--------------//
            if(stateList[0][11]!=0){
                map.addOverlay(delivered_marker,Icon8);
                var delivered_latlon = new GLatLng(stateList[0][31],stateList[0][32]);
                delivered_marker.setLatLng(delivered_latlon);
                GEvent.addListener(delivered_marker,"click", function() {
                    map.openInfoWindowHtml(delivered_latlon, htmlDelivered);
               });       
            }
            //------OutDest--------------//
            if(stateList[0][12]!=0){
                map.addOverlay(outdest_marker,Icon9); 
                var outdest_latlon = new GLatLng(stateList[0][29],stateList[0][30]);
                outdest_marker.setLatLng(outdest_latlon);  
                GEvent.addListener(outdest_marker,"click", function() {
                    map.openInfoWindowHtml(outdest_latlon, htmlOutDest);
               });    
            }
            //progressJobWin.hide();
    
    }  
    //-----------------------------MAP-------------------------------//  
    function initialize() {
        baseIcon.iconSize=new GSize(32,32);
        baseIcon.shadowSize=new GSize(56,32);
        baseIcon.iconAnchor=new GPoint(16,32);
        baseIcon.infoWindowAnchor=new GPoint(16,0);
        
        carIcon.iconSize=new GSize(28,43);
        carIcon.shadowSize=new GSize(56,32);
        carIcon.iconAnchor=new GPoint(16,32);
        carIcon.infoWindowAnchor=new GPoint(16,0);       
        
        pointIcon.iconSize=new GSize(24,38);
        pointIcon.shadowSize=new GSize(56,32);
        pointIcon.iconAnchor=new GPoint(16,32);
        pointIcon.infoWindowAnchor=new GPoint(16,0);
        
        var martini = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal2/icon27.png", null, "http://maps.google.com/mapfiles/kml/pal2/icon27s.png");
        IconCar = new GIcon(carIcon,"http://dev2.dxplace.com/dx1/images/CarRed/car_red0.png",null,null); 
        IconCarOff   = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal4/icon15.png", null, "http://maps.google.com/mapfiles/kml/pal4/icon15s.png");                   
        IconCarSelect   = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal4/icon31.png", null, "http://maps.google.com/mapfiles/kml/pal4/icon31s.png");  
        IconCarOn   = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal4/icon62.png", null, "http://maps.google.com/mapfiles/kml/pal4/icon62s.png");
        IconPlace   = new GIcon(baseIcon, "http://dev2.dxplace.com/dx1/images/iconPlace.png", null, null);
        IconA   = new GIcon(pointIcon, "http://dev2.dxplace.com/dx1/images/icon_greenA.png", null, "http://maps.google.com/mapfiles/ms/micons/msmarker.shadow.png");                               
        IconB   = new GIcon(pointIcon, "http://dev2.dxplace.com/dx1/images/icon_greenB.png", null, "http://maps.google.com/mapfiles/ms/micons/msmarker.shadow.png");  
        IconWhere   = new GIcon(baseIcon, "http://dev2.dxplace.com/dx1/images/iconWhere.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon0s.png");                              
        Icon0   = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal3/icon0.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon0s.png"); 
        Icon1   = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal3/icon1.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon1s.png"); 
        Icon2   = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal3/icon2.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon2s.png"); 
        Icon3   = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal3/icon3.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon3s.png"); 
        Icon4   = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal3/icon4.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon4s.png"); 
        Icon5   = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal3/icon5.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon5s.png"); 
        Icon6   = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal3/icon6.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon6s.png"); 
        Icon7   = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal3/icon7.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon7s.png"); 
        Icon8   = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal3/icon16.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon16s.png"); 
        Icon9   = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal3/icon17.png", null, "http://maps.google.com/mapfiles/kml/pal3/icon17s.png"); 
        IconStart   = new GIcon(pointIcon, "http://dev2.dxplace.com/dx1/images/BusImage/dd-start.png", null, "http://dev2.dxplace.com/dx1/images/BusImage/shadowPoint.png");                               
        IconStop   = new GIcon(pointIcon, "http://dev2.dxplace.com/dx1/images/BusImage/dd-end.png", null, "http://dev2.dxplace.com/dx1/images/BusImage/shadowPoint.png");                               
 

        A_marker  = new GMarker(new GLatLng(12.90443, 101.529902), {icon:IconA,draggable: true});
        B_marker  = new GMarker(new GLatLng(12.90443, 101.529902), {icon:IconB,draggable: true}); 
        Start_marker  = new GMarker(new GLatLng(12.90443, 101.529902), {icon:IconA,draggable: true});
        Stop_marker  = new GMarker(new GLatLng(12.90443, 101.529902), {icon:IconB,draggable: true}); 
        
        caron_marker  = new GMarker(new GLatLng(12.90443, 101.529902));     
        caroff_marker = new GMarker(new GLatLng(12.90443, 101.529902));
        inorigin_marker = new GMarker(new GLatLng(12.90443, 101.529902));
        atorigin_marker = new GMarker(new GLatLng(12.90443, 101.529902)); 
        loading_marker = new GMarker(new GLatLng(12.90443, 101.529902));
        outorigin_marker = new GMarker(new GLatLng(12.90443, 101.529902));
        ondelivery_marker = new GMarker(new GLatLng(12.90443, 101.529902));
        indest_marker = new GMarker(new GLatLng(12.90443, 101.529902));
        atdest_marker = new GMarker(new GLatLng(12.90443, 101.529902)); 
        offloading_marker = new GMarker(new GLatLng(12.90443, 101.529902));
        outdest_marker = new GMarker(new GLatLng(12.90443, 101.529902));
        delivered_marker = new GMarker(new GLatLng(12.90443, 101.529902));

        if (GBrowserIsCompatible()) {
            map = new GMap2(document.getElementById("map_canvas"));
            var mapControl = new GMapTypeControl();    
            var extLargeMapControl = new ExtLargeMapControl();
            map.addControl(extLargeMapControl);
            //map.addControl(new GLargeMapControl());       
            //map.addControl(new MDControl());          
            latlngThai = new GLatLng(12.90443,101.529902);
            map.setCenter(latlngThai, 6); 
            map.enableScrollWheelZoom(); 
            map.enableDoubleClickZoom(); 
            map.addControl(new GOverviewMapControl());
            setupDragZoom();
            localSearch = new google.maps.LocalSearch();//{externalAds : document.getElementById("ads")});
            map.addControl(localSearch);
            myQueryControl = new QueryControl(localSearch);
            map.addControl(myQueryControl);
            geocoder = new GClientGeocoder();
            client = new GStreetviewClient(); 
            
            var start = new GLatLng(37.090240,-95.712891);
            carMarker = getCarMarker(start);
            map.addOverlay(carMarker);
            carMarker.hide(); 
            //---------------------Menu----------------------//
            map.clearOverlays();
            featureTable_ = document.getElementById("featuretbody");
            select("hand_b");
            polyOptions = {geodesic:true};
            gdir = new GDirections(map, document.getElementById("getDirections2"));
            //-----------------More Button---------------//
             map.addMapType(G_PHYSICAL_MAP);
             var hControl = new GHierarchicalMapTypeControl();
             hControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Labels", false);
             map.addControl(hControl);

             //--------------------Light-----------------------------//
             fovIcon.image = "http://www.vegashotelhunt.com/Vegas-Vision/demoicon.php?yaw=180";
             fovIcon.iconSize = new GSize(iconSize, iconSize);
             fovIcon.iconAnchor = new GPoint(iconSize/2, iconSize/2); //anchor in the middle
             fovIcon.shadow = null;

            //-----------------Event---------------//
            GEvent.addListener(gdir, "load", function(){
                jumpInMyCar();
            });
            GEvent.addListener(gdir, "error", handleErrors);    
            GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay); 

            groute = new GDirections(map, document.getElementById("getRoute"));
            GEvent.addListener(groute, "load", onGRouteLoad); 
            
            GEvent.addListener(map,'singlerightclick', mapContextMenu);    
            GEvent.addListener(map,'click', function(latlng){
                if(markerWhere){
                    map.removeOverlay(markerWhere);
                }
                if(isMapContext==true){
                    mapContext.hide();
                    isMapContext=false;
                }  
            }); 
            GEvent.addListener(dirn,"load", function() {
                //document.getElementById("controls").style.display="none";
                poly=dirn.getPolyline();
                eol=poly.Distance();
                map.setCenter(poly.getVertex(0),17);
                map.addOverlay(new GMarker(poly.getVertex(0),G_START_ICON));
                map.addOverlay(new GMarker(poly.getVertex(poly.getVertexCount()-1),G_END_ICON));
                marker = new GMarker(poly.getVertex(0),{icon:car});
                map.addOverlay(marker);
                var steptext = dirn.getRoute(0).getStep(stepnum).getDescriptionHtml();
                document.getElementById("step").innerHTML = steptext;
                setTimeout("animate(0)",2000);  // Allow time for the initial map display
          });

          GEvent.addListener(dirn,"error", function() {
            alert("Location(s) not recognised. Code: "+dirn.getStatus().code);
          });
                    
        }
     }     
     
    //-----------------------Address-----------------------------------// 
    function foundLocation(response){
          if ((response == null) || (response.Status.code != G_GEO_SUCCESS)){
            alert("\"" + addressToGeoCode + "\" not found");
          }else{
            var place = response.Placemark[0];
            var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
            map.setCenter(point);
            if(markerWhere){
                map.removeOverlay(markerWhere);
            }
            markerWhere = new GMarker(point, {title: place.address,icon : IconWhere} ); 
            map.addOverlay(markerWhere);
            markerWhere.openInfoWindowHtml("<font size=-1><b>ชื่อสถานที่</b> : "+place.address+"<br><b>ละติจูด,ลองติจูด</b> : "+addressToGeoCode+"</font>");
          }
    }
    var txtProvince = "";
    var dataProvince = new Array();
    var numProvince = 0;
    var iStep=0; 
    var placeAddress = new Array();
    var sumPlace = "";
    function foundProvince(response){
          if ((response == null) || (response.Status.code != G_GEO_SUCCESS)){
            //alert("\"" + addressToGeoCode + "\" not found");
            //alert(iStep);  
            iStep++;
          }else{
            var place = response.Placemark[0];
            var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
            sumPlace += place.address+"\n"; 
            var province = (place.address).split(" ");
            var wordProvince = province[province.length-2];
            var isProvince =new RegExp("[0-9]");
            if(place.address!=""){  
                if(isProvince.test(wordProvince)){
                    dataProvince[numProvince] = province[province.length-3];     
                    if(numProvince==0){
                        txtProvince += (province[province.length-3]).replace("จ.","")+",";
                    }else{       
                        if(dataProvince[numProvince]!=dataProvince[numProvince-1]){
                            txtProvince += ","+(province[province.length-3]).replace("จ.","");
                        }
                    }    
                }else{         
                    dataProvince[numProvince] = province[province.length-2]; 
                    if(numProvince==0){
                        txtProvince += (province[province.length-2]).replace("จ.","")+",";
                    }else{       
                        if(dataProvince[numProvince]!=dataProvince[numProvince-1]){
                            txtProvince += ","+(province[province.length-2]).replace("จ.","");
                        }
                    }   
                }
                numProvince++;  
              }
          }
          g++;
          if(g<numAllStep){
            callGeoCoder();
          }else{
            //alertProvince();
            //alert("G :"+g+" ,Error : "+iStep);
            //alert(sumPlace);
          }
    }
    function returnAddress(response){
          if ((response == null) || (response.Status.code != G_GEO_SUCCESS)){
                alert("\"" + addressToGeoCode + "\" not found");
                return "";
          }else{
                var place = response.Placemark[0];
                var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
                if(place.address!=''){
                return place.address;
                }else{
                    return "";
                }
          }
    }
     function setupDragZoom() {
          var boxStyleOpts = {
              opacity: .2,
              border: "1px solid red" ,
              title:'Zoom Area'
          };
          var otherOpts = {
              buttonHTML: "<img src='http://dev2.dxplace.com/dx1/images/zoom_b.png' />",
              buttonZoomingHTML: "<img  src='http://dev2.dxplace.com/dx1/images/zoom_bselect.png' />",
              buttonStartingStyle: {width: '24px', height: '24px',marginLeft:'196px',marginTop:'-110px'},
              tooltip: {
                    text: 'ขยายภาพพื้นที่ที่กำหนด', 
                    title:'ขยายแผนที่'
                },
              overlayRemoveTime: 1000
          };
          map.addControl(new DragZoomControl(boxStyleOpts, otherOpts, {}), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(13, 120)));
    }
    //-------------------------------------PoiContextMenu-----------------------------//
    function mapContextMenu(point, src, overlay,latlng) {
        isMapContext=true;
        if(!mapContext) {
            mapContext = new Ext.menu.Menu({
                items: [{
                    text: 'เส้นทางจากที่นี่',
                    handler: function() {
                            map.removeOverlay(A_marker);
                            map.addOverlay(A_marker,IconA);
                            A_latlon = new GLatLng(latHere,lonHere);  
                            A_marker.setLatLng(A_latlon); 
                    }
                },{
                    text: 'เส้นทางสู่ที่นี่',
                    handler: function() {
                            map.removeOverlay(B_marker);
                            map.addOverlay(B_marker,IconB);
                            B_latlon = new GLatLng(latHere,lonHere);  
                            B_marker.setLatLng(B_latlon); 
                            
                            provinceLatLng = new Array();
                            dataProvince = new Array();
                            txtProvince = "";
                            sumPlace = "";
                            numAllStep = 0;
                            numProvince = 0;
                            g = 0;
                            getWayPoint();
                    }
                },{
                    text: 'ที่นี่ที่ไหน ?',
                    handler: function() {
                            addressToGeoCode = new GLatLng(latHere,lonHere); 
                            geocoder.getLocations(addressToGeoCode, foundLocation);
                    }
                },'-',{
                    text: 'บันทึกพิกัดนี้',
                    handler: function() {  
                        if (point && countPlaceMarker==0) {
                                singleClick = !singleClick; 
                                $('#followCarid').attr('checked', false); 
                                setTimeout("if (singleClick) createCircle(new GLatLng("+ latHere + ", " + lonHere +"), 200)", 300);
                                countPlaceMarker++;
                                select("hand_b");
                                //GEvent.removeListener(listener);
                        }             
                    }
                }]
            });
        }
        mapContext.point = point;
        mapContext.point = map.fromContainerPixelToLatLng(point);
        dataLatLon = mapContext.point;
        textLatLon = ""+dataLatLon+"";
        ArrayDataLatLon = (textLatLon.substring(1,textLatLon.length-1)).split(",");
        latHere = ArrayDataLatLon[0];
        lonHere = (ArrayDataLatLon[1]).substring(1,ArrayDataLatLon[1].length);
        mapContext.showAt([Ext.getCmp('content-panel').body.getAnchorXY()[0] + point.x, Ext.getCmp('content-panel').body.getAnchorXY()[1] + point.y]);
    } 
    function getPoint(Lat,Lon){
        alert(Lat+","+Lon);
        map.setCenter(new GLatLng(Lat,Lon), 12);
        $('#followCarid').attr('checked', false);
        place_marker  = new GMarker(new GLatLng(Lat,Lon),IconPlace);
        map.addOverlay(place_marker,IconPlace);
        place_latlon = new GLatLng(Lat,Lon);
        place_marker.setLatLng(place_latlon);
        htmlPosition = "<font size=-1><b>ตำแหน่งที่ :</b></font><font size=-1 color=red> "+Lat+","+Lon+"</font>";
        map.openInfoWindowHtml(place_latlon, htmlPosition);
    }
    function getWayPoint(){
        map.removeOverlay(A_marker);
        map.removeOverlay(B_marker);
        $('#followCarid').attr('checked', false);
        setDirections(A_latlon, B_latlon, "th"); 
        //dirn.loadFromWaypoints([A_latlon,B_latlon],{getPolyline:true,getSteps:true});
               
        mapContext.hide(); 
    }
 
     //====================GDirection================================//
     function setDirections(fromAddress, toAddress, locale) {
          $('#followCarid').attr('checked', false); 
          Ext.getCmp('wayPanel').expand(true);
          Ext.getCmp('dataPointid').expand(true); 
          Ext.getCmp('dataPortid').collapse(true); 
          gdir.load("from: " + fromAddress + " to: " + toAddress,{locale: 'th', getPolyline:true, getSteps : true, preserveViewport : true ,travelMode : 'G_TRAVEL_MODE_DRIVING' });
     }
     //------------carrun------------------//
      function animate(d) {
        if (d>eol) {
          document.getElementById("step").innerHTML = "<b>Trip completed<\/b>";
          document.getElementById("distance").innerHTML =  "Miles: "+(d/1609.344).toFixed(2);
          return;
        }
        var p = poly.GetPointAtDistance(d);
        if (k++>=180/step) {
          map.panTo(p);
          k=0;
        }
        marker.setPoint(p);
        document.getElementById("distance").innerHTML =  "Miles: "+(d/1609.344).toFixed(2)+speed;
        if (stepnum+1 < dirn.getRoute(0).getNumSteps()) {
          if (dirn.getRoute(0).getStep(stepnum).getPolylineIndex() < poly.GetIndexAtDistance(d)) {
            stepnum++;
            var steptext = dirn.getRoute(0).getStep(stepnum).getDescriptionHtml();
            document.getElementById("step").innerHTML = "<b>Next:<\/b> "+steptext;
            var stepdist = dirn.getRoute(0).getStep(stepnum-1).getDistance().meters;
            var steptime = dirn.getRoute(0).getStep(stepnum-1).getDuration().seconds;
            var stepspeed = ((stepdist/steptime) * 2.24).toFixed(0);
            step = stepspeed/2.5;
            speed = "<br>Current speed: " + stepspeed +" mph";
          }
        } else {
          if (dirn.getRoute(0).getStep(stepnum).getPolylineIndex() < poly.GetIndexAtDistance(d)) {
            document.getElementById("step").innerHTML = "<b>Next: Arrive at your destination<\/b>";
          }
        }
        setTimeout("animate("+(d+step)+")", tick);
      }
     //-----Arrow---------//
     function setCarMarkerImage(bearing) {
        carMarker.setImage(getArrowUrl(bearing));
     }
     function getCarMarker(start) {
        return new GMarker(start, getArrowIcon(0.0));
     }
     function jumpInMyCar() {
          route = gdir.getRoute(0);
          collapseVertices(gdir.getPolyline());
          map.setCenter(vertices[0], 16);
          renderTextDirections();
          checkCoverage(0);
    }
    function checkCoverage(step) {
      if (step > route.getNumSteps()) {
        //hideStatus();
        //stopDriving();
        jumpToVertex(0);
      } else {
        if (step == route.getNumSteps()) {
          ll = route.getEndLatLng();
        } else {
          ll = route.getStep(step).getLatLng();
        }
      }
    }
    function collapseVertices(path) {
         vertices = new Array();
         vertexMap = new Array(path.getVertexCount());

         vertices.push(path.getVertex(0));
         vertexMap[0] = 0;
         for (var i = 1; i < path.getVertexCount(); i++) {
           if (! path.getVertex(i).equals(vertices[vertices.length - 1])) {
             vertices.push(path.getVertex(i));
           }
           vertexMap[i] = vertices.length - 1;
         }

         stepToVertex = new Array(route.getNumSteps());
         stepMap      = new Array(vertices.length);

         for (var i = 0; i < route.getNumSteps(); i++) {
           stepToVertex[i] = vertexMap[route.getStep(i).getPolylineIndex()];
         }

         var step = 0;
         for (var i = 0; i < vertices.length; i++) {
           if (stepToVertex[step + 1] == i) {
             step++;
           }
           stepMap[i] = step;
         }
     }
     var provinceLatLng = new Array();
     var g = 0;
     var numAllStep = 0;
     function callGeoCoder(){
        geocoder.getLocations(provinceLatLng[g], foundProvince); 
     }
     function renderTextDirections() {
          var route = gdir.getRoute(0);
          var startAddress = route.getStartGeocode().address;
          var endAddress = route.getEndGeocode().address;
          
          var html  = "<table width=270px style='border: 1px red;' cellspacing=5px>"; 
              html +=  "<tr><td><img src=http://maps.google.com/intl/en_us/mapfiles/icon_greenA.png><font size=-1 color=red><b>ต้นทาง  : "+getDirectionsWaypointHtml(startAddress, "A")+"</b></font></td></tr>";
              html +=  "<tr><td align=right><font size=-1 color=blue><b>"+getDivHtml("summary", "", route.getSummaryHtml())+"</b></font></td></tr>";
          var iStepNum = 0
          numAllStep = route.getNumSteps(); 
          alert(route.getNumSteps());
          for (var n = 0; n < route.getNumSteps(); n++) { 
                provinceLatLng[n] = route.getStep(n).getLatLng();   
                
                html += '<tr><td><font size=-1><a onclick="selectStep(' + n + ')">';
                html += getDivHtml("step" + n, "dstep", route.getStep(n).getDescriptionHtml());
                html += '</a></font></td></tr>';
          }
          callGeoCoder();
          html += "<tr><td><img src=http://maps.google.com/intl/en_us/mapfiles/icon_greenB.png><font color=red size=-1><b>ปลายทาง : "+getDirectionsWaypointHtml(endAddress, "B")+"</b></font></td></tr></table>";
          document.getElementById("getDirections").innerHTML = html;
          setWaypointIcon('A');
          setWaypointIcon('B');

    }    
    function alertProvince(){  
        //alert(txtProvince);
        numStep = 0
        for(k=0;k<provinceLatLng.length;k++){
            if(provinceLatLng[k] !=""){
                numStep++;
            }    
        }
        //alert("Have LatLng : "+numStep+" point"); 
        txtProvince = "";
    }  
    function getDirectionsWaypointHtml(address, letter) {
            var content = getDivHtml('letter' + letter, 'letterIcon', "");
            content += '<span class="waypointAddress">' + address + '</span>';
            return getDivHtml("wayPoint" + letter, "waypoint", content);
    }
    function getDivHtml(id, cssClass, content) {
          var div = "<div";
          if (id != "") {
            div += ' id="' + id + '"';
          }
          if (cssClass != "") {
            div += ' class="' + cssClass + '"';
          }
          div += '>' + content + '</div>';
          return div;
    }
    function setWaypointIcon(letter) {
          var png = 'http://maps.google.com/intl/en_us/mapfiles/icon_green' + letter + '.png';
          document.getElementById('letter' + letter).style.backgroundImage = 'url(' + png + ')';
    }
    function selectStep(i) {
          var vertex = vertexMap[route.getStep(i).getPolylineIndex()];
          jumpToVertex(vertex);
    }
    function getArrowIcon(bearing) {
          var icon = new GIcon();
          icon.image = getArrowUrl(bearing);
          icon.iconSize = new GSize(24, 24);
          icon.iconAnchor = new GPoint(12, 12);
          return icon;
    }
   function getArrowUrl(bearing) {
        var id = (3 * Math.round(bearing / 3)) % 120;
        return "http://maps.google.com/mapfiles/dir_" + id + ".png";
    }
     function jumpToVertex(idx) {
          currentLatLng = vertices[idx];
          nextVertex = vertices[idx + 1];
          nextVertexId = idx + 1;

          bearing = getBearingFromVertex(idx);
          nextBearing = getBearingFromVertex(idx + 1);

           map.setCenter(currentLatLng);
          setCarMarkerImage(bearing);
          carMarker.setLatLng(currentLatLng);
          carMarker.show();

          currentStep = stepMap[idx];
          constructProgressArray(idx);
          setProgressDistance();
          updateProgressBar(0);
     }
     function constructProgressArray(vertexId) {
          progressArray = new Array();
          var stepStart = stepToVertex[currentStep];
          for (var i = stepToVertex[currentStep]; i <= vertexId + 1; i++) {
            progressArray.push(vertices[i]);
          }
    }
    function setProgressDistance() {
          var polyline = new GPolyline(progressArray);
          progressDistance = polyline.getLength();
    }
    function updateProgressBar(progress) {
          progress = (progress < 0 ? 0 : progress);
          var stepLength = route.getStep(currentStep).getDistance().meters;
          setProgressBarLength(1 - (progress / stepLength));
    }
     function getBearingFromVertex(n) {
          var origin = vertices[n];
          var destination = vertices[n+1];
          if (destination != undefined) {
            return getBearing(origin, destination);
          } else {
            return null;
          }
    }
    function getBearing(origin, destination) {
          if (origin.equals(destination)) {
            return null;
          }
          var lat1 = origin.lat().toRad();
          var lat2 = destination.lat().toRad();    
          var dLon = (destination.lng()-origin.lng()).toRad();
          
          var y = Math.sin(dLon) * Math.cos(lat2);
          var x = Math.cos(lat1)*Math.sin(lat2) -
                  Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);
          return Math.atan2(y, x).toBrng();
    }
    Number.prototype.toRad = function() {
      return this * Math.PI / 180;
    }
    Number.prototype.toDeg = function() {
      return this * 180 / Math.PI;
    }
    Number.prototype.toBrng = function() {
      return (this.toDeg()+360) % 360;
    }
    function setProgressBarLength(progress) {
      var width = (636 * progress);
      if (width < 0) {
        width = 0;
      }
    }

    function onGDirectionsAddOverlay(){ 
          for (var i=0; i<newMarkers.length; i++){
            map.removeOverlay(newMarkers[i]);
          }

          for (var i=0; i<=gdir.getNumRoutes(); i++){
            var originalMarker = gdir.getMarker(i);
            latLngs[i] = originalMarker.getLatLng();
            icons[i] = originalMarker.getIcon();
            newMarkers[i] = new GMarker(latLngs[i],{icon:icons[i], draggable:true, title:'Draggable'});
            map.addOverlay(newMarkers[i]);

            GEvent.addListener(newMarkers[i], "dragend", function(){
              var points = [];
              for (var i=0; i<newMarkers.length; i++){
                points[i]= newMarkers[i].getLatLng();
              }
              gdir.loadFromWaypoints(points);
            });

            copyClick(newMarkers[i],originalMarker);

            map.removeOverlay(originalMarker);
          }
          function copyClick(newMarker,oldMarker){
            GEvent.addListener(newMarker, 'click', function(){
              GEvent.trigger(oldMarker,'click');
            });
          }
    }
    function addImg(url, id) {
         var img = document.createElement("img");
         img.src = url;
         document.getElementById(id).innerHTML = "";
         document.getElementById(id).appendChild(img);
    }
    function handleErrors(){
         isPolylineErr = true ;
         if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS){
           Ext.MessageBox.alert("ไม่พบเส้นทางจากต้นทาง-ปลายทาง");
         }else if (gdir.getStatus().code == G_GEO_SERVER_ERROR){
           alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
         }else if (gdir.getStatus().code == G_GEO_MISSING_QUERY){
           alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
         }else if (gdir.getStatus().code == G_GEO_BAD_KEY){
           alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
         }else if (gdir.getStatus().code == G_GEO_BAD_REQUEST){
           alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
         }else{ Ext.MessageBox.alert("ไม่พบเส้นทางจากต้นทาง-ปลายทาง");  }
    }
     //----------------CenterMap-----------------//
     function centerState(LAT,LON,STATE){
        alert(LAT+","+LON);
         map.setCenter(new GLatLng(LAT, LON), 15);
         if(STATE == 'InOrigin'){
             map.openInfoWindow(map.getCenter(),htmlInOrigin);
         }else if(STATE == 'AtOrigin'){
             map.openInfoWindow(map.getCenter(),htmlAtOrigin);
         }else if(STATE == 'Loading'){
             map.openInfoWindow(map.getCenter(),htmlLoading);
         }else if(STATE == 'OnDelivery'){
             map.openInfoWindow(map.getCenter(),htmlOnDelivery);
         }else if(STATE == 'OutOrigin'){
             map.openInfoWindow(map.getCenter(),htmlOutOrigin);
         }else if(STATE == 'InDest'){
             map.openInfoWindow(map.getCenter(),htmlInDest);
         }else if(STATE == 'AtDest'){
             map.openInfoWindow(map.getCenter(),htmlAtDest);
         }else if(STATE == 'OffLoading'){
             map.openInfoWindow(map.getCenter(),htmlOffLoading);
         }else if(STATE == 'Delivered'){
             map.openInfoWindow(map.getCenter(),htmlDelivered);
         }else if(STATE == 'OutDest'){
             map.openInfoWindow(map.getCenter(),htmlOutDest);
         }
    }
    //----------------CenterPlace-----------------//
     function centerPlace(placeNo){
         map.setCenter(new GLatLng(myDataPoint[placeNo][3], myDataPoint[placeNo][4]), 12);
         htmlpoi = "<font size=-1><b>ชื่อผู้ใช้ :</b>"+myDataPoint[placeNo][1]+"&nbsp;&nbsp;<b>ชื่อสถานที่ :</b>"+myDataPoint[placeNo][2]+"<br><b>ละติจูด :</b>"+myDataPoint[placeNo][3]+"&nbsp;&nbsp;<b>ลองติจูด :</b>"+myDataPoint[placeNo][4]+"</font>";
         map.openInfoWindowHtml(map.getCenter(), htmlpoi);
     }
    //----------------------Action-------------------------//
    var addPoint = new Ext.Action({ 
            text:'<img src="/images/plugin_add.gif" > สถานที่',
            id : 'addPointid', 
            tooltip: {
                text: 'แสดงข้อมูลสถานที่,ค้นหาเส้นทาง ระยะทาง เวลาที่ใช้โดยประมาณ', 
                title:'จัดการข้อมูลพิกัด'
            }, 
            handler:function() {   
                Ext.getCmp('dataPointid').expand(true); 
                Ext.getCmp('dataPortid').collapse(true); 
                Ext.getCmp('content-panel').layout.setActiveItem('map-panel');  
            }
    });
    var viewData = new Ext.Action({ 
            text:'<img src="/images/application_view_list.png" > รายการใบงานในกล่อง',
            id : 'viewDataid', 
            tooltip: {
                text: 'แสดงข้อมูลกล่อง,ใบงาน,สถานะของใบงานทั้งหมด', 
                title:'รายการใบงานในกล่อง'
            }, 
            handler:function() {
                Ext.getCmp('dataPointid').collapse(true); 
                Ext.getCmp('dataPortid').expand(true);   
            }
    });
    var viewPlate = new Ext.Action({ 
            text:'<img src="/images/application_view_list.png" > งานที่อยู่ในกล่องทั้งหมด',
            id : 'viewPlate', 
            tooltip: {
                text: 'แสดงข้อมูลจัดการรายการรถและรายการใบงาน', 
                title:'รายการรถและใบงาน'
            }, 
            handler:function() {
                Ext.getCmp('content-panel').layout.setActiveItem('plate-panel');
                Ext.getCmp('dataPointid').collapse(true); 
                Ext.getCmp('dataPortid').collapse(true);  
            }
    });
    var viewAllJobBox = new Ext.Action({ 
            text:'<img src="/images/application_view_list.png" > งานปัจจุบันที่ดำเนินการอยู่',
            id : 'viewAllJobBoxid', 
            tooltip: {
                text: 'แสดงข้อมูลรายการใบงานทั้งหมดที่วิ่งอยู่', 
                title:'รายการใบงานที่ Active'
            }, 
            handler:function() {
                getAllJobBox();
                Ext.getCmp('content-panel').layout.setActiveItem('alljobbox-panel');
                Ext.getCmp('dataPointid').collapse(true); 
                Ext.getCmp('dataPortid').collapse(true);  
            }
    });
    var viewMap = new Ext.Action({ 
            text:'<img src="/images/feed_add.png" > ติดตามรถ',
            id : 'viewMapid', 
            tooltip: {
                text: 'แสดงข้อมูลการติดตามรถและสถานะต่างๆบนแผนที่', 
                title:'แผนที่และตำแหน่งรถ'
            }, 
            handler:function() {
                Ext.getCmp('content-panel').layout.setActiveItem('map-panel'); 
                Ext.getCmp('dataPortid').expand(true); 
                Ext.getCmp('dataPointid').collapse(true);
            }
    });
     var addjobMenu = new Ext.Action({
            text:'<img src="/images/add.gif" >เพิ่มใบงาน',
            tooltip: {
                    text: 'เพิ่มใบงาน', 
                    title:'เพิ่มข้อมูลของกล่อง'
            },  
            handler:function() { 
                Ajax_province();
                Ext.getCmp('content-panel').layout.setActiveItem('addshipment-panel'); 
            }
     }); 
     var addplateMenu = new Ext.Action({
            text:'<img src="/images/add.gif" >เซตทะเบียนรถ',
            tooltip: {
                    text: 'เซตทะเบียนรถในกล่อง', 
                    title:'เพิ่มข้อมูลของกล่อง'
            },  
            handler:function() { 
                Ajax_province();
                Ext.getCmp('content-panel').layout.setActiveItem('addplate-panel'); 
            }
     }); 
      var clearalljobMenu = new Ext.Action({
            text:'<img src="http://dev2.dxplace.com/dx1/images/delete.gif" >เคลียร์ข้อมูลใบงานทั้งหมด', 
            tooltip: {
                    text: 'ลบข้อมูลใบงานทั้งหมดที่อยู่ในกล่อง', 
                    title:'เคลียร์ข้อมูลใบงานทั้งหมด'
            }, 
            handler:function() { 
                setClear();
            }
     }); 
     var closeJobListBox = new Ext.Action({
            text:'<img src="http://dev2.dxplace.com/dx1/images/folder_go.png" > กลับ', 
            tooltip: {
                    text: 'กลับ',
                    title:'กลับไปหน้าก่อนหน้านี้'
            }, 
            handler:function() { 
                Ext.getCmp('content-panel').layout.setActiveItem('plate-panel'); 
            }
     });
     
     var refreshTracking = new Ext.Action({  
            text : '<img src="http://dev2.dxplace.com/dx1/images/refresh.gif"> Refresh RealTime Tracking ',
            handler: function() {
                    Ajax_tracking();  
            }  
     });
     var refreshJob = new Ext.Action({  
            text : '<img src="http://dev2.dxplace.com/dx1/images/refresh.gif"> Refresh JobData ',
            handler: function() {
                    Ajax_jobList();  
            } 
     });
     var refreshState = new Ext.Action({  
            text : '<img src="http://dev2.dxplace.com/dx1/images/refresh.gif"> ',
            handler: function() {
                    Ajax_stateList(jobSelect); 
            }  
     });
     var refreshJobBox = new Ext.Action({  
            text : '<img src="http://dev2.dxplace.com/dx1/images/refresh.gif"> Refresh JobList ',
            handler: function() {
                    getJobBox();  
            }  
     });   
     var refreshJobActive = new Ext.Action({  
            text : '<img src="http://dev2.dxplace.com/dx1/images/refresh.gif"> Refresh JobActive ',
            handler: function() {
                    getAllJobBox();  
            }  
     });     
     var refreshCheckBox = new Ext.Action({  
            text : '<img src="http://dev2.dxplace.com/dx1/images/refresh.gif"> Refresh CheckBox ',
            handler: function() {
                    Ajax_checkStatus();  
            }  
     });
     var queueMenu = new Ext.Action({  
            text:'<img src="/images/book.png\" >ดูคิวงานในกล่อง', 
            tooltip: {
                    text: 'ดูคิวงานที่เหลืออยู่ในกล่อง', 
                    title:'ดูคิวงานในกล่อง'
            }, 
            handler:function() {
                Ext.getCmp('content-panel').layout.setActiveItem('queue-panel');   
            }
     });
     //----------------------ActionMenu----------------//
    var viewPanel = new Ext.Action({ 
            text: '<img src="/images/application_view_list.png" > รายการงาน',
            tooltip: {
                text: 'ดูส่วนต่างๆของระบบ', 
                title:'View'
            },
            menu : {
                items: [viewAllJobBox,viewPlate]
            }
    });
    var manageMember = new Ext.Action({ 
            text: '<img src="/images/user_suit.gif" >ระบบสมาชิก',
            tooltip: {
                text: 'ล็อคอิน,สมัครสมาชิก ผ่านหน้าเวป', 
                title:'ระบบสมาชิก'
            },
            menu : {
                items: [{                                                   
                            text:'<img src="/images/user_add.png\">สมัครสมาชิก',  
                            handler:function() {
                                    window.open('http://www.dxplace.com/user/register');
                            }
                      },{                                                   
                            text:'<img src="/images/user_red.png\">เข้าสู่ระบบ',  
                            handler:function() {
                                    window.open('http://www.dxplace.com');
                            }
                      }]
                }
    });
    //------------------------LoadBox-----------------//
    var datanumStore = new Ext.data.SimpleStore({
        fields: [
            {name: 'BoxNum'},
            {name: 'NameUser'}    
                ]
        });    
    //------------------------LoadProvince-----------------//
    var provinceStore = new Ext.data.SimpleStore({
        fields: [
            {name: 'Province'},
            {name: 'ProvinceLat'},
            {name: 'ProvinceLon'},
            {name: 'ProvinceRadius'},
            {name: 'ProvinceAll'}           
        ]
    });
    //------------------------JobStore----------------------//
    function BoxIDChange(val){
            if(val == 'undefined' || val == ''){val='-';} 
            return '<span style="color:#FFFFFF"><b>' + val + '</b></span>';
    }
    function Plate(val){
            if(val == 'undefined' || val == ''){val='-';} 
            return '<span style="color:#bd1010"><b>' + val + '</b></span>';
    }
    function JobID(val){
            if(val == 'undefined' || val == ''){val='-';} 
            return '<span style="color:green"><b>' + val + '</b></span>';
    }
    function CustomerJob(val){
         if(val == 'undefined' || val == ''){val='-';} 
            return '<span style="color:green;"><b>' + val + '</b></span>';
    }
    function StatusChange(val){
            if(val == 'undefined' || val == ''){val='-';} 
            return '<span style="color:blue;"><b>' + val + '</b></span>';
    }
    var jobListStore = new Ext.data.SimpleStore({
        fields: [
            {name: 'AutoID'},
            {name: 'BoxID'},
            {name: 'Plate'},
            {name: 'JobID'},
            {name: 'Origin'},
            {name: 'Dest'},
            {name: 'LatOrigin'},
            {name: 'LonOrigin'},
            {name: 'RadiusOrigin'},
            {name: 'LatDest'},
            {name: 'LonDest'},
            {name: 'RadiusDest'},
            {name: 'Status'},
            {name: 'NumRow'},
            {name: 'CustomerJob'}           
                ]
    });
     //--------------------------------------JobGrid----------------------------//         
    var jobListGrid = new Ext.grid.GridPanel({
                store: jobListStore,
                border : false,
                columns: [                
                    {id:'ID',header: "<center><b>หมายเลขใบงาน</b></center>",css: 'text-align: center;',renderer: CustomerJob,  width: 100, sortable: true, dataIndex:'CustomerJob'},
                    {header: "<center><b>ต้นทาง</b></center>",css: 'text-align: center;',  width: 110, sortable: true, dataIndex: 'Origin'},
                    {header: "<center><b>ปลายทาง</b></center>",css: 'text-align: center;', width: 110, sortable: true,dataIndex: 'Dest'},
                    {header: "<center><b>สถานะ</b></center>",css: 'text-align: center;',renderer: BoxIDChange, width: 105, sortable: true,dataIndex: 'Status'}  
                ],
                stripeRows: true,
                autoHeight:true, 
                autoWidth : true,  
                onRender: function() {
                        Ext.grid.GridPanel.prototype.onRender.apply(this, arguments);
                        this.addEvents("beforetooltipshow");
                        this.tooltip = new Ext.ToolTip({
                            renderTo: Ext.getBody(),
                            target: this.view.mainBody,
                            listeners: {
                                beforeshow: function(qt) {
                                    var v = this.getView();
                                    var row = v.findRowIndex(qt.baseTarget);
                                    var cell = v.findCellIndex(qt.baseTarget);
                                    this.fireEvent("beforetooltipshow", this, row, cell);
                                },
                                scope: this
                            }
                        });
                    },
                    listeners: {
                        render: function(g) {
                            g.on("beforetooltipshow", function(grid, row, col,r) {
                                grid.tooltip.body.update(myData[row][15]);
                            });
                        }
                    },
                    bbar: new Ext.PagingToolbar({
                        pageSize: 15,
                        store: jobListStore,                        
                        displayInfo: true                                                     
                    })  
    });                                                                                            
    //-------------------JoblistAllGrid----------------------------//
    var jobListAllGrid =  new Ext.grid.GridPanel({
                store: jobListStore,
                border : false,
                columns: [         
                    {id:'ID',header: "<center><b>หมายเลขกล่อง</b></center>",css: 'text-align: center; background-color:#bd1010;', renderer: BoxIDChange, width: 90, sortable: true, dataIndex:'BoxID'},
                    {header: "<center><b>หมายเลขทะเบียนรถ</b></center>",css: 'text-align: center; background-color:#f1a7a7;',renderer: Plate,  width: 120, sortable: true, dataIndex:'Plate'},
                    {header: "<center><b>หมายเลขใบงาน</b></center>",css: 'text-align: center;',renderer: CustomerJob,  width: 90, sortable: true, dataIndex:'CustomerJob'},
                    {header: "<center><b>ต้นทาง</b></center>",css: 'text-align: center;',  width: 200, sortable: true, dataIndex: 'Origin'},
                    {header: "<center><b>ปลายทาง</b></center>",css: 'text-align: center;', width: 200, sortable: true,dataIndex: 'Dest'},
                    {header: "<center><b>สถานะ</b></center>",css: 'text-align: center;',renderer: Status, width: 100, sortable: true,dataIndex: 'Status'}  
                ],
                stripeRows: true,
                autoHeight:true, 
                autoWidth : true,
                autoScroll :true,  
                onRender: function() {
                        Ext.grid.GridPanel.prototype.onRender.apply(this, arguments);
                        this.addEvents("beforetooltipshow");
                        this.tooltip = new Ext.ToolTip({
                            renderTo: Ext.getBody(),
                            target: this.view.mainBody,
                            listeners: {
                                beforeshow: function(qt) {
                                    var v = this.getView();
                                    var row = v.findRowIndex(qt.baseTarget);
                                    var cell = v.findCellIndex(qt.baseTarget);
                                    this.fireEvent("beforetooltipshow", this, row, cell);
                                },
                                scope: this
                            }
                        });
                    },
                    listeners: {
                        render: function(g) {
                            g.on("beforetooltipshow", function(grid, row, col,r) {
                                grid.tooltip.body.update(myData[row][15]);
                            });
                        }
                    }
    }); 
    
    //--------------------------------------TimePickupGrid----------------------------//
    var myPickup = [
        ['จุดที่ 1 เข้าต้นทาง(InOrigin)','-'],
        ['<font color=blue>จุดที่ 2 อยู่ที่ต้นทาง(AtOrigin)</font>','-'],
        ['<font color=blue>จุดที่ 3 เริ่มขึ้นสินค้า(Loading)</font>','-'],
        ['<font color=blue>จุดที่ 4 เสร็จสิ้นการขึ้นสินค้า(On-Delivery)</font>','-'],
        ['จุดที่ 5 ออกจากต้นทาง(OutOrigin)','-']
    ];
    var storePickup = new Ext.data.SimpleStore({
        fields: [
           {name: 'statusPickup'},
           {name: 'timePickup'}
        ]
    });
    storePickup.loadData(myPickup);
    var timePickupGrid = new Ext.grid.GridPanel({
                store: storePickup,
                border : false,
                columns: [                
                    {id:'statusPickup',header: "<center><b>สถานะงาน</b></center>",css: ' text-color: blue; ',  width: 220, sortable: true, dataIndex:'statusPickup'},
                    {header: "<center><b>เวลา</b></center>",css: 'text-align: center;',  width: 200, sortable: true, dataIndex: 'timePickup'}
                ],
                stripeRows: true,
                autoHeight:true, 
                autoWidth : true
    });  
    //--------------------------------------TimeDeliveryrid----------------------------//         
    var myDelivery = [
        ['จุดที่ 6 เข้าปลายทาง(InDest)','-'],
        ['<font color=red>จุดที่ 7 อยู่ที่ปลายทาง(AtDest)</font>','-'],
        ['<font color=red>จุดที่ 8 เริ่มลงสินค้า(Off-loading)</font>','-'],
        ['<font color=red>จุดที่ 9 เสร็จสิ้นการลงสินค้า(Delivered)</font>','-'],
        ['จุดที่ 10 ออกจากปลายทาง(OutDest)','-']
    ];
    var storeDelivery = new Ext.data.SimpleStore({
            fields: [
               {name: 'statusDelivery'},
               {name: 'timeDelivery'}
            ]
        });
    storeDelivery.loadData(myDelivery);
    var timeDeliveryGrid = new Ext.grid.GridPanel({
                store: storeDelivery,
                border : false,
                columns: [                
                    {id:'statusDelivery',header: "<center><b>สถานะงาน</b></center>",css: 'text-color: blue; ',  width: 220, sortable: true, dataIndex:'statusDelivery'},
                    {header: "<center><b>เวลา</b></center>",css: 'text-align: center;',  width: 200, sortable: true, dataIndex: 'timeDelivery'}
                ],
                stripeRows: true,
                autoHeight:true, 
                autoWidth : true 
    });   
    //--------------------------------------BoxGrid----------------------------//   
    function BoxNum(val){
            if(val == 'undefined' || val == ''){val='-';} 
            return '<span style="color:#FFFFFF;"><b>' + val + '</b></span>';
    }
    function Battery(val){
            if(val == 'undefined' || val == ''){val='-';} 
            return '<span style="color:gray;"><b>' + val +'%</b></span>';
    }
    function JobActive(val){
            if(val == 'undefined' || val == ''){val='-';} 
            return '<span style="color:green;"><b>' + val + '</b></span>';
    }
    function Customer_JobID(val){
            if(val == 'undefined' || val == ''){val='-';}  
            return '<span style="color:green;"><b>' + val + '</b></span>';
    }
    function Status(val){
            if(val == 'undefined' || val == ''){val='-';} 
            return '<span style="color:blue;"><b>' + val + '</b></span>';
    }        
    function GPSTime(val){
            if(val == 'undefined' || val == ''){val='-';}
            else{ 
                ArrayTime = val.split(" ");
                TimeGPS = ArrayTime[1].substring(0,8);
                DateGPS = ArrayTime[0];
                val = DateGPS+" "+TimeGPS;
            }
            return '<span style="color:black;">' + val + '</span>';
    }
    var statusStore = new Ext.data.SimpleStore({
            fields: [
                {name: 'BoxNum'},
                {name: 'StatusBox'},
                {name: 'StatusGPS'},
                {name: 'Battery'},
                {name: 'FixLat'},
                {name: 'FixLon'},
                {name: 'GPSTime'},
                {name: 'GSMON'},
                {name: 'GPSON'},
                {name: 'JobActive'},
                {name: 'Status'},
                {name: 'Origin'},
                {name: 'Dest'},
                {name: 'Plate'},
                {name: 'NumAll'},
                {name: 'NumDeliverd'},
                {name: 'NumQueue'},
                {name: 'NumActive'},
                {name: 'GPSGSM'},
                {name: 'OriginDest'},
                {name : 'NumStatus'},
                {name : 'Customer_JobID'},
                {name : 'Direction'},
                {name : 'Speed'},
                {name : 'Altitude'},
                {name : 'Monitor'},
                {name : 'Acinput'},
                {name : 'StatusActive'}         
            ]                                                                     
    });    
    var boxListGrid = new Ext.grid.GridPanel({
                store: statusStore,                                          
                border : false,
                columns: [                
                    {id:'ID',header: "<center><b>กล่องที่</b></center>",css: 'text-align: center; background-color:#bd1010;', renderer: BoxNum , width: 45, sortable: true, dataIndex:'BoxNum'}, 
                    {header: "<center><b>GSM/GPS</b></center>",css: 'text-align: center;', width: 60, sortable: true, dataIndex: 'GPSGSM'},
                    {header: "<center><b>Battery</b></center>",css: 'text-align: center;',renderer: Battery ,width: 60, sortable: true,dataIndex: 'Battery'},
                    {header: "<center><b>ใบงาน</b></center>",css: 'text-align: center;',renderer: Customer_JobID ,width: 45, sortable: true,dataIndex: 'Customer_JobID'},   
                    {header: "<center><b>สถานะ</b></center>",css: 'text-align: center;',renderer: Status ,width: 70, sortable: true,dataIndex: 'Status'},
                    {header: "<center><b>ต้นทาง-ปลายทาง</b></center>",css: 'text-align: center;' ,width: 145, sortable: true,dataIndex: 'OriginDest'}   
                ],
                stripeRows: true,
                autoHeight:true, 
                autoWidth : true,
                onRender: function() {
                        Ext.grid.GridPanel.prototype.onRender.apply(this, arguments);
                        this.addEvents("beforetooltipshow");
                        this.tooltip = new Ext.ToolTip({
                            renderTo: Ext.getBody(),
                            target: this.view.mainBody,
                            listeners: {
                                beforeshow: function(qt) {
                                    var v = this.getView();
                                    var row = v.findRowIndex(qt.baseTarget);
                                    var cell = v.findCellIndex(qt.baseTarget);
                                    this.fireEvent("beforetooltipshow", this, row, cell);
                                },
                                scope: this
                            }
                        });
                    },
                    listeners: {
                        render: function(g) {
                            g.on("beforetooltipshow", function(grid, row, col,r) {
                                grid.tooltip.body.update(myDataStatus[row][28]);
                            });
                        }
                    }
                
    }); 
    function IconGrid(){
            return '<img src="http://dev2.dxplace.com/dx1/images/iconPlace.png" width="15" height="15">';
    }  
    function poiuserID(val){
            if(val == 'undefined' || val == ''){val='-';} 
            return '<a onclick="deletePlace('+val+')";><img src="http://maps.google.com/mapfiles/kml/pal5/icon7.png" width="15" height="15">';
    }  
    var pointStore = new Ext.data.SimpleStore({
            fields: [
                {name: 'poiuserID'},
                {name: 'poiuserAccount'},
                {name: 'poiuserPlace'},
                {name: 'poiuserLat'},
                {name: 'poiuserLon'},
                {name: 'poiuserTime'},
                {name: 'poiuserID'}
            ]
    });     
    var pointListGrid = new Ext.grid.GridPanel({
                store: pointStore,
                border : false,
                columns: [
                            {id:'ID',header: "<center><b>Icon</b></center>",css: 'text-align: center;', renderer : IconGrid  , width: 60, sortable: true, dataIndex:'Icon'},
                            {header: "<center><b>สถานที่</b></center>",css: 'text-align: center;', width: 150, sortable: true, dataIndex: 'poiuserPlace'},
                            {header: "<center><b>เวลาที่เพิ่ม</b></center>",css: 'text-align: center;' ,width: 120, sortable: true,dataIndex: 'poiuserTime'}
                ],
                stripeRows: true,
                autoHeight:true, 
                autoWidth : true, 
                onRender: function() {
                        Ext.grid.GridPanel.prototype.onRender.apply(this, arguments);
                        this.addEvents("beforetooltipshow");
                        this.tooltip = new Ext.ToolTip({
                            renderTo: Ext.getBody(),
                            target: this.view.mainBody,
                            listeners: {
                                beforeshow: function(qt) {
                                    var v = this.getView();
                                    var row = v.findRowIndex(qt.baseTarget);
                                    var cell = v.findCellIndex(qt.baseTarget);
                                    this.fireEvent("beforetooltipshow", this, row, cell);
                                },
                                scope: this
                            }
                        });
                    },
                    listeners: {
                        render: function(g) {
                            g.on("beforetooltipshow", function(grid, row, col,r) {
                                    grid.tooltip.body.update(myDataPoint[row][9]);
                            });
                        }
                    }
    });  
    //-------------------PlatelistAllGrid----------------------------//
    function NumStatus(val){
            var num_array = val.split("/");
            done = '<font color=green ><b>'+num_array[0]+'</b></font>';
            queue = '<font color=red ><b>'+num_array[1]+'</b></font>';  
            all = '<font color=blue ><b>'+num_array[2]+'</b></font>';  
            return done+"&nbsp;"+"|"+"&nbsp;"+queue+"&nbsp;"+"|"+"&nbsp;"+all;
    }    
    function PlatePlate(val){
            if(val == 'undefined' || val == ''){val='-';} 
            return '<span style="color:#bd1010;"><b>' + val + '</b></span>';
    }
    function BoxNumPlate(val){
            if(val == 'undefined' || val == ''){val='-';} 
            return '<span style="color:#FFFFFF;"><b>' + val + '</b></span>';
    }   
    
    Ext.ToolTip.prototype.onTargetOver = Ext.ToolTip.prototype.onTargetOver.createInterceptor(function(e) {
            this.baseTarget = e.getTarget();
    });
    Ext.ToolTip.prototype.onMouseMove = Ext.ToolTip.prototype.onMouseMove.createInterceptor(function(e) {             
            if (this.baseTarget != null){         
                if (!e.within(this.baseTarget)) {
                    this.onTargetOver(e);
                    return false;
                }                                                             
            }else {
                return false;  
            }
    });
    var cmPlateList = new Ext.grid.ColumnModel([   
                    {id:'ID',header: "<center><b>หมายเลขทะเบียน</b></center>",css: 'text-align: center; background-color:#f1a7a7;', renderer: PlatePlate , width: 100, sortable: true, dataIndex:'Plate'},
                    {header: "<center><b>หมายเลขกล่อง</b></center>",css: 'text-align: center; background-color:#bd1010;',renderer: BoxNumPlate, width:100, sortable: true, dataIndex: 'BoxNum'},             
                    {header: "<center><b>Active (JobID/Status/NumJob)</b></center>",css: 'text-align: center;' ,width: 200, sortable: true,dataIndex: 'StatusActive'},
                    {header: "<center><b>JobInBox (Done/Queue/All)</b></center>",css: 'text-align: center;' ,renderer: NumStatus,width: 200, sortable: true,dataIndex: 'NumStatus'},
                    {header: "<center><b>ต้นทาง-ปลายทาง</b></center>",css: 'text-align: center;' ,width: 200, sortable: true,dataIndex: 'OriginDest'},
                    {header: "<center><b>GSM/GPS</b></center>",css: 'text-align: center;', width: 60, sortable: true, dataIndex: 'GPSGSM'},
                    {header: "<center><b>Battery</b></center>",css: 'text-align: center;',renderer: Battery ,width: 80, sortable: true,dataIndex: 'Battery'}    
    ]);                                 
    var plateListAllGrid =  new Ext.grid.GridPanel({
                store: statusStore,
                border : false,
                cm: cmPlateList ,
                trackMouseOver:true,
                stripeRows: true,
                autoHeight:true, 
                loadMask: true,
           
                onRender: function() {
                        Ext.grid.GridPanel.prototype.onRender.apply(this, arguments);
                        this.addEvents("beforetooltipshow");
                        this.tooltip = new Ext.ToolTip({
                            renderTo: Ext.getBody(),
                            target: this.view.mainBody,
                            listeners: {
                                beforeshow: function(qt) {
                                    var v = this.getView();
                                    var row = v.findRowIndex(qt.baseTarget);
                                    var cell = v.findCellIndex(qt.baseTarget);
                                    this.fireEvent("beforetooltipshow", this, row, cell);
                                },
                                scope: this
                            }
                        });
                    },
                    listeners: {
                        render: function(g) {
                            g.on("beforetooltipshow", function(grid, row, col,r) {
                                    grid.tooltip.body.update(myDataStatus[row][28]);
                            });
                        }
                    }
    }); 
    function showQueueJob(){
        txtQuque = new Ext.ToolTip({
            text: 'จำนวนคิวในกล่อง '
        });
        txtQuque.show();
    }  
    
    //---------------------SearchForm-------------------------//
    var searchForm = new Ext.FormPanel({
        labelWidth: 70, // label settings here cascade unless overridden
        frame:true,
        border : false,
        items: [{
                xtype:'fieldset',
                title: 'ค้นหาสถานที่ด้วย ละติจูด,ลองติจูด',
                autoHeight:true,
                autoWidth : true,
                defaultType: 'textfield',
                items :[{
                    xtype : 'textfield',
                    fieldLabel : 'ค้นหาสถานที่',
                    id : 'idPlacePoint' 
                }],
                buttons: [{
                    text: 'ค้นหา',
                         handler:function() { 
                            placePoint = Ext.getCmp('idPlacePoint').getValue();
                            placePoint_array = placePoint.split(",");
                            getPoint(placePoint_array[0],placePoint_array[1]);
                         }
                }]
        },{
                xtype:'fieldset',
                title: 'ค้นหาเส้นทางและระยะทาง',
                autoHeight:true,
                autoWidth:true,
                defaultType: 'textfield',
                items :[{
                    xtype : 'textfield',
                    fieldLabel : 'ต้นทาง',
                    id : 'idStartPoint'
                },{
                    xtype : 'textfield',
                    fieldLabel : 'ปลายทาง',
                    id : 'idEndPoint'
                }],
                html : '<div id="getDistance"></div><div id="getDuration"></div>',
                buttons: [{
                    text: 'ค้นหา',
                    handler:function() { 
                        startPoint = Ext.getCmp('idStartPoint').getValue();  
                        endPoint = Ext.getCmp('idEndPoint').getValue();      
                        setDirections(startPoint,endPoint);    
                        Ext.getCmp('content-panel').layout.setActiveItem('map-panel');    
                    } 
                },{
                    text: 'เคลียร์',
                    handler:function() { 
                        Ext.getCmp('idStartPoint').reset();
                        Ext.getCmp('idEndPoint').reset();
                    } 
                }]
        }]
    });   
    function addOrigin(){
        tabs.add({
            title: 'New Tab ' + (++index),
            iconCls: 'tabs',
            html: 'Tab Body ' + (index) + '<br/><br/>'+ Ext.example.bogusMarkup,
            closable:true
        }).show();
    }
    //----------------------------------Manage Shipment Panel--------------------------------//
    manageShipmentPanel = new Ext.FormPanel({
            id : 'manageshipment-panel', 
            xtype : 'form',
            labelWidth: 150, 
            frame:true,
            title: '<div align=center>ใบงานหมายเลข&nbsp;&nbsp;<font color=red><span id=shipmentnum></span></font></div>',
            bodyStyle:'padding:5px 5px 0',
            items: [{
                xtype:'fieldset',
                title: 'ข้อมูลใบงาน',
                autoHeight:true,
                defaults: {width: 210},
                defaultType: 'textfield',
                html : '<div id=shipmentdataid></div>'
            }],
            buttonAlign:'right',    
                buttons: [{
                text: 'ปิด',
                handler:function() { 
                        Ext.getCmp('content-panel').layout.setActiveItem('job-panel'); 
                        Ext.getCmp('dataPortid').collapse(true);
                } 
            }]
    });  
    
    //----------------------------------Add Shipment Panel--------------------------------// 
    
    
    // tab generation code
    var index1 = 0;
    var index2 = 0;
    function CreateComboBoxOrigin() { 
        if(index1<16){   
            var comboOrigin = new Ext.form.ComboBox({        
                    store: provinceStore,
                    id : 'idAddOriginShipment'+ (++index1),        
                    displayField: 'Province',
                    valueField : 'ProvinceAll',        
                    typeAhead: true,        
                    mode: 'local',        
                    forceSelection: true,        
                    triggerAction: 'all',        
                    emptyText: 'ต้นทาง...',        
                    selectOnFocus: true,        
                    fieldLabel: 'ต้นทาง'+ (index1)    
            });    
            return comboOrigin;
        }else{
            return '';
        }
    }
    function CreateComboBoxDest() {   
         if(index2<16){  
            var comboDest = new Ext.form.ComboBox({        
                    store: provinceStore,
                    id : 'idAddDestShipment'+ (++index2),        
                    displayField: 'Province',
                    valueField : 'ProvinceAll',        
                    typeAhead: true,        
                    mode: 'local',        
                    forceSelection: true,        
                    triggerAction: 'all',        
                    emptyText: 'ปลายทาง...',        
                    selectOnFocus: true,        
                    fieldLabel: 'ปลายทาง'+ (index2)    
            });    
            return comboDest;
         }else{
             return '';
         }
    }
    addShipmentPanel = {
            id : 'addshipment-panel',
            xtype : 'form',
            labelWidth: 300, 
            frame:true,
            autoScroll : true,
            title: '<div align=center>เพิ่มข้อมูล</div>',
            bodyStyle:'padding:5px 5px 0',
            autoWidth : true,
            height : 400,
            items: [{
                xtype:'fieldset', 
                title: 'เพิ่มใบงาน',
                autoHeight:true,
                items :[{  
                        xtype: 'textfield',
                        fieldLabel : 'ใบงานหมายเลข',
                        id : 'idAddJobShipment',
                        emptyText : 'ใบงานหมายเลข.....'
                },{ 
                        layout:'column', 
                        labelWidth:200, 
                        defaults:{ 
                            columnWidth:0.5, 
                            border:true ,
                            bodyStyle:'padding:4px' 
                        }, 
                        items:[{ 
                            id : 'OriginFieldset',
                            xtype:'fieldset', 
                            autoHeight:true, 
                            width : 400,
                                title:'ต้นทาง' ,
                                buttons: [{
                                    text: 'เพิ่มต้นทาง',
                                         handler:function() { 
                                            if(index1<1){
                                                Ext.getCmp('OriginFieldset').add(CreateComboBoxOrigin());           
                                                Ext.getCmp('OriginFieldset').doLayout();
                                            }else{ 
                                                Ext.MessageBox.alert('Alert','ยังไม่สามารถเพิ่งต้นทางหลายที่ได้');      
                                            }
                                         }
                                }]
                        },{ 
                            id : 'DestFieldset',
                            xtype:'fieldset', 
                            width : 400,
                            autoHeight:true, 
                                title:'ปลายทาง' ,
                                buttons: [{
                                    text: 'เพิ่มปลายทาง',
                                         handler:function() { 
                                            if(index2<1){ 
                                                Ext.getCmp('DestFieldset').add(CreateComboBoxDest());           
                                                Ext.getCmp('DestFieldset').doLayout();
                                            }else{
                                                Ext.MessageBox.alert('Alert','ยังไม่สามารถเพิ่งปลายทางหลายที่ได้');     
                                            }
                                         }
                                }]
                        }] 
                } ],   
                html : '<br><div align="center" id=distanceShipmentid></div><br><div align="center" id=durationShipmentid></div>',
                buttonAlign:'right', 
                buttons:[{
                    scope:this ,
                    disabled : true,
                    text:'ดูแผนที่ต้นทาง -ปลายทางที่เลือก',
                    handler:function() { 
                        if(isOrigin==true && isDest==true){
                            //mapForm.show();    
                        }else{
                            Ext.MessageBox.alert('คุณยังเลือกต้นทาง-ปลายทางไม่ครบ');
                        }
                    }
                },{ 
                    scope:this,
                    text:'เพิ่มใบงาน', 
                    handler:function() {
                         var datajobShipment = Ext.getCmp('idAddJobShipment').getValue();
                         var dataAddOrigin1 = Ext.getCmp('idAddOriginShipment1').getValue();
                         //var dataAddOrigin2 = Ext.getCmp('idAddOriginShipment2').getValue();  
                         // dataAddOrigin3 = Ext.getCmp('idAddOriginShipment3').getValue();  
                         var dataAddDest1 =  Ext.getCmp('idAddDestShipment1').getValue();
                         //var dataAddDest2 =  Ext.getCmp('idAddDestShipment2').getValue();
                         //var dataAddDest3 =  Ext.getCmp('idAddDestShipment3').getValue(); */
                       if(dataAddOrigin1=='ต้นทาง...' || dataAddDest1=='ปลายทาง...' || dataAddOrigin1=='' || dataAddDest1==''){
                            Ext.MessageBox.alert('แจ้งเตือน','กรุณาเลือกต้นทาง-ปลายทาง');
                       }else{ 
                            var dataAddJob =  datajobShipment +","+ dataAddOrigin1+","+ dataAddDest1;
                            setJobDataInput(dataAddJob); 
                       }   
                       /*if(index1>1 && index2>1){
                            Ext.MessageBox.alert('Alert','ส่วนนี้ยังใช้งานได้แบบหนึ่งต้นทาง-หลายปลายทาง หรือ หลายปลายทาง-หนึ่งต้นทาง');     
                       } */                       
                    }
                }]
            }],
            buttonAlign:'right', 
                buttons:[{ 
                    scope:this ,
                    text:'ปิด', 
                    handler:function() { 
                        if(closeManagePanel == 1){
                            Ext.getCmp('content-panel').layout.setActiveItem('job-panel'); 
                        }else if(closeManagePanel == 2){
                            Ext.getCmp('content-panel').layout.setActiveItem('jobbox-panel'); 
                        }else if(closeManagePanel == 3){
                            Ext.getCmp('content-panel').layout.setActiveItem('plate-panel'); 
                        }
                    } 
            }]
    }; 
    //------------------Add PlatePanel-----------------//    
    addPlatePanel = {
            id : 'addplate-panel',
            xtype : 'form',
            labelWidth: 300, 
            frame:true,
            autoScroll : true,
            title: '<div align=center>เพิ่มข้อมูล</div>',
            bodyStyle:'padding:5px 5px 0',
            autoWidth : true,
            height : 400,
            items: [{
                xtype:'fieldset', 
                title: 'เซตหมายเลขทะเบียนรถ',
                autoHeight:true,
                items :[{
                    xtype : 'textfield', 
                    fieldLabel : 'รถหมายเลขทะเบียน',
                    id : 'idAddPlateShipment'
                },{         
                    xtype : 'textfield',
                    fieldLabel : 'แจ้งเตือนเมื่อความเร็วเกิน (km/h) ',
                    id : 'idOverSpeed',
                    value : 0
                },{   
                    xtype : 'textfield',
                    fieldLabel : 'ยกเลิกการเตือนเมื่อความเร็ว (km/h)',
                    id : 'idLowSpeed',
                    value : 0
                }],
                buttonAlign:'right', 
                buttons:[{ 
                    scope:this,
                    text:'เซตทะเบียนรถ', 
                    handler:function() {
                            var dataAddConfig =  Ext.getCmp('idAddPlateShipment').getValue()+","+Ext.getCmp('idOverSpeed').getValue()+","+Ext.getCmp('idLowSpeed').getValue(); 
                            if(dataAddConfig!=""){
                                setConfigDataInput(dataAddConfig);
                            } 
                    }
                }]
            }],
            buttonAlign:'right', 
                buttons:[{ 
                    scope:this ,
                    text:'ปิด', 
                    handler:function() { 
                        if(closeManagePanel == 1){
                            Ext.getCmp('content-panel').layout.setActiveItem('job-panel'); 
                        }else if(closeManagePanel == 2){
                            Ext.getCmp('content-panel').layout.setActiveItem('jobbox-panel'); 
                        }else if(closeManagePanel == 3){
                            Ext.getCmp('content-panel').layout.setActiveItem('plate-panel'); 
                        }
                    } 
            }]
    };     
    //------------------------MapPanel---------------------//
    var mapPanel = { 
            id : 'map-panel', 
            title : 'แผนที่และตำแหน่งรถ',    
            xtype : 'panel',
            bodyStyle : 'padding:0px',
            html : '<div id="map_canvas" border="1" style="width: 100%; height: 100% " valign="top"></div>'
                +'<div id="statusBoxid" title="แบบจำลองกล่อง Dx1" style="position:absolute; left:90; top:48px; z-index:5 "></div>'
                +'<div id="pbarBatteryid" title="ปริมาณแบตเตอรี่ในตัวกล่อง Dx1" style="position:absolute; left:90; top:130; z-index:5 "></div>'
                +'<div id="hand_b" title="เลื่อนแผนที่" onclick="stopEditing()" style="position:absolute; left:90; top:10px; z-index:5 "></div>'
                +'<div id="placemark_b" title="เพิ่มตำแหน่งสถานที่ลงบนแผนที่" onclick="placeMarker()" style="position:absolute; left:120; top:10px; z-index:5 "></div>'
                +'<div id="line_b" title="กำหนดพื้นที่" onclick="startLine()" style="position:absolute; left:150; top:10px; z-index:5 "></div>'
                +'<div id="shape_b" title="กำหนดพื้นที่สำหรับแจ้งเตือน" onclick="startShape()" style="position:absolute; left:180; top:10px; z-index:5 "></div>',
            bbar: [{
                text : '<img src=http://maps.google.com/mapfiles/kml/pal4/icon62.png width="18" height="18">สถานะกล่องออนไลด์',
                tooltip: {
                    text: 'กล่องออนไลด์ทั้งหมด :'+'<span id=countCarOnid></span>', 
                    title:'สถานะกล่องออนไลด์'
                } 
            },'-',{
                text : '<img src=http://maps.google.com/mapfiles/kml/pal4/icon15.png width="18" height="18">สถานะกล่องออฟไลด์',
                tooltip: {
                    text: 'กล่องออฟไลด์ทั้งหมด :'+'<span id=countCarOffid></span>', 
                    title:'สถานะกล่องออฟไลด์'
                } 
            }/*,'-',{
                text : '<img src=http://maps.google.com/mapfiles/kml/pal4/icon31.png width="18" height="18">สถานะกล่องปัจจุบันที่เลือกอยู่',
                tooltip: {
                    text: 'กล่องปัจจุบันที่เลือกอยู่ที่ตำแหน่ง :', 
                    title:'สถานะกล่องปัจจุบันที่เลือก'
                } 
            }*/,'-',{
                text : 'พื้นที่สำหรับดู  Street View',
                tooltip: {
                    text: 'พื้นที่ ที่สามารถดูเส้นทางบนท้องถนนแบบพาโนรามาได้ :', 
                    title:'Street View Area',
                    handler:function() { 
                        toggleOverlay();
                    }
                } 
            }]
    };
    //------------------------QueuePanel---------------------//
    var queuePanel = { 
            id : 'queue-panel', 
            title : '<div align="center">คิวงานในกล่อง<span id=queueBoxid></span></div>',
            xtype : 'form',
            frame:true,
            bodyStyle:'padding:5px 5px 0',
            items : [{    
                xtype : 'panel', 
                autoScroll : true,
                bodyStyle : 'padding:0px',
                html : '<div id=queuePanelid></div>'
            }], 
            buttons:[{ 
                    scope:this,
                    text:'ปิด', 
                    handler:function() {
                        Ext.getCmp('content-panel').layout.setActiveItem('job-panel');
                    }
            }]    
    };
    //-----------------------jobPanel---------------------//
    var jobPanel = {
        id: 'job-panel',
        title: 'Shipment',
        layout: 'absolute',
        autoScroll :true, 
        defaults: {
            bodyStyle: 'padding:0px;'
        },
        items:[jobListAllGrid],
        bbar: new Ext.PagingToolbar({
            pageSize: 25,
            store: jobListStore,
            displayInfo: true
        }),
        tbar: [{
                text : 'ใบงานที่ : ',
                tooltip: {
                    text: 'ค้นหาใบงานจากใบงานทั้งหมด', 
                    title:'Search Shipment'
                }
        },{
            xtype: 'textfield',
            id: 'filterJobid',
            selectOnFocus: true,
            width: 40,
            listeners: {
                'render': {fn:function(){
                    Ext.getCmp('filterJobid').getEl().on('keyup', function(){
                        filterJob();
                    }, 
                    this, {buffer:300});
                }, 
                scope:this}
            }
        },'-',{
                text : 'ต้นทาง : ',
                tooltip: {
                    text: 'ค้นหาต้นทางจากใบงานทั้งหมด', 
                    title:'Search Origin'
                }
        },{
            xtype: 'textfield',
            id: 'filterOriginid',
            selectOnFocus: true,
            width: 60,
            listeners: {
                'render': {fn:function(){
                    Ext.getCmp('filterOriginid').getEl().on('keyup', function(){
                        filterOrigin();
                    }, 
                    this, {buffer:300});
                }, 
                scope:this}
            }
        },'-',{
                text : 'ปลายทาง: ',
                tooltip: {
                    text: 'ค้นหาปลายทางจากใบงานทั้งหมด', 
                    title:'Search Dest'
                }
        },{
            xtype: 'textfield',
            id: 'filterDestid',
            selectOnFocus: true,
            width: 60,
            listeners: {
                'render': {fn:function(){
                    Ext.getCmp('filterDestid').getEl().on('keyup', function(){
                        filterDest();
                    }, 
                    this, {buffer:300});
                }, 
                scope:this}
            }
        },'-',addjobMenu,'-',addplateMenu,'-',clearalljobMenu
        ] 
    };   
    //-----------------------plateShipmentPanel---------------------//
    var platePanel = {
        id: 'plate-panel',
        title: 'รายการงานในกล่องทั้งหมด',
        layout: 'absolute', 
        defaults: {
            bodyStyle: 'padding:0px;'
        },
        items:[plateListAllGrid],
        bbar: new Ext.PagingToolbar({
            pageSize: 25,
            store: jobListStore,
            displayInfo: true
        }),
        tbar: [{
                text : 'ค้นหากล่องที่ : ',
                tooltip: {
                    text: 'ค้นหากล่องจากกล่องทั้งหมด', 
                    title:'Search BoxID'
                }
        },{
            xtype: 'textfield',
            id: 'filterBoxid',
            selectOnFocus: true,
            width: 80,
            listeners: {
                'render': {
                    fn:function(){
                        Ext.getCmp('filterBoxid').getEl().on('keyup', function(){
                            filterBox();
                        }, 
                        this, {buffer:300});
                    }, 
                    scope:this
                }
            }
        },'-',{
                text : 'ค้นหาทะเบียนที่: ',
                tooltip: {
                    text: 'ค้นหากล่องจากกล่องทั้งหมด', 
                    title:'Search Plate'
                }
        },{
            xtype: 'textfield',
            id: 'filterPlateid',
            selectOnFocus: true,
            width: 80,
            listeners: {
                'render': {
                    fn:function(){
                        Ext.getCmp('filterPlateid').getEl().on('keyup', function(){
                            filterPlate();
                        }, 
                        this, {buffer:300});
                    }, 
                    scope:this
                }
            }
        }]    
    };    
    function filterBox(){
        var filterBox = Ext.getCmp('filterBoxid');
        statusStore.filter('BoxNum', filterBox.getValue());
    } 
    function filterPlate(){
        var filterPlate = Ext.getCmp('filterPlateid');
        statusStore.filter('Plate', filterPlate.getValue());
    } 
    function filterJob(){
        var filterJob = Ext.getCmp('filterJobid');
        jobListStore.filter('JobID', filterJob.getValue());
    } 
    function filterOrigin(){
        var filterOrigin = Ext.getCmp('filterOriginid');
        jobListStore.filter('Origin', filterOrigin.getValue());
    }
    function filterDest(){
        var filterDest = Ext.getCmp('filterDestid');
        jobListStore.filter('Dest', filterDest.getValue());
    }
    function filterState(){
        var filterState = Ext.getCmp('filterStateid');
        jobListStore.filter('JobID', filterState.getValue());
    }   
    function filterPoi(){
        var filterPoi = Ext.getCmp('filterPoiId');
        pointStore.filter('poiuserPlace', filterPoi.getValue());
    }   
    //---------------------------------------------JobWin--------------------------------//
    StatusForm = new Ext.Window({                
                id          : 'statusformid',
                title       : '<img src="http://dev2.dxplace.com/images/folder_wrench.png\" >จัดการสถานะงาน',
                layout      : 'fit',
                width       : 500,
                height      : 350,
                closeAction :'hide', 
                plain       : true,        
                border:true ,
                deferredRender:true,
                defaults:{ 
                        layout:'form' ,labelWidth:200 ,defaultType:'textfield' ,bodyStyle:'padding:0px' ,hideMode:'offsets' 
                } ,
                items:[{
                        xtype : 'form',
                        frame : true,
                        id : 'manageJob',
                        labelWidth :200, 
                        bodyStyle : Ext.isIE ? 'padding:15px 15px 15px 15px;' : 'padding:15px 15px;',
                        defaults: {
                            anchor: '90%',
                            msgTarget: 'side'
                        },
                        items :[{
                            xtype:'fieldset', 
                            title: 'เปลี่ยนสถานะใบงาน',
                            autoHeight:true,
                            defaults: {width: 150},
                            defaultType: 'textfield',
                            items :[
                                new Ext.form.ComboBox({
                                    fieldLabel: 'เปลี่ยนสถานะใบงาน',
                                    id:'idChangeStateInBox', 
                                    hiddenName:'ChangeStatus',
                                    store:ChangeStatus,
                                    displayField:'ChangeStatus',
                                    typeAhead: true,
                                    mode: 'local',
                                    triggerAction: 'all',
                                    emptyText:'สถานะ...',
                                    selectOnFocus:true,
                                    width:100  
                            })],
                            buttonAlign:'right', 
                            buttons:[{ 
                                scope:this,
                                text:'เปลี่ยนสถานะ', 
                                handler:function() {
                                   //progressChangeStateWin.show();
                                   dataChangeState = Ext.getCmp('idChangeStateInBox').getValue();
                                   setChangeState(dataChangeState); 
                                }
                            }]
                        },{
                            xtype:'fieldset', 
                            title: 'ย้ายใบงานโดยหมายเลขกล่อง',
                            autoHeight:true,
                            defaults: {width: 150},
                            defaultType: 'textfield',
                            items :[
                                new Ext.form.ComboBox({
                                        fieldLabel: 'เปลี่ยนกล่อง(By BoxID)',
                                        id:'idBoxMoveInBox', 
                                        //valueField : 'BoxNum',
                                        hiddenName:'datanumStore',
                                        store:datanumStore,
                                        displayField:'BoxNum',
                                        typeAhead: false,
                                        mode: 'local',
                                        triggerAction: 'all',
                                        emptyText:'หมายเลข...', 
                                        forceSelection: true,
                                        selectOnFocus:true,
                                        width:100
                                })]  ,
                            buttonAlign:'right', 
                            buttons:[{ 
                                scope:this,
                                text:'ย้ายข้อมูล', 
                                handler:function() {
                                    if(statusShipment=='Queue'){
                                       //progressChangeStateWin.show();
                                       numBoxMoveTo = Ext.getCmp('idBoxMoveInBox').getValue();
                                       setMoveShipmentBox();
                                    }else{
                                        Ext.MessageBox.alert('Move Shipment',"คุณไม่สามารถย้ายงานนี้ได้ เพราะกำลังดำเนินการอยู่");   
                                    }
                                }
                            }]
                        }],
                        buttonAlign:'right', 
                        buttons:[{ 
                            scope:this ,
                            text:'ปิด', 
                            handler:function() { 
                                StatusForm.hide();
                            } 
                        }]        
                }]            
    });
    //---------------------------------------------QueueWin--------------------------------//
    queueForm = new Ext.Window({                
                id          : 'queueformid',
                title       : '<img src="/images/book.png" >ดูคิวงานในกล่องหมายเลข : <span id=boxQueueid></span>',
                layout      : 'fit',
                width       : 1000,
                height      : 300,
                closeAction :'hide',
                plain       : true,
                border:true ,
                deferredRender:true,
                defaults:{ 
                        layout:'form' ,labelWidth:120 ,defaultType:'textfield' ,bodyStyle:'padding:0px' ,hideMode:'offsets' 
                } ,
                autoScroll: true,
                html : '<div id=queueFormid></div>',
                buttons:[{ 
                    scope:this ,
                    text:'ปิดหน้าต่าง', 
                    handler:function() { 
                        queueForm.hide();
                    } 
                }]  
    });                    
    //---------------------------------------------QueueWin--------------------------------//
    directionForm = new Ext.Window({                
                id          : 'directionformid',
                title       : '<img src="/images/book.png" >ข้อมูลเส้นทาง : <span id=boxQueueid></span>',
                layout      : 'fit',
                width       : 400,
                height      : 500,
                closeAction :'hide',
                plain       : true,
                border:true ,
                deferredRender:true,
                defaults:{ 
                        layout:'form' ,labelWidth:120 ,defaultType:'textfield' ,bodyStyle:'padding:0px' ,hideMode:'offsets' 
                },
                items : [{
                    xtype : 'panel',
                    autoScroll: true,
                    html : '<div id="getGdir"></div> ' 
                }],
                buttonAlign:'right', 
                buttons:[{ 
                    scope:this,
                    text:'บันทึกเส้นทาง', 
                    handler:function() {
                    }
                },{ 
                    scope:this ,
                    text:'ยกเลิก', 
                    handler:function() { 
                        directionForm.hide();
                    } 
                }]           
    });    
    //----------------------------------MapForm--------------------------------//
    /*mapForm = new Ext.Window({                
                id          : 'mapformid',
                layout      : 'fit',
                width       : 400,
                height      : 500,
                closeAction :'hide',
                plain       : true,
                defaults:{layout:'fit'} , 
                border:true ,
                deferredRender:true,
                defaults:{ 
                        layout:'form' ,labelWidth:120 ,defaultType:'textfield' ,bodyStyle:'padding:0px' ,hideMode:'offsets' 
                } ,
                items : [mapPanel],
                buttonAlign:'right', 
                buttons:[{ 
                    scope:this ,
                    text:'ยกเลิก', 
                    handler:function() { 
                        mapForm.hide();
                    } 
                }]
    });       */
    //-------------------Progress-----------------------------// 
    progressJobWin = new Ext.Window({
                        title : 'กำลังโหลดข้อมูลใบงาน ',
                        layout      : 'fit',
                        width       : 300,
                        height      : 80,
                        closeAction :'hide',
                        plain       : true,
                        border:true ,
                        deferredRender:true,
                        defaults:{ 
                                layout:'form' ,labelWidth:100 ,defaultType:'textfield' ,bodyStyle:'padding:0px' ,hideMode:'offsets' 
                        } ,
                        items:[{      
                            xtype : 'panel',
                            width: 300,
                            height : 80,
                            bodyStyle : 'padding:10px',
                            html : '<center><img src="http://dev2.dxplace.com/dx1/images/blue-loading.gif" width="20" height="20" style="margin-right:5px;float:center;vertical-align:top;"><b>Loading...</b></center>' 
                        }]
    });   
    progressBoxWin = new Ext.Window({                    
                        title : 'กำลังโหลดข้อมูลกล่อง ',
                        layout      : 'fit',
                        width       : 300,
                        height      : 80,
                        closeAction :'hide',
                        plain       : true,
                        border:true ,
                        deferredRender:true,
                        defaults:{ 
                                layout:'form' ,labelWidth:100 ,defaultType:'textfield' ,bodyStyle:'padding:0px' ,hideMode:'offsets' 
                        } ,
                        items:[{      
                            xtype : 'panel',
                            width: 300,
                            height : 80,
                            bodyStyle : 'padding:10px',
                            html : '<center><img src="http://dev2.dxplace.com/dx1/images/blue-loading.gif" width="20" height="20" style="margin-right:5px;float:center;vertical-align:top;"><b>Loading...</b></center>' 
                        }]
    });   
    progressAddJobWin = new Ext.Window({                   
                        title : 'กำลังเพิ่มข้อมูลใบงาน ',
                        layout      : 'fit',
                        width       : 300,
                        height      : 80,
                        closeAction :'hide',
                        plain       : true,
                        border:true ,
                        deferredRender:true,
                        defaults:{ 
                                layout:'form' ,labelWidth:100 ,defaultType:'textfield' ,bodyStyle:'padding:0px' ,hideMode:'offsets' 
                        } ,
                        items:[{      
                            xtype : 'panel',
                            width: 300,
                            height : 80,
                            bodyStyle : 'padding:10px',
                            html : '<center><img src="http://dev2.dxplace.com/dx1/images/blue-loading.gif" width="20" height="20" style="margin-right:5px;float:center;vertical-align:top;"><b>Loading...</b></center>' 
                        }]
    });   
    progressAddConfigWin = new Ext.Window({               
                        title : 'กำลังเพิ่มข้อมูลทะเบียนรถ ',
                        layout      : 'fit',
                        width       : 300,
                        height      : 80,
                        closeAction :'hide',
                        plain       : true,
                        border:true ,
                        deferredRender:true,
                        defaults:{ 
                                layout:'form' ,labelWidth:100 ,defaultType:'textfield' ,bodyStyle:'padding:0px' ,hideMode:'offsets' 
                        } ,
                        items:[{      
                            xtype : 'panel',
                            width: 300,
                            height : 80,
                            bodyStyle : 'padding:10px',
                            html : '<center><img src="http://dev2.dxplace.com/dx1/images/blue-loading.gif" width="20" height="20" style="margin-right:5px;float:center;vertical-align:top;"><b>Loading...</b></center>' 
                        }]
    });     
    progressChangeStateWin = new Ext.Window({         
                        title : 'กำลังเปลี่ยนสถานะใบงาน ',
                        layout      : 'fit',
                        width       : 300,
                        height      : 80,
                        closeAction :'hide',
                        plain       : true,
                        border:true ,
                        deferredRender:true,
                        defaults:{ 
                                layout:'form' ,labelWidth:100 ,defaultType:'textfield' ,bodyStyle:'padding:0px' ,hideMode:'offsets' 
                        } ,
                        items:[{      
                            xtype : 'panel',
                            width: 300,
                            height : 80,
                            bodyStyle : 'padding:10px',
                            html : '<center><img src="http://dev2.dxplace.com/dx1/images/blue-loading.gif" width="20" height="20" style="margin-right:5px;float:center;vertical-align:top;"><b>Loading...</b></center>' 
                        }]
    }); 
    progressPlace = new Ext.Window({                   
                        title : 'กำลังโหลดข้อมูลใบงาน ',
                        layout      : 'fit',
                        width       : 300,
                        height      : 80,
                        closeAction :'hide',
                        plain       : true,
                        border:true ,
                        deferredRender:true,
                        defaults:{ 
                                layout:'form' ,labelWidth:100 ,defaultType:'textfield' ,bodyStyle:'padding:0px' ,hideMode:'offsets' 
                        } ,
                        items:[{      
                            xtype : 'panel',
                            width: 300,
                            height : 80,
                            bodyStyle : 'padding:10px',
                            html : '<center><img src="http://dev2.dxplace.com/dx1/images/blue-loading.gif" width="20" height="20" style="margin-right:5px;float:center;vertical-align:top;"><b>Loading...</b></center>' 
                        }]
    });
    progressLoad = new Ext.Window({   
                        title : 'กำลังโหลดข้อมูล ',
                        layout      : 'fit',
                        width       : 300,
                        height      : 80,
                        closeAction :'hide',
                        plain       : true,
                        border:true ,
                        deferredRender:true,
                        defaults:{ 
                                layout:'form' ,labelWidth:100 ,defaultType:'textfield' ,bodyStyle:'padding:0px' ,hideMode:'offsets' 
                        } ,
                        items:[{      
                            xtype : 'panel',
                            width: 300,
                            height : 80,
                            bodyStyle : 'padding:10px',
                            html : '<center><img src="http://dev2.dxplace.com/dx1/images/blue-loading.gif" width="20" height="20" style="margin-right:5px;float:center;vertical-align:top;"><b>Loading...</b></center>' 
                        }]
    });        
//---------------------------------------onReadyfunction-----------------------------------//      
Ext.onReady(function(){ 
    Ext.QuickTips.init();   
    deviceID = '1116'; 
    boxNo = '1116';
    jobNumber = 0;  
     var formViewport = new Ext.FormPanel({
            frame: true,
            title: 'Contact Details',
            renderTo:'main',
            items: [ 
                new Ext.Viewport({
                        id:'viewportTruck',
                        title: 'Border Layout',
                        layout:'border',
                        bodyBorder: false,
                        bodyStyle: 'padding:-5px',   
                        defaults: {
                            collapsible: false,
                            split: false,
                            animFloat: false,
                            autoHide: false,
                            useSplitTips: false,
                            bodyStyle: 'padding:-5px' 
                        },
                        items: [{
                            id : 'dataPointid',
                            title:'จัดการข้อมูลพิกัด',       
                            region:'west', 
                            collapsible:true, 
                            collapsed:true, 
                            split:true ,
                            border : true,
                            floatable: false,
                            margins: '0 0 0 0', 
                            cmargins: '0 0 0 0',
                            width: 350,
                            items :[{
                                xtype : 'panel',
                                layout:'accordion', 
                                layoutConfig:{animate:true}, 
                                border:false,
                                autoWidth : true,
                                autoHeight : true,     
                                items:[{      
                                    xtype : 'panel',
                                    id : 'pointListPanel',
                                    collapsed:false,
                                    title : '<div align="center"><b>ข้อมูลสถานที่</b></div>',
                                    autoWidth : true,
                                    autoHeight : true, 
                                    tooltip: {
                                        text: 'ข้อมูลสถานที่บน MAP', 
                                        title:'POI'
                                    },
                                    //bbar: pagingBarPlace,
                                    items : [pointListGrid],
                                    tbar: [{
                                            text : 'ค้นหาสถานที่สำคัญ: ',
                                            tooltip: {
                                                text: 'ค้นหาสถานที่สำคัญของเราที่ได้หมุดไว้', 
                                                title:'Search Poi'
                                            }
                                    },{
                                                xtype: 'textfield',
                                                id: 'filterPoiId',
                                                selectOnFocus: true,
                                                width: 150,
                                                listeners: {
                                                    'render': {fn:function(){
                                                        Ext.getCmp('filterPoiId').getEl().on('keyup', function(){
                                                            filterPoi();
                                                        }, this, {buffer:300});
                                                    }, scope:this}
                                                }
                                    },'-',{
                                            text : '<img src="http://dev2.dxplace.com/dx1/images/refresh.gif"> ',
                                            tooltip: {
                                                title:'Refresh'
                                            },
                                            handler:function() {   
                                                Ajax_point();
                                            }
                                    }]
                                },{
                                    xtype : 'panel',
                                    collapsed:true,
                                    id : 'searchListPanel',
                                    title : '<div align="center"><b>ค้นหาเส้นทาง</b></div>',
                                    autoScroll: true,
                                    autoWidth : true,
                                    autoHeight : true, 
                                    items :[searchForm]
                                },{
                                    xtype : 'panel',
                                    collapsed:true,
                                    id : 'wayPanel',
                                    title : '<div align="center"><b>ผลลัพธ์ของเส้นทาง</b></div>',
                                    autoWidth : true,
                                    autoHeight : true, 
                                    autoScroll: true,
                                    html : '<div id="step">&nbsp;</div><div id="distance">Miles: 0.00</div><div id="getDirections" style="height:420px; width:325px; "></div>'
                                }]
                            }]
                        },{
                            id : 'dataPortid',
                            title : '<div align="center"><b>รายการใบงานในกล่อง</b></div>', 
                            region:'east', 
                            collapsible:true, 
                            collapsed:false, 
                            split:true ,
                            border : true,
                            floatable: false,
                            margins: '0 0 0 0', 
                            cmargins: '0 0 0 0',
                            width: 430,
                            items:[{      
                                    id : 'boxListPanel',
                                    xtype : 'panel',
                                    autoScroll: true,
                                    border:false,
                                    autoWidth : true,
                                    autoHeight : true, 
                                    items : [boxListGrid],
                                    tooltip: {
                                        text: 'รายการและสถานะกล่องที่ใช้งานปัจจุบันทั้งหมด', 
                                        title:'Box Status'
                                    }
                            },{ 
                                xtype : 'panel',
                                layout:'accordion',       
                                layoutConfig:{animate:true}, 
                                border:false,
                                autoWidth : true,
                                autoHeight : true, 
                                items:[{    
                                    title : '<div align="center"><b>สถานะงาน<b></div>',
                                    id : 'statePanel', 
                                    collapsed : true,
                                    autoScroll: false,  
                                    autoWidth : true,
                                    border:true,
                                    autoHeight:true, 
                                    tooltip: {
                                        text: 'รายการสถานะงานของใบงานที่เลือก', 
                                        title:'State Shipment'
                                    },
                                    items : [{
                                        xtype : 'panel',    
                                        title : '<div align="left"  id=pickupid></div>',
                                        autoScroll: true,
                                        border : false,
                                        autoWidth : true,
                                        autoHeight:true, 
                                        items : [timePickupGrid]
                                    },{  
                                        xtype : 'panel',       
                                        title : '<div align="left" id=deliveredid></div>',
                                        border : false,
                                        autoScroll: true,
                                        autoWidth : true,
                                        autoHeight:true, 
                                        items : [timeDeliveryGrid]
                                    }],
                                    bbar:[{    
                                        text : '<img src="http://dev2.dxplace.com/dx1/images/offlineBox.png" width="13" height="13">ซ่อนไอคอนสถานะ',
                                        tooltip: {
                                            text: 'ซ่อนไอคอนสถานะงานเพื่อไม่ให้แสดง', 
                                            title:'Hide Icon'
                                        },
                                        handler:function() {  
                                            inorigin_marker.hide(); 
                                            atorigin_marker.hide(); 
                                            loading_marker.hide(); 
                                            outorigin_marker.hide(); 
                                            ondelivery_marker.hide(); 
                                            indest_marker.hide(); 
                                            atdest_marker.hide(); 
                                            offloading_marker.hide(); 
                                            outdest_marker.hide(); 
                                            delivered_marker.hide(); 
                                        }
                                    },'-',{    
                                        text : '<img src="http://dev2.dxplace.com/dx1/images/onlineBox.png" width="13" height="13">แสดงไอคอนสถานะ',
                                        tooltip: {
                                            text: 'แสดงไอคอนสถานะงานในแต่ละ State', 
                                            title:'Show Icon'
                                        },
                                        handler:function() {   
                                            inorigin_marker.show(); 
                                            atorigin_marker.show(); 
                                            loading_marker.show(); 
                                            outorigin_marker.show(); 
                                            ondelivery_marker.show(); 
                                            indest_marker.show(); 
                                            atdest_marker.show(); 
                                            offloading_marker.show(); 
                                            outdest_marker.show(); 
                                            delivered_marker.show(); 
                                        }
                                    },'-',{
                                            text : '<img src="/images/plugin.gif\" >ดูเส้นทางวิ่งงาน',
                                            tooltip: {
                                                text: 'แสดงเส้นทางการวิ่งงานของใบงานที่เลือก', 
                                                title:'Route Shipment'
                                            },
                                            handler: function() {
                                                    if(polyline){
                                                        map.removeOverlay(polyline);
                                                    }
                                                    Ext.getCmp('content-panel').layout.setActiveItem('map-panel');   
                                                    check_route();  
                                            }  
                                    },'-',refreshState/*,'-',{    
                                        text : 'ดูระยะทางจริงทั้งหมด',
                                        tooltip: {
                                            text: 'ดูระยะทางจริงที่วิ่งจากเริ่มงานจนจบงาน', 
                                            title:'Real Distance'
                                        },
                                        handler:function() {
                                            var distanceAll=0;
                                            for(i=0;i<countRoute;i++){
                                                distanceAll += parseInt(disRoute[i]);
                                            }    
                                            //alert("ระยะทางจริงทั้งหมด = "+distanceAll/1000+' กม.');
                                        }
                                    }*/]
                                }]
                            }]
                        },{
                            id : 'content-panel',
                            region:'center',
                            collapsible:true, 
                            collapsed:false, 
                            split:true ,
                            floatable: true,
                            margins: '0 0 0 0',
                            width : 500,
                            layout: 'card',
                            activeItem: 0,
                            items: [mapPanel,jobPanel,manageShipmentPanel,addShipmentPanel,queuePanel,platePanel,jobBoxPanel,allJobBoxPanel,addPlatePanel]
                        },{
                            id: 'Tab',                   
                            region:'north',
                            collapsible:false, 
                            collapsed:false, 
                            split:false ,
                            floatable: false,
                            tbar:[
                                    manageMember,'-',viewPanel,'-',viewMap,'-',addPoint
                                  ,'->',{
                                    text : '<div id="dataHeaduid"></div>',
                                    tooltip: {
                                        text: 'ชื่อ account ของผู้ใช้', 
                                        title:'User Account'
                                    }
                                },'-','Theme:',{
                                    xtype: 'themecombo',
                                    id:'theme-combo'
                                 }
                            ]
                        },{
                            id: 'ButtomBar',                   
                            region:'south',
                            collapsible:false, 
                            collapsed:false, 
                            split:false ,
                            floatable: false,
                            bbar:[{
                                    xtype: 'checkbox',
                                    id : 'followCarid',
                                    checked: false
                                    
                            },{
                                text : 'ติดตามสถานะรถ',
                                tooltip: {
                                        text: '<b>ติดตามตำแหน่งรถปัจจุบันตลอดเวลา</b>', 
                                        title:'Follow Car'
                                    }     
                            },'-',{
                                text : '<div id="dataHeadid"></div>',
                                tooltip: {
                                    text: 'ข้อมูลงานปัจจุบันที่เลือก', 
                                    title:'Job Data'
                                }        
                            },'->',refreshCheckBox/*,'-',{
                                text : '<div id="ajaxtimeid"></div>',
                                tooltip: {
                                    text: 'เวลาที่ส่งมาล่าสุด', 
                                    title:'AjaxTime'
                                }
                            }*/]
                        }]
              })  
      ]
     });  
      pbarBattery = new Ext.ProgressBar({
                id:'Batteryid',
                text:'<font size=-1><b>Battery</b></font>',
                width:100,
                tooltip: {
                    text: 'ค่าปริมาณแบตเตอรี่ของกล่อง', 
                    title:'Battery Level'
                },
                renderTo : 'pbarBatteryid'
      });
      pbarBattery.hide();  
              
    $(Ajax_checkStatus);
    $(Ajax_jobList); 
    $(Ajax_user);
    $(Ajax_point);
    $(checkCenter);  

        //---------------------------EndLoadPage----------------------//
        setTimeout(function(){
                Ext.EventManager.on(window, 'unload', function(){
                    if(map) GUnload();
                });
                Ext.get('loading').remove();
                Ext.get('loading-mask').fadeOut({remove:true});  
            }, 200);                      
}); 
    //---------------------------SelectGrid-----------------------//
    boxListGrid.getSelectionModel().on('rowselect', function(sm, rowIdx, r) { 
        boxListGrid.getSelectionModel().clearSelections();
        deviceID = r.data["BoxNum"];           
        iBox = rowIdx;  
        dataHead = '<b>ปัจจุบันติดตามกล่องหมายเลข :<font color=red> '+myDataStatus[iBox][0]+'</font> รถหมายเลขทะเบียน :<font color=red> '+myDataStatus[iBox][13]+'</font></b>';     
        $('#dataHeadid').html(dataHead);   
        goCarSelect(rowIdx); 
        Ext.getCmp('content-panel').layout.setActiveItem('map-panel');
    }); 
    boxListGrid.addListener('rowcontextmenu',menuBoxList); 
    function menuBoxList(grid, rowIndex, e ) {
        var boxListGrid = new Ext.menu.Menu();
            deviceID = myDataStatus[rowIndex][0];
            boxShipment = deviceID;
            boxListGrid.add({
                text:"ดูงานทั้งหมดของกล่องหมายเลข :<font color=red>"+deviceID+"</font>",
                handler:function(){ 
                    closeManagePanel = 1;
                    Ajax_jobList();
                    Ext.getCmp('content-panel').layout.setActiveItem('job-panel');
                }
            });    
            boxListGrid.add({
                text:"เซตทะเบียนในกล่องหมายเลข :<font color=red>"+deviceID+"</font>",
                handler:function(){ 
                    closeManagePanel = 1;
                    Ext.getCmp('content-panel').layout.setActiveItem('addplate-panel');              
                }
            });
            boxListGrid.add({
                text:"เพิ่มใบงานในกล่องหมายเลข :<font color=red>"+deviceID+"</font>",
                handler:function(){ 
                    closeManagePanel = 1;
                    Ajax_province();
                    Ext.getCmp('content-panel').layout.setActiveItem('addshipment-panel');              
                }
            });  
            boxListGrid.add({   
                text:"เคลียร์งานในกล่องหมายเลข :<font color=red>"+deviceID+"</font>",
                handler:function(){ 
                    setClear();              
                }
            }); 
            boxListGrid.add({
                text:"เปลี่ยนสถานะ/ย้ายงานไปยังกล่องอื่น",
                handler:function(){ 
                    StatusForm.show(); 
                }
            });
            e.stopEvent(); 
            boxListGrid.showAt(e.xy);
    }
    jobListGrid.getSelectionModel().on('rowselect', function(sm, rowIdx, r) {
                jobListGrid.getSelectionModel().clearSelections();
                     jobNumber = 0;
                     jobShipment = r.data["JobID"];
                     Ext.getCmp('statePanel').expand(true);  
                     map.closeInfoWindow();
                     Ajax_stateList(jobShipment);  
    }); 
    jobListAllGrid.getSelectionModel().on('rowselect', function(sm, rowIdx, r) {
                jobListAllGrid.getSelectionModel().clearSelections();
                     jobNumber = 0;
                     jobShipment = r.data["JobID"];
                     plateShipment = r.data["Plate"];
                     customerJob = r.data["CustomerJob"];
                     boxShipment = r.data["BoxID"]; 
                     statusShipment = r.data["Status"];
                     originShipment = r.data["Origin"]; 
                     destShipment = r.data["Dest"];  
                     latoriginShipment = r.data["LatOrigin"]; 
                     lonoriginShipment = r.data["LonOrigin"]; 
                     latdestShipment = r.data["LatDest"];
                     londestShipment = r.data["LonDest"];
                      
                     var dataShipment = '<font size=-1 >กล่องหมายเลข  :&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font size=-1 color=red> '+boxShipment+
                                        '</font><br><font size=-1 >รถหมายเลขทะเบียน  :&nbsp;&nbsp;</font><font size=-1 color=red>  '+plateShipment+
                                        '</font><br><font size=-1 >ใบงานหมายเลข  :&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font size=-1 color=red>  '+jobShipment+
                                        '</font><br><font size=-1 >ต้นทาง  :&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font size=-1 color=red>  '+originShipment+
                                        '</font><br> <font size=-1 >ปลายทาง  :&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font size=-1 color=red>  '+destShipment+
                                        '</font><br><font size=-1 >สถานะของงานปัจจุบัน  : </font><font size=-1 color=red>'+statusShipment+
                                        '</font><br><font size=-1 >ระยะทางจริงที่เดินทาง  : </font><font size=-1 color=red>'+
                                        '</font><br><font size=-1 >เวลาทั้งหมดที่ใช้  : &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font size=-1 color=red><span id=timeallid></span></font><font size=-1>(hh:mm:ss)'+
                                        '</font><br><font size=-1 >เวลาที่อยู่ที่ต้นทาง: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font size=-1 color=red><span id=timeoriginid></span></font><font size=-1>(hh:mm:ss)'+
                                        '</font><br><font size=-1 >เวลาที่อยู่ที่ปลายทาง  : &nbsp;</font><font size=-1 color=red><span id=timedestid></span></font><font size=-1>(hh:mm:ss)</font>';
                     $('#shipmentnum').html(customerJob);
                     $('#shipmentdataid').html(dataShipment);
                     Ext.getCmp('dataPortid').expand(true);  
                     Ext.getCmp('statePanel').expand(true);    
                     Ext.getCmp('content-panel').layout.setActiveItem('manageshipment-panel');
                     //progressJobWin.show();  
                     map.closeInfoWindow();
                     Ajax_stateList(jobShipment);
    });  
           
    //---------------------------SelectPickupGrid-----------------------//
    timePickupGrid.getSelectionModel().on('rowselect', function(sm, rowIdx, r) {
                timePickupGrid.getSelectionModel().clearSelections();
                if(stateList=='undefined'){
                }else{
                     if(rowIdx==0){
                        centerState(stateList[0][13],stateList[0][14],'InOrigin');
                     }else if(rowIdx==1){
                        centerState(stateList[0][15],stateList[0][16],'AtOrigin');
                     }else if(rowIdx==2){
                        centerState(stateList[0][17],stateList[0][18],'Loading');
                     }else if(rowIdx==3){
                        centerState(stateList[0][19],stateList[0][20],'OnDelivery');
                     }else if(rowIdx==4){
                        centerState(stateList[0][21],stateList[0][22],'OutOrigin');
                     }
                     Ext.getCmp('content-panel').layout.setActiveItem('map-panel'); 
                }
    });
    //---------------------------SelectPickupGrid-----------------------//
    timeDeliveryGrid.getSelectionModel().on('rowselect', function(sm, rowIdx, r) {
                timeDeliveryGrid.getSelectionModel().clearSelections(); 
                if(stateList=='undefined'){
                }else{
                     if(rowIdx==0){
                        centerState(stateList[0][23],stateList[0][24],'InDest');
                     }else if(rowIdx==1){
                        centerState(stateList[0][25],stateList[0][26],'AtDest');
                     }else if(rowIdx==2){
                        centerState(stateList[0][27],stateList[0][28],'OffLoading');
                     }else if(rowIdx==3){
                        centerState(stateList[0][29],stateList[0][30],'Delivered');
                     }else if(rowIdx==4){
                        centerState(stateList[0][31],stateList[0][32],'OutDest');  
                     }      
                     Ext.getCmp('content-panel').layout.setActiveItem('map-panel'); 
                }
    });
    //-------------------------EventGrid Point--------------------//
    pointListGrid.getSelectionModel().on('rowselect', function(sm, rowIdx, r) { 
        pointListGrid.getSelectionModel().clearSelections();
        centerPlace(rowIdx);
        clickrowPoi = rowIdx;
    }); 
    pointListGrid.addListener('rowcontextmenu',menus); 
    function menus(grid, rowIndex, e ) {
        var pointGridContext = new Ext.menu.Menu();
        deleteID = myDataPoint[rowIndex][7];
              
        pointGridContext.add({text:"ลบสถานที่",handler:function(){ deletePlace(deleteID); }});
        pointGridContext.add({text:"แก้ไขสถานที่"});

        e.stopEvent(); 
        pointGridContext.showAt(e.xy);
    }       
    //-------------------------EventGrid PlateList--------------------//
    plateListAllGrid.getSelectionModel().on('rowselect', function(sm, rowIdx, r) { 
        plateListAllGrid.getSelectionModel().clearSelections();
        boxInBox = r.data["BoxNum"];
        plateInBox = r.data["Plate"];
        jobID = r.data["Customer_JobID"]; 
        deviceID = boxInBox;  
        closeManagePanel = 2;
        dataHead = '<b>กล่องหมายเลข :<font color=red> '+boxInBox+'</font> รถหมายเลขทะเบียน :<font color=red> '+plateInBox+' </font>ใบงานปัจจุบันของกล่องหมายเลข :<font  color=red> '+jobID+'</font></b>'; 
        $('#headinboxid').html('กล่องหมายเลข :<font color=red> '+boxInBox+"</font> ทะเบียนหมายเลข :<font color=red>"+plateInBox+"</font>");
        $('#dataHeadid').html(dataHead); 
        getJobBox(boxInBox);
        Ext.getCmp('content-panel').layout.setActiveItem('jobbox-panel');
        Ext.getCmp('dataPointid').collapse(true); 
        Ext.getCmp('dataPortid').collapse(true);
    });
    plateListAllGrid.addListener('rowcontextmenu',menuPlateList); 
    function menuPlateList(grid, rowIndex, e ) {
        var plateListAllGrid = new Ext.menu.Menu();
            deviceID = myDataStatus[rowIndex][0];
            plateListAllGrid.add({
                text:"ดูงานทั้งหมดของกล่องหมายเลข :<font color=red>"+deviceID+"</font>",
                handler:function(){ 
                    closeManagePanel = 1;
                    Ajax_jobList();
                    Ext.getCmp('content-panel').layout.setActiveItem('job-panel');                 
                }
            });   
            plateListAllGrid.add({
                text:"เซตทะเบียนในกล่องหมายเลข :<font color=red>"+deviceID+"</font>",
                handler:function(){ 
                    closeManagePanel = 3;
                    Ext.getCmp('content-panel').layout.setActiveItem('addplate-panel');              
                }
            });
            plateListAllGrid.add({
                text:"เพิ่มใบงานในกล่องหมายเลข :<font color=red>"+deviceID+"</font>",
                handler:function(){ 
                    closeManagePanel = 3;
                    Ajax_province();
                    Ext.getCmp('content-panel').layout.setActiveItem('addshipment-panel');              
                }
            });  
            plateListAllGrid.add({
                text:"เคลียร์งานในกล่องหมายเลข :<font color=red>"+deviceID+"</font>",
                handler:function(){ 
                    setClear();              
                }
            });  
            e.stopEvent(); 
            plateListAllGrid.showAt(e.xy);
    }

    //------------------------getData--------------------//
    function getProvince(province){
        dataProvince = province.split(","); 
    } 
    function getBoxall(boxAll,name){
        nameUser =name; 
        //alert(boxAll+","+name);
        dataBoxNumber = boxAll.split(","); 
    }
    //-----------------------------GetJobBox--------------------------//
    function getJobBox(){
        var job_url = "http://dev2.dxplace.com/dx1/index.php/demo/json_getjobbox/"+boxInBox;
        //var jobListBox = new Array(); 
        var jobListBoxTmp = new Array();    
        for(i=0;i<15;i++){                                         
                 var temp_jobListBox = new Array();  
                        temp_jobListBox[0] = "";
                        temp_jobListBox[1] = "";
                        temp_jobListBox[2] = "";
                        temp_jobListBox[3] = "";
                        temp_jobListBox[4] = "";
                        temp_jobListBox[5] = "";
                        temp_jobListBox[6] = ""; 
                        temp_jobListBox[7] = ""; 
                        temp_jobListBox[8] = ""; 
                        temp_jobListBox[9] = ""; 
                        temp_jobListBox[10] = ""; 
                        temp_jobListBox[11] = ""; 
                        temp_jobListBox[12] = ""; 
                        temp_jobListBox[13] = ""; 
                        temp_jobListBox[14] = ""; 
                        temp_jobListBox[15] = ""; 
                        jobListBoxTmp[i] =temp_jobListBox;                
            }       
            jobListBox=new Array(); 
            jobListBox = jobListBoxTmp;
            setJobListBox(jobListBox);
        $.getJSON(job_url,function(p){ 
            for(i=0;i<p.jobListBox.length;i++){                                         
                 var temp_jobListBox = new Array();  
                        temp_jobListBox[0] = p.jobListBox[i].Plate;
                        temp_jobListBox[1] = p.jobListBox[i].BoxID;
                        temp_jobListBox[2] = p.jobListBox[i].JobID;
                        temp_jobListBox[3] = p.jobListBox[i].Origin;
                        temp_jobListBox[4] = p.jobListBox[i].Dest;
                        temp_jobListBox[5] = p.jobListBox[i].Status;
                        temp_jobListBox[6] = p.jobListBox[i].TimeInOrigin; 
                        temp_jobListBox[7] = p.jobListBox[i].TimeAtOrigin; 
                        temp_jobListBox[8] = p.jobListBox[i].TimeLoading; 
                        temp_jobListBox[9] = p.jobListBox[i].TimeOndelivery; 
                        temp_jobListBox[10] = p.jobListBox[i].TimeOutOrigin; 
                        temp_jobListBox[11] = p.jobListBox[i].TimeInDest; 
                        temp_jobListBox[12] = p.jobListBox[i].TimeAtDest; 
                        temp_jobListBox[13] = p.jobListBox[i].TimeOffloading; 
                        temp_jobListBox[14] = p.jobListBox[i].TimeDelivered; 
                        temp_jobListBox[15] = p.jobListBox[i].TimeOutDest; 
                        temp_jobListBox[16] = p.jobListBox[i].Customer_JobID;
                        jobListBoxTmp[i] =temp_jobListBox;                
            } 
            //window.setTimeout("getJobBox()", 20000); 
            jobListBox=new Array(); 
            jobListBox = jobListBoxTmp;
            setJobListBox(jobListBox);
        });
    
    }  
    function setJobListBox(jobListBox){
        myjobListBox = jobListBox;
        jobListBoxStore.loadData(myjobListBox); 
        //progressLoad.hide(); 
        jobListBoxGrid.getView().refresh();
    }
    var jobListBoxStore = new Ext.data.SimpleStore({
            fields: [
                {name: 'PlateInBox'},{name: 'BoxIDInBox'},{name: 'JobIDInBox'},{name: 'OriginInBox'},
                {name: 'DestInBox'},{name: 'StatusInBox'},
                {name: 'TimeInOrigin'},{name: 'TimeAtOrigin'},{name: 'TimeLoading'},{name: 'TimeOndelivery'},
                {name: 'TimeOutOrigin'},{name: 'TimeInDest'},{name: 'TimeAtDest'},{name: 'TimeOffloading'},
                {name: 'TimeDelivered'},{name: 'TimeOutDest'},{name: 'CustomerJobID'}               
            ]
    });                           
    function JobIDInBox(val){
        if(val == 'undefined' || val == ''){val='-';} 
         return '<span style="color:white;"><b>' + val + '</b></span>';
    }
    function CustomerJobID(val){
         if(val == 'undefined' || val == ''){val='-';} 
         return '<span style="color:white;"><b>' + val + '</b></span>';
    }
    function StatusInBox(val){
        if(val=="Queue"){
            return '<span style="color:green;"><b>' + val + '</b></span>'; 
        }else {
            return '<span style="color:blue;"><b>'+ val +'</b></span>';
        }                    
         //return '<span style="color:brown;"><b>' + val + '</b></span>';
    }
    function TimeImage(val){
        if(val!=""){
            return '<img src = "http://dev2.dxplace.com/dx1/images/clock.png" style="width:15px; height:15px;" >';   
        }else{
            return '';
        }
    }
    var jobListBoxGrid = new Ext.grid.GridPanel({
                store: jobListBoxStore,
                border : false,
                columns: [                
                    {id:'ID',header: "<center><b>Job</b></center>",css: 'text-align: center; background-color:green;',renderer :CustomerJobID ,width: 50, sortable: true,dataIndex: 'CustomerJobID'},  
                    {header: "<center><b>ต้นทาง</b></center>",css: 'text-align: center;' ,width: 80, sortable: true,dataIndex: 'OriginInBox'},
                    {header: "<center><b>ปลายทาง</b></center>",css: 'text-align: center;' ,width: 80, sortable: true,dataIndex: 'DestInBox'},
                    {header: "<center><b>สถานะ</b></center>",css: 'text-align: center;' ,renderer :StatusInBox , width: 85, sortable: true,dataIndex: 'StatusInBox'},
                    {header: "<center><b>เข้าต้นทาง</b></center>",css: 'text-align: center;' ,renderer :TimeImage,width: 85, sortable: true,dataIndex: 'TimeInOrigin'},
                    {header: "<center><b>อยู่ที่ต้นทาง</b></center>",css: 'text-align: center;'  ,renderer :TimeImage,width: 85, sortable: true,dataIndex: 'TimeAtOrigin'},
                    {header: "<center><b>เริ่มขึ้นสินค้า</b></center>",css: 'text-align: center;'  ,renderer :TimeImage,width: 95, sortable: true,dataIndex: 'TimeLoading'},
                    {header: "<center><b>เสร็จสิ้นการขึ้นสินค้า</b></center>",css: 'text-align: center;' ,renderer :TimeImage ,width: 90, sortable: true,dataIndex: 'TimeOndelivery'},
                    {header: "<center><b>ออกจากต้นทาง</b></center>",css: 'text-align: center;'  ,renderer :TimeImage,width: 90, sortable: true,dataIndex: 'TimeOutOrigin'},
                    {header: "<center><b>เข้าปลายทาง</b></center>",css: 'text-align: center;'  ,renderer :TimeImage,width: 85, sortable: true,dataIndex: 'TimeInDest'},
                    {header: "<center><b>อยู่ที่ปลายทาง</b></center>",css: 'text-align: center;'  ,renderer :TimeImage,width: 85, sortable: true,dataIndex: 'TimeAtDest'},
                    {header: "<center><b>เริ่มลงสินค้า</b></center>",css: 'text-align: center;'  ,renderer :TimeImage,width: 95, sortable: true,dataIndex: 'TimeOffloading'},
                    {header: "<center><b>เสร็จสิ้นการลงสินค้า</b></center>",css: 'text-align: center;'  ,renderer :TimeImage,width: 90, sortable: true,dataIndex: 'TimeDelivered'},
                    {header: "<center><b>ออกจากปลายทาง</b></center>",css: 'text-align: center;'  ,renderer :TimeImage,width: 90, sortable: true,dataIndex: 'TimeOutDest'}
                ],
                stripeRows: true,  
                autoWidth : true,
                autoHeight : true,
                onRender: function() {
                        Ext.grid.GridPanel.prototype.onRender.apply(this, arguments);
                        this.addEvents("beforetooltipshow");
                        this.tooltip = new Ext.ToolTip({
                            renderTo: Ext.getBody(),
                            target: this.view.mainBody,
                            listeners: {
                                beforeshow: function(qt) {
                                    var v = this.getView();
                                    var row = v.findRowIndex(qt.baseTarget);
                                    var cell = v.findCellIndex(qt.baseTarget);
                                    this.fireEvent("beforetooltipshow", this, row, cell);
                                },
                                scope: this
                            }
                        });
                    },
                    listeners: {
                        render: function(g) {
                            g.on("beforetooltipshow", function(grid, row, col,r) {
                                if(col==0){ 
                                    grid.tooltip.body.update(myjobListBox[row][16]);
                                }
                                if(col==1){ 
                                    grid.tooltip.body.update(myjobListBox[row][3]);
                                }
                                if(col==2){ 
                                    grid.tooltip.body.update(myjobListBox[row][4]);
                                }
                                if(col==3){ 
                                    grid.tooltip.body.update(myjobListBox[row][5]);
                                }
                                else if(col>3){ 
                                    grid.tooltip.body.update(myjobListBox[row][col+2]);
                                }
                            });
                        }
                    }
    });
    //-----------------------jobBoxPanel---------------------//
    var jobBoxPanel = {
        id: 'jobbox-panel',
        title: 'รายการงานในกล่องทั้งหมด',
        layout: 'absolute', 
        defaults: {
            bodyStyle: 'padding:0px;'
        }, 
        items:[jobListBoxGrid],
        bbar: new Ext.PagingToolbar({
            pageSize: 25,
            store: jobListBoxStore,
            displayInfo: true,
            items:[
                '-', {
                pressed: true,
                enableToggle:true,
                text: 'Show Preview',
                toggleHandler: function(btn, pressed){
                    var view = jobListBoxStore.getView();
                    view.showPreview = pressed;
                    view.refresh();
                }
            }]
        }),
        tbar: [{
                text : 'ค้นหาใบงานที่: ',
                tooltip: {
                    text: 'ค้นหาจากใบงานในกล่อง', 
                    title:'Search ShipmentID'
                }
        },{
            xtype: 'textfield',
            id: 'filterJobInBoxid',
            selectOnFocus: true,
            width: 60,
            listeners: {
                'render': {fn:function(){
                    Ext.getCmp('filterJobInBoxid').getEl().on('keyup', function(){
                        filterJobInBox();
                    }, this, {buffer:300});
                }, scope:this}
            }
        },'-',
            addjobMenu,'-',addplateMenu,'-',clearalljobMenu,'-',refreshJobBox,'-',closeJobListBox,'->',{text : '<div id=headinboxid></div>' }
        ]
    };  
    function filterJobInBox(){
        var filterJobInBox = Ext.getCmp('filterJobInBoxid');
        jobListBoxStore.filter('JobIDInBox', filterJobInBox.getValue());
    }  
    //------------------------Event JobListBox-------------------------------// 
    jobListBoxGrid.addListener('rowcontextmenu',menuStatusForm); 
    function menuStatusForm(grid, rowIndex, e ) {
        boxShipment =  boxInBox;
        plateShipment = plateInBox;
        jobShipment =  myjobListBox[rowIndex][2];
        statusShipment =  myjobListBox[rowIndex][5];
        originShipment =  myjobListBox[rowIndex][3];
        destShipment =  myjobListBox[rowIndex][4];
        
        var jobListBoxGrid = new Ext.menu.Menu();
        deleteID = myDataPoint[rowIndex][7];
        jobListBoxGrid.add({
            text:"เปลี่ยนสถานะ/ย้ายงานไปยังกล่องอื่น",
            handler:function(){ 
                StatusForm.show(); 
            }});
        jobListBoxGrid.add({
            text:"ลบงานออกจากกล่อง",handler:function(){
                if(statusShipment == 'Queue'){ 
                    deleteOneJob(boxShipment,jobShipment);
                }else{
                    Ext.MessageBox.alert('Delete',"คุณไม่สามารถลบงานนี้ได้ เพราะกำลังดำเนินการอยู่");     
                } 
            }                                                    
        });
        jobListBoxGrid.add({
            text:"ดู สถานะการวิ่งงาน และ Timestamp (PickUp/Delivery)",
            handler:function(){ 
                Ajax_stateList(jobShipment); 
                Ext.getCmp('content-panel').layout.setActiveItem('map-panel');
                Ext.getCmp('dataPortid').expand(true);
                Ext.getCmp('statePanel').expand(true);  
            }
        });  
        e.stopEvent(); 
        jobListBoxGrid.showAt(e.xy);
    
    }
    //-----------------------------GetAllJobBox--------------------------//
    function getAllJobBox(){
        var alljob_url = "http://dev2.dxplace.com/dx1/index.php/demo/json_getalljobbox";
        var allJobListBox=new Array();  
            for(i=0;i<15;i++){                                         
                 var temp_allJobListBox = new Array();  
                        temp_allJobListBox[0] = "";
                        temp_allJobListBox[1] = "";
                        temp_allJobListBox[2] = "";
                        temp_allJobListBox[3] = "";
                        temp_allJobListBox[4] = "";
                        temp_allJobListBox[5] = "";
                        temp_allJobListBox[6] = "";
                        temp_allJobListBox[7] = ""; 
                        temp_allJobListBox[8] = "";
                        temp_allJobListBox[9] = ""; 
                        temp_allJobListBox[10] = "";
                        temp_allJobListBox[11] = "";
                        temp_allJobListBox[12] = "";
                        temp_allJobListBox[13] = "";
                        temp_allJobListBox[14] = "";
                        temp_allJobListBox[15] = "";
                        allJobListBox[i] =temp_allJobListBox;                
            }        
            myAllJobListBox = allJobListBox;    
            allJobListBoxStore.loadData(myAllJobListBox); 
        $.getJSON(alljob_url,function(p){ 
            for(i=0;i<p.allJobListBox.length;i++){                                         
                 var temp_allJobListBox = new Array();  
                        temp_allJobListBox[0] = p.allJobListBox[i].Plate;
                        temp_allJobListBox[1] = p.allJobListBox[i].BoxID;
                        temp_allJobListBox[2] = p.allJobListBox[i].JobID;
                        temp_allJobListBox[3] = p.allJobListBox[i].Origin;
                        temp_allJobListBox[4] = p.allJobListBox[i].Dest;
                        temp_allJobListBox[5] = p.allJobListBox[i].Status;
                        temp_allJobListBox[6] = p.allJobListBox[i].TimeInOrigin; 
                        temp_allJobListBox[7] = p.allJobListBox[i].TimeAtOrigin; 
                        temp_allJobListBox[8] = p.allJobListBox[i].TimeLoading; 
                        temp_allJobListBox[9] = p.allJobListBox[i].TimeOndelivery; 
                        temp_allJobListBox[10] = p.allJobListBox[i].TimeOutOrigin; 
                        temp_allJobListBox[11] = p.allJobListBox[i].TimeInDest; 
                        temp_allJobListBox[12] = p.allJobListBox[i].TimeAtDest; 
                        temp_allJobListBox[13] = p.allJobListBox[i].TimeOffloading; 
                        temp_allJobListBox[14] = p.allJobListBox[i].TimeDelivered; 
                        temp_allJobListBox[15] = p.allJobListBox[i].TimeOutDest;
                        temp_allJobListBox[16] = p.allJobListBox[i].Customer_JobID;  
                        allJobListBox[i] =temp_allJobListBox;                
            }
            //window.setTimeout("getJobBox()", 20000); 
            setAllJobListBox(allJobListBox);
        });
    
    }   
    function setAllJobListBox(allJobListBox){
        myAllJobListBox = allJobListBox;    
        allJobListBoxStore.loadData(myAllJobListBox); 
        //progressLoad.hide(); 
    }
    var allJobListBoxStore = new Ext.data.SimpleStore({
            fields: [
                {name: 'PlateInBox'},{name: 'BoxIDInBox'},{name: 'JobIDInBox'},{name: 'OriginInBox'},
                {name: 'DestInBox'},{name: 'StatusInBox'},
                {name: 'TimeInOrigin'},{name: 'TimeAtOrigin'},{name: 'TimeLoading'},{name: 'TimeOndelivery'},
                {name: 'TimeOutOrigin'},{name: 'TimeInDest'},{name: 'TimeAtDest'},{name: 'TimeOffloading'},
                {name: 'TimeDelivered'},{name: 'TimeOutDest'},{name: 'CustomerJobIDInBox'}              
            ]
    });  
    function AllJobIDInBox(val){
        if(val == 'undefined' || val == ''){val='-';} 
         return '<span style="color:white;"><b>' + val + '</b></span>';
    }
    function AllCustomerJobIDInBox(val){
         if(val == 'undefined' || val == ''){val='-';} 
         return '<span style="color:white;"><b>' + val + '</b></span>';
    }
    function AllPlateIDInBox(val){ 
        if(val == 'undefined' || val == ''){val='-';}      
         return '<span style="color:#bd1010;"><b>' + val + '</b></span>';
    }
    function AllBoxIDInBox(val){
        if(val == 'undefined' || val == ''){val='-';} 
         return '<span style="color:white;"><b>' + val + '</b></span>';
    }
    function AllStatusInBox(val){
        if(val=="Queue"){
            return '<span style="color:blue;"><b>' + val + '</b></span>'; 
        }else if(val=="Delivered" || val=="OutDest"){
            return '<span style="color:green;"><b>' + val + '</b></span>'; 
        }else {
            return '<span style="color:red;"><b>'+ val +'</b></span>';
        }                    
    }                                  
    var allJobListBoxGrid = new Ext.grid.GridPanel({                          
                store: allJobListBoxStore,
                border : false,
                columns: [                
                    {id:'ID',header: "<center><b>ทะเบียน</b></center>",css: 'text-align: center; background-color:#bd1010;',renderer :AllPlateIDInBox ,width: 50, sortable: true,dataIndex: 'PlateInBox'},  
                    {header: "<center><b>กล่อง</b></center>",css: 'text-align: center; background-color:#f1a7a7;',renderer :AllJobIDInBox ,width: 50, sortable: true,dataIndex: 'BoxIDInBox'},
                    {header: "<center><b>ใบงาน</b></center>",css: 'text-align: center; background-color:green;',renderer :AllCustomerJobIDInBox ,width: 50, sortable: true,dataIndex: 'CustomerJobIDInBox'},
                    {header: "<center><b>ต้นทาง</b></center>",css: 'text-align: center;' ,width: 80, sortable: true,dataIndex: 'OriginInBox'},
                    {header: "<center><b>ปลายทาง</b></center>",css: 'text-align: center;' ,width: 80, sortable: true,dataIndex: 'DestInBox'},
                    {header: "<center><b>สถานะ</b></center>",css: 'text-align: center;' ,renderer :AllStatusInBox , width: 85, sortable: true,dataIndex: 'StatusInBox'},
                    {header: "<center><b>เข้าต้นทาง</b></center>",css: 'text-align: center;' ,renderer :TimeImage,width: 80, sortable: true,dataIndex: 'TimeInOrigin'},
                    {header: "<center><b>อยู่ที่ต้นทาง</b></center>",css: 'text-align: center;' ,renderer :TimeImage,width: 80, sortable: true,dataIndex: 'TimeAtOrigin'},
                    {header: "<center><b>เริ่มขึ้นสินค้า</b></center>",css: 'text-align: center;',renderer :TimeImage ,width: 80, sortable: true,dataIndex: 'TimeLoading'},
                    {header: "<center><b>เสร็จสิ้นการขึ้นสินค้า</b></center>",css: 'text-align: center;' ,renderer :TimeImage,width: 80, sortable: true,dataIndex: 'TimeOndelivery'},
                    {header: "<center><b>ออกจากต้นทาง</b></center>",css: 'text-align: center;' ,renderer :TimeImage,width: 80, sortable: true,dataIndex: 'TimeOutOrigin'},
                    {header: "<center><b>เข้าปลายทาง</b></center>",css: 'text-align: center;' ,renderer :TimeImage,width: 80, sortable: true,dataIndex: 'TimeInDest'},
                    {header: "<center><b>อยู่ที่ปลายทาง</b></center>",css: 'text-align: center;' ,renderer :TimeImage,width: 80, sortable: true,dataIndex: 'TimeAtDest'},
                    {header: "<center><b>เริ่มลงสินค้า</b></center>",css: 'text-align: center;',renderer :TimeImage ,width: 80, sortable: true,dataIndex: 'TimeOffloading'},
                    {header: "<center><b>เสร็จสิ้นการลงสินค้า</b></center>",css: 'text-align: center;',renderer :TimeImage ,width: 80, sortable: true,dataIndex: 'TimeDelivered'},
                    {header: "<center><b>ออกจากปลายทาง</b></center>",css: 'text-align: center;' ,renderer :TimeImage,width: 80, sortable: true,dataIndex: 'TimeOutDest'}
                ],
                stripeRows: true,
                autoWidth : true,
                autoHeight : true,
                onRender: function() {
                        Ext.grid.GridPanel.prototype.onRender.apply(this, arguments);
                        this.addEvents("beforetooltipshow");
                        this.tooltip = new Ext.ToolTip({
                            renderTo: Ext.getBody(),
                            target: this.view.mainBody,
                            listeners: {
                                beforeshow: function(qt) {
                                    var v = this.getView();
                                    var row = v.findRowIndex(qt.baseTarget);
                                    var cell = v.findCellIndex(qt.baseTarget);
                                    this.fireEvent("beforetooltipshow", this, row, cell);
                                },
                                scope: this
                            }
                        });
                    },
                    listeners: {
                        render: function(g) {
                            g.on("beforetooltipshow", function(grid, row, col,r) {
                                if(col==2){
                                    grid.tooltip.body.update(myAllJobListBox[row][16]);
                                }else{
                                    grid.tooltip.body.update(myAllJobListBox[row][col]);
                                }
                            });
                        }
                    }
    });
    //-----------------------jobBoxPanel---------------------//
    var allJobBoxPanel = {
        id: 'alljobbox-panel',
        title: 'รายการงานปัจจุบันที่ดำเนินการอยู่',
        layout: 'absolute',
        //autoScroll : true,   
        defaults: {
            bodyStyle: 'padding:0px;'
        },                                            
        items:[allJobListBoxGrid],
        bbar: new Ext.PagingToolbar({
            pageSize: 25,
            store: allJobListBoxStore,
            displayInfo: true,
            items:[
                '-', {
                pressed: true,
                enableToggle:true,
                text: 'Show Preview',
                toggleHandler: function(btn, pressed){
                    var view = allJobListBoxStore.getView();
                    view.showPreview = pressed;
                    view.refresh();
                }
            }]
        }),
        tbar: [{
                text : 'ค้นหาทะเบียนที่: ',
                tooltip: {
                    text: 'ค้นหาจากใบงานในกล่อง', 
                    title:'Search ShipmentID'
                }
        },{
            xtype: 'textfield',
            id: 'filterAllPlateInBoxid',
            selectOnFocus: true,
            width: 60,
            listeners: {
                'render': {
                    fn:function(){
                        Ext.getCmp('filterAllPlateInBoxid').getEl().on('keyup', function(){
                                filterAllPlateInBox();
                            }, this, {buffer:300});
                        }, 
                    scope:this
                }
            }
        },'-',{
                text : 'ค้นหากล่องที่: ',
                tooltip: {
                    text: 'ค้นหากล่องจากกล่องทั้งหมด', 
                    title:'Search BoxID'
                }
        },{
            xtype: 'textfield',
            id: 'filterAllBoxInBoxid',
            selectOnFocus: true,
            width: 40,
            listeners: {
                'render': {fn:function(){
                    Ext.getCmp('filterAllBoxInBoxid').getEl().on('keyup', function(){
                        filterAllBoxInBoxid();
                    }, this, {buffer:300});
                }, scope:this}
            }
        },'-',{
                text : 'ค้นหาใบงานที่: ',
                tooltip: {
                    text: 'ค้นหาจากใบงานในกล่อง', 
                    title:'Search ShipmentID'
                }
        },{
            xtype: 'textfield',
            id: 'filterAllJobInBoxid',
            selectOnFocus: true,
            width: 60,
            listeners: {
                'render': {fn:function(){
                    Ext.getCmp('filterAllJobInBoxid').getEl().on('keyup', function(){
                        filterAllJobInBox();
                    }, this, {buffer:300});
                }, scope:this}
            }
        },'-',{
                text : 'ค้นหาต้นทาง : ',
                tooltip: {
                    text: 'ค้นหาต้นทางจากใบงานทั้งหมด', 
                    title:'Search Origin'
                }
        },{
            xtype: 'textfield',
            id: 'filterAllOriginInBoxid',
            selectOnFocus: true,
            width: 60,
            listeners: {
                'render': {fn:function(){
                    Ext.getCmp('filterAllOriginInBoxid').getEl().on('keyup', function(){
                        filterAllOriginInBox();
                    }, this, {buffer:300});
                }, scope:this}
            }
        },'-',{
                text : 'ค้นหาปลายทาง: ',
                tooltip: {
                    text: 'ค้นหาปลายทาง', 
                    title:'Search Dest'
                }
        },{
            xtype: 'textfield',
            id: 'filterAllDestInBoxid',
            selectOnFocus: true,
            width: 60,
            listeners: {
                'render': {fn:function(){
                    Ext.getCmp('filterAllDestInBoxid').getEl().on('keyup', function(){
                        filterAllDestInBox();
                    }, this, {buffer:300});
                }, scope:this}
            }
        },'-',refreshJobActive,'-',closeJobListBox
        ] 
     
    };  
    //------------------------Event AllJobListBox-------------------------------//
    allJobListBoxGrid.addListener('rowcontextmenu',menuStatusForm02); 
    function menuStatusForm02(grid, rowIndex, e ) {
        boxShipment =  myAllJobListBox[rowIndex][1];
        plateShipment = myAllJobListBox[rowIndex][0];
        jobShipment =  myAllJobListBox[rowIndex][2];
        statusShipment =  myAllJobListBox[rowIndex][5];
        originShipment =  myAllJobListBox[rowIndex][3];
        destShipment =  myAllJobListBox[rowIndex][4];
        
        var allJobListBoxGrid = new Ext.menu.Menu();
        allJobListBoxGrid.add({
            text:"เปลี่ยนสถานะ/ย้ายงานไปยังกล่องอื่น",
            handler:function(){ 
                StatusForm.show(); 
            }
        }); 
        e.stopEvent(); 
        allJobListBoxGrid.showAt(e.xy);
    
    }
    //------------------------Filter-----------------------//
    function filterAllJobInBox(){
        var filterAllJobInBox = Ext.getCmp('filterAllJobInBoxid');
        allJobListBoxStore.filter('JobIDInBox', filterAllJobInBox.getValue());
    }  
    function filterAllPlateInBox(){
        var filterAllPlateInBox = Ext.getCmp('filterAllPlateInBoxid');
        allJobListBoxStore.filter('PlateInBox', filterAllPlateInBox.getValue());
    }
    function filterAllBoxInBox(){
        var filterAllBoxInBox = Ext.getCmp('filterAllBoxInBoxid');
        allJobListBoxStore.filter('BoxIDInBox', filterAllBoxInBox.getValue());
    }
    function filterAllOriginInBox(){
        var filterAllOriginInBox = Ext.getCmp('filterAllOriginInBoxid');
        allJobListBoxStore.filter('OriginInBox', filterAllOriginInBox.getValue());
    }
    function filterAllDestInBox(){
        var filterAllDestInBox = Ext.getCmp('filterAllDestInBoxid');
        allJobListBoxStore.filter('DestInBox', filterAllDestInBox.getValue());
    }
    allJobListBoxGrid.getSelectionModel().on('rowselect', function(sm, rowIdx, r) { 
    });       
    //-----------------------------SetLogin---------------------------------//
    function setLogin(loginData){
         loginArray = loginData.split(","); 
         user = loginArray[0];
         pass = loginArray[1];  
    }
    function getJobDataAll(deviceID){
        var jobDataAll_url = "http://dev2.dxplace.com/dx1/index.php/demo/jobData/"+deviceID;
                           if (window.XMLHttpRequest) {
                                xmlReq = new XMLHttpRequest();
                            } else {
                                xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
                            }
                            xmlReq.onreadystatechange = callBack_jobAll;
                            xmlReq.open("GET", jobDataAll_url, true);
                            xmlReq.send(null);   
    }
    function callBack_jobAll(){
        if (xmlReq.readyState == 4) {
                    if (xmlReq.status == 200) {
                    }
        }
    }
    //-----------------------------ConfigInput----------------------------//
    function setConfigDataInput(dataAddConfig){
        array_dataAddConfig = dataAddConfig.split(",");
        plateNumber = array_dataAddConfig[0];
        overSpeed = array_dataAddConfig[1]; 
        lowSpeed = array_dataAddConfig[2]; 

        config = urlencode("0,"+deviceID+","+plateNumber+","+overSpeed+","+lowSpeed);

        var config_url = "http://dev2.dxplace.com/dx1/index.php/demo/send_config/"+config;
                           if (window.XMLHttpRequest) {
                                xmlReq = new XMLHttpRequest();
                            } else {
                                xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
                            }
                            xmlReq.onreadystatechange = callBack_config;
                            xmlReq.open("GET", config_url, true);
                            xmlReq.send(null);   
    }
    function callBack_config(){
        if (xmlReq.readyState == 4) {
                    if (xmlReq.status == 200) { 
                    }
        }
    }            
    //-----------------------------SavePoint----------------------------//
    function setSavePoint(Lat,Lon,Radius){   
        userID = 1;  
        Place = document.getElementById('namePlaceNewid').value;
        var pointHere = new GLatLng(Lat,Lon);
        markerpoi  = new GMarker(pointHere,{icon: IconPlace}); 
        map.addOverlay(markerpoi);   
        dataSvaePoint = nameUser+","+userID+","+Lat+","+Lon+","+Place+","+Radius;
        var savepoint_url = "http://dev2.dxplace.com/dx1/index.php/demo/send_savepoint/"+dataSvaePoint;
                           if (window.XMLHttpRequest) {
                                xmlReq = new XMLHttpRequest();
                            } else {
                                xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
                            }
                            xmlReq.onreadystatechange = callBack_savepoint;
                            xmlReq.open("GET", savepoint_url, true);
                            xmlReq.send(null);   
    }
    function callBack_savepoint(){
        if (xmlReq.readyState == 4) {
                    if (xmlReq.status == 200) {
                        Ext.getCmp('dataPointid').expand(true); 
                        Ext.getCmp('dataPortid').collapse(true); 
                        Ext.MessageBox.alert('AddPoint',"เพิ่มสถานที่แล้ว");
                        //map.removeOverlay(markerpoi);
                        setTimeout("Ajax_point()",2000);
                    }
        }
    }     
    //---------------------------------Delete Point------------------------//   
    function deletePlace(deletePlaceID){
        var deleteplace_url = "http://dev2.dxplace.com/dx1/index.php/demo/send_deletePlace/"+deletePlaceID;
                           if (window.XMLHttpRequest) {
                                xmlReq = new XMLHttpRequest();
                            } else {
                                xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
                            }
                            xmlReq.onreadystatechange = callBack_deleteplace;
                            xmlReq.open("GET", deleteplace_url, true);
                            xmlReq.send(null);     
    }
    function callBack_deleteplace(){
        if (xmlReq.readyState == 4) {
                    if (xmlReq.status == 200) {
                        //map.removeOverlay(markerpoi);
                        Ext.MessageBox.alert('DeletePoint',"ลบสถานที่เรียบร้อยแล้ว");   
                        setTimeout("Ajax_point()",2000);
                    }
        }
    }
    //-----------------------------JobDataInput---------------------------//
    function setJobDataInput(dataAddJob){
        dataJob = dataAddJob.split(",");
        dataJobID = dataJob[0]; 
        fromProvinceData1 = urldecode(dataJob[1]); 
        toProvinceData1 = urldecode(dataJob[2]); 
        
        fromProvince_array1 = fromProvinceData1.split(":");
        fromProvince1 =  fromProvince_array1[0];
        origin_lat1 =  fromProvince_array1[1];
        origin_lon1 =  fromProvince_array1[2];
        origin_radius1 =  fromProvince_array1[3];  

        toProvince_array1 = toProvinceData1.split(":");
        toProvince1 =  toProvince_array1[0];
        dest_lat1 =  toProvince_array1[1];
        dest_lon1 =  toProvince_array1[2];
        dest_radius1 =  toProvince_array1[3];

        messageSend = "1,"+deviceID+","+dataJobID+","+fromProvince1+","+toProvince1+","+origin_lat1+","+origin_lon1+","+origin_radius1+","+dest_lat1+","+dest_lon1+","+dest_radius1+","+dataJobID;
        messageJob = urlencode(messageSend);  

        jobData = deviceID+","+plateNumber+","+dataJobID+","+fromProvince1+","+toProvince1+","+origin_lat1+","+origin_lon1+","+origin_radius1+","+dest_lat1+","+dest_lon1+","+dest_radius1+","+dataJobID; 
        jobData = urlencode(jobData);
    
        var dataInput_url = "http://dev2.dxplace.com/dx1/index.php/demo/test_send/"+messageJob+"/"+jobData;
                   if (window.XMLHttpRequest) {
                        xmlReq = new XMLHttpRequest();
                    } else {
                        xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    xmlReq.onreadystatechange = callBack_sendData;
                    xmlReq.open("GET", dataInput_url, true);
                    xmlReq.send(null);   
    }  
    function callBack_sendData(){
        if (xmlReq.readyState == 4) { 
                    if (xmlReq.status == 200) {
                        Ext.MessageBox.alert('Status',"ส่งข้อมูลเข้ากล่องเรียบร้อยแล้ว"); 
                        Ajax_jobList();
                    }
        }
    }
    //-----------------------------ChangeStatus---------------------------// 
    function setChangeState(dataChangeState){
         if(dataChangeState == 'เข้าต้นทาง'){
             statusChange = 2;      
         }else if(dataChangeState == 'อยู่ที่ต้นทาง'){
             statusChange = 3;
         }else if(dataChangeState == 'เริ่มขึ้นสินค้า'){
             statusChange = 4;
         }else if(dataChangeState == 'เสร็จสิ้นการขึ้นสินค้า'){
             statusChange = 5;
         }else if(dataChangeState == 'เข้าปลายทาง'){
             statusChange = 6;
         }else if(dataChangeState == 'อยู่ที่ปลายทาง'){
             statusChange = 7;
         }else if(dataChangeState == 'เริ่มลงสินค้า'){
             statusChange = 8;
         }else if(dataChangeState == 'เสร็จสิ้นการลงสินค้า'){
             statusChange = 9;
         }
        changeState = "8,"+boxShipment+","+statusChange;
        var changeState_url = "http://dev2.dxplace.com/dx1/index.php/demo/send_changeState/"+changeState;
                           if (window.XMLHttpRequest) {
                                xmlReq = new XMLHttpRequest();
                            } else {
                                xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
                            }
                            xmlReq.onreadystatechange = callBack_changeState;
                            xmlReq.open("GET", changeState_url, true);
                            xmlReq.send(null);     
    }
    function callBack_changeState(){
        if (xmlReq.readyState == 4) {
                    if (xmlReq.status == 200) {
                        Ext.MessageBox.alert('Status',"เปลี่ยนสถานะเป็น"+dataChangeState+"แล้ว");
                        StatusForm.hide(); 
                        Ajax_jobList();
                        //Ajax_stateList(jobClick); 
                    }
        }
    }
    //----------------------------Clear--------------------------------//
    function setClear(){
            Ext.MessageBox.confirm('Confirm', 'คุณต้องการลบข้อมูลทั้งหมด ?', showResultClear);
    }
    function showResultClear(btn){
            if(btn=='yes'){
                clear = "4,"+deviceID+",8,"+deviceID+",0";
                var clear_url = "http://dev2.dxplace.com/dx1/index.php/demo/send_clear/"+clear;
                           if (window.XMLHttpRequest) {
                                xmlReq = new XMLHttpRequest();
                            } else {
                                xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
                            }
                            xmlReq.onreadystatechange = callBack_Clear;
                            xmlReq.open("GET", clear_url, true);
                            xmlReq.send(null);
            }else if(btn=='no'){
            }
    }
    function callBack_Clear(){
        if (xmlReq.readyState == 4) {
                    if (xmlReq.status == 200) {
                        Ext.MessageBox.alert('Status',"ลบข้อมูลสถานะแล้ว");
                        //StatusForm.hide();
                        Ajax_jobList();
                    }
        }
    }   
    //--------------------------Delete OneJob---------------------------//
    function deleteOneJob(boxDelete,jobDelete){
        deleteJob =  "3,"+boxDelete+","+jobDelete;   
        var deleteJob_url = "http://dev2.dxplace.com/dx1/index.php/demo/send_deletejob/"+deleteJob;
                           if (window.XMLHttpRequest) {
                                xmlReq = new XMLHttpRequest();
                            } else {
                                xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
                            }
                            xmlReq.onreadystatechange = callBack_DeleteJob;
                            xmlReq.open("GET", deleteJob_url, true);
                            xmlReq.send(null);
    }
    function callBack_DeleteJob(){
        if (xmlReq.readyState == 4) {
                    if (xmlReq.status == 200) {
                        Ext.MessageBox.alert('Status',"ลบข้อมูลงานหมายเลข : " +jobShipment+" แล้ว");
                        Ajax_jobList();
                    }
        }
    }   
    //----------------------------MoveBox--------------------------------//
    function setMoveShipment(){
            Ext.MessageBox.confirm('Confirm', 'คุณต้องการย้ายใบงานไปยังกล่อง'+numBoxMoveTo+'?', showResultMoveShipment);
    }
    function showResultMoveShipment(btn){
            if(btn=='yes'){
                //manageShipmentPanel.getEl().mask();
                //progressLoad.show();
                move = "3,"+boxShipment+","+jobShipment+","+statusShipment+":1,"+numBoxMoveTo+","+jobShipment+","+originShipment+","+destShipment+","+latoriginShipment+","+lonoriginShipment+",200,"+latdestShipment+","+londestShipment+",200";
                //alert(move);
                var move_url = "http://dev2.dxplace.com/dx1/index.php/demo/send_move/"+move;
                           if (window.XMLHttpRequest) {
                                xmlReq = new XMLHttpRequest();
                            } else {
                                xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
                            }
                            xmlReq.onreadystatechange = callBack_Move;
                            xmlReq.open("GET", move_url, true);
                            xmlReq.send(null);                                
            }else if(btn=='no'){
            }
    }
    function callBack_Move(){
        if (xmlReq.readyState == 4) {
                    if (xmlReq.status == 200) {
                        //progressLoad.hide();
                        //manageShipmentPanel.getEl().unmask(); 
                        Ext.MessageBox.alert('Move Shipment',"ย้ายข้อมูลใบงานแล้ว");
                        //StatusForm.hide();
                        Ajax_jobList();
                    }
        }
    }
    //----------------------------MoveByPlate--------------------------------//
    function setMoveShipmentPlate(){
            Ext.MessageBox.confirm('Confirm', 'คุณต้องการย้ายใบงานไปยังกล่อง'+numBoxMoveTo+'?', showResultMoveShipment);
    }
    function showResultMoveShipmentPlate(btn){
            if(btn=='yes'){
                //manageShipmentPanel.getEl().mask();
                //progressLoad.show();
                move = plateShipment+","+boxShipment+","+jobShipment+","+statusShipment+","+numPlateMoveTo+","+originShipment+","+destShipment;
                //alert(move);
                var move_url = "http://dev2.dxplace.com/dx1/index.php/demo/send_movePlate/"+move;
                           if (window.XMLHttpRequest) {
                                xmlReq = new XMLHttpRequest();
                            } else {
                                xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
                            }
                            xmlReq.onreadystatechange = callBack_MovePlate;
                            xmlReq.open("GET", move_url, true);
                            xmlReq.send(null);                                
            }else if(btn=='no'){
            }
    }
    function callBack_MovePlate(){
        if (xmlReq.readyState == 4) {
                    if (xmlReq.status == 200) {
                        //progressLoad.hide();
                        //manageShipmentPanel.getEl().unmask(); 
                        Ext.MessageBox.alert('Move Shipment by Plate',"ย้ายข้อมูลใบงานแล้ว");
                        //StatusForm.hide();
                        Ajax_jobList();
                    }
        }
    }
    //----------------------------MoveByBox--------------------------------//
    function setMoveShipmentBox(){
            Ext.MessageBox.confirm('Confirm', 'คุณต้องการย้ายใบงานไปยังกล่อง'+numBoxMoveTo+'?', showResultMoveShipmentBox);
    }
    function showResultMoveShipmentBox(btn){
                                                                            
            if(btn=='yes'){
                //progressLoad.show();
                move = plateShipment+","+boxShipment+","+jobShipment+","+statusShipment+","+numBoxMoveTo+","+originShipment+","+destShipment;
                var move_url = "http://dev2.dxplace.com/dx1/index.php/demo/send_moveBox/"+move;
                           if (window.XMLHttpRequest) {
                                xmlReq = new XMLHttpRequest();
                            } else {
                                xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
                            }
                            xmlReq.onreadystatechange = callBack_MoveBox;
                            xmlReq.open("GET", move_url, true);
                            xmlReq.send(null);                                
            }else if(btn=='no'){
            }
    }
    function callBack_MoveBox(){
        if (xmlReq.readyState == 4) {
                    if (xmlReq.status == 200) {
                        //progressLoad.hide();
                        Ext.MessageBox.alert('Move Shipment',"ย้ายข้อมูลใบงานแล้ว");
                        StatusForm.hide();
                        Ajax_jobList();
                    }
        }
    }
    //----------------------------Route--------------------------------//
    function check_route(){
            var timeIn,timeOut;
                for(i=3 ; i<=12 ; i++){
                    if(stateList[0][i]!=""){
                        timeIn = stateList[0][i];
                        break;
                    }
                }
                for(i=12 ; i>=3 ; i--){
                    if(stateList[0][i]!=""){
                        timeOut = stateList[0][i];
                        break;
                    }
                }
                var route_url = "http://dev2.dxplace.com/dx1/index.php/demo/send_checkRoute/"+deviceID+"/"+timeIn+"/"+timeOut;
                var routeMessageTmp = new Array(); 
                $.getJSON(route_url,function(p){ 
                    for(i=0;i<p.routeMessage.length;i++){                                         
                         var temp_routeMessage = new Array();  
                                temp_routeMessage[0] = p.routeMessage[i].LatRoute;
                                temp_routeMessage[1] = p.routeMessage[i].LonRoute;
                                //temp_routeMessage[2] = p.routeMessage[i].LogtimeRoute;
                                routeMessageTmp[i] =temp_routeMessage;                
                    }
                    var routeMessage = new Array();
                    routeMessage = routeMessageTmp;
                    setDataRoute(routeMessage,timeIn,timeOut);
                });
    }
    function setDataRoute(routeMessage,timeIn,timeOut){ 
        myRoute = routeMessage;
        var myAddress_Route = [];
        countRoute = 0 ; 
        
        if(polyline!=null){ 
            map.removeOverlay(polyline);  
        }
        if(myRoute.length>1){   
            var pointPoly = [];
            for(i=0 ; i<myRoute.length-1 ; i++){  
                pointPoly[i] = new GLatLng(myRoute[i][0], myRoute[i][1]); 
                countRoute +=1;                  
            }
            polyline = new GPolyline(pointPoly, "red",4,1,polyOptions); 
            map.addOverlay(polyline); 
            
            if(Start_marker){ map.removeOverlay(Start_marker);}
            if(Stop_marker){ map.removeOverlay(Stop_marker);}         
            $('input[name=followCarid]').attr('checked', false); 
            map.setCenter(new GLatLng(myRoute[countRoute][0], myRoute[countRoute][1]),map.getZoom());
            pointA = new GLatLng(myRoute[0][0], myRoute[0][1]);
            pointB = new GLatLng(myRoute[countRoute-1][0], myRoute[countRoute-1][1]);
            
            //----------------------MarkerA-----------------------------//
            Start_marker  = new GMarker(pointA,IconStart);
            map.addOverlay(Start_marker);
            htmlA = '<font size=-1><b>จุดเริ่มต้นของงาน :</b>'+customerJob+'</font>';
            GEvent.addListener(Start_marker, "click", function() {
                zoom = map.getZoom();
                if(zoom<=10){
                    zoom=15;    
                }else{
                    zoom = map.getZoom();
                }
                map.setCenter(pointA, zoom);      
                map.openInfoWindowHtml(map.getCenter(),htmlA);  
            });
            //----------------------MarkerB-----------------------------//
            if(timeOut!=''){
                htmlB = '<font size=-1><b>จุดสิ้นสุดของงาน :</b>'+customerJob+'</font>'; 
                Stop_marker  = new GMarker(pointB,IconStop);
                map.addOverlay(Stop_marker);
                GEvent.addListener(Stop_marker, "click", function() {
                    zoom = map.getZoom();
                    if(zoom<=10){
                        zoom=15;    
                    }else{
                        zoom = map.getZoom();
                    }
                    map.setCenter(pointB, zoom); 
                    map.openInfoWindowHtml(map.getCenter(),htmlB);  
                }); 
            }
        }else{
            Ext.MessageBox.alert("Route","ไม่พบเส้นทางที่ถูกต้อง");
        }
    }
    function onGRouteLoad(){ 
        var distanceRoute = groute.getDistance().meters;   
        disRoute[countRoute]= distanceRoute;
        countRoute +=1;       
    }
    function setRoute(fromAddress, toAddress, locale) { 
        groute.load("from: " + fromAddress + " to: " + toAddress,{locale: 'th',getSteps:true});  
        //alert(groute.getDistance().meters);
     }
    function animateCar(){
        if(myRoute.length>1){      
            for(i=1 ; i<=myRoute.length ; i++){
                map.setCenter(new GLatLng(myRoute[i-1][0], myRoute[i-1][1]),map.getZoom());
                window.setTimeout(function() {
                     map.panTo(new GLatLng(myRoute[i][0], myRoute[i][1]));
                }, 5000);
            }
        }
    }  
    //--------------------------Urlencode----------------------//
    function urlencode( str ) {
        var histogram = {}, tmp_arr = [];
        var ret = str.toString();                
        var replacer = function(search, replace, str) {
            var tmp_arr = [];
            tmp_arr = str.split(search);
            return tmp_arr.join(replace);
        };
        histogram["'"]   = '%27';
        histogram['(']   = '%28';
        histogram[')']   = '%29';
        histogram['*']   = '%2A';
        histogram['~']   = '%7E';
        histogram['!']   = '%21';
        histogram['%20'] = '+';
        
        ret = encodeURIComponent(ret);
        for (search in histogram) {
            replace = histogram[search];
            ret = replacer(search, replace, ret) // Custom replace. No regexing
        }
        return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
            return "%"+m2.toUpperCase();
        });
        return ret;
    }
    function urldecode( str ) {
            var histogram = {};
            var ret = str.toString();
            var replacer = function(search, replace, str) {
                var tmp_arr = [];
                tmp_arr = str.split(search);
                return tmp_arr.join(replace);
            };
            histogram["'"]   = '%27';
            histogram['(']   = '%28';
            histogram[')']   = '%29';
            histogram['*']   = '%2A';
            histogram['~']   = '%7E';
            histogram['!']   = '%21';
            histogram['%20'] = '+';
         
            for (replace in histogram) {
                search = histogram[replace]; // Switch order when decoding
                ret = replacer(search, replace, ret) // Custom replace. No regexing   
            }
            ret = decodeURIComponent(ret);
         
            return ret;
}
    //----------------------- MenuMap-------------------//
    function select(buttonId) {
      document.getElementById("hand_b").className="unselected";
      document.getElementById("shape_b").className="unselected";
      document.getElementById("line_b").className="unselected";
      document.getElementById("placemark_b").className="unselected";
      document.getElementById(buttonId).className="selected";
    }
    function stopEditing() {
      select("hand_b");
    }

    function getColor(named) {
      return COLORS[(colorIndex_++) % COLORS.length][named ? 0 : 1];
    }
    function getIcon(color) {
      var icon = new GIcon();
      icon.image = "http://google.com/mapfiles/ms/micons/" + color + ".png";
      icon.iconSize = new GSize(32, 32);
      icon.iconAnchor = new GPoint(15, 32);
      return icon;
    }
    function startShape() {
      select("shape_b");
      Ext.MessageBox.alert('Alert',"ยังไม่สามารถใช้งานส่วนนี้ได้"); 
      /*var color = getColor(false);
      var polygon = new GPolygon([], color, 2, 0.7, color, 0.2);
      startDrawing(polygon, "Shape " + (++shapeCounter_), function() {
        var cell = this;
        var area = polygon.getArea();
        cell.innerHTML = (Math.round(area / 10000) / 100) + "km<sup>2</sup>";
        //alert((Math.round(area / 10000) / 100) + "km<sup>2</sup>");
      }, color);            */
    }

    function startLine() {
      select("line_b");
      Ext.MessageBox.alert('Alert',"ยังไม่สามารถใช้งานส่วนนี้ได้");     
      /*var color = getColor(false);
      var line = new GPolyline([], color);
      startDrawing(line, "Line " + (++lineCounter_), function() {
        var cell = this;
        var len = line.getLength();
        cell.innerHTML = (Math.round(len / 10) / 100) + "km";
      }, color);         */
    }

    function addFeatureEntry(name, color) {
        //alert(name+","+color);
      currentRow_ = document.createElement("tr");
      var colorCell = document.createElement("td");
      currentRow_.appendChild(colorCell);
      colorCell.style.backgroundColor = color;
      colorCell.style.width = "1em";
      var nameCell = document.createElement("td");
      currentRow_.appendChild(nameCell);
      nameCell.innerHTML = name;
      var descriptionCell = document.createElement("td");
      currentRow_.appendChild(descriptionCell);
      featureTable_.appendChild(currentRow_);
      return {desc: descriptionCell, color: colorCell};
    }

    function startDrawing(poly, name, onUpdate, color) {
      map.addOverlay(poly);
      poly.enableDrawing(options);
      poly.enableEditing({onEvent: "mouseover"});
      poly.disableEditing({onEvent: "mouseout"});
      GEvent.addListener(poly, "endline", function() {
        select("hand_b");
        var cells = addFeatureEntry(name, color);
        GEvent.bind(poly, "lineupdated", cells.desc, onUpdate);
        GEvent.addListener(poly, "click", function(latlng, index) {
          if (typeof index == "number") {
            poly.deleteVertex(index);
          } else {
            var newColor = getColor(false);
            cells.color.style.backgroundColor = newColor
            poly.setStrokeStyle({color: newColor, weight: 4});
          }
        });
      });
    }

    function placeMarker() {
      select("placemark_b");    
      var listener = GEvent.addListener(map, "click", function(overlay, point) {
            if (point && countPlaceMarker==0) {
                    singleClick = !singleClick; 
                    $('#followCarid').attr('checked', false); 
                    setTimeout("if (singleClick) createCircle(new GLatLng("+ point.y + ", " + point.x +"), 200);", 300);
                    countPlaceMarker++;
                    select("hand_b");
                    GEvent.removeListener(listener);
            }    
      });   

    }

    function updateMarker(marker, cells, opt_changeColor) {
      if (opt_changeColor) {
        var color = getColor(true);
        marker.setImage(getIcon(color).image);
        cells.color.style.backgroundColor = color;
      }
      var latlng = marker.getPoint();
      cells.desc.innerHTML = "(" + Math.round(latlng.y * 100) / 100 + ", " +Math.round(latlng.x * 100) / 100 + ")";
    }
    //------------------------------------------------LocalSearch------------------------------------//
      var metric = false;
      var singleClick = false;
      var queryCenterOptions = new Object();
      var queryLineOptions = new Object();

        queryCenterOptions.icon = new GIcon();
        queryCenterOptions.icon.image = "http://dev2.dxplace.com/dx1/images/iconPlace.png";
        queryCenterOptions.icon.iconSize = new GSize(32,32);
        queryCenterOptions.icon.shadowSize = new GSize(20, 20);
        queryCenterOptions.icon.iconAnchor = new GPoint(20, 32); 
        queryCenterOptions.draggable = true;
        queryCenterOptions.bouncy = false;

        queryLineOptions.icon = new GIcon();
        queryLineOptions.icon.image = "http://jfno.net/images/resizeArrow.png";
        queryLineOptions.icon.iconSize = new GSize(25,20);
        queryLineOptions.icon.shadowSize = new GSize(0, 0);
        queryLineOptions.icon.iconAnchor = new GPoint(12, 10);
        queryLineOptions.draggable = true;
        queryLineOptions.bouncy = false;

    function createCircle(point, radius) {
      singleClick = false;
      geoQuery = new GeoQuery();
      geoQuery.initializeCircle(radius, point, map);
      myQueryControl.addGeoQuery(geoQuery);
      geoQuery.render();
    }

    function destination(orig, hdng, dist) {
      var R = 6371; // earth's mean radius in km
      var oX, oY;
      var x, y;
      var d = dist/R;  // d = angular distance covered on earth's surface
      hdng = hdng * Math.PI / 180; // degrees to radians
      oX = orig.x * Math.PI / 180;
      oY = orig.y * Math.PI / 180;

      y = Math.asin( Math.sin(oY)*Math.cos(d) + Math.cos(oY)*Math.sin(d)*Math.cos(hdng) );
      x = oX + Math.atan2(Math.sin(hdng)*Math.sin(d)*Math.cos(oY), Math.cos(d)-Math.sin(oY)*Math.sin(y));

      y = y * 180 / Math.PI;
      x = x * 180 / Math.PI;
      return new GLatLng(y, x);
    }
    function distance(point1, point2) {
      var R = 6371; // earth's mean radius in km
      var lon1 = point1.lng()* Math.PI / 180;
      var lat1 = point1.lat() * Math.PI / 180;
      var lon2 = point2.lng() * Math.PI / 180;
      var lat2 = point2.lat() * Math.PI / 180;

      var deltaLat = lat1 - lat2
      var deltaLon = lon1 - lon2

      var step1 = Math.pow(Math.sin(deltaLat/2), 2) + Math.cos(lat2) * Math.cos(lat1) * Math.pow(Math.sin(deltaLon/2), 2);
      var step2 = 2 * Math.atan2(Math.sqrt(step1), Math.sqrt(1 - step1));
      return step2 * R;
    }

    function GeoQuery() {

    }
    GeoQuery.prototype.CIRCLE='circle';
    GeoQuery.prototype.COLORS=["#0000ff", "#00ff00", "#ff0000"];
    var COLORI=0;
    
    GeoQuery.prototype = new GeoQuery();
    GeoQuery.prototype._map;
    GeoQuery.prototype._type;
    GeoQuery.prototype._radius;
    GeoQuery.prototype._dragHandle;
    GeoQuery.prototype._centerHandle;
    GeoQuery.prototype._polyline;
    GeoQuery.prototype._color ;
    GeoQuery.prototype._control;
    GeoQuery.prototype._points;
    GeoQuery.prototype._dragHandlePosition;
    GeoQuery.prototype._centerHandlePosition;


    GeoQuery.prototype.initializeCircle = function(radius, point, map) {
        this._type = this.CIRCLE;
        this._radius = radius;    
        this._map = map;
        this._dragHandlePosition = destination(point, 90, this._radius/1000);
        this._dragHandle = new GMarker(this._dragHandlePosition, queryLineOptions);
        this._centerHandlePosition = point;
        this._centerHandle = new GMarker(this._centerHandlePosition, queryCenterOptions);
        this._color = this.COLORS[COLORI++ % 3];
        map.addOverlay(this._dragHandle);
        map.addOverlay(this._centerHandle);
        
        this._color = getColor(true);    
        /*this._marker = new GMarker(this._centerHandlePosition, {icon: IconPlace, draggable: true});
        map.addOverlay(this._marker);    */   
        var myObject = this;
        GEvent.addListener (this._dragHandle, "dragend", function() {
            myObject.updateCircle(1,point); 
        });
        GEvent.addListener (this._dragHandle, "drag", function() {
            myObject.updateCircle(1,point);                             
        });
        GEvent.addListener(this._centerHandle, "dragend", function() {
            myObject.updateCircle(2,point);
        });
        GEvent.addListener(this._centerHandle, "drag", function() {
            myObject.updateCircle(2,point);
        });  
        map.setCenter(new GLatLng(point.y , point.x ), 15);   
        //alert(this._control.getIndex(this)); 
        htmlAddPlace = '<table><tr><td><font size=-1>ชื่อ          :</td><td><input type=text  id=namePlaceNewid> </td> </font> </tr>'
                        //+'<tr><td><font size=-1>ข้อความ  </font></td><td><textarea row=3  id=textPlaceNewid></textarea></td></tr>'
                        +'<tr><td><font size=-1>ละติจูด     : </td><td><input type=text value='+point.y+'  id=latPlaceNewid></td> </font> </tr>'
                        +'<tr><td><font size=-1>ลองติจูด   : </td><td><input type=text  value='+point.x+' id=lonPlaceNewid></td> </font> </tr>'
                        +'<tr><td><font size=-1>รัศมี        :  </td><td><input type=text value='+radiusPlace+'  id=radiusPlaceNewid></td> </font> </tr>'
                        +'<tr><td></td><td align=right><input type=submit onclick="setSavePoint('+point.y+','+point.x+','+this._radius+');myQueryControl.remove(0);" value=เพิ่มสถานที่ ><input type=submit onclick="myQueryControl.remove(0);" value=ยกเลิก ></td> </font> </tr></table>';
        map.openInfoWindowHtml(this._centerHandle.getPoint(), htmlAddPlace);  
          
    }
    GeoQuery.prototype.updateCircle = function (type,point) {
        this._map.removeOverlay(this._polyline);
        if (type==1) {
          this._dragHandlePosition = this._dragHandle.getPoint();
          this._radius = distance(this._centerHandlePosition, this._dragHandlePosition) * 1000;
          this.render();
          map.setCenter(this._centerHandlePosition);  
        } else {
          this._centerHandlePosition = this._centerHandle.getPoint();
          this.render();
          this._dragHandle.setPoint(this.getEast());
          map.setCenter(this._centerHandle.getPoint());  
        }
        pointUpdate = this._centerHandle.getPoint();
        htmlAddPlace = '<table><tr><td><font size=-1>ชื่อ          : </font> </td><td><input type=text  id=namePlaceNewid></td></tr>'
                        +'<tr><td><font size=-1>ละติจูด     : </font></td><td><input type=text value='+pointUpdate.y+'  id=latPlaceNewid></td></tr>'
                        +'<tr><td><font size=-1>ลองติจูด   : </font></td><td><input type=text  value='+pointUpdate.x+' id=lonPlaceNewid></td></tr>'
                        +'<tr><td><font size=-1>รัศมี        :  </font></td><td><input type=text value='+this._radius+'  id=radiusPlaceNewid></td></tr>'
                        +'<tr><td></td><td align=right><input type=submit onclick="setSavePoint('+pointUpdate.y+','+pointUpdate.x+','+this._radius+');myQueryControl.remove(' + this._control.getIndex(this) + ');" value=เพิ่มสถานที่ ><input type=submit onclick="myQueryControl.remove(' + this._control.getIndex(this) + ');" value=ยกเลิก ></td></tr></table>';
        map.openInfoWindowHtml(this._centerHandle.getPoint(), htmlAddPlace);
    }
    GeoQuery.prototype.render = function() {
      if (this._type == this.CIRCLE) {
        this._points = [];
        var distance = this._radius/1000;
        for (i = 0; i < 72; i++) {
          this._points.push(destination(this._centerHandlePosition, i * 360/72, distance) );
        }
        this._points.push(destination(this._centerHandlePosition, 0, distance) );
        //this._polyline = new GPolyline(this._points, this._color, 6);
        this._polyline = new GPolygon(this._points, this._color, 2, 1, this._color, 0.2);
        this._map.addOverlay(this._polyline)
        this._control.render();
      }
    }
    GeoQuery.prototype.remove = function() {
      this._map.removeOverlay(this._polyline);
      this._map.removeOverlay(this._dragHandle);
      this._map.removeOverlay(this._centerHandle);
    }

    GeoQuery.prototype.getRadius = function() {
        return this._radius;
        //alert(this._radius);
    }
    GeoQuery.prototype.getHTML = function() {
      //return "<span><font color='"+ this._color + "''>" + this.getDistHtml() + "</font></span>";   
      return "";  
    }
    GeoQuery.prototype.getDistHtml = function() {
      result = "<img src='http://jfno.net/images/close.gif' onClick='myQueryControl.remove(" + this._control.getIndex(this) + ");'/>Radius ";
      if (metric) {
        if (this._radius < 1000) {
          result += "in meters : " + this._radius.toFixed(1);
        } else {
          result += "in kilometers : " + (this._radius / 1000).toFixed(1);
        }
      } else {
        var radius = this._radius * 3.2808399;
        if (radius < 5280) {
          result += "in feet : " + radius.toFixed(1);
        } else {
          result += "in miles : " + (radius / 5280).toFixed(1);
        }
      }
      return result; 
    }

    GeoQuery.prototype.getNorth = function() {
      return this._points[0];
    }
    GeoQuery.prototype.getSouth = function() {
      return this._points[(72/2)];
    }
    GeoQuery.prototype.getEast = function() {
      return this._points[(72/4)];
    }
    GeoQuery.prototype.getWest = function() {
      return this._points[(72/4*3)];
    }
    function QueryControl (localSearch) {
      this._localSearch = localSearch;
    }
    QueryControl.prototype = new GControl();
    QueryControl.prototype._geoQueries ;
    QueryControl.prototype._mainDiv;
    QueryControl.prototype._queriesDiv;
    QueryControl.prototype._minStar;
    QueryControl.prototype._minPrice;
    QueryControl.prototype._maxPrice;
    QueryControl.prototype._timeout;
    QueryControl.prototype._localSearch;
    var titleDiv;
    QueryControl.prototype.initialize = function(map) {
      this._mainDiv = document.createElement("div");
      this._mainDiv.id = "GQueryControl";
      titleDiv = document.createElement("div");
      titleDiv.id = "GQueryControlTitle";
      titleDiv.appendChild(document.createTextNode(""));
      this._mainDiv.appendChild(titleDiv);
      this._queriesDiv = document.createElement("div");
      this._queriesDiv.id = "queriesDiv";
      this._mainDiv.appendChild(this._queriesDiv);

      map.getContainer().appendChild(this._mainDiv);
      this._geoQueries = new Array();
      return this._mainDiv;
    }

    QueryControl.prototype.getDefaultPosition = function() {
      return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(50, 10));
    }

    QueryControl.prototype.addGeoQuery = function(geoQuery) {
      this._geoQueries.push(geoQuery);
      geoQuery._control = this;
      newDiv = document.createElement("div");
      newDiv.innerHTML = geoQuery.getHTML();
      this._queriesDiv.appendChild(newDiv);
     
    }

    QueryControl.prototype.render = function() {
      for (i = 0; i < this._geoQueries.length; i++) {
        geoQuery = this._geoQueries[i];
        this._queriesDiv.childNodes[i].innerHTML = geoQuery.getHTML();
      }
      if (this._timeout == null) {
        this._timeout = setTimeout(myQueryControl.query, 1000);
      } else {
        clearTimeout(this._timeout);
        this._timeout = setTimeout(myQueryControl.query, 1000);
      }
    }

    QueryControl.prototype.query = function() {
      listMarkers = myQueryControl._localSearch.markers.slice();
      for (i = 0; i < listMarkers.length; i++) {
        marker = listMarkers[i].marker;
        result = listMarkers[i].resultsListItem;
        listImage = marker.getIcon().image;
        inCircle = true;
        for (j = 0; j < myQueryControl._geoQueries.length; j++) {
          geoQuery = myQueryControl._geoQueries[j];
          dist = distance(marker.getLatLng(), geoQuery._centerHandlePosition); 
          if (dist > geoQuery._radius / 1000) {
            inCircle = false;
            break;
          }
        }
        if (inCircle) {
          marker.setImage(listImage);
          result.childNodes[1].style.color = '#0000cc';
        } else {
          var re = new RegExp(".*(marker.\.png)");
          marker.setImage(listImage.replace(re, "img/$1"));
          result.childNodes[1].style.color = '#b0b0cc';
        }
      }
    }
    QueryControl.prototype.remove = function(index) {
      this._geoQueries[index].remove();
      this._queriesDiv.removeChild(this._queriesDiv.childNodes[index]);
      delete this._geoQueries[index];
      this._geoQueries.splice(index,1);
      this.render();
      map.closeInfoWindow(); 
      countPlaceMarker=0;
    }
    QueryControl.prototype.getIndex = function(geoQuery) {
      for (i = 0; i < this._geoQueries.length; i++) {
        if (geoQuery == this._geoQueries[i]) {
          return i;
        }
      }
      return -1;
    }
   
    //-------------------------------ToSave-----------------//
    function MDControl() { }
     MDControl.prototype = new GControl();
     MDControl.prototype.initialize = function(map) {
     var container = document.createElement("div");
     map.getContainer().appendChild(container);
     return container;
    }

    MDControl.prototype.getDefaultPosition = function() {
     return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7,31));
    }
    //--------------------------------Map---------------------------//
    var highlightCircle;
    var currentMarker;

    function highlightCurrentMarker(currentMarker,i){
        if(currentMarker=='undefined'){
                alert('NoHightlight');
        }else{
              var markerPoint = currentMarker.getPoint();

              var polyPoints = Array();

              if (highlightCircle) {
                map.removeOverlay(highlightCircle);
              }

              var mapNormalProj = G_NORMAL_MAP.getProjection();
              var mapZoom = map.getZoom();
              var clickedPixel = mapNormalProj.fromLatLngToPixel(markerPoint, mapZoom);

              var polySmallRadius = 20;

              var polyNumSides = 20;
              var polySideLength = 18;

              for (var a = 0; a<(polyNumSides+1); a++) {
                var aRad = polySideLength*a*(Math.PI/180);
                var polyRadius = myDataPoint[i][8]; 
                var pixelX = clickedPixel.x + polyRadius * Math.cos(aRad);
                var pixelY = clickedPixel.y + polyRadius * Math.sin(aRad);
                var polyPixel = new GPoint(pixelX,pixelY);
                var polyPoint = mapNormalProj.fromPixelToLatLng(polyPixel,mapZoom);
                polyPoints.push(polyPoint);
              }
              
              highlightCircle = new GPolygon(polyPoints,"#000000",2,0.0,"#FF0000",.5);
              map.addOverlay(highlightCircle);
        }
   }


   

         
  

    
    
