var autoplay = true;
var currentvideo = "";
var mode = "sd";
var isAd = false;

function getNextVid() {
	if (currentvideo == "") return false;
	curobj = $('#playlist-item-'+currentvideo).next();
	if (curobj.attr('id') == null) {
		curobj = $('#playlist').children().filter(":first");
	}
	return curobj.attr('id').replace('playlist-item-','');
}

function getNextVideo() {
	at = $('#playlist-item-'+currentposition);
	nsib = at.next();
	return parseInt(nsib.attr('id').replace('playlist-item-',''));
}

function findIndex() {}

function jumpTo(index) {
	var pl = $f('videoplayer123').getPlaylist();
	for(var i=0;i<pl.length;i++) {
		if (substr_count(pl[i].completeUrl,'gamereport.de/videos')>0) {
			var spl = pl[i].completeUrl.split("/");
			var inde = spl[6];
			if (parseInt(inde) == index) {
				$f('videoplayer123').play(i);
				return;
			}
		}
	}
}

function playlistswitch() {
	if ($('#playlistswitch').val() == "-1") return;
	var ul = $('#playlistswitch').val();
	location.href = ul;
}

var referer = '';
function selectInListById(cur) {
	if (oldselection != '') {
		at = $('#playlist-item-'+oldselection)[0];
		$('#'+at.id).removeClass('playlist-playing');
	}

	currentposition = cur;
	at = $('#playlist-item-'+currentposition)[0];
	$('#'+at.id).addClass('playlist-playing');
	$('#playlist').scrollTo( $('#'+at.id), 800 );
	currentvideocode = at.id.replace('playlist-item-','');
	cururl = '';
	dotherequest = false;
	for(i=0;i<playlist.length;i++) {
		testurl = playlist[i]['url'];
		var spl = testurl.split("/");
		if (substr_count(testurl,'gamereport.de/videos')>0 && spl[6] == cur) {
    		dotherequest = true;
    		cururl = testurl;
    		break;
    	}
	}
	if (dotherequest) {
		$.post("/ajax/ajax.php", { func: "getvideo", code: currentvideocode, vurl: cururl,ref:referer },
	    function(data) {
			$('#block_video_top').html(data['videotop']);
			$('#block_video_comments').html(data['comments']);
			$('#block_video_more').html(data['videomore']);
			
			if (data['similiargames'] == false) {
				$('#playlistswitch').hide();
			} else {
				$('#playlistswitch').html('');
				t = $("<option>").attr('value','-1');
				t.html("&nbsp;&nbsp;&nbsp;Ähnliche Spiele");
				$('#playlistswitch').append(t);
				for(i=0;i<data['similiargames'].length;i++) {
					t = $("<option>").attr('value','/v/g/'+data['similiargames'][i]['url']+'/');
					t.html(data['similiargames'][i]['title'] + " ("+data['similiargames'][i]['videocount']+")");
					$('#playlistswitch').append(t);
				}
				$('#playlistswitch').show();
			}
			var plugin = $f("videoplayer123").getPlugin("gameBanner");
			plugin.setHtml('<p align="center" class="fulltitle">'+data['title']+'</p><img src="http://www.gamereport.de/static/head/'+data['gamebanner']+'/head.jpg" hspace="30" align="center" />');
			if (info && !isAd) {
				gamebannerInTimer = window.setTimeout("showGameBanner()",4000);
				gamebannerOutTimer = window.setTimeout("hideGameBanner()",8000);
			}
			//FB.XFBML.Host.parseDomTree();
	    }, "json");
	}
	
	oldselection = cur;
}

var gamebannerInTimer;
var gamebannerOutTimer;

function showGameBanner() {
	if (isAd) return;
	var plugin = $f("videoplayer123").getPlugin("gameBanner"); 
	plugin.animate({left:0},2000);
}

function hideGameBanner() {
	clearTimeout(gamebannerInTimer); clearTimeout(gamebannerOutTimer);
	var plugin = $f("videoplayer123").getPlugin("gameBanner"); 
	plugin.animate({left:2000},2000);
}

function showEmbedCode(h) {
	if (currentposition == '') return;
	currentp = ''+(parseInt(currentposition) + 51123);
	h = h.replace(/_MID_/g,currentp);
	$('#embedcode').css('opacity','0.9');
	$('#embedcode').fadeIn();
	cnt = $('<div>').attr('style','margin:15px;').html(
			$('<h2>').html('Embedcode:')
	);
	cnt.append($('<textarea>').attr('style','width:500px;height:250px;').val(h));
	cnt.append($('<a>').attr('href','javascript:void(0)').html('schlie&szlig;en').click(function(){hideEmbed();}));
	$('#embedcode').html(cnt);
}

