///////////////////////////////////////////////////////////////////////////////
//
// Advertisement
//
// Author: Clayton Wong
//
// Description: JS object used for advertisement rendering and stats
//
///////////////////////////////////////////////////////////////////////////////


var Advertisement =
{
    ///////////////////////////////////////////////////////////////////////////
    //
    // rendering
    //
	AdSlots : [],
	PubId : '',
    Load : function()
    {
        //
        // global left nav
        //
        if(!!Advertisement.AdSlots[0])
		{
            Advertisement.Html.GetRandomAd("globalLeftNavAdvertisement", 121,600, Advertisement.Position.GlobalLeftNav, Advertisement.AdSlots[0]);
		}

        //
        // global footer
        //
        if(!!Advertisement.AdSlots[1])
		{
            Advertisement.Html.GetRandomAd("globalFooterAd", 728,90, Advertisement.Position.GlobalFooter, Advertisement.AdSlots[1]);
		}
		
		//
        // FanBoxHome
        //
        if(!!Advertisement.AdSlots[2])
		{
            Advertisement.Html.GetRandomAd("fanboxHomeRightAdvertisement", 160,600, Advertisement.Position.FanBoxHome, Advertisement.AdSlots[2]);
		}
		
		//
		// Ad - Right 120x600
		//
		if(!!Advertisement.AdSlots[3])
		{
			Advertisement.Html.GetRandomAd("StandAloneRight120x600", 121,653, Advertisement.Position.StandAloneRight_120x600, Advertisement.AdSlots[3]);
		}
		
		//
		// Ad - Right 430x600
		//
		if(!!Advertisement.AdSlots[4])
		{
			Advertisement.Html.GetRandomAd("StandAloneRight430x600", 430,628, Advertisement.Position.StandAloneRight_430x600, Advertisement.AdSlots[4]);
		}
		
		//
		// Ad - RightTop 300x250
		//
		if(!!Advertisement.AdSlots[5])
		{
			Advertisement.Html.GetRandomAd("StandAloneRightTop300x250", 300,278, Advertisement.Position.StandAloneRight_Top_300x250, Advertisement.AdSlots[5]);
		}
		
		//
		// Ad -RightBot 300x350
		//
		if(!!Advertisement.AdSlots[6])
		{
			Advertisement.Html.GetRandomAd("StandAloneRightBot300x250", 300,278, Advertisement.Position.StandAloneRight_Bottom_300x250, Advertisement.AdSlots[6]);
		}
    },
	LoadTopBrowser : function()
	{
		try{
			if (!($('frm' + top.browser.activeWinId).contentWindow.ProfileWindow))
			{
				Advertisement.ActualLoadTopBrowser();
			}
		}
		catch(e)
		{	
	        Advertisement.ActualLoadTopBrowser();
		}
	},
	ActualLoadTopBrowser : function()
	{
        if (!!window.ShowProfileHeaderAd)
        {
            if (!Advertisement.topBrowser)
            {
                Advertisement.topBrowser = document.getElementById('topBrowser');
            }
            if (!Advertisement.topBrowser.firstChild)
            {
                var iframe = document.createElement('iframe');
                iframe.style.height = '90px';
                iframe.style.width = '728px';
                iframe.scrolling = 'no';
                iframe.style.border = 'none';
                Advertisement.topBrowser.appendChild(iframe);
                iframe.src = 'http://www.fanbox.com/socnet/adframe.aspx?PageTimer_Request=' + encodeURIComponent((new Date()).getTime());
            }
            else
            {
                Advertisement.topBrowser.firstChild.contentWindow.reloadMe();
            }
            return true;
        }
        else
        {
            return false;
        }
	},
	LoadOptin : function()
	{
		var atLeastOne = false;
		var optinAdSkyLeftC = top.document.getElementById('optinAdSkyLeftContainer');
		var optinAdSkyRightC = top.document.getElementById('optinAdSkyRightContainer');
		var optinAdBannerLeftC = top.document.getElementById('optinAdBannerLeftContainer');
		var optinAdBannerRightC = top.document.getElementById('optinAdBannerRightContainer');
		var optinAdSkyLeft = top.document.getElementById('optinAdSkyLeft');
		var optinAdSkyRight = top.document.getElementById('optinAdSkyRight');
		var optinAdBannerLeft = top.document.getElementById('optinAdBannerLeft');
		var optinAdBannerRight = top.document.getElementById('optinAdBannerRight');
		if (!!optinAdSkyLeftC)
		{
		    atLeastOne = true;
			optinAdSkyLeftC.style.display = 'block';
		}
		if (!!optinAdSkyRightC)
		{
		    atLeastOne = true;
			optinAdSkyRightC.style.display = 'block';
		}
		if (!!optinAdBannerLeftC)
		{
		    atLeastOne = true;
			optinAdBannerLeftC.style.display = 'block';
		}
		if (!!optinAdBannerRightC)
		{
		    atLeastOne = true;
			optinAdBannerRightC.style.display = 'block';
		}
		if (!atLeastOne)
		{
		    return;
		}
		top.decrementAdCount = decrementAdCount;
		top.PageTimer.AddPlaceholderSession(top.pageAK);
		top.PageTimer.ConnectToSession(window, top.pageAK);
		
		top.PageTimer.AddPlaceholderSession(top.optinAdSkyRightAK);
		top.PageTimer.ConnectToSession(window, top.optinAdSkyRightAK);
		top.PageTimer.DefineProgressCountersForActivityKind(window, ['Ads' + top.optinAdSkyRightAK], top.optinAdSkyRightAK);
		top.PageTimer.DefineProgressCountersForActivityKind(window, ['Ads' + top.pageAK], top.pageAK);
		top.PageTimer.DefineProgressCountersForActivityKind(window, ['Ads' + top.AK], top.AK);
		
		top.BBLoadSponsoredPosts();
		
		
		
		return;
        if(!!Advertisement.AdSlots[0] && !!optinAdSkyLeft)
		{
            Advertisement.Html.GetRandomAdByDiv(optinAdSkyLeft, 160,600, Advertisement.Position.OptIn, Advertisement.AdSlots[0], top.AK, top.pageAK, top.optinAdSkyLeftAK);
		    top.PageTimer.AddPlaceholderSession(top.optinAdSkyLeftAK);
		    top.PageTimer.ConnectToSession(window, top.optinAdSkyLeftAK);
			top.PageTimer.DefineProgressCountersForActivityKind(window, ['Ads' + top.optinAdSkyLeftAK], top.optinAdSkyLeftAK);
			top.PageTimer.DefineProgressCountersForActivityKind(window, ['Ads' + top.pageAK], top.pageAK);
			top.PageTimer.DefineProgressCountersForActivityKind(window, ['Ads' + top.AK], top.AK);
		}
        if(!!Advertisement.AdSlots[1] && !!optinAdSkyRight)
		{
            Advertisement.Html.GetRandomAdByDiv(optinAdSkyRight, 160,600, Advertisement.Position.OptIn, Advertisement.AdSlots[1], top.AK, top.pageAK, top.optinAdSkyRightAK);
		    top.PageTimer.AddPlaceholderSession(top.optinAdSkyRightAK);
		    top.PageTimer.ConnectToSession(window, top.optinAdSkyRightAK);
			top.PageTimer.DefineProgressCountersForActivityKind(window, ['Ads' + top.optinAdSkyRightAK], top.optinAdSkyRightAK);
			top.PageTimer.DefineProgressCountersForActivityKind(window, ['Ads' + top.pageAK], top.pageAK);
			top.PageTimer.DefineProgressCountersForActivityKind(window, ['Ads' + top.AK], top.AK);
		}
        if(!!Advertisement.AdSlots[2] && !!optinAdBannerLeft)
		{
            Advertisement.Html.GetRandomAdByDiv(optinAdBannerLeft, 120,600, Advertisement.Position.OptIn, Advertisement.AdSlots[2], top.AK, top.pageAK, top.optinAdBannerLeftAK);
		    top.PageTimer.AddPlaceholderSession(top.optinAdBannerLeftAK);
		    top.PageTimer.ConnectToSession(window, top.optinAdBannerLeftAK);
			top.PageTimer.DefineProgressCountersForActivityKind(window, ['Ads' + top.optinAdBannerLeftAK], top.optinAdBannerLeftAK);
			top.PageTimer.DefineProgressCountersForActivityKind(window, ['Ads' + top.pageAK], top.pageAK);
			top.PageTimer.DefineProgressCountersForActivityKind(window, ['Ads' + top.AK], top.AK);
		}
        if(!!Advertisement.AdSlots[3] && !!optinAdBannerRight)
		{
            Advertisement.Html.GetRandomAdByDiv(optinAdBannerRight, 120,600, Advertisement.Position.OptIn, Advertisement.AdSlots[3], top.AK, top.pageAK, top.optinAdBannerRightAK);
		    top.PageTimer.AddPlaceholderSession(top.optinAdBannerRightAK);
		    top.PageTimer.ConnectToSession(window, top.optinAdBannerRightAK);
			top.PageTimer.DefineProgressCountersForActivityKind(window, ['Ads' + top.optinAdBannerRightAK], top.optinAdBannerRightAK);
			top.PageTimer.DefineProgressCountersForActivityKind(window, ['Ads' + top.pageAK], top.pageAK);
			top.PageTimer.DefineProgressCountersForActivityKind(window, ['Ads' + top.AK], top.AK);
		}
	},
    _un : '',
    LoadWidget : function(podSize)
    {
        var dimension;
        var position;
    
		if( podSize == 1 )
		{
			dimension = "180x150";
			position = Advertisement.Position.WidgetSingleWide;
		}
		else
		{
			dimension = "430x600";
			position = Advertisement.Position.WidgetDoubleWide;
		}
		
		Advertisement.Html.GetAd_CPX("AdWidget", dimension, position);
    },
    //
    //
    ///////////////////////////////////////////////////////////////////////////
    

    ///////////////////////////////////////////////////////////////////////////
    //
    // stats
    //
    RecordLoad : function ( partnerID, positionID, UTCTicks, Cid )
    {
        this.onload = null;
        Advertisement.Record ( Advertisement.Action.Load, partnerID, positionID, UTCTicks, Cid );
    },
    
    RecordClick : function ( partnerID, positionID, UTCTicks, Cid )
    {
        Advertisement.Record ( Advertisement.Action.Click, partnerID, positionID, UTCTicks, Cid );
    },
    
    Record : function ( actionID, partnerID, positionID, UTCTicks, Cid )
    {
        var u_n;
        try { u_n = top.safeId; }
        catch (e) { u_n = Advertisement._un; };
	    var beacon = document.createElement("SCRIPT");
	    beacon.type = 'text/javascript';
	    beacon.src = "http://www.fanbox.com/Advertisement/Advertisement.ashx?action=" + encodeURIComponent(actionID) + "&partner=" + encodeURIComponent(partnerID) + "&position=" + encodeURIComponent(positionID) + "&ticks=" + encodeURIComponent(UTCTicks) + "&cid=" + encodeURIComponent(Cid) + "&userno=" + u_n + "&rand=" + Math.random();
	    document.getElementsByTagName('head')[0].appendChild(beacon);
    },    

    Action :
    {
        Load : 1,
        Click : 2
    },
    
    Position :
    {
        GlobalLeftNav : 1,
        GlobalFooter : 2,
        WidgetDoubleWide : 3,
        WidgetSingleWide : 4,
        IMSideBar : 5,
        StandardFriendsDisplay : 6,
        OptIn : 7,
        FanFareDoubleWideImage : 8,
        FanFareDoubleWideText : 9,
        FanFareEmbeddedNote : 10,
		WONChatWindow : 11,
		FanFareDoubleWideRightSkyScraper : 12, 
        FanBoxHome : 13,
		StandAloneRight_120x600: 14,
		StandAloneRight_430x600: 15,
		StandAloneRight_Top_300x250: 16,
		StandAloneRight_Bottom_300x250: 17
    },
    //
    //
    ///////////////////////////////////////////////////////////////////////////



    ///////////////////////////////////////////////////////////////////////////
    //
    // Partners
    //
    Partner :
    {
        CPXInteractive : 1,
        AdSense : 2
    },
    //
    //
    ///////////////////////////////////////////////////////////////////////////
    
    
    
    ///////////////////////////////////////////////////////////////////////////
    //
    // Html snippets
    //
    Html :
    {
        GetRandomAd : function(DivID, width, height, positionID, adSlotName, activityKind, allAdsActivityKind, pageActivityKind ){
            var div = document.getElementById(DivID);
            return Advertisement.Html.GetRandomAdByDiv(div, width, height, positionID, adSlotName, activityKind, allAdsActivityKind, pageActivityKind);
        },
        GetRandomAdByDiv : function(div, width, height, positionID, adSlotName, activityKind, allAdsActivityKind, pageActivityKind ){
            if (!!div)
			{
				var old_document_write = document.write;
				document.write = Advertisement.Html.TempWriter;
				Advertisement.Html.TempString = '';
                GA_googleFillSlotWithSize(Advertisement.PubId, adSlotName, width, height);
				document.write = old_document_write;
				if (!!activityKind)
				{
				    div.innerHTML = Advertisement.Html.AddAdCount(Advertisement.Html.TempString, activityKind, allAdsActivityKind, pageActivityKind);
				}
				else
				{
				    div.innerHTML = Advertisement.Html.TempString;
				}
            }
            return !!div
        },
		InternalAd : function(adPositionId)
		{
			var divname = "AdText_" + adPositionId;
			var div = document.getElementById(divname);
			if (!!div)
			{
				div.style.display = "none";
			}
			if (adPositionId == Advertisement.Position.WONChatWindow && !!Advertisement.AdSlots[0])
			{
				var adIframe = document.getElementById('google_ads_iframe_' + Advertisement.AdSlots[0]);
				if (!!adIframe)
				{
					adIframe.height = 278;
				}
			}
			if (adPositionId == Advertisement.Position.GlobalLeftNav && !!Advertisement.AdSlots[0])
			{
				var adIframe = document.getElementById('google_ads_iframe_' + Advertisement.AdSlots[0]);
				if (!!adIframe)
				{
					adIframe.height = 653;
				}
			}
			if (adPositionId == Advertisement.Position.GlobalFooter && !!Advertisement.AdSlots[1])
			{
				var adIframe = document.getElementById('google_ads_iframe_' + Advertisement.AdSlots[1]);
				if (!!adIframe)
				{
					adIframe.height = 128;
				}
			}
			if (adPositionId == Advertisement.Position.OptIn && !!Advertisement.AdSlots[0])
			{
				var adIframe = document.getElementById('google_ads_iframe_' + Advertisement.AdSlots[0]);
				if (!!adIframe)
				{
					adIframe.height = 653;
				}
			}
		},
		TempWriter : function(s)
		{
			Advertisement.Html.TempString += s;
		},
		TempString : '',
		AddAdCount : function(adText, activityKind, allAdsActivityKind, pageActivityKind)
		{
			/* The handler runs more reliably by altering the HTML instead of attaching the function directly in the DOM. */
			var cursorIndex = adText.search(/onload=/i);
			if(cursorIndex !== -1)
			{
				cursorIndex += 7;
				var quote = adText.charAt(cursorIndex);
				switch(quote)
				{
					case "\"":
					case "'":
						cursorIndex = adText.indexOf(quote, cursorIndex + 1);
						if(cursorIndex !== -1)
						{
							adText = adText.substring(0, cursorIndex) + ";decrementAdCount(" + activityKind + "," + allAdsActivityKind + "," + pageActivityKind + ");" + adText.substr(cursorIndex);
						}
						else
						{
							decrementAdCount(activityKind, allAdsActivityKind, pageActivityKind);
						}
						break;
					default:
						decrementAdCount(activityKind, allAdsActivityKind, pageActivityKind);
						break;
				}
			}
			else
			{
				cursorIndex = adText.search(/<iframe/i);
				if(cursorIndex !== -1)
				{
					cursorIndex += 7;
					adText = adText.substring(0, cursorIndex) + " onload=\"decrementAdCount(" + activityKind + "," + allAdsActivityKind + "," + pageActivityKind + ");\"" + adText.substr(cursorIndex);
				}
				else
				{
					cursorIndex = adText.search(/<img/i);
					if(cursorIndex !== -1)
					{
						cursorIndex += 4;
						adText = adText.substring(0, cursorIndex) + " onload=\"decrementAdCount(" + activityKind + "," + allAdsActivityKind + "," + pageActivityKind + ");\"" + adText.substr(cursorIndex);
					}
					else
					{
						decrementAdCount(activityKind, allAdsActivityKind, pageActivityKind);
					}
				}
			}
			return adText;
		}
    }
    //
    //
    ///////////////////////////////////////////////////////////////////////////
};

