/// <reference path="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js" />
/// <reference path="http://www.google.com/jsapi" />
/// <reference path="http://creative.myspace.com/au/customcommunities/rollingstone/scripts/swfobject.js" />
/// <reference path="jquery.timer.js" />

var rollingStoneVars = {
    xmlEntries: null,
    videos: null,
    newCommentsHeader: null,
    maxPostCount: 3 ,
    blogFriendId: 69791736,
    videoFriendId: 69791736
}

function renderFeature() {
    var featureNode = $('#currentIssue .currentIssueFeature')[0];
    
    $('#coverImage')[0].src = $(featureNode).children('.imageUrl').html();
    
    $('#issueHeader').html($(featureNode).children('.featureTitle').html());
    $('#issueOverview')[0].appendChild(document.createTextNode($(featureNode).children('.featureBody').html()));
    
    var featureLinkText = $(featureNode).children('.featureLinkText');
    var featureLinkUrl = $(featureNode).children('.featureLinkUrl');

    if (featureLinkText.length > 0 && featureLinkUrl.length > 0) {
        var featureLink = $('<br /><br /><a href="' + featureLinkUrl.html() + '" target="_blank">' + featureLinkText.html() + '</a>');
        featureLink.appendTo($('#issueOverview')[0]);
    }
    
    $('#coverImage').wrap('<a href="' + featureLinkUrl.html() + '" target="_blank"></a>');
}

function renderStreetStyle() {
    var featureNode = $('#streetstylecms')[0];
    $('#styleimg')[0].src = $(featureNode).children('.imageUrl').html();
    $('#streetdesc').html($(featureNode).children('.streetDesc').html());
    $('#namestate').html($(featureNode).children('.streetDetails').html());
    $('#enternowbutton').attr("href", $(featureNode).children('.enterHereLink').html());
}

function displayVideo(index) {
    var video = rollingStoneVars.videos[index];
    var videoXml = video.xmlNode;
    var contentUrl = $(getElementByTagName(videoXml, 'media:player')).attr('url');
    var videoUrl = contentUrl.replace(/ap=0/, 'ap=1');

//    var params = {      wmode: "transparent"    };
//    swfobject.embedSWF(videoUrl, 'featuredVideo', '409', '342', '9.0.0', '', '', params);
	    swfobject.embedSWF(videoUrl, 'featuredVideo', '409', '342', '9.0.0');
    $('#videoTitle').html(video.title);
    $('#videoDescription').html(video.content);
}

function loadVideoSwitcher() {
    var feedUrl = 'http://mediaservices.myspace.com/services/rss.ashx?fuseaction=vids.channel&ChannelID=' + rollingStoneVars.videoFriendId + '&RSSAction=VideoChannel'
	
	feedUrl ='http://feeds.foxinteractivemedia.com.au/feeds/videos_'+ rollingStoneVars.videoFriendId + '.xml';
feedUrl =	'http://mediaservices.myspace.com/services/rss.ashx?ContributorId=1709296&RSSAction=VideoChannel' ;
    var feed = new google.feeds.Feed(feedUrl);
    feed.setResultFormat(google.feeds.Feed.MIXED_FORMAT);
    feed.load(function(result) {
        if (!result.error) {
            var feedItems = result.feed.entries;
            rollingStoneVars.videos = feedItems;
            $.each(feedItems, function(i) {
          var videoXml = this.xmlNode;
                var contentElement = getElementByTagName(videoXml, 'media:content');
                var contentUrl = $(contentElement).attr('url');
                var thumbnailElement = getElementByTagName(videoXml, 'media:thumbnail');
                var thumbnailUrl = $(thumbnailElement).attr('url');

                var thumbnailLink = $('<a title="' + this.title + '"></a>');
                thumbnailLink.click(function(event) { displayVideo(i); });
                thumbnailLink.bind('mouseover', this.contentSnippet, showSnippet);
                thumbnailLink.bind('mouseout', hideSnippet);


                var thumbnailImage = $('<img src="' + thumbnailUrl + '" />');
                if (i == rollingStoneVars.videos.length - 1) {
                    thumbnailImage.addClass('lastImage');
                }

                thumbnailImage.appendTo(thumbnailLink[0]);
                thumbnailLink.appendTo($('#videoThumbnailList')[0]);
            });

            if (feedItems.length > 0) {
                displayVideo(0);
            }
        }
    });
}

function showSnippet(event) {
    $('#thumbnailDescription').html(event.data);
}

function hideSnippet(event) {
    $('#thumbnailDescription').html('');
}

function getElementByTagName(parentNode, childNode) {
    var targetNode = null;

    $.each(parentNode.childNodes, function() {
        if (this.tagName == childNode) {
            targetNode = this;
            return false;
        }
    });

    return targetNode;
}



function renderFriend() {
    var friendNode = $('#currentIssue .featuredFriend')[0];
    var name = $(friendNode).children('.friendName').html();
    var description = $(friendNode).children('.friendDescription').html();
    var profileID = $(friendNode).children('.friendId').html();
    var imageUrl = $(friendNode).children('.imageUrl').html().replace(/&amp;/g, '&');
    
    $('<img src="' + imageUrl + '" />').appendTo($('#friendImage')[0]);

    $('#featuredFriendName').html(name);
    $('#friendDetail').html(description);
    $('#friendLink')[0].href = 'http://www.myspace.com/' + profileID;
}

