// AD SYNCHING ------------------------------------------------------------------------
var adSync = {
	version: "1.0",
	comscoreId: "img1",
	dartUrl: "http://ad.ca.doubleclick.net/N3081/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/N3081/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;
	},

	// Generate Ad URL from the page for Photo Galleries
	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 + ";" +  
			"sz=" + this.GetAdSize(adType) + ";" + 
			"exp=no;!c=iframe;" + 
			keywords + ";" +
			"tile=1"+
			";ord=" + 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;
	},

	// refresh ads operator
	RefreshAds: function(adType, adUrl){				
		var adDivs = jQuery(this.ConstructContainerId(adType));
		for (var i=0;i<adDivs.length;i++){
			var adloc = "top";
			if(i==0){
				adloc = "top";
			}else if(i==(adDivs.length-1)){
				adloc="bot";	
			}else if(i>0){
				adloc="mid";	
			} 
			
			// add location and tile value
			var newAdURLtile = adUrl.replace("tile=1", "tile="+this.adTile+";loc="+adloc);
			var newAdocp= newAdURLtile.replace(";dcopt=ist","");
			var newAdURL= newAdocp.replace(";;", ";");
			this.CreateNewAdiFrame(adType, newAdURL, adDivs.eq(i));
			adSync.adTile++;
		}
	},

	TriggerVideoAdSynch: function(pdkEvent){
		adSync.adTile=2;
		if (pdkEvent.data.isAd){
			for (var i=0;i<pdkEvent.data.baseClip.banners.length;i++){
				var adType = pdkEvent.data.baseClip.banners[i].region;
				var adUrl = pdkEvent.data.baseClip.banners[i].src.replace("pfadx", "adi");
				adSync.RefreshAds(adType, adUrl);
			}
		}
	},

	TriggerAdSynch: function (eKWs){	
		this.adTile=1;
		adSync.ordinal=Math.floor((Math.random() * 100000000));
		for (var i=0;i<this.autoSyncTypes.length;i++)
		{
			this.RefreshAds(this.autoSyncTypes[i],this.GetAdUrl(this.autoSyncTypes[i] , eKWs));
		}
		
		// Refresh comscore
		if (document.getElementById(adSync.comscoreId) != null){
		
		document.getElementById(adSync.comscoreId).src="http://beacon.securestudies.com/scripts/beacon.dll?C1=2&C2=3005660&C3=3005660&C4=" + window.location.hostname.toLowerCase() + "test&C5=&C6=&C7=" + escape(window.location.href) + "&C8=" + escape(document.title) + "&C9=" + escape(document.referrer) + "&rn=" + Math.floor(Math.random()*99999999);
		
		}
		
	},

	RegisterVideoRefresh: function(){
		if (typeof tpController != 'undefined') {
 		   tpController.addEventListener("OnMediaStart", "adSync.TriggerVideoAdSynch");
		}
	}
};

// 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"};