function decrementAdCount(activityKind, allAdsActivityKind, pageActivityKind)
{
    top.PageTimer.FulfillProgressCounter(window, "Ads" + activityKind);
    top.PageTimer.FulfillProgressCounter(window, "Ads" + allAdsActivityKind);
    top.PageTimer.FulfillProgressCounter(window, "Ads" + pageActivityKind);
}

function BBLoadSponsoredPosts() {
	var page = statPageName;
	
	jQuery.post(
		"/DeveloperApp/BlogBubble.ashx",
		{ page: page },
		BBLoadSponsoredPosts_Success,
		"json");
}

function BBLoadSponsoredPosts_Success(data) {
	decrementAdCount(top.optinAdSkyRightAK, top.pageAK, top.AK);

	if (data && data.success) {
		jQuery("#blogPromotions").html(data.html);
		BBShowHideSponsoredPosts();
		
		if (data.displayusageurl) {
			jQuery.post(data.displayusageurl);
		}
	}
}

function BBShowHideSponsoredPosts()
{
    var blogBubbleContainer = jQuery("#blogBubbleContainer");
    var blogPromotions = jQuery("#blogPromotions").children(".BlogBubble").not("[placeholder]");
    
    if (blogPromotions.length > 0)
    {
        blogBubbleContainer.show();
    }
    else
    {
        blogBubbleContainer.hide();
    }
}

