var ggItems = [];
var ggCurrentIndex;
var loc = 'content_detail';
        
function addAsFavorite(){
    var options = {
    		"c":ggChain,
    		"loc":loc,
    		"contentid":ggCurrentContentItem.pid
    }; 
    var post_auth = {'action':'favorite','data':options};   
    if (!isAuthed(false,post_auth,$('tw_favoriteContainer'))) return;    
    options.userid = ggCurrentUserId;
    options.contentType = ggCurrentContentItem.base_type;
    options.action = 'favorited';
    ajax('ajax/content/act.php',options,function (transport)
            {$('tog_isFavorite_true').show();$('tog_isFavorite_false').hide();});
}
function removeAsFavorite(){
    if (!isAuthed(true)) return;
    ajax('ajax/content/act.php',{action:'unfavorited','c':ggChain,'loc':loc,userid:ggCurrentUserId,contentid:ggCurrentContentItem.pid,contentType:ggCurrentContentItem.base_type},function (transport)
            {$('tog_isFavorite_true').hide();$('tog_isFavorite_false').show();});
}

function report()
{
	
    if (!isAuthed(true)) return;            
    ajax('ajax/content/report.php',{userid:ggCurrentUserId,'c':ggChain,contentid:ggCurrentContentItem.pid,'loc':loc,contentType:ggCurrentContentItem.base_type},function (transport)
            {alert('This content item has been reported and will be flagged for review by system administrators.')});
}

function doRating(inRating)
{         
    invalidate();
    var options = {
		"c":ggChain,
		"loc":loc,
		"contentid":ggCurrentContentItem.pid,
		"rating":inRating/5.0
    }; 
    var post_auth = {'action':'rate','data':options}; 
    if (!isAuthed(false,post_auth,$('tw_rateContainer'))) return; 
    options.action = 'rated';
    options.userid = ggCurrentUserId;
    options.contentType = ggCurrentContentItem.base_type;
    
    ajax('ajax/content/act.php',options,function (transport){/*no action*/});
}      
   
function addTags()
{          
    invalidate();
    var options = {
		"c":ggChain,
		"loc":loc,
		"contentid":ggCurrentContentItem.pid,
		"tags":$('tagsAdd').value
    }; 
    var post_auth = {'action':'tag','data':options}; 
    if (!isAuthed(false,post_auth,$('tw_tagContainer'))) return; 
    
    options.action = 'tagged';
    options.userid = ggCurrentUserId;
    options.contentType = ggCurrentContentItem.base_type;
    
    ajax('ajax/content/tag.php',options,function (transport)
            {tagsAdded(transport.responseText)});
} 
function tagsAdded(response)
{
	$('tagsAdd').value = '';
    $('cloudTagMessage').update('Your tag(s) have been added:');
    $('cloudTagDiv').update(response);
}




function watchContent()
{
    ajax('ajax/content/act.php',{action:'viewed','r':ggRef, 's':ggSvc,'c':ggChain,'loc':loc,userid:ggCurrentUserId,'loc':loc,contentid:ggCurrentContentItem.pid,contentType:ggCurrentContentItem.base_type},function (transport)
            {
                // no visible action.
            });
}


function playContent(notAvailable)
{
    var pOptions = {action:'played','r':ggRef, 's':ggSvc,'c':ggChain,'loc':loc,userid:ggCurrentUserId,'loc':loc,contentid:ggCurrentContentItem.pid,contentType:ggCurrentContentItem.base_type};
    if (notAvailable)
    {
        pOptions.unavailable = true;
    }
    ajax('ajax/content/act.php',pOptions,function (transport)
            {
                // no visible action.
            });
}

function comment()
{
    invalidate();
    var options = {
		"c":ggChain,
		"loc":loc,
		"ownerid":ggCurrentContentItem.owner_id,
		"contentid":ggCurrentContentItem.pid,
		"message":$('txtComment').value
    }; 
    var post_auth = {"action":"contentcomment","data":options}; 
    if (!isAuthed(false,post_auth,$('tw_commentContainer'))) return; 
    
    options.action = 'comment';
    options.userid = ggCurrentUserId;
    options.contentType = ggCurrentContentItem.base_type;
    
    ajax('ajax/content/comment.php', options,
        function (transport){
        	$('txtComment').value = '';
            $('dynamicAreaComment').update(transport.responseText);
    	},
    	'post'
    );
}    

