﻿// AD SYNCHING ------------------------------------------------------------------------
var adSync = {
	version: "1.1",
	dartUrl: "http://ad.ca.doubleclick.net/N6872/adi/",
	siteName: "ccn.com",
	adTile: 1,
	ordinal: Math.floor((Math.random() * 100000000)),
	adParams: new Object(),
	autoSyncTypes: new Array ("banner", "bbox", "sky"), // these are the list of ad elements that we attempt to refresh on each non-video trigger.  This list can be overridden with values specific to a particular template
	
	// Returns the id of the target div based on the adType.  We can override this if a particular site names those divs differently 
	ConstructContainerId: function(adType){
		return "." + adType + "Container";
	},

	// 	DART PARSER
	ParseDartAdUrl: function(pageAdUrl){
		// define an object to contain the parsed dartAd data
		var dartAdResult = {};
		var newAdString = "http://ad.ca.doubleclick.net/N6872/adj/";
		var keyValues = "";
		var pageDartValues = {};
  
		// split the dartAd string around ampersands and semicolons
		var pageAdComp = pageAdUrl.split(/[;]/g);
		tu=pageAdComp[0].split("/adj/");
		ua=tu[1].split("/");
		adSite = ua[0];
		zone=ua[1];
		for (var i = 2; i < ua.length; i++){
			zone= zone+"/"+ua[i];
		}
		pageDartValues["site"]=adSite;
		pageDartValues["zone"]=zone;
		newAdString = newAdString + adSite + "/" + zone + ";";
 	 // loop over the dartAd string components
		for (var i = 1; i < pageAdComp.length; i++){
			// extract this component's key-value pair
			var keyValuePair = pageAdComp[i].split('=');
			var key = decodeURIComponent(keyValuePair[0]);
			var value = decodeURIComponent(keyValuePair[1]);

			// update the parsed dartAd data with this component's key-value pair
			if (!dartAdResult[key]){
				dartAdResult[key] = [];
			}
			dartAdResult[key].push((keyValuePair.length == 1) ? '' : value);
		
			if(key!="sz" && key!="?" && key!="tile" && key!="ord" && key!="loc"){
				keyValues = keyValues+key+"="+value+";";
			}
		}
		pageDartValues["keyValues"]=keyValues;
	
	  // return the parsed dartAd data
		return pageDartValues;
	},

	GetAdSize: function(adtype){
		if (typeof this.adParams[adType.toLowerCase()] == "object"){
			return this.adParams[adType.toLowerCase()].size;
		}
		return "";
	},
	
	GetZone: function () {
		var url = "";
		var startPos = 0;

		//remove the domain...
		url = document.location.toString().replace("http://", "");
		startPos = url.indexOf("/");
		url = url.substring(startPos, url.length);
	
		//remove question marks
		startPos = url.indexOf("?");
		if (startPos>0){url = url.substring(0, startPos);}

		//remove #
		startPos = url.indexOf("#");
		if (startPos>0){url = url.substring(0, startPos);}
			
		//remove html, htm...
		url = url.replace(".html", "").replace(".htm", "");
	
		return url + ";";	
	},

	GetKeywords: function(zone){
		if (typeof zone != "string" || zone == ""){
			return "";
		}
		var parts = zone.split('/');
		var kws = "";

		for (var i=0;i<parts.length; i++){
			if (parts[i] != null && parts[i] != "" && parts[i] != "/"){
				kws+= "kw=" + parts[i] + ";";
			}
		}
		return kws;
	},

	// NOTE: Do not use this method.  It is not logically sound
	GetAdUrl: function(adType, kws){	
		kws = kws || "";

		var zone, keywords;
		// dartad_url is defined seperately via dart code
		if (typeof dartad_url == 'string'){
			var pac = this.ParseDartAdUrl(dartad_url);
		
			this.Zone=pac["zone"];
			this.siteName = pac["site"];
			this.KeyValues=pac["keyValues"];
			zone = this.Zone;
			keywords = this.KeyValues+kws;
		}else{
			zone = this.GetZone();
			keywords = this.GetKeywords(zone) + ";" + kws;
		}

		return this.dartUrl + 
			this.siteName + "/" +
			zone + ";" + 
			keywords + ";" + 
			"sz=" + this.GetAdSize(adType) + ";" + 
			"exp=no;!c=iframe;" + 
			"tile=1",
			//			"tile=" + this.adTile + ";loc=" +adloc+
			";dc_seed=" + this.ordinal;
	},

	CreateNewAdiFrame: function (adType, adUrl, adContainer){
		// If we do not have a valid container or it is an invalid adType, don't bother going further
		if ( typeof adContainer != "object" || typeof this.adParams[adType.toLowerCase()] != "object"){
			return false;
		}

		var htmlStr = "<iframe border='no' scrolling='no' frameBorder='0' width='" + this.adParams[adType.toLowerCase()].width + "' height='" + this.adParams[adType.toLowerCase()].height + "' style='border:none;' src='" + adUrl + "'></iframe>"
		adContainer.html(htmlStr);
		return true;
	},

	// Should be rewritten to use jquery
	RefreshAds: function(adType, adUrl){				
		var adDivs = $(this.ConstructContainerId(adType));
		for (var i=0;i<adDivs.length;i++){
			var adloc;
			if(i==0){
				adloc = "top"
			}else if(i==(adDivs.length-1)){
				adloc="bot";
			}else{
				adloc="mid";	
			} 
			
			// For now we will not add the location or tile value to the thread
			var newAdURL = adUrl.replace(/tile=\d{1,2}/, "tile=" + this.adTile).replace(/loc=[^;]*/,"loc=" + adloc);
			this.CreateNewAdiFrame(adType, newAdURL, adDivs.eq(i));
			adSync.adTile++;
		}
	},

	// Refresh old style ads (iFrame) - will be deprecated as old sites are moved to Southparc/LEGO
	RefreshOldStyleVideoAds: function(adParams, adDiv){
		var adType = null;
		// Determine what type of ad we are dealing with
		for (name in adParams){
			if (adParams.hasOwnProperty(name)){
				if (name == adDiv.attr("id")){
					adType = name;
					break;
				}
			}
		}
		// We should never get an adType we don't recognize, but we should stop if we do
		if (!adType){return;}
		var adloc;
		if(adParams[adType].currentIndex==0){
			adloc = "top"
		}else if(adParams[adType].currentIndex==adParams[adType].lastIndex){
			adloc="bot";
		}else{
			adloc="mid";	
		}

		var newAdURL = adParams[adType].adUrl.replace(/tile=\d{1,2}/, "tile=" + this.adTile).replace(/loc=[^;]*/,"loc=" + adloc);
		adDiv.attr("src",newAdURL);
		this.adTile++;
		adParams[adType].currentIndex++;
	},

	// Refresh new style ads (not iFrame)
	RefreshVideoAds: function(adParams, adDiv){
		var adType = null;
		// Determine what type of ad we are dealing with
		for (name in adParams){
			if (adParams.hasOwnProperty(name)){
				if (adDiv.hasClass(this.ConstructContainerId(name))){
					adType = name;
					break;
				}
			}
		}
		// We should never get an adType we don't recognize, but we should stop if we do
		if (!adType){return;}
		var adloc;
		if(adParams[adType].currentIndex==0){
			adloc = "top"
		}else if(adParams[adType].currentIndex==adParams[adType].lastIndex){
			adloc="bot";
		}else{
			adloc="mid";	
		}

		var newAdURL = adParams[adType].adUrl.replace(/tile=\d{1,2}/, "tile=" + this.adTile).replace(/loc=[^;]*/,"loc=" + adloc);
		this.CreateNewAdiFrame(adType, newAdURL, adDiv);
		this.adTile++;
		adParams[adType].currentIndex++;
	},

	TriggerVideoAdSynch: function(pdkEvent){
		if (pdkEvent.data.isAd){
			// If we are synching to video, the video ad itself was tile 1
			this.adTile=2;
			// If we are synching to video, the video ad itself was tile 1
			var adParams = new Object();
			var jSelector = "";
			var oldStyleJSelector = "";
			// Build up adParam objects and selector for all ad items
			for (var i=0;i<pdkEvent.data.baseClip.banners.length;i++){
				var adType = pdkEvent.data.baseClip.banners[i].region;
				adParams[adType] = new Object();
				adParams[adType].adUrl = pdkEvent.data.baseClip.banners[i].src.replace("pfadx", "adi");
				adParams[adType].currentIndex = 0;
				adParams[adType].lastIndex = 0;
				jSelector += ((i==0)?"":",") + this.ConstructContainerId(adType);
				oldStyleJSelector += ((i==0)?"":",") + "#" + adType;
			}
			var adDivs = $(jSelector);
			
			// If we get any ads in this format
			if (adDivs.length>0){
				for (name in adParams){
					if (adParams.hasOwnProperty(name)){
						adParams[name].lastIndex = adDivs.find(this.ConstructContainerId(name)).length;
					}
				}
			
				for (var i=0;i<adDivs.length;i++){
					this.RefreshVideoAds(adParams, adDivs.eq(i));
				}
			// If we don't find any ads in the new format, check the old format
			}else{
				adDivs = $(oldStyleJSelector);
				for (name in adParams){
					if (adParams.hasOwnProperty(name)){
						adParams[name].lastIndex = adDivs.find("#" + name).length;
					}
				}
				for (var i=0;i<adDivs.length;i++){
					this.RefreshOldStyleVideoAds(adParams, adDivs.eq(i));
				}
			}
		}
	},

	TriggerAdSynch: function (){	
		this.adTile=1;
		for (var i=0;i<this.autoSyncTypes.length;i++)
		{
			this.RefreshAds(this.autoSyncTypes[i],this.GetAdUrl(this.autoSyncTypes[i]));
		}
	},

	RegisterVideoRefresh: function(){
		if (typeof tpController != 'undefined') {
 		   tpController.addEventListener("OnMediaStart", "adSync.TriggerVideoAdSynch");
		}
	},

	// Used in Southparc/LEGO sites to gather kw, ck, sck and page values
	CollectExtraKeyValues: function(){
		var newKeywords = "";
		// Strip out the hostname
		var tempStr = location.href.replace("http://","").replace(/^[^\/]*\//,"");
		// strip out any query string or anchor
		if (tempStr.indexOf("?")>-1){
			tempStr = tempStr.substring(0,tempStr.indexOf("?"));
		}
		if (tempStr.indexOf("#")>-1){
			tempStr = tempStr.substring(0,tempStr.indexOf("#"));
		}
		// break the url path into its components
		var tokenizedUrl = tempStr.split("/");
	
		// strip the story name and id if present
		if (tokenizedUrl.length>2 && tokenizedUrl[tokenizedUrl.length-2].match(/^\d{6,}$/)!==null){
			// If this fails for whatever reason, we can just continue
			try{
				tokenizedUrl.splice(tokenizedUrl.length-3,2);
			}catch(e){}
		}

		// remove the file extension from the last token
		var sck = "";
		var filename = tokenizedUrl[tokenizedUrl.length-1];
		if (filename.indexOf(".")>-1){
			tokenizedUrl[tokenizedUrl.length-1] = filename.substring(0,filename.indexOf("."));
			// If there is only the html filename, then we use that for the ck and leave the page blank
			if (tokenizedUrl.length>1){
				adParameters.keyvalues.page = tokenizedUrl[tokenizedUrl.length-1];
			}
		}
		
		adParameters.keyvalues.ck = tokenizedUrl[0];
		var sck = "";
		// Loop through the tokenized path and collect appropriate kw and sck values
		for (var i=0;i<tokenizedUrl.length;i++){
			if (i>0){
				newKeywords += ";";
				// If we aren't at the last token, or if we are and the last token was a folder rather than a page value
				if (i<tokenizedUrl.length-1 || typeof(adParameters.keyvalues.page)!="string"){
					if (i>1){
						sck += ";";
					}
					sck += tokenizedUrl[i];
				}
			}
			newKeywords += tokenizedUrl[i];
		}
		if (sck.length>0){
			adParameters.keyvalues.sck = sck;
		}
		if (adParameters.keyvalues.kw){
			adParameters.keyvalues.kw += ";" + newKeywords;
		}else{
			adParameters.keyvalues.kw = newKeywords;
		}
		return null;
	}
};

// We define some default ad parameters.  These can be overridden or expanded upon in for custom templates
adSync.adParams["banner"] = {name:"banner",size:"468x60,728x90",width:"728px",height:"90px"};
adSync.adParams["thetop"] = {name:"banner",size:"468x60,728x90",width:"728px",height:"90px"}; // dupe of banner
adSync.adParams["bbox"] = {name:"bbox",size:"250x250,300x250",width:"300px",height:"250px"};
adSync.adParams["bigbox"] = {name:"bbox",size:"250x250,300x250",width:"300px",height:"250px"}; // dupe of bbox
adSync.adParams["sky"] = {name:"sky",size:"120x240,160x600",width:"160px",height:"600px"};

