//
// Functions
//
function rand( min, max ) {
    if( max ) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    } else {
        return Math.floor(Math.random() * (min + 1));
    }
}

function DynToolTipp_Show() {}
function DynToolTipp_Hide() {}

function DynCont_Display(headline, url) {
	var url = url.split("spielid=");
	var spielid = parseInt(url[1]);
	url = document.location.href.split(".php/");
	url = url[0]+".php/spielsysteminfo/Allgemein/"+spielid+"/index.html";
	document.location.href = url;
}

function toggleTabs(tab_id, tab_count, cur_system, tab_id_name, content_id_name) {
	var i = 1;
	for(i; i <= tab_count; i++) {
		if(i == tab_id) {
			$(tab_id_name+i).removeClassName('tab_'+cur_system+'_unselected')
			$(tab_id_name+i).addClassName('tab_'+cur_system+'_selected');
			$(content_id_name+i).removeClassName('hide');
			$(content_id_name+i).addClassName('show');
		}
		else {
			$(tab_id_name+i).addClassName('tab_'+cur_system+'_unselected');
			$(tab_id_name+i).removeClassName('tab_'+cur_system+'_selected');
			$(content_id_name+i).removeClassName('show');
			$(content_id_name+i).addClassName('hide');
		}
	}
}

function RedaktionsFavoritUpdate(max) {
	var redfav_select = $('RedfavSelect');
	var redfav_options = redfav_select.options;
	var redfav_selected = redfav_options.selectedIndex;
	var redfav_i = 0;

	for (var redfav_i; redfav_i < max; redfav_i++) {

		//console.log("redfav_i:"+redfav_i);
		//console.log("redfav_selected:"+redfav_selected);

		if(redfav_i == redfav_selected) {
			$('RedFavIndex'+(redfav_i+1)).removeClassName('hide');
			$('RedFavIndex'+(redfav_i+1)).addClassName('show');
		}
		else {
			$('RedFavIndex'+(redfav_i+1)).removeClassName('show');
			$('RedFavIndex'+(redfav_i+1)).addClassName('hide');
}	}	}

// layout: indexmmog
function swapMMOG(id) {
	$('mmoglist_left_headline').innerHTML = mmoglist_left_headline[id];
	$('mmoglist_left_genre').innerHTML = "Genre: " + mmoglist_left_genre[id];
	$('mmoglist_pic').src = mmoglist_pic[id];
	$('mmoglist_pic_href').href = mmoglist_link[id];
	$('mmoglist_left_teaser').innerHTML = mmoglist_left_teaser[id] + '<br><div style="float:right;margin-top:10px;"><a href="' + mmoglist_link[id] + '" target="_blank"><img src="http://static.4players.de/sourcen/portal/4players/red_mehr.gif" border="0"></a></div>';
}

function toggleSpielinfoSystemMenuIMG(id, total) {
	if(total==1) return;
	var i = 1;
	var tmp = '';
	for(i; i<=total; i++) {
		if(i==id) {
			tmp = $('SpielinfoSystemMenuIMG'+i).src;
			if(tmp.match(/_over.jpg/)) return;
			tmp = tmp.split(".jpg");
			$('SpielinfoSystemMenuIMG'+i).src = tmp[0]+"_over.jpg";
		}
		else {
			tmp = $('SpielinfoSystemMenuIMG'+i).src;
			if(tmp.match(/_over.jpg/)) {
				tmp = tmp.split("_over.jpg");
				$('SpielinfoSystemMenuIMG'+i).src = tmp[0]+".jpg";
}	}	}	}

function RightNow() {
    var time = new Date();
    return time.getTime();
}

showChartStoreanbieter = function(obj)
{
	// alle expand-icon aendern
	$$('.storeanbieterexpand-icon').each(function(s){
		$(s).removeClassName('storeanbieterexpanded');
		$(s).addClassName('storeanbieterexpand');
	});

	// alle bloecke verstecken
	$$('.storeanbieter').each(function(s){
		// li style aendern
		$(s).up().removeClassName('storeanbieteropen');
		// div hide hinzufuegen
		$(s).addClassName('hide');
	});

	// li style aendern
	$(obj).up().addClassName('storeanbieteropen');
	// div hide entfernen
	$(obj).next('div').removeClassName('hide');
	// expand-icon aendern
	$(obj).up().select('.storeanbieterexpand-icon').each(function(c) {
		$(c).addClassName('storeanbieterexpanded');
	});
}

