/* ************************************************* */
/* Copyright 2010, Viktor Bodrogi. All rights reserved.
 */

/* ************************************************* */
/* Ad slot handling
 * Copyright 2010, Viktor Bodrogi. All rights reserved.
 */

var Ad = {
	PubId: "pub-3630894445352926", // google_ad_client
	Prefix: "Doculus",
	Placements: $H({
		Header: [['', 468, 60]],
		Leftside: [['1', 120, 90], ['2', 120, 60], ['', 120, 240]],
		Rightside: [['0', 120, 240], ['1', 120, 90], ['2', 120, 60], ['', 120, 240]],
		Footer: [['', 728, 90]],
	}),
	Stripes: {
		_: [
			[[120, 60],  [120, 90],  [120, 240], [120, 600]],
			[[120, 60],  [120, 90],  [120, 60],  [120, 90]],
			[[120, 90],  [120, 60],  [120, 90],  [120, 60]],
			[[120, 60],  [120, 240], [120, 60],  [120, 240]],
			[[120, 90],  [120, 240], [120, 90],  [120, 240]],
			[[120, 240], [120, 90],  [120, 240], [120, 90]],
			[[120, 240], [120, 90],  [120, 240], [120, 60]],
			[[120, 240], [120, 60],  [120, 240], [120, 90]],
			[[120, 60],  [120, 600]],
			[[120, 90],  [120, 600]],
			[[120, 600], [120, 60]],
			[[120, 600], [120, 90]]
		],
	},

	init: function() {
		this.CaId = "ca-" + this.PubId;
		Ad.Slots.init();
	},
	/* Google AdManager handling */
	ga_setup: function() {
		write_script_src('http://partner.googleadservices.com/gampad/google_service.js');
		write_script_text('GS_googleAddAdSenseService("'+this.CaId+'");\nGS_googleEnableAllServices();\n');
		write_script_text(this.Slots.collect(function(slot) {
			return('GA_googleAddSlot("'+this.CaId+'", "'+slot.name+'");');
		}, this).join('\n'));
		write_script_text('GA_googleFetchAds();');
	},
	/* Ad.Slots */
	Slots: {
		slots: [],
		_slots: $H(),
		visible: $H(),

		_each: function(iterator) {
			this.slots._each(iterator);
		},
		exists: function(name) {
			return (this._slots.keys().indexOf(name) >= 0);
		},
		// push new adslot by name if not exists already
		push: function(name, placement, width, height) {
			var slot = null;
			var _name = name;
			if (placement) name = placement + name;
			if (!this.exists(name)) {
				slot = new Ad.Slot(name, placement, width, height);
				this._slots.set(name, slot);
			}
			return slot;
		},
		get: function(name) {
			return this._slots.get(name);
		},
		names: function() {
			return this.slots.collect(function(slot) { return slot.name; });
		},
		init: function() {
			Ad.Placements.each(function(pair) {
				pair.value.each(function(slot) {
					Ad.Slots.push(slot[0], pair.key, slot[1], slot[2]);
				});
			});
		},
		stripe: function(name, index) {
			var stripes = Ad.Stripes._[index];
			return stripes.collect(function(s, i) {
				return Ad.Slots.push(i, name, s[0], s[1]);
			});
		},
		resize: function() { this.invoke ('resize'); },
		setup: function() { this.invoke ('setup'); },
		placements: function(placement) {
			return Ad.Placements.keys();
		},
		placement: function(placement) {
			if (placement && placement != 'undefined' && !placement.empty())
				return this.findAll(function(s){ return s.placement == placement });
			else return this;
		},
		show: function(placement) {
			this.stopTimer();
			this.placement(placement).invoke ('show');
			if (placement) {
				this.visible.set(placement, true);
				$('adsButton_'+placement).innerHTML = "Remove Ads";
			} else {
				this.placements().each(function(i) { Ad.Slots.visible.set(i, true); });
				$$('.adsButton').each(function(i) { i.innerHTML = "Remove Ads"; });
			}
		},
		hide: function(placement) {
			this.placement(placement).invoke ('hide');
			if (placement) {
				this.visible.set(placement, false);
				$('adsButton_'+placement).innerHTML = "Show Ads";
			} else {
				this.placements().each(function(i) { Ad.Slots.visible.set(i, false); });
				$$('.adsButton').each(function(i) { i.innerHTML = "Show Ads"; });
			}
			this.restartTimer();
		},
		toggle: function(placement) {
			(this.visible.get(placement) || this.visible.get(placement) == undefined)?
			this.hide(placement) : this.show(placement);
		},
		onTimer: function() {
			this.show(null);
			GoGa.trackAdShowAuto();
		},
		restartTime: 7,
		restartTimer: function() {
			if (this.executer) this.executer.stop();
			this.executer = new PeriodicalExecuter(Ad.Slots.onTimer.bind(this), this.restartTime);
		},
		stopTimer: function() {
			if (this.executer) this.executer.stop();
		},
	},
	/* Ad.Slot */
	Slot: Class.create({
		_name: null,
		name: null,
		id: null,
		cls: 'Ad-Slot',
		placement: null,
		// gam: Google AdManager
		// gas: Google AdSense
		type: 'gam',
		div: null,
		ad: null,

		initialize: function(name, placement, width, height) {
			this._name = name;
			this.name = this.mkname(name);
			this.placement = placement;
			this.id = this.idname();
			this.cls = this.clsname();
			this.width = width;
			this.height = height;
			//this.fill = this.fill_gam;
			this.fill = this.fill_this;
			//this.fill = this.fill_me;
		},
		mkname: function(name) {
			return Ad.Prefix + "_" + name;
		},
		idname: function() {
			return 'Ad_' + this.name;
		},
		clsname: function() {
			return [ 'Ad-Slot', 'Ad-'+this._name, 'Ad-'+this.placement ].join(' ');
		},
		toString: function() {
			//return "[Ad.Slot: "+this.name+", div: "+this.div+", ad: "+this.ad+"]";
			return "[Ad.Slot: "+this.name+"]";
		},

		fill_slot: function(inner) {
			document.write("<div id='X"+this.id+
					"' class='"+this.cls+
					"' style='width: "+this.width+"; height: "+this.height+
					"'>");
			if (inner) inner.bind(this)();
			document.write("</div>");
		},
		fill_ad: function(inner) {
			document.write("<span id='"+this.id+"'>");
			//document.write("<div id='"+this.id+"' class='"+this.cls+"'>");
			if (inner) inner.bind(this)();
			document.write("</span>");
			//this.ad = $(this.id);
			//this.ad.slot = this;
		},
		div: function() {
			return $("X"+this.id);
		},
		ad: function() {
			return $(this.id);
		},
		
		fill_text: function(text) {
			if (text) document.write(text);
		},
		fill_this: function() {
			this.fill_text(this);
		},
		fill_nbsp: function() {
			this.fill_text("&nbsp;");
		},
		gam_script: function() {
			return script_text('GA_googleFillSlot("'+this.name+'")');
		},
		fill_gam: function() {
			document.write(this.gam_script());
		},
		fill_gas: function() {
			google_ad_client = "pub-3630894445352926";
			/* Rightside1, 120x240, created 10/11/09 */
			google_ad_slot = "0893142337";
			google_ad_width = 120;
			google_ad_height = 240;
		},
		fill_me: function() {
			//write_script_text('$("'+this.id+'").ad_slot.run.defer()');
			//write_script_text(this.id+'.ad_slot.run.defer()');
		},

		write_slot: function(text) {
			text = (text || "&nbsp;");
			this.fill_slot(function(){ document.write(text) });
		},
		write_ad: function() {
			this.fill_ad(this.fill_gam);
		},

		resize: function() {
			//this.ad().makePositioned();
			this.ad().setStyle({ position: 'absolute' });
			this.ad().clonePosition(this.div(), { offsetTop: 0 }); 
			//this.ad().absolutize();
			//this.ad().relativize();
		},
		setup: function() {
			this.resize();
			this.show();
		},
		opacity: 0.05,
		show: function() {
			this.ad().setOpacity(this.opacity);
			this.ad().show();
			this.ad().fade({ duration: 1.0, from: this.opacity, to: 1 });
		},
		hide: function() {
			this.ad().fade({ duration: 2.0, from: 1, to: this.opacity });
		},
	}),

	/* Functions for in-page usage */

	supportText1: "<br/>Remove Ads? Support Doculus! Please Donate!",
	supportText2: "Remove Ads?<br/>Support Doculus!<br/>Please Donate!",
	// Renders an AdSlot
	slot: function (name, text) {
		Try.these(
		function() {
			var slot = Ad.Slots.get(name);
			Ad.Slots.slots.push(slot);
			slot.write_slot((text == null || text == undefined) ? this.supportText2 : text);
		},
		function() {
			document.write("Ads Disabled!");
		});
	},
	// Renders a dynamic AdStripe
	stripe: function (name, index, text) {
		Try.these(
		function() {
			var stripes = Ad.Slots.stripe(name, index);
			stripes.each(function(slot) {
				Ad.Slots.slots.push(slot);
				slot.write_slot((text == null || text == undefined) ? this.supportText1 : text);
			});
		},
		function() {
			document.write("Ads Disabled!");
		});
	},

	// Renders the loader script
	loader: function() {
		try {
			Ad.ga_setup();
			Ad.Slots.invoke ('write_ad');
			document.observe('dom:loaded', Ad.onLoad);
			//document.observe('dom:loaded', Ad.onLoad.bind(this));
		} catch (e) {
			document.write("Ads Loader Disabled: " + e);
		}
	},

	// Called on dom loaded
	onLoad: function(event) {
		try {
			Ad.Slots.setup();
			window.onresize = Ad.onResize;
			GoGa.setAdImpressions(Ad.Slots.size());
			GoGa.trackAdLoaded();
		} catch (e) {}
	},
	// Called on resize loaded
	onResize: function(event) {
		Ad.Slots.resize();
	},
	toggleAds: function(placement) {
		//Ad.Slots.toggle(placement);
		//Ad.Slots.invoke('toggle');
		Ad.Placements.keys().each(function(place) {
			Ad.Slots.toggle(place);
		});
		if (Ad.Slots.visible.get(placement))
			GoGa.trackAdShow();
		else GoGa.trackAdRemove();
	},
	// Remove ads button
	adsButton: function(placement) {
		document.write('<DIV class="Ad-Button Ad-Button-'+placement+'">'+
			'<SMALL><A id="adsButton_'+placement+'" class="adsButton"'+
			'" href="javascript:Ad.toggleAds(\''+placement+'\')">Remove Ads</A></SMALL></DIV>');
	},
};