function invalidate()
{
    try
    {   
        ggRenderInfoCache[ggCurrentContentItem.pid] = undefined;
    }
    catch (e) {}
}

function ajax(url, options, successFunc,method)
{
    var pMethod = 'get';
    if (method == 'post') pMethod = 'post';
    new Ajax.Request(url, 
    {
		method:pMethod,
		requestHeaders: {Accept: 'application/json'},
		parameters:options,
		onSuccess: successFunc
    });           

}

function toggleAdsView()
{
    GGshowingTags = !GGshowingTags;
    if (GGshowingTags)
    {
        $('tagAdder').style.display="block";
        $('cloudTagMessage').style.display="block";
        $('tagToggler').update('finished');
    }
    else
    {
        $('cloudTagMessage').style.display="none";
        $('tagAdder').style.display="none";
        $('tagToggler').update('add tags');
    }
}
function toggleCommentsView()
{
    GGshowingComments = !GGshowingComments;
    if (GGshowingComments)
    {
        $('commentAdder').style.display="block";
        $('commentMessage').style.display="block";
        $('commentToggler').update('finished');
    }
    else
    {
        $('commentMessage').style.display="none";
        $('commentAdder').style.display="none";
        $('commentToggler').update('add comment');
    }
}

function getTags()
{
    ajax('ajax/content/getTags.php',{contentid:ggCurrentContentItem.pid},function (transport) {getTags_response(transport.responseText)});
}
function getTags_response(response)
{
//    ggRenderInfoCache[];
    $('cloudTagDiv').update(response);
}       
function getRatings()
{
}

function getRenderDetails()
{
    ajax('ajax/content/getRenderInfo.php',{contentType:ggCurrentContentItem.base_type,'loc':loc,setviewed:true, contentid:ggCurrentContentItem.pid,userid:ggCurrentUserId},function (transport) {getRenderDetails_response(transport.responseText)});
}
function getRenderDetails_response(response)
{
    try
    {
        var pResponse = response.sub('\n','');
        pResponse = pResponse.sub('\r','');
        pResponse = pResponse.evalJSON(true);
        ggRenderInfoCache[pResponse['content_id']] = pResponse;
        renderDetails(pResponse);
    } catch (e)
    {
//        alert(e);
    }
}
function renderDetails(inObj)
{
    $('cloudTagDiv').update(inObj['tags']);
    var pComments = (inObj['comments'] != '') ? unescape(inObj['comments']) : '<span class="userNote">No comments have been added to this content item</span><br/>';
    $('dynamicAreaComment').update(pComments);
    ratingPipe_me.setValue(inObj['ratings']['userRating'] * 5,false,true); 
//    ratingPipe_friends.setValue(inObj['ratings']['friendRatings'] * 5,false,true); 
    ratingPipe_all.setValue(inObj['ratings']['allRatings'] * 5,false,true); 
}
function setContentId(newId)
{
//    GGcontentId = parseInt(newId,10);
//    GGuserId = parseInt(GGuserId,10);
    ggPhotoAlbum.currentActive = newId;
    ggCurrentContentItem = ContentItem.getById(newId);
//    var pContentItem = ContentItem.getById(newId);
    //TODO: Fix.
//    GGcontentType = 'Photo';
    $('dynamicAreaTitle').update('Photo #' + ggPhotoAlbum.getIndexFromPid(newId) + ' - ' + ggCurrentContentItem.title);
    $('dynamicAreaUpdated').update('<span class="userNote">added ' + ggCurrentContentItem.getStandardUpdateTime() + ' ( About '+ggCurrentContentItem.getFriendlyUpdateTime()+' )</span>');
    if (ggRenderInfoCache[newId] == undefined)
    {
        getRenderDetails();
    }
    else
    {
        renderDetails(ggRenderInfoCache[newId]);
    }
}

function generate_linkback(code)
{
	//var protocol = (location.host=='www.ripl.com') ? '' : 'http://'; // www. will hyperlink on twitter without http:// (shorter)
    var baseLinkback = 'http://' + location.host + '/?'+code+'=' + ggCurrentUserId.toString(36) + '-' + ggOriginalContentItem.pid.toString(36);
  
    if (ggPhotoAlbum != null)
    {
        baseLinkback += '#i_' + ggPhotoAlbum.currentActive; 
    };
    return baseLinkback;
}

