//Global Variables
var bt_numOfItemsToShow = 5;
var activeTab;
var photo_tab = "photo";
var video_tab = "video";
var travel_journal_tab = "travelJournal";
var var_yes = "yes";
var var_no = "no";
var adminTag_editorPref = "editorial Preference";
var adminTag_publish = "publish";
var photo_cache_avail = "no";
var video_cache_avail = "no";
var travelJournal_cache_avail = "no";
var var_photos = "photo(s)";
var var_videos = "video(s)";
var var_travelJournals = "travel journal(s)";

function showUploadedTime(pubDate)
{
    //alert("pubDate::"+pubDate);
    var uploadedTime = "";
    var d = new Date(pubDate);
    var dateFunc = new Date();
    var timeSince = dateFunc.getTime() - d.getTime();
    var inSeconds = timeSince / 1000;
    var inMinutes = timeSince / 1000 / 60;
    var inHours = timeSince / 1000 / 60 / 60;
    var inDays = timeSince / 1000 / 60 / 60 / 24;
    var inWeeks = timeSince / 1000 / 60 / 60 / 24 / 7;
    var inMonths = timeSince / 1000 / 60 / 60 / 24 / 30;
    var inYears = timeSince / 1000 / 60 / 60 / 24 / 365;

    //document.write("secs:"+inSeconds+":mins:"+inMinutes+":inHours:"+inHours+":inDays:"+inDays+":inWeeks:"+inWeeks+":inMonths:"+inMonths+":inYears:"+inYears+"<br/>");

    // in seconds
    if(Math.round(inSeconds) == 1){
    uploadedTime = "1 second ago";
    }
    else if(Math.round(inMinutes) < 1){
    uploadedTime = Math.round(inSeconds) + " seconds ago";
    }

    // in minutes
    else if(Math.round(inMinutes) == 1){
    uploadedTime = "1 minute ago";
    }
    else if(Math.round(inHours) < 1){
    uploadedTime = Math.round(inMinutes) + " minutes ago";
    }

    // in hours
    else if(Math.round(inHours) == 1){
    uploadedTime = "1 hour ago";
    }
    else if(Math.round(inDays) < 1){
    uploadedTime = Math.round(inHours) + " hours ago";
    }

    // in days
    else if(Math.round(inDays) == 1){
    uploadedTime = "1 day ago";
    }
    else if(Math.round(inWeeks) < 1){
    uploadedTime = Math.round(inDays) + " days ago";
    }

    // in weeks
    else if(Math.round(inWeeks) == 1){
    uploadedTime = "1 week ago";
    }
    else if(Math.round(inMonths) < 1){
    uploadedTime = Math.round(inWeeks) + " weeks ago";
    }

    // in months
    else if(Math.round(inMonths) == 1){
    uploadedTime = "1 month ago";
    }
    else if(Math.round(inYears) < 1){
    uploadedTime = Math.round(inMonths) + " months ago";
    }

    // in years
    else if(Math.round(inYears) == 1){
    uploadedTime = "1 year ago";
    }
    else
    {
    uploadedTime = Math.round(inYears) + " years ago";
    }

    return uploadedTime;
}

function sendRss(params, handler, errorHandler){
    $.ajax({
        url: '/bt-socialmedia/RssServlet',
        data: params,
        success : handler,
        error : errorHandler
    });
}

