// JScript File

//START function AddMapControls ********************
function AddMapControls() {
    //Advanced dragzoom
    //zoom in and out controlls
    //map.addControl(new GSmallMapControl());	                
    map.addControl(new GLargeMapControl());
    
    //gives user choice of swapping between map,sattelite or both(hybrid)
    map.addControl(new GMapTypeControl());
    
    //small navigation map
    map.addControl(new GOverviewMapControl(new GSize(200, 160)));
    
    //Add scale to map showing km & miles
    map.addControl(new GScaleControl());
    
    AddZoomControl(map);
}

//END function AddMapControls ********************

//START function getMarkerState ********************
function getMarkerState(TimeInSeconds){
    //calculate the tracking state
    var elapsedMIN = parseFloat(TimeInSeconds) / 60;
    
    if (elapsedMIN < 5) {
        return 1;
    }
    else  {
        if (elapsedMIN < 10) {
            return 2;
        }
        else {
            return 3;
        }
    }
}

//START function getMarkerState ********************


//START function GetImageName ********************
function GetImageName(direction, state, type) {
    if (type == "Direction") {
        var color = "";
        var headingID = 0;
        switch (state) {
            case 0:
                return "stop.png";
            case 1:
                color = "g";
                break;
            case 2:
                color = "y";
                break;
            case 3:
                color = "r";
                break;
        }
        
        headingID = parseInt(parseFloat(direction) / (360 / 16)) + 1;
        
        if (headingID > 16) {
            headingID = 16;
        }
        else {
            if (headingID < 1) {
                headingID = 1;
            }
        }
        return color + headingID + ".png";
    }
    else {
        var TrackIconName = "";
        if (type == "StartTrack") {
            TrackIconName = "trackstart.png";
        }
        else 
            if (type == "EndTrack") {
                TrackIconName = "trackend.png";
            }
            else {
                if (type == "MarkTrack") {
                    TrackIconName = "trackmarker.png";
                }
            }
        return TrackIconName;
    }
}

//END function GetImageName ********************


//START function getDateFromFormat ********************
/**
 * returns the GMT of the value if it matches the format.
 * @return If the date string matches the format string, it returns the
 * GMT of the date.
 * @param val the date string
 * @param format the format string
 * @return false if it is not a date, the date otherwise
 */
getDateFromFormat = function(val, format){
    var y;
    var m;
    var d;
    var h = 0;
    var i = 0;
    var s = 0;
    
    var spl = format.split(/[-\/\s\:]/);
    var valspl = val.split(/[-\/\s\:]/);
    var last_sep = 0;
    var last_val_sep = 0;
    for (var a = 0; a < spl.length; a++) {
        //verify that separators are the same
        last_sep += spl[a].length;
        last_val_sep += valspl[a].length;
        if (format.charAt(last_sep) != val.charAt(last_val_sep)) {
            return false;
        }
        last_sep++;
        last_val_sep++;
        //try a match
        switch (spl[a].toLowerCase()) {
            case 'yyyy':
                y = parseInt(valspl[a]);
                break;
            case 'yy':
                y = parseInt(2000 + (valspl[a] - 0));
                break;
            case 'mmm':
                for (m = 0; m < 12; m++) {
                    var m_name = DateFunction.monthNames[m].toLowerCase();
                    if (m_name == valspl[a].toLowerCase()) 
                        break;
                }
                m++;
                break;
            // *1 needed // parseInt bizzarre with august month? ex: 15/08/2006
            case 'mm':
                m = (valspl[a] * 1);
                break;
            case 'dd':
                d = (valspl[a] * 1);
                break;
            case 'h':
                h = (valspl[a] * 1);
                break;
            case 'i':
                i = (valspl[a] * 1);
                break;
            case 's':
                s = (valspl[a] * 1);
                break;
            default:
                return false;
        }
    }
    //check month
    if (m < 1 || m > 12) {
        return false;
    }
    //check day in month
    if (d < 1) {
        return false;
    }
    if (m == 4 || m == 6 || m == 9 || m == 11) {
        if (d > 30) {
            return false;
        }
    }
    else 
        if (m == 2) {
            if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) {
                if (d > 29) {
                    return false;
                }
            }
            else 
                if (d > 28) {
                    return false;
                }
        }
        else {
            if (m > 31) {
                return false;
            }
        }
    //check hours
    if (h < 0 || h > 23) {
        return false
    }
    //check minutes
    if (m < 0 || m > 59) {
        return false
    }
    //check seconds
    if (s < 0 || s > 59) {
        return false
    }
    
    return new Date(y, m - 1, d, h, i, s);
}

//END function getDateFromFormat ********************