function hideEmbed() {
	$('#embedcode').fadeOut();
}

var currentvideocode = '';
function loadComments() {
	$('#commentsloader').html('');
	$('#commentsloader').append($('<img>').attr('src','/static/gfx/commentsloader.gif').attr('style','border:0px;'));
	/*at = $('#playlist-item-'+currentposition)[0];
	currentvideocode = at.id.replace('playlist-item-','');*/
	$.post("/ajax/ajax.php", { func: "getcomments2", code: currentposition },
    function(data) {
		$('#commentsloader').hide();
		$('#block_video_comments').html(data['comments']);
		//FB.XFBML.Host.parseDomTree();
    }, "json");
}


function searchEntity(code,platform_ps3,platform_wii,platform_x360,platform_pc,gametitle,relevance,timestamp,timestamp2) {
	this.code = code;
	this.platform_ps3 = platform_ps3;
	this.platform_wii = platform_wii;
	this.platform_x360 = platform_x360;
	this.platform_pc = platform_pc;
	this.gametitle = gametitle;
	this.relevance = relevance;
	this.timestamp = timestamp;
	this.timestamp2 = timestamp2;
}
var searchResults = new Array();

var playlist = new Array();
function addToPlaylist(url,duration) {
	ndur = duration;
	if (substr_count(duration, ":") == 0) ndur = "00:00:"+duration;
	if (substr_count(duration, ":") == 1) ndur = "00:"+duration;
	duration = ndur;
	var p = {
			"file":url,
			url:url,
    		"duration":duration
		} ;
	playlist.push(p);
}

var quickSeekTo = -1;

function switchTo(mod) {
	var icnt = 0;
	var frm = $("<form>").attr('name','switchTo').attr('method','post').attr('action','');
	var chi = $("<input>").attr('type','hidden').attr('name','action').attr('value','switchTo');
	frm.append(chi);
	var chi = $("<input>").attr('type','hidden').attr('name','mode').attr('value',mod);
	frm.append(chi);
	var chi = $("<input>").attr('type','hidden').attr('name','time').attr('value',$f('videoplayer123').getTime());
	frm.append(chi);
	var chi = $("<input>").attr('type','hidden').attr('name','offset').attr('value',currentposition);
	frm.append(chi);
	var holder = $('<div>').css('display','none');
	holder.append(frm);
	$('body').append(holder);
	$f('videoplayer123').stop();
	document.switchTo.submit();
}
function switchToSD() {
	switchTo('sd');
}
function switchToHD() {
	switchTo('hd');
}

function switchAutoPlay() {
	if (autoplay == true) autoplay = false;
	else autoplay = true;
	
	if (autoplay) $('#autoplaystatus').html("AN");
	else $('#autoplaystatus').html("AUS");
}

var currentposition = 0;

var expo = null;

function switchLight() {
	if (expo == null) { 
		expo = $('#videocontainer').expose({api:true,color: '#000',opacity: 0.95}).load();
		expo.onClose(function(){$('#overlaybutton_light').css('backgroundPosition','0px 0px');expo=null;});
		$('#overlaybutton_light').css('backgroundPosition','0px 48px');
	} else {
		expo.close();
		expo = null;
		$('#overlaybutton_light').css('backgroundPosition','0px 0px');
	}
}

var info = false;

function switchInfo() {
	if (info == false) { 
		info = true;
		$('#overlaybutton_info').css('backgroundPosition','0px 48px');
		showGameBanner();
		window.setTimeout("hideGameBanner()",4000);
		
		var a = new Date();
		a = new Date(a.getTime() +1000*60*60*24*365);
		document.cookie = 'showgameinfo=true; expires='+a.toGMTString()+'; path=/'; 
	} else {
		info = false;
		$('#overlaybutton_info').css('backgroundPosition','0px 0px');
		hideGameBanner();
		document.cookie = 'showgameinfo=false; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/';
	}
}

$(document).ready(function(){
	if (readCookie('showgameinfo') == "true") {
		info = true;
		$('#overlaybutton_info').css('backgroundPosition','0px 48px');
	}
});

function readCookie(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;
}