function BBClose(o, e) {
	preventDefault(e);
	
	var blogBubble = jQuery(o).closest(".BlogBubble");
	var newBlogBubble = jQuery('<div placeholder="1" style="text-align: center;">' +
		'<span style="display: inline-block; vertical-align: middle; width: 0px; height: 100%">&nbsp;</span>' +
		'<img src="//files.fbstatic.com/Themes/_images/Loading_bar_2.gif" alt="Loading..." height="6" width="' +
		(blogBubble.width() - 12) +
		'" /></div>');
	newBlogBubble.attr("id", blogBubble.attr("id"));
	newBlogBubble.attr("class", blogBubble.attr("class"));
	newBlogBubble.css("height", blogBubble.height());
	
	var otherBubbleIds = [ ];
	jQuery("#blogPromotions > .BlogBubble").not(blogBubble).each(function() { otherBubbleIds.push(jQuery(this).attr("id")); });
	var otherbbs = otherBubbleIds.join(',');
	
	blogBubble.replaceWith(newBlogBubble);
	
	var bubbleId = blogBubble.attr("id");
	var bbposition = blogBubble.attr("bbposition");
	var page = statPageName;
	
	jQuery.ajax({ url: "/DeveloperApp/blogbubble.ashx",
		type: "post",
		data: { bbid: bubbleId, bbposition: bbposition, otherbbs: otherbbs, page: page },
		dataType: "json",
		success: BBSwapBubble,
		error: BBSwapBubble_Error});
}

