var main_map = null;

var crunchedLayerManager = null;

var myLayers=new Array(); 

var m_iCustomerID=2;
var m_sSelectedUnits = "g|1";
var iCurrentMarkerID = -1;

var apiSensor;

var xmlUnitsDoc;
var xmlUnitStatus;

var xmlSearchDocXML;
var xmlSearchDoc;

var gms_uniqueid;
var xmlPlanDoc;
var xmlSensorDoc;

var xmlGeoSearch;
var xmlHistoryDoc;
  
var m_sData = new Array;
var m_Accounts = new Array();
var m_AccountUnits = new Array();
var m_AccountUnitsGeo = new Array();
var m_Group = new Array();
var m_GroupUnit = new Array();

var aPinMarker = new Array();
var aPinMarkerDir = new Array();
var aPinMarkerBCT = new Array();
var aPinMarkerGF = new Array();

var aPinMarkerClone = new Array();

var amarker = new Array();
var amarkerDir = new Array();
var amarkerHTML = new Array();
var amarkerListener = new Array();

var markerHistory = new Array();

var winTracking;


function SaveAll()
{
    Ext.Msg.alert('<div class=\'pointat-messagebox\'></div>', 'Save All Settings');

}

function showExit()
{
    Ext.Msg.OK.ok = false;
    Ext.Msg.alert('<div class=\'pointat-messagebox\'></div>', 'You have now been successfully logged out of PointAT');

    setTimeout('redirectURL(\'http://www.point-at.net/\')', 1000);

}

function redirectURL(e){
    window.location.href = e;
}

function ShowHelp(e){
        var tabs = new Ext.TabPanel({
            region: 'center',
            margins:'3 3 3 0', 
            activeTab: 0,
            defaults:{autoScroll:true},

            items:[{
                title: 'Details',
                html: ''
            },{
                title: 'FAQs',
                html: ''
            },
            {
                title: 'Media Gallery',
                html: ''
            },
            {
                title: 'Contact Support',
                html: ''
            }
            ]
        });

        // Panel for the west
        var nav = new Ext.Panel({
            title: 'Topics',
            region: 'west',
            split: true,
            width: 200,
            collapsible: true,
            margins:'3 0 3 3',
            cmargins:'3 3 3 3'
        });

        var winHelp = new Ext.Window({
            title: 'PointAT Online Help',
            closable:true,
            width:600,
            height:350,
            //border:false,
            plain:true,
            layout: 'border',

            items: [nav, tabs]
        });

        winHelp.show(e);


}

function onMapLoad(e)
{
    document.getElementById('loadingPanel').style.width = main_map.GetWidth();
    document.getElementById('loadingPanel').style.height = main_map.GetHeight();
    document.getElementById('loadingPanel').style.top = main_map.GetTop()+2;
    document.getElementById('loadingPanel').style.left = main_map.GetLeft()+2;
    document.getElementById('loadingPanel').style.display = "";
    
}

function onMapChangeView()
 {
    Ext.getCmp('map_be_view').setDisabled(!main_map.IsBirdseyeAvailable());
    mapChangeView(main_map);
 }

function getMapStyleLabel(ms_style, mb_labels)
{
    switch (ms_style)
    {
         case 's':
            if (mb_labels){return 's';}else{return 'r';}
            break;
        case 'r':
            if (mb_labels){return 's';}else{return 'r';}
            break;
        case 'h':
            if (mb_labels){return 'h';}else{return 'a';}
            break;
        case 'a':
            if (mb_labels){return 'h';}else{return 'a';}
            break;
         case 'b':
            if (mb_labels){return 'b';}else{return 'o';}
            break;
        case 'o':
            if (mb_labels){return 'b';}else{return 'o';}
            break;
    
    }

}

function isMapLabelsVisible(e)
{
    switch (e.GetMapStyle())
    {
         case 's':
            return true;
            break;
        case 'r':
            return true;
            break;
        case 'h':
            return true;
            break;
        case 'a':
            return false;
            break;
         case 'b':
            return true;
            break;
        case 'o':
            return false;
            break;
    
    }

}

function mapChangeView(e){

    mb_map_change_in_progress = true;
    
    switch (e.GetMapStyle())
    {
         case 's':
            Ext.getCmp('map_labels').setDisabled(true);
            Ext.getCmp('map_labels').setChecked(true);
            if (!Ext.getCmp('map_road_view').checked){Ext.getCmp('map_road_view').setChecked(true);}
            break;
        case 'r':
            Ext.getCmp('map_labels').setDisabled(true);
            Ext.getCmp('map_labels').setChecked(true);
            if (!Ext.getCmp('map_road_view').checked){Ext.getCmp('map_road_view').setChecked(true);}
            break;
        case 'h':
            Ext.getCmp('map_labels').setDisabled(false);
            Ext.getCmp('map_labels').setChecked(true);
            if (!Ext.getCmp('map_aerial_view').checked){Ext.getCmp('map_aerial_view').setChecked(true);}
            break;
        case 'a':
            Ext.getCmp('map_labels').setDisabled(false);
            Ext.getCmp('map_labels').setChecked(false);
            if (!Ext.getCmp('map_aerial_view').checked){Ext.getCmp('map_aerial_view').setChecked(true);}
            break;
         case 'b':
            Ext.getCmp('map_labels').setDisabled(false);
            Ext.getCmp('map_labels').setChecked(true);
            if (!Ext.getCmp('map_be_view').checked){Ext.getCmp('map_be_view').setChecked(true);}
            break;
        case 'o':
            Ext.getCmp('map_labels').setDisabled(false);
            Ext.getCmp('map_labels').setChecked(false);
            if (!Ext.getCmp('map_be_view').checked){Ext.getCmp('map_be_view').setChecked(true);}
            break;
    
    }
    
    mb_map_change_in_progress = false;

}

function playBCT(bool_play)
{
   if ( (HistoryGrid.getSelectionModel().last + 1 )< HistoryGrid.getStore().pageSize){
        HistoryGrid.getSelectionModel().selectNext();
    }
    else
    {   
        clearInterval(mi_bct_timer_id);
        Ext.getCmp('playBCT').setDisabled(false);
        Ext.getCmp('pauseBCT').setDisabled(true);
        Ext.getCmp('stopBCT').setDisabled(true);
        Ext.Msg.alert('<div class=\'pointat-messagebox\'></div>', 'End of Page');
    }
}

function stopBCT(){
    clearInterval(mi_bct_timer_id);
    HistoryGrid.getSelectionModel().selectFirstRow();
    ClearBCT();
    Ext.getCmp('playBCT').setDisabled(false);
    Ext.getCmp('pauseBCT').setDisabled(true);
    Ext.getCmp('stopBCT').setDisabled(true);
}

function pauseBCT(){
    clearInterval(mi_bct_timer_id);
    Ext.getCmp('playBCT').setDisabled(false);
    Ext.getCmp('pauseBCT').setDisabled(true);
    Ext.getCmp('stopBCT').setDisabled(true);
}

var mi_bct_timer_id;

function PlayBCT()
{
    var w = Ext.getCmp('west-panel');
    w.expand();
    
    HistoryGrid.expand();
    
    if (!HistoryGrid.getSelectionModel().last){
        HistoryGrid.getSelectionModel().selectRow(0, false, false);
    }
    
    mi_bct_timer_id = setInterval("playBCT()", 1000);
    
    Ext.getCmp('playBCT').setDisabled(true);
    Ext.getCmp('pauseBCT').setDisabled(false);
    Ext.getCmp('stopBCT').setDisabled(false);
    

}

function ClearBCT()
{
    for (mi_idx=0;mi_idx<markerHistory.length;mi_idx++){
        var obj_mh = markerHistory.pop();
        if (obj_mh != undefined)
        {
            main_map.DeleteShape(obj_mh);
        }
    }
}



function showHistoryGPS(recGPS){

   
    if (!Ext.getCmp('toogleBCT').checked)
    {
        ClearBCT();
    }
    
    var vepoint = new VELatLong(parseFloat(recGPS.data.loclatlong.split(',')[0]), parseFloat(recGPS.data.loclatlong.split(',')[1]));
    
    markerHistory[recGPS.id] = new VEShape(VEShapeType.Pushpin, vepoint);
	markerHistory[recGPS.id].SetCustomIcon("<div class='mapicon " + recGPS.data.type + "-map' onclick=_showUnitHistory(this," + recGPS.id + ");></div>");
	markerHistory[recGPS.id].SetTitle(null);
	markerHistory[recGPS.id].SetDescription(null);
	markerHistory[recGPS.id].IconID = recGPS.id;

	main_map.AddShape(markerHistory[recGPS.id]); 
	
	main_map.SetCenterAndZoom(markerHistory[recGPS.id].GetPoints()[0],16);
}

function _showUnitHistory(obj, recGPS)
{

}

function showUnit(unitID){
    try{setUnitItem(unitID + '|');}catch(e){}
    setProperties('Unit', unitID);

}

function showTrackingInfo(){
    if(!winTracking){
        winTracking = new Ext.Window({
            applyTo:'hello-win',
            layout:'fit',
            width:500,
            height:300,
            closeAction:'hide',
            plain: true,

            items: new Ext.TabPanel({
                applyTo: 'hello-tabs',
                autoTabs:true,
                activeTab:0,
                deferredRender:false,
                border:false
            }),

            buttons: [{
                text:'Submit',
                disabled:true
            },{
                text: 'Close',
                handler: function(){
                    winTracking.hide();
                }
            }]
        });
    }
    winTracking.show(this);

}
		
