RegisterNamespace('NPR.Stations.Station');

NPR.Stations.Station = function()
{
    // Private Members
    var self = this;
    var xmlHttpRequest = null;
    
    // Public Properties
    this.Band = null;
    this.CallLetters = null;
    this.MemberStatus = null;
    this.OrgDisplayName = null;
    this.CoverageUri = null;
    this.Frequency = null;
    this.Id = null;
    this.GroupId = null;
    this.Number = 0;
    this.OrganizationTagline = '';
    this.Polygons = new Array();
    this.Position = null;
    this.Pushpin = null;
    this.SignalStrength = -1;
    this.StandardTagline = '';
    this.StatusId = null;
    this.TranslatorCallLetters = null;
    this.TranslatorBand = null;
    this.Uris = new Array();	
    
    // Public Methods
    this.GetDisplayName = function()
    {
        return self.CallLetters + '-' + self.Band + ': ' + self.Frequency;
    }
    
    this.GetInfoBoxHtml = function()
    {
		var html = '<span class="close"><a href="javascript:map.HideInfoBox();"><img alt="close" src="http://media.npr.org/images/close.png" /></a></span>';
        html += self.StandardTagline == '' ? '' : '<p class="tagline">' + self.StandardTagline + '</p>';

        var orgHomeUrl = '';
        var orgHomeUrlTitle = '';
        for(var i = 0; i < self.Uris.length; i++)
        {
            if (self.Uris[i].Type == 1)
            {
                orgHomeUrl = self.Uris[i].Uri;
                orgHomeUrlTitle = self.Uris[i].Title;
                break;
            }
        }

  		if (orgHomeUrl != '') {
	    	html += '<p><a href="' + orgHomeUrl + '" target="_blank">NPR Station Profile</a></p>';
	    }

        
        // Add the station profile link
  		if(orgHomeUrl != '')
  		{
        	html += '<p class="stationProfileDescription">Find the station\'s broadcast schedule, send the station a message, and pledge support at the station\'s profile page</p>';
        	html += '<p><a href="' + orgHomeUrl + '" target="_blank">' + orgHomeUrlTitle + '</a></p>';
	    }
        
        return html;
    }
    
    this.GetPushpinHtml = function()
    {
        // NOTE: <a> tag not allowed here. Virtual Earth wraps the HTML specified here with its own <a> tag.
        var html = '<span class="pushpin"><img class="tower" src="' + NPR.Stations.Settings.StationPushpinImageUri + '" />'
        
        if(self.Number != 0)
        {
            html += '<span class="pushpinNumber">' + self.Number + '</span>';
        }
        
        html += '</span>';
        return html;
    }
    
    this.GetResultsHtml = function()
    {
        var orgHomeUrl = '';
        var orgHomeUrlTitle = '';
        for(var i = 0; i < self.Uris.length; i++)
        {
            if (self.Uris[i].Type == 1)
            {
                orgHomeUrl = self.Uris[i].Uri;
                orgHomeUrlTitle = self.Uris[i].Title;
                break;
            }
        }

        var html = '<div class="station">';
        
        html += '<a class="pushpinLink" href="#" onclick="stations[\'' + self.Id + '\'].ShowInfoBox(); return false;" onmouseover="stations[\'' + self.Id + '\'].ShowCoverage(false);">';
        html += self.GetPushpinHtml();
        html += '</a>';
        
        html += '<div class="body">';
        
        html += '<h2>';
        html += self.OrgDisplayName;
        html += '<span class="moreInfo"><a href="#" onclick="stations[\'' + self.Id + '\'].ShowInfoBox(); return false;">more info</a></span>';
        html += '</h2>';
        
        html += '<h2 class="call">';
        html += self.GetDisplayName();
        html += '</h2>';
        
	    html += self.StandardTagline == '' ? '' : '<p class="tagline">' + self.StandardTagline + '</p>';
	    
	    html += '<p class="stationlinks">';
	    if (orgHomeUrl != '') {
			html += '<a href="' + orgHomeUrl + '" target="_blank">Station homepage</a>';
			html += ' | ';			
		}	    
		
		if (self.CallLetters != null && self.Band != null && self.MemberStatus != 'Non-Member - NPR') {
	    	html += "<a href=\"javascript:NPR.Stations.Station.ConfirmBox(\'" + self.CallLetters + "-" + self.Band + "\');\">Save as my NPR station</a></p>";
	    }
	    
	    switch (self.SignalStrength) {
	    	case 5:
	    		html += '<p class="strength">Strength: <img class="signalStrength" src="http://media.npr.org/images/stations/strong.gif" />';
	    		break;
	    	case 3:
	    		html += '<p class="strength">Strength: <img class="signalStrength" src="http://media.npr.org/images/stations/moderate.gif" />';
	    		break;
	    	case 1:
	    		html += '<p class="strength">Strength: <img class="signalStrength" src="http://media.npr.org/images/stations/weak.gif" />';
	    		break;
	    }
		
		// Add the view coverage link
	    if (NPR.Stations.MapDisplayed) {
	    	html += '<a href="#" onclick="stations[\'' + self.Id + '\'].ShowCoverage(true); return false;">View coverage</a>';
	    }
	    
	    html += '</p>';
	    html += '</div>';
	    html += '</div>';
    	
	    return html;
    }
    
    this.HideCoverage = function()
    {
        if (!NPR.Stations.MapDisplayed)
    	{
    		return;
    	}

        NPR.Stations.Coverage.Layer.Hide();
    }
    
    this.HideInfoBox = function()
    {
        if (!NPR.Stations.MapDisplayed)
    	{
    		return;
    	}


        map.HideInfoBox();
    }
        
    this.HidePushpin = function()
    {
        if (!NPR.Stations.MapDisplayed)
    	{
    		return;
    	}
        map.DeleteShape(self.Pushpin);
    }
    
    this.LoadCoverage = function(callback)
    {
        // Clear previous polygons
        self.HideCoverage();
        self.Polygons = new Array();
        
        var uri = self.CoverageUri;
        xmlHttpRequest = GetXMLHttpRequest();
        
        xmlHttpRequest.onreadystatechange = function()
        {
            if(xmlHttpRequest.readyState == 4)
            {
                if(xmlHttpRequest.status == 200)
                {
                    try
                    {
                        var latitude = xmlHttpRequest.responseXML.getElementsByTagName('station')[0].getAttribute('latitude');
                        var longitude = xmlHttpRequest.responseXML.getElementsByTagName('station')[0].getAttribute('longitude');
                        self.Position = new VELatLong(parseFloat(latitude), parseFloat(longitude));
                        
                        var spokes = xmlHttpRequest.responseXML.getElementsByTagName('spoke');
                        var strengths = new Object();
                        var maxStrength = 0;
                        
                        for(var i = 0; i < spokes.length; i++)
                        {
                            // Get the strength
                            var strength = parseInt(spokes[i].getAttribute('strength'));
                            maxStrength = Math.max(maxStrength, strength);
                            
                            // Get the position
                            var position = new VELatLong(parseFloat(spokes[i].getAttribute('latitude')), parseFloat(spokes[i].getAttribute('longitude')));
                            
                            if(!strengths[strength] || strengths[strength] == undefined)
                            {
                                strengths[strength] = new Array();
                            }
                            
                            strengths[strength].push(position);
                        }
                        
                        for(var strength in strengths)
                        {
                            // Add the first position again to close the polyline
                            strengths[strength].push(strengths[strength][0]);
                        
                            // Polygon
                            var polygon = new VEShape(VEShapeType.Polygon, strengths[strength]);
                            polygon.HideIcon();
                            polygon.SetFillColor(NPR.Stations.Settings.PolygonColor);
                            polygon.SetLineWidth(1);
                            polygon.SetLineColor(NPR.Stations.Settings.PolygonOutlineColor);
                            
                            self.Polygons.push(polygon);
                        }
                    }
                    catch(e)
                    {
                    }
                }
                
                callback(self);
            }
        }
        
        // TODO: No need for proxy once in production @ NPR. Remove these lines.
        //uri = "http://www.npr.org" + uri;
        //uri = 'Proxy.ashx?uri=' + encodeURIComponent(uri);
        
        xmlHttpRequest.open("GET", uri);
        xmlHttpRequest.send(null);
    }
    
    this.ShowCoverage = function(zoomToFit)
    {
    	if (!NPR.Stations.MapDisplayed)
    	{
    		return;
    	}
    
        if(zoomToFit)
        {
            self.ZoomToFit();
        }
        
        NPR.Stations.Coverage.Layer.DeleteAllShapes();
        
        for(var i = 0; i < self.Polygons.length; i++)
        {
            var polygon = self.Polygons[i].Clone();
            polygon.HideIcon();
            
            NPR.Stations.Coverage.Layer.AddShape(polygon);
        }
        
        self.Pushpin.SetZIndex(zIndex++);
        NPR.Stations.Coverage.Layer.Show();
    }
    
    this.ShowInfoBox = function()
    {
    	if (!NPR.Stations.MapDisplayed)
    	{
    		return;
    	}    
    
        self.ZoomToFit();
        self.Pushpin.SetZIndex(zIndex++);
        map.ShowInfoBox(self.Pushpin);
    }   
    
    this.ShowPushpin = function()
    {
        if (!NPR.Stations.MapDisplayed)
    	{
    		return;
    	}
    
        if(self.Pushpin == null)
        {
            self.Pushpin = new VEShape(VEShapeType.Pushpin, self.Position);
            self.Pushpin.SetCustomIcon(self.GetPushpinHtml());
            self.Pushpin.SetDescription(self.GetInfoBoxHtml());
            self.Pushpin.SetTitle('<h2>' + self.GetDisplayName() + '</h2>');
            
            map.AddShape(self.Pushpin);            
        }
    }

    this.ZoomToFit = function()
    {
        if (!NPR.Stations.MapDisplayed)
    	{
    		return;
    	}
    
        map.SetAnimationEnabled(false);
        map.SetMapView(self.Polygons);
        map.SetAnimationEnabled(true);
    }
}