function showRss(json, txtStatus){

    if( txtStatus == 'success' )
    {
        var rssFeed = eval('(' +json+ ')');
        var html = '';
        //alert("rssFeed::"+rssFeed);
        setTagsUrlandCount(rssFeed.totalItems);
        if(rssFeed.error == undefined)
        {
            if(rssFeed.items != null)
            {
                $.each(rssFeed.items, function(i,item){
                    if( i == (bt_numOfItemsToShow-1) ){
                        html += '<li class="last">';
                    }else{
                        html += '<li>';
                    }
                   
                    if(activeTab == travel_journal_tab)
                    {
                        html += '<a class="thumbs" href="'+ item.link +'" style="background:#eee url('+ item.uploadedByThumbnail +') no-repeat center center">' ;
                    }else{
                        $.each(item.mediaContent.mediaThumbnails, function(j,mediaThumbnail){
                            
                            if( mediaThumbnail.width == 100 )
                            {
                                // html += '<a class="thumbs" href="'+ item.link +'"><img class="thumbs" src="' + mediaThumbnail.url + '" alt="" /></a>' ;
                                html += '<a class="thumbs" href="'+ item.link +'" style="background:#eee url('+ mediaThumbnail.url +') no-repeat center center">' ;
                            }
                        });
                    }
                    html += '<h4><a href="'+ item.link +'">' + item.title + '</a></h4>';
                    html += '<p> <span class="credit">By <a class="membername" href="'+item.uploadedByUrl +'">'+ item.creator + '</a>' ;
                    if( item.level == "SuperMember")
                    {
                        html += '<a class="memberlevel active super"><span>SuperMember '+ item.points+' pts<span class="arrow"></span></span></a></span>';
                    }
                    else if( item.level == "GoldMember")
                    {
                        html += '<a class="memberlevel active gold"><span>GoldMember '+ item.points+' pts<span class="arrow"></span></span></a></span>';
                    }
                    else if( item.level == "SilverMember")
                    {
                        html += '<a class="memberlevel active silver"><span>SilverMember '+ item.points+' pts<span class="arrow"></span></span></a></span>';
                    }
                    else{
                        // html += '<a class="memberlevel active gold"><span>SilverMember '+ item.points+' pts<span class="arrow"></span></span></a></span>';
                        html += '<a class="memberlevel"></a></span>';
                    }
                    html += '<span class="pubdate">'+ showUploadedTime( item.pubDate ) +'</span></p>' ;
                    html += "</li>";
                });

                if( rssFeed.items.length < bt_numOfItemsToShow)
                {
                    html = addUploadPhotos(html, bt_numOfItemsToShow-(rssFeed.items.length));
                }
            }else{
                html = addUploadPhotos(html, bt_numOfItemsToShow);
            }
        }else{
            html += "<li><h4>"+rssFeed.error+"</h4></li>";
        }
        //alert("Total Items::"+rssFeed.totalItems);
        clearContent();
        appendHtmlToTab(html);
    }else{
        alert("Failure in getting rss");
    }
}

function showRssErrorHandler(XMLHttpRequest, textStatus, errorThrown){
    alert("Request Status::"+textStatus+">>>>>>>error Message::"+errorThrown);
}

function addUploadPhotos(html, number)
{
    for(var i=0;i< number;i++){
		 
		if( i == (number-1) ){
			html += '<li class="upload last">';
		}else{
			html += "<li class='upload'>";
		}
		 
        if( activeTab == photo_tab ){
            html += '<a class="thumbs" href=\'javascript:submitForm("http://mybt.budgettravel.com/kickapps/service/displayPhotoUpload.kickAction?as=21864", "sso")\'><img src="' + "http://budgettravel.com/bt-srv/test/projects/2009/reader_media/upload_your_photo.gif" + '" /></a>' ;
        }else if( activeTab == video_tab ){
            html += '<a class="thumbs" href=\'javascript:submitForm("http://mybt.budgettravel.com/kickapps/service/displayVideoUpload.kickAction?as=21864", "sso")\'><img src="' + "http://budgettravel.com/bt-srv/test/projects/2009/reader_media/upload_your_video.gif" + '" /></a>' ;
        }else if( activeTab == travel_journal_tab ){
            html += '<a class="thumbs" href=\'javascript:submitForm("http://mybt.budgettravel.com/kickapps/view/displayAddBlog.kickAction?as=21864", "sso")\'><img src="' + "http://budgettravel.com/bt-srv/test/projects/2009/reader_media/upload_your_journal.gif" + '" /></a>' ;
        }
        html += "</li>";
    }
    return html;
}


