/* ================== General =============== */
function switchReacties(doID) {

	var tabs = new Array();
	tabs[0] = 'tab_left'
	tabs[1] = 'tab_right'
	
	for(i=0; i<tabs.length; i++) {
		if(tabs[i] == doID) {
			document.getElementById(tabs[i]).style.display = 'inline';
			document.getElementById('id_'+tabs[i]).className = 'active_'+tabs[i];
		}
		else {
			document.getElementById(tabs[i]).style.display = 'none';
			document.getElementById('id_'+tabs[i]).className = tabs[i];
		}
	}
}

function popup(url, width, height, name)
{
	if (!name)
	{
		name = '_popup';
	}

	window.open(url.replace(/&amp;/g, '&'), name, 'height=' + height + ',resizable=yes,scrollbars=yes,width=' + width);
	return false;
}

function showAllRelated(gid, nid) {
	$.post("/relatednews.inc.php", {'game_id': gid,'news_id': nid, 'limit': 'none'}, function(result){
		$("#relatedNews").fadeOut("slow", function() {
			$(this).html(result).fadeIn("slow");
		});
	});
}

/* ================ Reacties =============== */
function addBBCodeToReactie(tag, target) {
	var src = document.getElementById(target);
 
	if(tag == 'link'){
		var url = prompt('Voeg URL in', '');
		if(url) {
			var title = prompt('Voeg link titel in', '');
			if(title == ''){
				var title = url
			}
			start = '[url='+url+']'+title;
			end = '[/url]';
		}
		else {
			start = ''; end = '';
		}
	}
	else if(tag == 'quote') {
		var start = '[quote]';
		var end = '[/quote]';
	}
	else if(tag == 'b' || tag == 'i' || tag == 'u') {
		var start = '['+tag+']';
		var end = '[/'+tag+']';
	}
	else {
		var start = tag;
		var end = '';
	}
	if(!src.setSelectionRange) { 
		var selected = document.selection.createRange().text; 
		if(selected.length <= 0) {
			src.value += start + end;
		}
		else {
			var codetext = start + selected + end; document.selection.createRange().text = codetext;
		}
	} else {
		var pretext = src.value.substring(0, src.selectionStart);
		var codetext = start + src.value.substring(src.selectionStart, src.selectionEnd) + end;
		var posttext = src.value.substring(src.selectionEnd, src.value.length)
		if(codetext == start + end)
			codetext = start + end;
			src.value = pretext + codetext + posttext;
	}
	src.focus();
}

function quoteReactie(rid, username) {
	var quotedText = $("#reactie_"+rid).text();
	//quotedText = quotedText.replace(/<br>/g, ".space.");
	quotedText = "[quote][b]"+username+" schreef:[/b]" + quotedText + "[/quote]";
	var textarea = $('textarea#reactie').get(0);
	textarea.value += (quotedText);
	textarea.scrollTop = textarea.scrollHeight;
	$.scrollTo('#reactiesTop',{speed:600});
	$("#reactie").text(textarea);
}

function editReactie(rid) {
	$("#rr"+rid).slideUp("slow", function() {
		clearTimeout(t);
		$("#reactieSubmitButton").attr('src','/images/button_bewaar.png');
		$("#reactieCancelButton").fadeIn("fast");
		var curText = $("#reactie_r"+rid).text();
		var textarea = $('textarea#reactie').get(0);
		textarea.value = (curText);
		textarea.scrollTop = textarea.scrollHeight;
		$.scrollTo('#reactiesTop',{speed:600});
		//alert('text ophalen');
		//$("#reactie").text(textarea);
		//alert('text erin');
		var currReactieID = $("#reactieid").val();
		if(currReactieID !=0 && currReactieID !=rid) {
			$("#rr"+currReactieID).slideDown("slow");
		}
		$("#reactieid").val(rid);
		//alert('reactie id set: '+rid);
		$("#mode").val('edit');
		//alert('mode set: edit');
	});
}

function cancelEdit() {
	var rid = $("#reactieid").val();
	$("#rr"+rid).slideDown("slow");
	$("textarea#reactie").val(" ");
	$("#reactieid").val(0);
	$("#mode").val('submit');
	$("#reactieSubmitButton").attr('src','/images/button_plaats_reactie.gif');
	$("#reactieCancelButton").fadeOut("fast");
}