//START function AddZoomControl ********************
function AddZoomControl(map){

    //simple dragzoom
    //  map.addControl(new GZoomControl({sColor:'#000',nOpacity:.3,sBorder:'1px solid yellow'}), new GControlPosition(G_ANCHOR_TOP_RIGHT,new GSize(10,30)));
    //http://dev.compuhouse.com/CHVTSweb/
    var zoombutton="<img src='" + WebRoot + "/Images/zoom-button.gif' />";
    var zoombuttonActive="<img src='" + WebRoot + "/Images/zoom-button-activated.gif' />";
    
    map.addControl(new GZoomControl(    /* first set of options is for the visual overlay.*/
    {
        nOpacity: .2,
        sBorder: "2px solid red"
    },    /* second set of optionis is for everything else */
    {
        sButtonHTML: zoombutton,
        sButtonZoomingHTML:zoombuttonActive,
        oButtonStartingStyle: {
            width: '16px',
            height: '16px'
        }
    }, null    /* third set of options specifies callbacks */
    //		{
    //			buttonClick:function(){display("Looks like you activated GZoom!")},
    //			dragStart:function(){display("Started to Drag . . .")},
    //			dragging:function(x1,y1,x2,y2){display("Dragging, currently x="+x2+",y="+y2)},
    //			dragEnd:function(nw,ne,se,sw,nwpx,nepx,sepx,swpx){display("Zoom! NE="+ne+";SW="+sw)}
    //		}
    ), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(23, 285)));
    
}

//END function AddZoomControl ********************

//START function createMarkerInfoWindowHTML ********************

function createMarkerInfoWindowHTML(point, icon, HTMLcontent){
    //Normal info window  example
    opts = {
        "icon": icon,
        "clickable": true,
        "zIndexProcess": importanceOrder
    };
    var marker = new GMarker(point, opts);
    GEvent.addListener(marker, "click", function(){
        marker.openInfoWindowHtml(HTMLcontent);
    });
    return marker;
}

//END function createMarkerInfoWindowHTML ********************

//START function createMarkerInfoWindowHTMLPanToPoint ********************
//Normal info window  example
function createMarkerInfoWindowHTMLPanToPoint(point, icon, HTMLcontent){
    opts = {
        "icon": icon,
        "clickable": true,
        "zIndexProcess": importanceOrder
    };
    var marker = new GMarker(point, opts);

    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(HTMLcontent);
    });    
    
    GEvent.addListener(marker, "dblclick", function(){
        map.panTo(point);
    });
    
    return marker;
}

function UpdateFuelTab() {
    if (http_request3.readyState == 4) {
        if (http_request3.status == 200) {
            var xmlDoc = http_request3.responseXML;

            if (xmlDoc.documentElement != null) {
                if (xmlDoc.getElementsByTagName("ErrorMessage").length == 1) {
                    alert(xmlDoc.getElementsByTagName("ErrorMessage")[0].firstChild.nodeValue);
                }
                else {
                    var trackid = xmlDoc.getElementsByTagName("TrackId")[0].firstChild.nodeValue;
                    var timestamp = xmlDoc.getElementsByTagName("TimeStamp")[0].firstChild.nodeValue;
                    // Hide the timestamprow
                    var timestamprow = document.getElementById('timestamprow_' + trackid);
                    timestamprow.style.display = "none";
                    // Show the just sent in row
                    var justsentinrow = document.getElementById('justsentinrow_' + trackid);
                    justsentinrow.style.display = "";
                    map.closeInfoWindow();
                }
            }
        }
        else {
            // Fejl ved request
            alert("System fejl. Kontakt Xyonmap.");
        }
    }
}

function submitFuel(strTrackId) {
    var fuelForm = document.getElementById('fuelform_' + strTrackId);
    var liter = fuelForm.liter.value;
    var price = fuelForm.price.value;
    var fueltype = fuelForm.fueltype.value;
    var comment = fuelForm.comment.value;
    var imei = fuelForm.imei.value;
    var trackid = fuelForm.trackid.value;
    var gpstimestamp = fuelForm.gpstimestamp.value;
    var odo = fuelForm.odo.value;
    
    var requestParameters =
    "liter=" + liter + "&price=" + price + "&fueltype=" + fueltype + "&comment=" + comment +
    "&imei=" + imei + "&trackid=" + trackid + "&gpstimestamp=" + gpstimestamp + "&odo=" + odo;
    makeRequest3("fuelsubmit.aspx", requestParameters, "fuel");
}

