
var confirm_exit = false;
var confirm_exit_msg = "If you leave this page all your changes will be discarded.";
window.onbeforeunload = function(){
  if(confirm_exit) return confirm_exit_msg;
}

$(document).ready(function(){
	
	var topswidth = $("#topnav").width() + 60;
	
	//arr: 0=title; 1=type; 2=url; 3=tag
	$("#topsearch").hover(
		function(){ $(this).addClass("hov"); },
		function(){ $(this).removeClass("hov"); }
	).find("input").css("width", topswidth).focus(function(){
		$(this).removeClass("blurred");
		$("#newpms").hide();
	}).blur(function(){
		$(this).animate({opacity:1}, 200, function(){ $(this).addClass("blurred"); });
		$("#newpms").show();
	}).autocomplete(
		"/bin/php/autocomplete.php",
		{ minChars:3,
			max:50,
			width:(topswidth + 21),
			selectFirst:false,
			formatItem:function(row) {
				return '<small>'+row[1]+"</small>"+row[0];
			}
		}
	).result(function(event, data, formatted) {
		document.location=data[2];
	});
	
	$("a[href='#login'], a[href='/login.php']").click(function(Ev) {
		Ev.preventDefault();
		if( $("#login").is(":visible") ) $("#login").fadeOut();
		else $("#login").fadeIn();
	});
	
	$("input.styled, textarea.styled").focus(function() {
		$(this).addClass("styled-on");
	}).blur(function() {
		$(this).removeClass("styled-on");
	});
	
	$(".resetonfocus").each(function() {
		var ival = $(this).val();
		$(this).focus(function() {
			if( $(this).val() == ival ) {
				$(this).removeClass("resetonfocus").val("");
			};
		}).blur(function(){
			if( $(this).val() == "" ) $(this).addClass("resetonfocus").val(ival);
		});
	});
	//clear field set as resetonfocus upon form submit
	$("form").submit(function(){
		$(this).children(".resetonfocus").val('');
	});
	$(".fftt .ff").each(function(){
		if( $(this).val() ){ $(this).siblings(".tt").hide(); }
	}).live("focus", function(){
		$(this).siblings(".tt").animate({opacity:.2}, 1000, function(){ $(this).addClass("foc") });
	}).live("blur", function(){
		if( $(this).val() == '' ){ $(this).siblings(".tt").show().removeClass("foc").css("opacity",1); }
		else $(this).siblings(".tt").hide();
	});
	$(".fftt .tt").live("click", function(){
		$(this).siblings(".ff").focus();
	});
	
	$("input[type='button'], button, input[type='submit'], input[type='reset']").hover(
		function(){
			$(this).addClass("over");
		}, function(){
			$(this).removeClass("over");
		}
	).mousedown(function() {
		$(this).addClass("down");
	}).mouseup(function() {
		$(this).removeClass("down");
	}).mouseout(function() {
		$(this).removeClass("down");
	});
	
	$(".preventdefault").click(function(Ev) {
		Ev.preventDefault();
	});
	
	//$("#topnav dd ul").prev("a").attr("title", ""); //remove nav titles if there's a dropdown
	$("#topnav li").hover(function(){
		$(this).addClass("hov").siblings().addClass("blurred");
		$(this).find("dl").show();
	}, function(){
		$(this).removeClass("hov").siblings().removeClass("blurred");
		$(this).find("dl").hide();
	});
	
	if( $("#notify").html() ) showNotifications();
	
	$(".chbox").hover(function(){ $(this).addClass("chbox-hov"); }, function(){ $(this).removeClass("chbox-hov"); }).click(function(){
		$(this).toggleClass("chbox-checked");
	});
	
	$(".thumbnail").each(function(){
		if($(this).hasClass("center")) return;
		var w = $(this).find('img, object').width();
		if(w < 100) w = 100;
		$(this).css("width", w+"px");
		if(w <= 200) $(this).find('.caption').wrapInner('<small />');
	});
	
	if(!$.browser.msie) { //strange IE bug when messing with opacity here
		$("#twitter_div").hover(function(){
			$(this).animate({'opacity':1});
		}, function(){
			$(this).animate({'opacity':.6});
		});
	}
	
	//latest tweet
	if( !$("#head").hasClass("condensed") ) $("body").append('<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script><script type="text/javascript" src="http://twitter.com/statuses/user_timeline/videogamin.json?callback=twitterCallback2&amp;count=1"></script>');
	
	$("#head.condensed").hover(function(){
		$("#head, #head > *").addClass("hov");
	}, function(){
		$("#head, #head > *").removeClass("hov");
	});
	
	$(".spoiler").hover(function(){ $(this).addClass("hov"); }, function(){ $(this).removeClass("hov"); });
	
	$("form.#footfeedback").submit(function() {
		
		var ffbinp = $(this).serialize();
		
		$("#footfeedback .loading").show();
		$("#footfeedback :input").attr("disabled", "disabled");
		$("#footfeedbacksend").val('Sending...');
		
		$.post(
			"/contact.php",
			{ _input:ffbinp,
				_ajax:1 },
			function(res){
				if(res.error) alert(res.error);
				else {
					alert("Your feedback query has been successfully transmitted to the appropriate human outlet. Thanks for your feedback!");
					$("#footfeedback .inp").val('');
				}
				$("#footfeedback .loading").hide();
				$("#footfeedback :input").removeAttr("disabled");
				$("#footfeedbacksend").val('Send');
			}, "json"
		);
		
  	return false;
  	
	});
	
});

