var ads = new Object();
/*
 * builds request to ad server
 */
ads.buildadcall = function(src){document.write('<scr'+'ipt type="text/javascript" src="'+src+'"></scr'+'ipt>');return '';},

/*
 * UI tool to render ads that may or maynot be served by double click
 */
ads.builddummyad = function(src, width, height){
	document.write('<di' + 'v style="width:' + width + 'px;height:' + height + 'px;border-width:1px;border-style:solid;background-color:grey;border-color:blue"><a href="javascript:console.log(\'' + src + '\')" title="' + src + '">' +width+ 'x' +height+ '</a></d' + 'iv>')
}

/*
 * Prepares the ads object with meta data. This data should be provided by the page descriptor  
 */
ads.init = function(params){
	
	if(params.sitemeta != null){
		if( params.sitemeta.doubleclick_s1 != null && params.sitemeta.doubleclick_sitezone != null ){
			ads.setSiteInfo(params.sitemeta.doubleclick_sitezone, params.sitemeta.doubleclick_s1 );
		}
		this.sitemeta = params.sitemeta;
	}
	
	if(params.sectionmeta != null){
		if( params.sectionmeta.doubleclick_s2 != null ){
			ads.setSection(params.sectionmeta.doubleclick_s2);
		}
		this.sectionmeta = params.sectionmeta;
	}
	
	if(params.pagemeta != null){
		if( params.pagemeta.revenuescience_seg_qs != null ){
			ads.setRevenueScience(params.pagemeta.revenuescience_seg_qs);
		}
		
		if( params.pagemeta.revenuescience_dmloc_pageType != null ){
			ads.setPageType(params.pagemeta.revenuescience_dmloc_pageType);
		}
		
		this.pagemeta = params.pagemeta;
	}
	
}

/*
 * Sets the site info for a doubleclick ad
 */
ads.setSiteInfo = function(sitezone, s1){
	this.site 		= sitezone;
	this.s1 	  	= s1;
}

/*
 * Overrides the section info thats passed to the ad server
 * Params: ad section
 */
ads.setSection = function(section){
	if(ads.notempty(section) ){
		this.section = section;
	}
}

/*
 * Sets the page type used by ad server to target ads to specific content types
 * Params: ad page type
 */
ads.setPageType = function(pagetype){
	if(ads.notempty(pagetype) ){
		this.pagetype = pagetype.toLowerCase();
	}
}

/*
 * Overrides the section info thats passed to the ad server
 * Params: ad section
 */
ads.setRevenueScience = function(revscienceparams){
	if(this.revscienceparams == null && ads.notempty(revscienceparams) ){
		this.revscienceparams = revscienceparams;
	}
}

/*
 * Creates an ad. Must call this in the location you want the ad to appear.
 * Params: ad section
 * Params: ad position
 * Params: ad size
 */
ads.write = function(pos, size) {
	//first check for Yume right column and top ads on channel pages only
	if( size == "300x250" && pos == "right column" && this.pagetype == "subsection"){
		var emptyhtmlpath = this.sitemeta.static_asset_root != null ? this.sitemeta.static_asset_root + "/html/empty.html" : "";
		var width = size.split("x")[0];
		var height = size.split("x")[1];
		var container = "cb_medrect1";
		ads.writeYuMeAdContainer(this.section,pos,width,height,container,emptyhtmlpath);
	} 
	else if ( size == "728x90" && pos == "top" && this.pagetype == "subsection" ) {
		var emptyhtmlpath = this.sitemeta.static_asset_root != null ? this.sitemeta.static_asset_root + "/html/empty.html" : "";
		var width = size.split("x")[0];
		var height = size.split("x")[1];
		var container = "cb_leaderboard1";
		ads.writeYuMeAdContainer(this.section,pos,width,height,container,emptyhtmlpath);
		
	} else {
		var url = ads.createAdUrl(this.section, pos, size, ads.constants.calltype.script);
		ads.prebuildadcall(url,pos,size);
	}
}

/*
 * Writes an ad that passes section, position and size info to the ad server
 * Params: ad section
 * Params: ad position
 * Params: ad size
 */
ads.writeSectionPosSize = function(pos, size) {
	ads.write(pos, size);
}

/*
 * Writes an ad that passes section, position and size info to the ad server
 * Params: ad section
 * Params: ad position
 * Params: ad size
 */
ads.writePosSize = function(pos, size) {
	ads.write(pos, size);
}

/*
 * Writes an ad that passes section, position and size info to the ad server. Ignores stored section info stored in the ads object
 * Params: ad section
 * Params: ad position
 * Params: ad size
 */
