var mg3url="";
var ajax_ssi_url = '/includes/ajax_ssi.php';
var ajax_traiter = '/traiter/';
/**
* Default function.  Usually would be overriden by the component
*/
function submitbutton(pressbutton) {
	submitform(pressbutton);
}

/**
* Submit the admin form
*/
function submitform(pressbutton){
	try {
		document.adminForm.onsubmit();
		}
	catch(e){}
	document.adminForm.submit();
}

function sendlink(){
	var name=document.sendlinkform.name.value;
	var sender=document.sendlinkform.senderemail.value;
	var receiver=document.sendlinkform.receiveremail.value;
	var subject=document.sendlinkform.subject.value;
	var link=document.sendlinkform.link.value;

	if(name== "")
		alert("Merci d'indiquer votre nom");
	else{
		if(sender == "")
			alert("Merci d'indiquer votre email");
		else{
			if(receiver == "")
				alert("Merci d'indiquer l'email du destinataire");
			else{
				if(subject == "")
					alert("Merci d'indiquer un sujet pour l'email");
				else{
					$('submitlink').disable();
					var url = mg3url+'/?page=processdata&task=sendlink&name='+name+'&sender='+sender+'&receiver='+receiver+'&subject='+subject+'&link='+encodeURIComponent(link);
					new Ajax.Request(url, {
					  method: 'get',
					  onSuccess: function(transport) {
					    var notice = $('sendlinknotice');
					    if (transport.responseText.match("erreur"))
					      notice.update('Il y a eu une erreur, merci de réessayer plus tard.').setStyle({ background: '#fdd', color: 'red' });
					    else{
					      notice.update('L\'email a bien été envoyé. vous pouvez fermer le module.').setStyle({ background: '#dfd', color: 'red' });
								$('submitlink').enable();	
							}
					  }
					});
					
				}
			}
		}
	}
	return false;
}

function checkarticle(){
	var title=document.formnewarticle.title.value;
	var category=document.formnewarticle.references.selectedIndex;
	var intro= FCKeditorAPI.GetInstance('EditorIntro');
	var alias=document.formnewarticle.alias.value;
	var publish_date=document.formnewarticle.publish_date.value;
	var metadesc=document.formnewarticle.metadesc.value;
	var metakey=document.formnewarticle.metakey.value;

	if(title== "")
		alert("Merci de choisir un titre pour cet article");
	else{
		if(category == "")
			alert("Merci de selectionner une catégorie dans la liste déroulante");
		else{
			if(intro.IsDirty() == "")
				alert("Le texte d'introduction doit avoir du contenu.");
			else{
				if(alias == "")
					alert("Vous devez choisir un alias d'auteur pour cet article.");
				else{
					if(publish_date == "")
						alert("Merci de choisir une date de publication");
					else{
						if(metadesc == "")
							alert("Merci de remplir la meta-description");
						else{
							if(metakey == "")
								alert("Merci de remplir les meta-keys (mots clés)");
							else
								return true;
						}
					}
				}
			}
		}
	}
	return false;
}

function displayMsg(elt, title, msg){
	elt.update('<h3>'+title+'</h3>\n'+msg).setStyle({ background: '#dfd', color: 'red' });
}

function setloading(elt){
	elt.innerHTML = elt.innerHTML+
	"&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp"+
	"<img src='/template/images/loading.gif' alt='loading' title='loading' />";
}

/***************************
           Identification
***************************/

function get_login_form(){
	var form=
	'<form id="formlogin" onsubmit="return try_login();">'+
	'<label for="user">Identifiant:</label>'+
	'<input id="user" name="user" size="9" value="" type="text"><br/>'+
	'<label for="passwrd">Mot de passe:</label>'+
	'<input name="passwrd" id="passwrd" size="9" type="password">'+
	'<input name="cookielength" value="43200" type="hidden">'+
	'<input value="Identifiez-vous" class="button" type="submit">'+
	'</form>'+
	'<br/><a href="/forum/index.php?action=reminder" class="orange" rel="gb_page_fs[]">Mot de passe oublié&nbsp;?</a><br/>'+
	'Pas encore de compte&nbsp;? <a href="/forum/index.php?action=register" class="orange" title="Inscription MythesGrecs.com" rel="gb_page_fs[]"> Enregistrez-vous !</a>';
	
	return form;
}

function get_logout_form(){
	var memberName = "";
	new Ajax.Request(ajax_ssi_url, {
		method: 'get',
		asynchronous: false,
		parameters: $H({action: 'session', item: 'user', item2: 'memberName'}),
		onSuccess: function(transport) {
			memberName=transport.responseText;
		}
	});
	
	var form=
	"Bonjour "+memberName+
	"<form onSubmit='return logout();'>"+
	"<input class='button' type='submit' value='Déconnexion' />"+
	"</form>"+
	"<table width='100%' border='0' cellpadding='0' cellspacing='0'>"+
	"<tr align='left'>"+
		"<td>"+
			"<a href='/forum/index.php?action=profile' rel='gb_page_fs[]' class='mainlevel' >Votre profil</a>"+
		"</td>"+
	"</tr>"+
	"<tr align='left'>"+
		"<td>"+
			"<a href='/ecrire-nouvel-article/' class='mainlevel' >Soumettre un article</a>"+
		"</td>"+
	"</tr>"+
	"<tr align='left'>"+
		"<td>"+
			"<a href='/mes-articles/' class='mainlevel' >Vérifier vos articles</a>"+
		"</td>"+
	"</tr>"+
"</table>";

	return form;
}

