$(document).ready(function(){
	
	
	
	/*
	 * Changement Statut Etape/sous Etape
	 */
	$(".jsrouge").az_Xstatut({couleur:"rouge",Xpage:ajax_page});
	$(".jsorange").az_Xstatut({couleur:"orange",Xpage:ajax_page});
	$(".jsvert").az_Xstatut({couleur:"vert",Xpage:ajax_page});
	/*
	 * Plier / Déplier : Parcours Porteur
	 */
	$(".fermer").az_plierDeplierPorteur();
	//$(".openall").az_plierDeplierPorteur({type:"tout"});
	$(".js_ttouvrir").az_plierDeplierPorteur({type:"ttouvrir"});
	$(".js_ttfermer").az_plierDeplierPorteur({type:"ttfermer"});
	/*
	 * Plier / Déplier : Utiles
	 */
	 $(".gestionutiles").css("cursor","pointer");
	 $(".gestionutiles").each(function () { // Plie tous au chargement
		num = ( ie )?2:3;
		$(this.parentNode.childNodes[num]).toggle();
	});
	$(".gestionutiles").click(function () {
		num = ( ie )?2:3;
		$(this.parentNode.childNodes[num]).toggle();
		if ( $(this).children('img').attr('src') == "fileadmin/templates/img/plus.png")

			$(this).children('img').attr('src',"fileadmin/templates/img/moins.png");

		else

			$(this).children('img').attr('src',"fileadmin/templates/img/plus.png");
		return false;
	});

	
	
	


	/*
	 * Affectation d'un referent specialiste a une sous etape
	 *//*
	$("span[id*=l2.ssetape]").click(function() {
		num = ( ie )?2:3;
		id = this.parentNode.childNodes[num].value;
		
		$("#creation_parcours_referent_spe").html("");
		$("#creation_parcours_attribuer_me").html("");
		$("#creation_parcours_referent_spe").fadeOut(5);
		
		$.post("index.php?id=33", { az_op: 3, az_id: id }, function(data){
			$("#creation_parcours_referent_spe").html(data);
			$("#creation_parcours_referent_spe").fadeIn("slow");
		});
	});*/
	/*
	 * Autorisation de rerefent sur une sous etape
	 */
	 tid=0;
   tref_gen = 0;
   tref_spe = 0;
	$('.autorisation').az_autoriser();
	$(".ajax_autoriser").click(function() {
		obj = this.parentNode;
		tid=0;
		tref_gen = 0;
		tref_spe = 0;
		inputs = obj.getElementsByTagName('input');
		
		$(obj).find("input[name='ref_gen']").each( function () {
			tref_gen= (!this.checked)?0:this.value;
		});
		
		$(obj).find("input[name='ref_spe']").each( function () {
			tref_spe= (!this.checked)?0:this.value;
		});
		
		$(obj).find("input[name='id']").each( function () {
			tid=this.value;
		});
		//alert(tref_gen+" "+tref_spe+" "+tid);
		
		$(obj.getElementsByTagName('span')[0]).fadeIn(1);
		$(obj.getElementsByTagName('span')[0]).html(ajax_chargement);

		$.post(ajax_page, { az_op: 5, az_id: tid, az_gen: tref_gen, az_spe: tref_spe }, function(data){//alert(data);
			$(obj.getElementsByTagName('span')[0]).fadeOut("slow");
		});
	});
	/*
	 * Upload
	 */
	/*
	 * Tooltips
	 */
	$('.tooltip').az_tooltip();
	$('.show_event').az_tooltip({css_classe:'event_month_cal'});
	$('.alerte').az_tooltip({css_classe:'div_alerte'});


	// From Ref js Ok
	
	
	


	
	    // Mise en forme du formulaire accueil 
    $("input[name='tx_gestionprojet_pi3[name]'],input[name='tx_gestionprojet_pi10[name]'],input[name='tx_gestionprojet_pi3[tx_gestionprojet_nom_jf]'],input[name='tx_gestionprojet_pi10[tx_gestionprojet_nom_jf]']").keyup( function(){
        this.value = this.value.toUpperCase(); 
    });
    $("input[name='tx_gestionprojet_pi3[tx_gestionprojet_prenom]'],input[name='tx_gestionprojet_pi10[tx_gestionprojet_prenom]']").keyup( function(){
        if( this.value != '' )
        {
            tmp = this.value.substr(0,1).toUpperCase();
            tmp += this.value.substr(1).toLowerCase();
            this.value = tmp;
        }
    });

    $("input[name='tx_gestionprojet_pi3[city]'],input[name='tx_gestionprojet_pi10[city]'],input[name='tx_gestionprojet_pi2[search_ville]']").keyup( function(){
        this.value = this.value.toUpperCase(); 
    }).autocomplete(ajax_page,{
            matchContains: true,
            minChars: 0
    });
	
    //ajout fred
	$("input[name='tx_gestionprojet_pi3[telephone]'],input[name='tx_gestionprojet_pi3[tx_gestionprojet_tel_portable]'],input[name='tx_gestionprojet_pi3[tx_gestionprojet_tel_pro]'],input[name='tx_gestionprojet_pi3[fax]']").keyup( function(e){
	if (e.keyCode!=8)
	{
		tmpo = this.value.replace(/ /g,"");
		this.value = wordwrap(tmpo, 2, ' ', true);
	}
    });
    $("input[name='tx_gestionprojet_pi10[tx_gestionprojet_tel_portable]'],input[name='tx_gestionprojet_pi10[tel_pro]'],input[name='tx_gestionprojet_pi10[tx_gestionprojet_tel_pro]'],input[name='tx_gestionprojet_pi10[fax]']").keyup( function(e){
	if (e.keyCode!=8)
	{
		tmpo = this.value.replace(/ /g,"");
		this.value = wordwrap(tmpo, 2, ' ', true);
	}
    });

    $("#pacc_b").click( function () {
	$("#pacc_c").toggle("slow");
	this.value = ( this.value=="Ouvrir" )?"Fermer":"Ouvrir";
    });
    
    
    $('.date-pick').datePicker({startDate:'01/01/1996'})
    $('#start-date').bind(
            'dpClosed',
            function(e, selectedDates)
            {
                    var d = selectedDates[0];
                    if (d) {
                            d = new Date(d);
                            $('#end-date').dpSetStartDate(d.addDays(1).asString());
                    }
            }
    );
    $('#end-date').bind(
            'dpClosed',
            function(e, selectedDates)
            {
                    var d = selectedDates[0];
                    if (d) {
                            d = new Date(d);
                            $('#start-date').dpSetEndDate(d.addDays(-1).asString());
                    }
            }
    );
$("input[name='tx_gestionprojet_pi11[diagnostique_date]']:visible").datePicker({startDate:'01/01/1996'});
    $(".az_toolTips").az_toolTips();

		
$("input[name='tx_gestionprojet_pi3[accueil_date]']:visible").datePicker({startDate:'01/01/1996'});
	// From Ref js test
	

	ie=document.all;
	trouve = 0;
	 obj = '';

	function insererAuDebut(de,quoi) {
		$(quoi).clone(true).appendTo(de);
// append
	}
	function insererApres(de,quoi) {
		$(quoi).clone(true).insertAfter(de);
// insertAfter	
	}
	function insererAvantTout(de,quoi) {
// prepend
		$(quoi).clone(true).prependTo(de);
	}
	function cherchePlace(depart,destination,liste,etape,ssetape) {
		obj = '';
		trouve = 0;
		
		if( ssetape == -1 )
		{
			$("#liste"+destination+" span[id^=l"+destination+".etape]").each(function(i){
				/*if( !obj )
					obj = this.parentNode.parentNode;*/
				tmp_id = this.id.split('.');
				if( parseInt(tmp_id[2]) < parseInt(this_id_etape) )
				{
					trouve = 1;
					obj=this.parentNode;
				}						
			});
			
			if( !obj )
			{
				obj = $("#liste"+destination+" ul:first-child");
			}
		}
		else
		{
			$("#liste"+destination+" span[id^=l"+destination+".ssetape."+etape+".]").each(function(i){
				if( !obj )
					obj = this.parentNode.parentNode;
				tmp_id = this.id.split('.');
				//On test si la sous ÃƒÂ©tape de la liste de destination est aprÃƒÂ¨s la sous ÃƒÂ©tape en cours
				if( parseInt(tmp_id[3]) < parseInt(ssetape) )
				{
					// Si oui, elle servira de rÃƒÂ©ference tant qu'on aura pas trouver de sous ÃƒÂ©tape supÃƒÂ©rieur Ãƒ  elle et infÃƒÂ©rieur Ãƒ  notre sous ÃƒÂ©tape en cours
					obj = this.parentNode;
					// On marque trouvÃƒÂ© pour dÃƒÂ©finir la mÃƒÂ©thode Ãƒ  utiliser
					trouve = 1;
				}
			});
			
			
		}

		
		return obj;
	}
	function insererSousEtape(choix,depart,destination,this_id_liste,this_id_etape,this_id_ssetape) {
			
		obj = cherchePlace(depart,destination,this_id_liste,this_id_etape,this_id_ssetape);	
					
		if( trouve )
			insererApres(obj,choix);
		else
			insererAvantTout(obj,choix);
	}
	var tmpObjHighLight
	function renommeId() {
		tmpObjHighLight = new Array();
		// Renomme les id comme il faut (doublons, pas bien !! ;=) )
		$("#liste2 span[id^=l1]").each(function(i){
			tmp_id = this.id.split('.');
			if( tmp_id[1] == 'etape' )
				this.id = 'l2.'+tmp_id[1]+'.'+tmp_id[2];
			else
				this.id = 'l2.'+tmp_id[1]+'.'+tmp_id[2]+'.'+tmp_id[3];
			tmpObjHighLight[tmpObjHighLight.length] = this
		});
		
		$("#liste1 span[id^=l2]").each(function(i){
			tmp_id = this.id.split('.');
			if( tmp_id[1] == 'etape' )
				this.id = 'l1.'+tmp_id[1]+'.'+tmp_id[2];
			else
				this.id = 'l1.'+tmp_id[1]+'.'+tmp_id[2]+'.'+tmp_id[3];
			
			$(this.parentNode).css({"background-color":"white"})
		});
		
		for(i=0;i<tmpObjHighLight.length;i++)
		{
			$(tmpObjHighLight[i].parentNode).css({"background-color":"red","opacity":0.1})
							.animate({opacity: 1}, 800, "",function (){
								$(this).css({"background-color":"white"});
							});
		}
	}

	$("span[id*=etape]").addClass("selectionable");
	
	$("span[id*=etape]").dblclick(function() {
		// Tweak pour enlever la selection du texte lors du double clique
		tmp = this.innerHTML;
		this.innerHTML = tmp;
		
		// On split l'id de l'ÃƒÂ©lement sÃƒÂ©lÃƒÂ©ctionnÃƒÂ© pour rÃƒÂ©cupÃƒÂ©rer les informations de base sur celui-ci
		did = this.id;
		id = did.split('.');
		this_id_liste = id[0];
		this_id_type = id[1];
		this_id_etape = id[2];
		this_id_ssetape = (  id[3] )? id[3]:-1;
		
		depart = ( id[0] ==  'l1' )?'1':'2';
		destination = ( id[0] ==  'l1' )?'2':'1';
		
		// Si l'objet est un ÃƒÂ©tape
		if( this_id_type == 'etape' )
		{
			// On vÃƒÂ©rifie si l'ÃƒÂ©tape existe dans la liste de destination
			trouve = 0;
			$("#liste"+destination+" span[id='l"+destination+".etape."+this_id_etape+"']").each(function(i){
					trouve++;
			});
			
			// Si l'ÃƒÂ©tape existe, on ne la recopie pas, on prend uniquement ces ÃƒÂ©lÃƒÂ©ments restant dans la liste 1
			if( trouve )
			{
				// Pour chaque sous ÃƒÂ©tape correpondantes Ãƒ  l'ÃƒÂ©tape en cours dans la liste 1 ...
				$("#liste"+depart+" span[id^=l"+depart+".ssetape."+this_id_etape+"]").each(function(i){
					// On rÃƒÂ©cupÃƒÂ©re le tableau de l'id de la sous-ÃƒÂ©tape trouvÃƒÂ©e
					ptmp_id = this.id.split('.');
					
					insererSousEtape(this.parentNode,depart,destination,ptmp_id[0],ptmp_id[2],ptmp_id[3]);							
				});
			}
			// Sinon on copie tout le DOM
			else
			{
				obj = cherchePlace(depart,destination,this_id_liste,this_id_etape,this_id_ssetape);	
				
				if( trouve )
					insererApres(obj,this.parentNode);
				else
					insererAvantTout(obj,this.parentNode);
			}
			
			// On supprime l'ÃƒÂ©tape copiÃƒÂ©e
			$(this.parentNode).remove();
			
		}
		else
		{
			// VÃƒÂ©rifie si il faut dÃƒÂ©placer l'ÃƒÂ©tape ou si elle existe dÃƒÂ©jÃƒ !
			trouve = 0;
			$("#liste"+destination+" span[id=l"+destination+".etape."+id[2]+"]").each(function(i){
				trouve++;									
			});
			
			if( trouve )
			{
				insererSousEtape(this.parentNode,depart,destination,this_id_liste,this_id_etape,this_id_ssetape);					
			}
			else
			{
				obj = cherchePlace(depart,destination,this_id_liste,this_id_etape,-1);	
				
				if( trouve )
					insererApres(obj,this.parentNode.parentNode.parentNode);
				else
					insererAvantTout(obj,this.parentNode.parentNode.parentNode);
				
				
				// On supprime les sous ÃƒÂ©tapes clonÃƒÂ©es en trop
				$("#liste"+destination+" span[id^=l"+depart+".ssetape.]").each(function(i){
					tmp_id = this.id.split('.');
					if( tmp_id[3] != id[3] )
						$(this.parentNode).remove();									
				});
			}
			$(this.parentNode).remove();
			// On test si l'etape n'est pas vide :)
			trouve = 0;
			$("#liste"+depart+" span[id^=l"+depart+".ssetape."+id[2]+".]").each(function(i){
				trouve++;
			});
			
			if( !trouve )
			{
				$("#liste"+depart+" span[id=l"+depart+".etape."+id[2]+"]").each(function(i){
					$(this.parentNode).remove();							
				});
			}
			
		}
		
		
		renommeId();
	});
        
	$(".etapenv1").click( function(){
		obj = $(this.parentNode).find('ul').css('display');
		
		$(this).toggleClass("etapenv1_fermer");

		/*if( obj.css('display') == 'block' )
		{
			
		}*/
		
		$(this.parentNode).find('ul').toggle();
		/*if( $(this.parentNode).find('ul').css('display'))
		alert($(this.parentNode).find('ul').css('display'));*/
	});
        
        
        
        
    /*
     * Affectation d'un referent specialiste a une sous etape
     */
  /*  $("span[id*=l2.ssetape]").click(function() {
            num = ( ie )?2:3;
            id = this.parentNode.childNodes[num].value;
            
            $("#creation_parcours_referent_spe").html("");
            $("#creation_parcours_attribuer_me").html("");
            $("#creation_parcours_referent_spe").fadeOut(5);
            
            $.post("index.php?id=33", { az_op: 3, az_id: id }, function(data){
                    $("#creation_parcours_referent_spe").html(data);
                    $("#creation_parcours_referent_spe").fadeIn("slow");
            });
    });*/
    
    
    $(".alerte").click(function() {
            obj = this;


            tid = this.parentNode.parentNode.parentNode.parentNode.parentNode.id;
  	
            $.post(ajax_page, { az_op: 7, az_id: tid}, function(data){
                //alert(data);
                obj.src="fileadmin/templates/img/etapwarningoff.gif";
            });
    });


	// Fin
});