function getFuelForm(strTrackId, strFuelType, strIMEI, strLiter, strPris, strKommentar, strFuelTimestamp, strGpsTimeStamp, strODO) {
    // Here is a cheap way of making the select select the right box - 
    // not exactly futureproof but will do the job
    var selected;
    if (strFuelType == 2) { selected = ['', 'selected']; }
    else { selected = ['selected', '']; }
    // Make the null values eatable for the form
    // if we are not displaying the timestamp line we should add an extra line
    if (strFuelTimestamp == "") { timestampDisplay = "none"; extraLine = "<br/>"; }
    else { timestampDisplay = ""; extraLine = ""; }

    var fuelTable = [
    '<form id="fuelform_' + strTrackId + '"><table>',
    '<tr>',
    '<td>Br\u00E6ndstof&nbsp;</td>',
    '<td><input id="liter" type="text" style="text-align:right" value="' + strLiter + '" size="12"/>&nbsp;Liter</td>',
    '</tr><tr>',
    '<td>Pris</td>',
    '<td><input id="price" type="text" style="text-align:right" value="' + strPris + '" size="12"/>&nbsp;DKr</td>',
    '</tr><tr>',
    '<td>Type</td>',
    '<td><select id="fueltype">',
    '<option value=1 ' + selected[0] + '>Benzin</option>',
    '<option value=2 ' + selected[1] + '>Diesel</option>',
    '</select></td>',
    '</tr><tr>',
    '<td valign="top">Kommentar</td>',
    '<td><textarea id="comment" cols="15" rows="2">' + strKommentar + '</textarea></td>',
    '</tr><tr id="timestamprow_' + strTrackId + '" style="display:' + timestampDisplay + '">',
    '<td>Indtastet</td>',
    '<td style="font-size:10pt"><div id="timestampcell_' + strTrackId + '">' + strFuelTimestamp + '</div></td>',
    '</tr><tr id="justsentinrow_' + strTrackId + '" style="display:none">',
    '<td></td><td style="font-size:10pt; font-style:italic;">Indsendt tidligere i dag</td>',
    '</tr><tr>',
    '<td></td><td>',
    '<input onclick="javascript:submitFuel(' + strTrackId + ')" type="button" value="Send" width="10"/>',
    '<input id="trackid" type="hidden" value="' + strTrackId + '" />',
    '<input id="imei" type="hidden" value="' + strIMEI + '" />',
    '<input id="gpstimestamp" type="hidden" value="' + strGpsTimeStamp + '" />',
    '<input id="odo" type="hidden" value="' + strODO + '" />',
    '</td></tr>',
    '</table></form>',
    extraLine
    ];
    return fuelTable.join('');
}

//Normal info window  example
function createTabbedMarkerInfoWindowHTMLPanToPoint(point, icon, HTMLcontent1, HTMLcontent2) {
    opts = {
        "icon": icon,
        "clickable": true,
        "zIndexProcess": importanceOrder
    };
    var marker = new GMarker(point, opts);
    var label1 = "Br\u00E6ndstof";
    var html1 = HTMLcontent1;
    var label2 = "Info";
    var html2 = HTMLcontent2;

    var infoTabs = [new GInfoWindowTab(label2, html2), new GInfoWindowTab(label1, html1)];

    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowTabsHtml(infoTabs);
    });

    GEvent.addListener(marker, "dblclick", function() {
        map.panTo(point);
    });

    return marker;
}

//END function createMarkerInfoWindowHTMLPanToPoint ********************

//START function getDateDK ********************

function getDateDK(sDate){
    //"dd-mm-yyyy"
    var ldate = getDateFromFormat(sDate, "dd-mm-yyyy h:i:s");
    return ldate.toLocaleString();
}

//END function getDateDK ********************

//START function decodeLine ********************

// Decode an encoded polyline into a list of lat/lng tuples.
function decodeLine(encoded){
    var len = encoded.length;
    var index = 0;
    var array = [];
    var lat = 0;
    var lng = 0;
    
    while (index < len) {
        var b;
        var shift = 0;
        var result = 0;
        do {
            b = encoded.charCodeAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        }
        while (b >= 0x20);
        var dlat = ((result & 1) ? ~ (result >> 1) : (result >> 1));
        lat += dlat;
        
        shift = 0;
        result = 0;
        do {
            b = encoded.charCodeAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        }
        while (b >= 0x20);
        var dlng = ((result & 1) ? ~ (result >> 1) : (result >> 1));
        lng += dlng;
        
        array.push([lat * 1e-5, lng * 1e-5]);
    }
    return array;
}

//END function decodeLine ********************

//START function decodeLineToGLatLng ********************

function decodeLineToGLatLng(encoded){
    // Decode an encoded polyline into a list of lat/lng tuples.
    var array = decodeLine(encoded);
    var GLatLngArray = [];
    var point = null;
    
    for (var i = 0; i < array.length; i++) {
        point = new GLatLng(array[i][0], array[i][1]);
        GLatLngArray.push(point);
    }
    
    return GLatLngArray;
}

