/*
 * This code is designed to put an add in the sidebar of Capture your Flag
 * It is called by inserting the ad element into the sidebar.
 *
 * It does two things:  1.  Tries to call an ad directly into the sidebar, 
 * using the end of the URL as a key for DFP.  2.  For interview pages, it
 * has to wait until the tag links show up at the bottom of the page to 
 * determine which category should be passed to DFP.  It runs code at the
 * bottom that checks on this; if an ad is served, it is moved up to the spot
 * where the side ad should be by absolute positioning.
 * 
 * Things prone to breaking here, depending on what happens at Squarespace:  
 *   1.  The HTML ID of the space on the side for the ad space (sideAdSelector)
 *   2.  The industryKeySelector, where we find the tags for the current interview
 */
 
if(typeof(DoubleClickIndustries) == "undefined") DoubleClickIndustries = "arts-entertainment,business-economy,education,food-travel-leisure,health-care-well-being,media-publishing,non-profit-philanthropy,politics-government,science-technology";
CYFDoubleClick = {

	// This is the whitelist for 
	useIndustryWhiteList: true,
	
	bottomReplaceInterval:500,
	maxBottomReplaceTries:2,
	retryInterval:200,
	maxRetryReplace:6,

	sideAdSelector: "#moduleContent7133409",
	bottomAdSelector: "#bottom_bar",
	generalAdPrefix: "w233-",
	googlePublisherId: "ca-pub-0722125903915331",
	industryAdMidfix: "industry-",
	industryKeySelector: ".journal-entry-tag-post-body-line2 a",
	adBottomPadding:5,
	
	key: null,
	keyInterview:null,
	setKey: function () {

		var addr = location.href;
		var key;
		
		addr = addr.replace(/\?.*$/,"").replace(/http:\/\/.*?\//,"").replace(/\/$/,"");
		if(addr.match('interview-library/tag')) { // we're on a theme page
		
			key = "interview-library";

		} else if(addr.match('interview-library/category')) { // we're on an industry page
			
			key = "industry";
			CYFDoubleClick.keyInterview = addr.replace(/^.*\//,"");
				
		} else if(addr == "interview-library") { // we're on the Interview Library tab
			
			key = "interview-library";

		} else if(addr.match('interview-library')) { // we're on an interview page
			
			key = "industry";
		
		} else {
			
			key = addr.replace(/\/.*$/,"");
			if(key == "") key = "home";
		}
		
//		CYFDoubleClick.isInterview = true;
//		key = "industry";
		
		CYFDoubleClick.key = key;
		
	},
	
	
	loadAd: function(key) {
		GA_googleAddSlot(CYFDoubleClick.googlePublisherId, CYFDoubleClick.generalAdPrefix+key);
	},
	loadIndustryAd: function (industry) {
		CYFDoubleClick.loadAd(CYFDoubleClick.industryAdMidfix+industry)
	},
	insertAd: function(key) {
		GA_googleFillSlot(CYFDoubleClick.generalAdPrefix+key);
	},
	insertIndustryAd: function (industry) {
		CYFDoubleClick.insertAd(CYFDoubleClick.industryAdMidfix+industry)
	},
	getIndustryKeyFromURL: function () {

		var addr = location.href;
		return addr.replace(/\?.*$/,"").replace(/.*\//,"");
		
	},

	// This head stuff--just load what's coming next
	runHeadStart: function () {
		GS_googleAddAdSenseService(CYFDoubleClick.googlePublisherId);
		GS_googleEnableAllServices();
	},
	runHead: function () {

		CYFDoubleClick.setKey();
		// Regular, non-industry page
		if(CYFDoubleClick.key != "industry") {
			GA_googleFetchAds();
			CYFDoubleClick.loadAd(CYFDoubleClick.key);

		// We're looking at an industry, but it's right there in the URL
		} else if(CYFDoubleClick.keyInterview) {
			GA_googleFetchAds();
			CYFDoubleClick.loadIndustryAd(CYFDoubleClick.keyInterview);
		}

	},
	
	runSideBar: function () {
		CYFDoubleClick.setKey();

		// Regular, non-industry page
		if(CYFDoubleClick.key != "industry") {
			CYFDoubleClick.insertAd(CYFDoubleClick.key);
			/*
			setTimeout(function () {
				var obj = $(CYFDoubleClick.bottomAdSelector + " div");
				target.css({
					height:obj.height()+CYFDoubleClick.adBottomPadding
				});
				source.css({
					height:obj.height()+CYFDoubleClick.adBottomPadding
				});
			},10)
			*/
		// We're looking at an industry, but it's right there in the URL
		} else if(CYFDoubleClick.keyInterview) {
			CYFDoubleClick.insertIndustryAd(CYFDoubleClick.keyInterview);
		}
	},
	
	
	/*
	 	Down at the bottom here, we're looking out for industry tags that might tell us we 
	 	need to get targeted ads based on the industry of the interview we're looking at.
	 	It's not in the URL, so we have to do something kinda messy--look at the HTML
    */
	shuffle: function (arr) {
		for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
		return arr;
	},
	
	// Check our HTML for these industries
	getIndustryKeysFromHTML: function () {
		var keys = [];
		$(CYFDoubleClick.industryKeySelector).each(function () {
			var key = this.href.replace(/^.*\//,'');
			keys.push(key);
		})
		return keys;		
	},
	
	runBottom: function () {
		// Is this an interview?  If not, quit.
		if(CYFDoubleClick.keyInterview || CYFDoubleClick.key != "industry") return null;
		
		// Set us up
		GA_googleFetchAds();

		// For each industry on the page, get an ad and place it in this invisible bottom area
		var bottomKeys = CYFDoubleClick.shuffle(CYFDoubleClick.getIndustryKeysFromHTML());
		
		
		var industryWhitelist = DoubleClickIndustries.toLowerCase().replace(/ /g,"").split(',');

		for(var i=0; i < bottomKeys.length; i++) {
			if( !CYFDoubleClick.useIndustryWhiteList || (industryWhitelist.length == 0) || industryWhitelist.indexOf(bottomKeys[i].toLowerCase()) != -1) {
				CYFDoubleClick.loadIndustryAd(bottomKeys[i]);
				CYFDoubleClick.insertIndustryAd(bottomKeys[i]);
				setTimeout(CYFDoubleClick.replaceSideAd,300);
				break;
			}
		}
	
	},
	
	haveRetriedReplace: 0,
	replaceSideAd: function () {
	
		var target = $(CYFDoubleClick.sideAdSelector);
		var source = $(CYFDoubleClick.bottomAdSelector);

		// if we don't have an ad, don't do the move.  Try it again in a second.
		if(!CYFDoubleClick.haveAnAdBottom()) {
		
			if (CYFDoubleClick.haveRetriedReplace > CYFDoubleClick.maxRetryReplace) {
				CYFDoubleClick.haveRetriedReplace++;
				setTimeout(CYFDoubleClick.replaceSideAd,CYFDoubleClick.retryInterval);
			}
			
		} else { // we got an ad!

			var target_offset = target.position();
			source.css({
				width:target.width()+"px",
				position:"absolute",
				left:parseInt(target_offset.left)+"px",
				top:parseInt(target_offset.top)+"px",
				display:"block",
				height:"1px"
			});

			//html > body #modulePage7133372 > div #canvasWrapper > div #canvas > div #pageFooterWrapper > div #pageFooter > div #bottom_bar > div #google_ads_div_sq233-industry-business-economy_ad_container > div			

			target.css({
				height:"1px"
			});
			setTimeout(function () {
				var obj = $(CYFDoubleClick.bottomAdSelector + " div");
				target.css({
					height:obj.height()+CYFDoubleClick.adBottomPadding
				});
				source.css({
					height:obj.height()+CYFDoubleClick.adBottomPadding
				});
			},10)
		
		}
		
	},
	
	// Do we have anything other than scripts in the ad box?
	haveAnAdBottom: function () {
		var done = false;
		$(CYFDoubleClick.bottomAdSelector).children().each (function () {
			if(!$(this).is("script")) {
				done = true;
			}
		});
		return done;
	}
	
	

}