function populateBlogs() {
    var feed = new google.feeds.Feed('http://blogs.myspace.com/blog/rss.cfm?friendID=' + rollingStoneVars.blogFriendId);
    feed.load(function(result) {
        if (!result.error) {
            rollingStoneVars.xmlEntries = $('#currentIssue .entry');
            var newsItems = $('#newsItems')[0];
            var feedItems = result.feed.entries;
            $.each(feedItems, function(i) {
                if (i < rollingStoneVars.maxPostCount) {
                    var entryNode = rollingStoneVars.xmlEntries[i];
                    var imageUrl = $(entryNode).children('.imageUrl').html().replace(/&amp;/g, '&');
                    var entryBody = $(entryNode).children('.blogBody').html();
                    var newsItem = $('<div class="newsItem"></div>');
                    var newsImage = $('<img class="blogImage" src="' + imageUrl + '" />');

                    var itemDetail = $('<div class="itemDetail"></div>');

                    var itemTitle = $('<div class="itemTitle"></div>');
                    var itemTitleLink = $('<a href="'+this.link+'"></a>');
                    itemTitleLink.appendTo(itemTitle);
                    
                    if (this.title == '') {
                        itemTitleLink.html($(entryNode).children('.title').html());
                    }
                    else {
                        itemTitleLink.html(this.title);
                    }
                    
                    itemTitle.appendTo(itemDetail);

                    var blogBody = $('<div class="blogBody"></div>');
                    var blogBodyLink = $('<a href="'+this.link+'"></a>');
                    blogBodyLink.appendTo(blogBody);
                    
                    if (this.contentSnippet != '') {
                        var constrain = this.contentSnippet.substr(0, 50);
                        constrain += "...";
                        blogBodyLink.html(constrain);
                        
                    } else {
                        blogBodyLink.html(entryBody);
                    }
                    
                    blogBody.appendTo(itemDetail);

                    //var itemLink = $('<a class="itemLink" href="' + this.link + '"></a>');
                    //var viewMoreImage = $('<img src="http://creative.myspace.com/au/customcommunities/rollingstone/images/blogviewmore.png" />');
                    //viewMoreImage.appendTo(itemLink);
                    //itemLink.appendTo(itemDetail);

                    newsImage.appendTo(newsItem);
                    itemDetail.appendTo(newsItem);
                    $('<div class="clear"></div>').appendTo(newsItem);
                    newsItem.appendTo(newsItems);
                }
            });
            
            var blogLink = $('<a href="http://blogs.myspace.com/girlfriendmagazine">{View all Blog Entries}</a>');
            blogLink.appendTo(newsItems);
        }
    });
}

function loadPoll() {
    var pollNode = $('#currentIssue .poll')[0];
    var pollID = $(pollNode).children('.pollID').html();
    var pollBody = $('#pollBody')[0];

    //Because we're dynamically loading the poll script we need to create the container element first.
    //If we don't then the poll script will try to put it at the end...
    $('<a name="pd_a_' + pollID + '"></a>').appendTo(pollBody);
    $('<div id="PDI_container' + pollID + '" class="PDS_Poll"></div>').appendTo(pollBody);
    
    $('<script type="text/javascript" src="http://s3.polldaddy.com/p/' + pollID + '.js"></script>').appendTo(pollBody);

    var descriptionElement = $('<div class="pds-question-description"></div>');
    descriptionElement.html($(pollNode).children('.pollDescription').html());

    //Wait for the script to load and render before inserting description...
    var questionList = $('#pollContainer .pds-question-inner');
    $.timer(1000, function(timer) {
        if (questionList.length > 0) {
            descriptionElement.appendTo(questionList[0]);
            timer.stop();
        }
        else {
            questionList = $('#pollContainer .pds-question-inner');
        }
    });

}

function renderCompetition() {
    var competitionNode = $('#currentIssue .competition')[0];
    $('#competitionImage')[0].src = $($(competitionNode).children('.imageUrl')[0]).html().replace(/&amp;/g, '&');
    $('#competitionImage').show();
    $('#competitionLink')[0].title = $($(competitionNode).children('.competitionTitle')[0]).html();
    $('#competitionLink')[0].href = $($(competitionNode).children('.url')[0]).html().replace(/&amp;/g, '&');
}

function renderPromotion() {
    var promoNode = $('#currentIssue .promo')[0];
    $('#promoImage')[0].src = $($(promoNode).children('.imageUrl')[0]).html().replace(/&amp;/g, '&');
    $('#promoImage').show();
    $('#promoLink')[0].href = $($(promoNode).children('.url')[0]).html().replace(/&amp;/g, '&');
    
    $('#promoLink')[0].title = $($(promoNode).children('.promotionTitle')[0]).html();
    $('#promoLink')[0].target = $($(promoNode).children('.promoTarget')[0]).html();
    
}


function setForumStyles() {
    $('#profile_forums tr:nth-child(even)').addClass('forumEven');
    $('#profile_forums tr:nth-child(odd)').addClass('forumOdd');
}

function displayCommentDetails() {
    rollingStoneVars.newCommentsHeader = $('<div id="newCommentsHeader"></div>');
    var childNodes = $('#profile_comments').children();
    $.each(childNodes, function(i) {
        if ((this.nodeType == 3) || (this.className != 'cols')) {
            $(this).appendTo(rollingStoneVars.newCommentsHeader);
        }
        else {
            return false;
        }
    });

    //Remove the extraneous parens from above the comment list
    var commentsChildren = $('#profile_comments')[0].childNodes;
    var i = 0;
    for (i = 0; i < commentsChildren.length; i++) {
        if (commentsChildren[i].nodeType == 3) {
            $(commentsChildren[i]).remove();
        }
        else {
            break;
        }
    }

    $(rollingStoneVars.newCommentsHeader).appendTo($('#commentsHeader')[0]);
}