(function($) {
$.createGPX = function() {
    $("#gpxCreate,#createGPXLink").click(function(event) {
        if (!gpxGeneratorRoute.hasPoints()) {
            return displayError("You must have some points before you can " +
                "generate a GPX file. Click on the map to create the points.");
        }

        var routeTextDiv = $("#route");
        routeTextDiv.html("");
        $("<img class='centerImage' src='img/ajax-loader-loading.gif' />").appendTo(routeTextDiv);

        $.post("downloadGPX.php", generateGPXPostData(), function(data) {
            gpxGeneratorRoute.setGpxData(data);
            var safeData = data.replace(/</g, "&lt;").replace(/>/g, "&gt;");
            routeTextDiv.html("");
            var downloadFormHtml = generateGPXDownloadFormHTML();
            $(downloadFormHtml).appendTo(routeTextDiv);

            $("<pre id='gpxData'>" + safeData + "</pre>").appendTo(routeTextDiv);
        });

        return false;
    });

    function generateGPXPostData() {
        var data = {};

        data['author'] = $("#gpxAuthor").val();
        data['name'] = $("#gpxName").val();


        for (var index = 0; index < gpxGeneratorRoute.numOfPoints(); index++) {
            var lonLat = getLonLatFromPoint(gpxGeneratorRoute.getPoint(index));
            data["lat" + index] = lonLat.lat;
            data["lon" + index] = lonLat.lon;
        }

        return data;
    }

    function generateGPXDownloadFormHTML() {
        var downloadFormHtml = "<form method='POST' action='downloadGPX.php'>";
        downloadFormHtml += "<input type='hidden' name='author' value='" + $("#gpxAuthor").val() + "' />";
        downloadFormHtml += "<input type='hidden' name='name' value='" + $("#gpxName").val() + "' />";
        for (var index = 0; index < gpxGeneratorRoute.numOfPoints(); index++) {
            var lonLat = getLonLatFromPoint(gpxGeneratorRoute.getPoint(index));

            downloadFormHtml += "<input type='hidden' name='lat" + index + "' value='" + lonLat.lat + "'/>";
            downloadFormHtml += "<input type='hidden' name='lon" + index + "' value='" + lonLat.lon + "'/>";
        }
        downloadFormHtml += "<input type='submit' value='Download' />";
        downloadFormHtml += "</form>";

        return downloadFormHtml;
    }
}
})(jQuery);

function GarminPluginListener(domain, garminKey) {
    this.domain = domain;
    this.garminKey = garminKey;
    try {
        this.control = new Garmin.DeviceControl();
        if (this.control.isPluginInstalled()) {
            this.control.register(this);
            var unlocked = this.unlockPlugin();
            $('devices').innerHTML = "<span class='new'>NEW</span> connect a Garmin GPS to this computer and click the Tranfer button to begin transferring GPX data straight to device.";

            this.pluginInitialize = unlocked;
        }
        else {
            this.pluginInitialize = false;
        }
    }
    catch(e) {
        //Todo better loging of error if we alert this will get a popup when browser is not supported by plugin.
        //alert("Detecting plugin: " + e);
    }
}


GarminPluginListener.prototype.unlockPlugin = function() {
    return this.control.unlock( ["http://" + this.domain, this.garminKey] );
}

GarminPluginListener.prototype.findDevices = function() {
    try {
        //Hack get an unlocked exception if this is not here.
        this.unlockPlugin();
        this.control.findDevices();
    } catch(e) {
        displayError(e);
    }
}

GarminPluginListener.prototype.writeToDevice = function() {
    this.control.writeToDevice(gpxGeneratorRoute.getGpxData(), "gpxData.gpx");
}

GarminPluginListener.prototype.onFinishFindDevices = function(json) {
    var devices = json.controller.getDevices();

    if (json.controller.numDevices > 0) {
        $('devices').innerHTML = "Found GPS " + devices[0].getDisplayName() + " transfering GPX data to device. <br />" +
            "<img class='centerImage' src='img/ajax-loader-bar.gif' />";
        this.control.setDeviceNumber(0);
        this.writeToDevice();
    }
    else {
        $('devices').innerHTML = "Could not find a Garmin GPS device. Please check connection and try again."
    }
}

GarminPluginListener.prototype.onFinishWriteToDevice = function(json) {
    $('devices').innerHTML = "Connect a Garmin GPS to this computer and click the Transfer button to begin transferring GPX data straight to device.";
    displayMessage("File transferred to GPS device.");
}

 GarminPluginListener.prototype.onException = function(msg) {
    displayError("On Exception: " + msg.msg);
}