//
// Magazin
//
var Magazin4Players = Class.create();
Magazin4Players.prototype = {
	rootPath:			'',

	initialize: function(rootpath)
	{
		this.rootPath = rootpath;
	},

	callAjaxFunction: function(func, params, callfunc)
	{
		var url = this.rootPath + "ajax/" + func + ".ajax.php";
		new Ajax.Request(url, {
						 method: 'post',
						 parameters: params,
						 evalJSON: false,
					  	 onSuccess: function(transport) {
					   		callfunc(transport.responseText);
					   	}
		});
	},

	loadAjaxContent: function(container,func, params, callfunc)
	{
		var url = this.rootPath + "/ajax/" + func + ".html.php";
		new Ajax.Updater(container,
						 url, {
						 method: 'post',
						 asynchronous:true,
						 evalScripts: true,
						 parameters: params,
						 onComplete: function(){
						 	if (callfunc)
						 	{
						 		callfunc();
						 	}
						 }
					   	});
	}
}

//
// Contextmenu
//
var ContextMenu = Class.create();
ContextMenu.prototype =
{
	contextMenuContainer: null,
	contextMenuItemList: null,
	lastContextMenuEffect: null,
	keepMenu: false,
	menuTimer: null,

	addMenuItem: function(name,link,classname)
	{
		var li = $(document.createElement("li"));
		if (classname)
		{
			li.addClassName(classname);
		}

		li.innerHTML = "<a href='" + link + "'>" + name + "</a>";
		this.contextMenuItemList.appendChild(li);
	},

	clearMenu: function()
	{
		this.contextMenuItemList.select('li').each(function(item) {
			if (!item.hasClassName('static'))
			{
				item.remove();
			}
		});
	},

	showToolTipp: function(item, text)
	{
		this.clearMenu();
		var li = $(document.createElement("li"));
		li.innerHTML = text;
		this.contextMenuItemList.appendChild(li);
		this.showMenu(item);
	},

	showMenu: function(item)
	{
		var pos = item.viewportOffset();
		var bubbledim = this.contextMenuContainer.getDimensions();
		var scrolloffset = document.viewport.getScrollOffsets();

		var imgoffsetx = (item.getWidth()/2);
		var bubbleoffsetx = (bubbledim["width"]/2);

		var bubblex = pos["left"] + scrolloffset["left"] + imgoffsetx - bubbleoffsetx;
		var bubbley = pos["top"] + scrolloffset["top"] - bubbledim["height"]-5;
		this.contextMenuContainer.setStyle({left: bubblex+"px", top: bubbley+"px"});

		if (this.lastContextMenuEffect) this.lastContextMenuEffect.cancel();
		this.lastContextMenuEffect = new Effect.Appear(this.contextMenuContainer,{duration: 0.2});
	},

	startMenuHideTimer: function()
	{
		var self = this;
		window.setTimeout(function() {
			if (!self.keepMenu)
			{
				self.lastContextMenuEffect = new Effect.Fade(self.contextMenuContainer,{duration: 0.2});
			}
		}, 200);
	},

	hideMenu: function()
	{
		this.contextMenuContainer.hide();
		this.lastContextMenuEffect = null;
		this.keepMenu = false;
	},

	initialize: function()
	{
		var self = this;

		//Context Menu bauen
		this.contextMenuContainer = $(document.createElement('div'));
		this.contextMenuContainer.addClassName('context-menu-container');
		this.contextMenuContainer.hide();

		this.contextMenuContainer.observe("mouseover",function(e) {
			self.keepMenu = true;
		});

		this.contextMenuContainer.observe("mouseout",function(e) {
			self.keepMenu = false;
			self.startMenuHideTimer();
		})

		this.contextMenuItemList = $(document.createElement("ul"));
		this.contextMenuContainer.appendChild(this.contextMenuItemList);

		document.body.insertBefore(this.contextMenuContainer, document.body.childNodes[0]);
	}
}

contextmenu = null;
Event.observe(window,"load",function() {
	contextmenu = new ContextMenu();
})

