﻿// data store objects
var newsArticles = [];
var newsCategories = [];
var newsContentToLoad;
var newsContentData;
var currentNewsContent;
var loadingNews;

function NewsArticle(title, caption, content, link, author, categories, publishDate) {
    this.title = title;
    this.caption = caption;
    this.content = content;
    this.linkTitle = link.replace('http://www.ironcreative.com/blog/', '');
    this.link = link.replace('http://www.ironcreative.com/blog/', '#/latest-news/post/');
    this.author = author;
    this.categories = categories;
    this.publishedDate = publishDate;
}

// data models
function Category(name, count) {
    this.name = name;
    this.count = count;
}

function compareDates(a, b) {
	return b.publishedDate - a.publishedDate;
}

function initNews() {
    newsContentToLoad = '';
    newsContentData = '';
    currentNewsContent = '';
    loadingNews = true;

    $.ajax({
        async: false,
		// http://code.google.com/apis/feed/v1/jsondevguide.html#json_args
		// scoring: "The only value this parameter takes is h, and setting this value instructs the system to return any additional historical entries that it might have in its cache."
        url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=-1&scoring=h&callback=?&q=' + encodeURIComponent('http://www.ironcreative.com/blog/feed'),
        dataType: 'json',
        success: function (data) {
            // store
            var entries = data.responseData.feed.entries;

			// console.dir(entries);

            for (var index = 0; index < entries.length; index++) {
                var entry = entries[index];
                var article = new NewsArticle(
                    entry.title,
                    entry.contentSnippet,
                    entry.content,
                    entry.link,
                    entry.author,
                    entry.categories,
                    new Date(entry.publishedDate));

                newsArticles.push(article);
            }

			newsArticles.sort(compareDates);
			
			// console.dir(newsArticles);

            newsCategories = parseNewsCategories();

            loadingNews = false;

            if (newsContentToLoad == '' || newsContentToLoad == 'featured') {
                loadFeaturedArticles();
            } else if (newsContentToLoad == 'list') {
                loadNewsList();
            } else if (newsContentToLoad == 'category-list') {
                loadCategoryNewsList();
            } else if (newsContentToLoad == 'news-article') {
                loadArticle();
            }
        }
    });
}

function parseNewsCategories() {
    var categories = [];
    if (newsArticles.length > 0) {
        var allCategories = [];
        var allUniqueCategories = ["Advertising","Brand Strategy","Graphic Design","Integrated Marketing", "Interactive","Mobile","Nonprofit","Retail","San Francisco / Bay Area","Social Good","Social Media","Radio","E-Commerce","Awards"];

        // create an array with all categories from every article
        $.each(newsArticles, function (index, article) {
            allCategories = allCategories.concat(article.categories);
        });

        // create categories, set count
        $.each(allUniqueCategories, function (position, category) {
            var count = allCategories.find(category).length;
            if (allCategories.find(category) === false) count = 0;

            var cat = new Category(category, count);
            categories.push(cat);
        });
    }

    // sort by most count
    categories.sort(function (a, b) {
        return (b.count - a.count);
    });

    return categories;
}

function resetLatestNews() {
    if (newsArticles.length > 0) {

        var latestNewsArticles = [];
        latestNewsArticles.push(newsArticles[0]);
        latestNewsArticles.push(newsArticles[1]);
        latestNewsArticles.push(newsArticles[2]);

        $.each(latestNewsArticles, function (index, article) {

            $('#featured-news-article-tmpl').tmpl({
                publishedDate: article.publishedDate.toString('MMMM dd, yyyy'),
                title: article.title,
                caption: article.caption,
                link: article.link
            }).appendTo('.latest-news-content');
        });

        // add wrapper
        $('.featured-news-article').wrapAll('<div class="featured-news-articles"></div>');

        // add verticle rules
        $('.featured-news-article').first().after('<div class="vr-faded"></div>');
        $('.featured-news-article').last().before('<div class="vr-faded"></div>');

        var contentHeight = $('.latest-news-content > div:first-child').height() + 20;
        $('.latest-news-content').animate({ 'height': contentHeight },
                    {
                        duration: 1000,
                        easing: 'easeInOutExpo',
                        complete: function () {
                            $('#latest-news').removeClass('active');
                            currentNewsContent = 'featured'
                            newsContentToLoad = '';
                            curRoute.runRouteHandler(curRoute.view, curRoute.position, curRoute.command);
                        }
                    });
    }
}

