function voie(){ //trouve la voie. Fonction utile? Ne pourrait-on pas utiliser un php document_self?
	if (window.location.pathname != "/index.php" && window.location.pathname != "/"){
	return "../";		
	} else { return "";}
}

function limitText(form,valeur) {// limite le nombre de caractères pouvant être entrés dans les champs
	var longueur = form.value.length;
	var compte = form.id+"_compte";
	(longueur > valeur)?form.value = form.value.substring(0,valeur):document.getElementById(compte).innerHTML = valeur - longueur ;
	}//fin function LimitText  
			 
function motsCommuns(str) { //ôte une série de chaînes du titre pour en faire l'url
removelist = ["un", "une", "le", "la", "les", "de", "pour", "a", "est",
                  "dans", "comme", "par", "que", "avec", "des", "t-", "il", "été", "d'", "l'", "t'", "m'","n'", "ne","qu'",
                  "ce", "en", "sur", "sous", "du","à"];
    r = new RegExp('\\b(' + removelist.join('|') + ')\\b', 'gi');
    return str.replace(r, '');
}
	 
function slugify(s) { //ôte les caractères gênants pour transformer le titre en url
	s = motsCommuns(s);
	s = stripVowelAccent(s);
    s = s.replace(/[^-\w\s]/g, '');  // remove unneeded chars
    s = s.replace(/^\s+|\s+$/g, ''); // trim leading/trailing spaces
	s = s.replace(/^\s+|\s+$/g, ''); // trim leading/trailing spaces
    s = s.replace(/[-\s]+/g, '-');   // convert spaces to hyphens
   s = s.toLowerCase();             // convert to lowercase
	if (s.charAt(0) == '-')  { s = s.substring(1);}
	if (s.charAt(s.length - 1) == '-')  { s = s.substring(0,s.length - 1);}
	s = s.replace('--','');
    return s.substring(0, 81);// trim to first num_chars chars
}
	
function stripVowelAccent(str) { //ôte les accents
    var s = str;
    var rExps = [/[\xC0-\xC4]/g, /[\xE0-\xE5]/g,
/[\xC8-\xCB]/g, /[\xE8-\xEB]/g,
/[\xCC-\xCF]/g, /[\xEC-\xEF]/g,
/[\xD2-\xD6]/g, /[\xF2-\xF6]/g,
/[\xD9-\xDC]/g, /[\xF9-\xFC]/g];
    var repChar = ['A', 'a', 'E', 'e', 'I', 'i', 'O', 'o', 'U', 'u'];
    for (var i = 0; i < rExps.length; i++)
        s = s.replace(rExps[i], repChar[i]);
    return s;
}

function url(obj) {// limite le nombre de caractères pouvant être entrés dans les champs
	 if ($("#img_verrou").attr('src') == '../../img/lock_on.png'){
	 var objet = obj.id;
	 } 
	 else  {
	 var objet = "tx_url";
	 }
	 //if (!(obj.id == 'tx_titre' && $('#url').style.display == ""))  {
	   $("#tx_url").attr('value',slugify($("#"+objet+"").val()));
	// }
}

function form_article(mode){ //fait apparaître le formulaire d'entrée d'un article
	$('#cadre_form_breve').hide();
	$('#cadre_form_article').show();
	$('#cadre_form_commun').show();
	$("#bn_article").attr('class','front');
	$("#bn_breve").attr('class','back');
	$("#tx_titre").focus();
	$("#bn_verrou").hover(function(){
			$("#bn_verrou").attr('class','petit_bouton_selec');
		}, function(){
			$("#bn_verrou").removeAttr('class');
		});
	$("#bn_verrou").click(function(){
		if ($("#img_verrou").attr('src') == '../../img/lock_on.png') {
		$("#img_verrou").attr('src','../../img/lock_off.png');
		$("#tx_url").removeAttr("disabled");
		}
		else {
		$("#img_verrou").attr('src','../../img/lock_on.png');
		$("#tx_url").attr('disabled',true);
		}
	});
	
	$("#tx_titre").blur(function(){
			//if ($(this).val() == "") $(this).attr('value','Titre');
	});
	
	if (mode == "modif"){
		$.getJSON(voie()+"console/scripts/getData.php", { id: $('#hn_id').val()}, function(data) { 
				putForm(data.titre, data.url, data.date, data.id, data.categorie,data.texte,data.clef);
				});
	}
}

