//==============================================================================
// Title:       BusinessWeek Ad System JavaScript
// Purpose:     BusinessWeek JavaScript code to manage the front-end (Client-Side) aspect of the ad system. 
// Copyright:   (c) The McGraw-Hill Companies Inc. All Rights Reserved.
// Version:     1.5.2
//------------------------------------------------------------------------------
// Notes:
// * Standard JS library for all front-end Ad System functionality. Used for standard cross-browser JavaScript
// * The following functions only support browsers that are W3C compliant and allow document.getElementById object references. NN4 and IE4 or earlier will NOT work.
// 
// Revision Authors:
// * TTM: Thomas Mroczkowski
//==============================================================================



//==============================================================================
// BusinessWeek Globals
//==============================================================================

var BW_company = 'mgh';
var BW_division = 'bw';
var BW_site = ''; //Channel (Site) Name
var BW_zone = ''; //Subchannel (Zone) Name
var BW_sitezone;
var BW_sector; 
var BW_size;
var BW_page = '/';
var BW_host = location.hostname.toLowerCase();
var BW_url = location.href;
var BW_queryRaw = location.search.substring(1); //Raw query string code
var BW_queryEscape = BW_queryRaw && unescape(BW_queryRaw);
var BW_query = BW_queryRaw; //Get query string
var BW_queryList = BW_queryRaw && BW_queryRaw.split('&');
var BW_isDebug = (/debug/i.test(BW_query));
var BW_env_ua = navigator.userAgent.toLowerCase(); //User-Agent
var BW_rn = ('1' + ('' + Math.random()).substring(2, 11));
var BW_meta = (document.getElementsByTagName) ? document.getElementsByTagName("meta") : null;

var BW_siteList = [

	//Host                        Site
	['bwads.businessweek.com',    'test'],
	['bw1ads.businessweek.com',   'test1'],
	['bw2ads.businessweek.com',   'test2'],
	['bw3ads.businessweek.com',   'test3']
];

function BW_init() {
	BW_adsys_init();
}



//==============================================================================
// BusinessWeek Ad System
//==============================================================================

var BW_adsys_target = '_blank';
var BW_adsys_baseUrl = 'http://ad.doubleclick.net/';
var BW_adsys_isRich = (!(/mozilla\/3/.test(BW_env_ua) || (/webtv/.test(BW_env_ua)))); //Browser is not mozilla 3 or not WebTv
var BW_adsys_genCode; //Temp global holder of generated ad code
var BW_adsys_template; //Ad template number
var BW_adsys_defaultSite = 'general'; //Value used when site is not available
var BW_adsys_defaultZone = 'general'; //Value used when zone is not available
var BW_adsys_isSiteListChecked = false; //Flag to determine if BW_siteList checking was conducted

//Lists all ads within current web page. Will be populated during runtime.
var BW_adsys_adList = [ 
	//Position:0    Source File:1    Size:2    Tile:3    Url:4    Generated Code:5    Ticker:6
];