/*
 * Initiation des variables globales
 */
ie=document.all; // Grrrr !
obj = '';
x = 0;
y = 0;
ajax_page = "index.php?id=33";
ajax_chargement = '<img src="fileadmin/templates/img/ajax.gif" />';
message_1 = "Veuillez selectionner un referent avant de valider.";
message_2 = "Affectation reussie!";
message_3 = "Envoi en cours";
message_4 = "Envoyer votre fichier";

/*
 * Affectation d'un referent specialiste a une sous etape
 */
function save_ref_spe() {
	id = $("#creation_parcours_attribuer_id").attr("value");
	val = $("#creation_parcours_attribuer_va").attr("value");
	
	$("#creation_parcours_attribuer_me").html("");
	
	$("#creation_parcours_attribuer_me").fadeOut(5, function () {
		if( val ) {		
			$.post(ajax_page, { az_op: 4, az_id: id, az_val: val }, function(data){
				$("#creation_parcours_attribuer_me").html(message_2);
				$("#creation_parcours_attribuer_me").fadeIn("slow");
			});
		}
		else {
			$("#creation_parcours_attribuer_me").html(message_1);
			$("#creation_parcours_attribuer_me").fadeIn("slow");
		}
	});
}







//ajout fred
function wordwrap( str, int_width, str_break, cut ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Nick Callen
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Sakimori
    // *     example 1: wordwrap('Kevin van Zonneveld', 6, '|', true);
    // *     returns 1: 'Kevin |van |Zonnev|eld'
    // *     example 2: wordwrap('The quick brown fox jumped over the lazy dog.', 20, '<br />\n');
    // *     returns 2: 'The quick brown fox <br />\njumped over the lazy<br />\n dog.'
    // *     example 3: wordwrap('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.');
    // *     returns 3: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod \ntempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim \nveniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea \ncommodo consequat.'
 
    // PHP Defaults
    var m = ((arguments.length >= 2) ? arguments[1] : 75   );
    var b = ((arguments.length >= 3) ? arguments[2] : "\n" );
    var c = ((arguments.length >= 4) ? arguments[3] : false);
 
    var i, j, l, s, r;
 
    str += '';
 
    if (m < 1) {
        return str;
    }
 
    for (i = -1, l = (r = str.split("\n")).length; ++i < l; r[i] += s) {
        for(s = r[i], r[i] = ""; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j)).length ? b : "")){
            j = c == 2 || (j = s.slice(0, m + 1).match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length || c == 1 && m || j.input.length + (j = s.slice(m).match(/^\S*/)).input.length;
        }
    }
 
    return r.join("\n");
}

