RegisterNamespace('NPR.Stations.Coverage');

NPR.Stations.Coverage.Layer = new VEShapeLayer();
NPR.Stations.Coverage.ResultsElement = null;
NPR.Stations.Coverage.StationsLoaded = 0;
NPR.Stations.Coverage.SearchValue = null;

// Clears the current coverage area displayed on the map
NPR.Stations.Coverage.Clear = function()
{
    // Remove coverage
    for(var stationId in stations)
    {
        stations[stationId].HideCoverage();
    }
    
    // Remove stations
    for(var stationId in stations)
    {        
        stations[stationId].HidePushpin();
    }
    
    if(NPR.Stations.Coverage.ResultsElement)
    {
        NPR.Stations.Coverage.ResultsElement.innerHTML = ''; 
    }
    
    stations = [];
    NPR.Stations.Coverage.StationsLoaded = 0;
}

NPR.Stations.Coverage.OnFindComplete = function(shapeLayer, findResults, places, moreResults, errorMessage)
{
    if (!places || places.length == 0)
    {
        NPR.Stations.Coverage.ResultsElement.innerHTML = 'Location not found.';
    }
    else if (places.length == 1)
    {
        // BUG 9526: Place names that don't match return High Plains Public Radio
        if (places[0].Name != 'United States')
        {
            NPR.Stations.Coverage.SearchLatLong(places[0].LatLong.Latitude, places[0].LatLong.Longitude);
        }
        else
        {
            NPR.Stations.Coverage.ResultsElement.innerHTML = 'Location not found.';
        }
    }
    else if(places.length > 1)
    {
        // Build the ambiguous list
        var details = '<h2>Did you mean?</h2>';
        details += '<ul class="AmbiguousAddresses">';
        
        for(var i = 0; i < places.length; i++)
        {
            details += '<li><a href="#" onclick="try { document.getElementById(\'q\').value = \'' + places[i].Name.replace("'", "\\'") + '\'; } catch(e) {} NPR.Stations.Coverage.SearchLatLong(' + places[i].LatLong.Latitude + ',' + places[i].LatLong.Longitude + '); return false;">' + places[i].Name + '</a></li>';
        }
        
        details += '</ul>';
        
        NPR.Stations.Coverage.ResultsElement.innerHTML = details;
    }
}

NPR.Stations.Coverage.OnLoadCoverageComplete = function()
{
    // Make sure we've loaded all the stations
    if(++NPR.Stations.Coverage.StationsLoaded >= NPR.Stations.GetStationCount())
    {
        // Ensure we've found at least one station
        if(NPR.Stations.GetStationCount() == 0)
        {
            NPR.Stations.Coverage.ResultsElement.innerHTML = '<p>No NPR Stations could be found in your area.</p>';
            return;
        }
        
        var currentStationNumber = 1;
        var polygons = new Array();

        var html = '';  
        
        for(var stationId in stations)
        {
            // Get the current station
            var station = stations[stationId];
            
            // Ensure station has a valid latitude and longitude
            if(station.Position != null)
            {
                // Set the station's number
                station.Number = currentStationNumber++;
                
                // Get the HTML for the station
                html += station.GetResultsHtml();
                
                // Add the icon to the map
                station.ShowPushpin();
                
                // Store the polygons so that later we can ensure a good map view
                if(station.Polygons.length > 0)
                {
                    polygons.push(station.Polygons[0]);
                }
            }
        }
        
        NPR.Stations.Coverage.ResultsElement.innerHTML = html;
        
        // Set the map view to include all the specifed polygons
        if(polygons.length > 0 && NPR.Stations.MapDisplayed)
        {
            map.SetMapView(polygons);
        }
    }
}

NPR.Stations.Coverage.OnLoadStationsComplete = function()
{
    if(NPR.Stations.GetStationCount() > 0)
    {
        for(var stationId in stations)
        {
            stations[stationId].LoadCoverage(NPR.Stations.Coverage.OnLoadCoverageComplete);
        }
    }
    else
    {
        NPR.Stations.Coverage.OnLoadCoverageComplete();
    }
}

NPR.Stations.Coverage.ParseQueryString = function()
{
    var queryParams = GetQueryParameters();
    
    // Perform search if query parameters contain search terms    
    if(queryParams['q']) {
        var q = decodeURIComponent(queryParams['q']);
        
        var directions = q.split(' to ');
        if (directions.length == 2) {
            document.getElementById('txtStartAddress').value = directions[0];
            document.getElementById('txtEndAddress').value = directions[1];
            
            showTab('nprRoadTrip');
            NPR.Stations.Directions.GetDirections(document.getElementById('txtStartAddress').value, document.getElementById('txtEndAddress').value, document.getElementById('nprRoadTripResults'));
        }
        else {
            document.getElementById('q').value = q;
            NPR.Stations.Coverage.Search(q, document.getElementById('findAStationResults'));
        }
    }
}