//Lists all possible ad positions within ad system. This list provides default properties for each ad position. This list is static.
var BW_adsys_posList = {

	//Position    Default Size              Name                 Description
	top:          {s: '728x90,468x60',      n: 'Top',            desc: 'Old pos10, Sizes: 728x90, 468x60'},
	specialtop:   {s: '970x115,980x115,1x1',        n: 'SpecialTop',     desc: 'Special top ad below header navigation'},
	top1:         {s: '88x31',              n: 'Top1',           desc: ''},
	top2:         {s: '88x31',              n: 'Top2',           desc: 'Sizes: 88x31, 120x15'},
	top3:         {s: '88x31',              n: 'Top3',           desc: 'pos8, email a story(88x31)'},
	topleft:      {s: '1x1',                n: 'TopLeft',        desc: ''},
	topright:     {s: '180x150',            n: 'TopRight',       desc: 'Sponship box with fixed size'},
	middle:       {s: '300x250',            n: 'Middle',         desc: 'Right hand column in all pages. Middle ad in column (used when there are 3 - 300x250\'s or only 1-300x250).'},
	middle1:      {s: '120x40',             n: 'Middle1',        desc: 'Story tools sponsorship. Middle1,(300x200)'},
	middle2:      {s: '120x60',             n: 'Middle2',        desc: 'Forums, eBooks.'},
	middle3:      {s: '88x31',              n: 'Middle3',        desc: 'Legacy printer friendly'},
	left:         {s: '120x90',             n: 'Left',           desc: 'Left navigation column.'},
	left1:        {s: '300x25',             n: 'Left1',          desc: 'Home page. Left column. First ad. Under Market info module'},
	right:        {s: '160x600',            n: 'Right',          desc: 'Right hand column. Sizes: 140x800, 120x600, 160x600'},
	right1:       {s: '88x31',              n: 'Right1',         desc: 'Legacy marketinfo box'},
	right2:       {s: '300x250,300x500,300x600',    n: 'Right2',         desc: 'Right hand column in all pages. Top ad in column. Old pos9.'},
	right3:       {s: '300x250,1x1',        n: 'Right3',         desc: 'Old pos9.'},
	bottom:       {s: '150x1',              n: 'Bottom',         desc: 'Text ad lower right. Placed under Bottom1 and Bottom2.'},
	bottom1:      {s: '120x60',             n: 'Bottom1',        desc: 'Old pos8. Left ad of pair. Lower right of page. Sizes: 120x40, 120x60.'},
	bottom2:      {s: '120x60',             n: 'Bottom2',        desc: 'Right ad of pair. Lower right of page.'},
	bottom3:      {s: '112x54',             n: 'Bottom3',        desc: 'Fixed size. Placed in global nav. Available for sponsorship.'},
	bottomleft:   {s: '120x60',             n: 'BottomLeft',     desc: ''},
	bottomright:  {s: '120x40',             n: 'BottomRight',    desc: 'Used within linkedIn widget'},
	frame1:       {s: '1x1',                n: 'Frame1',         desc: 'Presitial, popups'},
	frame2:       {s: '1x1',                n: 'Frame2',         desc: 'Out-of-banner, pop under (no inline positioning).'},
	position1:    {s: '1x1',                n: 'Position1',      desc: ''},
	position3:    {s: '1x1',                n: 'Position3',      desc: ''},
	position4:    {s: '468x60',             n: 'Position4',      desc: 'Reader comments sponsorships. Within story pages.'},
	x01:          {s: '120x60,1x1',         n: 'X01',            desc: 'Broker box. Companies channel (far left)'},
	x02:          {s: '120x60,1x1',         n: 'X02',            desc: 'Broker box. Companies channel (left)'},
	x03:          {s: '120x60,1x1',         n: 'X03',            desc: 'Broker box. Companies channel (right)'},
	x04:          {s: '120x60,1x1',         n: 'X04',            desc: 'Broker box. Companies channel (far right)'},
	z01:          {s: '300x100',            n: 'Z01',            desc: 'Special position for home page'},
	z02:          {s: '468x60,1x1',         n: 'Z02',            desc: 'Broker box. Companies channel.'}
};

//Lists all current ad templates within ad system. This list is static.
var BW_adsys_tempList = [

	//==========================================================================
	// Object:      Anonymous Object
	// Description: Objects for each possible template type
	// Properties:  n, posList, desc
	//--------------------------------------------------------------------------
	// Properties Detail:
	// * n = integer Template Number (Required)
	// * posList = (array|string) Positions List (Optional): This property is a template type criterion used to match against position listings. BW_listpos & OAS_listpos provide a means to identify a web page as a template type.
	// * desc = string Description (Optional)
	//==========================================================================
	{
		n: 0, 
		desc: 'Represents all pages that can not be identified as any particular template.'
	},
	{
		n: 1, 
		posList: [
			'Right2,Right3,Top', 
			'Right2,Right3,Frame1,Top', 
			'Top,Right2,Right3'
		], 
		desc: 'Home and Search template types'
	},
	{
		n: 2, 
		posList: 'Middle1,Right2,Right3,Bottom1,Bottom2,Bottom,Position4,Frame1,Top', 
		desc: 'Article template type'
	},
	{
		n: 3, 
		posList: 'Top,z02,x01,x02,x03,x04,Right2,Right3',
		desc: 'Companies template type.'
	},
	{
		n: 4,
		desc: 'Newsletter template type'
	},
	{
		n: 5,
		posList: 'Top,Right2',
		desc: 'Slideshow template type'
	}
];

//Initialize ad system
function BW_adsys_init() {
	BW_adsys_setTemp();
}