//
// Foreplaypixel
//
var foreplayPixelPath = 'http://pixel.4players.de/';
var href = window.location.href;
var action = "pagecounter";
var tobecounted = 0;
var world = href.split("4players.de/");
world = world[1].split(".php/");
world = world[0];
var href = href.split(".php/");

function initForeplayPixel() {

	if(href.length==1) return;

	layout = href[1].split("/");
	param = href[1].split("/");
	layout = layout[0];

	switch(layout) {
		case "download_start":	action = "downloadcounter";
								if(world=="cs") {
									action = "cs_downloadcounter";
									if(param[2]=="updates") {
										action = "downloadcounter";
									}
									if(param[2]=="demos") {
										action = "democounter";
									}
								}
								tobecounted = parseInt(param[3]);
								break;
		case "spielvideos":		action = "videocounter";
								tobecounted = parseInt(param[3]);
								break;
		case "tvplayer":		action = "videocounter";
								tobecounted = parseInt(param[4]);
								break;
		default:			break;
	}
	if(action && tobecounted) {
		var foreplayPixel = document.createElement('img');
		foreplayPixel.id = "foreplayPixel";
		foreplayPixel.src = foreplayPixelPath+action+";"+tobecounted;
		foreplayPixel.style.position = 'absolute';
		document.getElementsByTagName("body")[0].appendChild(foreplayPixel);
	}
}

//addLoadEvent(initForeplayPixel);
Event.observe(window, 'load', initForeplayPixel);

//
// Observe Actions
//
// Verhalten von Buttons, Feldern, etc.
function initActions() {
	var achuri = 'http://www.4players.de/ajax/set_user_achievement.php';

	if (typeof Event != 'undefined') {
		// Suchfeld
		if ($('suchfeld')){
			Event.observe('suchfeld', 'focus', function() {
				if ($('suchfeld').value == 'Suchbegriff eingeben...') $('suchfeld').value = '';
			});
		}
		if ($('Menu_4P_Facebook')) {
			$('Menu_4P_Facebook').observe('click', function() {
				new Ajax.Request(achuri, {
					method: 'post',
					parameters: {agid: 147}
				});
			});
		}
		if ($('Menu_4P_Twitter')) {
			$('Menu_4P_Twitter').observe('click', function() {
				new Ajax.Request(achuri, {
					method: 'post',
					parameters: {agid: 148}
				});
			});
		}

		// Sub-Navi-Einträge an Mouseover der Haupt-Navi-Einträge anhängen
		/*$$('.haupt-navi-sys').each(function(e){
			Event.observe(e, 'mouseover', function() {
				$$('.haupt-navi-sys a').each(function(g){
					g.removeClassName('aktiv');
				});

				e.firstChild.addClassName('aktiv');

				$$('.unter-navi-sys').each(function(f){
					f.addClassName('hide');
				});

				var subNavi = e.id.replace(/haupt/, 'unter');

				if($(subNavi)) {
					$(subNavi).removeClassName('hide');
				}
			});
		});

		Event.observe($('unter-navi'), 'mouseover', function() {
			clearTimeout(menuTimeout);
		});

		// Navi-Mouseout: Urspr. aktives Navi-Element wieder zeigen
		Event.observe('kopf', 'mouseover', function() {
			$$('.unter-navi-sys').each(function(f){
				f.addClassName('hide');
			});
			$$('.haupt-navi-sys a').each(function(g){
				g.removeClassName('aktiv');
				if(g.hasClassName('init-aktiv')) {
					g.addClassName('aktiv');
					var subNavi = g.up().id.replace(/haupt/, 'unter');
					if($(subNavi)) {
						$(subNavi).removeClassName('hide');
					}
				}
			});
		});
		Event.observe('inhalt', 'mouseover', function() {
			$$('.unter-navi-sys').each(function(f){
				f.addClassName('hide');
			});
			$$('.haupt-navi-sys a').each(function(g){
				g.removeClassName('aktiv');
				if(g.hasClassName('init-aktiv')) {
					g.addClassName('aktiv');
					var subNavi = g.up().id.replace(/haupt/, 'unter');
					if($(subNavi)) {
						$(subNavi).removeClassName('hide');
					}
				}
			});
		});
		*/

	}
}

initActions();