$(document).ready(function(){
									
		/* switch tabs */
		$('#wrapper_readermedia ul.tab_headings li').click(function()
		{
			$('#wrapper_readermedia ul.tab_headings li').removeClass('active');
			$('#wrapper_readermedia li.tab').removeClass('active');

			var tabClass = $(this).attr('class');
			$('.' + tabClass).addClass('active');
		});
		
		/* rounded corners on the tabs */
		$('#wrapper_readermedia ul.tab_headings li').append('<span class="ul"></span><span class="ur"></span>');

		/* populate the contents of each tab */
    if(  window['bt_IncludeSocialMediaPhotos'] != undefined && bt_IncludeSocialMediaPhotos == var_yes ){
        activeTab = photo_tab;
        sendRss(createFeedUrl(),showRss, showRssErrorHandler);
    }else if( window['bt_IncludeSocialMediaVideos'] != undefined && bt_IncludeSocialMediaVideos == var_yes ){
        activeTab = video_tab;
        sendRss(createFeedUrl(),showRss, showRssErrorHandler);
    }else if( window['bt_IncludeSocialMediaJournals'] != undefined && bt_IncludeSocialMediaJournals == var_yes ){
        activeTab = travel_journal_tab;
        sendRss(createFeedUrl(),showRss, showRssErrorHandler);
    }

    $('#tabRMPhotos').click(function(){
        activeTab = photo_tab;
        if( photo_cache_avail == var_no )
        {
            //alert("Clicked photos tab");
            sendRss(createFeedUrl(),showRss, showRssErrorHandler);
        }
    });

    $('#tabRMVideos').click(function(){
        activeTab = video_tab;
        if( video_cache_avail == var_no )
        {
            //alert("Clicked videos tab");
            sendRss(createFeedUrl(),showRss, showRssErrorHandler);
        }
    });

    $('#tabRMJournals').click(function(){
        activeTab = travel_journal_tab;
        if( travelJournal_cache_avail == var_no )
        {
            //alert("Clicked TravelJournals tab");
            sendRss(createFeedUrl(),showRss, showRssErrorHandler);
        }
    });

    $('span.tags').replaceWith(quotedTags());
    
});

function quotedTags(){
    var quotedTags = '<span> ';
    var tagsArr = bt_readerMediaTags.split(",");
    $.each(tagsArr,function(i, tag){
        tag = $.trim(tag);
        if( i > 0)
        {
            quotedTags += " or ";
        }
        var tagArr = tag.split(" ");
        if(tagArr.length > 1)
        {
            quotedTags += "\""+ tag.bold() + "\"";
        }else{
            quotedTags += tag.bold();
        }
    });
    quotedTags += '</span>';
    return quotedTags;
}

function setTagsUrlandCount(count) {
    //alert("setTagsUrlandCount Total Items::"+count);
    if( activeTab == photo_tab ){
        if( window['bt_SocialMediaPhotosEditorsChoice'] != undefined && bt_SocialMediaPhotosEditorsChoice == var_yes )
        {
            $('#tabReaderMediaPhotos ul.upload span').removeClass('editors_choice_tags');
        }    
        $('#tabReaderMediaPhotos ul.upload span.count').append(count);
        $('#tabReaderMediaPhotos ul.upload li.tags a').attr("href", "http://mybt.budgettravel.com/service/searchEverything.kickAction?as=21864&includePhoto=on&keywords="+bt_readerMediaTags);
    }else if( activeTab == video_tab ){
        if( window['bt_SocialMediaVideosEditorsChoice'] != undefined && bt_SocialMediaVideosEditorsChoice == var_yes )
        {
            $('#tabReaderMediaVideos ul.upload span').removeClass('editors_choice_tags');
        }    
        $('#tabReaderMediaVideos ul.upload span.count').append(count);
        $('#tabReaderMediaVideos ul.upload li.tags a').attr("href", "http://mybt.budgettravel.com/service/searchEverything.kickAction?as=21864&includeVideo=on&keywords="+bt_readerMediaTags);
    }else if( activeTab == travel_journal_tab ){
        if( window['bt_SocialMediaJournalsEditorsChoice'] != undefined && bt_SocialMediaJournalsEditorsChoice == var_yes )
        {
            $('#tabReaderMediaJournals ul.upload span').removeClass('editors_choice_tags');
        }    
        $('#tabReaderMediaJournals ul.upload span.count').append(count);
        $('#tabReaderMediaJournals ul.upload li.tags a').attr("href", "http://mybt.budgettravel.com/service/searchEverything.kickAction?as=21864&includeBlog=on&keywords="+bt_readerMediaTags);
    }
}