//Set the template type for web page. If function can not determine template type then default 0 type is given.
function BW_adsys_setTemp() {
	
	var sLP /*stringListPos*/, aTL /*arrayTemplateList*/, xPL /*variablePosList*/;
	
	aTL = BW_adsys_tempList; //Assign template list to local var
	
	//Check for any existing positions listing
	if (window.BW_listpos) { 
		sLP = BW_listpos.toLowerCase();
	} else if (window.OAS_listpos) { //Check for OAS_listpos legacy positions list
		sLP = OAS_listpos.toLowerCase();
	}
	
	//Process template type
	if (sLP) { 
		for (var i in aTL) { //Loop through all template types
			if (aTL[i]['posList']) { //posList property exists for template type
				xPL = aTL[i].posList; //Assign posList property to local var
				if (typeof(xPL) == 'object' && xPL.constructor == Array) { //posList property is an array
					for (var j in xPL) { //Loop through posList array
						if (xPL[j].toLowerCase() == sLP) { //Successful match
							BW_adsys_template = aTL[i].n; //Assign template number
							return;
						}
					}
				} else { //posList assumed string data type
					if (xPL.toLowerCase() == sLP) { //Successful match
						BW_adsys_template = aTL[i].n; //Assign template number
						return;
					}
				}
			}
		}
	} 
	
	//All above failed so set default template number
	BW_adsys_template = 0;
}

//==============================================================================
// Function:     BW_adsys = BusinessWeek_AdSystem
// Purpose:      Main ad system function used to initialize an ad position and return the appropiate ad code to the ad position. 
// Arguments:    string Position, string Source File, string Size, string Return Type
// Dependencies: BW_adsys_posList, BW_adsys_addAd(), BW_adsys_debug()
// Return:       HTML code as string data type or '' empty string on error
//------------------------------------------------------------------------------
// Arguments Detail:
// * sPos (Required): sPos is the ad position name/id. This agrument is required. If this value doesn't match any of the available positions in the position list (BW_adsys_posList) then an error will result. Each ad position name should only be used once per page. 
// * sSourceFile (Optional): This is used to track which include file made the ad position request. Mostly used for debugging purposes. 
// * sSize (Optional): The width and height of the ad. Set this argument when the ad position will have a different size from the default ad position size as found in BW_adsys_posList. The format of the string is WIDTHxHEIGHT where the numerical values of width and height are used. When there are multiple sizes use a comma (,) as a delimiter. Example: "300x250,300x600"
// * sReturnType (Optional): String value to set what type of HTML generated code should be returned. If there is no value for this argument then the default generated code returned is determined by the ad system framework.
//     ** Possible Values: 
//         *** 'basic': This will return the Basic HTML code type. Example Return: '<a href=""><img src="" /></a>'
//         *** 'script': This will return the Script HTML code type. Example Return: '<script src=""></script>'
// 
// Notes: 
// * Each ad position has a default width and height. You only need to pass the size argument if the ad position size is different from the default.
// * Set sReturnType when you want to specify which type of generated code should be returned. There may be situations where you don't want Script HTML code to be returned but only Basic HTML code. If you set 'script' the system will still return Basic HTML if the web browser is not a Rich Media browser.
// * This function will also return any ad debugging info if the debug command is in the query string of the web page address.
//==============================================================================

function BW_adsys(sPos, sSourceFile, sSize, sReturnType) {

	var $sFunc = 'BW_adsys'; //Special String Function: Represents the function name as string datatype
	var sMsg, oPos, sCode;
	
	//Check if sPos exists. If not then throw error and exit
	if (!sPos) { 
		throw new Error($sFunc + '(): Position argument (sPos) does not exist.');
		return '';
	}
	
	oPos = BW_adsys_posList[sPos.toLowerCase()] || null; //Use sPos object within Position List if it exists otherwise set to null 
	
	//Check if oPos exists. If not then throw error and exit
	if (!oPos) {
		throw new Error($sFunc + '(): ' + sPos + ' does NOT exist within Ad System Position List.');
		return '';
	}
	
	//Set local defaults
	sSourceFile = sSourceFile || ''; //Use sSourceFile if it exists otherwise set empty string.
	sSize = sSize || oPos.s; //Use sSize if it exists or use default size from position list
	sReturnType = sReturnType || ''; //Use sReturnType if it exists otherwise set empty string.
	
	//Assign ad code
	sCode = BW_adsys_addAd(oPos, sSourceFile, sSize, sReturnType);
	
	//Assign ad position debug info
	if (BW_isDebug) {
		sCode += BW_adsys_debug(oPos, sSourceFile, sSize);
	}
	
	return sCode;
}

