var manager = Seam.Component.getInstance("activityPathBean");
var editing = false;
var points = new Array(0);
var currentPath = null;
var currentPathName = null;
var serverDisconnected = false;


A4J.AJAX.onExpired = function(loc,expiredMsg){
    alert("You are discconected from the server, and will not be able to save any paths.  Please log out and back in.");
    serverDisconnected = true;
};

A4J.AJAX.onError = function(req,status,message) {
    alert("You are discconected from the server, and will not be able to save any paths.  Please log out and back in.");
    serverDisconnected = true;
};


function gotoAddress() {
    if (editing==true) {
        var answer=confirm("You are currently editing a path, click OK to discard your work and load the new path");
        if (!answer) {
            return;
        }
        editing=false;
        setCurrentPath(null, null);
    }
    // AJAX load the map 
    Seam.Remoting.loadingMessage = "Loading map, please wait";
    var startAddress = document.getElementById("startLocationTF").value;
    var geocoder = new GClientGeocoder();
    geocoder.getLocations(startAddress, function(returnResult) {
        if (returnResult.Status.code == G_GEO_SUCCESS) {
            // clear the existing polyline.
            clearMap();
            
            var place = returnResult.Placemark[0];
            //alert(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName + ", " + place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName);
            var zLevel = Math.min(3*place.AddressDetails.Accuracy,15);
            var center = new GLatLng(
                place.Point.coordinates[1],
                place.Point.coordinates[0]
                );
            map.setCenter(center, zLevel);

            listNearbyRoutes(place.Point.coordinates[1], place.Point.coordinates[0]);

        } else {
            alert(startAddress + " not found")
        }
    });
}

function listNearbyRoutes(lat, lon) {
    // set the lat and lng hidden form elements that are submited
    hiddenLat = document.getElementById("inputForm:latHiddenField");
    hiddenLng = document.getElementById("inputForm:lngHiddenField");
    hiddenLat.setAttribute("value", lat);
    hiddenLng.setAttribute("value", lon);
    // triger the partial refresh
    clickLink('inputForm:updateNearbyPathHiddenLink');
    // switch to the "Nearby" routes tab
    RichFaces.switchTab("inputForm:routesTabPanel", "inputForm:nearByPathTab", "nearByPathTab")
}

function onMapClick(overlay, latlng) {
    if (document.getElementById("autoScrollCheckBox").checked && 
        editing==true) {
        map.setCenter(latlng);
    }
    if (editing==true && points.length == 0) {
        clearMap();
        points.push(latlng);
        polyline = new GPolyline(latlng, "#0000ff", 4, 0.8);
        GEvent.addListener(polyline, "lineupdated", function(latlng) {
            onPolylineClick(latlng);
        });
        map.addOverlay(polyline);
        map.addOverlay(startMarker = new GMarker(latlng, {
            title:"Start Point"
        }));
        polyline.insertVertex(0,latlng);
        polyline.enableDrawing();
    }
//if (editing==true || points.length > 0) {
//    points.push(latlng);
//}
}

function onPolylineClick(latlng) {
    updateDistanceLabel();
}

function clearMap() {
    if (polyline != null) {
        polyline.disableEditing();
    }
    polyline = null;
    map.clearOverlays();
}

function createNewPathButtonClick() {
    if (serverDisconnected) {
        alert("You are discconected from the server, and will not be able to save any paths.  You must log out and back in before you can create a path");
        return;
    }
    if (!isAuthenticated) {
        answer=confirm("You must be logged in to save a path and calculate calories.  Click OK to register or Cancel to continue without the ability to save");
        if (answer) {
            window.location = "/registrationSuccessful.xhtml"
        }
    }
    if (!editing && polyline == null) {
        createNewPath();
    } else {
        answer=confirm("You are currently editing a path, click OK to discard your work and create a new path");
        if (answer) {
            createNewPath();
        }
    }
}

function askToRegister() {
    if (!isAuthenticated) {
        answer=confirm("You must be logged in to save a path, calculate calories or add shoes.  Click OK to register or Cancel to continue");
        if (answer) {
            window.location = "/registrationSuccessful.xhtml"
        }
    }
}
function createNewPath() {
    map.clearOverlays();
    points = new Array(0);
    document.getElementById("saveStatusLabel").innerHTML = null;
    setCurrentPath(null, null);
    editing=true;
}

function getPolyLine(activityPathID, activityPathName) {
    manager.getPolylineById(activityPathID, getPolyLineCallBack);
}

function setCurrentPath(newCurrentPath, activityPathName) {
    editing=false;
    if (newCurrentPath == "") {
        newCurrentPath = null;
    }
    var currentPath = newCurrentPath;
    var currentPathName = activityPathName;
    displayCurrentPathInfo(currentPath, currentPathName)
}