ads.createAdUrl = function(section, pos, size, calltype) {
	
	section = ads.formatparamvalue(section);
	
	if(this.ord == null){
		var rand = new String(Math.random()); 
		this.ord = rand.substring (2, 11);
	}
	
	if(this.relpath == null){
		this.relpath = ads.formatparamvalue(location.pathname.toLowerCase());
	}
	
	if(this.keywords == null){
		var keywords = ads.buildKw();
		this.keywords = keywords != null ? keywords : "";
		
	}
	
	var site = this.site;
	
	if( ads.notempty(this.s1) ){
		site += "/" + this.s1;
	}
	
	if( ads.notempty(section) ){
		site += "/" + section + ";";
	}
	else{
		site += ";";
	}
	
	if( !ads.notempty(calltype) ){
		calltype = ads.constants.calltype.script;
	}
	
	var basepath 	= "http://ad.doubleclick.net/" + calltype + "/" + site;
			
	var params = new Array();
	
	if(ads.notempty(this.s1)){
		params.push("s1=" + this.s1);
	}
	
	if(ads.notempty(section)){
		params.push("s2=" + section);
	}
	
	if(ads.notempty(this.relpath)){
		params.push("url=" + this.relpath);
	}
	
	if(ads.notempty(pos)){
		params.push("pos=" + ads.formatparamvalue(pos));
	}
	
	if(ads.notempty(this.revscienceparams)){	
		for(var i = 0; i < this.revscienceparams.length && i < 10; i++){
			params.push(this.revscienceparams[i]);
		}
	}
	
	if(ads.notempty(this.pagetype)){
		params.push("ptype=" + ads.formatparamvalue(this.pagetype));	
	}
	
	if(ads.notempty(this.keywords)){
		params.push("kw=" + this.keywords);
	}
	
	//double click standard params at end (required: size, tile, ord).
	if(ads.notempty(size)){
		params.push("sz=" + size); 
	}
	
	params.push("tile=" + ads.incrementtile() );
	
	params.push("ord=" + this.ord + "?" );
	
	var paramstring = params.join(";")
	
	return basepath + params.join(";");
	
}

/*
 * Called before the ad call is written to the DOM
 */
ads.prebuildadcall = function(adsrc,pos,size){
	
	if( utils.queryString.param.exists("dummyads") ){
		var firstsize = size.split(",")[0];
		ads.builddummyad(adsrc, firstsize.split("x")[0], firstsize.split("x")[1]);
	} else {
		ads.buildadcall(adsrc);
	}
}

/*
 * Registers a YuMe ad for processing after page load
 * This is useful for loading default page ads when yume ad doesn't exist or video player isn't auto playing
 */
ads.registerYumeAd = function(ad){
	ads.registeredYumeAds.push(ad);
	//if there is a registered ad, add the build function to the document ready event
	if(ads.registeredYumeAds.length == 1){
		$(document).ready(ads.buildYumeAds);
	}
}

/*
 * Builds the YuMe ads after the page loads.
 */
ads.buildYumeAds = function(){
	for (ad in ads.registeredYumeAds){
		yume_serve_cb_frame(ads.registeredYumeAds[ad].div_id, ads.registeredYumeAds[ad].frame_id, ads.registeredYumeAds[ad].src);
	}
}

/*
 * Builds the yume ad container
 */
ads.writeYuMeAdContainer = function(section, pos, width, height, cbname, iframesrc){
	var stringbuilder = new Array();
	stringbuilder.push('<div id="' +cbname+ '_div" class="yume-ad" style="overflow: hidden; width: '+width+'px; height: '+height+'px;">');
	stringbuilder.push('<iframe name="'+cbname+'_frame" id="'+cbname+'_frame" src="'+iframesrc+'" marginheight="0" marginwidth="0" topmargin="0" leftmargin="0" allowtransparency="true" frameborder="0" height="'+height+'" scrolling="no" width="'+width+'"> </iframe>');
	stringbuilder.push('</div>');
	document.write( stringbuilder.join("\n") );
	
	if (utils.queryString.param.get('auto-play') != "true" ) {
		ads.registerYumeAd({div_id: cbname+"_div", frame_id: cbname+"_frame", src: ads.createYuMeAdUrl(pos,width+"x"+height )} );
	}
}

/*
 * Creates the yume ad url for iframes
 */
ads.createYuMeAdUrl = function(pos, size){
	return ads.createAdUrl(this.section, pos, size, ads.constants.calltype.iframe);
}

/*
 * Checks if a string is valid
 */
ads.notempty = function(str){
	return (str != null) && (typeof str != "undefined") && (str != ""); 
}

/*
 * Increments the tile value for each doubleclick ad call
 */
ads.incrementtile = function(){
	
	if(this.tile == null){
		this.tile = 1;
	} else {
		this.tile = this.tile + 1;
	}
	
	return this.tile;
}

/*
 * Formats param values passed to ad server
 */
ads.formatparamvalue = function(value){
	return value.replace(/([^a-zA-Z0-9])+/g, "_").replace(/^_|_$/g, "");
}

/*
 * Formats the keyword values passed to ad server
 */
ads.formatkeywords = function(keywords){
	return keywords.replace(/, /g,',').replace(/ /g,'_').replace(/,/g,'+').replace(/'/g,'').toLowerCase();
}

/*
 * Gets keywords passed by query string (for testing) and the meta tags in html. 
 */
ads.buildKw = function(){
	
	var keywordarray = new Array();
	
	var testkeyword = utils.queryString.param.get("testkeyword");
	
	if( ads.notempty(testkeyword) ){
		keywordarray.push( ads.formatkeywords(testkeyword) );
	}
	
	var sMeta = document.getElementsByTagName('meta');
	for(i=0;i<sMeta.length;i++){
		
		if(sMeta[i].name=="keywords"){ 
			
			var keywords = ads.formatkeywords(sMeta[i].getAttribute('content'));
			keywordarray.push(keywords);
		}
	}
	
	if(keywordarray.length > 0){
		return keywordarray.join("+");
	}	
	else{
		return "";
	}
}

ads.registeredYumeAds = new Array();
ads.constants = { calltype: {script:"adj", iframe:"adi"}};