Object.extend(Ad.Slots, Enumerable);

/* ************************************************* */
/* Google Analytics handling */
var GoGa = {
	Acct: "UA-10922724-2",
	//pageTracker: null,
	//ga: null,

	load: function() {
		try {
			window.gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
			document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
		} catch(err) {}
	},
	setup: function(acct) {
		try {
			if (acct) this.Acct = acct;
			window.pageTracker = this._gat_getTracker();
			this.init();
		} catch(err) {}
		return pageTracker;
	},
	init: function() {
		this.setAdSlots();
	},
	_gat_getTracker: function() {
		return _gat._getTracker(this.Acct);
	},
	// Pageview tracking
	trackPageview: function() {
		try {
			pageTracker._trackPageview();
		} catch(err) {}
	},
	// Event tracking
	trackEvent: function(category, action, opt_label, opt_value) {
/*		var label = null;
		var value = null;*/
		pageTracker._trackEvent(category, action, opt_label, opt_value);
	},
	trackAdRemove: function() {
		this.trackEvent('Ad', 'Remove');
	},
	trackAdShow: function() {
		this.trackEvent('Ad', 'Show');
	},
	trackAdShowAuto: function() {
		this.trackEvent('Ad', 'Show Auto', null, Ad.Slots.restartTime);
	},
	trackAdLoaded: function() {
		this.trackEvent('Ad', 'Loaded');
	},
	// Custom variables
	setCustomVar: function(index, name, value, opt_scope) {
		pageTracker._setCustomVar(index, name, value, opt_scope);
	},
	// Set AdSlots, before loaded.
	setAdSlots: function(slots) {
		slots = (slots || Ad.Slots._slots.size());
		this.setCustomVar(1, "Ad Slots", slots, this.SCOPE_PAGE);
	},
	// Set AdSlots, after loaded.
	setAdImpressions: function(slots) {
		slots = (slots || Ad.Slots.size());
		this.setCustomVar(2, "Ad Impressions", slots, this.SCOPE_PAGE);
	},
	SCOPE_VISITOR: 1,
	SCOPE_SESSION: 2,
	SCOPE_PAGE: 3,
	// not yet working
/*	script_async: (function() {
		var _gaq = _gaq || [];
		_gaq.push(['_setAccount', this.Acct]);
		_gaq.push(['_trackPageview']);
		var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
		ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
		(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
	}),
*/
};

/* ************************************************* */
 /* Cookie handling */
function setCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function clearCookie(name) {
	createCookie(name,"",-1);
}

/* Menu handling */
function menuInit(id) {
//    if (getCookie(id)) $(id).show();
//    else $(id).hide();
	$$('ul.sub-cat').invoke('hide');
}
function menuClick(id) {
    //var s = $(id).getStyle('display');
	var s = $(id).visible();
	$$('ul.sub-cat').invoke('hide');
    if (s) $(id).hide();
	else $(id).show();
//    setCookie(id, $(id).visible() ? '1' : '', 3650);
}

/* Script handling */
function script_src(src) {
	return('<script type="text/javascript" src="'+src+'"></script>\n');
}
function script_text(text) {
	return('<script type="text/javascript">' + text + '</script>\n');
}
function write_script_src(src) {
	document.write(script_src(src));
}
function write_script_text(text) {
	document.write(script_text(text));
}
