﻿/**
 *  MapControl, controls Flash/HTML interaction and news/events/groups updating
 *  
 *  @author     Thomas J Bradley <hey@thomasjbradley.ca>
 *  @package    _scripts
 *  @version    1.0
 */
var MapControl = {

    /**
     *  Holds a jQuery reference to the country list drop-down
     */
    countryBox: null,
 
    /**
     *  Holds a Dom reference to the Flash movie
     */
    flash: null,

    /**
     *  A copy of the new-item div, used as a template, for populating individual news items
     */
    newsTemplate: null,

    /**
     *  A copy of the event-item div, used as a template, for populating individual event items
     */
    eventTemplate: null,

    /**
     *  A copy of the group-item div, used as a template, for populating individual group items
     */
    groupTemplate: null,
    
    /**
     *  The template for holding the no news articles
     */
    noNewsTemplate: null,

    /**
     *  The default value for the drop-down
     */
    ddDefaultValue: 'Select your country',

    /**
     *  Holds a jQuery reference to the add button
     */
    addButton: null,
    
    /**
     *  The base Urls for the different ajaxed-in items
     */
    baseUrlNews: '/Community/News',
    baseUrlEvents: '/Community/Event',
    baseUrlGroups: '/Community/News',

    /**
     *  Initalises the control be setting references and templates
     *  Adds an event handler to the drop box
     *
     *  @param  string  flashId             The id/name of the Flash movie to interact with
     *  @param  string  addButtonSelector   The jQuery/Css selector for the add button
     *
     *  @return void
     */
    Init: function(flashId, addButtonSelector)
    {
        MapControl.countryBox = $('.countrylist');

        MapControl.newsTemplate = $('#news .col').eq(0).clone();
        MapControl.eventTemplate = $('#events .col').eq(0).clone();
        MapControl.groupTemplate = $('#groups .col').eq(0).clone();

        var isIE = navigator.appName.indexOf("Microsoft") != -1;
        MapControl.flash = (isIE) ? document.all[flashId] : document[flashId];

        MapControl.addButton = $(addButtonSelector);

        if(MapControl.countryBox.val() == MapControl.ddDefaultValue)
        {
            MapControl.addButton.hide();
        }

        MapControl.countryBox.change(function()
        {
            MapControl.SetCountry($(this).val(), true);
        });
        
        MapControl.noNewsTemplate = $('.no-news').clone();
        MapControl.noNewsTemplate.show();
        $('.no-news').remove();
    },

    /**
     *  Sets the country drop-box and alerts Flash if required
     *  Makes and Ajax request for news/events/groups from a specific country
     *
     *  @param  string  name        The full country name, proper spaces and captialisation
     *  @param  bool    alertFlash  Should the Flash movie be alerted to the country change
     *
     *  @return void
     */
    SetCountry: function(name, alertFlash)
    {
        MapControl.countryBox.val(name);
        $.uniform.update();
        
        if(MapControl.countryBox.val() == MapControl.ddDefaultValue)
        {
            MapControl.addButton.hide();
        }
        else
        {
            MapControl.addButton.show();
        }
        
        if(alertFlash)
        {
            MapControl.SetFlashCountry(name);
        }

        $.ajax({
            type: 'POST',
            data: '{category:"' + name + '"}',
            url: '/WebServices/MapService.asmx/GetCategoryRecent',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data)
            {
                var content = jQuery.parseJSON(data.d);
                MapControl.DisplayNews(content.news);
                MapControl.DisplayEvents(content.events);
                MapControl.DisplayGroups(content.groups);
                
                var api = $('div.tabbed ul.tabs').tabs();
                api.click('#news');
            },
            error: function(xhr){}
        });
    },

    /**
     *  Alerts the Flash movie to the change in country
     *
     *  @param  string  name    The full country name, proper spaces and captialisation
     *
     *  @return void
     */
    SetFlashCountry: function(name)
    {
        MapControl.flash.sendTextToFlash(name);
    },

    /**
     *  Makes a copy of the news template for each news item returned from the Ajax request
     *  Populates the item fields and adds it to the news block
     *  Displays a no news info box with links to events/groups if no recent news
     *
     *  @param  array   newsData    Contains a series of news objects to populate the template with
     *
     *  @return void
     */
    DisplayNews: function(newsData)
    {
        var totalNews = newsData.length;
        var newsBlock = $('#news');
        var moreNews = $('<div id="more-news" class="align-right more" style="clear: both;">' +
			'<a href="/Community/Local_Groups/NewsList.aspx" class="more"><span>More</span></a>' +
			'</div>');

        newsBlock.html('');

        for(var i = 0; i < totalNews; i++)
        {
            var newsItem = MapControl.newsTemplate.clone();
            $('.title', newsItem).html(newsData[i].title);
            $('.author .time', newsItem).html(newsData[i].published);
            $('.author .name', newsItem).html(newsData[i].author);
            $('.summary', newsItem).html(newsData[i].summary);
            $('a', newsItem).attr('href', MapControl.baseUrlNews+newsData[i].url);
                       
            if(i == totalNews -1)
            {
                newsItem.addClass('col3');
            }
            
            newsBlock.append(newsItem);                        
        }
        
        if(totalNews <= 0)
        {
            var emptyNewsItem = MapControl.noNewsTemplate.clone();
            
            $('.no-news-events', emptyNewsItem).click(function()
            {
                var api = $('div.tabbed ul.tabs').tabs();
                api.click('#events');
                return false;
            });
            $('.no-news-groups', emptyNewsItem).click(function()
            {
                var api = $('div.tabbed ul.tabs').tabs();
                api.click('#groups');
                return false;
            });
            
            newsBlock.append(emptyNewsItem);        

        }
        newsBlock.append(moreNews);
    },

    /**
     *  Makes a copy of the event template for each event item returned from the Ajax request
     *  Populates the item fields and adds it to the events block
     *
     *  @param  array   eventsData    Contains a series of event objects to populate the template with
     *
     *  @return void
     */
    DisplayEvents: function(eventsData)
    {
        var totalEvents = eventsData.length;
        var eventsBlock = $('#events');
        eventsBlock.html('');

        var moreEvents = $('<div id="more-events" class="align-right more" style="clear: both;">' +
			'<a href="/Community/Local_Groups/Events.aspx" class="more"><span>More</span></a>' +
			'</div>');

        for(var i = 0; i < totalEvents; i++)
        {
            var eventsItem = MapControl.eventTemplate.clone();
            $('.title', eventsItem).html(eventsData[i].title);
            $('.author .time', eventsItem).html(eventsData[i].published);
            $('.author .name', eventsItem).html(eventsData[i].author);
            $('.summary', eventsItem).html(eventsData[i].summary);
            $('a', eventsItem).attr('href', MapControl.baseUrlEvents+eventsData[i].url);
            
            if(i == totalEvents -1)
            {
                eventsItem.addClass('col3');
            }
            
            eventsBlock.append(eventsItem);            
        }
        
        eventsBlock.append(moreEvents);
    },

    /**
     *  Makes a copy of the group template for each group item returned from the Ajax request
     *  Populates the item fields and adds it to the groups block
     *
     *  @param  array   groupsData    Contains a series of group objects to populate the template with
     *
     *  @return void
     */
    DisplayGroups: function(groupsData)
    {
        var totalGroups = groupsData.length;
        var groupsBlock = $('#groups');
        var moreGroups = $('<div id="more-support" class="align-right more" style="clear: both;">' +
			'<a href="/Community/Local_Groups/NewsList.aspx" class="more"><span>More</span></a>' +
			'</div>');
        groupsBlock.html('');

        for(var i = 0; i < totalGroups; i++)
        {
            var groupsItem = MapControl.groupTemplate.clone();
            $('.title', groupsItem).html(groupsData[i].title);
            $('.author .time', groupsItem).html(groupsData[i].published);
            $('.author .name', groupsItem).html(groupsData[i].author);
            $('.summary', groupsItem).html(groupsData[i].summary);
            $('a', groupsItem).attr('href', MapControl.baseUrlGroups+groupsData[i].url);
            
            if(i == totalGroups -1)
            {
                groupsItem.addClass('col3');
            }
            
            groupsBlock.append(groupsItem);
        }
        
        groupsBlock.append(moreGroups);
    }
};

$(function()
{
    MapControl.Init('prototype', '.contribute');
});