function closeLatestNews() {
    $('.latest-news-content').animate({ 'height': 0 },
                    {
                        duration: 1000,
                        easing: 'easeInOutExpo',
                        complete: function () {
                            $(this).empty();
                            $('#latest-news').removeClass('active');

                            updateLatestNewsHeader();

                            if (newsContentToLoad == 'reset') {  
                                resetLatestNews();
                            } else if (newsContentToLoad == 'featured') {
                                loadFeaturedArticles();
                            } else if (newsContentToLoad == 'list') {
                                loadNewsList();
                            } else if (newsContentToLoad == 'category-list') {
                                loadCategoryNewsList();
                            } else if (newsContentToLoad == 'news-article') {
                                loadArticle();
                            }
                        }
                    });
}

function openLatestNews() {
    var contentHeight = $('.latest-news-content > div:first-child').height() + 20;
    $('.latest-news-content').animate({ 'height': contentHeight },
                    {
                        duration: 1000,
                        easing: 'easeInOutExpo',
                        complete: function () {
                            $('#latest-news').addClass('active');
                        }
                    });
}

function loadFeaturedArticles() {
    if (newsArticles.length > 0) {

        var latestNewsArticles = [];
        latestNewsArticles.push(newsArticles[0]);
        latestNewsArticles.push(newsArticles[1]);
        latestNewsArticles.push(newsArticles[2]);

        $.each(latestNewsArticles, function (index, article) {

            $('#featured-news-article-tmpl').tmpl({
                publishedDate: article.publishedDate.toString('MMMM dd, yyyy'),
                title: article.title,
                caption: article.caption,
                link: article.link
            }).appendTo('.latest-news-content');
        });

        // add wrapper
        $('.featured-news-article').wrapAll('<div class="featured-news-articles"></div>');

        // add verticle rules
        $('.featured-news-article').first().after('<div class="vr-faded"></div>');
        $('.featured-news-article').last().before('<div class="vr-faded"></div>');
    }

    currentNewsContent = 'featured';
    if (newsContentToLoad != '') {
        newsContentToLoad = '';
        newsContentData = '';
        UpdatePosition('#latest-news', 1000, openLatestNews);
    }
}

function loadNewsList() {
    $('#news-list-tmpl').tmpl({
        listTitle: 'Latest News'
    }).appendTo($('.latest-news-content').empty());

    if (newsArticles.length > 0) {
        $.each(newsArticles.slice(0, 10), function (index, article) {

            $('#news-list-item-tmpl').tmpl({
                title: article.title,
                link: article.link
            }).appendTo('.news-list');
        });
    }

    //loadArticleFeaturedList();
    loadPopularCategoryList();

    currentNewsContent = newsContentToLoad;
    newsContentToLoad = '';
    newsContentData = '';
    UpdatePosition('#latest-news', 1000, openLatestNews);
}

function loadCategoryNewsList() {
    $('#news-list-tmpl').tmpl({
        listTitle: newsContentData
    }).appendTo($('.latest-news-content').empty());

    var articles = [];
    articles = findNewsArticlesByCatgory(newsContentData);

    if (articles.length > 0) {
        $.each(articles, function (index, article) {

            $('#news-list-item-tmpl').tmpl({
                title: article.title,
                link: article.link
            }).appendTo('.news-list');
        });
    } else {
        $('#empty-news-list-item-tmpl').tmpl({
            text: 'No articles were found related to ' + newsContentData  + '.'
        }).appendTo('.news-list');
    }

    //loadArticleFeaturedList();
    loadPopularCategoryList();

    currentNewsContent = newsContentToLoad;
    newsContentToLoad = '';
    newsContentData = '';
    UpdatePosition('#latest-news', 1000, openLatestNews);
}