//
// Skimmer
//
var SkimmerItem = Class.create();
SkimmerItem.prototype = {
	numFrames: 			0,
	height: 			0,
	backheight:			0,
	item:				null,
	imagesrc:			"",
	thumbsrc:			"",
	image:				null,
	width:				0,
	backwidth:			0,
	selected:			null,
	onFrameChangedFunc: null,
	currentFrame: 		0,
	locked:				false,

	initialize: function(item)
	{
		this.numFrames = item.getAttribute("data-numframes");
		this.height = item.getAttribute("data-frameheight");
		this.backheight = item.getAttribute("data-height");
		this.width = item.getAttribute("data-framewidth");
		this.backwidth = item.getAttribute("data-width");
		this.imagesrc = item.getAttribute("data-skimimageurl");
		this.thumbsrc = item.getAttribute("data-thumburl") ? item.getAttribute("data-thumburl") : this.imagesrc;
		this.selected = item.getAttribute("data-selectedframe");
		this.donotreset = item.getAttribute("data-donotreset");
		if (item.getAttribute("data-onframechanged") && item.getAttribute("data-onframechanged")!="")
		{
			this.onFrameChangedFunc = item.getAttribute("data-onframechanged");
		}
		this.item = item;
		this.currentFrame = 0;

		var self = this;
		if (this.donotreset)
		{
			this.item.onclick = function(e) {self.onClicked();}
		}

		//Set Width and Height
		this.item.setStyle ({width: this.width+'px', height: this.height+'px'});
	},

	onClicked: function()
	{
		this.locked = true;
	},

	onFrameChanged: function(frame)
	{
		if (this.onFrameChangedFunc != "")
		{

		}
	},

	setFrame: function(frame)
	{
		if (this.currentFrame == frame) return;
		if (this.locked) return;

		this.item.setStyle({backgroundPosition: 'center ' + (-frame * (this.item.getHeight() - 2)) + "px"});
		this.currentFrame = frame;

		this.onFrameChanged(frame);
	},

	doSkim: function(e)
	{
		if (!e) return;

		//Get X-Position of Mouse relativ to top-left corner of the Skim-Image
		//so we can calculate which frame to display
		var mx = Event.pointerX(e);
		var itempos = this.item.cumulativeOffset();
		var px = itempos["left"];
		var difx = mx-px;

		//Calculate the frame to display
		var frame = Math.round(difx / (this.item.getWidth()/this.numFrames));

		//Position Skim-Image with the correct frame
		this.item.setStyle({backgroundImage:'url(' + this.imagesrc + ')'});
		this.setFrame(frame);
	},

	resetItem: function()
	{
		var frame = parseInt(this.numFrames/2);
		if (self.selected)
		{
			frame = self.selected;
		}
		this.item.setStyle({backgroundImage:'url(' + this.thumbsrc + ')'});
		this.setFrame(frame);
	},

	initItem: function(success)
	{
		var self = this;
		this.item.innerHTML = "";

		//Falls das Skim-Image kaputt oder nicht vorhanden ist ein "No Preview Bild einblenden"
		if (!success)// || this.image.height < ((this.numFrames-1)*this.height))
		{
			self.item.setStyle({backgroundImage:'url(http://static.4players.de/sourcen/portal/4players/4ptv/nopreview.png)'});
			return;
		}

		self.item.setStyle({backgroundImage:'url(' + self.image.src + ')'});

		if (self.backheight > 0 && self.backwidth > 0)
		{
			self.item.setStyle({backgroundSize: self.backwidth + 'px' + ' ' + self.backheight + 'px'});
			self.item.setStyle({backgroundRepeat: 'no-repeat'});
		}
		else if (self.backheight > 0)
		{
			self.item.setStyle({backgroundSize: self.backheight + 'px' + ' ' + 'auto'});
			self.item.setStyle({backgroundRepeat: 'no-repeat'});
		}
		else if (self.backwidth > 0)
		{
			self.item.setStyle({backgroundSize: 'auto' + ' ' + self.backwidth + 'px'});
			self.item.setStyle({backgroundRepeat: 'no-repeat'});
		}

		//self.item.onmousemove = function(e) {self.doSkim(e);}
		self.item.observe('mousemove', function(e) {self.doSkim(e);});
		self.item.observe('mouseout', function(e) {
			if (!self.donotreset)
			{
				self.resetItem();
			}
			self.locked = false;
		});

		//Set initial Position in the middle of the Video
		self.resetItem();
	},

	loadImage: function()
	{
		var self = this;
		this.image = new Image();
		this.image.onload = function(){self.initItem(true);};
		this.image.onerror = function(){self.initItem(false);};
		this.image.src = this.thumbsrc;
	}
};