function clearContent() {
    if( activeTab == photo_tab ){
        $('#tabReaderMediaPhotos ul.thumbs').empty();
    }else if( activeTab == video_tab ){
        $('#tabReaderMediaVideos ul.thumbs').empty();
    }else if( activeTab == travel_journal_tab ){
        $('#tabReaderMediaJournals ul.thumbs').empty();
    }
}

function appendHtmlToTab(html) {
    if( activeTab == photo_tab ){
        $('#tabReaderMediaPhotos ul.thumbs').append($(html));
        photo_cache_avail = var_yes;
    }else if( activeTab == video_tab ){
        $('#tabReaderMediaVideos ul.thumbs').append($(html));
        video_cache_avail = var_yes;
    }else if( activeTab == travel_journal_tab ){
        $('#tabReaderMediaJournals ul.thumbs').append($(html));
        travelJournal_cache_avail = var_yes;
    }
}

function createFeedUrl()
{
    var feedUrl = '';
    if( activeTab == photo_tab )
    {
        if( window['bt_SocialMediaPhotosFeedURL'] != undefined && bt_SocialMediaPhotosFeedURL != null && bt_SocialMediaPhotosFeedURL != "" )
        {
            feedUrl += "feedUrl="+escape(bt_SocialMediaPhotosFeedURL);
        }else{
            feedUrl += "mediaType=photo&tags="+bt_readerMediaTags+"&quantity="+bt_numOfItemsToShow;
            if( window['bt_SocialMediaPhotosEditorsChoice'] != undefined && bt_SocialMediaPhotosEditorsChoice == var_yes )
            {
                feedUrl += "&adminTags="+adminTag_editorPref;
            }else{
                feedUrl += "&adminTags="+adminTag_publish;
            }
        }

    }else if( activeTab == video_tab )
    {
        if( window['bt_SocialMediaVideosFeedURL'] != undefined && bt_SocialMediaVideosFeedURL != null && bt_SocialMediaVideosFeedURL != "" )
        {
            feedUrl += "feedUrl="+escape(bt_SocialMediaVideosFeedURL);
        }else{
            feedUrl += "mediaType=video&tags="+bt_readerMediaTags+"&quantity="+bt_numOfItemsToShow;
            if( window['bt_SocialMediaVideosEditorsChoice'] != undefined && bt_SocialMediaVideosEditorsChoice == var_yes )
            {
                feedUrl += "&adminTags="+adminTag_editorPref;
            }else{
                feedUrl += "&adminTags="+adminTag_publish;
            }
        }

    }else if( activeTab == travel_journal_tab )
    {
        if( window['bt_SocialMediaJournalsFeedURL'] != undefined && bt_SocialMediaJournalsFeedURL != null && bt_SocialMediaJournalsFeedURL != "" )
        {
            feedUrl += "feedUrl="+escape(bt_SocialMediaJournalsFeedURL);
        }else{
            feedUrl += "mediaType=blog&tags="+bt_readerMediaTags+"&quantity="+bt_numOfItemsToShow;
            if( window['bt_SocialMediaJournalsEditorsChoice'] != undefined && bt_SocialMediaJournalsEditorsChoice == var_yes )
            {
                feedUrl += "&adminTags="+adminTag_editorPref;
            }else{
                feedUrl += "&adminTags="+adminTag_publish;
            }
        }
    }
    return feedUrl;
}