function setProperties(ms_type,mi_id){
    
     var  menu_sensor_edit = Ext.getCmp('menu-sensor-edit');
     
    if (gms_uniqueid != undefined && !menu_sensor_edit.disabled){
        if (pinLayer[gms_uniqueid].GetVisibility()){pinLayer[ms_uniqueid].Hide();menu_sensor_edit.setChecked(!menu_sensor_edit.checked);gms_uniqueid=undefined;}
    }
   
    var  menu_sensor_point_add = Ext.getCmp('menu-sensor-point-add');
    var  menu_sensor_point_remove = Ext.getCmp('menu-sensor-point-remove');
    
    menu_sensor_edit.disable();
    menu_sensor_point_add.disable();
    menu_sensor_point_remove.disable();
    
    
    switch(ms_type)
    {
        case "Group":
            
//            m_node = xmlUnitsDoc.selectNodes('//units/unit[@id=\'' + mi_id.toString() + '\']');
		
//		    if (m_node.length == 1){
		        
		        ms_id = "1"; //_checkNode(m_node[0].getElementsByTagName('id').item(0).firstChild);
		        ms_name = "Example Group"; //_checkNode(m_node[0].getElementsByTagName('name').item(0).firstChild);
		        ms_type = "normal-folder";
    		    ms_notes = "Example Groups"; //_checkNode(m_node[0].getElementsByTagName('notes').item(0).firstChild);
    		    
                mo_property_grid.setSource({
                        "(type)": "Group",
                        "(id)": ms_id,
                        "Name": ms_name,
                        "Icon Cls": ms_type
                    });
                    
               document.getElementById('setting-note').innerHTML = ms_notes;
//            }
            break;
            
        case "Sensor":
            
            m_sensor_node = xmlSensorDoc.selectNodes('//sensors/sensor[@uniqueid=' + mi_id.toString() + ']');
		
		    if (m_sensor_node.length == 1){
		        ms_uniqueid = m_sensor_node[0].getAttribute("uniqueid");
        		
		        ms_id = _checkNode(m_sensor_node[0].getElementsByTagName('id').item(0).firstChild);
		        ms_name = _checkNode(m_sensor_node[0].getElementsByTagName('name').item(0).firstChild);
    		    ms_location = _checkNode(m_sensor_node[0].getElementsByTagName('location').item(0).firstChild);
    		    ms_plan = _checkNode(m_sensor_node[0].getElementsByTagName('plan').item(0).firstChild);
    		    ms_lat = _checkNode(m_sensor_node[0].getElementsByTagName('lat').item(0).firstChild);
    		    ms_long = _checkNode(m_sensor_node[0].getElementsByTagName('long').item(0).firstChild);
    		    ms_alt = _checkNode(m_sensor_node[0].getElementsByTagName('alt').item(0).firstChild);
    		    ms_coords = _checkNode(m_sensor_node[0].getElementsByTagName('coords').item(0).firstChild);
    		    ms_tagstyle = _checkNode(m_sensor_node[0].getElementsByTagName('tagstyle').item(0).firstChild);
    		    ms_offbackcolor = _checkNode(m_sensor_node[0].getElementsByTagName('offbackcolor').item(0).firstChild);
    		    ms_onbackcolor = _checkNode(m_sensor_node[0].getElementsByTagName('onbackcolor').item(0).firstChild);
    		    ms_opacity = _checkNode(m_sensor_node[0].getElementsByTagName('opacity').item(0).firstChild);
    		    ms_notes = _checkNode(m_sensor_node[0].getElementsByTagName('notes').item(0).firstChild);
    		    
                mo_property_grid.setSource({
                        "(type)": "Sensor",
                        "(uid)": ms_uniqueid,
                        "(id)": ms_id,
                        "Name": ms_name,
                        "Location": ms_location,
                        "Plan": ms_plan,
                        "Latitude [center]": ms_lat,
                        "Longitude [center]": ms_long,
                        "Altitude": ms_alt,
                        "Boundary": ms_coords,
                        "Line color": ms_offbackcolor,
                        "Fill color": ms_onbackcolor,
                        "Opacity": ms_opacity,
                        "Icon Cls": ms_tagstyle
                    });
                    
                document.getElementById('setting-note').innerHTML = ms_notes;
               
                gms_uniqueid = mi_id;
                menu_sensor_edit.enable();
                menu_sensor_point_add.enable();
                menu_sensor_point_remove.enable();
               
               
            }
            break;
            
            
        case "Layer":
            
            m_node = xmlPlanDoc.selectNodes('//plans/plan[@planid=\'' + mi_id.toString() + '\']');
		
		    if (m_node.length == 1){
		        ms_uniqueid = m_node[0].getAttribute("uniqueid");
        		
		        ms_id = _checkNode(m_node[0].getElementsByTagName('id').item(0).firstChild);
		        ms_name = _checkNode(m_node[0].getElementsByTagName('name').item(0).firstChild);
    		    ms_plan = _checkNode(m_node[0].getElementsByTagName('plan').item(0).firstChild);
    		    ms_location = _checkNode(m_node[0].getElementsByTagName('location').item(0).firstChild);
    		    ms_lat = _checkNode(m_node[0].getElementsByTagName('lat').item(0).firstChild);
    		    ms_long = _checkNode(m_node[0].getElementsByTagName('long').item(0).firstChild);
    		    ms_zoom = _checkNode(m_node[0].getElementsByTagName('zoom').item(0).firstChild);
    		    ms_notes = _checkNode(m_node[0].getElementsByTagName('notes').item(0).firstChild);
    		    
                mo_property_grid.setSource({
                        "(type)": "Plan",
                        "(id)": ms_id,
                        "Name": ms_name,
                        "Plan": ms_plan,
                        "Location": ms_location,
                        "Latitude [center]": ms_lat,
                        "Longitude [center]": ms_long,
                        "Default Zoom": ms_zoom
                    });
                    
               document.getElementById('setting-note').innerHTML = ms_notes;
            }
            break;
            
        case "Unit":
            try{
            m_node = xmlUnitsDoc.selectNodes('//units/unit[@id=\'' + mi_id.toString() + '\']');
		
		    if (m_node.length == 1){
		        
		        ms_id = _checkNode(m_node[0].getElementsByTagName('id').item(0).firstChild);
		        ms_name = _checkNode(m_node[0].getElementsByTagName('name').item(0).firstChild);
    		    ms_type = _checkNode(m_node[0].getElementsByTagName('type').item(0).firstChild);
    		    ms_reg = _checkNode(m_node[0].getElementsByTagName('reg').item(0).firstChild);
    		    ms_notes = _checkNode(m_node[0].getElementsByTagName('notes').item(0).firstChild);
    		    
    		    ms_sensordatestamp = _checkNode(m_node[0].getElementsByTagName('sensordatestamp').item(0).firstChild);
    		    ms_utc = _checkNode(m_node[0].getElementsByTagName('utc').item(0).firstChild);
    		    
                mo_property_grid.setSource({
                        "(type)": "Unit",
                        "(id)": ms_id,
                        "Name": ms_name,
                        "Icon Cls": ms_type,
                        "Reg": ms_reg
                    });
                    
               document.getElementById('setting-note').innerHTML = ms_notes;
               
               if (Date.parse(ms_sensordatestamp) > Date.parse(ms_utc))
               {
                    ms_sensorpairs = _checkNode(m_node[0].getElementsByTagName('sensorpairs').item(0).firstChild);

				    mi_max_rss = 0;
				    ms_sensor_tag = '';
				    msa_pairs = ms_sensorpairs.split(',');
				    for (idxP=0;idxP<msa_pairs.length;idxP++){
				        mi_rss = parseInt(msa_pairs[idxP].split('|')[1]);
				        if (mi_rss > mi_max_rss){
				            mi_max_rss = mi_rss;
				            ms_sensor_tag = msa_pairs[idxP].split('|')[0];
				        }
				    }
				    
                    m_sensor_node = xmlSensorDoc.selectNodes('//sensors/sensor[@id=\'' + ms_sensor_tag + '\']');
                    
                    ms_plan = _checkNode(m_sensor_node[0].getElementsByTagName('plan').item(0).firstChild);
                    
                    try{ToggleLayer(ms_plan, true);}catch(e){}
               }
               
               
            }
        }
            
        catch(e){}
        break;            
            
    }

}

function clearLayers()
{
	for (var idx=0;idx<myLayers.length;idx++){
		try{myLayers[idx].Deactivate(main_map);}catch(e){}
		
	}
}

function ToggleLayer(name, active)
{
    if (active == true)
    {
    	clearLayers();
        crunchedLayerManager.layerList.find(name).Activate(main_map);
    }
    else
    {
        crunchedLayerManager.layerList.find(name).Deactivate(main_map);
    }
    
    var mo_floorplans = apiSensor.root.childNodes[0].childNodes[0].childNodes[0].childNodes;
    
    for(mi_idx=0;mi_idx<mo_floorplans.length;mi_idx++){
        mo_floorplans[mi_idx].ui.checkbox.checked = (mo_floorplans[mi_idx].id == 'Layer.' + name) && active;
    }
    
    //apiSensor.root.reload();
    
}

function InitMap(){
    LoadMap();
    refreshPlanXML(true);
    refreshSensorXML(true);
    refreshUnitXML(true);


    setInterval("refreshUnitXML(false)", 10000);
}