function loadArticle() {
    var article = findNewsArticleByTitle(newsContentData);

    $('#news-article-tmpl').tmpl({
        title: article.title,
        publishedDate: article.publishedDate.toString('MMMM dd, yyyy')
    }).appendTo($('.latest-news-content').empty());

    $('.article-content').html(article.content);

    //loadArticleShareLinks(article);
    loadArticleRelatedNews(article);

    //loadArticleFeaturedList();
    loadPopularCategoryList();
    //loadArticleCategoryList(article);

    newsContentToLoad = '';
    newsContentData = '';
    currentNewsContent = 'news-article';
    UpdatePosition('#latest-news', 1000, openLatestNews);
}

function loadArticleShareLinks(article) {
    $('.shares-links img').each(function () {
        $(this).hover(
        // mouseover
        function () {
            this.src = this.src.replace('_icon.png', '_icon_blue.png');
        },
        // mouseout
        function () {
            this.src = this.src.replace('_icon_blue.png', '_icon.png');
        });
    });

    // linkedin
    var linkedinLink = '';
    $('.shares-links a.linkedin').attr('href', linkedinLink);
    // twitter
    var twitterLink = 'http://twitter.com/home?status=' + article.title + article.link;
    $('.shares-links a.twitter').attr('href', twitterLink);
    // facebook
    var facebookLink = 'http://www.facebook.com/share.php?u=' + article.link + '&t=' + article.title;
    $('.shares-links a.facebook').attr('href', facebookLink);
    // behanced
    var behancedLink = '';
    $('.shares-links a.behanced').attr('href', behancedLink);
}

function loadArticleRelatedNews(article) {
    var articles = findRelatedNewsArticles(article);
    if (articles.length > 0) {
        $.each(articles, function (index, relatedArticle) {
            $('#related-article-tmpl').tmpl({
                publishedDate: relatedArticle.publishedDate.toString('MMMM dd, yyyy'),
                title: relatedArticle.title,
                link: relatedArticle.link
            }).appendTo('.related-articles');
        });

        // add wrapper
        $('.related-article').wrapAll('<div class="related-articles-list"></div>');

        // add dividers
        $('.related-article').first().after('<div class="vr-faded"></div>');
        $('.related-article').last().before('<div class="vr-faded"></div>');
    }
}

function loadArticleFeaturedList() {
    if (newsArticles.length > 0) {
        $.each(newsArticles, function (index, article) {

            if (index == 3) { return false; }

            $('#featured-list-item-tmpl').tmpl({
                title: article.title,
                link: article.link
            }).appendTo('.featured-list');
        });
    }
}

function loadArticleCategoryList(article) {
    var categoriesList = [];
    if (article.categories.length > 0) {

        // get category object for each category in article
        $.each(article.categories, function (index, category) {
            var cat = findCategory(category);
            if (cat !== undefined) {
                categoriesList.push(cat);
            }
        });

        // sort categories by name
        categoriesList.sort(function (a, b) {
            var category_a = a.name; category_b = b.name;
            if (category_a < category_b) return -1;
            else if (category_a > category_b) return 1;
            else return 0;
        });

        // render each category
        $.each(categoriesList, function (index, category) {
            $('#categories-list-item-tmpl').tmpl({
                link: category.name.replace(' / ', '-').replace(' ', '-').replace(' ', '-').toLowerCase(),
                name: category.name,
                count: category.count
            }).appendTo('.category-list');
        });

    } else {
        alert('no categories found.');
    }
}