//END function decodeLineToGLatLng ********************

//START function getEncodeLevels ********************

function getEncodeLevels(leveltype, latlngcount){
    //generate encode level
    var strResult = "";
    for (var i = 0; i < latlngcount; i++) {
        strResult += leveltype;
    }
    return strResult;
}

//END function getEncodeLevels ********************

//START function handleErrors_Direction ********************

function handleErrors_Direction(){
    var hasError = true;
    var message = "An unknown error occurred.";
    
    if (Directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS) 
        message = "No corresponding geographic location could be found" +
        " for one of the specified addresses." +
        "This may be due to the fact that the address is" +
        " relatively new, or it may be incorrect.";
    
    else 
        if (Directions.getStatus().code == G_GEO_UNAVAILABLE_ADDRESS) 
            message = "Unavailable Address:  The geocode for the given address " +
            " cannot be returned due to legal or contractual reasons.";
        
        else 
            if (Directions.getStatus().code == G_GEO_MISSING_ADDRESS) 
                message = "Missing Address: The address was either missing or had no value. ";
            
            else 
                if (Directions.getStatus().code == G_GEO_TOO_MANY_QUERIES) 
                    message = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
                
                else 
                    if (Directions.getStatus().code == G_GEO_UNKNOWN_DIRECTIONS) 
                        message = "The GDirections object could not compute directions between the points.";
                    
                    else 
                        if (Directions.getStatus().code == G_GEO_SERVER_ERROR) 
                            message = "A geocoding or directions request could not be" +
                            " successfully processed, yet the exact reason" +
                            " for the failure is not known.";
                        
                        else 
                            if (Directions.getStatus().code == G_GEO_MISSING_QUERY) 
                                message = "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.";
                            
                            else 
                                if (Directions.getStatus().code == G_GEO_BAD_KEY) 
                                    message = "The given key is either invalid or does not match" +
                                    " the domain for which it was given.";
                                
                                
                                else 
                                    if (Directions.getStatus().code == G_GEO_BAD_REQUEST) 
                                        message = "A directions request could not be successfully parsed.";
                                    
                                    
                                    else 
                                        if (Directions.getStatus().code == G_GEO_SUCCESS) 
                                            hasError = false;
    //message = "Directions received OK" 
    
    
    if (hasError == true) 
        alert("Message:" + message + "\n Error code: " + Directions.getStatus().code);
}

//END function handleErrors_Direction ********************

//START function DirectionsLoader ********************
function DirectionsLoader(){
    // alert("Directions loaded!"); 
    var DirectionPolyline = null;
    
    DirectionPolyline = Directions.getPolyline();
    
    var tmpbounds = new GLatLngBounds();
    if (DirectionPolyline != null) {
        map.addOverlay(DirectionPolyline);
        tmpbounds = DirectionPolyline.getBounds();
        
        if (bounds != null) {
            if (!bounds.containsBounds(tmpbounds) && (tmpbounds != null)) {
                //Add the new bounds to the existing bounds
                bounds.extend(tmpbounds.getSouthWest());
                bounds.extend(tmpbounds.getNorthEast());
            }
        }
        else {
            bounds = tmpbounds;
        }
    }
    map.setZoom(map.getBoundsZoomLevel(bounds));
    map.setCenter(bounds.getCenter());
}

//END function DirectionsLoader ********************

//START function getInnerText ********************

function getInnerText(node){
    if (typeof node.textContent != 'undefined') {
        return node.textContent;
    }
    else 
        if (typeof node.innerText != 'undefined') {
            return node.innerText;
        }
        else 
            if (typeof node.text != 'undefined') {
                return node.text;
            }
            else {
                switch (node.nodeType) {
                    case 3:
                    case 4:
                        return node.nodeValue;
                        break;
                    case 1:
                    case 11:
                        var innerText = '';
                        for (var i = 0; i < node.childNodes.length; i++) {
                            innerText += getInnerText(node.childNodes[i]);
                        }
                        return innerText;
                        break;
                    default:
                        return '';
                }
            }
}

//END function getInnerText ********************

//START  function importanceOrder ***********
function importanceOrder(marker, b){
    return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance * 1000000;
}

//END  function importanceOrder *********** 
//START function orderOfCreation *************
function orderOfCreation(marker, b){
    return 1;
}

//END function orderOfCreation *************
//START  function inverseOrder***********
function inverseOrder(marker, b){
    return -GOverlay.getZIndex(marker.getPoint().lat());
}

//END function inverseOrder***********