//==============================================================================
// Function:     BW_adsys_addAd = BusinessWeek_AdSystem_AddAdvertisement
// Purpose:      Used to add ad to ad system and generate ad code for web page. This function is used internally by the ad system and should not be called directly by the user. Use BW_adsys instead.
// Arguments:    object Position, string Source File, string Size, string Return Type
// Dependencies: BW_adsys_adList, BW_company, BW_division, BW_adsys_defaultSite, BW_adsys_defaultZone, BW_adsys_baseUrl, BW_adsys_target
// Return:       HTML ad code as string data type
//------------------------------------------------------------------------------
// Arguments Detail:
// * oPos (Required): oPos is the ad position object as found within BW_adsys_posList. This agrument is required. 
// * sSourceFile (Optional): This is used to track which include file made the ad position request. Mostly used for debugging purposes. 
// * sSize (Required): The width and height of the ad. The format of the string is WIDTHxHEIGHT where the numerical values of width and height are used. When there are multiple sizes use a comma (,) as a delimiter. Example: "300x250,300x600"
// * sReturnType (Optional): String value to set what type of HTML generated code should be returned. See BW_adsys() function for more details.
// 
// Notes: 
// * oPos object must be a reference to one of the existing objects found in BW_adsys_posList
// * This function uses BW_adsys_adList to set ad detail info for the ad position and to set the current tile number.
// * BW_sitezone is a special variable. It is used as a flag to signify that the sitezone has been set for the entire page. It is also used by this function to create the url to request an ad from the current ad agent (Ex: DoubleClick). If it does not exist then it is created using other data. BW_sitezone will always be populated after this function is called.
//==============================================================================