function share_ripl()
{
    location.href="messageWrite.php?contentid=" + ggOriginalContentItem.pid + '&subid=' + ggCurrentContentItem.pid;
}
function share_email()
{
    var pLink = generate_linkback('e');
    var mailto = 'mailto:?subject=I found this on RIPL&body=Check out this ' + ggCurrentContentItem.base_type + ' that I found on RIPL:  ';
    mailto += pLink;
    window.location=mailto;
}
function share_digg()
{
    var baseHref = 'http://digg.com/submit?url=';
    var pOptions = escape(generate_linkback('d'));
    if (ggCurrentContentItem.title != 'Untitled') pOptions += '&title='+escape(ggCurrentContentItem.title);
    if (ggCurrentContentItem.base_type == 'Photo') pOptions += '&media=image';
    else if (ggCurrentContentItem.base_type == 'Video')pOptions += '&media=video';
    if (ggCurrentContentItem.description != '') pOptions += '&bodytext='+escape(ggCurrentContentItem.description);

    window.open(baseHref + pOptions,'digg','toolbar=yes,width=800,height=550');

    return false;
}
function share_facebook()
{
    var pLink = escape(generate_linkback('f'));
    window.open('http://www.facebook.com/share.php?u=' + pLink,'facebook','toolbar=no,width=800,height=550');
    return false;
}
function share_delicious()
{
    var pLink = escape(generate_linkback('l'));
    window.open('http://delicious.com/save?v5&noi&jump=close&url=' + pLink + '&title' +escape(ggCurrentContentItem.title),'delicious','toolbar=no,width=800,height=550');
    return false;
}

var ggNapsterId = 0;

document.observe("dom:loaded", function()
{
    switch (ggOriginalContentItem['base_type'])
    {
        case 'PhotoAlbum':
            ggItems = ggRawData['items'];
            ggCurrentIndex = ggItems[0].pid;
            ggPhotoAlbum = new PhotoAlbum(ggRawData);
            $('dynamicArea').update(ggPhotoAlbum.renderBar());
            $('dynamicArea').insert('<br class="clearBoth" />');
            $('dynamicArea').insert('<table class="widthFull"><tr><td id="dynamicAreaTitle" style="text-align:left; padding-left:10px">&nbsp;</td><td id="dynamicAreaUpdated" style="text-align:right">foo</td></tr></table>');
            $('dynamicArea').insert(ggPhotoAlbum.renderContentArea());

            var pDefault = (location.hash != '') ? location.hash : 'first';
            new Control.Tabs('photo_tabs',{  
                 hover: true,
                 defaultTab:pDefault,
                 afterChange:function(new_container)
                 {
                    setContentId(new_container.getAttribute('ripl:contentid'));
                 }
            });  
            break;
        case 'Music':
            if (ggNapsterId <= 0)
            {
                $('dynamicArea').update('<div class="musicWrapper">'+
        				'<div class="musicFrame">'+
        				'<div class="musicCon">'+
        					'<img width="270" height="270" class="prv_musicBG" src="'+((ggOriginalContentItem['preview_image_url'] != null)?ggOriginalContentItem['preview_image_url'] : 'images/music/no_art_large.jpg')+'" alt="" />'+
        					'<img width="302" height="288" class="prv_music" src="images/music/frame_large.png" alt="" />'+
        				'</div>'+
    				'</div>'+
    				'<div class="musicText">'+
						'<span class="musicTitle">' + ggOriginalContentItem['title'] + '</span><br /><span class="musicArtist">' + ggOriginalContentItem['artist'] + '</span><br /><span class="musicAlbum">' + ggOriginalContentItem['album'] + '</span>'+
					'</div>'+
    			'</div>');
                $('dynamicTitle').update();
                playContent(false);
            }
            else
            {
                playContent();
            }
            break;
        case 'Video':
            playContent();
            break;
        case 'Photo':
            $('dynamicArea').update('<img src="'+ggOriginalContentItem['preview_image_url']+'" alt="" />');
            playContent();
            break;
    }
});