//	News
//	old News JS, needs cleaned
//	removes leading 0s from numbers
var removeLeadingZeros = function(tmp) {
    if (tmp < 10) {tmp = tmp.toString().replace(/0/,"");} return tmp;
}
//	adds leading 0s from numbers
var addLeadingZeros = function(tmp) {
    if (String(tmp).length < 2) {tmp = "0" + tmp;} return tmp;
}
//	receive amount to slide, slide Hot List UL left or right; used on Category Index page
var moveList = function(obj,n) {
    var o = document.getElementById(obj);				// get the toutList ul
    o.style.left = String(n+"px");					// move toutList
}
//	receive direction to slide (prev/next), slide Hot List UL left or right; used on Category Index page
var slideHotList = function(dir) {
    var m = 296;										// if the function received a direction, set the movement width to 296; if not, set it to 0
    var n = 0;											// initialize n as 0; if function received a direction, it will be reset
    var UL = document.getElementById("toutList");		// get the toutList ul
    if (dir) {
        if (dir == "next") {m = m*(-1);}				// for "next" make 296 a negative number
        var c = Number(UL.style.left.replace(/px/,""));	// get the current left position of toutList
        n = c + m;									// create the new left (by adding 296 or -296 to the current left)
        var speed = 150;
        //determine the direction for the blending, if start and end are the same nothing happens
        if (c > n) {
            for(i = c; i >= n; i--) {
                setTimeout("moveList('toutList'," + i + ")",speed);
                speed++;
            }
        } else if (c < n) {
            for(i = c; i <= n; i++) {
                setTimeout("moveList('toutList'," + i + ")",speed);
                speed++;
            }
        }
    }
    var LIs = UL.getElementsByTagName("li");			// get all the LIs in toutList
    var prev = document.getElementById("hotTopicsPrev");
    prev.className = "";							// remove any class from the previous navigation link
    prev.childNodes[0].onclick = function() {		// attach an onclick event to the previous navigation link
        slideHotList("prev");
    }
    var next = document.getElementById("hotTopicsNext");
    next.className = "";							// remove any class from the next navigation link
    next.childNodes[0].onclick = function() {		// attach an onclick event to the next navigation link
        slideHotList("next");
    }
    if (n == 0) {										// if toutList is at its left-most position, disable the previous navigation link
        prev.className = "disabled";
        prev.childNodes[0].onclick = null;
    }
    if (n == (m * (LIs.length - 2))) {					// if toutList is at its right-most position, disable the next navigation link
        next.className = "disabled";
        next.childNodes[0].onclick = null;
    }
}
//	initialize Hot List; used on Category Index page
var initializeHotList = function() {
    if (!document.getElementById) return;
    if (!document.getElementsByTagName) return;
    if (!document.getElementById("hotTopicsSlide")) return;
    slideHotList();
}
//	get the next/previous XML feed, create the next/previous navigation buttons, and place them into the page
var articleNextPrevNavCallback = function(pos,response) {
    var u = location.href.split(',');
    var id = String(u[2]);
    var items = response.getElementsByTagName('item');
    for (i = 0; i < items.length; i++) {// NOTE: the data file is in descending order
        var link = items[i].getElementsByTagName('link')[0].firstChild.data;
        if (link.indexOf(id) > -1) {
            var topnav = '<ul>';
            var botnav = '<ul>';
            var p = i-1;
            if (p >= 0) {
                var prevTitle = items[p].getElementsByTagName('title')[0].firstChild.data;
                var prevLink = items[p].getElementsByTagName('link')[0].firstChild.data;
//					topnav += '<li class="prev"><a href="' +prevLink+ '">' +prevTitle+ '</a></li>';
                topnav += '<li class="prev"><a href="' +prevLink+ '" title="' + prevTitle +'"><span>Previous Article</span></a></li>';
                botnav += '<li class="prev"><a href="' +prevLink+ '"><span>Previous</span>' +prevTitle+ '</a></li>';
            }
            var n = i+1;
            if (n < items.length) {
                var nextTitle = items[n].getElementsByTagName('title')[0].firstChild.data;
                var nextLink = items[n].getElementsByTagName('link')[0].firstChild.data;
//					topnav += '<li class="next"><a href="' +nextLink+ '">' +nextTitle+ '</a></li>';
                topnav += '<li class="next"><a href="' +nextLink+ '" title="' + nextTitle + '"><span>Next Article</span></a></li>';
                botnav += '<li class="next"><a href="' +nextLink+ '"><span>Next</span>' +nextTitle+ '</a></li>';
            }
            topnav += '</ul>';
            botnav += '</ul>';
            document.getElementById('nextprevpaginationtop').innerHTML = topnav;
            document.getElementById('nextprevpaginationtop').className += ' active';
            document.getElementById('nextprevpaginationbottom').innerHTML = botnav;
            document.getElementById('nextprevpaginationbottom').className += ' active';
        }
    }
}
//	initialize Article page's next/previous article links; used on... Article page
var initializeArticleNextPrevNav = function() {
    if (!document.getElementById) return;
    if (!document.getElementsByTagName) return;
    if (PEOPLE.News.articledate == null || PEOPLE.News.articledate == '') return;
    arrCalendarDates.length = 0;
    addCalendarDates(PEOPLE.News.articledate,'/people/xml/nextprev/0,,' +PEOPLE.News.articledate+ ',00.xml');// example: /people/xml/nextprev/0,,10-28-2008,00.xml
    getFeed(arrCalendarDates[0],'nextprevpaginationtop',articleNextPrevNavCallback);
}