function visible(element) {
	  if (element.offsetWidth === 0 || element.offsetHeight === 0) return false;
	  var height = document.documentElement.clientHeight,
	      rects = element.getClientRects();
	  for (var i = 0, l = rects.length; i < l; i++) {
	    var r = rects[i],
	        in_viewport = r.top > 0 ? r.top <= height : (r.bottom > 0 && r.bottom <= height);
	    if (in_viewport) return true;
	  }
	  return false;
}

var skimContainers = null;
var skimReload = false;
function initSkimmer()
{
	skimContainers = skimContainers ? skimContainers : $$('.skim');
	if (skimReload) {
		skimContainers = $$('.skim');
		skimReload = false;
	}
	skimContainers.each(function(item) {
		if (!item.hasClassName('loaded'))
		{
			if (visible(item))
			{
				var skimitem = new SkimmerItem(item);
				skimitem.loadImage();
				item.addClassName('loaded');
			}
		}
	});
}

function initSkimmerAndroid()
{
	skimContainers = skimContainers ? skimContainers : $$('.skim');
	if (skimReload) {
		skimContainers = $$('.skim');
		skimReload = false;
	}
	skimContainers.each(function(item) {
		// Text anstatt das Bildes einfügen
		item.update(item.up().title);
	});
}

function initContainerSkims(container)
{
	$(container).select('.skim').each(function(item) {
		if (!item.hasClassName('loaded'))
		{
			var skimitem = new SkimmerItem(item);
			skimitem.loadImage();
			item.addClassName('loaded');
		}
	});
}


function getCookie(name){
	var cookies = document.cookie.match(name + '=(.*?)(;|$)');
	if (cookies) {
		return (unescape(cookies[1])).evalJSON();
	} else {
		return null;
	}
}

var isAndroid = navigator.userAgent.toLowerCase().indexOf("android") > -1;
if(isAndroid) {
	Event.observe(document, 'dom:loaded', initSkimmerAndroid);
} else {
	Event.observe(document, 'dom:loaded', initSkimmer);
	Event.observe(window, 'scroll', initSkimmer);
}
//
// Systemswitcher für Startseite
//
var SystemSwitcher = {
	init: function() {
		fpIndexSystems = JSON.parse(localStorage.getItem('fpIndexSystems'));

		if (!fpIndexSystems) {
			fpIndexSystems = {};
		}

		if (typeof localStorage != 'undefined') {
			// An- und Ausschalten
			$$('.system-toggle').each(function(e) {
				var sys = e.id.replace(/system-toggle-(\w+)-(on|off)/, '$1');
				if (e.id.match(/-on/)) {
					e.onclick = function() {
						fpIndexSystems[sys] = 1;
						localStorage.setItem('fpIndexSystems', JSON.stringify(fpIndexSystems));
						SystemSwitcher.showSystem(sys);
					};
				} else {
					e.onclick = function() {
						fpIndexSystems[sys] = 0;
						localStorage.setItem('fpIndexSystems', JSON.stringify(fpIndexSystems));
						SystemSwitcher.hideSystem(sys);
					};
				}

			});

			// Gespeicherte Werte anwenden
			if (fpIndexSystems) {
				$$('.system-section').each(function(e) {
					var sys = e.id.replace(/system-section-/, '');
					if (fpIndexSystems[sys] == 0) {
						SystemSwitcher.hideSystem(sys);
					}
				});
			}
		} else {
			$$('.system-toggle').each(function(e) {
				e.onclick = function() {
					alert('Dein Browser it leider zu alt und unterstützt dieses Feature nicht. Bitte update deinen Browser.')
				};
			});
		}
	},

	hideSystem: function(sys) {
		$('system-section-' + sys).addClassName('hide');
		$('system-min-' + sys).removeClassName('hide');
	},

	showSystem: function(sys) {
		$('system-section-' + sys).removeClassName('hide');
		$('system-min-' + sys).addClassName('hide');
		if (sys == 'liga') {
			// Liga Bilder laden
			initSkimmer();
		}
	}
};

