/**** RECEIPTS VERIFICATION ****/
mozmarket.receipts.verify(function(verifier) {
    if (verifier.state instanceof verifier.states.NeedsInstall) {
        forcePurchase("You must install the app");
    }
    if (verifier.state instanceof verifier.states.NetworkError) {
        // it was some kind of network or server error
        // i.e., not the fault of the user
        // you may want to let the user in, but for a limited time
        forcePurchase("Network error :(");
    } else if (verifier.state instanceof verifier.states.InternalError) {
        // The verifier library itself got messed up; this shouldn't happen!
        // It's up to you if you want to reject the user at this point
        logToServer(verifier.app, verifier.error);
        forcePurchase("Unexpected error :(");
    } else if (verifier.state instanceof verifier.states.OK) {
        // Everything is cool
    } else {
        // Some other error occurred; maybe it was never a valid receipt, maybe
        // the receipt is corrupted, or someone is trying to mess around.
        // It would not be a bad idea to log this.
        logToServer(verifier.app, verifier.receiptErrors);
        forcePurchase("Your purchase is invalid; please purchase again, or reinstall from the Marketplace");
    }
});

function forcePurchase(reason) {
    // Of course, this is kind of terrible, but you can do better yourself ;)
    alert('Ondetoi PRO\n' + reason);
    window.location.href = 'http://marketplace.firefox.com/app/ondetoi-pro';
    return;
}

function logToServer(app, data) {
    try {
        app = JSON.stringify(app);
    } catch (e) {
        app = app + '';
    }
    try {
        data = JSON.stringify(data);
    } catch (e) {
        data = data + '';
    }
    var req = new XMLHttpRequest();
    req.open('POST', '/receipt-error-log');
    req.send('app=' + encodeURIComponent(app) + '&error=' + encodeURIComponent(data));
}

/**** RECEIPTS VERIFICATION ****/

var app_token = "bf0b5fbe7f5ce0221ad5defcf295e4d1";
var lat = "";
var lon = "";
var map = null;
var assetLayerGroup = null;
var points = [];

$(document).ready(function() {

    function call(topic) {
        $('#container').empty();
        $('#container').add('div').attr('id', 'mapa').empty().height('93%');



        var RedIcon = L.Icon.Default.extend({
            options: {
                //iconUrl: 'http://stuff.samat.org/Test-Cases/Leaflet/881-Marker-Subclassing/marker-icon-red.png'
                iconUrl: '../icons/map/select-marker.png'
            }
        });
        var redIcon = new RedIcon();

        map = L.map('mapa').setView([lat, lon], 15);

        L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
            maxZoom: 18,
            attribution: 'Map data &copy; 2011 OpenStreetMap contributors, Imagery &copy; 2011 CloudMade. Font Awesome by Dave Gandy'
        }).addTo(map);

        L.marker([lat, lon], {
            icon: L.AwesomeMarkers.icon({
                icon: 'spinner',
                prefix: 'fa',
                markerColor: 'red',
                spin: true
            })
        }).addTo(map).bindPopup("Ud. est&aacute; <b>aqu&iacute;</b>");


        paint_markers('bar', lat, lon, app_token, map);


        var popup = L.popup();



    }

    function paint_markers(topic, lat, lon, app_token, map) {
        for (i = 0; i < points.length; i++) {
            map.removeLayer(points[i]);
        }
        points = [];

        // categorias para iconos
        var ic = "";
        switch (topic) {
            case "bar":
                ic = "beer";
                ic_color = "pink";
                break;
            case "restaurante":
                ic = "cutlery";
                ic_color = "blue";
                break;
            case "pizza":
                ic = "dot-circle-o";
                ic_color = "green";
                break;
            case "banco":
                ic = "btc";
                ic_color = "purple";
                break;
            case "gimnasio":
                ic = "tachometer";
                ic_color = "orange";
                break;
            case "museo":
                ic = "trophy";
                ic_color = "darkred";
                break;
            case "hotel":
                ic = "suitcase";
                ic_color = "cadetblue";
                break;
            case "cafeteria":
                ic = "coffee";
                ic_color = "darkpurple";
                break;
            case "cine":
                ic = "film";
                ic_color = "darkgreen";
                break;
            case "farmacia":
                ic = "medkit";
                ic_color = "darkblue";
                break;

        }


        //lamada al API 11870
        //http://api.11870.com/api/v2/search?q=bar&lat=40.3941&lon=-3.7078&radius=1&appToken=bf0b5fbe7f5ce0221ad5defcf295e4d1&alt=json

        $.ajax({
            type: "GET",
            url: "http://api.11870.com/api/v2/search?q=" + topic + "&lat=" + lat + "&lon=" + lon + "&radius=1&appToken=" + app_token + "&alt=json",
            contentType: "application/json; charset=utf-8",
            dataType: "jsonp",
            async: false,
            success: function(data) {
                if (data.entries.length == 0) {
                    alert("Vaya tela de barrio el tuyo, no hay " + topic);
                    return;
                }
                console.log(data);

                data.entries.forEach(function(element) {
                    //console.log(element);
                    new_marker = element.extensions.georss_where.gml_point.gml_pos.split(" ");
                    //var point = L.marker([new_marker[0], new_marker[1]], {icon: L.AwesomeMarkers.icon({icon: 'spinner', prefix: 'fa', markerColor: 'red', spin:true}) }).addTo(map);
                    var point = L.marker(
                            [new_marker[0], new_marker[1]], {
                                icon: L.AwesomeMarkers.icon({
                                    icon: ic,
                                    prefix: 'fa',
                                    markerColor: ic_color
                                })
                            })
                        .addTo(map)
                        .bindPopup(
                            "<a href='" + element.id + "' target='_new'>" + element.title + "</a><br><i>" + element.summary + "</i><br><b>" + element.extensions.oos_telephone + "</b><br>" + element.extensions.oos_useraddress + "<i> (" + element.extensions.oos_subdependentlocality.name + ") </i>"
                        );
                    points.push(point);
                });
            }
        });
    }

    var options = {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 300000
    };


    //runtime
    $('#container').append("<progress></progress>");

    navigator.geolocation.getCurrentPosition(
        function(position) {
            lat = position.coords.latitude;
            lon = position.coords.longitude;
            console.log("lon " + lon);

            $('#info_sup').html("<small><small>" + lat.toFixed(2) + ", " + lon.toFixed(2) + "</small></small>");
            call('bar');
            $(".option").on("click", function() {
                paint_markers($(this).attr("valor"), lat, lon, app_token, map);
            });

        },
        function(error) {
            alert('OndeToiPRO  ERROR(' + error.code + '): ' + error.message);
            $('progress').hide();
            $('#container').prepend('<img id="theImg" src="icons/ondetoi/trollface.jpg" />');
            $('#container').prepend('<p>Habilita la Geolocalización de tu teléfono en Ajustes, por favor ..</p>');

        },
        options
    );

});
