jq(document).ready(function() { 

    competitors = []
    
    // Pull the competitor information out of the list we
    // put onto the page for non-JS browsers.
    jq("li.competitor-location").each(function() {                    
        that = jq(this);
        
        latitude = that.attr("latitude");
        longitude = that.attr("longitude");
        
        competitors.push({
            "latitude" : parseFloat(latitude),
            "longitude" : parseFloat(longitude),
            "name" : jq("span.competitor-name", this).text(),
            "country" : jq("span.competitor-country", this).text(),
            "link" : jq("a.competitor-link", this).attr("href"),
            "summary" : that.html()
        });
    });

    jq("#map_canvas").height("400px");    

    var map_centre = new google.maps.LatLng(20.766112,30.402344);

    var options = {
        zoom: 2,
        center: map_centre,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    var map = new google.maps.Map(document.getElementById("map_canvas"), options);

    reset_map = function() {
        map.panTo(map_centre);
        map.setZoom(2);
    };
    
    jq.each(competitors, function() {
        var point = new google.maps.LatLng(this["latitude"], 
                                           this["longitude"]
                                          );
        var marker = new google.maps.Marker({
            position: point,
            title:this["country"]
        });
        var infowindow = new google.maps.InfoWindow({
            content: this["summary"],
            maxWidth: 400
        });

        google.maps.event.addListener(infowindow, 'closeclick', function() {
            reset_map();
        });

        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map,marker);
        });
        
        marker.setMap(map);

    });
        
    // Now we have loaded the map, remove the plain HTML list and add map help text.
    jq("#competitor-listing").remove();
    
    jq("#map_canvas").after(
        jq("<p></p>").text("Click on a marker to view details for that competitor. ")
            .append(
                jq("<a></a>")
                    .text("Reset the map to default view.")
                    .attr('href','#')
                    .click(function(event) {
                        event.preventDefault();
                        reset_map();
                    })
            )
    );
    
 });