var nurl = '';
var ndur = '00:00:00';
var plpos = 0;
var oldselection = '';
var firstad = true;
function startPlaying(cur) {
	$('#errorwindow').hide();
	$('#videoplayer123').html('');
	var pitem = "";
	for (i=0;i<playlist.length;i++) {
		testurl = playlist[i]['url'];
		var spl = testurl.split("/");
		if (substr_count(testurl,'gamereport.de/videos')>0 && spl[6] == cur) {
			pitem = playlist[i];
    		break;
    	}
	}

	currentposition = cur;
	at = $('#playlist-item-'+currentposition)[0];

		//currentvideocode = at.id.replace('playlist-item-','');
		var player = $f("videoplayer123", {
				src:"/static/swf/322/player.swf",
				wmode:'transparent',
					 // we need at least this Flash version 
				 // we need at least this Flash version 
			    version: [10, 0], 
			 
			    // older versions will see a custom message 
			    onFail: function()  { 
					if (this.getVersion() == "0,0") {
						$('#videoplayer123').html('<div style="text-align:center;padding-top:30px;font-size:14px;font-weight:bold;">Du benötigst Adobe Flash um diese Seite korrekt anzeigen zu können.<br /><br /><a href="javascript:void(0);" onclick="location.href=\'http://www.adobe.com/go/getflashplayer/\'">Neueste Version des Flash Player herunterladen</a></div>');
					}
					
					else {
						var str = this.getVersion()+ " ";
						str = str.replace(",",".");
						$('#videoplayer123').html('<div style="text-align:center;padding-top:30px;font-size:14px;font-weight:bold;">Du benötigste eine aktuellere Version von Adobe Flash<br />um diese Seite korrekt anzeigen zu können.<br /><small>Deine Version '+str+'</small><br /><br /><a href="javascript:void(0);" onclick="location.href=\'http://www.adobe.com/go/getflashplayer/\'">Neueste Version des Flash Player herunterladen</a></div>');
					} 
			    } 
			}, {
		    key: '80696b4370a127d31fe',
		    debug: false,
		    log: 'none',
		    onMouseOver: function() { 
		        $('#overlaybuttons').fadeIn();
		    }, 
		    onMouseOut: function() { 
		    	$('#overlaybuttons').fadeOut();     
		    },
            onError: function(errorCode,errorMessage) {
		    	/*if (errorCode != 300) {
		    		jslog(errorCode + " - " + errorMessage+ " - " + pitem['url']);
		    		$('#errorwindow').show();
		    	}*/
            },
			clip:  {
		    	url: pitem['url'],
	        	autoPlay: true,
	        	/**autoBuffering: true,**/
	        	scaling: "fit",
	        	provider: "pseudo",
	        	onFinish: function(f) {
            		
		    		if (substr_count(f.url,'gamereport.de/videos')>0) {
		    			for (i=0;i<playlist.length;i++) {
		    				if (playlist[i].url == f.completeUrl) {
		    					if ((i+1)<=playlist.length) {
		    						nitem = playlist[i+1];
		    						var spl2 = nitem['url'].split("/");
		    						if (autoplay && nitem['url'] != "") {
		    							startPlaying(spl2[6]);
		    						} else {
		    							if (nitem['url'] == "") {
		    								nitem = playlist[0];
				    						spl2 = nitem['url'].split("/");
				    						showSplash(spl2[6],'Playlistende erreicht. Bitte klicken um Playlist neu zu starten.');
				    						$('#errorwindow').hide();
		    							} else {
		    								showSplash(spl2[6],'Nächstes Video bitte klicken');
		    							}
		    						}
		    					}
		    				}
		    			}
		    		}
        		
		    		hideGameBanner();
	            },
	            onStop: function() {
	            	hideGameBanner();
	            },
	            onMetaData: function(e1) {
	            	//$('#menu').html(e1.url);
	                if (substr_count(e1.url,'gamereport.de')>0) {
	                    playingvid = true;
	                } else {
	                    playingvid = false;
	                }
	            },
	            onBeforeBegin: function(f) {
	            	
	            },
	            onBegin: function(f) {
            		selectInListById(cur);
	            	if (substr_count(f.completeUrl,'gamereport.de/videos')>0) {
	            		$('#playlist-blocker').hide();
	            		$('#comment-box').show();
	            		isAd = false;
	            	} else {
	            		$('#playlist-blocker').show();
	            		$('#comment-box').hide();
	            		isAd = true;
	            	}
	            }
			},
	        canvas: { 
	 		   backgroundColor: '#000000', 
	 		   backgroundGradient: 'none' 
	 		},
	        plugins: {
				pseudo: {
			    	url: "/static/swf/322/pseudostreaming.swf",
			    	queryString: escape('?start=${start}')
				},
				pseudoInstream: {
			    	url: "/static/swf/322/pseudostreaming.swf",
			    	queryString: escape('?start=${start}')
				},
				controls: {
					url: "/static/swf/322/controls.swf",
					playlist:false
				},
			    gameBanner: { 
			        url: '/static/swf/322/content.swf', 
			        left: 2000,
			        bottom: 25, 
			        height: 200,
			        borderRadius: 0,  
			        border: 0,
			        backgroundColor: 'transparent',
					backgroundGradient: 'none',
					opacity: 1.0,
					style: {
						'.fulltitle': {
								fontSize: 26,
								fontFamily: 'verdana,arial,helvetica' 
						}
					}
			    },
			    gatracker: {
					url: "/static/swf/322/analytics.swf",
					trackingMode: "AS3",
					debug: false,
					googleId: google_id,
					labels: {
						start: "Start",	
						play: "Play",	
						pause: "Pause",	
						resume: "Resume",	
						seek: "Seek",	
						stop: "Stop",	
						finish: "Finish",	
						mute: "Mute",	
						unmute: "Unmute",	
						fullscreen: "Full Screen",	
						fullscreenexit: "Full Screen Exit"	
					}
				},
			    ova: {
		            url: "/static/swf/322/ova.swf",
		            "providers": {
		                "http": "pseudo"
			        },
                    "shows": {
                        "streams": playlist
                    },
                    "autoPlay": true,
		            "ads": adconfig
		         }

	        }
	    });

	//player.play(0);
	
}