function submitReactie(uid, nid, cat) {
	$("#reactieSubmitButton").attr('src','/images/button_versturen.gif');
	var reactie = $('textarea#reactie').val();
	var reactieid = $("#reactieid").val();
	var mode = $("#mode").val();
	
	if(reactie.length > 3 && uid != 0 && nid !=0) {
		$.post("/scripts/ajax.reactie.php", {'reactie': reactie,'userid': uid,'artikelid': nid,'cat': cat,'reactieid': reactieid,'mode': mode}, function(result){
			if (result == 'error') alertTop('Er is een fout opgetreden bij het bewaren van je reactie, probeer het nogmaals of meld dit in het Feedback forum');
			else if(result == 'error1') alertTop('Je kan niet zo snel achter elkaar een reactie plaatsen, ga even gamen ofzo <img src="http://forum.ps3life.nl/images/smilies/icon_e_smile.gif">');
			else if(result == 'error2') alertTop('Je kan als gast niet meer reageren, je moet registreren of inloggen om te reageren op dit artikel');
			//alert(result);
			else {
				$("textarea#reactie").val(" ");
				clearTimeout(t);
				refreshReacties(nid, 1);
				if(mode == 'edit') {
					//alert('Je reactie is bewaard, ik scroll nu naar #r'+reactieid);
					alertTop('Je reactie is bewaard');
					$("#rr"+reactieid).show();
					$("#reactieid").val(0);
					$("#mode").val('submit');
					$("#reactieCancelButton").fadeOut("fast");
					$.scrollTo("#rr"+reactieid,{speed:600});
				}
			}
		});
	}
	else alertTop('Je moet wel wat invullen als je een reactie wilt plaatsen <img src="http://forum.ps3life.nl/images/smilies/icon_e_wink.gif">');
	setTimeout('$("#reactieSubmitButton").attr("src","/images/button_plaats_reactie.gif");', 1500);
}

function reactiesPage(nid, page) {
	clearTimeout(t);
	setTimeout('refreshReacties('+nid+', '+page+')', 1500);
	$.scrollTo("#reactiesTop",{speed:900});
}

function refreshReacties(nid, page) {
	//$("#loadingImage").slideDown("slow");
	if(!page) page = 1;
	if(nid !=0) {
		$.post("/scripts/ajax.reactie.php", {'artikelid': nid, 'reactiespagina': page}, function(result){ $("#reactiesTable").html(result); });
		t=setTimeout('refreshReacties('+nid+', '+page+')', 30000);
	}
	else alertTop('Geen artikel id opgegeven');
	setTimeout('$("#loadingImage").slideUp("slow");', 1500);
	//$("#loadingImage").slideUp("fast");
}

/* =========== Collections / Wishlists ======= */
function appendRatings(gameid) {
	var i=1;
	rate_html = "<div class='ratingbox'><div id='ratingcontainer'><form id='rate' action='/scripts/ratings.php' method='post' accept-charset='utf-8'><label for='rating'>Rate deze game:</label><select name='rating' id='rating'>"
	for (i=1;i<11;i++) {
		if(i==6) rate_html = rate_html + "<option value='"+i+"' selected='selected'>"+i+"</option>";
		else rate_html = rate_html + "<option value='"+i+"'>"+i+"</option>";
	}
	rate_html = rate_html + "</select><input type='hidden' name='gid' value='"+gameid+"'/><input id='ratingbutton' type='submit' value=''/></form></div></div>";

	/*$(".ratingbox").css({height: "175px"}).animate({height: "1px"},700);*/
	$(".ratingbox").slideUp("slow");
	$("#resultRating").html(rate_html).fadeIn("slow");
	$('select#rating').selectToUISlider({labels: 10, tooltip: false });
  $("#rate").submit(rateProcess);
}

function addGame(gameid, userid, lijsttype, move, returnslider) {
	if(lijsttype == 'wens') {
		$.post("/scripts/ajax.wenslijst.php", {'gameid': gameid,'userid': userid}, function(result){
			if(move) {
				$("#g" + gameid).fadeOut("slow", function () {
					$("#ratingbox").empty();
					$(this).remove();
					alertTop('Het spel is verplaatst naar je wenslijst');
				});
			}
			else {
				//$("#resultMessage").fadeOut("slow", function(){ $("#resultMessage").animate({height: "45px"},500).text(result).fadeIn("slow");});
				//$("#addcollwish").fadeOut("slow", function(){ $(this).remove(); });
				alertTop(result);
			}
		});
	}
	else if (lijsttype == 'collectie') {
		$.post("/scripts/ajax.collectielijst.php?move="+move, {'gameid': gameid,'userid': userid}, function(result){
			if(move) {
				if(result == 'ok') {
					$("#g" + gameid).fadeOut("slow", function () {
						$(this).remove();
						alertTop('Het spel is verplaatst naar je collectie');
					});
				}
				else alertTop('Je kan dit spel niet in je collectie plaatsen, waarschijnlijk is hij nog niet uit');
			}
			else {
				if(result == 'ok') {
					//$("#resultMessage").fadeOut("slow", function(){ $("#resultMessage").animate({height: "45px"},500).text('Het spel is toegevoegd aan je collectie').fadeIn("slow");});
					alertTop('Het spel is toegevoegd aan je collectie');
					if(returnslider) appendRatings(gameid);
					//$("#addcollwish").fadeOut("slow", function(){ $(this).remove(); });
				}
				else if(result == 'duplicate') alertTop('Je hebt dit spel al in je collectie staan');
				else alertTop('Je kan dit spel niet in je collectie plaatsen, waarschijnlijk is hij nog niet uit');
			}
		});
	}
	else return false;
}

