/* AUTHENTIFICATION FUNCTIONS */

var recover_pwd = function(){
	var query_string = form2query('authentification')+'&ajax=1';
	var options      = {'method':'post','mime':'plain'};
	var show_auth = function (e) {
		$('authentification').className = '';
		if (e.status === 200) {
			var pw = $('auth_passwd'), lg = $('auth_lg'), tr = $('text-recovery'), email = $('auth_email'), tc = $('text-connect'); 
			var str = (/OK/i.test(e.responseText)) ? cs.wording.auth.pwd_ok : cs.wording.auth.pwd_ko + '<a href="?module=subscribe" onclick="open_popunder(this); return false">' + cs.wording.auth.register + '<\/a>' + cs.wording.auth.or; 
			if (/OK/i.test(e.responseText)) {
				pw.style.display = '';
				lg.style.display = '';
				tr.style.display = '';
				tc.style.display = 'none';
				email.style.display = 'none';
				$('hidden_action').value = 'authentification';
				$('authentification').onsubmit = auth_check;
				tr.innerHTML = str;
			} else if (/module=subscribe/i.test(e.responseText)) {
				window.location = window.location.pathname + '?' + e.responseText;
			} else {
				tc.innerHTML = str +  '<a href="#" onclick="pwd_recovery_setup(false);">' + cs.wording.auth.connect + '<\/a>'; 
			}
			e = null;
			cs.HR.form = null;
		}
	};
	if (cs.HR.form === null) {
		$('authentification').className = 'ajaxprocessing';
		cs.HR.form = sAjax(window.location.pathname,query_string,show_auth,options);
	}
	return false;
};

var auth_check = function() {
	if(!cs.regex.pseudo.test($('auth_lg').value) || !cs.regex.passwd.test($('auth_passwd').value)){
		alert(cs.errorText.auth);
		$('auth_lg').focus();
		return false;
	}
	return true;
};

//toogle between authentification and password recovery
var pwd_recovery_setup = function(show){
	var pw = $('auth_passwd'), lg = $('auth_lg'), tr = $('text-recovery'), email = $('auth_email'), tc = $('text-connect'); 
	if (show === true) {
		pw.style.display = 'none';
		pw.value = '';
		lg.style.display = 'none';
		lg.value = '';
		tr.style.display = 'none';
		tc.style.display = 'inline';
		email.style.display = 'inline';
		$('hidden_action').value = 'mdp_recovery';
		$('authentification').onsubmit = recover_pwd;
	} else {
		pw.style.display = '';
		lg.style.display = '';
		tr.style.display = '';
		tc.style.display = 'none';
		email.style.display = 'none';
		$('hidden_action').value = 'authentification';
		$('authentification').onsubmit = auth_check;
	}
};

/* PROFIL UPDATE */
var printError = function (el,txt) {
	sp = document.createElement('BR');
	el.parentNode.appendChild(sp);
	p = document.createElement('STRONG');
	p.className = 'error';
	p.innerHTML = txt;
	el.parentNode.appendChild(p);
};

var resetError = function (el){
	var p = getLastElement(el.parentNode), sp = getPreviousElement(p);
	if(p.tagName.toUpperCase() === 'STRONG' && sp.tagName.toUpperCase() === 'BR'){
		removeNode(p);
		removeNode(sp);
	}
};

//update profil infos
var updateProfil = function(event) {
	var f = $('edit_profil'), doSubmit = true, birth = {};
	for (var i = 0, el; el = f.elements[i]; i += 1) {
		switch (el.id) {
			case 'year': 
			case 'month': 
			case 'day': 
				if( el.id === 'year') {
					resetError(el);
				}
				birth[el.id] = parseInt(el.value,10);
				break;
			case 'email':
				resetError(el);
				if (!cs.regex.email.test(el.value)) {
					doSubmit = false;
					printError(el, cs.errorText.email);
				}
				break;
		}
	}
	if (!is_adult(birth['year'] + '-' + birth['month'] + '-' + birth['day'])) { 
		doSubmit = false; 
		printError($('year'), cs.errorText.birthdate); 
	} 
	if (doSubmit === true) {
		sendForm('edit_profil');
	}
	stopEvent(event);
};