if (adconfig == undefined) var adconfig = {};

function showSplash(id,txt) {
	var size = 'wl';
	if (mode == 'hd') size = 'hd';
	$('#videoplayer123').html(
			$('<div>').attr('style','position:relative').append(
				$('<a>').attr('href','javascript:void(0)').attr('onclick','startPlaying(\''+id+'\')').append(
						$('<img>').attr('src','http://static001.gamereport.de/videos/preview/'+id+'/preview_'+size+'_9.jpg')
				)
			).append(
					$('<div>').attr('style','position:absolute;left:0px;top:0px;padding:10px;background-color:#000000;font-size:12px;color:#FFFFFF').append(
							$('<p>').html(txt)
					)
			)
	);
}


function substr_count (haystack, needle, offset, length) {
    var pos = 0, cnt = 0;

    haystack += '';
    needle += '';
    if (isNaN(offset)) {offset = 0;}
    if (isNaN(length)) {length = 0;}
    offset--;

    while ((offset = haystack.indexOf(needle, offset+1)) != -1){
        if (length > 0 && (offset+needle.length) > length){
            return false;
        } else{
            cnt++;
        }
    }

    return cnt;
}

function createColorPicker(field,sel,colour,livepreview) {
	$('#selector_'+field+'_'+sel+' div').css('backgroundColor', '#' + colour);
	$('#color_'+field+'_'+sel).val('#' + colour);
	//$(''+field+'').css(sel+'', '#' + colour);
	
	$('#selector_'+field+'_'+sel).ColorPicker({
		color: colour,
		onShow: function (colpkr) {
			$(colpkr).fadeIn(500);
			return false;
		},
		onHide: function (colpkr) {
			$(colpkr).fadeOut(500);
			return false;
		},
		onChange: function (hsb, hex, rgb) {
			$('#selector_'+field+'_'+sel+' div').css('backgroundColor', '#' + hex);
			$('#color_'+field+'_'+sel).val('#' + hex);
			if (livepreview == "true") $(''+field+'').css(sel+'', '#' + hex);
		}					
	});
}
var loginoverlay = "";
var logincallback = "";
function login(callback) {
	logincallback = callback;
	if(fbLoggedIn) {
		$('#loginbox_fb').show();
		$('#loginbox_gr').hide();
		$('#loginbox_login').hide();
	} else if(grid != '') {
		$('#loginbox_fb').hide();
		$('#loginbox_gr').show();
		$('#loginbox_login').hide();
	} else {
		$('#loginbox_fb').hide();
		$('#loginbox_gr').hide();
		$('#loginbox_login').show();
	}
	
	FB.XFBML.Host.parseDomTree();
	if (loginoverlay == "") {
		loginoverlay = $('#loginbox').overlay({
			api: true,
		    top: 120, 
		    closeOnClick:false, 
		    expose: {  
		        color: '#fff', 
		        loadSpeed: 200, 
		        opacity: 0.5 
		    },
		    onClose: function(event) {
		    	if (logincallback != null && logincallback != "") {
		    		window.setTimeout(logincallback,1);
		    		window.setTimeout("resetLoginCallBack()",500);
		    	}
		    } 
		});
	}
	loginoverlay.load();
}
function cancelLogin() {
	resetLoginCallBack();
	loginoverlay.close();
}
function resetLoginCallBack() {
	logincallback = "";
}