SystemSwitcher.init();

//
// sichere Logfunktion
//
function log(object)
{
	if (typeof console != 'undefined')
	{
		console.log(object);
	}
	else
	{
		//alert(object);
	}
}

var Tooltip = Class.create();
Tooltip.prototype = {
	anchor: $(document.body),
	position: {'top':0, 'left':0},
	contentBox: null, contentText: '',
	initParams: {
		'show':				false,
		'fadeOut':			0,
		'cssClass':			'',
		'backgroundColor':	'#ffeeee',
		'borderWidth':		'1px',
		'borderStyle':		'solid',
		'borderColor':		'#cccccc',
		'width':			'250px',
		'padding':			'10px'
	},
	params: null,
	initialize: function(anchor, contentText, params, callfunc){
		this.anchor = $(anchor);
		this.contentText = contentText;
		this.create(params);
		if(params.show){
			this.show(callfunc);
		}
	},
	setStyle: function(pkey){
		eval("this.contentBox.setStyle({ '"+pkey+"' : '"+this.params[pkey]+"' });");
		return this;
	},
	create: function(params){
		if($('tt4p')){ $('tt4p').remove(); }
		this.params = this.initParams;
		this.updateParams(params);
		this.contentBox = document.createElement('div').addClassName('tt4p_tooltip').writeAttribute({'id':'tt4p'}).setStyle({'position':'absolute','display':'none','zIndex':102}).update('<div>'+this.contentText+'</div>');
		var arrow = document.createElement('canvas').writeAttribute({'id':'tt4p_arrow', 'width':30, 'height':13}).setStyle({'position':'absolute','bottom':'-14px','left':'14px'});
		this.contentBox.insert({'bottom':arrow});

		this.setStyle('backgroundColor').setStyle('borderColor').setStyle('borderWidth').setStyle('borderStyle').setStyle('width').setStyle('padding');
		this.position.top = this.anchor.cumulativeOffset().top;
		this.position.left = this.anchor.cumulativeOffset().left;
		$(document.body).insert({top:this.contentBox});

		var schattenDiv = document.createElement('div').setStyle({
			'position':'absolute',
			'borderLeft':'solid 1px '+this.params.borderColor,
			'borderRight':'solid 1px '+this.params.borderColor,
			'top':'0px',
			'left':'-2px',
			'width': parseInt(parseInt(this.params.width)+22)+'px',
			'height':'100%',
			'backgroundColor':this.params.backgroundColor
		});
		this.contentBox.insert({'top':schattenDiv});

		var objCanvas = document.getElementById("tt4p_arrow");
		if(objCanvas.getContext){
		    var objContext = objCanvas.getContext('2d');
		    objContext.beginPath();
		    objContext.moveTo(7, 0);
		    objContext.lineTo(30, 0);
		    objContext.lineTo(0, 13);
		    objContext.lineTo(7, 0);
		    objContext.closePath();
		    objContext.fillStyle = this.params.backgroundColor;
		    objContext.strokeStyle = this.params.backgroundColor;
		    objContext.fill();
		    objContext.stroke();
		  }else{
		    // Sonstiger Code
		  }


	},
	show: function(callfunc){
		if(this.params.cssClass!=''){
			this.contentBox.addClassName( this.params.cssClass );
			this.contentBox.childElements()[0].addClassName( this.params.cssClass );
		}
		this.contentBox.setStyle({'top': this.position.top-this.contentBox.getHeight()+'px', 'left':this.position.left+this.anchor.getWidth()+'px' });

		var self = this;
		Effect.Appear(this.contentBox.id, {afterFinish: function(){
				if(callfunc){ callfunc(); }
				if(self.params.fadeOut>0){
					window.setTimeout(function(){ Effect.Fade(self.contentBox.id, { afterFinish:
													function(){
													  if($('tt4p')){ $('tt4p').remove(); }
													}
												  });
												},
									  self.params.fadeOut );
				}
			}
		 });
	},
	updateParams: function(params){
		for(var pkey in params){
			if(params[pkey]!=''){
				var validParam = this.params[pkey];
				if(typeof validParam != 'undefined'){
					if(typeof validParam == typeof params[pkey]){
						this.params[pkey] = params[pkey];
					}
				}
			}
		}
	}
}