//	initialize recirc feeds; used on Main and Category pages
var initializeNewswireFeed = function() {
    if (!document.getElementById) return;
    if (!document.getElementsByTagName) return;
    var recircArray = {
        'recircs' : [
            {
                'id'		: 'recirc1',
                'feed' 		: [
                    {
                        'name'  	: 'Huffington Post',
                        'json' 		: 'http://img2-short.timeinc.net/people/static/json/huffingtonpost/feed.js',
                        'site' 		: 'http://www.huffingtonpost.com/entertainment/',
                        'image' 	: 'http://img2.timeinc.net/people/static/i/misc/logoHuffingtonPost.gif',
                        'display'	: 5
                    }
                ]
            },{
                'id'		: 'recirc2',
                'type' 		: 'random',
                'display'	: 1,
                'feed' 		: [
                    {
                        'name'  	: 'PopSugar.com',
                        'json' 		: 'http://img2-short.timeinc.net/people/static/json/popsugar/feed.js',
                        'site' 		: 'http://www.popsugar.com',
                        'image' 	: 'http://img2.timeinc.net/people/static/i/news/logoPopSugar.gif',
                        'display'	: 5
                    },
                    {
                        'name'  	: 'Moviefone',
                        'json' 		: 'http://www.people.com/people/static/json/moviefone/feed.js',
                        'site' 		: 'http://www.moviefone.com',
                        'image' 	: 'http://img2.timeinc.net/people/static/i/news/logoMoviefone.gif',
                        'display'	: 5
                    }
                ]
            },{
                'id'		: 'recirc3',
                'feed' 		: [
                    {
                        'name'  	: 'Celebrity-Babies.com',
                        'json' 		: 'http://img2-short.timeinc.net/people/static/json/celebrity_babies/feed.js',
                        'site' 		: 'http://celebritybabies.people.com/',
                        'image' 	: 'http://www.people.com/people/static/i/news/logoCBB.gif',
                        'display'	: 5
                    }
                ]
            }
        ]
    };
    pushToMasterArray(recircArray);
};
initializeNewswireFeed();
//	initialize Partner Recirc feeds; uses Global PartnerRecirc function
var initializeArticleRecirc = function() {
    if (!document.getElementById) return;
    if (!document.getElementsByTagName) return;
    var recircArray = {
        'recircs' : [
            {
                'id'		: 'rightcolumnrecirc',
                'type' 		: 'random',
                'display'	: 1,
                'feed' 		: [
                    {
                        'name'  	: 'PopSugar.com',
                        'json' 		: 'http://img2-short.timeinc.net/people/static/json/popsugar/feed.js',
                        'site' 		: 'http://www.popsugar.com',
                        'image' 	: 'http://img2.timeinc.net/people/static/i/news/logoPopSugar.gif?1',
                        'callback'	: PEOPLE.recirccallback,
                        'display'	: 3
                    },
                    {
                        'name'  	: 'Moviefone',
                        'json' 		: 'http://www.people.com/people/static/json/moviefone/feed.js',
                        'site' 		: 'http://www.moviefone.com',
                        'image' 	: 'http://img2.timeinc.net/people/static/i/news/logoMoviefone.gif',
                        'display'	: 3
                    }
                ]
            },{
                'id'		: 'rightcolumnrecircbottom',
                'feed' 		: [
                    {
                        'name'  	: 'Today Show',
                        'json' 		: 'http://www.people.com/people/static/json/todayshow/feed.js',
                        'site' 		: 'http://today.msnbc.msn.com/',
                        'image' 	: 'http://img2.timeinc.net/people/static/i/news/logoTodayShow.png',
                        'callback'	: PEOPLE.recirccallback,
                        'display'	: 3
                    }
                ]
            },{
                'id'		: 'afterarticlerecirc',
                'display'	: 1,
                'feed' 		: [
                    {
                        'name'  	: 'Huffington Post',
                        'json' 		: 'http://img2-short.timeinc.net/people/static/json/huffingtonpostarticle/feed.js',
                        'site' 		: 'http://www.huffingtonpost.com/entertainment/',
                        'image' 	: 'http://img2.timeinc.net/people/static/i/photos/logoHuffingtonPost3.gif',
                        'callback'	: PEOPLE.recirccallback,
                        'display'	: 2
                    }
                ]
            }
        ]
    };
    pushToMasterArray(recircArray);
};
initializeArticleRecirc();
//	collapse right column adMarketplace if no ad
function hideAdMarketplace() {
    if (!document.getElementById("adMarketplace")) return;
    document.getElementById("adMarketplace").id = "adMarketplaceNoAds";
}
//	this will be reset to true if the adMarketplace ad fires; if not, the initializeAdMarketplace function will hide the DIV
var adMarketplace = "false";
//	redefines function from 0,,,00.js to set wmode to transparent
var buildBrightcovePlayer = function(videoID) {
    var config = new Array();
    config["videoId"] = videoID;
    config["videoRef"] = null;
    config["lineupId"] = null;
    config["playerTag"] = null;
    config["autoStart"] = false;
    config["preloadBackColor"] = "#FFFFFF";
    config["width"] = 300;
    config["height"] = 320;
    config["wmode"] = "transparent";
    config["playerId"] = (brightcovePlayerID == "") ? 416421276 : brightcovePlayerID;
    createExperience(config, 8);
}
//	append calendar JS if page requires a calendar
var initializeCalendar = function() {
    $.getScript('/people/static/j/news/calendar.js');
}
//	can list as many functions as you want and the loader below will load them as soon as the page is loaded
var leftColumnFunctions = function() {
    //addBookmarkDropdown("div");
    if(document.getElementById("addPeopleNews")){document.getElementById("addPeopleNews").style.position = "absolute";}
}
//	can list as many functions as you want and the loader below will load them as soon as the page is loaded
var pageLoadFunctions = function() {
    if(adMarketplace == "false"){hideAdMarketplace();}
    tii_attachHoverAffect("div","tout","hover","posts"); // elements to find, class to find within elements, new class to add elements, optional parent id
    tii_attachHoverAffect("li","","hover","newsCategories");
    tii_attachHoverAffect("li","","hover","specialFeaturesList");
    tii_attachHoverAffect("div","tout","hover","top10Categories");
    tii_attachHoverAffect("li","addPeopleNews","hover","middleColumn");
}
//	load scripts once these elements are loaded
tii_callFunctionOnElementLoad("calendars", initializeCalendar);
tii_callFunctionOnElementLoad("hotTopicsSlide", initializeHotList);
tii_callFunctionOnElementLoad("leftColumn", leftColumnFunctions);
tii_callFunctionOnElementLoad("nextprevpaginationbottom", initializeArticleNextPrevNav);
//	load scripts once full page is loaded
tii_callFunctionOnWindowLoad(pageLoadFunctions);
// setting document.domain so polls and fbconnect will play with each other
if(document.location.href.indexOf('people.com') > 0){
    document.domain = 'people.com';
}else if(document.location.href.indexOf('peoplestylewatch.com') > 0){
    document.domain = 'peoplestylewatch.com';
}
// new News JS
PEOPLE.News = {
    init : function() {
        PEOPLE.News.huffingtonNewsRecirc();
        if ($('#addPeopleNews')) {PEOPLE.News.addPeopleNews();} // Newswire drop-down
    },
    addPeopleNews : function() {
        if (!$('#addPeopleNews').length) {return;}
        $('#addPeopleNews')
            .hover(
            function(){
                $(this).addClass('hover');
            },function(){
                $(this).removeClass('hover click');
            }
        ).find('span').click(function(){
                $(this)
                    .addClass('click')
                    .find('ul:first')
                    .addClass('active')
                    .hover(
                    function(){
                        $(this).addClass('active');
                        $(this).parent().addClass('click');
                    },
                    function(){
                        $(this).removeClass('active');
                        $(this).parent().removeClass('click');
                    }
                );
                return false;
            });
    },
    huffingtonNewsRecirc : function() {
        $.ajax({
            url: 'http://' + location.hostname + '/people/static/h/inc/news/huffington.txt',
            success: function(data) {
                var rightRecirc = $('#rightcolumnrecirc'),
                    markup = '<div id="rightcolumn-recirc-top" class="toutSection recirc hfeed active">' +
                        '<p class="title">Around the Web</p>' +
                        data +
                        '</div>';
                if ( rightRecirc.length ) {
                    rightRecirc.before(markup);
                }
            }
        })
    },
    startsubnav : function() {
        $('#subnavMore').find('a:first').bind('click',function(e) {
            e.preventDefault();
            $(this).parent().addClass('active');
        })
            .end()
            .find('div').bind('mouseleave',function() {
                $(this).parent().removeClass('active');
            });
    },
    addsubnavarrows : function() {
        $('#subnavMore').find('div').find('a').each(function() {
            $(this).append('<span />');
        });
    }
};
tii_callFunctionOnWindowLoad(PEOPLE.News.init);