var fbLoggedIn = false;
function ensureLoginState() {
	FB.ensureInit(
		function() { 
			FB.Connect.get_status().waitUntilReady( 
					function( status ) { 
						switch ( status ) { 
							case FB.ConnectState.connected: 
								fbLoggedIn = true; 
								break; 
							case FB.ConnectState.appNotAuthorized: 
							case FB.ConnectState.userNotLoggedIn:  
								fbLoggedIn = false; 
								break;
						} 
					}
			); 
		}
	); 
}
function onConnected(user_id) {
	fbLoggedIn = true; 
	if (loginoverlay != '') loginoverlay.close();
	loginstate();
} 
function onNotConnected() { 
	fbLoggedIn = false;
	if (loginoverlay != '') loginoverlay.close();
	loginstate();
} 
var grid = '';
var gravatar = '';
function isLoggedIn() {
	if (optinemail != "") return true;
	if (fbLoggedIn) return true;
	if (grid != '') return true;
	return false;
}
function GRLogout() {
	$('#grloginloading').show();
	$.post("/ajax/ajax.php", { func: "grlogout" },
    function(data) {
		grid = "";
		gravatar = "";
		loginoverlay.close();
		$('#grloginloading').show();
		$('#grloginfailed').hide();
    	$('#grloginlogin').show();
    	loginstate();
    }, "json");
}
function GRLogin() {
	$('#grloginloading').show();
	$('#grloginfailed').hide();
	$('#grloginlogin').hide();
	$.post("/ajax/ajax.php", { func: "grlogin", user: $('#grusername').val(), pass: $('#grpass').val() },
    function(data) {
		$('#grloginloading').hide();
	    if (data == "failed") {
	    	$('#grloginfailed').show();
	    	$('#grloginlogin').show();
	    	loginstate();
		    return false;
	    }
	    loginoverlay.close(); 
	    $('#grloginfailed').hide();
	    $('#grloginlogin').show();
		grid = data['loginname'];
		gravatar = data['avatarcode']; 
		loginstate();
		//useGRLogin();
		//$('#commenttext').focus();
    }, "json");
}
var optinemail = "";
function UseOptIn() {
	optinemail = $('#optinemail').val();
	$('#grloginloading').show();
	$.post("/ajax/ajax.php", { func: "optinlogin", optinemail: optinemail },
    function(data) {
		$('#grloginloading').hide();
	    if (data == "failed") {
	    	alert('failed');
	    }
	    loginoverlay.close(); 
		loginstate();
		//useGRLogin();
		//$('#commenttext').focus();
    }, "json");
	
}
function loginstate() {
	$.post("/ajax/ajax.php", { func: "loginstate" },
		    function(data) {
				$('#myaccount').html(data);
				FB.XFBML.Host.parseDomTree();
		    }, "json");
}

var nickavailable = false;
function doComment() {
	if (grid == "") {
		if($('#commentnick').val().length < 4 || $('#commentnick').val() == 'Dein Nickname') {
			alert('Bitte gebe einen Nick an der für dich verwendet werden soll');
			$('#commentnick').focus();
			return;
		}
	}
	if($('#commenttext').val().length<5) {
		alert('Kommentar zu kurz');
		$('#commenttext').focus();
	}
	$.post("/ajax/ajax.php", { func: "comment2", comment: $('#commenttext').val(), code: currentvideocode, optinemail: optinemail, cnick:$('#commentnick').val() },
    function(data) {
		$('#commenttext').val('');
		if (data == "already") {
			alert('Du hast bereits einen Kommentar vor einigen Momenten geschrieben');
			$('.writecommentinfo').fadeIn();
			$('#writecomment').slideUp();
		} else {
			if (data=="successoptin") {
				alert('Du hast eine E-Mail mit Aktivierungslink für deinen Kommentar erhalten.');
			}
			loadComments();
		}
    }, "json");
}
function reloadComments() {
	at = $('#playlist-item-'+currentposition)[0];
	currentvideocode = at.id.replace('playlist-item-','');
	$.post("/ajax/ajax.php", { func: "getcomments2", code: currentvideocode },
    function(data) {
		$('#block_video_comments').html(data['comments']);
		showCommentField();
    }, "json");
	
}