NPR.Stations.Station.FromDom = function(element)
{
    var station = new NPR.Stations.Station();
    
    station.Band = element.getElementsByTagName('band')[0].firstChild.data;
    station.CallLetters = element.getElementsByTagName('callLetters')[0].firstChild.data; 
    station.CoverageUri = element.getElementsByTagName('coverage_url')[0].firstChild.data;
    station.Frequency = element.getElementsByTagName('frequency')[0].firstChild.data;

    if (element.getElementsByTagName('orgDisplayName')[0].firstChild != null)
    {
    	 station.OrgDisplayName = element.getElementsByTagName('orgDisplayName')[0].firstChild.data;
    }
    else
    {
    	 station.OrgDisplayName = '';
    }

    if (element.getElementsByTagName('group').length > 0)
    {
    	station.GroupId = element.getElementsByTagName('group')[0].getAttribute('id');
    }
 
    if (element.getElementsByTagName('memberStatus').length > 0)
    {
    	station.MemberStatus = element.getElementsByTagName('memberStatus')[0].firstChild.data;
    }
    
    if (element.getElementsByTagName('translator_callLetters').length > 0)
    {
    	station.TranslatorCallLetters = element.getElementsByTagName('translator_callLetters')[0].firstChild.data;
    }
    
    if (element.getElementsByTagName('translator_band').length > 0)
    {
    	station.TranslatorBand = element.getElementsByTagName('translator_band')[0].firstChild.data;
    }    
    
	if (station.TranslatorCallLetters != null)
	{    
    	station.Id = 'NPR_Stations_Station_' + station.TranslatorCallLetters + "_" + station.TranslatorBand;
    }
    else
    {
	    station.Id = 'NPR_Stations_Station_' + station.CallLetters + "_" + station.Band;
    }
    
    if (element.getElementsByTagName('signal')[0])
    {
    	station.SignalStrength = parseInt(element.getElementsByTagName('signal')[0].getAttribute('strength'));
    }
    
    var taglines = element.getElementsByTagName('tagline');
    if (taglines.length > 0)
    {
    	if (taglines[0].firstChild != null)
    	{
    		station.StandardTagline = taglines[0].firstChild.data;
    	}
    }    

    var urls = element.getElementsByTagName('url');
    for(var j = 0; j < urls.length; j++)
    {
        if(urls[j].getAttribute('title'))
        {
            var stationUri = new NPR.Stations.StationUri(urls[j].getAttribute('title'), urls[j].getAttribute('typeId'), urls[j].firstChild.data);
            station.Uris.push(stationUri);
        }
    }
    
    return station;
};

NPR.Stations.Station.ConfirmBox = function(callLetters) {
	var modalHtml = "<div class=\"localizationpop\">" + 
		                "<img src=\"http://media.npr.org/chrome/news/station_local_ex.gif\" />" + 
		                "<div class=\"bucketblock\">" + 
		                    "<h3><span>" + callLetters + "</span> is now your NPR station.</h3>" + 
		                    "<p>Your NPR station will appear at the top of each page. Click the station's logo to access audio streams, podcasts, station homepage, schedule, and more.</p>" + 
		                "</div>" + 
		                "<p class=\"buttons\"><a href=\"javascript:NPR.Stations.Station.SetStation('" + callLetters + "')\" class=\"ok\"></a><a href=\"\" class=\"cancel simplemodal-close\"></a></p>" + 
	                "</div> ";
	$.modal(modalHtml);
	
	$("#simplemodal-overlay").css("height", $(document).height());
};

NPR.Stations.Station.SetStation = function(callLetters) {
	$(window.location).attr('href', '/templates/stations/stations/cookies/stations_set_cookie.php?cookieValue=' + callLetters);
	NPR.metrics.event({
		category : 'Favorite',
		action : 'Station',
		label : callLetters
	});
};

