// GAMES NETWORK
var GN = {
	
	domain: '',
	root_url: '',
	clicklogger: '',
	added_favorite: [],
	
	init: function(domain,root_url,clicklogger,crons) {
		this.domain = domain;
		this.root_url = root_url;
		this.clicklogger = clicklogger;
		if (crons && crons.length>0) {
			this.init_crons(crons);
		}

		// add click logger to banners
		var banners = $$('div.bannercontainer');
		var iframes, bannerid;
		for (i = 0; i < banners.length; i++) {
			if (!banners[i].id) { continue; }
			bannerid = parseInt(banners[i].id.replace(/^b([0-9]+)$/,'$1'));
			if (!bannerid) { continue; }
			iframes = banners[i].getElementsByTagName("iframe");
			if (iframes.length>0) {
				for(x=0; x<iframes.length; x++) {
					eval('iframes[x].onfocus = function() { GN.logclick('+bannerid+',\'banner\'); }');
				}
			}
			embeds = banners[i].getElementsByTagName("embed");
			if (embeds.length>0) {
				for(x=0; x<embeds.length; x++) {
					eval('embeds[x].onclick = function() { GN.logclick('+bannerid+',\'banner\'); }');
				}
			}
		}
		
	},
	
	initiated: function() {
		if (this.domain == '') {
			return false;
		}
		return true;
	},
	
	init_crons: function(crons) {
		for (i=0; i<crons.length; i++) {
			(function(cron) {
			var spcl = document.createElement('script'); spcl.type = 'text/javascript'; spcl.async = true; spcl.src = cron;
			var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(spcl, s);
			})(crons[i]);
		}
	},
	
	SSO: function(domains,sid) {
		var signed = false;
		if (!sid) { return false; }
		for (i=0; i<domains.length; i++) {
			signed = this.getCookie('sso-'+domains[i]);
			if (signed) { continue; }
			(function(domain,sid) {
			var spcl = document.createElement('script'); spcl.type = 'text/javascript'; spcl.async = true; spcl.src = 'http://' + domain + '/sso.php?s=' + sid + '&domain='+domain;
			var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(spcl, s);
			})(domains[i],sid);
		}
	},
	
	login: function(msg) {
		if ($('navbar_username')) {
			Effect.ScrollTo('navbar_username', { duration:'0.5', offset:-60 });
			$('navbar_username').focus();
			if (msg && msg!='') {
				new Tip('navbar_username', msg, {
					style: 'crazygames',
					width: '200',
					hideOthers: false,
					delay: false,
					stem: 'topMiddle',
					hook: { tip: 'topMiddle', target: 'bottomMiddle' },
					hideOn: false, // disable the normal hide event, because we only want to use the hideAfter option
					hideAfter: 2,
					showOn: 'click'
				});
				$('navbar_username').observe('prototip:shown', function() {
					this.tip.wrapper.shake();
				});
				setTimeout(function() { $('navbar_username').simulate('click'); },100);
			}
		}
		
	},
	
	set_favorite: function(gameid) {
		if (!this.initiated()) { return false; }
		for (key in this.added_favorite) {
			if (this.added_favorite[key] == gameid) { return false; }
		}
		(function(gameid) {
		var gnt = document.createElement('script'); gnt.type = 'text/javascript'; gnt.async = true; 
		gnt.src = GN.root_url + '/useraction.php?do=set_favorite&gameid=' + gameid;
		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gnt, s);
		})(gameid);
	},
	
	rate_game: function(gameid,rating) {
		var valid_rating = false;
		for (i=1; i<=10; i++) { if (i == rating) { valid_rating = true; break; } }
		if (!valid_rating) {
			alert('Error: invalid rating value');
			return false;
		}
		(function(gameid,rating) {
		var gnt = document.createElement('script'); gnt.type = 'text/javascript'; gnt.async = true; 
		gnt.src = GN.root_url + '/useraction.php?do=rate_game&gameid=' + gameid + '&rating='+rating;
		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gnt, s);
		})(gameid,rating);
	},
	
	logclick: function(ad,type) {
		if (ad && this.clicklogger) {
			_gaq.push(['_trackEvent', 'Ad Click '+type, ad]); // track click in analytics
			(function(ad,type) {
			var spcl = document.createElement('script'); spcl.type = 'text/javascript'; spcl.async = true;
			var rnd = Math.floor(Math.random()*1001);
			spcl.src = GN.clicklogger+'?type='+type+'&ad='+ad+'&rnd='+rnd;
			var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(spcl, s); 
			})(ad,type);
		}
	},
	
	setCookie: function(c_name,value,expiredays) {
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		document.cookie=c_name+ "=" +this.escape(value)+
		((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+
		((this.domain==null) ? "" : ";domain="+this.domain+"");
	},
	
	getCookie: function(c_name) {
		if (document.cookie.length>0) {
			c_start=document.cookie.indexOf(c_name + "=");
			if (c_start!=-1) {
				c_start=c_start + c_name.length+1;
				c_end=document.cookie.indexOf(";",c_start);
				if (c_end==-1) c_end=document.cookie.length;
				return unescape(document.cookie.substring(c_start,c_end));
			}
		}
		return "";
	},
	
	escape: function(txt) {
		return escape(txt).replace( 
			new RegExp( "\\+", "g" ), 
			"%2B" 
		);
	},
	
	gamehover: function(id,url,title,thumb,rating) {
		if ($('ghover_'+id).prototip) {
			//$('ghover_'+id).simulate('click');
			return true;
		}
		var con = new Element('div', { align: 'center' } ).update(new Element('a', { href: url } ).update(new Element('img', { src: thumb, width: 200, height: 149, border: 0, title: title } )));
		if (rating) {
			starsize = Math.round((rating / 2) * 20);
		} else {
			starsize = 0;
		}
		//alert(starsize);
		var ratecon = new Element('div', { align: 'center', style: 'margin-top:4px;' } ).update('<div style="background:url(\'/gamesnetwork/stars/oxygen/stars20.png\') 0px -40px repeat-x;width:100px;height:20px;" align="left"><div style="background:url(\'/gamesnetwork/stars/oxygen/stars20.png\') 0px -20px repeat-x;width:'+starsize+'px;height:20px;">&nbsp;</div></div>');
		con.appendChild(ratecon);
		
		new Tip('ghover_'+id, con, {
			style: 'crazygames',
			width: 'auto',
			hideOthers: true,
			//showOn: 'click'
			delay: 0.01
		});
		//$('ghover_'+id).simulate('click');
	},
	
	catgamehover: function(id,url,title,thumb,rating,players,desc) {
		if ($('cghover_'+id).prototip) {
			return true;
		}
		
		var title = new Element('div').update(new Element('strong', { style: 'font-size:12px;' } ).update(title));
		if (players>0) {
			title.appendChild(new Element('span', { } ).update('&nbsp;('+players+' spelers)'));
		}
		var con = new Element('div', { align: 'left' } ).update(title);
		con.appendChild(new Element('div', { style: 'padding:4px;font-style:italic;' }).update(desc));
		if (rating) {
			starsize = Math.round((rating / 2) * 20);
		} else {
			starsize = 0;
		}
		//alert(starsize);
		var ratecon = new Element('div', { align: 'center', style: 'margin-top:4px;' } ).update('<div style="background:url(\'/gamesnetwork/stars/oxygen/stars20.png\') 0px -40px repeat-x;width:100px;height:20px;" align="left"><div style="background:url(\'/gamesnetwork/stars/oxygen/stars20.png\') 0px -20px repeat-x;width:'+starsize+'px;height:20px;">&nbsp;</div></div>');
		con.appendChild(ratecon);
		
		new Tip('cghover_'+id, con, {
			style: 'crazygames',
			width: 200,
			hideOthers: true,
			//showOn: 'click'
			delay: 0.01
		});
		//$('ghover_'+id).simulate('click');
	}
}

GameCountDown = function(){
    this.date = !(this.finished = this.paused = false);
}
GameCountDown.prototype.start = function(n, e, t, r){
    var o = this;
    r ? o.onResume && o.onResume(o.n) :
    (o.n = o.date ? new Date(n).getTime() : n, o.e = o.date ? new Date(e).getTime() : e,
    o.t = t, o.finished = false, o.onStart && o.onStart(o.n));
    o.d = e < n ? 1 : -1, o.paused = false, o.i = setInterval(function(){
        o.d * (o.n -= o.d * (o.date ? 1e3 : 1)) <= o.e * o.d &&
        (o.finished = !o.stop()) && !clearInterval(o.i) ||
        o.onUpdate && o.onUpdate(o.n);
    }, (o.t || 1) * 1e3);
}
GameCountDown.prototype.pause = function(t){
    var o = this;
    clearTimeout(o.x), o.paused ? o.start(o.n, o.e, o.t, 1) :
    (o.paused = !clearInterval(o.i), o.onPause && o.onPause(o.n),
    t && (o.x = setTimeout(function(){
        o.start(o.n, o.e, o.t, 1);
    }, t * 1e3)));
}
GameCountDown.prototype.stop = function(){
    var o = this;
    clearInterval(o.i), clearTimeout(o.x), o.onStop && o.onStop(o.n), o.n = 0;
}


var counter_oncomplete = { 
	funcs: [],
	timers: [],
	add_function: function(funcobj) {
		this.funcs.push(funcobj);
	},
	exec_funcs: function(id) {
		if (this.funcs.length>0) {
			for (i=0; i<this.funcs.length; i++) {
				this.funcs[i].exec(id);
			}
		}
	},
	set_timer: function(id,seconds) {
		for (t_i = 0; t_i<this.timers.length; t_i++) {
			if (this.timers[t_i].id == id) {
				this.timers[t_i].seconds = seconds;
				return;
			}
		}
		this.timers.push({id: id, seconds: seconds});
	},
	get_time_left: function(id) {
		for (t_i = 0; t_i<this.timers.length; t_i++) {
			if (this.timers[t_i].id == id) {
				return this.timers[t_i].seconds;
			}
		}
		return 0;
	}
};
Number.prototype.toTimerFormat = function() {
	var minutes = Math.floor(this / 60);
	if (minutes>59) {
		var hours = Math.floor(minutes / 60);
	} else {
		var hours = 0;
	}
	var minutes = minutes - hours * 60;
	var seconds = this - ((hours * 60 * 60) + (minutes * 60));

	var p_hours = ((hours<10) ? "0"+hours : hours);
	var p_minutes = ((minutes<10) ? "0"+minutes : minutes);
	var p_seconds = ((seconds<10) ? "0"+seconds : seconds);
	return p_hours+':'+p_minutes+':'+p_seconds;
}

function timer_init(seconds, id, expiredtxt) {
	output = $('timer_'+id);
	seconds = seconds - 1;
	if (seconds < 0) {
		return false;
	}
	output.innerHTML = seconds.toTimerFormat();
	if(seconds > 0) {
		counter_oncomplete.set_timer(id, seconds);
		window.setTimeout(function(){timer_init(seconds, id, expiredtxt)}, 1000);
	} else if (seconds <= 0) {
		counter_oncomplete.set_timer(id, 0);
		counter_oncomplete.exec_funcs(id);
		
		output.style.color = 'red';
		output.innerHTML = expiredtxt;
	}
}