(function(){
$.postJSON = function(url,data,callbacks){
	$.ajax({'url':url,'data':data,'dataType':'json','error':callbacks.error,'success':callbacks.success,'type':'POST','global':'false'});
	//$.post(url,data,callback,'json');
};

// Define namespace for AXN interview
AXN_IV = {};

AXN_IV.templates = {
	'question'	:	{
		'template':'<p>%content%</p>',
		'keys':{'content':/%content%/g}
	},
	'answer'	:	{
		'template':'<div class="item"><span>%name%</span><p>%question%</p><span class="%axn%">&nbsp;</span><p class="w">%answer%</p></div>',
		'keys':{'question':/%question%/g,'answer':/%answer%/g,'name':/%name%/g,'axn':/%axn%/g}
	}
};

AXN_IV._ = function($_){
	if (arguments.length==0)
		return;
};

AXN_IV.inherit = function(s,b) {
	function $_$() {}
	$_$.prototype = b.prototype;
	s.prototype = new $_$();
	s.prototype.constructor = s;
	s.baseConstructor = b;
	s.superClass = b.prototype;
};

AXN_IV.itemCollection = function(container,type, timerSeconds, form) {
	if (arguments.length>0) {
		AXN_IV.itemCollection.baseConstructor.call(this,null);
		this.enableSend = true;
		this.form = form;
		this.container = container;
		this.hasMore = true;
		this.type = type;
		this.items = [];
		var _this = this;

		function onTimer() {
			_this.checkNew();
		}
		
		this.timer = setInterval(onTimer,timerSeconds*1000);
		this.container.parent().scroll(function(){
			if (_this.hasMore) {
				var t = $(this);
				if (t[0].scrollHeight - t.scrollTop() == t.outerHeight()) {
					_this.checkMore();
				}
			}
		});
	}
};

AXN_IV.inherit(AXN_IV.itemCollection,AXN_IV._);

var icp = AXN_IV.itemCollection.prototype;

icp.getNewestId = function() {
	return (this.items.length==0) ? 0 : this.items[0].info.id;
};

icp.getOldestId = function() {
	return (this.items.length==0) ? 0 : this.items[this.items.length-1].info.id;
};

icp.getURL = function(suffix) {
	return '/'+this.type+'/'+suffix;
};

icp.setSend = function(enable) {
	this.enableSend = enable;
	if (this.form!=null)
		$('#submit',this.form).attr('disabled',enable?'':'disabled');
};

icp.onError = function(err) {
	err = err || 'An error occured, please try again!';
	this.setSend(true);
	//alert(err);
};

icp.getResponseError = function(data) {
	if (data==null)
		return 'Empty response';
	else if ((typeof data.error != 'undefined') && (data.error != ''))
		return data.error;
	else
		return null;
};

/**
 * TODO Ossze kell vonni a ket fetchert, es checkolni kell a json-os hibakat is!
 */
icp.checkNew = function(data,suffix) {
	function onError(err) {		
		_this.onError(err);
	}
	if (!this.enableSend)
		return;
	this.setSend(false);
	data = data || {};
	data.LastId = this.getNewestId();
	var _this = this;	
	$.postJSON(this.getURL(suffix||'list'),data,{'success':function($$data){
		_this.setSend(true);
		var err = _this.getResponseError($$data);
		if (err!=null) {
			onError(err);
		} else {
			if (_this.type=='question' && suffix=='add') {
				Recaptcha.reload();
				_this.form[0].question.value = '';
			}
			var counter = 0;
			$.each($$data,function($$index,$$item){
				var i = _this.createItem($$item);
				_this.container.prepend(i);
				_this.items.unshift({'info':$$item,'elem':i});
				counter++;
			});
			if (_this.type=='answer') {
				try {
				    (counter>0) ? $('#noAnswerImage').remove() : $('#noAnswerImage').css('visibility','visible');
				} catch (e) {}
			}

		}
	},'error':onError});
};

icp.checkMore = function() {
	function onError(err) {
		_this.onError(err);
	}
	var _this = this;
	$.postJSON(this.getURL('suffix'),{'LastId':this.getOldestId()},{'success':function($$data){
		var err = _this.getResponseError($$data);
		if (err!=null) {
			onError(err);
		} else {
			_this.hasMore = false;
			$.each($$data,function($$index,$$item){
				var i = _this.createItem($$item);
				_this.container.append(i);
				_this.items.push({'info':$$item,'elem':i});
				_this.hasMore = true;
			});
		}
	},'error':onError});
};

icp.createItem = function($$item) {
	var html = AXN_IV.templates[this.type].template;
	for (var key in AXN_IV.templates[this.type].keys) {
		html = html.replace(AXN_IV.templates[this.type].keys[key],$$item[key]);
	}
	return $(html);
};

AXN_IV.questionCollection = function(container,form) {
	if (arguments.length>0) {
		AXN_IV.questionCollection.baseConstructor.call(this,container,'question',3600,form);
	}
};

AXN_IV.inherit(AXN_IV.questionCollection,AXN_IV.itemCollection);

AXN_IV.questionCollection.prototype.send = function(name,content,challenge,response) {
	var data = {
		'name'				:	name.substr(0,128),
		'content'			:	content.substr(0,300),
		'captchaChallenge'	:	challenge,
		'captchaResponse'	:	response
	};
	this.checkNew(data,'add');
};

AXN_IV.answerCollection = function(container) {
	if (arguments.length>0) {
		AXN_IV.answerCollection.baseConstructor.call(this,container,'answer',1200,null);
	}
};

AXN_IV.inherit(AXN_IV.answerCollection,AXN_IV.itemCollection);

AXN_IV.answerCollection.prototype.createItem = function($$item) {
	return AXN_IV.answerCollection.superClass.createItem.call(this,{'question':$$item.question,'answer':$$item.answer,'name':$$item.name,'axn':$$item.axn?'axn':'joe'});
};

})();

($(document).ready(function(){
	var charsRegexp = /%chars%/g;
	$('*[maxlength]').keyup(function(){
		var _this = $(this);
		var max = parseInt(_this.attr('maxlength'));
		if (_this.val().length>max) {
			_this.val(_this.val().substr(0,_this.attr('maxlength')));
		}
		if (_this.attr('charsleft'))
			$('#'+_this.attr('charsleft')).text(OPTIONS.charsLeftTemplate.replace(charsRegexp,max-_this.val().length));
	});
	CONTROLLERS = {
		'question'	:	new AXN_IV.questionCollection($('#innerQuestions'),$('#questionForm')),
		'answer'	:	new AXN_IV.answerCollection($('#innerAnswers'))
	};
	CONTROLLERS.question.checkNew();
	CONTROLLERS.answer.checkNew();
}));

function sendQuestion(form) {
	CONTROLLERS.question.send(form.name.value,form.question.value,form.recaptcha_challenge_field.value,form.recaptcha_response_field.value);
	return false;
}

function biography(lang) {
	window.open('/popup/'+lang,'','width=600,height=500');
}