// AD SYNCHING ------------------------------------------------------------------------
var adSync = {
	version: "1.2",
	dartUrl: "",
	siteName: "ccn.com",
	adTile: 1,
	ordinal: Math.floor((Math.random() * 100000000)),
	adParams: {},
	autoSyncTypes: ["banner","bbox","sky","button","tile","wallpaper"], // 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
	
	// DEPRECATED
	CollectExtraKeyValues: function(){
	},
	// DEPRECATED

	// 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";
	},
	
	ParseBaseDartUrl: function() {
		var pageLevelDartUrl = dartad_url;
		// find /adj/ in the string
		var endPosition = pageLevelDartUrl.indexOf("/adj/");		
		// extract everything up to that
		var domainAndSite = pageLevelDartUrl.substring( 0, endPosition );
	
		return domainAndSite + "/adi/";
	},

	// 	DART PARSER
	ParseDartAdUrl: function(pageAdUrl){
		// define an object to contain the parsed dartAd data
		var dartAdResult = {};
		var newAdString = this.ParseBaseDartUrl() + "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(/loc=[^;]*/,"loc=" + adloc);
			this.CreateNewAdiFrame(adType, newAdURL, adDivs.eq(i));
			adSync.adTile++;
		}
	},

	// 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).substring(1))){
					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(/loc=[^;]*/,"loc=" + adloc);
		// If we have a callback method, we should invoke it.  If we don't have a callback, or the callback returns true, add the ad normally
		if (typeof(this.adParams[adType].callback)!="function" || this.adParams[adType].callback(newAdURL)){
			this.CreateNewAdiFrame(adType, newAdURL, adDiv);
		}
		this.adTile++;
		adParams[adType].currentIndex++;
	},

	TriggerVideoAdSynch: function(pdkEvent){
		if (pdkEvent.data.isAd || pdkEvent.data.baseClip.isAd){
			// If we are synching to video, the video ad itself was tile 1
			this.adTile = 2;
			var adParams = {};
			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] = {};
				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.filter(this.ConstructContainerId(name)).length-1;
					}
				}
			
				for (var i=0;i<adDivs.length;i++){
					this.RefreshVideoAds(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");
		}
	},

	GetAdParameters: function(defaultAdParameters){
		dartUrl = this.ParseBaseDartUrl();
	
		// This method is used to determine whether an ad keyword needs to be passed through or not
		var isNotBlocked = function(key){
			var blockedList = ["loc","ord","sz","tile","nati","meal","cour"];
			for (var i=0;i<blockedList.length;i++){
				if (key==blockedList[i]){return false}
			}
			return true;
		};
		// If the dart defined ad string is available
		if (typeof dartad_url == 'string'){
			var keyvalues = dartad_url.split(";");
			var adParams = {};
			// Loop through all the key values except the first, which is the url
			for (var i=1;i<keyvalues.length;i++){
				var kv = keyvalues[i].split("=");
				if (isNotBlocked(kv[0])){
					if (!adParams[kv[0]]){
						adParams[kv[0]] = [];
					}
					adParams[kv[0]].push(kv[1]);
					
				}
			}
			return adParams;
		}else if (defaultAdParameters){
			return defaultAdParameters;
		}else{
			return {};
		}
	}
};

// 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",callback:null};
adSync.adParams["thetop"] = {name:"banner",size:"468x60,728x90",width:"728px",height:"90px",callback:null}; // dupe of banner
adSync.adParams["bbox"] = {name:"bbox",size:"250x250,300x250",width:"300px",height:"250px",callback:null};
adSync.adParams["bigbox"] = {name:"bbox",size:"250x250,300x250",width:"300px",height:"250px",callback:null}; // dupe of bbox
adSync.adParams["sky"] = {name:"sky",size:"120x240,160x600",width:"160px",height:"600px",callback:null};
adSync.adParams["button"] = {name:"sky",size:"120x60,160x90",width:"160px",height:"90px",callback:null};
adSync.adParams["tile"] = {name:"tile",size:"122x62",width:"122px",height:"62px"};
adSync.adParams["wallpaper"] = {name:"wallpaper",size:"1x1",width:"1px",height:"1px"};