function resetUnfocused() {
	$(".resetonfocus").val("");
}

function showNotifications() {
	$("#notify:hidden").slideDown(500).append('<a href="javascript:void(0);" style="position:absolute; right:15px; bottom:12px;" onclick="$(this).parent().slideUp(300);" onmouseover="$(this).children(\'span\').addClass(\'ximg-hover\');"><span class="ximg" style="margin:1px 0 0 -20px;">x</span><b>CLOSE THIS MESSAGE</b></a>');
}

function chboxLoading(el) {
	
	if( $(el).hasClass("chbox-loading") ) return true;
	
	$(el).addClass("chbox-loading");
	return false;
	
}

var collectionOn = "synopsis"; //default on for game overview

function formRequire(req) {
	
	var reqs = req.split(",");
	for(i = 0; i < reqs.length; i++) {
		if(document.getElementById(reqs[i]).value=="") {
			alert("Please input something into the '"+reqs[i]+"' field");
			return false;
		}
	}
	
}	

function saveDraft(occ, field, fname, datetime) {
	var x = document.getElementById(field).value;
	x = x.replace('&', '[AMP]');
	document.getElementById("save-draft-button-"+occ).value="Saving...";
	document.getElementById("save-draft-button-"+occ).disabled=true;
	asyncRequest(
		"post",
		"/ninadmin/drafts.php",
		function(response) {
			if(response.responseText) {
				document.getElementById("save-draft-button-"+occ).value="Save a copy to your drafts";
				document.getElementById("save-draft-button-"+occ).disabled=false;
				document.getElementById("draft-last-saved-"+occ).innerHTML="last saved <b>"+datetime+"</b>";
			}
		},
		"new_draft=1&filename="+fname+"&words="+x
	);
}
	
var asyncRequest = function() {
	function handleReadyState(o, callback) {
	var poll = window.setInterval(function() {
	if(o && o.readyState == 4) {
	window.clearInterval(poll);
	if ( callback ){
	callback(o);
	}
	}
	},
	50);
	}
	var http;
	try {
	http = new XMLHttpRequest();
	}
	catch(e) {
	var msxml = [
	'MSXML2.XMLHTTP.3.0',
	'MSXML2.XMLHTTP',
	'Microsoft.XMLHTTP'
	];
	for ( var i=0, len = msxml.length; i < len; ++i ) {
	try {
	http = new ActiveXObject(msxml[i]);
	break;
	}
	catch(e) {}
	}
	}
	return function(method, uri, callback, postData) {
	http.open(method, uri, true);
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	handleReadyState(http, callback);
	http.send(postData || null);
	return http;
	};
}();

function validateRegistration() {
	var errormsg = "";
	var user = document.getElementById('user').value;
	var pass = document.getElementById('pass').value;
	var pass2 = document.getElementById('pass2').value;
	var email = document.getElementById('email').value;
	var validate_email = (email.indexOf(".") > 2) && (email.indexOf("@") > 0);
	var math0 = document.getElementById('reg-math').value;
	var math1 = document.getElementById('reg-math1').value;
	var math2 = document.getElementById('reg-math2').value;
	
	if(!user) errormsg = "Username is blank";
	if(/[^a-zA-Z0-9-_]/.test(user)) errormsg = "Username contains illegal characters";
	if(!pass || !pass2) errormsg = "Password is blank";
	if(pass != pass2) errormsg = "Passwords don't match";
	if(!email) errormsg = "Email is blank";
	if(!validate_email) errormsg = "Email address isn't valid";
	if(parseInt(math1) + parseInt(math2) != parseInt(math0)) errormsg = "Your math is wrong";
	if(errormsg) {
		alert("Error: "+errormsg+". Registration not submitted.");
		return false;
	} else {
		return true;
	}
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
				curleft += obj.offsetLeft;
				curtop += obj.offsetTop;
			} while (obj = obj.offsetParent);
		return [curleft,curtop];
	}
}

var NLval;
var NLvals = Array();
var NLn;
function newlineInsert(what, into) {
	if(!what) return;
	if(!into) return;
	$("#"+into).focus();
	NLval = $("#"+into).val();
	NLvals = NLval.split("\n");
	NLn = NLvals.length - 1;
	if(NLvals[NLn]) $("#"+into).val(NLval+"\n"+what);
	else $("#"+into).val(NLval+what);
}

function htmlSC(what) {
	what = what.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/\'/g, '&#039;');
	return what;
}

function registerViaAjax(em, un, pw) {
	
	$.post(
		"/register.php",
		{ _do: "ajaxreg",
			em: em,
			un: un,
			pw: pw
		},
		function(t) {
			return t;
		}
	);
	
}