function BW_adsys_addAd(oPos, sSourceFile, sSize, sReturnType) {

	var sCode = '', sDefault, sBaseKeys = '', iTile, sScriptUrl, sBasicLinkUrl, sBasicImgUrl, sPosName, iTemp, sSite, sZone, rSlash, aQuery, sQuery, sTicker;

	sPosName = oPos.n.toLowerCase();	
	iTile = BW_adsys_adList.length + 1;
	iTemp = BW_adsys_template || 0;
	
	//Generate Site & Zone
	if (!BW_sitezone) { //Sitezone is not populated. This means this is the first call to this function. 
		rSlash = (/^\/|\/$/g); //Pattern to identify begining and trailing slash '/' characters
		if (!BW_site) { //Site has no value. Assign default value
			sSite = BW_adsys_defaultSite;
		} else if (/\//.test(BW_site)) { //Site contains '/'. Multiple level site value
			sSite = BW_site.replace(rSlash, ''); //Remove begining and trailing '/' characters. Ex: '/autos/specialreport/hybridbuying/'
		} else {
			sSite = BW_site;
		}
		
		if (!BW_zone) {
			sZone = BW_adsys_defaultZone;
		} else if (/\//.test(BW_zone)) {
			sZone = BW_zone.replace(rSlash, ''); //Remove begining and trailing '/' characters. Ex: '/tech/internet'
		} else {
			sZone = BW_zone;
		}
		
		BW_sitezone = sSite + '/' + sZone; //Example: tech/ceotechguide
	}
	
	//Special code to change site if current host matches site list
	if (!BW_adsys_isSiteListChecked) { //The site list has NOT been checked yet
		for (var i in BW_siteList) {
			if (BW_host.match(BW_siteList[i][0])) { //Test if code string is contained within host string
				BW_sitezone = BW_sitezone.replace(/\w+\//, BW_siteList[i][1] + '/'); //Replace site portion within BW_sitezone with site from BW_sitelist
				break;
			}
		}
		BW_adsys_isSiteListChecked = true;
	}
	
	//Generate base keys
	sBaseKeys += 'url=' + location.pathname + ';'; //URL path
	if (window.segQS) { //Revenue Science code exists
		sBaseKeys += segQS;
	}
	
	if (window.s_sectorCode) { //Sector code exists
		sBaseKeys += 'sectr=' + s_sectorCode + ';';
	}
	
	if (window.s_industryCode) { //Industry code exists
		sBaseKeys += 'indus=' + s_industryCode + ';';
	}
	
	if (window.BW_query) { //Query string exists
		if (/(symbol)|(privcapid)|(textin)\=/i.test(BW_query)) { //Specific Query Names Exist
			for (var j in BW_queryList) {
				aQuery = BW_queryList[j].split('=');
				if (aQuery.length > 1) { //Check to make sure query has a value
					sQuery = aQuery[0].toLowerCase(); //Assign query name to local var
					if (sQuery == 'symbol' || sQuery == 'privcapid' || sQuery == 'textin') { //Specific Query names exist
						sTicker = aQuery[1].split('.')[0]; //Keep only text before dot (.) if it exists.
						break;
					}
				}
			}
			sBaseKeys += (sTicker) ? 'tickr=' + escape(sTicker) + ';' : '';
		}
	}
	
	sBaseKeys += 'page=t' + iTemp + ';'; //Template number
	sBaseKeys += 't' + iTemp + '=' + sPosName + ';'; //Position name
	if (iTile == 1) { //Special code for first ad on page
		sBaseKeys += 'dcopt=ist;';
	}
	sBaseKeys += 'sz=' + sSize + ';'; //Size
	sBaseKeys += 'tile=' + iTile + ';'; //Tile
	sBaseKeys += 'ord=' + BW_rn + '?;'; //Random number
	
	//Generate url path
	sDefault = BW_company + '.' + BW_division + '.' + BW_sitezone + ';' + sBaseKeys; //Default path
	
	//Generate full url strings
	sScriptUrl = BW_adsys_baseUrl + 'adj/' + sDefault;
	sBasicLinkUrl = BW_adsys_baseUrl + 'jump/' + sDefault;
	sBasicImgUrl = BW_adsys_baseUrl + 'ad/' + sDefault;
	
	//Generate ad code
	if (sReturnType == 'basic' || !BW_adsys_isRich) { //Basic code
		sReturnType = 'basic';
		sCode += '<a href="' + sBasicLinkUrl + '" target="' + BW_adsys_target + '">'; 
		sCode += '<img src="' + sBasicImgUrl + '" border="0"><\/a>'; 
	} else { //Script code
		sReturnType = 'script';
		sCode += '<script src="' + sScriptUrl + '" type="text/javascript" language="Javascript"><\/script>';
	}
	
	BW_adsys_adList.push([oPos.n, sSourceFile, sSize, iTile, ((sReturnType == 'basic') ? sBasicImgUrl : sScriptUrl), sCode, sTicker]); //Add new ad details to ad list
	
	return sCode;
}

//Used to display debugging info for an ad position
function BW_adsys_debug(oPos, sSourceFile, sSize) {

	var sCode = '', d1 = '<div style="height: auto; font-size: 11px;">', d2 = '<\/div>'; 
	var aAL = BW_adsys_adList[BW_adsys_adList.length-1]; //Add current ad details to local variable
	var sWidth = (/x01|x02|x03|x04/i.test(oPos.n)) ? 'width: 118px;' : 'width: 98%;';

	sCode += '<div id="AdCode-Debug-' + oPos.n + '" style="border: 1px solid #6699ff; background-color: #fff; overflow: auto; margin-top: 1px; font-size: 11px; text-align: left; ' + sWidth +'">';
	sCode += '<table style="margin: 0px; padding: 0px; border-collapse: collapse; width: 100%;">';
	sCode += '<tbody><tr>';
	sCode += '<td style="padding: 5px; background: #6699ff; font-weight: bold; font-size: 12px;">Ad Code - Debug Info<\/td>';
	sCode += '<\/tr><tr><td style="padding: 10px;">';
	sCode += d1 + '<b>Position: <\/b>' + oPos.n.toLowerCase() + d2;
	sCode += d1 + '<b>Size: <\/b>' + sSize + d2;
	sCode += d1 + '<b>Tile: <\/b>' + aAL[3] + d2;
	if (sSourceFile) {
		sCode += d1 + '<b>Source File: <\/b><a href="' + sSourceFile + '" target="_blank">' + sSourceFile + '</a>' + d2;
	}
	sCode += d1 + '<b>Description: <\/b>' + oPos.desc + d2;
	sCode += d1 + '<b>Template: <\/b>' + BW_adsys_template + d2;
	sCode += d1 + '<b>SiteZone: <\/b>' + BW_sitezone + d2;
	if (window.s_sectorCode) {
		sCode += d1 + '<b>Sector Code: <\/b>' + window.s_sectorCode + d2;
	}
	if (window.s_industryCode) {
		sCode += d1 + '<b>Industry Code: <\/b>' + window.s_industryCode + d2;
	}
	if (aAL[6]) { //Ticker exists
		sCode += d1 + '<b>Ticker: <\/b>' + aAL[6] + d2;
	}
	sCode += d1 + '<b>Query: <\/b>' + BW_query + d2;
	sCode += d1 + '<b>Random #: <\/b>' + BW_rn + d2;
	sCode += d1 + '<b>Generated Code: <\/b>' + d2;
	sCode += d1 + '<a href="' + aAL[4] + '" target="_blank">' + (aAL[5]).replace(/\</g,'&lt;').replace(/\>/g,'&gt;') + '</a>' + d2;
	sCode += '<\/td><\/tr><\/tbody><\/table>' + d2;
	
	return sCode;
}



//==============================================================================
// Initialize / Finalize
//==============================================================================

BW_init(); //Initialize