var markerSensor = new Array();
var polyline = new Array();
var polylineMask= new Array();
var points = new Array(new Array());
var moving = false;
var currentDragHandle = null;
var pinLayer = new Array();
var pointIndex = null;

var currentSensorUID = null;

function LoadSensors(uniqueid, ms_id, ms_name, ms_plan, ms_lat, ms_long, ms_coords,ms_offbackcolor,ms_onbackcolor,ms_opacity,ms_tagstyle)
{
    var ams_coords = ms_coords.split(';');
    
    points[uniqueid] = [];
    
    for (iX=0;iX<ams_coords.length;iX++){
        points[uniqueid].push(new VELatLong(ams_coords[iX].split(',')[0],ams_coords[iX].split(',')[1]));
    }
	
	AddSensorPoints(uniqueid,ms_offbackcolor,ms_onbackcolor,ms_opacity);
    

}

function AddSensorCenter(uniqueid, ms_name, ms_plan, ms_location, ms_lat, ms_long, ms_alt, ms_notes,ms_offbackcolor){

    markerSensor[uniqueid] = new VEShape(VEShapeType.Pushpin, new VELatLong(ms_lat,ms_long));
    markerSensor[uniqueid].SetCustomIcon("<div class='mapicon " + ms_offbackcolor + "'></div>");
							
    markerSensor[uniqueid].SetTitle(ms_name + ', ' + ms_location);         
    markerSensor[uniqueid].SetDescription('<p>' + ms_notes + '</p>' + '<p><a href=\"javascript:showSensorZoom(' + uniqueid + ',\'' + ms_plan + '\');\">Show Sensor Network</a></p>');
    main_map.AddShape(markerSensor[uniqueid]);


}

function showSensorZoom(uniqueid, planid){
    ToggleLayer(planid, true);
	showSensorZoom(uniqueid);
}

function AddSensorPoints(uniqueid,ms_offbackcolor,ms_onbackcolor,ms_opacity)
{

    ma_line_color = ms_offbackcolor.split(',');
    ma_fill_color = ms_onbackcolor.split(',');
    
    polyline[uniqueid] = new VEShape(VEShapeType.Polygon, points[uniqueid]);
    polyline[uniqueid].HideIcon();
    polyline[uniqueid].SetLineWidth(2);
    polyline[uniqueid].SetLineColor(new VEColor(
        ma_line_color[0],
        ma_line_color[1],
        ma_line_color[2],
        ms_opacity
        ));
    polyline[uniqueid].SetFillColor(new VEColor(
        ma_fill_color[0],
        ma_fill_color[1],
        ma_fill_color[2],
        ms_opacity
        ));
    main_map.AddShape(polyline[uniqueid]);
    
    //Create polygon mask (set visible to false)
    polylineMask[uniqueid] = new VEShape(VEShapeType.Polygon, points[uniqueid]);
    polylineMask[uniqueid].HideIcon();
    polylineMask[uniqueid].Hide();
    polylineMask[uniqueid].SetLineColor(new VEColor(
        ma_line_color[0],
        ma_line_color[1],
        ma_line_color[2],
        ms_opacity
        ));
    polylineMask[uniqueid].SetFillColor(new VEColor(
        ma_fill_color[0],
        ma_fill_color[1],
        ma_fill_color[2],
        0
        ));
    polylineMask[uniqueid].Primitives[0].symbol.stroke_dashstyle = "Dash";
    main_map.AddShape(polylineMask[uniqueid]);
    
    //Add drag handles
    pinLayer[uniqueid] = new VEShapeLayer();
    main_map.AddShapeLayer(pinLayer[uniqueid]);
    for (i = 0; i <= (points[uniqueid].length -1); i++){
        var dragHandle = new VEShape(VEShapeType.Pushpin, points[uniqueid][i]);
        if (i == 0){
            dragHandle.SetCustomIcon('images/DragHandleFirst.gif');
            dragHandle.SetZIndex(dragHandle.GetZIndex() + 1);
        }
        else{dragHandle.SetCustomIcon('images/DragHandle.gif');}
        
        pinLayer[uniqueid].AddShape(dragHandle);
    }
    pinLayer[uniqueid].Hide();

}

function addSensorPoint(uniqueid)
{
    if (uniqueid == undefined){uniqueid = gms_uniqueid;}
    
    if (pinLayer[uniqueid].GetVisibility()){pinLayer[uniqueid].Hide();}
    main_map.DeleteShape(polyline[uniqueid]);
    main_map.DeleteShape(polylineMask[uniqueid]);
    
    var lastPoint = points[uniqueid][0];
    points[uniqueid].push(lastPoint);
    
    polyline[uniqueid] = new VEShape(VEShapeType.Polygon, points[uniqueid]);
    polyline[uniqueid].HideIcon();
    polyline[uniqueid].SetLineWidth(2);
    
    main_map.AddShape(polyline[uniqueid]);
    
    //Create polygon mask (set visible to false)
    polylineMask[uniqueid] = new VEShape(VEShapeType.Polygon, points[uniqueid]);
    polylineMask[uniqueid].HideIcon();
    polylineMask[uniqueid].Hide();
    polylineMask[uniqueid].SetLineColor(new VEColor(0,0,0,0.5));
    polylineMask[uniqueid].SetFillColor(new VEColor(0,0,0,0.0));
    polylineMask[uniqueid].Primitives[0].symbol.stroke_dashstyle = "Dash";
    main_map.AddShape(polylineMask[uniqueid]);
    
    //Add drag handles
    pinLayer[uniqueid] = new VEShapeLayer();
    main_map.AddShapeLayer(pinLayer[uniqueid]);
    for (i = 0; i <= (points[uniqueid].length -1); i++){
        var dragHandle = new VEShape(VEShapeType.Pushpin, points[uniqueid][i]);
        if (i == 0){
            dragHandle.SetCustomIcon('images/DragHandleFirst.gif');
            dragHandle.SetZIndex(dragHandle.GetZIndex() + 1);
        }
        else{dragHandle.SetCustomIcon('images/DragHandle.gif');}
        pinLayer[uniqueid].AddShape(dragHandle);
    }
    pinLayer[uniqueid].Show();
    
}

function removeSensorPoint(uniqueid)
{
    if (uniqueid == undefined){uniqueid = gms_uniqueid;}
    
    if (points[uniqueid].length > 3){
        if (pinLayer[uniqueid].GetVisibility()){pinLayer[uniqueid].Hide();}
        main_map.DeleteShape(polyline[uniqueid]);
        main_map.DeleteShape(polylineMask[uniqueid]);
        
        var lastPoint = points[uniqueid][0];
        points[uniqueid].shift();
        
        polyline[uniqueid] = new VEShape(VEShapeType.Polygon, points[uniqueid]);
        polyline[uniqueid].HideIcon();
        polyline[uniqueid].SetLineWidth(2);
        
        main_map.AddShape(polyline[uniqueid]);
        
        //Create polygon mask (set visible to false)
        polylineMask[uniqueid] = new VEShape(VEShapeType.Polygon, points[uniqueid]);
        polylineMask[uniqueid].HideIcon();
        polylineMask[uniqueid].Hide();
        polylineMask[uniqueid].SetLineColor(new VEColor(0,0,0,0.5));
        polylineMask[uniqueid].SetFillColor(new VEColor(0,0,0,0.0));
        polylineMask[uniqueid].Primitives[0].symbol.stroke_dashstyle = "Dash";
        main_map.AddShape(polylineMask[uniqueid]);
        
        //Add drag handles
        pinLayer[uniqueid] = new VEShapeLayer();
        main_map.AddShapeLayer(pinLayer[uniqueid]);
        for (i = 0; i <= (points[uniqueid].length -1); i++){
            var dragHandle = new VEShape(VEShapeType.Pushpin, points[uniqueid][i]);
            if (i == 0){
                dragHandle.SetCustomIcon('images/DragHandleFirst.gif');
                dragHandle.SetZIndex(dragHandle.GetZIndex() + 1);
            }
            else{dragHandle.SetCustomIcon('images/DragHandle.gif');}
            pinLayer[uniqueid].AddShape(dragHandle);
        }
        pinLayer[uniqueid].Show();
    }
}

function showSensorZoom(uniqueid)
{
    try{
        main_map.SetMapView(polyline[uniqueid].GetPoints());
    }
    catch(e)
    {
        Ext.Msg.alert('<div class=\'pointat-messagebox\'></div>', e.message);
    
    }
}

function getSensorPoint(uniqueid)
{
    if (uniqueid == undefined){uniqueid = gms_uniqueid;}
    ms_Points = "";
    
    for (idx=0;idx<polyline[uniqueid].GetPoints().length;idx++){
        ms_Points += ";" + polyline[uniqueid].GetPoints()[idx];
    }
    ms_Points = ms_Points.substring(1);
    document.getElementById("sensor-coords").innerHTML = ms_Points;
}

function getSensorCenter(uniqueid)
{
    if (uniqueid == undefined){uniqueid = gms_uniqueid;}
    ms_Points = "";
    
    for (idx=0;idx<markerSensor[uniqueid].GetPoints().length;idx++){
        ms_Points += ";" + markerSensor[uniqueid].GetPoints()[idx];
    }
    ms_Points = ms_Points.substring(1);
    document.getElementById("sensor-coords").innerHTML = ms_Points;
}