function delGame(gameid, userid, lijsttype) {
	if(confirm('Weet je zeker dat je het spel wilt verwijderen?')) {
		if(lijsttype == 'wens') {
			$.post("/scripts/ajax.wenslijst.php", {'gameid': gameid,'userid': userid, 'delete': true}, function(result){
				if(result == 'error') alertTop('Er is een fout opgetreden tijdens het bewerken van je wenslijst, probeer het nogmaals');
				else {
					$("#g" + gameid).fadeOut("slow", function () {
						$(this).remove();
						alertTop('Het spel is verwijderd');
					});
				}
			});
		}
		else if (lijsttype == 'collectie') {
			$.post("/scripts/ajax.collectielijst.php", {'gameid': gameid,'userid': userid, 'delete': true}, function(result){
				if(!result) alertTop('Er is een fout opgetreden tijdens het bewerken van je collectie, probeer het nogmaals');
				else {
					$("#g" + gameid).fadeOut("slow", function () {
						$(this).remove();
						alertTop('Het spel is verwijderd');
					});
				}
			});
		}
	}
	else return false;
}

/* ================== Polls ================== */

// Global variable definitions
var votedPID;

function pollProcess(event){
	event.preventDefault();
	var id = $("input[name='poll']:checked").attr("value") || false;
	if (id == false) {
		return false;
	};

	id = id.replace("opt",'');
	var pollid = $("input[name='pid']").attr("value");
	votedPID = id;

	if (jQuery.browser.msie) {
		overlay = "<div id='polloverlay'></div>";
		$("#pollbox").prepend(overlay);
		$("#polloverlay").fadeIn("slow",function(){
			$("#poll-container").empty();
			$.post("/scripts/poll.php",{vote: id, pid: pollid}, loadPollResults, "json");
		});
	}else{
		$("#poll-container").fadeOut("slow",function(){
			$(this).empty();
			$.post("/scripts/poll.php",{vote: id, pid: pollid}, loadPollResults, "json");
		});
	}
}

function animatePollResults(){
	$("#poll-results div").each(function(){
		var percentage = $(this).next().text();
		$(this).css({width: "0%"}).animate({width: percentage}, 1600);
	});
}

function loadPollResults(data) {
	var total_votes = 0;
	var percent;

	for (id in data["options"]) {
		total_votes = total_votes+parseInt(data["options"][id].votecount);
	}
	var results_html = "<div id='poll-results'><h3>Poll Resultaten</h3>\n<p id='polltitel'>"+data.pollquestion+"</p>\n<dl class='graph'>\n";
	for (id in data["options"]) {
		percent = Math.round((parseInt(data["options"][id].votecount)/parseInt(total_votes))*100);
		if (id == votedPID) {
			results_html = results_html+"<dt class='bar-title'>"+data["options"][id].optionTitle+"</dt><dd class='bar-container top'><div id='bar"+data["options"][id]+"'style='width:0%;'>";
			if (percent > 5) { results_html = results_html+percent+"%"; }
			results_html = results_html+"</div><span>"+percent+"%</span><strong>"+data["options"][id].votecount+"</strong></dd>\n";
		} else {
			results_html = results_html+"<dt class='bar-title'>"+data["options"][id].optionTitle+"</dt><dd class='bar-container'><div id='bar"+data["options"][id]+"'style='width:0%;'>";
			if (percent > 5) { results_html = results_html+percent+"%"; }
			results_html = results_html+"</div><span>"+percent+"%</span><strong>"+data["options"][id].votecount+"</strong></dd>\n";
		}
	}
	results_html = results_html+"</dl><p>Totaal aantal votes: "+total_votes+"</p></div>\n";

  if (jQuery.browser.msie) {
  	$("#poll-container").append(results_html);
  	$("#polloverlay").fadeOut(1500,function(){animatePollResults();});
  }else{
  	$("#poll-container").append(results_html).fadeIn("slow", function(){animatePollResults();});
  }
}