function putCkeditor(texte){ //crée l'instance personnalisée de ckeditor - fonction appelée par putForm()
	var config =
            {
				filebrowserBrowseUrl : '/console/ckfinder/ckfinder.html',
 	filebrowserImageBrowseUrl : '/console/ckfinder/ckfinder.html?type=Images',
 	filebrowserFlashBrowseUrl : '/console/ckfinder/ckfinder.html?type=Flash',
 	filebrowserUploadUrl : '/console/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
 	filebrowserImageUploadUrl : '/console/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images',
 	filebrowserFlashUploadUrl : '/console/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash',
                    toolbar :
                    [
                        ['Source','-','Save','NewPage','Preview'],
                    ['PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt','-','Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
                    '/',
                    ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
                    ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','CreateDiv'],
                    ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
                    ['Link','Unlink','Anchor'],
                    ['Image','Flash','Table','HorizontalRule','SpecialChar','PageBreak'],
                    ['Styles','Format'],
                    ['Maximize', 'ShowBlocks']              
                    ],skin : 'v2',customConfig : 'console/ckeditor/configperso.js'

			};
	$('#ta_texte').ckeditor(config);
	$('#ta_texte').val(texte);
}

function putForm(titre,url,date,id,categorie,texte,clef){ //insère ce que le script getData a rapporté en données JSON dans le formulaire de modification
	$("#tx_titre").val(titre); // (suite) fonction putForm() appelée par form_article()
				$("#tx_url").val(url);
				$("#date").val(date);
				$("#aj_id").text(id);
				cat_ar = categorie.split(",");
				$.each(cat_ar, function(i, val){
					$("#"+val).attr('checked', true);
					});
				clef_ar = clef.split(",");
				$.each(clef_ar, function(i, val){
									span = $("<span>").text(val),
									a = $("<a>").addClass("remove").attr({
										href: "javascript:",
										title: "Remove " + val
									}).text("x").appendTo(span);
								span.insertBefore("#tx_clef");	//add friend to friend div
						});
				$("#tx_clef").val("").css("top", 2);
				putCkeditor(texte);
}

function loadIframe(id){ //charge l'iframe nécessaire à la transmission d'images de bandeau
	$('#cadre_getImg').html('<iframe src ="http://www.sinomedia.info/console/images.php?modid='+id+'" width="540" height="170" frameborder="0"></iframe>');	
}

function hideForm(){ //cache le formulaire de modification/création d'article ou de brève. Utilisé dans loadForm et dans bn_modifier
	$("#cadre_form_article").hide();
	$('#cadre_form_commun').hide();
	$('#ta_breve_compte').hide();
	$('#bn_fleche_haut').hide();
	//$("#filet_form").hide();
}

function loadForm(){
	hideForm();
	$(function(){//attach autocomplete
						$("#tx_clef").autocomplete({
							source: function(req, add){//define callback to format results
								$.getJSON(voie()+"console/scripts/getHint.php?callback=?", req, function(data) {//pass request to server
									var suggestions = [];		//create array for response objects
									$.each(data, function(i, val){		//process response						
										suggestions.push(val.name);
									});
									add(suggestions);//pass array to callback
								});
							},	
							select: function(e, ui) {	//define select handler			
								var friend = ui.item.value,	//create formatted friend
									span = $("<span>").text(friend),
									a = $("<a>").addClass("remove").attr({
										href: "javascript:",
										title: "Annuler " + friend
									}).text("x").appendTo(span);
								span.insertBefore("#tx_clef");	//add friend to friend div
							},
							change: function() {//define select handler
								$("#tx_clef").val("").css("top", 2);//prevent 'to' field being updated and correct position
							}
						});
						$("#hints").click(function(){	//add click handler to friends div	
							$("#tx_clef").focus();//focus 'to' field
						});	
						$(".remove", document.getElementById("hints")).live("click", function(){//add live handler for clicks on remove links
							
							$(this).parent().remove();	//remove current friend
							if($("#hints span").length === 0) {//correct 'to' field position
								$("#tx_clef").css("top", 0);
							}				
						});				
		});//$(function(){//attach autocomplete
		
		$('#bn_submit').click(function(){
			var cb_ar = [];
			$('#cadre_form_commun :checkbox:checked').each( function()
				{
				 cb_ar.push( this.id );
				 //cb_ar = cb_ar+"";
				});
				var clef_ar = [];
				$('#hints span').each(function(){
				var input =	$(this).text();
				input = input.substring(0, input.length-1);//ôte le x de fin
				clef_ar.push(input);
				});
				cb_ar = cb_ar.join(",");
				clef_ar = clef_ar.join(",");
				if ($('#bn_breve').attr('class') == "front"){
					if ($('#aj_url').html() != "") texte = $('#ta_breve').val()+'<div class="ref_url">'+$('#aj_url').html()+'</div>';
					else texte = $('#ta_breve').val();
					$.post(voie()+"console/scripts/putData.php", { breve:"oui", id: $('#hn_nvid').val(), texte:texte, categorie:cb_ar, clef:clef_ar, date:$('#date').val() }, function(data) { 
					if (data) {
						window.location = voie()+"index.php";
						} //if (data == "ok") 
					});//$.post("console/scripts/login.php",
				} // fin if bn_breve
				else {	
				$.post(voie()+"console/scripts/putData.php", { titre: $('#tx_titre').val(), id: $('#aj_id').text(), url:$('#tx_url').val(), texte:$('#ta_texte').val(), date:$('#date').val(), categorie:cb_ar, clef:clef_ar }, function(data) { 
					if (data) {
						window.location = voie()+data;
					}//if (data == "ok") 
				});//$.post("console/scripts/login.php",
			}// fin else
		});//$('#bn_submit').click(function(){
	
		$("#lb_logout").click(function(){
			logout();
		});
		
	if (window.location.pathname == "/index.php" || window.location.pathname == "/") {
		jQuery("textarea[class*=expand]").TextAreaExpander();
		$("#bn_breve").click(function(){
			$('#cadre_form_article').hide();
			$('#cadre_form_breve').show();
			$('#cadre_form_commun').show();
			$('#ta_breve_compte').show();
			$("#bn_breve").attr('class','front');
			$("#bn_article").attr('class','back');
			$('#bn_fleche_haut').show();
			$("#ta_breve").focus();
		});
		$("#bn_article").click(function(){
			form_article();
			loadIframe("");
		});
		$("#bn_breve").hover(function(){
			if ($("#bn_breve").attr('class') == 'back') $("#bn_breve").attr('class','selec');
		}, function(){
			if ($("#bn_breve").attr('class') == 'selec') $("#bn_breve").attr('class','back');
		});
		$("#bn_article").hover(function(){
			if ($("#bn_article").attr("class") === "back") $("#bn_article").attr('class','selec');
		}, function(){
			if ($("#bn_article").attr('class') == 'selec') $("#bn_article").attr('class','back');
		});
		
		$("#bn_fleche_haut").click(function(){
			loadForm();
			$('#cadre_img').text("");
		});
		$("#ta_breve").click(function(){
			$("#cadre_form_commun").show();
			$('#ta_breve_compte').show();
			$('#bn_fleche_haut').show();
		});
		$("#ta_breve").keyup(function(){// fonction pour extraire un contenu distant
				$("#cadre_form_commun").show();
				$('#ta_breve_compte').show();
				limitText(this,'409');
				var content=$(this).val();
				var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
				var test= content.match(urlRegex);
				var url = test+"";
				if (test == null) 
				$("#aj_url").html("");
				if(test.length>0){
					$("#aj_url").slideDown('show');
					$("#aj_url").html("<img src='../img/link_loader.gif'>");
					$.post(voie()+'console/scripts/getUrl.php', { url: url }, function(data) {
					  $('#aj_url').html(data);
					  });
					} //if(test.length>0)
				return false();
				});//$("#ta_breve").keyup(function()
	}//if (window.location.pathname == "/index.php")
	else {
		$("#filet_form").hide();	
		$("#menu_form").html('<div id="cadre_modif"><span id="bn_modifier" title="Modifier" class="back">Modifier</span> - <span id="bn_del" title="Supprimer" class="back">Supprimer</span></div>');
		$("#bn_modifier").click(function(){
			if ($("#bn_modifier").attr('class') == 'back'){
				$("#bn_modifier").attr('class','front');
				$("#filet_form").show();
				form_article("modif");
				loadIframe($("#hn_id").val());
			} else {
				$("#bn_modifier").attr('class','back');
				hideForm();
				/*$("#filet_form").hide();
				$('#cadre_img').text("");*/
			}
			});
		$("#bn_del").click(function(){
		del_page($("#hn_id").val());
		});
	}//fin else
}	//function loadForm(){

function bouton() { //pour créer un bouton suppression/modification
	
}

function del_page(idmod) {
	if(confirm('Supprimer la page'))
	{
	$.post(voie()+"console/scripts/delData.php", { id: $('#hn_id').val() }, function(data) { 
						alert(data);
						window.location = voie()+"index.php";
						});

	}
}
	
function parseXml(xml)
{
  //find every Tutorial and print the author
  $(xml).find("elt").each(function()
  {   
	  if($(this).find("titre").text() !=""){
		var elm = '<div class="elt_article">';  
	  	elm += '<h1><a href="'+$(this).find("url").text()+'">'+$(this).find("titre").text()+'</a></h1>';
	  	//elm += '<div class="signature">Article de <span class="auteur">'+$(this).find("auteur").text()+'</span></div>';
		 if($(this).find("vignette").text() !=""){ elm += '<img src="'+$(this).find("vignette").text()+'"/>'; }
	  	elm += '<div class="chapeau"><a href="'+$(this).find("url").text()+'">'+$(this).find("texte").text()+'[...]</a></div>';
	  } else {
		var elm = '<div class="elt_breve">'; 
		//elm += '<div class="signature">Brève de <span class="auteur">'+$(this).find("auteur").text()+'</span></div>';
		//elm += '<span class="date">'+$(this).find("date").attr("fr")+'</span>';
		elm += '<a href="'+$(this).find("url").text()+'">'+$(this).find("texte").text()+'('+$(this).find("date").attr("fr")+')</a>';
		elm += '<div class="cadre_comment"></div>';
	  }
	  elm += '</div>';
    $("#content").append(elm);
  });
}
	 
$(document).ready(function() {
	$.get(voie()+"console/scripts/getNewId.php", function(data){
	if(data){
	eval(data);
	}
	else {
	$('#connexion').show();
	$('#accueil').hide();
	}
});
	form_label();
	loadForm();
	if (window.location.pathname == "/index.php"  || window.location.pathname == "/") {
		$.ajax({
    		type: "GET",
   			url: "une.xml",
    		dataType: "xml",
    		success: parseXml
  		});
	}
}); //$(document).ready(function()

	/**
	 * This function, body_onload, is called when the page finishes loading, and
	 * hides any elements that should be hidden and sets a /keyup/ event on the
	 * /tx_clef/ <input> element as well as a /blur/ event to hide /aj_hints/.
	 */

		
		//Event.observe($('tx_clef'), 'keyup', fetchHints, false);
		//$('tx_clef').observe('keyup', fetchHints);
		//Event.observe($('tx_clef'), 'blur', $('aj_hints').hide.bind($('aj_hints')), false);
	//}
	//]]>
function getForm(){
$.get(voie()+"console/scripts/getForm.php", function(form) {
			$("#cadre_form").html(form).slideDown();
			loadForm();
			});//$.get("console/scripts/getForm.php"
}

/*function getImg(){ //fonction obsolète, avant utilisée dans modele.php
$.get("console/scripts/getImg.php", function(form) {
			$("#cadre_img").html(form).slideDown();
			//loadForm();
			});//$.get("console/scripts/getForm.php"
			  $("#cadre_img").html('<iframe src ="console/scripts/getImg.php"></iframe>');
			     *//* $('iframe#myId').load(function() 
    {
        alert(this);
    });
}*/

/*function callIframe(url, callback) {
    $(document.body).append('<IFRAME id="myId" ...>');
    $('iframe#myId').attr('src', url);

    $('iframe#myId').load(function() 
    {
        callback(this);
    });
}*/


function login() { /*la fonction getNewId est maintenant utilisée à la place*/
var login = $("#tx_login").val();
var password = $("#tx_password").val();
if ($("#cb_cookie").val() == "persistant") {
var duree = "persistant";
}
$.post(voie()+"console/scripts/login.php", { login: login, password: password, persistant:duree }, function(data) { 
	if (data) {
		$("#accueil").show();	
		$("#connexion").hide();	
		$(".user").val(data);
		getForm();
		}//if (data == "ok") 
	});//$.post("console/scripts/login.php",
}

function logout() {//détruit la session et le cookie
$.post(voie()+"console/scripts/logout.php", { login: "<?php echo $_SESSION['valid_user']; ?>" }, function(data) { 
	if (data == "ok") {
		$("#cadre_form").html("");
		$("#accueil").hide();	
		$("#connexion").show();	
		}
	});//$.post("console/scripts/login.php",
/*var login = $("#tx_login").val();
var password = $("#tx_password").val();
if ($("#cb_cookie").val() == "persistant") {
var duree = "persistant";
}
$.post("console/scripts/login.php", { login: login, password: password, persistant:duree }, function(data) { 
	if (data == "ok") {
		getForm();
		}//if (data == "ok") 
	});//$.post("console/scripts/login.php",*/
}

function connect(){
	if($("#cadre_login").is(':hidden')){
	$("#cadre_login").show();
	}
	else $("#cadre_login").hide();
}

function form_label(){
	$("#tx_login").focus(function(){
		$('#tx_login').attr('value','');
		//test = $.cookie('login');
		
		
		});
	$("#tx_login").blur(function(){
		//alert($("#tx_login").val());
		if ($.trim($("#tx_login").val()).length == 0) 
		$('#tx_login').attr('value','Identifiant');
		});
	$("#cache_password").click(function(){
		$("#cache_password").hide();
		$("#tx_password").focus();
		});
}

function blurPassword(){
		if ($.trim($("#tx_password").val()).length == 0) {
		$("#cache_password").show();
		}
}