//onmousedown handler
function mouseDownHandler(e) {
    if (e.elementID) {
        if (e.elementID.substring(0,12) != 'msftve_1000_' || e.rightMouseButton)
        {
            currentDragHandle = main_map.GetShapeByID(e.elementID);
            if (currentDragHandle.GetType() == VEShapeType.Pushpin){
               moving = true;
               polylineMask[gms_uniqueid].Show();
               main_map.vemapcontrol.EnableGeoCommunity(true);
               document.getElementById("myMap").style.cursor = 'crosshair';
               
               //Determine point index
               var handleLocation = currentDragHandle.GetPoints();
               for (i = 0; i <= (points[gms_uniqueid].length - 1); i++){
                var pointLocation = points[gms_uniqueid][i].toString();
                if(handleLocation == pointLocation){
                    pointIndex = i;
                    break;
                }   
               }       
            }
        }
    }
}

//onmousemove handler
function mouseMoveHandler(e) {
    if (moving) {
        var loc = main_map.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
        currentDragHandle.SetPoints(loc);
        points[gms_uniqueid][pointIndex] = loc;
        polylineMask[gms_uniqueid].SetPoints(points[gms_uniqueid]);
    }
}

//onmouseup handler
function mouseUpHandler(e) {
    if (moving) {
        moving = false;
        polylineMask[gms_uniqueid].Hide();
        main_map.vemapcontrol.EnableGeoCommunity(false);
        
        polyline[gms_uniqueid].SetPoints(points[gms_uniqueid]);
        try
        {
            document.getElementById("MyMap").style.cursor = '';
        }catch(e){}
    }
}

function toogleSensorEdit(e)
{
    toggleEdit(gms_uniqueid);
}

function sensorEdit(uniqueid)
{
    if (pinLayer[uniqueid].GetVisibility()){pinLayer[uniqueid].Hide();}
    gms_uniqueid = uniqueid;
    toggleEdit(uniqueid);

}



//toggle edit mode
function toggleEdit(ms_uniqueid){
    if (!pinLayer[ms_uniqueid].GetVisibility()){
        pinLayer[ms_uniqueid].Show();
        currentSensorUID = ms_uniqueid;
        //document.getElementById("cmdEdit").value = 'Click to end edit';
    } else {
        pinLayer[ms_uniqueid].Hide();
        //document.getElementById("cmdEdit").value = 'Click to start edit';
    }
}

var MiniMapSize;

function LoadMap(){
    
    main_map = new VEMap('myMap');
    
    
    
            
    main_map.LoadMap();
    onMapLoad(main_map);
    main_map.SetMapStyle(VEMapStyle.Shaded);
    main_map.SetMouseWheelZoomToCenter(false);	

    // Attach the event handlers to the mouse 
    main_map.AttachEvent("onmousemove", mouseMoveHandler);
    main_map.AttachEvent("onmousedown", mouseDownHandler);
    main_map.AttachEvent("onmouseup", mouseUpHandler);

    main_map.AttachEvent('onchangeview', onMapChangeView);
    
    MiniMapSize = VEMiniMapSize.Small
    
    main_map.ShowMiniMap(0, 0, MiniMapSize);
    
    RealignMiniMap();

    LoadLayers();
    
}

function RealignMiniMap()
{

    main_map.Resize();
    document.getElementById("MSVE_minimap").style.left = main_map.GetWidth()-148;
    //main_map.ShowMiniMap(main_map.GetWidth()-150, 0, MiniMapSize);

/// Hide the Mini Map resizer so the Mini Map cannot be resized
    document.getElementById("MSVE_minimap_resize").style.display = "none";

}



var winCurrentInfo;

function showCurrentInfo(e){
    // create the window on the first click and reuse on subsequent clicks
    if(!winCurrentInfo){
        winCurrentInfo = new Ext.Window({
            title:'Current Realtime Information',
            layout:'fit',
            width:500,
            height:300,
            closeAction:'hide',
            plain: true,
            items: GPSGrid

            
        });
    }
    winCurrentInfo.show(e);
}

var winAbout;

function showAbout(e){
            
    if(!winAbout)
    {
        winAbout = new Ext.Window({
            title:'About PointAT',
            layout:'fit',
            width:400,
            height:300,
            closeAction:'hide',
            plain: true,
            modal: true,
            resizable: false,
            items: [
                new Ext.BoxComponent({
	                contentEl: 'pointat-about',
                    margins: '0 0 0 0'
                })
            ],
            buttons: [
            {
                text: 'OK',
                handler: function(){
                    winAbout.hide();
                }
            }]
        });
            
            
    }
    winAbout.show(e);

}


function ShowMiniMap(show_minimap)
{
    
    if (show_minimap){
        document.getElementById("MSVE_minimap").style.display = '';
    }
    else
    {
        document.getElementById("MSVE_minimap").style.display = 'none';
    }
}

function ResizeMap(){
	
	var mi_height = document.getElementById('mapview').parentNode.parentNode.parentNode.parentNode.clientHeight -28;
	document.getElementById('mapview').style.height = mi_height + 'px';
	
	main_map.Resize(main_map.width,mi_height);
	
	RealignMiniMap();
	
}


function OnResize(e)
 {
    Ext.Msg.alert('<div class=\'pointat-messagebox\'></div>', e.eventName + ' has been called.');
    return 0;
 }



function LoadLayers()
{
	crunchedLayerManager = new VE.MapCruncher.CrunchedLayerManager(main_map);
        crunchedLayerManager.ImportLayersFromAnchorHRef("CrunchedLayers");

	var permalinkProvided = false;
	
        if (!permalinkProvided) {
		    myLayers[0] = crunchedLayerManager.layerList.find('NL_2_1');
		    
		    myLayers[1] = crunchedLayerManager.layerList.find('NL_2_2');
		    //myLayers[1].Activate(main_map);
            myLayers[2] = crunchedLayerManager.layerList.find('NL_2_3');
            myLayers[0].Activate(main_map);
		    
        }
        
        document.getElementById('VE_MapCruncher_legend_box').style.display = "none";
}

