/**
 * reaction.js
 *
 * used for reactions/comments
 */

function loadXMLDoc(url, method, handler, params){
	if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}else{
		// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.open(method,url,true);
	xmlhttp.onreadystatechange=handler;

	if(params){
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.setRequestHeader("Content-length", params.length);
		xmlhttp.setRequestHeader("Connection", "close");
		xmlhttp.send(params);
	}else{
		xmlhttp.send();
	}
}

function ajaxGetReactionsHandler(){
	if(xmlhttp.readyState==4){
		$('reactions_list').update(xmlhttp.responseText);
		ajaxifyCommentPaging('commentpager_${viewHelper.article.id}_top');
		ajaxifyCommentPaging('commentpager_${viewHelper.article.id}_bottom');
	}
}

function login(element){
	(element.form).request({
		method: 'post',
		parameters: { op:'simplelogin', returnUrl:'' },
		onSuccess: successFunc,
		onFailure:  failureFunc
	})
}

function successFunc(response){
	var id = response.responseText;
	$('reaction' + id).toggle();
	$('reaction' + id).focus();
        $('password_forgot' + id).hide();
	hideLogins();
}

function failureFunc(){
	alert('login failed');
}

function ajaxForgotPassword(){
	if(xmlhttp.readyState==4){
		var password_forgot = document.getElementById('password_forgot');
		password_forgot.style.display = 'none';
	}
}

function loadComments(url){
	loadXMLDoc(url, 'GET', ajaxGetReactionsHandler, null);
}

function ajaxifyCommentPaging(id) {
	if($(id)){
		$(id).select('a.commentpageajax').each( function( element ) {
			element.onclick = function() {
				loadComments(genericUrl + element.readAttribute('rel'));
				return false;
			};
		});
	}
}

function onClickReaction(element){
	if(getCookie('username')){ //or 'auth''?
		//user is logged in
	}else{
		//user is NOT logged in
		var form = element.form;
		var id = form.a.value;
		
		if(!form.i.value){
			id = form.c.value;
		}
		
		$('reaction' + id).toggle();
		$('login' + id).toggle();
		$('password_forgot' + id).setStyle('display', 'none');
			
		/* Focus inputfield */
		var loginForm = $('loginForm' + id);
		loginForm.elements['username'].focus();
	}
}

function onClickReactionForm(element){
        var form = element.form;
        var id = form.a.value;
		if(getCookie('username')){ //or 'auth''?
		//user is logged in
		var value = form.reaction_textarea.value;
		if(value.length>0){
			// CHECK FOR HTML TAGS
			var regExp = new RegExp("(<([^>]+)>)","ig");
			var message = "Het gebruik van html tags in een reactie is niet toegestaan";
			if ( regExp.match( value ) ) {
				if ( slang == "fr" ) {
					message = "Utilisation d'HTML dans un commentaire n'est pas authoris&eacute";
				}
				alert(message);
				return false;
			}
			
			$('submit_btn' + id).disabled=true;
			return true;
		}
		return false;
	}else{
		//user is NOT logged in
		if(!form.i.value){
			id = form.c.value;
		}
		
		$('reaction' + id).toggle();
		$('login' + id).toggle();
		$('password_forgot' + id).setStyle('display', 'none');
		$('submit_btn' + id).disabled=false;

		/* Focus inputfield */
		var loginForm = $('loginForm' + id);
		loginForm.elements['username'].focus();
		return false;
	}
}

function cancelLogin(id){
	$('password_forgot' + id).toggle();
}

function focusFirst(id){
	var reaction = document.getElementById('reaction' + id);
	if(reaction.style.display=='block'){
		var form = document.getElementById('commentForm' + id);
	}else{
		var form = document.getElementById('loginForm' + id);
	}
	
	var firstText = findFirstText(form);
	firstText.focus();

}

function clearText(id, language){
	if(id){
		var e = document.getElementById(id);
		e.value='';
		e.focus();
		CountLeft(e, $('charLeftMessage'), 1000, language);
	}
}

function findFirstText(form){
	var element;

	for(x=0; x<form.elements.length; x++){
		var e = form.elements[x];
		if(e.type == 'text' || e.type == 'textarea'){
			element = e;
			break;
		}
	}
	
	return element;
}

function submitForm(element){
		if($(element.form).hasClassName('notificationForm')){
			(element.form).request({
				method: 'post',
				onSuccess: ajaxNotificationHandler,
				onFailure:  emailFailureFunc
			})
		} else {
			(element.form).request({
				method: 'post',
				parameters: {op: 'lostpassword'},
				onSuccess: showPasswordSend,
				onFailure:  emailFailureFunc
			})
		}
}

function showPasswordForgotComment(id){
	$(id).show();
}

function showPasswordSend(transport){
	var response = transport.responseText.evalJSON();
	var commentId = response.commentId;
	if (response.code == "00") {
		//let's replace the form by the result sent by the ajax command, and
		$('password_forgot' + commentId).update(response.message);
		//and display the done button now
	} else {
		$('lostpassword_alert' + commentId).update(response.message);
		$('lostpassword_alert' + commentId).show();
	}
	
}

function emailSuccessFunc(){
	$('password_forgot').toggle();
}

function emailFailureFunc(){
	$('password_forgot').toggle();
}

function ajaxNotificationHandler(response){
	var commentId = getCookie('commentId');

	if(commentId){
		$('inappropriate' + commentId).update(response.responseText);
	}
}

function toggleById(name, id){
	if(name){
		var element = document.getElementById(name + id);
		var currentDisplay = element.style.display;
		hideAll(id);
		element.style.display = (currentDisplay=='none')?'block':'none';
	}
	return false;
}

function toggleForm(id){
	if(id){
		var reaction = document.getElementById('reaction' + id);
		var login = document.getElementById('login' + id);
		
		if(reaction.style.display=='block' || login.style.display=='block'){
			reaction.style.display = 'none';
			login.style.display = 'none';
		}else{
			toggleById('reaction', id);
			focusFirst(id);
		}
	}
}

function hideAll(id){
    var divs = ['reaction', 'password_forgot', 'login', 'bookmarklink', 'inappropriate'];

    for(var i=0; i<divs.length; i++){
        var div = $(divs[i] + id);
        if(div){
            div.hide();
        }
    }
}

function hideLogins(){
	var divs = document.getElementsByTagName('div');
	for(var x=0; x<divs.length; x++){
		if(divs[x].id.indexOf('login')==0){
			divs[x].style.display = 'none';
		}
		var reaction = document.getElementById('reaction');
		if(reaction){
			reaction.style.display = 'block';
		}
	}
}