//update login infos
var updatePasswd = function(event) {
	var f = $('edit_passwd'), n, o, doSubmit = true;
	for (var i = 0, el; el = f.elements[i]; i += 1) {
		switch(el.id){
			case 'old_passwd':
				resetError(el);
				if (!cs.regex.passwd.test(el.value)) {
					doSubmit = false;
					printError(el, cs.errorText.passwd);
				} else {
					o = el.value;
				}
				break;
			case 'new_passwd':
				resetError(el);
				if (!cs.regex.passwd.test(el.value)) {
					doSubmit = false;
					printError(el,cs.errorText.passwd);
				} else {
					n = el.value;
				}
				break;
		}
	}
	if (doSubmit === true) {
		if (n===o) {
			doSubmit = false;
			printError($('new_passwd'),cs.errorText.update_password);
		} else {
			sendForm('edit_passwd');
		}
	}
	if(event.preventDefault){
		event.preventDefault();
	}
	return false;
};

var unsubscribed = function (event) {
	if (!confirm(cs.wording.unsubscribe)) {
		stopEvent(event);
		return false;
	}
};

var updateGeoip = function () {
	var fieldUpdate, geoip, messageUpdate;
	var updateForm = function () {
		if (cs.HR.form.status == 200) {
			var data = eval(cs.HR.form.responseText);
			fieldUpdate.disabled       = false;
			fieldUpdate.options.length = 0;
			fieldUpdate.options[0]     = new Option(cs.wording.geoip.select_default, '', true, false);
			for (var i=0, j=data.length; i<j; i++) {
				fieldUpdate.options[(i+1)] = new Option(data[i].text, data[i].value, false, false);
			}
			fieldUpdate.parentNode.parentNode.style.display='';
			messageUpdate.innerHTML='';
			cs.HR.form = null;
		}
	};
	return function (event) {
		var o = getEventTarget(event), params = []; 
		geoip = $('geoip_country', 'geoip_reg', 'geoip_dep', 'geoip_city');
		if (geoip.length != 4 || o.value=='') {
			return;
		}
		if (o === geoip[1]) {
			fieldUpdate   = geoip[2];
			messageUpdate = getNextElement(geoip[1].parentNode);
			messageUpdate.innerHTML = cs.wording.geoip.search_dep;
			geoip[2].disabled = true;
			geoip[2].parentNode.parentNode.style.display = 'none';
			geoip[3].disabled = true;
			geoip[3].parentNode.parentNode.style.display = 'none';
		} else if (o === geoip[2]) {
			fieldUpdate   = geoip[3];
			messageUpdate = getNextElement(geoip[2].parentNode);
			messageUpdate.innerHTML = cs.wording.geoip.search_city;
			geoip[3].disabled = true;
			geoip[3].parentNode.parentNode.style.display = 'none';
		}
		params.push('module=ajax');
		params.push('action=geolocation');
		params.push('geofix[c]=' + geoip[0].value);
		params.push('geofix[r]=' + geoip[1].value);
		params.push('geofix[d]=' + ((geoip[2].disabled !== true) ? geoip[2].value : ''));
		qs = params.join('&');
		var options= {'method':'get','encoded':true, 'mime':'plain'};
		cs.HR.form = sAjax(window.location.pathname, qs, updateForm , options);
	}
}();


/* CONTACT FUNCTIONS */

//selectionner les contact
var select_contact_list = function (formId,type) {
	var f = $(formId);
	if (typeof type === 'string' || /^(DEL|BAN|FAV|ALL)$/.test(type)){
		for (var i = 0, j = f.elements.length; i < j; i += 1){
			if (f.elements[i].type === 'checkbox') {
				f.elements[i].checked = (f.elements[i].value===type) ? true : false;
			}
		} 
	}
};