function displayCurrentPathInfo(pathId, pathName) {
    var nameDiv = document.getElementById("currentPathName");
    var name = document.createElement("h3");
    var link = document.createElement("a");
    //var href = document.createElement("href");
    if (pathId != null && pathName != null) {
        removeChildrenFromNode(nameDiv);
        var linkLocation = "/map-dataentry.xhtml?pathId=" + pathId;
        link.setAttribute('href', linkLocation);
        var linkText = document.createTextNode("(Want to Log Activity or Add This to My Routes?)");
        link.appendChild(linkText);

        var nameText = document.createTextNode(pathName);
        name.appendChild(nameText);

        nameDiv.appendChild(name);
        nameDiv.appendChild(link);
    } else {
        removeChildrenFromNode(nameDiv);
    }
}

function removeChildrenFromNode(node) {
    if(node.hasChildNodes()) {
        while(node.childNodes.length >= 1 ) {
            node.removeChild(node.firstChild);
        }
    }
}

function getPolyLineCallBack(result) {
    // check to see if this worked...if not...perms probably failed
    if (result == null) {
        alert("Could not load path, you probably dont have permission");
        return;
    }
    encodedPoints = result[0];
    encodedLevel = result[1];
    
    polyline = new GPolyline.fromEncoded(
    {
        color: '#0000ff',
        weight: 4,
        opacity: 0.8,
        points: encodedPoints ,
        levels: encodedLevel,
        zoomFactor: 2,
        numLevels: 18
    });
    GEvent.addListener(polyline, "lineupdated", function(latlng) {
        onPolylineClick(latlng);
    });

    map.setCenter(polyline.getVertex(0), 13);
    updateDistanceLabel();
    map.clearOverlays(); //clear the existing paths.
    map.addOverlay(polyline);

    // set currentPath to this path
    setCurrentPath(result[2], result[3]);

    listNearbyRoutes(polyline.getVertex(0).lat(), polyline.getVertex(0).lng());
}

function updateDistanceLabel() {
    if (document.getElementById("distanceLabel")) {
        var distanceKM = (polyline.getLength()/1000).toFixed(2);
        var distanceMiles = (polyline.getLength() * 0.000621371192).toFixed(2);
        document.getElementById("distanceLabel").innerHTML = distanceMiles;
        document.getElementById("distanceLabelKM").innerHTML = distanceKM;
    }
}

function endDrawing() {
    polyline.disableEditing();
    editing = false;
    map.removeOverlay(polyline);
    map.addOverlay(polyline);
    if (isAuthenticated) {
        displaySavePathDialog();
    }
}

function displaySavePathDialog() {
    document.getElementById('mp').component.show();
}

function undoLastPoint() {
    polyline.deleteVertex(polyline.getVertexCount()-1);
    polyline.enableDrawing();
}
   
function uploadMapPoints() {  
    Seam.Remoting.loadingMessage = "Saving map, please wait";
    // grey/disable button
    document.getElementById("savePathForm:saveMapPointsButton").disabled=true;
    //document.getElementById("savePathForm:saveMapPointsButton").style.color="grey";
    // display "Saving path" message
    document.getElementById("saveStatusLabel").innerHTML = "Status: Saving...";
    
    points = new Array();
    var name = document.getElementById("savePathForm:pathNameTF").value;
    var desc = document.getElementById("savePathForm:pathDescriptionTF").value;
    for (var i=0; i < document.forms['savePathForm']['savePathForm:viewableBy'].length; i++)  {
        if (document.forms['savePathForm']['savePathForm:viewableBy'][i].checked)  {
            var perm = document.forms['savePathForm']['savePathForm:viewableBy'][i].value;
        }
    }
    for (var i=0; i < polyline.getVertexCount(); i++) {
        points[i] = polyline.getVertex(i).toString();
    }
    manager.setMapPoint(points, name, desc, polyline.getLength(), 1, perm, checkMapPointCallBack);
}
            
function checkMapPointCallBack (result) {
    if (result > 0) {
        document.getElementById("saveStatusLabel").innerHTML = "Status: Successfully saved path";
        setTimeout('document.getElementById(\'mp\').component.hide()', 1500);
        setCurrentPath(null, null);
        document.getElementById("savePathForm:saveMapPointsButton").disabled=false;
        window.location = "map-dataentry.xhtml?pathId=" + result;
    }
    else {
        document.getElementById("saveStatusLabel").innerHTML = "ERROR: Could not save path.  Please try again";
        setCurrentPath(null, null);
        document.getElementById("savePathForm:saveMapPointsButton").disabled=false;
    //document.getElementById("saveMapPointsButton").style.color="grey";
    }
//TODO: Add a timer here.
}

function focusStartingPointTextField() {
    var startPointTF = document.getElementById("startLocationTF");
    if (startPointTF.value == startPointTF.defaultValue) {
        startPointTF.value = '';
    }
}

function getParamByName(name) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
        return "";
    else
        return results[1];
}

// Hidden button press
function clickLink(linkId)
{
    var fireOnThis = document.getElementById(linkId)
    if (document.createEvent)
    {
        var evObj = document.createEvent('MouseEvents')
        evObj.initEvent( 'click', true, false )
        fireOnThis.dispatchEvent(evObj)
    }
    else if (document.createEventObject)
    {
        fireOnThis.fireEvent('onclick')
    }
}