PEOPLE.flyingrecirc = {
    bottom : '-500px',
    speed : 400,
    display : 6,
    init : function() {
        if (!$('#news').hasClass('article')) {return false;}
        $.getScript('/people/json/articles/');
    },
    append : function(obj) {
        this.json = obj;
        var articleid = adFactory.params.aid, i, len = this.json.length, n;
        for (i = -1; ++i < len;) {
            n = this.json[i];
            if (n.articleid == articleid) {this.json.splice(i,1);break;}
        }
        if (this.json.length > this.display) {this.json.length = this.display;}
        this.getstarted();
    },
    getstarted : function() {
        var h, n, i, len = this.json.length, c = 'odd';
        h = '<div id="flyingrecirc">';
        h += '<p class="title"><strong>PEOPLE</strong> Most Read Stories</p>';
        h += '<div class="contentSection">';
        h += '<ul class="toutSection">';
        for (i = -1; ++i < len;) {
            n = this.json[i];
            h += '<li id="article'+n.articleid+'" class="tout hentry '+c+'">';
            h += '<div class="imgcont"><a href="'+n.url+'">'+n.img+'</a></div>';
            h += '<div class="txtcont">';
            h += '<h4 class="entry-title"><a href="'+n.url+'" rel="bookmark">'+n.headline+'</a></h4>';
            h += '<p class="more entry-permalink"><a href="'+n.url+'">'+n.cta+'</a></p>';
            h += '</div>';
            h += '</li>';
            c = (c =='odd') ? 'even' : 'odd';
        }

        h += '<li id="articleCM" class="tout hentry '+c+'">';
        h += '<div class="imgcont"><a href="https://subscription.people.com/storefront/subscribe-to-people/link/1002110.html" target="_blank"><img src="http://img2.timeinc.net/people/peoplecovers/peoplecover_75x100.jpg" /></a></div>';
        h += '<div class="txtcont">';
        h += '<h4 class="entry-title"><a href="https://subscription.people.com/storefront/subscribe-to-people/link/1002110.html" target="_blank" rel="bookmark">Get More Stories Like These Delivered to Your Door!</a></h4>';
        h += '<p class="more entry-permalink"><a href="https://subscription.people.com/storefront/subscribe-to-people/link/1002110.html" target="_blank">Get 4 Free Issues!</a></p>';
        h += '</div>';
        h += '</li>';

        h += '</ul>';
        h += '</div>';
        h += '</div>';
        $('#container').append(h);
        this.recirc = $('#flyingrecirc');
        this.slider = this.recirc.find('ul:first');
        this.count = this.slider.find('li').length;
        this.recircwidth = this.recirc.width();
        this.slider.css('position','absolute').prepend(this.slider.find('li:last')).css('left','-'+this.recircwidth+'px');
        var h = this.slider.height();
        this.slider.parent().css('height',h+'px');
        this.addnav();
        this.sliderclick();
        $(window).scroll(function(){PEOPLE.flyingrecirc.scroll();});
    },
    isvisible : function(elem) { // altered from http://stackoverflow.com/questions/487073/jquery-check-if-element-is-visible-after-scroling
        var doctop = $(window).scrollTop(),
            docbot = doctop + $(window).height(),
            elemtop = $(elem).offset().top,
            elembot = elemtop + $(elem).height() + this.recirc.height() + 10;
        return (docbot > elembot);
    },
    scroll : function() {
        var c = PEOPLE.flyingrecirc.recirc.hasClass('showing'),
            v = PEOPLE.flyingrecirc.isvisible('#rightColumn');
        if (!c && v) {
            PEOPLE.flyingrecirc.show();
        } else if (c && !v) {
            PEOPLE.flyingrecirc.hide();
        }
    },
    show : function() {
        this.recirc.addClass('showing').animate({'bottom':'0px'},this.speed);
        omniFlyOutTracker('impression',this.getheadline());
    },
    hide : function() {
        this.recirc.removeClass('showing').animate({'bottom':this.bottom},this.speed);
        omniFlyOutTracker('close');
    },
    close : function() {
        this.recirc.removeClass('showing').animate({'bottom':this.bottom},this.speed,function(){PEOPLE.flyingrecirc.recirc.remove();PEOPLE.flyingrecirc.scroll = null;});
        omniFlyOutTracker('close');
    },
    next : function(dist) {
        this.slider.animate({'left':dist},300,function(){
            PEOPLE.flyingrecirc.slider.append(PEOPLE.flyingrecirc.slider.find('li:first')).css('left','-'+PEOPLE.flyingrecirc.recircwidth+'px');
            omniFlyOutTracker('next');
            omniFlyOutTracker('impression',PEOPLE.flyingrecirc.getheadline());
        });
    },
    previous : function(dist) {
        this.slider.animate({'left':dist},300,function(){
            PEOPLE.flyingrecirc.slider.prepend(PEOPLE.flyingrecirc.slider.find('li:last')).css('left','-'+PEOPLE.flyingrecirc.recircwidth+'px');
            omniFlyOutTracker('previous');
            omniFlyOutTracker('impression',PEOPLE.flyingrecirc.getheadline());
        });
    },
    getheadline : function() {
        return this.slider.find('li:eq(1)').find('h4').text();
    },
    addnav : function() {
        if (this.count < 2) {return;}
        var h = '<ul id="reciricnav">';
        h += '<li class="close"><a href="#">X <span>Close</span></a></li>';
        h += '<li class="previous"><a href="#">Previous</a></li>';
        h += '<li class="next"><a href="#">Next</a></li>';
        h += '</ul>';
        this.recirc.prepend(h);
        this.navclick();
    },
    navclick : function() {
        $('#reciricnav').click(function(e) {
            var html = $(e.target).html(),
                dist = PEOPLE.flyingrecirc.recircwidth;
            switch (html) {
                case 'Next':
                    PEOPLE.flyingrecirc.next('-='+dist);
                    break;
                case 'Previous':
                    PEOPLE.flyingrecirc.previous('+='+dist);
                    break;
                default:
                    PEOPLE.flyingrecirc.close();
            }
            return false;
        });
    },
    sliderclick : function() {
        this.slider.click(function(e) {
            var el = $(e.target),
                p = el.parent().get(0).tagName;
            switch (p) {
                case 'A': // image
                    omniFlyOutTracker('image_click',PEOPLE.flyingrecirc.getheadline());
                    break;
                case 'H4': // headline
                    omniFlyOutTracker('headline_click',PEOPLE.flyingrecirc.getheadline());
                    break;
                case 'P': // cta
                    omniFlyOutTracker('cta_click',PEOPLE.flyingrecirc.getheadline());
                    break;
            }
        });
    }
};
// don't show on ipads
if (!(navigator.userAgent.match('iPhone')) && !(navigator.userAgent.match('iPad')) && !(navigator.userAgent.match('iPod'))) {
    tii_callFunctionOnWindowLoad(PEOPLE.flyingrecirc.init);
}