function logout(){
	var notice = $('identification');
	new Ajax.Request(ajax_ssi_url, {
		method: 'get',
		asynchronous: true,
		parameters: $H({action: 'session', item: 'rand_code'}),
		onLoading: function(){
			notice.update("<h4>Deconnexion en cours...<h4>");
			setloading(notice);
		},
		onSuccess: function(transport) {
			var session=transport.responseText;
			var url = '/forum/index.php?action=logout;sesc='+session.strip();
			
			new Ajax.Request(url, {
				onSuccess: function(transport) {
					notice.update(get_login_form());
				}
			});
		}
	});
	return false;
}

function try_login(){
	var notice = $('identification');
	new Ajax.Request("/forum/index.php?action=login2", {
		method: 'post',
		asynchronous: true,
		parameters: $H({user: $('formlogin').user.value, passwrd: $('formlogin').passwrd.value, cookielength: $('formlogin').user.cookielength}),
		onLoading: function(){
			notice.update("<h4>Connexion en cours...<h4>");
			setloading(notice);
		},
		onSuccess: function(transport) {
			notice.update(get_logout_form());
		},
		onFailure: function(transport) {
			notice.update(get_login_form());
		}
	});
	return false;
}


/**********************
		Rating
**********************/

function add_rating(form){
	var radio=form.user_rating;
	var id_article=form.id_article.value;
	
	for (var i=0; i<radio.length;i++) {
		if (radio[i].checked) {
			//alert("rate = "+radio[i].value +" for "+id_article)
			
			var user_rating_notice = $('user_rating_notice');
			
			new Ajax.Request(ajax_traiter, {
				method: 'get',
				asynchronous: false,
				parameters: $H({task: 'rating', rating: radio[i].value, id: id_article}),
				onLoading: function(){
					user_rating_notice.update("<h4>Enregistrement de votre vote...</h4>");
					setloading(user_rating_notice);
				},
				onSuccess: function(transport) {
					if (transport.responseText.match("Erreur"))
						user_rating_notice.update("<h4>Il y a eu une erreur pendant l'enregistrement de votre vote. Peut-être avez vous déja voté pour cet article il y a moins de 24h. Réessayez ultérieurement.</h4>");
					else{
						user_rating_notice.update("<h4>Votre vote a été pris en compte, merci!</h4>");
					}
				},
				onFailure: function(transport) {
					user_rating_notice.update("<h4>Il y a eu une erreur pendant l'enregistrement de votre vote. Réessayez ultérieurement.</h4>");
				}
			});
		}
	}
	return false;
}



/**********************
		Intitialisations
**********************/



sfHover = function() {
	var sfEls = document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}

if (window.attachEvent) window.attachEvent("onload", sfHover);


			

function init_identification_module(){
	var notice = $('identification');
	
	new Ajax.Request(ajax_ssi_url, {
		method: 'get',
		asynchronous: true,
		parameters: $H({action: 'login'}),
		onLoading: function(){
			notice.update("<h4>Identification en cours...<h4>");
			setloading(notice);
		},
		onSuccess: function(transport) {
			if (transport.responseText.match("Identifiant"))
				notice.update(get_login_form());
			else
				notice.update(get_logout_form());
		}
	});
}

/**********************
		check functions
**********************/
function checkAgree(){
	if ($('regagree').checked)
		$('regSubmit').enable();
	else
		$('regSubmit').enable();
}

function check_empty_value(id){
	var elt=$(id);
	
	if(elt.value == "")
		elt.setStyle({ backgroundColor: '#FFD5BF', border: "red 1px solid" });
}



/*********************
           Cookies
*********************/

/* function setCookie(nom, valeur)
{
	var argv=setCookie.arguments;
	var argc=setCookie.arguments.length;
	var expires=(argc > 2) ? argv[2] : null;
	var path=(argc > 3) ? argv[3] : null;
	var domain=(argc > 4) ? argv[4] : null;
	var secure=(argc > 5) ? argv[5] : false;
	document.cookie=nom+"="+escape(valeur)+
	((expires==null) ? "" : ("; expires="+expires.toGMTString()))+
	((path==null) ? "" : ("; path="+path))+
	((domain==null) ? "" : ("; domain="+domain))+
	((secure==true) ? "; secure" : "");
}

function getCookieVal(offset){
	var endstr=document.cookie.indexOf (";", offset);
	if (endstr==-1) 
		endstr=document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

function readCookie(nom){
	var arg=nom+"=";
	var alen=arg.length;
	var clen=document.cookie.length;
	var i=0;
	while (i<clen){
		var j=i+alen;
		if (document.cookie.substring(i, j)==arg) return getCookieVal(j);
		i=document.cookie.indexOf(" ",i)+1;
		if (i==0) break;
	}
	return null;
} */


function getCookie (name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg)
			return getCookieVal (j);
	i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break; 
	}
	return null;
}

function setCookie (name,value,expires,path,domain,secure) {
	document.cookie = name + "=" + escape (value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
}

function hashLoginPassword(doForm, cur_session_id)
{
 // Compatibility.
 if (cur_session_id == null)
 cur_session_id = smf_session_id;

 if (typeof(hex_sha1) == "undefined")
 return;
 // Are they using an email address?
 if (doForm.user.value.indexOf("@") != -1)
 return;

 // Unless the browser is Opera, the password will not save properly.
 if (typeof(window.opera) == "undefined")
 doForm.passwrd.autocomplete = "off";

 doForm.hash_passwrd.value = hex_sha1(hex_sha1(doForm.user.value.php_to8bit().php_strtolower() + doForm.passwrd.value.php_to8bit()) + cur_session_id);

 // It looks nicer to fill it with asterisks, but Firefox will try to save that.
 if (navigator.userAgent.indexOf("Firefox/") != -1)
 doForm.passwrd.value = "";
 else
 doForm.passwrd.value = doForm.passwrd.value.replace(/./g, "*");
}