function loadPopularCategoryList() {
    var categoriesList = [];
    if (newsCategories.length > 0) {

        // get category object for each category in article
        for (var index = 0; index < newsCategories.length; index++) {
            categoriesList.push(newsCategories[index]);
        }

        // sort categories by name
        categoriesList.sort(function (a, b) {
            var category_a = a.name; category_b = b.name;
            if (category_a < category_b) return -1;
            else if (category_a > category_b) return 1;
            else return 0;
        });

        // render each category
        $.each(categoriesList, function (index, category) {
            $('#categories-list-item-tmpl').tmpl({
                link: category.name.replace(' / ', '-').replace(' ', '-').replace(' ', '-').toLowerCase(),
                name: category.name,
                count: category.count
            }).appendTo('.category-list');
        });

    } else {
        alert('no categories found.');
    }
}

function updateLatestNewsHeader() {
    var btnHref;
    var btnCssClass;
    var btnTitle;

    if (newsContentToLoad == 'reset' || newsContentToLoad == 'featured') {
        btnTitle = 'view all';
        btnCssClass = 'view-all';
        btnHref = '#/latest-news/list';
    } else if (newsContentToLoad == 'list' || newsContentToLoad == 'category-list') {
        btnTitle = 'close';
        btnCssClass = 'close';
        btnHref = '#/latest-news';
    } else if (newsContentToLoad == 'news-article') {
        btnTitle = 'view all';
        btnCssClass = 'view-all';
        btnHref = '#/latest-news/list';
    }

    $('#latest-news > .content-header > a').text(btnTitle);
    $('#latest-news > .content-header > a').removeClass().addClass(btnCssClass);
    $('#latest-news > .content-header > a').attr('href', btnHref);
    
}

function findNewsArticleByTitle(title) {
    var article;

    for (var index = 0; index < newsArticles.length; index++) {
        if (newsArticles[index].linkTitle == title) {
            article = newsArticles[index];
            break;
        }
    }

    return article;
}

function findRelatedNewsArticles(article) {

    var relatedArticles = [];
    var uniqueArticles = [];
    var allArticleLinkTitlesList = [];

    $.each(article.categories, function (ac_index, category) {
        var articlesByCategory = findNewsArticlesByCatgory(category);
        $.each(articlesByCategory, function (abc_index, articleInCategory) {
            allArticleLinkTitlesList.push(articleInCategory.linkTitle);
        });
    });

    allArticleLinkTitlesList.sort(function (a, b) {
        return (allArticleLinkTitlesList.find(b).length - allArticleLinkTitlesList.find(a).length);
    });

    $.each(allArticleLinkTitlesList, function (index, link_title) {
        if (relatedArticles.length == 3) return false;

        if (article.linkTitle != link_title && uniqueArticles.find(link_title) === false) {
            uniqueArticles.push(link_title);
            relatedArticles.push(findNewsArticleByTitle(link_title));
        }
    });

    return relatedArticles;
}

function findNewsArticlesByCatgory(name) {
    var articles = [];
    $.each(newsArticles, function (article_index, article) {
        $.each(article.categories, function (category_index, category) {
            if (category.replace(' / ', '-').replace(' ', '-').replace(' ', '-').toLowerCase() === name.toLowerCase()) {
                articles.push(article);
                return false;
            }
        });
    });
    return articles;
}

function findCategory(name) {
    var category;

    for (var index = 0; index < newsCategories.length; index++) {
        if (newsCategories[index].name == name) {
            category = newsCategories[index];
            break;
        }
    }

    return category;
}

Array.prototype.find = function (searchStr) {
    var returnArray = false;
    for (i = 0; i < this.length; i++) {
        if (typeof (searchStr) == 'function') {
            if (searchStr.test(this[i])) {
                if (!returnArray) { returnArray = [] }
                returnArray.push(i);
            }
        } else {
            if (this[i] === searchStr) {
                if (!returnArray) { returnArray = [] }
                returnArray.push(i);
            }
        }
    }
    return returnArray;
}