function BBStopBubble(o, e) {
    preventDefault(e);
    
    if (!!window.event && window.event.cancelBubble !== undefined) {
        window.event.cancelBubble = true;
    }
    else {
        e.stopPropagation();
    }
}

function BBSwapBubble(response) {
	if (response && response.oldbbid)
	{
		var oldbb = jQuery("#" + response.oldbbid);
		oldbb.empty();
	
		if (response.success && response.count > 0 && response.html)
		{
			var newbb = jQuery(response.html);
			var newbbid = newbb.attr("id");
			
			newbb.attr("class", oldbb.attr("class"));
			
			if (jQuery("#" + newbbid).length) {
				var bbposition = newbb.attr("bbposition");
	
				var otherBubbleIds = [ ];
				jQuery("#blogPromotions > .BlogBubble").not(oldbb).each(function() { otherBubbleIds.push(jQuery(this).attr("id")); });
				var otherbbs = otherBubbleIds.join(',');
				var page = statPageName;
				
				jQuery.ajax({ url: "/DeveloperApp/blogbubble.ashx",
					type: "post",
					data: { bbid: response.oldbbid, bbposition: bbposition, otherbbs: otherbbs, page: page },
					dataType: "json",
					success: BBSwapBubble,
					error: BBSwapBubble_Error});
			}
			else {
				oldbb.replaceWith(newbb);
				
				if (response.displayusageurl)
				{
					new Ajax.Request(response.displayusageurl);
				}
				
				var tooltipSpan = jQuery(newbb).find(".BlogBubbleInfo span");
				if (tooltipSpan.length) {
				    ConnectInlineHTMLTooltipTargetEvents(tooltipSpan[0]);
				
				    if (response.tooltip) {
				        var tooltip = jQuery(response.tooltip);
					    jQuery("body").append(tooltip);
					    ConnectInlineHTMLTooltipEvents(tooltip[0]);
				    }
				}
			}
		}
		else {
			oldbb.removeAttr("id");
		}
	}
	
	BBShowHideSponsoredPosts();
}

function BBSwapBubble_Error() {
	jQuery(".BlogBubble").filter("[placeholder]").empty();
	
	BBShowHideSponsoredPosts();
}

function preventDefault(e) {
    if (e.preventDefault)
    {
        e.preventDefault();
    }
    else
    {
        e.returnValue = false;
    }
}
