var gmarkers = [];
var map;
var stationinfo = new google.maps.InfoWindow({
    maxWidth: 200
});

// A function to create the marker and set up the event window
function createMarker(point, name, description, url, id) 
{
    var marker = new google.maps.Marker({
        position: point,
        clickable: true,
        title: name,
        map:map
    });
    google.maps.event.addListener(marker, "click", function() {
        var sHtml = '<p style="width:190px; white-space:normal; font-size:x-small!important">' + 
            '<a href="javascript:void(0)" onclick="loadStation(\'' + url + '\')" style="color:#3399cc">' + name + 
            '</a><br />' + description + '</p>';
        stationinfo.setContent(sHtml);
        stationinfo.open(map, marker);
    });
    // save the info we need to use later for the side_bar
    gmarkers[id] = marker;
    return marker;
}
function loadStation(href) {
    if (lat && lng) {
        href += '&lat=' + lat + '&long=' + lng;
    }
    top.location.href = href;
    return;
}
function loadTunerMap() {
    location.hash = 'tunermap';
    var $content = $('#content');
    var title = 'TunerMap&trade;';
    //titles.push($('#title').html());
    lists.push($content.html());
    //$('#title').html(title);
    $('#leftnav').show();
    
    var $map = $(document.createElement('div'));
    $map.attr('id', 'map_canvas').css({"width" : "100%", "height" : "380px"});
    $content.html('');
    $content.append($map);
    $content.show();
    
    var sanfran = new google.maps.LatLng(37.62510898062149,-122.1514892578125);
    var myOptions = {
              zoom: 7,
              center: sanfran,
              mapTypeControl: false,
              navigationControl: true,
              navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
              mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    google.maps.event.addListener(map,"idle",refreshMarkers.debounce(500));
    //loadMarkers();
    
    if (undefined != lat && undefined != lng) {
        var initialLocation = new google.maps.LatLng(lat, lng);
        map.setCenter(initialLocation);
    }
}

Function.prototype.debounce = function (threshold, execAsap) {
    var func = this, // reference to original function
    timeout; // handle to setTimeout async task (detection period)
    // return the new debounced function which executes the original function only once
    // until the detection period expires
    return function debounced ()
    {
        var obj = this, // reference to original context object
        args = arguments; // arguments at execution time
        // this is the detection function. it will be executed if/when the threshold expires
        function delayed ()
        {
            // if we're executing at the end of the detection period
            if( !execAsap )
                func.apply(obj, args); // execute now
                // clear timeout handle
                timeout = null; 
        };
        // stop any current detection period
        if (timeout)
            clearTimeout(timeout);
        // otherwise, if we're not already waiting and we're executing at the beginning of the detection period
        else if (execAsap)
            func.apply(obj, args); // execute now
        // reset the detection period
        timeout = setTimeout(delayed, threshold || 100); 
    };
};

function refreshMarkers() {
    for (var ii = 0; ii < gmarkers.length; ii++) {
        gmarkers[ii].setMap(null);
    }
    loadMarkers();
}

function loadMarkers() {
    if (map) {
        //get boundries
        var bounds = map.getBounds();
        if (bounds) {
            var swlat = bounds.getSouthWest().lat();
            var swlong = bounds.getSouthWest().lng();
            var nelong = bounds.getNorthEast().lng();
            var nelat = bounds.getNorthEast().lat();
            var host = (location.host.match(/^dev/)) ? 'http://devwww.tuner2.com/' : 'http://www.tuner2.com/';
            var data =  host + '/tuner/geo.json?stream_formats=icy&swlat='+swlat+'&nelat='+nelat+'&swlong='+swlong+'&nelong='+nelong;
            var proxy = location.pathname + '?ajaxUrl=' + encodeURIComponent(data);
            //get new markers
            var ListenEventsObject = {};
            var request = new XMLHttpRequest();
            request.open("GET", proxy, true);
            loading = 1;
            request.onreadystatechange = function() {
                if (request.readyState == 4) {     
                    //alert(request.responseText);
                    try {
                        ListenEventsObject = eval('('+ request.responseText + ')');
                        for (var le = 0, len = ListenEventsObject.listen_events.length; le < len; le++) {
                            var point = new google.maps.LatLng(ListenEventsObject.listen_events[le].point[1], 
                                ListenEventsObject.listen_events[le].point[0]);
                            var description  = ListenEventsObject.listen_events[le].description;
                            var name = ListenEventsObject.listen_events[le].name;
                            var id  = ListenEventsObject.listen_events[le].entry_id;
                            var url = ListenEventsObject.listen_events[le].url;
                            createMarker(point, name, description, url, id);
                        }
                    } catch(e) {
                        //alert(e + ' ' + request.responseText);   
                    }
                }
            }
            request.send(null);
        }
    }
}
