/*
 * Load posts from specified blog feed, and display them in a div of class
 * blog_feed.  This is intentded to be shared between different pages and
 * sites (holding and live), each must have CSS rules for div.blog_feed,
 * div.blog_post, etc.  See holding site for example.
 *
 * In cases where there is no blog, or the feed is empty, or some other
 * error, load and display alternative content from get-feed-alternate.php.
 *
 * TODO localised blog feeds.  If we use WPML feed will just use /REQUEST_LANGUAGE/,
 * but Rio will need a specific URL here
 *
 */

// Find city and lang
var p=location.pathname.split('/');
var city=p[1];
var lang=p[2];

// --------------------------------------------------------------------
/*
 * Attempt to load RSS feed from this city's blog.  If nothing found, fall
 * back and load alternate content from get-feed-alternate.php.
 *
 * @param blog_url The URL to the human readable front page of the blog
 * @param feed_path The path needed to append to the blog_url to see the
 * RSS feed, eg "feed/".  Having this separated from blog_url allows us to
 * support off-site blogs which don't use Wordpress and have different feed
 * URLs.
 * @param count_posts The number of posts to return
 * @param site_status live or holding, calling site's status
 * @return JSON object of status and message
 *
 */
function load_blog_feed(blog_url,feed_path,count_posts, site_status) {

    // WPML-enabled blogs will have this sorted out, but Rio has a separate
    // blog for PT_BR and EN
    if ((city=='rio-de-janeiro' || city=='belo-horizonte' || city=='sao-paulo') && lang=='en') {
        blog_url='http://blog.limeandtonic.com/' + city + '-en/';
    }

    // Load the blog feed
    $.ajax({
        // TODO testing added s to feed path
        url: '/' + city + '/' + lang + '/ajax/get-feed.php?f=' + blog_url + '/' + feed_path + '&c=' + count_posts,
        dataType: 'json',
        success: function(response) {
            if (response.status=="OK") {

                // Check we got some posts
                if (response.posts.length>0) {
                    var i;
                    var post_output = '';

                    $.each(response.posts, function(i, val) {

                        // Probably not completely safe way to remove all html
                        var desc = val.description.replace(/<\/?[^>]+>/gi, '');

                        // strip the default "[...]" from the end of the description
                        desc=val.description.replace('\[\.\.\.\]','')

                        // Pull first 128 chars, and append "...".  POZOR this will cause problems if the
                        // break happens in the middle of an html entity, eg "&nbsp;".
                        desc=desc.substring(0,128) + " ...";

                        // alert(i + ' ' + response.posts[i].title);
                        post_output += "<div class='left lime'>" + val.formatted_date + " </div>\n\
                                        <div class='left blog_post'><span class='title'><a href='" + val.link + "'>" + val.title + "</a></span> :\n\
                                            <span class='desc'>" + desc + "\n\
                                            {<a class='lime' href='" + val.link + "'>" + val.more_text + "</a>}</span>\n\
                                        </div>\n\
                                        <br style='clear:both;'/>";

                        // Add a <br/> after all but the last item.  response is zero-based array
                        if (i<(count_posts-1)) {
                            post_output += "<br/>";
                        }
                    })

                    post_output+="<div class='right blog_more'><a class='lime' href='" + blog_url + "'>" + response.posts[0].more_text + "</a></div>"
                    $("div#blog_container").html("<div class='blog_feed'>" + post_output + "</div>");

                } else {
                    // Response was OK, but no posts - empty blog
                    $("div#blog_container").html('<!-- No posts found -->');
                    load_alternate_content(site_status);
                }

            } else {
                // Request failed - show alternate content, with err msg as a comment
                $("div#blog_container").html('<!-- ' + response.message + ' -->');
                load_alternate_content(site_status);
            }
        },
        error: function() {
            // Some error, eg blog does not exist
            $("div#blog_container").html('<!-- AJAX failed, no blog found -->');
            load_alternate_content(site_status);
        }
    });
}

// --------------------------------------------------------------------
/*
 * Load alternate content to be displayed in place of a blog feed.
 *
 * @param site_status live or holding, calling site's status
 * @return JSON object of status and content
 *
 */
function load_alternate_content (site_status) {

    // Get the content
    $.ajax({
        url: '/' + city + '/' + lang + '/ajax/get-feed-alternate.php?s=' + site_status,
        dataType: 'json',
        success: function(response) {
            if (response.status=="OK") {
                // We have our content, slot it into place
                $("div#blog_container").append(response.content);

            } else {
                // Request failed - write an error msg as a content
                $("div#blog_container").append('<!-- ' + response.content + ' -->');
            }
        },
        error: function() {
            // Some error - write an error msg as a content
            $("div#blog_container").append('<!-- Alt AJAX failed, ' + response.content + ' -->');
        }
    });

}