/* Visual Revenue Top Story Tracking */
$(document).ready(function(){
    $('#vr018001001').bind('click', function(e){
        var t = $(e.target),
            li = (t.parent()[0].nodeName === 'UL') ? t : t.parent(),
            n = li.prevAll().size()+1
        linkTrack('topstory'+n, t.text());
    })
});

/* Prompt to Like PEOPLE.com on FB Like Event on articles */
$(document).ready(function(){
//	if($('#news').hasClass('article')){
    if($('body.article').length){
        FB.init({appId: '56579077293', status: true, cookie: true, xfbml: true});

        var popuptitle	= $('h1').text() ? '"' + $('h1').text() + '"' : 'story',
            popuphtml =	'<div id="time-fb-like" style="display:block; clear:left; float:left; border:1px solid #ccc; width:240px; margin:0 10px 4px 0;">'
                +		'<p style="margin:0; padding:4px; font:normal 11px arial,sans-serif; color:#555;">'
                +			'Thanks for liking PEOPLE\'s ' + popuptitle + '. Like PEOPLE on Facebook for breaking news, celebrity pictures, exclusive deals and more!'
                +		'</p>'
                +		'<p style="margin:0; padding:4px; height:20px;"><fb:like layout="button_count" href="http://www.facebook.com/peoplemag" width="80" font="arial" show-faces="false"></fb:like></p>';
        +	'</div>';

        $(popuphtml).insertAfter('.sharebox');
        $('#time-fb-like').css('display','none');
        window.fbAsyncInit = function() {
            FB.init({appId: '56579077293', status: true, cookie: true, xfbml: true});
        };

        FB.Event.subscribe('edge.create',
            function () {
                $('#time-fb-like').css('display','block')
            }
        );

        FB.Event.subscribe('edge.remove',
            function(response) {
                $('#time-fb-like').css('display','none');
            }
        );
    }
});

$(function(){
    $('#leftFirst').append('<div class="cmlink"><a href="https://subscription.people.com/storefront/subscribe-to-people/link/1008332.html" target="_blank">Get a FREE Swag Bag</a></div>');
});


$(document).ready(function() {

    PEOPLE.News.startsubnav();
    PEOPLE.News.addsubnavarrows();

    // Add cover label if article is a cover story (Edit adds <span class="coverlabel"></span> in CT)
    var coverheader = '<img src="http://img2.timeinc.net/people/static/i/news/cover_label.png" alt="See the full story on newsstands now!" />';
    $('body.article .coverlabel').parent().addClass('coverarticle');
    $('body.article .coverarticle .img300x400').prepend(coverheader);
});