/* ================== Gameratings ================== */

var votedGID;

function rateProcess(event) {
	var id = $("select#rating").attr("value") || false;
	if (id == false) {
		return false;
	};
	votedRID = id;
	var gameid = $("input[name='gid']").attr("value");
	/*alert(votedRID + ' and ' + gameid);*/

	if (jQuery.browser.msie) {
		overlay = "<div id='rateoverlay'></div>";
		$(".ratingbox").prepend(overlay);
		$(".ratingbox").css({height: "50px"}).animate({height: "175px"},1000);
		$("#rateoverlay").fadeIn(500,function(){
			$("#ratingcontainer").empty();
			$.post("/scripts/ratings.php",{rstem: id, gid: gameid}, loadRateResults, "json");
		});
	}else{
		$(".ratingbox").css({height: "50px"}).animate({height: "175px"},1000);
		$("#ratingcontainer").fadeOut(500,function(){
			$(this).empty();
			$.post("/scripts/ratings.php",{rstem: id, gid: gameid}, loadRateResults, "json");
		});
	}
	return false;
}

function loadRateResults(data) {
	var total_votes = 0;
	var percent;

	max_votes = data["max"];
	for (id in data["results"]) {
		total_votes = total_votes+parseInt(data["results"][id].vc);
	}

	var results_html = "<h4>Community beoordeling:</h4><dl id='ratings'>\n";
	for (id in data["results"]) {
		percent = Math.round((parseInt(data["results"][id].vc)/parseInt(total_votes))*100);
		if (percent == 100) {
			barpct = percent;
		}else{
			barpct = Math.round((parseInt(data["results"][id].vc)/parseInt(total_votes))*(((parseInt(total_votes)/parseInt(max_votes))*0.88)*100));
		}
		if (id == votedRID) {
			results_html = results_html+"<dt class='rbar-title'>"+id+"</dt><dd class='rbar-container top'><div id='rate"+id+"' style='width:"+barpct+"%;'>";
			if (barpct > 10) { results_html = results_html+percent+"%"; }
			results_html = results_html+"</div><strong>"+data["results"][id].vc+"</strong></dd>\n";
		} else {
			results_html = results_html+"<dt class='rbar-title'>"+id+"</dt><dd class='rbar-container'><div id='rate"+id+"' style='width:"+barpct+"%;'>";
			if (barpct > 10) { results_html = results_html+percent+"%"; }
			results_html = results_html+"</div><strong>"+data["results"][id].vc+"</strong></dd>\n";
		}
	}
	results_html = results_html+"</dl><p>Totaal aantal stemmen: "+total_votes+"</p>\n";
	
  if (jQuery.browser.msie) {
  	$("#rateoverlay").css({height: "175px"});
  	$("#ratingcontainer").append(results_html).show();
  	$("#rateoverlay").fadeOut(500);
  }else{
  	$("#ratingcontainer").append(results_html).fadeIn(500);
 	}
}
/* =================== ERROR ================== */
function alertTop(msg) {
	$alert = $('div#alertTop');
	$alert.animate({top:$(window).scrollTop()+"px" },{queue: false, duration: 350});
	$alert.html(msg);
	var alerttimer = window.setTimeout(function () {
		$alert.trigger('click');
	}, 3000);
	$alert.animate({height: $alert.css('line-height') || '50px'}, 200)
	.click(function () {
		window.clearTimeout(alerttimer);
		$alert.animate({height: '0'}, 200);
	});
}

/* ================== DocReady =============== */
$(document).ready(function(){
/* spoilers */
	$("span.spoiler").hide();
	
	$('<a class="reveal"><b>Lees spoiler »</b></a> ').insertBefore('span.spoiler');

	$("a.reveal").click(function(){
		$(this).parents("div").children("a.reveal").hide();
		$(this).parents("div").children("span.spoiler").fadeIn(1000);
	});

/* ratings and polls */
	$("#rate").submit(rateProcess);
	$("#poll").submit(pollProcess);
	if ($("select#rating").length > 0 ) { $('select#rating').selectToUISlider({labels: 10, tooltip: false }); }
	if ($("#poll-results").length > 0 ) { animatePollResults(); }

/* trophies unhide */
	$('a.tsone').click(function() {
		$(this).parent().parent().fadeOut('fast');
		$(this).parent().parent().parent().removeClass('tbg_H');
		return false;
	});
	$('a.tsall').click(function() {
		$('div.overlay').fadeOut('fast');
		$('div.trop').removeClass('tbg_H');
		return false;
	});
});