function js_autoriser_change(obj)
{
    id = obj.id;
    num = id.split('_');
    num = num[num.length-1];
    document.getElementById('js_autoriser_submit_'+num).disabled = false;
}
function js_autoriser_envoie(obj)
{
    id = obj.id;
    num = id.split('_');
    num = num[num.length-1];
    val = document.getElementById('js_autoriser_select_'+num).value;
    last = document.getElementById('js_autoriser_last_'+num).value;
    
    $.post(ajax_page, { az_op: 8, az_etape: num, az_ref_spe: val, az_last: last }, function(data){
        document.getElementById('js_autoriser_last_'+num).value = val;
        document.getElementById('js_autoriser_submit_'+num).disabled = true;//alert(data);
    });

}

/*var isIE = document.all;
var mouseX = 0;
var mouseY = 0;
function getMouseXY(e)
{
    if (!e) e = window.event;	
    if (e)
    {
        mouseX = isIE ? (e.clientX + document.body.scrollLeft) : e.pageX;
        mouseY = isIE ? (e.clientY + document.body.scrollTop) : e.pageY;
    }
}
document.onmousemove = getMouseXY;*/


var mouseX = 0
var mouseY = 0
 
var browser=navigator.appName;
var IE=true;
 
if (browser!="Microsoft Internet Explorer") {
		document.captureEvents(Event.MOUSEMOVE);
		IE=false;
	}
 
document.onmousemove = getMouseXY;
 
function getMouseXY(e) {
  if (IE) {
    mouseX = event.clientX + document.body.scrollLeft
    mouseY = event.clientY + document.documentElement.scrollTop;
	mouseY = mouseY-20;
  } else {
    mouseX = e.pageX
    mouseY = e.pageY
  }
  if (mouseX < 0){mouseX = 0}
  if (mouseY < 0){mouseY = 0}  
 
  return true
}

function view_user(id)
{
    obj = document.getElementById('view_user_'+id);
	
    obj.style.top = mouseY +7+"px";
    obj.style.left = mouseX +7+"px";
    obj.style.display='block';
}