// Search for all stations near the specified value (address, zip code, or call letters)
NPR.Stations.Coverage.Search = function(value, resultsElement)
{
	// Save the search term to be used later if API returns no results. 
	NPR.Stations.Coverage.SearchValue = value;
	
    // Save the element that will be populated with the list of stations
    NPR.Stations.Coverage.ResultsElement = resultsElement;
    
    // Clear previous search
    NPR.Stations.Coverage.Clear();
    
    // Display a loading message
    NPR.Stations.Coverage.ResultsElement.innerHTML = 'Loading...';
    
    // trim the input string before parsing it
    value = value.replace(/^\s+|\s+$/g,"");
    
    if(value.match(/^\d{5}([\-]\d{4})?$/))
    {
        // We have a zip code
        NPR.Stations.Coverage.SearchPostalCode(value);
    }
    else if(value.match(/^[WwKk][A-Za-z]{2,3}$/))
    {
        // We have a station or network
        NPR.Stations.Coverage.SearchCallLetters(value);
    }
    else if(value.match(/^[WwKk][A-Za-z]{3}.[AaFf][Mm]$/))
    {
        // We have a station or network
        var callAndBand = value.split(/\W/);
        NPR.Stations.Coverage.SearchCallLettersAndBand(callAndBand[0], callAndBand[1]);
    }
    else
    {
    	// Search via network, if no results, then by Geocode later
    	NPR.Stations.Coverage.SearchNetwork(value);
    }
}

NPR.Stations.Coverage.SearchLatLong = function(latitude, longitude)
{
    var stationFinderUri = '/templates/xanadu/view/api/stations.php';
    stationFinderUri += '?lat=' + Math.abs(parseFloat(latitude));
    stationFinderUri += '&lon=' + Math.abs(parseFloat(longitude));
    
    NPR.Stations.Coverage.SearchWorker(stationFinderUri);
}

NPR.Stations.Coverage.SearchCityState = function(searchText)
{
    var cityState = searchText.split(',');

    if (cityState.length == 2)
    {
        var stationFinderUri = '/templates/xanadu/view/api/stations.php';
        stationFinderUri += '?city=' + cityState[0].replace(/^\s+|\s+$/g,"");
        stationFinderUri += '&state=' + cityState[1].replace(/^\s+|\s+$/g,"");
        
        NPR.Stations.Coverage.SearchWorker(stationFinderUri);
    }
    else
    {
        NPR.Stations.Coverage.ResultsElement.innerHTML = "Sorry, we don't understand your request. Please try again.";
    }
    
    
}

NPR.Stations.Coverage.SearchNetwork = function(network)
{
    var stationFinderUri = '/templates/xanadu/view/api/stations.php';
    stationFinderUri += '?network=' + network;
    
    NPR.Stations.Coverage.SearchWorker(stationFinderUri);
}

NPR.Stations.Coverage.SearchCallLetters = function(callLetters)
{
    var stationFinderUri = '/templates/xanadu/view/api/stations.php';
    stationFinderUri += '?callLetters=' + callLetters;
    
    NPR.Stations.Coverage.SearchWorker(stationFinderUri);
}

NPR.Stations.Coverage.SearchCallLettersAndBand = function(callLetters, band)
{
    var stationFinderUri = '/templates/xanadu/view/api/stations.php';
    stationFinderUri += '?callLetters=' + callLetters;
    stationFinderUri += '&band=' + band;
    
    NPR.Stations.Coverage.SearchWorker(stationFinderUri);
}

NPR.Stations.Coverage.SearchPostalCode = function(postalCode)
{
    var stationFinderUri = '/templates/xanadu/view/api/stations.php';
    stationFinderUri += '?zip=' + postalCode;
    
    NPR.Stations.Coverage.SearchWorker(stationFinderUri);
}

NPR.Stations.Coverage.SearchByGeocode = function()
{
	if (NPR.Stations.MapDisplayed)
    {
		// Geocode the address
		var value = NPR.Stations.Localize(NPR.Stations.Coverage.SearchValue);
	    map.Find(null, value, null, null, 0, 10, false, false, false, false, NPR.Stations.Coverage.OnFindComplete); 
    }
    else
    {
        NPR.Stations.Coverage.SearchCityState(NPR.Stations.Coverage.SearchValue);
    }
}

NPR.Stations.Coverage.SearchWorker = function(stationFinderUri)
{	
	NPR.Stations.Coverage.ResultsElement.innerHTML = 'Loading...';
    
    var xmlHttpRequest = GetXMLHttpRequest();

    xmlHttpRequest.onreadystatechange = function()
    {
        if(xmlHttpRequest.readyState == 4)
        {
            if(xmlHttpRequest.status == 200)
            {
                var stationElement = xmlHttpRequest.responseXML.getElementsByTagName('station');
                
                /* 
                 * API returns an empty station node when no results are found necessitating 
                 * the getAttribute call (to determine if any real results are returned).
                 * If no valid results are found and this is a search for network then
                 * attempt to geocode the search value. 
                 */
                
                if(stationElement.length >= 1 && stationElement[0].getAttribute('id') != null)
                {
	                for(var i = 0; i < stationElement.length; i++)
	                {
	                    try
	                    {
	                        var station = NPR.Stations.Station.FromDom(stationElement[i]);
	                        stations[station.Id] = station;
	                    }
	                    catch(ex)
	                    {
	                    }          
	                }
                }
                else if (stationFinderUri.indexOf('network=') != -1) 
                {
                	NPR.Stations.Coverage.SearchByGeocode();
                	
                	//a second AJAX call will result from SearchByGeocode, no need to finish here, so just return
                	return;
                }

            }
           
            NPR.Stations.Coverage.OnLoadStationsComplete();
        }      
    }
    
    // TODO: No need for proxy once in production @ NPR. Remove this line. 
    //stationFinderUri = 'Proxy.ashx?uri=' + encodeURIComponent(stationFinderUri);
    //stationFinderUri = stationFinderUri + '&apiKey=' + NPR.Stations.Settings.APIKey;
    xmlHttpRequest.open("GET", stationFinderUri);
    xmlHttpRequest.send(null);
}