﻿/*
 * @author Marco, Tom
 */

/*
 * Create Bloom namespace
 */
if (!window.Bloom) { window.Bloom = {}; }

/*
 * Create ad namespace
 */
Bloom.Adverts = {};

/*
 * Create individual ad object
 */
Bloom.Adverts.Advert = function() {}
Bloom.Adverts.Advert.prototype =
{
	Width: 0,
	Height: 0
}

/*
 * Activate default ad object if exists
 */
$(document).ready(function() {
	if( Bloom.Adverts.AdvertServer.Current )
	{
		Bloom.Adverts.AdvertServer.Current.CalcRSI();
		Bloom.Adverts.AdvertServer.Current.RefreshAdverts();
	}
});

/*
 * Create a new ad server
 * @constructor
 * @param {string} serverUrl Ad Server URL
 */
Bloom.Adverts.AdvertServer = function( sServarURL )
{
	this.Server = sServarURL;
	this.ServerId = ( Math.round(Math.random() * 100000000) );
}

/*
 * Ad serving methods
 */
Bloom.Adverts.AdvertServer.prototype =
{
	Server: null,
	Site: null,
	Area: null,
	Adverts: [],
	Off: false,
	RSI:'',
	AdHash:{},

	
	/*
	 * Add an advert to the page, called inline & onload
	 * @param {object} oAdvert Ad object to register in ad server object
	 */
	RegisterAdvert: function( oAdvert )
	{
		if( this.AdHash[ oAdvert.Width + 'x' + oAdvert.Height ] === undefined )
		{
			this.AdHash[ oAdvert.Width + 'x' + oAdvert.Height ] = 1;
		}
		else
		{
			this.AdHash[ oAdvert.Width + 'x' + oAdvert.Height ]++;
		}
		
		oAdvert.Position = this.AdHash[ oAdvert.Width + 'x' + oAdvert.Height ];
		oAdvert.HolderId = 'bloomHolder_' + this.ServerId + '_' + oAdvert.Width + 'x' + oAdvert.Height + '_' + oAdvert.Position;
		oAdvert.FrameId = 'bloomAd_' + this.ServerId + '_' + oAdvert.Width + 'x' + oAdvert.Height + '_' + oAdvert.Position;
	
		//if( document.getElementById( oAdvert.HolderId ) === undefined )
		//{
		    var adDiv = $('<div id="' + oAdvert.HolderId  + '" style="width:' + oAdvert.Width + 'px;height:' + oAdvert.Height + 'px;"></div>');
			$("#" + oAdvert.ParentId).append(adDiv);
		//}
		//else
		//{
		//	return;
		//}
	
		oAdvert.Server = this.Server;
		oAdvert.Site = this.Site;
		oAdvert.Area = this.Area;
		oAdvert.Page = this.Page;
		oAdvert.RSI = this.RSI;
		oAdvert.Dimentions = oAdvert.Width + 'x' + oAdvert.Height;
		
		
	    switch (oAdvert.Dimentions)
	    {
	        case '150x113':
				oAdvert.Target = '/AAMSZ=SPONSORBUTTON';
			break;
			
	        case '163x64':
				oAdvert.Target = '/AAMSZ=FOOTBALLSPONSORBUTTON';
			break;
			
	        case '1x1':
				oAdvert.Target = '/AAMSZ=OUTOFPAGE';
			break;
			
	        default:
				oAdvert.Target = '/AAMSZ=' + oAdvert.Dimentions;
			break;
	    }
					
		this.Adverts.push( oAdvert );
	},
	
	/*
	 * Calculate Revenue Scinece, only needs to be done once per ad server
	 */
	CalcRSI:function()
	{
		var rsiSegments = [];
		var segmentBegin = document.cookie.indexOf('rsi_segs=');
		
		if (segmentBegin >= 0) 
		{
			segmentBegin = document.cookie.indexOf('=', segmentBegin) + 1;
			
			if (segmentBegin > 0) 
			{
				var segmentEnd = document.cookie.indexOf(';', segmentBegin);
				
				if (segmentEnd == -1) 
				{
					segs_end = document.cookie.length;
				}
					
				rsiSegments = document.cookie.substring(segmentBegin, segmentEnd).split('|');
			}
		}
		this.RSI = '';
		for (var i = 0; i < rsiSegments.length; i++) 
		{
			this.RSI += (rsiSegments[i] + '.');
		}
		this.RSI = this.RSI.replace(/_/g, "");
	},

	/*
	 * Attache an iframe to as container, null out contents if frame does not exist
	 * @param {object} oAdvert Target ad to render / refresh on page
	 */
	TargetAd:function( oAdvert )
	{
		var eHolder = document.getElementById( oAdvert.HolderId );
		
		if (this.Off === false) 
		{
			var eNewFrame = document.createElement("IFRAME");
			var eFrame = document.getElementById(oAdvert.FrameId);
			var sAdURL = this.GetAdUrl(oAdvert);
			eNewFrame.src = sAdURL;
			eNewFrame.id = oAdvert.FrameId;
			eNewFrame.name = oAdvert.FrameId;
			eNewFrame.frameBorder = 'no';
			eNewFrame.scrolling = 'no';
			eNewFrame.width = oAdvert.Width;
			eNewFrame.height = oAdvert.Height;
			
			// Test to see if frame busting has activated, Needs testing
			if (eFrame) 
			{
				eHolder.replaceChild(eNewFrame, eFrame);
			}
			else 
			{
				eHolder.innerHTML = '';
				eHolder.appendChild(eNewFrame);
			}
		}
		else
		{
			eHolder.className += " cms-AdvertOff";
			eHolder.innerHTML = '<strong>Site</strong>=' + this.Site + ' <strong>Area</strong>=' + this.Area + ' <strong>Segment</strong>=' + this.Area + ' <strong>Position</strong>=' + oAdvert.Position + ' <strong>Size</strong>=' + oAdvert.Width + "x" + oAdvert.Height 
		}
		
		// Try to delete calling script element from DOM		
		try {
			var eScript = document.getElementById( oAdvert.ScriptID );
			eScript.parentNode.removeChild( eScript );
		}
		catch(e)
		{
		
		}
		
		
		
	},

	/*
	 * Return URL for an ad iframe, points to stub file as set in the ad server object
	 * @param {object} oAdvert Target ad to create stub URL for
	 */
	GetAdUrl:function( oAdvert )
	{
		return this.Stub + '&adserver='
        + escape(oAdvert.Server)
        + '&itvsite='
        + escape(oAdvert.Site)
        + '&itvarea='
        + escape(oAdvert.Area)
        + '&seg='
        + escape(oAdvert.Area)
        + '&position='
        + oAdvert.Position
        + '&dimensions='
        + oAdvert.Dimentions
        + '&holder='
        + oAdvert.HolderId
        + '&pagenum='
        + ( Math.round(Math.random() * 10000000000) * 10 )
		+ '&rs='
		+ this.RSI;
	},

	/*
	 * Refresh all ads, does what it says on the tin, will only refresh ads in the current ad server
	 */
	RefreshAdverts: function()
	{
		for (var iAdCount = 0; iAdCount < this.Adverts.length; iAdCount++) 
		{
			try 
			{
				var oAdvert = this.Adverts[iAdCount];
				this.TargetAd(oAdvert);
			} 
			catch (Err) 
			{
				//console.log(Err);
			}
			finally 
			{
			}
		}
		return false;
	},
	
	/*
	 * Turn on adverts, tests to see if they are already on
	 */
	ActivatAdverts: function()
	{
		if (this.Off === true) 
		{
			this.Off = false;
			this.RefreshAdverts();
		}
		
		
	},
	/*
	 * Turn off adverts, tests to see if they are already off
	 */
	DeactivateAdverts: function()
	{
		if (this.Off === false) 
		{
			this.Off = true;
			this.RefreshAdverts();
		}
	}
}