function refreshPlanXML(){

    var xmlRequest;

    if (window.XMLHttpRequest)
    {
        xmlRequest =new XMLHttpRequest();
    }
    else // Internet Explorer 5/6
    {
        xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlRequest.onreadystatechange = function () {
        if (xmlRequest.readyState == 4) {
            showPlans(xmlRequest);
        }
    };
	
	xmlRequest.open('GET', 'xml/xml-plan.asp?icustomerid=' + m_iCustomerID.toString() + "&ruid=" + new Date().toUTCString(), true);                   
    xmlRequest.send(); 

}

function refreshSensorXML(){

    var xmlRequest;

    if (window.XMLHttpRequest)
    {
        xmlRequest =new XMLHttpRequest();
    }
    else // Internet Explorer 5/6
    {
        xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlRequest.onreadystatechange = function () {
        if (xmlRequest.readyState == 4) {
            showSensors(xmlRequest);
        }
    };
	
	xmlRequest.open('GET', 'xml/xml-sensor.asp?icustomerid=' + m_iCustomerID.toString() + "&ruid=" + new Date().toUTCString(), true);                   
    xmlRequest.send(); 

}
		

function refreshUnitXML(bZoom)
{

	var xmlRequest;
    
    if (window.XMLHttpRequest)
    {
        xmlRequest =new XMLHttpRequest();
    }
    else // Internet Explorer 5/6
    {
        xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
}

    xmlRequest.onreadystatechange = function () {
    		
	    if (xmlRequest.readyState == 4) {
		    showUnits(xmlRequest, bZoom);
	    }
    };
	
	xmlRequest.open('GET', 'xml/xml-gps.asp?icustomerid=' + m_iCustomerID.toString() + "&ruid=" + new Date().toUTCString(), true); 
	//xmlHttpRequest.open('GET', 'http://localhost/www.point-at.net/xml/test.xml', false);                    
    xmlRequest.send(); 

}

function getHistory(){

    if (unit_type.getValue() != "" && start_date_field.value != undefined && end_date_field.value != undefined){
        md_from = start_date_field.value.replace(/\-/gi,'');
        md_to = end_date_field.value.replace(/\-/gi,'');
        refreshHistoryXML(unit_type.getValue(),md_from,md_to);
    }

}

function refreshHistoryXML(mi_unit_id, md_from, md_to){

    var xmlRequest;

    if (window.XMLHttpRequest)
    {
        xmlRequest =new XMLHttpRequest();
    }
    else // Internet Explorer 5/6
    {
        xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlRequest.onreadystatechange = function () {
        if (xmlRequest.readyState == 4) {
            showHistory(xmlRequest);
        }
    };
	
	xmlRequest.open('POST', 'xml/xml-gps-unit-history.asp?icustomerid=' + m_iCustomerID.toString() + 
	    "&iunitid=" + mi_unit_id.toString() + 
	    "&dfrom=" + md_from.toString() + 
	    "&dto=" + md_to.toString() + 
	    "&ruid=" + new Date().toUTCString(), true);                   
    xmlRequest.send(); 

}

function showHistory(xmlRequest)
{
    if (window.XMLHttpRequest)
    {
        gs_responseText = xmlRequest.responseText;
    }
    else // Internet Explorer 5/6
    {
        gs_responseText = xmlRequest.responseText;
    }

    if (window.DOMParser)
    {
        parser=new DOMParser();
        xmlHistoryDoc=parser.parseFromString(gs_responseText,"text/xml");
        
    }
    else 
    {
        xmlHistoryDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlHistoryDoc.async="false";
        xmlHistoryDoc.loadXML(gs_responseText); 
    }
    
    
    HistoryGrid.getStore().proxy = new Ext.data.BufferedMemoryProxy(xmlHistoryDoc);
    HistoryGrid.getStore().reload();
    HistoryGrid.getColumnModel().setHidden(0, false);
    HistoryGrid.getColumnModel().setHidden(1, false);
    HistoryGrid.getColumnModel().setHidden(2, false);
    
    stopBCT();
    Ext.getCmp('playBCT').setDisabled(HistoryGrid.getStore().totalLength == 0);
    
}

function showPlans(xmlRequest)
{
    if (window.XMLHttpRequest)
    {
        gs_responseText = xmlRequest.responseText;
    }
    else // Internet Explorer 5/6
    {
        gs_responseText = xmlRequest.responseText;
    }

    if (window.DOMParser)
    {
        parser=new DOMParser();
        xmlPlanDoc=parser.parseFromString(gs_responseText,"text/xml");
        
    }
    else 
    {
        xmlPlanDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlPlanDoc.async="false";
        xmlPlanDoc.loadXML(gs_responseText); 
    }
    
    
    for(var idxNodes=0;idxNodes<xmlPlanDoc.getElementsByTagName('plans').length;idxNodes++){
			
		var m_node = xmlPlanDoc.getElementsByTagName('plans')[idxNodes];
		
		ms_id = _checkNode(m_node.getElementsByTagName('id').item(0).firstChild);				
    }
        
    
    
}

function showSensors(xmlRequest)
{
    if (window.XMLHttpRequest)
    {
        gs_responseText = xmlRequest.responseText;
    }
    else // Internet Explorer 5/6
    {
        gs_responseText = xmlRequest.responseText;
    }

    if (window.DOMParser)
    {
        parser=new DOMParser();
        xmlSensorDoc=parser.parseFromString(gs_responseText,"text/xml");
        
    }
    else 
    {
        xmlSensorDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlSensorDoc.async="false";
        xmlSensorDoc.loadXML(gs_responseText); 
    }
    
    
    for(var idxNodes=0;idxNodes<xmlSensorDoc.getElementsByTagName('sensor').length;idxNodes++){
			
		var m_node = xmlSensorDoc.getElementsByTagName('sensor')[idxNodes];
		
		ms_uniqueid = m_node.getAttribute("uniqueid");
		
		ms_id = _checkNode(m_node.getElementsByTagName('id').item(0).firstChild);				
			
		ms_name = _checkNode(m_node.getElementsByTagName('name').item(0).firstChild);
		ms_plan = _checkNode(m_node.getElementsByTagName('plan').item(0).firstChild);
		ms_location = _checkNode(m_node.getElementsByTagName('location').item(0).firstChild);
		
		ms_lat = _checkNode(m_node.getElementsByTagName('lat').item(0).firstChild);
		ms_long = _checkNode(m_node.getElementsByTagName('long').item(0).firstChild);
		ms_alt = _checkNode(m_node.getElementsByTagName('alt').item(0).firstChild);
		ms_coords = _checkNode(m_node.getElementsByTagName('coords').item(0).firstChild);
		
		ms_tagstyle = _checkNode(m_node.getElementsByTagName('tagstyle').item(0).firstChild);
		ms_offbackcolor = _checkNode(m_node.getElementsByTagName('offbackcolor').item(0).firstChild);
		ms_onbackcolor = _checkNode(m_node.getElementsByTagName('onbackcolor').item(0).firstChild);
		ms_opacity = _checkNode(m_node.getElementsByTagName('opacity').item(0).firstChild);
		ms_notes = _checkNode(m_node.getElementsByTagName('notes').item(0).firstChild);
		
		LoadSensors(parseInt(ms_uniqueid), ms_id, ms_name, ms_plan, parseFloat(ms_lat), parseFloat(ms_long), ms_coords,ms_offbackcolor,ms_onbackcolor,ms_opacity,ms_tagstyle);
		//AddSensorCenter(parseInt(ms_uniqueid),ms_name, ms_plan, ms_location, parseFloat(ms_lat), parseFloat(ms_long), parseFloat(ms_alt),ms_notes,ms_offbackcolor);	
    }
        
    
    
}

function getSensorValues(ms_sensor_tag)
{
    for(var idxNodes=0;idxNodes<xmlSensorDoc.getElementsByTagName('sensor').length;idxNodes++){
			
		var m_node = xmlSensorDoc.getElementsByTagName('sensor')[idxNodes];
		
		if (_checkNode(m_node.getElementsByTagName('id').item(0).firstChild) == ms_sensor_tag){	
		
		    ms_uniqueid = m_node.getAttribute("uniqueid");
    		
		    ms_id = _checkNode(m_node.getElementsByTagName('id').item(0).firstChild);				
    			
		    ms_name = _checkNode(m_node.getElementsByTagName('name').item(0).firstChild);
		    ms_plan = _checkNode(m_node.getElementsByTagName('plan').item(0).firstChild);
    		
		    ms_lat = _checkNode(m_node.getElementsByTagName('lat').item(0).firstChild);
		    ms_long = _checkNode(m_node.getElementsByTagName('long').item(0).firstChild);
		    ms_coords = _checkNode(m_node.getElementsByTagName('coords').item(0).firstChild);
    		
		    ms_offbackcolor = _checkNode(m_node.getElementsByTagName('offbackcolor').item(0).firstChild);
		    ms_onbackcolor = _checkNode(m_node.getElementsByTagName('onbackcolor').item(0).firstChild);
		    ms_opacity = _checkNode(m_node.getElementsByTagName('opacity').item(0).firstChild);
		    
		    return ms_uniqueid + '|' + ms_id + '|' + ms_name + '|' + ms_plan + '|' + 
		        ms_lat + '|' + ms_long + '|' + ms_coords + '|' + ms_offbackcolor + '|' + ms_onbackcolor + '|' + ms_opacity;
		}	
    }
}

function showUnits(xmlRequest, bZoom)
{
    
    if (window.XMLHttpRequest)
    {
        gs_responseText = xmlRequest.responseText;
    }
    else // Internet Explorer 5/6
    {
    	
        gs_responseText = xmlRequest.responseText;
        
    }
    
    
  
    if (window.DOMParser)
    {
        parser=new DOMParser();
        xmlUnitsDoc=parser.parseFromString(gs_responseText,"text/xml");
        
    }
    else 
    {
        xmlUnitsDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlUnitsDoc.async="false";
        xmlUnitsDoc.loadXML(gs_responseText); 
    }
    
    xmlUnitStatus = xmlUnitsDoc;

    xmlSearchDocXML = gs_responseText;
    
    var d = new Date();

    document.getElementById("south-lastupdate").innerHTML = "Last Update:" + d.toLocaleTimeString();

    loadUnits(xmlUnitsDoc, bZoom);
    
    
}

function _checkNode(ms_firstChild){
    if (ms_firstChild != undefined){
		return ms_firstChild.nodeValue;
	}
	else
	{
	    return  '';
	}
}


function loadUnits(xmlDoc, bZoom, sDate){
			
			
		try{
		
		GPSGrid.getStore().proxy = new Ext.data.MemoryProxy(xmlUnitsDoc);
        GPSGrid.getStore().reload();
        
        unit_type.getStore().proxy = new Ext.data.MemoryProxy(xmlUnitsDoc);
        unit_type.getStore().reload();
        
        
		sSpeedType = xmlDoc.documentElement.getAttribute("speedTypeLabel");
		
		sSpeedConvFactor = xmlDoc.documentElement.getAttribute("speedConvFactor");
		sDistanceType = xmlDoc.documentElement.getAttribute("distanceTypeLabel");
		

		
		if (m_Accounts == undefined){
			m_Accounts = new Array();
		}
		if (m_AccountUnits == undefined){
			m_AccountUnits = new Array();
		}
		
		if (m_AccountUnitsGeo == undefined){
			m_AccountUnitsGeo = new Array();
		}
		
		if (m_GroupUnit == undefined){
			m_GroupUnit = new Array();
		}
		if (m_Group == undefined){
			m_Group = new Array();
		}
		
		m_Group[0] = undefined;
		m_Group[1] = undefined;
		m_Group[2] = undefined;
		m_Group[3] = undefined;
		
		m_gsUnitID = -1;
		try{
			m_gsUnitID = sDate.split('|')[0];
		}
		catch(err){
			
		}

        
		for(var idxNodes=0;idxNodes<xmlDoc.getElementsByTagName('unit').length;idxNodes++){
			
			var m_node = xmlDoc.getElementsByTagName('unit')[idxNodes];
			
			sUnitID = m_node.getAttribute("id");
			
			
			if (m_AccountUnits[m_iCustomerID] == undefined){
				m_AccountUnits[m_iCustomerID] = sUnitID;
			}
			else
			{
				m_AccountUnits[m_iCustomerID] = m_AccountUnits[m_iCustomerID] + "," + sUnitID;
			}


			if (m_gsUnitID == sUnitID || m_gsUnitID == -1){
				status = "Loading Unit: " + sUnitID;
                
                
			
                
				sUnitName = _checkNode(m_node.getElementsByTagName('name').item(0).firstChild);				
				
				sUTC = _checkNode(m_node.getElementsByTagName('utc').item(0).firstChild);
				sXGPS = _checkNode(m_node.getElementsByTagName('long').item(0).firstChild);
				sYGPS = _checkNode(m_node.getElementsByTagName('lat').item(0).firstChild);
				sZGPS = _checkNode(m_node.getElementsByTagName('alt').item(0).firstChild);
				sAddress = _checkNode(m_node.getElementsByTagName('address').item(0).firstChild);
				
				sSensorUTC = _checkNode(m_node.getElementsByTagName('sensordatestamp').item(0).firstChild);
				sSensorPairs = _checkNode(m_node.getElementsByTagName('sensorpairs').item(0).firstChild).replace('|','@');
				
				ms_locdatetime =  _checkNode(m_node.getElementsByTagName('locdatetime').item(0).firstChild);
				ms_loc = _checkNode(m_node.getElementsByTagName('loc').item(0).firstChild);
				ma_loclatlong =  _checkNode(m_node.getElementsByTagName('loclatlong').item(0).firstChild).split(',');
				
				
				
				
//				if (Date.parse(sSensorUTC) > Date.parse(sUTC) && sSensorPairs != "")
//				{
//				    mi_max_rss = 0;
//				    ms_sensor_tag = '';
//				    msa_pairs = sSensorPairs.split(',');
//				    for (idxP=0;idxP<msa_pairs.length;idxP++){
//				        mi_rss = parseInt(msa_pairs[idxP].split('@')[1]);
//				        if (mi_rss > mi_max_rss){
//				            mi_max_rss = mi_rss;
//				            ms_sensor_tag = msa_pairs[idxP].split('@')[0];
//				        }
//				    }
//				    
//				    msa_sensor = getSensorValues(ms_sensor_tag).split('|');
//				    
//				    sUTC = sSensorUTC;
//				    sAddress = msa_sensor[2];
//				    sXGPS = points[parseInt(msa_sensor[0])][0].Longitude
//				    sYGPS = points[parseInt(msa_sensor[0])][0].Latitude;
//				    
//				}
				
				
				
				sIgnition = _checkNode(m_node.getElementsByTagName('ignition').item(0).firstChild);
				sStopped = _checkNode(m_node.getElementsByTagName('stopped').item(0).firstChild);
				sUnitType = _checkNode(m_node.getElementsByTagName('type').item(0).firstChild);

				sLastCom = _checkNode(m_node.getElementsByTagName('lastcomm').item(0).firstChild);

				sUnitIndicator = "n";
				sGroupIDS = m_node.getAttribute("groups");
				sReg = m_node.getAttribute("reg");
				aGroupID = sGroupIDS.split(",");

				sSpeed =  _checkNode(m_node.getElementsByTagName('speed').item(0).firstChild);
				sASpeed =  _checkNode(m_node.getElementsByTagName('aspeed').item(0).firstChild);


				sSpeed = parseInt(Math.round(parseFloat(sASpeed) * parseFloat(sSpeedConvFactor) * 1.8520));
				

				mt_sSpeed = sSpeed

				sSpeed = sSpeed + " " + sSpeedType;
				
				sDirection = _checkNode(m_node.getElementsByTagName('direction').item(0).firstChild);
				sRealStatus = _checkNode(m_node.getElementsByTagName('status').item(0).firstChild);
				
				
			
				sDistance = _checkNode(m_node.getElementsByTagName('distance').item(0).firstChild);
				sMaxSpeed = _checkNode(m_node.getElementsByTagName('maxspeed').item(0).firstChild);

				sATM =  _checkNode(m_node.getElementsByTagName('name').item(1).firstChild);
				sUID =  _checkNode(m_node.getElementsByTagName('uid').item(0).firstChild);
				sPWD =  _checkNode(m_node.getElementsByTagName('pwd').item(0).firstChild);

				sSERVER = _checkNode(m_node.getElementsByTagName('server').item(0).firstChild);
				sPORT = _checkNode(m_node.getElementsByTagName('port').item(0).firstChild);

				sINTERVAL = _checkNode(m_node.getElementsByTagName('interval').item(0).firstChild);
				sMODE = _checkNode(m_node.getElementsByTagName('mode').item(0).firstChild);

				sFMW = _checkNode(m_node.getElementsByTagName('version').item(0).firstChild);

				sRStatus = sRealStatus;

				if (sStopped == "true")
				{
					sUnitIndicator ="s";
				}
				else
				{
					if (sIgnition == "false")
					{
						sUnitIndicator ="i";
					}
				}

				sDisplayStatus = sRealStatus;
				if ((sRealStatus == "11") && (parseFloat(sASpeed) < 5))
				{
					sDisplayStatus = "10";
				}

				if (parseFloat(parseInt(Math.round(parseFloat(sASpeed) * 1.8520))) > parseFloat(sMaxSpeed)){
					if (sRealStatus == "11") {
						sDisplayStatus = "22";
					}
				}

				if ((sRealStatus == "11") && (parseFloat(sASpeed) == 0)){
					sDisplayStatus = "33";
				}

				if (sDate != undefined){
					var aoDate = sDate.split(" ");
					var adDate = aoDate[0].split("-");
					var atDate = aoDate[1].split(":");
					var dNow = new Date(adDate[0], adDate[1] -1, adDate[2], atDate[0], atDate[1], atDate[2]);
				}
				else
				{
					var dNow = new Date();
				}

				if (sLastCom != "" || ms_locdatetime != ""){
					var aoDate = sLastCom.split(" ");
					var adDate = aoDate[0].split("/");
					var atDate = aoDate[1].split(":");
					var dLastCom = new Date(adDate[2], adDate[1] -1, adDate[0], atDate[0], atDate[1], atDate[2]);

					var aoUTCDate = ms_locdatetime.split(" ");
					var adUTCDate = aoUTCDate[0].split("/");
					var atUTCDate = aoUTCDate[1].split(":");
					var dLastUTCCom = new Date(adUTCDate[2], adUTCDate[1] -1, adUTCDate[0], atUTCDate[0], atUTCDate[1], atUTCDate[2]);

				}
				

				sStatus = "IGNITION ON";

				sImageURL =  "images/units/" + sUnitType + "_" + sDisplayStatus + ".gif";
				
				
				
				switch (sRealStatus)
				{
					case "111":
					{
						if (sSpeed == "0"){
							sRealStatus = "IGNITION ON - STOPPED";
						}
						else
						{
							sRealStatus = "IGNITION ON - MOVING";
						}
						break;
					}
					case "101":
					{
						sRealStatus = "IGNITION OFF";
						sSpeed = "0" + " " + sSpeedType; 
						break;
					}
					case "110":
					{
						sRealStatus = "INVALID GPS LOCK";
						break;
					}

					case "11":
					{
						if (sSpeed == "0"){
							sRealStatus = "IGNITION ON - STOPPED";
						}
						else
						{
							sRealStatus = "IGNITION ON - MOVING";
						}
						break;
					}
					case "1":
					{
						sRealStatus = "IGNITION OFF";
						sSpeed = "0" + " " + sSpeedType; 
						break;
					}
					case "10":
					{
						sRealStatus = "IGNITION ON - IDLING";
						break;
					}
				}



				m_sData[sUnitID] = sUnitID + "|" + sUnitName + "|" + sUnitType + "|" + sImageURL + "|" + ms_locdatetime + "|" + sRealStatus + "|" + ma_loclatlong[0] + "|" + ma_loclatlong[1] + "|" + ma_loclatlong[2] + "|" + sGroupIDS + "|" + sReg + "|" + sSpeed + "|" + sDirection + "|" + sATM + "|" + sUID + "|" + sPWD  + "|" + sSERVER  + "|" + sPORT  + "|" + sINTERVAL  + "|" + sMODE  + "|" + sFMW + "|" + ms_loc + "|" + sSensorUTC + "|" + sSensorPairs;

				try{
				
				    mi_direction = parseInt(parseInt(sDirection)/10) * 10;

					if (sRStatus == "1"){
						mi_direction = 255;
					}

					//var sUnitHTML = getUnitHTML(m_sData[parseInt(sUnitID)]);
					//sUnitHTML = sUnitHTML.replace("@@sDir@@", "images/directions/" + mi_direction + ".gif");

					try{

						
						var vepoint = new VELatLong(parseFloat(ma_loclatlong[0]),parseFloat(ma_loclatlong[1]));

						
						try{
							main_map.DeleteShape(aPinMarker[parseInt(sUnitID)]);
							main_map.DeleteShape(aPinMarkerDir[parseInt(sUnitID)]);
						}
						catch(err){}

						amarkerHTML[parseInt(sUnitID)] = "";
						amarkerHTML[parseInt(sUnitID)] = ""; //sUnitHTML;

						sDirImageURL = "images/directions/" + mi_direction + ".gif";							

						amarker[parseInt(sUnitID)] = null;
						
						amarkerDir[parseInt(sUnitID)] = null;
						amarkerListener[parseInt(sUnitID)] = null;
						
						sImageURL =  'images/points/' + sUnitType + '.png';
						
						//sDirImageURL =  'http://maps.google.com/mapfiles/kml/pal2/icon18.png';

						try{

							aPinMarker[parseInt(sUnitID)] = new VEShape(VEShapeType.Pushpin, vepoint);
							aPinMarker[parseInt(sUnitID)].SetCustomIcon("<div class='mapicon " + sUnitType + "-map' onclick=_showUnitInfo(this,parseInt(" + sUnitID + "));></div>");
							aPinMarker[parseInt(sUnitID)].SetTitle(null);
							aPinMarker[parseInt(sUnitID)].SetDescription(null);
							aPinMarker[parseInt(sUnitID)].IconID = parseInt(sUnitID);
							
							aPinMarkerClone[parseInt(sUnitID)] = aPinMarker[parseInt(sUnitID)] ;

							main_map.AddShape(aPinMarker[parseInt(sUnitID)]); 								

						}

						catch(err){}

						try{

							aPinMarkerDir[parseInt(sUnitID)] = new VEShape(VEShapeType.Pushpin, vepoint);
							aPinMarkerDir[parseInt(sUnitID)].SetCustomIcon("<div class='mapicon-dir-" + mi_direction + "' onclick=_showUnitInfo(this,parseInt(" + sUnitID + "));></div>");
							aPinMarkerDir[parseInt(sUnitID)].SetTitle(null);
							aPinMarkerDir[parseInt(sUnitID)].SetDescription(null);
							aPinMarkerDir[parseInt(sUnitID)].IconID = parseInt(sUnitID);
							

							main_map.AddShape(aPinMarkerDir[parseInt(sUnitID)] );   
							
						}

						catch(err){}



						sTag = "[ID:" + sUnitID + "] " + sUnitName + " - " + sReg;

						//amarker[parseInt(sUnitID)].iconImage.setAttribute("title", sTag );
					}
					catch(err){
					    Ext.Msg.alert('<div class=\'pointat-messagebox\'></div>', err.message);
					}


					//iLeft = parseInt(document.getElementById("m_imgUnit_" + sUnitID).style.left);
					//iWidth = parseInt(document.getElementById("panPopUp").style.width);

					iclientWidth = parseInt(document.body.clientWidth);


					dLatGPS = parseFloat(ma_loclatlong[0]);
					dLongGPS = parseFloat(ma_loclatlong[1]);

					if (m_GroupUnit[0] == undefined){
						m_GroupUnit[0] = sUnitID;
					}
					else
					{
						m_GroupUnit[0] = m_GroupUnit[0] + "," + sUnitID;
					}



					for(i=0;i<aGroupID.length;i++){


						if ((dLongGPS < m_Group[0]) | (m_Group[0] == undefined)){
							m_Group[0] = dLongGPS;
						}
						if ((dLongGPS > m_Group[1]) | (m_Group[1] == undefined)){
							m_Group[1] = dLongGPS;
						}
						if ((dLatGPS < m_Group[2]) | (m_Group[2] == undefined)){
							m_Group[2] = dLatGPS;
						}
						if ((dLatGPS > m_Group[3]) | (m_Group[3] == undefined)){
							m_Group[3] = dLatGPS;
						}

						if ((dLongGPS < m_Group[aGroupID[i]*4]) | (m_Group[aGroupID[i]*4] == undefined)){
							m_Group[aGroupID[i]*4] = dLongGPS;
						}

						if ((dLongGPS > m_Group[aGroupID[i]*4 + 1]) | (m_Group[aGroupID[i]*4 + 1] == undefined)){
							m_Group[aGroupID[i]*4 + 1] = dLongGPS;
						}

						if ((dLatGPS < m_Group[aGroupID[i]*4 + 2]) | (m_Group[aGroupID[i]*4 + 2] == undefined)){
							m_Group[aGroupID[i]*4 + 2] = dLatGPS;
						}

						if ((dLatGPS > m_Group[aGroupID[i]*4 + 3]) | (m_Group[aGroupID[i]*4 + 3] == undefined)){
							m_Group[aGroupID[i]*4 + 3] = dLatGPS;
						}	

						if (m_GroupUnit[aGroupID[i]] == undefined){
							m_GroupUnit[aGroupID[i]] = sUnitID;
						}
						else
						{
							m_GroupUnit[aGroupID[i]] = m_GroupUnit[aGroupID[i]] + "," + sUnitID;
						}

					}
					
					
					
					
				}
				catch(err){}


			}
			
			
					
			
		}
		
		status = "Finished Loading Units";
		
		m_AccountUnitsGeo[m_iCustomerID] = m_Group[0] + "|" + m_Group[1] + "|" + m_Group[2]+ "|" + m_Group[3];
												
		
		
		var am_sSelectedUnits = m_sSelectedUnits.split("|");
					
		switch (am_sSelectedUnits[0]){
			case "u":
			{
				locateOnMap(parseInt(am_sSelectedUnits[1]), true, true);
				break;
			}
			
			case "g":
			{

				if (am_sSelectedUnits.length > 2){
					showGroup(am_sSelectedUnits[1], '', bZoom, am_sSelectedUnits[2]);
				}
				else
				{
					showGroup(am_sSelectedUnits[1], '', bZoom);
				}
				break;
			}
			case "a":
			{
				showAccountUnits(m_iCustomerID, '', false);
				break;
			}

		
		}
		
		if (iCurrentMarkerID != -1){
			if(!bShowZoom){
				amarker[iCurrentMarkerID].openInfoWindowHtml(amarkerHTML[iCurrentMarkerID]);
			}
		}
	}
	catch(err){}
	
	if (document.getElementById('loadingPanel').style.display == ""){document.getElementById('loadingPanel').style.display = "none";};
	
	status = "Done";
}

function setUnitInfoHTML(mi_unit_id)
{
    ms_html = document.getElementById("panUnitMapPopUp").innerHTML;
    
    m_node = xmlUnitsDoc.selectNodes('//units/unit[@id=\'' + mi_unit_id.toString() + '\']');
		
    if (m_node.length == 1){
        
        ms_id = _checkNode(m_node[0].getElementsByTagName('id').item(0).firstChild);
        ms_name = _checkNode(m_node[0].getElementsByTagName('name').item(0).firstChild);
	    ms_type = _checkNode(m_node[0].getElementsByTagName('type').item(0).firstChild);
	    ms_reg = _checkNode(m_node[0].getElementsByTagName('reg').item(0).firstChild);
	    ms_utc = _checkNode(m_node[0].getElementsByTagName('utc').item(0).firstChild);
	    ms_address = _checkNode(m_node[0].getElementsByTagName('address').item(0).firstChild);
	    ms_status = _checkNode(m_node[0].getElementsByTagName('status').item(0).firstChild);
	    ms_speed = _checkNode(m_node[0].getElementsByTagName('speed').item(0).firstChild);
	    ms_direction = _checkNode(m_node[0].getElementsByTagName('direction').item(0).firstChild);
	    
	    ms_notes = _checkNode(m_node[0].getElementsByTagName('notes').item(0).firstChild);
	    
	    ms_sensorpairs = _checkNode(m_node[0].getElementsByTagName('sensorpairs').item(0).firstChild);
	    ms_sensordatestamp = _checkNode(m_node[0].getElementsByTagName('sensordatestamp').item(0).firstChild);
	    ms_locdatetime = _checkNode(m_node[0].getElementsByTagName('locdatetime').item(0).firstChild);
	    ms_loc = _checkNode(m_node[0].getElementsByTagName('loc').item(0).firstChild);
	    ms_loclatlong = _checkNode(m_node[0].getElementsByTagName('loclatlong').item(0).firstChild);
	    
	    
	    ms_html= ms_html.replace("@@id@@", ms_id);
	    ms_html= ms_html.replace("@@id@@", ms_id);
	    ms_html= ms_html.replace("@@name@@", ms_name);
	   // ms_html= ms_html.replace("@@sReg@@", ms_reg);
	    ms_html= ms_html.replace("@@utc@@", ms_locdatetime);
	    ms_html= ms_html.replace("@@address@@", ms_loc);
	   // ms_html= ms_html.replace("@@sStatus@@", ms_status);
	    //ms_html= ms_html.replace("@@dcSpeed@@", ms_speed);
	    //ms_html= ms_html.replace("@@dcDir@@", ms_direction);
	    ms_html= ms_html.replace("@@type@@", ms_type);
	    ms_html= ms_html.replace("@@notes@@", ms_notes);
	    
	    document.getElementById("unit-info-detail").innerHTML = ms_html;
        document.getElementById("unit-info-notes").innerHTML = ms_notes;
        msx_sensorpairs = ms_sensorpairs.replace(/,/gi,'<br/>');
        msx_sensorpairs = msx_sensorpairs.replace(/\|/gi,'=');
        document.getElementById("unit-info-sensor").innerHTML = msx_sensorpairs + '<br/><br/><br/>' + 
                ms_sensordatestamp + '<br/>' + 
                ms_locdatetime + '<br/>' + 
                ms_loc + '<br/>' + 
                ms_loclatlong;
                
    
	}
	else
	{
	    return "";
	}
    

}
		


function showGroup(iGroupID, sGroup, bZoom, sGroupIDsIDX){
			
try{

    m_sSelectedUnits = "g|" + iGroupID.toString();
    
	dLong = m_Group[iGroupID*4] + (m_Group[iGroupID*4 + 1] - m_Group[iGroupID*4])/2;
	dLat = m_Group[iGroupID*4 + 2] + (m_Group[iGroupID*4 + 3] - m_Group[iGroupID*4 + 2] )/2;

	dLongDiff = (m_Group[iGroupID*4 + 1] - m_Group[iGroupID*4]) ;
	dLatDiff = (m_Group[iGroupID*4 + 3]  - m_Group[iGroupID*4 + 2] );

	try{

		var dcxLeft;
		var dcxRight;
		var dcxTop;
		var dcxBot;

		if (sGroupIDsIDX != undefined){
			aSm_GroupIDs= sGroupIDsIDX.split(",");

			for(idxGroupID=0;idxGroupID<aSm_GroupIDs.length;idxGroupID++){
				var m_igroupidx = aSm_GroupIDs[idxGroupID]
				
				var m_dcxLeft = parseFloat(m_Group[m_igroupidx*4]);
				var m_dcxRight = parseFloat(m_Group[m_igroupidx*4 + 1]);
				var m_dcxTop = parseFloat(m_Group[m_igroupidx*4 + 2]);
				var m_dcxBot = parseFloat(m_Group[m_igroupidx*4 + 3]);
				
				
				
				if (!isNaN(m_dcxLeft) && !isNaN(m_dcxRight) && !isNaN(m_dcxTop) && !isNaN(m_dcxBot)){
					if (m_dcxLeft < dcxLeft || dcxLeft == undefined) { dcxLeft = m_dcxLeft;}
					if (m_dcxRight > dcxRight || dcxRight == undefined) { dcxRight = m_dcxRight;}
					if (m_dcxTop < dcxTop || dcxTop == undefined) { dcxTop = m_dcxTop;}
					if (m_dcxBot > dcxBot || dcxBot == undefined) { dcxBot = m_dcxBot;}
				}
			}
		}
		else
		{
			dcxLeft = parseFloat(m_Group[iGroupID*4]);
			dcxRight = parseFloat(m_Group[iGroupID*4 + 1]);
			dcxTop = parseFloat(m_Group[iGroupID*4 + 2]);
			dcxBot = parseFloat(m_Group[iGroupID*4 + 3]);
		
			
		}
	
		dLong = dcxLeft + ((dcxRight - dcxLeft)/2);
		dLat = dcxTop + ((dcxBot - dcxTop)/2)

		var i =0;

		if (bZoom){
			
			MapBounds = [new VELatLongRectangle(new VELatLong(dcxTop, dcxLeft),new VELatLong(dcxBot, dcxRight))];
			main_map.SetMapView(MapBounds);
		}
		
	}
	catch(err){
		
	}
	
	if (sGroupIDsIDX != undefined){

		aSm_GroupUnitStr = "";
		aSm_GroupIDs= sGroupIDsIDX.split(",");
		
		for(idxGroupID=0;idxGroupID<aSm_GroupIDs.length;idxGroupID++){
			if (m_GroupUnit[aSm_GroupIDs[idxGroupID]] != undefined){
				aSm_GroupUnitStr = aSm_GroupUnitStr + ',' + m_GroupUnit[aSm_GroupIDs[idxGroupID]];
			}
		}
		
		aSm_GroupUnit = aSm_GroupUnitStr.substring(1).split(",");
		
	}
	else{
		
		aSm_GroupUnit = m_GroupUnit[iGroupID].split(",");
	}
	
	for (var idxPinMarker in aPinMarker){
		
		var bFoundIcon = false;
		
		for(var iX=0;iX<aSm_GroupUnit.length;iX++){
			if (idxPinMarker == parseInt(aSm_GroupUnit[iX])){
				bFoundIcon = true;
				
			}
		}
		
		sPinID = aPinMarker[idxPinMarker].GetID() + '_' + String(parseInt(aPinMarker[idxPinMarker].GetID().split('_')[2]) - 190000);

		if (bFoundIcon)
		{
			if (document.getElementById(sPinID) == undefined){
				aPinMarker[idxPinMarker].Show();
				aPinMarkerDir[idxPinMarker].Show();
			}
		}
		else
		{
			aPinMarker[idxPinMarker].Hide();
			aPinMarkerDir[idxPinMarker].Hide();
		}
	}
	
	try{						
		if (sGroup != undefined){
			var bounds = omap.getBounds();
			var dcLat = omap.getCenter().x;
			var dcLong = omap.getCenter().y;

			sHTML = document.getElementById("panGroupGMPopUp").innerHTML;
			sHTML = sHTML.replace("@@iGroupID@@", iGroupID);
			sHTML = sHTML.replace("@@iGroupID@@", iGroupID);
		
			sHTML = sHTML.replace("@@sGroup@@", sGroup);
			sHTML = sHTML.replace("@@sGroup@@", sGroup);
			sHTML = sHTML.replace("@@sGroup@@", sGroup);
			//omap.openInfoWindowHtml(new GLatLng(dcLat, dcLong), sHTML); 
			
			
		}
	}
	catch(err){}

}
catch(err){

}

status = 'Done';
}

function findElementCoords(obj) 
{
	var curleft = curtop = 0;
	if (obj.offsetParent) 
	{
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) 
		{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft,curtop];
}

function windowDim() {
    
  var myWidth = 0;
  var myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  
  return [myWidth,myHeight];
}

var unitInfo;

function _showUnitInfo(e,gma_iUnitID){

   
    
    //var sUnitHTML = getUnitInfoHTML(m_sData[parseInt(gma_iUnitID)]);
    
    var sUnitHTML = setUnitInfoHTML(gma_iUnitID);
    
    
    
    if(!unitInfo){
        unitInfo = new Ext.Window({
            minimizable: false,  
            maximizable: false,
            applyTo:'unit-info',
            layout:'fit',
            width:260,
            height:220,
            closeAction:'hide',
            plain: true,

            items: new Ext.TabPanel({
                applyTo: 'unit-tabs',
                autoTabs:true,
                activeTab:0,
                deferredRender:false,
                border:false
            }),

            buttons: [
            {
                text: 'Zoom',
                handler: function(){
                    showMapBlow(gma_iUnitID);
                     unitInfo.hide();
                }
            }
            ,
            {
                text: 'History',
                handler: function(){
                    showUnitHist(gma_iUnitID);
                    unitInfo.hide();
                }
             }   
            ,
            {
                text: 'Close',
                handler: function(){
                    unitInfo.hide();
                }
            }]
        });
    }
    else
    {
        unitInfo.buttons[0].handler = function(){
                    showMapBlow(gma_iUnitID);
                     unitInfo.hide();
                };
                
        unitInfo.buttons[1].handler = function(){
                    showUnitHist(gma_iUnitID);
                     unitInfo.hide();
                };  
            
        unitInfo.hide();
    }
    
    
    if (findElementCoords(e)[1] + unitInfo.height > windowDim()[1]){
        unitInfo.y = windowDim()[1] - (unitInfo.height + 40);
    }
    else
    {
        unitInfo.y = findElementCoords(e)[1] + 22;
    }
    
    if (findElementCoords(e)[0] + unitInfo.width > windowDim()[0]){
        unitInfo.x = windowDim()[0] - (unitInfo.width + 40);
    }
    else
    {
        unitInfo.x = findElementCoords(e)[0] + 22;
    }

    unitInfo.show(e);

    
}

function _showUnitInfoX(gma_iUnitID){
	var pin = aPinMarker[parseInt(gma_iUnitID)];
	
	aPinMarker[parseInt(gma_iUnitID)].SetTitle('');
	aPinMarker[parseInt(gma_iUnitID)].SetDescription(amarkerHTML[parseInt(gma_iUnitID)]);
	
		
	main_map.ShowInfoBox(aPinMarker[parseInt(gma_iUnitID)], pin.GetPoints()[0], new VEPixel(0,0));
	
	aPinMarker[parseInt(gma_iUnitID)].SetTitle('');
	aPinMarker[parseInt(gma_iUnitID)].SetDescription('');
}

function showMapBlow(iGFID){
	main_map.SetCenterAndZoom(aPinMarker[iGFID].GetPoints()[0],19);
}

function showUnitHist(iUnitID){
    var w = Ext.getCmp('west-panel');
    w.expand();
    
    HistoryGrid.expand();
    
    var currentTime = new Date();
    
    unit_type.setValue(iUnitID);
    start_date_field.setValue(currentTime);
    end_date_field.setValue(currentTime.add('d',1));

    getHistory();
    
    
    
}

function setUnitItem(sUnitSet, bShow, bRefresh, bCentre){
		
	
	if (sUnitSet.indexOf("|") == -1){
	    sUnitSet+= "|";
	}
			
	var aUnitSet = sUnitSet.split("|");
	
	m_sSelectedUnits = "u|" + aUnitSet[0];
			
	bShow = false;

	if (m_sData[aUnitSet[0]] != undefined){
		aUnitSet = m_sData[aUnitSet[0]].split("|");
		if (aUnitSet[12] == "255"){
			aUnitSet[12] = "[NA]";
		}
		else{
			aUnitSet[12] = aUnitSet[12] * 2;
		}


		try{
			locateOnMap(parseInt(aUnitSet[0]))
		}
		catch(err){}
	
	}
	else
	{
	     Ext.Msg.alert('<div class=\'pointat-messagebox\'></div>', 'Sorry, no current data for unit');
	}


} 

function locateOnMap(iUnitID, bNoInfo, bNoZoom){

	try{
	
		var maData = m_sData[iUnitID].split("|");

		for(var i=0;i<aPinMarker.length;i++){
			if (aPinMarker[i]  != undefined){
				
				try{
					aPinMarker[i].Hide();
					aPinMarkerDir[i].Hide();
				}
				catch(err){}
			}
		}
		
		try{
			aPinMarker[parseInt(maData[0])].Show();
			aPinMarkerDir[parseInt(maData[0])].Show();
		}
		catch(err){}
		
		if (bNoZoom == undefined){
			main_map.SetCenter(new VELatLong(parseFloat(maData[6]), parseFloat(maData[7])));
		}
	}
	catch(err){}
	
	
			
}


		