//mettre a jour les contact
var updateContact = function(event) {
	var f = getEventTarget(event), doSubmit = false;
	for (var i = 0, j = f.elements.length; i < j; i++) {
		if (f.elements[i].type === 'checkbox' && f.elements[i].checked === true) {
			doSubmit = true;
			break;
		}
	}
	stopEvent(event);
	if (doSubmit === true) {
		sendForm('update-contact');
	} else {
		var txt = (/member_type=blacklist/.test(cs.qs_storage)) ? cs.errorText.no_block_selected : cs.errorText.no_contact_selected;
		window.alert(txt);
	}
};

var update_contact_list = function() {

	var showResult = function() {
		if (cs.HR.form.status == 200) {
			var l = $('main');
			var ll = l.getElementsByTagName('*');
			var current=[];
			for (var i = 0, o; o = ll[i]; i++){
				if(/ajaxprocessing/i.test(o.className)){
					current.push(o);
				}
			}
			if (current.length === 0) {
				return;
			} else if (current.length > 1) {
				for( var i=0, o; o=current[i]; i++){
					o.className.replace(/ajaxprocessing/,'');	
				}
				return;
			} else {
				var aList= current[0].getElementsByTagName('a');
				var i = /(ADD_CONTACT|BLOCK_CONTACT|DEL_CONTACT|KO)/.exec(cs.HR.form.responseText);
				switch(i[0]){
					case 'ADD_CONTACT':
						aList[0].className = 'added';
						aList[0].onclick = function(){ update_contact_list(this,'DEL'); return false;};
						aList[0].firstChild.nodeValue = cs.wording.delContact;
						aList[1].className = 'block';
						aList[1].onclick = function(){ update_contact_list(this,'BAN'); return false;};
						aList[1].firstChild.nodeValue = cs.wording.blockContact;
						break;
					case 'BLOCK_CONTACT':
						aList[0].className = 'add';
						aList[0].onclick = function(){ update_contact_list(this,'FAV'); return false;};
						aList[0].firstChild.nodeValue = cs.wording.addContact;
						aList[1].className = 'blocked';
						aList[1].onclick = function(){ update_contact_list(this,'DEL'); return false;};
						aList[1].firstChild.nodeValue = cs.wording.deBlockContact;
						break;
					case 'DEL_CONTACT':
						aList[0].className = 'add';
						aList[0].onclick = function(){ update_contact_list(this,'FAV'); return false;};
						aList[0].firstChild.nodeValue = cs.wording.addContact;
						aList[1].className = 'block';
						aList[1].onclick = function(){ update_contact_list(this,'BAN'); return false;};
						aList[1].firstChild.nodeValue = cs.wording.blockContact;
						break;
					case 'KO':
						alert(cs.errorText.update_contact_list);
						break;
				}
				current[0].className = 'contact';
			}
			cs.HR.form = null;
		}
	};

	return function(o,state) {
		var id_contact = parseInt( o.id.substring(4) , 10);
		if (id_contact === 0 || id_contact === cs.id_user || !/^(DEL|FAV|BAN)$/.test(state)) {
			return; //should not happen but let's check for that anyway
		}
		var l=$('main_bottom');
		var ll=l.getElementsByTagName('*');
		for (var i = 0, h; h = ll[i]; i++){
			if(/ajaxprocessing/i.test(h.className)){
				return; //a contact update is already on it's way we don't want to make multiple Ajax action at one given time....
			}
		}
		o.parentNode.className += ' ajaxprocessing';
		var options= {'method':'get','encoded':true, 'mime':'plain'};
		cs.HR.form = sAjax( window.location.pathname, 'module=ajax&action=update_contact_list&id_target=' + id_contact + '&relation_type=' + state, showResult , options);
	};

}();

