/*---------------------------------------------------------------------------------------
*
*  The purpose of this file is to create the front-end AJAX logic for the new
*   news center.
*
*  Author: Brad Quillen - brad.quillen@rightnow.com
*
*         Usage: loadPressRoom([TYPE],[AREA])
*  Requirements: [TYPE] must be:
*			"newscenter" - only load 2 articles for each [AREA]
*			"start"	     - only load 5 articles for each [AREA]
*			"go"	     - load all applicable articles for the [AREA]
*		 [AREA] must be:
*			"press" - load the press articles into a <ul> with id "press_area"
*			"news"  - load the news articles into a <ul> with id "news_area"
*
*	  Usage: loadRnTwitter([NUM_OF_TWEETS])
*  Requirements: [NUM_OF_TWEETS] - must be an integer between 1 and 200
*		 This function loads the data into a <ul> with id "rn-twitter" 
*
*/

// loadPressRoom() function
function loadPressRoom(type, area)
{
    if (type !== 'newscenter')
    {
    	// Get the Selected year and category from the page
        var selYear = jQuery("#"+area+"-year").val();
        var selCat  = jQuery("#"+area+"-category").val();
    }
    
    // If the page is first loaded, select all years and cats
    if (type == 'start' || type == 'newscenter')
    {
        selYear = 'all';
        selCat  = 'all';
    }

    // Sanitize the data so everything is URL safe
    selYear = escape(selYear);
    selCat  = escape(selCat);
    type    = escape(type);
    area    = escape(area);

    // Set the AJAX request engine page
    var url = 'http://www.rightnow.com/pressAjax.php';

    // Fade out the area that we are updating so everything appears at the same time.
    //  On the callback function, we'll start building the data
    jQuery("#"+area+"_area").fadeOut(500, function() {
    	    // Clear the area so we can append fresh content
            jQuery("#"+area+"_area").html("");
	    // Make the main AJAX request with the specified constraints
            jQuery.getJSON(url+'?year='+selYear+'&category='+selCat+'&type='+type+'&area='+area+'&callback=?', function(data,textStatus) {
	    	// If data.error exists, then there were no search results; write that out and return
                if (data.error) {
                	jQuery("#"+area+"_area").append("<em>No items matched your filter selections.</em>").fadeIn(500);
                	return;
                }
		// If the page is the specific Press or News pages, build out the full 
		//  listing with all the details
                if (type == 'start' || type == 'go')
                {
		    // Loop through each object returned from the AJAX call and write the li
                    jQuery.each(data, function() {
                        if (area == 'news') { publication = '<br>'+this['publication']+'<br>'; }
                        else if (area == 'press') { publication = ''; }
                        jQuery("#"+area+"_area").append("<li class='hentry'><h4 class='entry-title'><a href='"+this['linkHref']+"'>"+this['title']+"</a></h4><abbr class='published'>"+this['releaseDate']+"</abbr><br /><span class='location'>"+this['location']+"</span>"+publication+"<p class='entry-summary'>"+this['description']+" <a href="+this['linkHref']+" rel='bookmark nofollow' class='continue'>continue</a></p></li>");
                    });
                }
		// If the page is the newscenter, only display a simple link with the date after it
                else if (type == 'newscenter')
                {
		    // Loop through each object returned from the AJAX call and write the li
                    jQuery.each(data, function() {
                        jQuery("#"+area+"_area").append("<li class='hentry'><a href='"+this['linkHref']+"'>"+this['title']+"</a>, <abbr class='published'>"+this['releaseDate']+"</abbr></li>");
                    });
                }
            });
        });
    // Fade the area in after all the data is loaded to present it in a "pretty" way
    jQuery("#"+area+"_area").fadeIn(1500);
}

// loadRnTwitter() function
function loadRnTwitter(tweets)
{
	// Create the AJAX Request to the Twitter API, requesting JSONp data
	jQuery.getJSON('http://twitter.com/statuses/user_timeline/RightNowNews.json?count='+tweets+'&callback=?', function(data) {
		// For each "tweet":
		jQuery.each(data, function() {
			// Before posting the tweet we need to match and replace the URLs and Titter users and hashtags
			//  to create hyperlinks just as they are on twitter.com
			var tweet = this['text'];
			var RegExp = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i
			tweet = tweet.replace(RegExp,'<a href="$1">$1</a>');
			tweet = tweet.replace(/(^|\s)@(\w+)/g, '$1@<a href="http://www.twitter.com/$2">$2</a>');
			tweet = tweet.replace(/(^|\s)#(\w+)/g, '$1<a href="http://search.twitter.com/search?q=%23$2">#$2</a>');
			
			// Now we can write the tweet to the page
			jQuery("#rn-twitter").append("<li>"+tweet+"</li>");
		});
	});
}
/* NEW Press Release AJAX Filtering ----------------------------------------------------------
*
*
*
*/

// Load when the DOM is ready
jQuery(document).ready(function(){
	// Only the specific News and Press listing pages should have the 
	//  class 'newscenter'
	if(jQuery('body').hasClass('newscenter')){

		// Set the AJAX PHP Processor
		var url = 'http://www.rightnow.com/pressAjax.php';

		// Make the AJAX call to get populate the "Year" dropdown
		jQuery.getJSON(url+'?function=getYears&callback=?', function(data) {
			jQuery.each(data, function() {
				jQuery("#press-year").append("<option>"+this+"</option>");
				jQuery("#news-year").append("<option>"+this+"</option>");
				});
			});

		// Make the AJAX call to get populate the "Category" dropdown
		jQuery.getJSON(url+'?function=getCats&callback=?', function(data) {
			jQuery.each(data, function() {
				jQuery("#press-category").append("<option>"+this+"</option>");
				jQuery("#news-category").append("<option>"+this+"</option>");
				});
			});
		// Call the functions to load the press/news/twitter feeds
		loadPressRoom('start', 'press');
		loadPressRoom('start', 'news');
		loadRnTwitter(3);
	}
	// The main NewsCenter page has the class 'template-newscenter'
	//  so we'll make different function calls for them
	if (jQuery('body').hasClass('template-newscenter')){
		loadPressRoom('newscenter', 'press');
		loadPressRoom('newscenter', 'news');
		loadRnTwitter(3);
	}
});
