var firstTime = true;

function onSelectAsset(eventObj, assetId){
    var selected = eventObj.checked;
    var numSelected = 0;
    //clear all of the other ones
    firstTime = true;
    for(i = 0; i < profiles.length; i++){
        profileId = profiles[i];
        if(assetHash.get(profileId) && profileId != assetId){
            assetElement = document.getElementById("assetId" + profileId);
            assetElement.checked = false;
            assetHash.remove(profileId);
            assetHash.put(profileId, false);
            killAsset(profileId);
        }
    }
    
    if(selected){
        numSelected++;
        assetHash.remove(profileId);
        assetHash.put(assetId, true);
    }else{
        killAsset(assetId);
        assetHash.remove(assetId);
        assetHash.put(assetId, false);
    }
    
    if(numSelected == 0){
        map.setZoom(4);
    }else{
      generateRealTimeRequest(new Array(assetId));
    }
}

function newLocate(location){
    var locationId = parseInt(location.getAttribute('id'));
    var assetId = parseInt(location.getAttribute('assetId'));
    var lat = parseFloat(location.getAttribute('lat'));
    var lng = parseFloat(location.getAttribute('long'));
    var timestamp = parseInt(location.getAttribute('timestamp'));
    var assetName = location.getAttribute('assetName');
    var animated = location.getAttribute('animated') == 'true';
    var speed = location.getAttribute('speed');
    var type = "location";
    
    var selectedAsset = null;
    for(i = 0; i < profiles.length; i++){
        profileId = profiles[i];
        if(assetHash.get(profileId)){
          selectedAsset = profileId;
        }
    }
    if(assetId == selectedAsset){
      addPointArgs({id: locationId, assetId: assetId, lat: lat, lng: lng, timestamp: timestamp, assetName: assetName, animated: animated, speed: speed, type: type});
    }
}

function newIdle(idle){
    var location = idle.xml.firstChild;
    var locationId = parseInt(location.getAttribute('id'));
    var assetId = parseInt(location.getAttribute('assetId'));
    var lat = parseFloat(location.getAttribute('lat'));
    var lng = parseFloat(location.getAttribute('long'));
    var timestamp = parseInt(location.getAttribute('timestamp'));
    var assetName = location.getAttribute('assetName');
    var animated = location.getAttribute('animated') == 'true';
    var speed = location.getAttribute('speed');
    var duration = parseInt(idle.getAttribute('duration'));
    var type = "idle";
    
    var selectedAsset = null;
    for(i = 0; i < profiles.length; i++){
        profileId = profiles[i];
        if(assetHash.get(profileId)){
          selectedAsset = profileId;
        }
    }
    if(assetId == selectedAsset){
      addPointArgs({id: locationId, assetId: assetId, lat: lat, lng: lng, timestamp: timestamp, assetName: assetName, animated: animated, speed: speed, type: type, duration: duration});
    }
}

function newIgnitionOn(ignitionOn){
    var location = ignitionOn.xml.firstChild;
    var locationId = parseInt(location.getAttribute('id'));
    var assetId = parseInt(location.getAttribute('assetId'));
    var lat = parseFloat(location.getAttribute('lat'));
    var lng = parseFloat(location.getAttribute('long'));
    var timestamp = parseInt(location.getAttribute('timestamp'));
    var assetName = location.getAttribute('assetName');
    var animated = location.getAttribute('animated') == 'true';
    var speed = location.getAttribute('speed');
    var type = "ignitionOn";
    
    var selectedAsset = null;
    for(i = 0; i < profiles.length; i++){
        profileId = profiles[i];
        if(assetHash.get(profileId)){
          selectedAsset = profileId;
        }
    }
    if(assetId == selectedAsset){
      addPointArgs({id: locationId, assetId: assetId, lat: lat, lng: lng, timestamp: timestamp, assetName: assetName, animated: animated, speed: speed, type: type});
    }
}

function cutTail(){
    currentTime = new Date();
    startDisplay = new Date(currentTime - windowLength);
    for(var i = 0; i < profiles.length; i++){
        firstTimestamp = getFirstTimeStamp(profiles[i]);
        var count = 0;
        if(firstTimestamp){
            checkTime = new Date(firstTimestamp);    
            while(startDisplay.getTime() > checkTime.getTime() && checkTime.getTime() > 0){
                removeFirstPoint(profiles[i]);
                checkTime = new Date(getFirstTimeStamp(profiles[i]));
                count++;
            }
            
            if(checkTime.getTime() == 0){
                userObject = getUserObject(profiles[i]);
                if(map){
                  map.removeOverlay(userObject.animatedMarker);
                }
            }
        }else{
            //already empty
        }
    }
}

var realTimeRequestObject;
function generateRealTimeRequest(){
    cutTail();
    var url = './servlet/LocateEventServlet';
    var params = "op=realTime&windowLength=" + windowLength + "&";
    var assetSelected = false;
    
    for(i = 0; i < profiles.length; i++){
        profileId = profiles[i];
        if(assetHash.get(profileId)){
          params += "lastTimestamp=" + getLastTimeStamp() + "&";
          params += "assetId=" + profileId + "&";
          assetSelected = true;
        }
    }

    params += "firstTime=" + firstTime;
    if(firstTime){
        firstTime = false;
    }
    
    //Get a new request object, it seems more robust this way.
    if(assetSelected){
      realTimeRequestObject = createRequestObject();
      doAjaxCall(realTimeRequestObject, 'POST', url, processRealTimeUpdateResult, params);
    }
}

function processRealTimeUpdateResult(){
    //try{
        geomaxXMLHandler.processXML(realTimeRequestObject);
    //}catch(e){}
}

geomaxXMLHandler.addGeomaxEventListener(geomaxXMLDefinition.LOCATE_EVENT, newLocate);
geomaxXMLHandler.addGeomaxEventListener(geomaxXMLDefinition.IGNITION_ON, newIgnitionOn);
geomaxXMLHandler.addGeomaxEventListener(geomaxXMLDefinition.IDLE, newIdle);
geomaxXMLHandler.addGeomaxEventListener(geomaxXMLDefinition.REDRAW, redraw);
geomaxXMLHandler.addGeomaxEventListener(geomaxXMLDefinition.DRAW_POLYLINE, redrawPolylines);
geomaxXMLHandler.addGeomaxEventListener(geomaxXMLDefinition.MESSAGE_EVENT, displayMessage);

realTimeRefresh = new GeomaxAutoRefresh('realTimeRefresh');
realTimeRefresh.setRequestGenerator(generateRealTimeRequest);
//realTimeRefresh.setDelay(10000);
realTimeRefresh.run();