/*ouvre une fenetre sur le curseur ou centree sur l'ecran*/
function ouvreFenetre(larg, haut,fenetre,e,centre,resizable,scroll){
    return ouvreFenetreUrl('',larg, haut,fenetre,e,centre,resizable,scroll);
}
function ouvreFenetreUrl(url,larg, haut,fenetre,e,centre,resizable,scroll){
    var posx = 0;
    var posy = 0;
	
    if (centre=='O'){
        var y=(screen.height-haut)/2;
        var x=(screen.width-larg)/2;
	
    }else{
		
        //CALCUL position curseur
        var x = (navigator.appName.substring(0,3) == "Net") ? e.pageX+document.body.scrollLeft+window.screenX : event.x+window.screenLeft;
        var y = (navigator.appName.substring(0,3) == "Net") ? e.pageY-document.body.scrollTop+window.screenY  : event.y+window.screenTop;
  		
        y+=100;
        x-=(larg/2);
    }
    // positionnement des options de la fenetre
    var options = "height="+ haut +",width="+ larg+",top="+y+",left="+x;
    options +=",status=no, location=no, toolbar=no,directories=no";
    if (resizable=='O'){
        options+=",resizable=yes";
    }else{
        options+=",resizable=no";
    }
    if (scroll=='N'){
        options+=",scrollbars=no";
    }else{
        options+=",scrollbars=yes";
    }
	
    //creation de la fenetre
    var popup = window.open (url , fenetre, options);
    if (!popup.opener)
        popup.opener = self;
    //positionnement du focus
    if (window.focus)
        popup.focus();
    return popup;
}

/* ouvre une fenetre avec window.js*/
var win;
function openWindow(title,statusInfo,idContent,w,h,e){

    var closable=true;
    var modalWin = false;

    //CALCUL position curseur
    var  leftWin = (navigator.appName.substring(0,3) == "Net") ? e.pageX+document.body.scrollLeft+window.screenX : event.x+window.screenLeft;
    var topWin = (navigator.appName.substring(0,3) == "Net") ? e.pageY-document.body.scrollTop+window.screenY  : event.y+window.screenTop;

    topWin+=100;
    leftWin-=(w/2);
	
    if (win != undefined) {
        win.centered = false;
        win.setSize(w,h);
        win.showCenter(modalWin);
    }else{
        win = new Window({
            className: "dialog",
            width:w,
            height:h,
            zIndex: 100,
            resizable: false,
            title: title,
            draggable:true,
            wiredDrag: true,
            closable:true,
            showEffectOptions: {
                duration: null
            }
            });
        win.setStatusBar(statusInfo);
        win.setLocation(topWin, leftWin);
        
        win.showCenter(modalWin);
        
    }

    win.setContent(idContent,false,false) ;
}

/*place tous les elements du formulaire a la valeur donnee (true ou false*/
function setAllFormValues(form,val){
    for (i=0;i<form.elements.length-1;i++){
        if (form.elements[i].type=='checkbox'){
            form.elements[i].checked=val;
        }
    }
}

//
function checkUncheckAll(field,val){
    for (i = 0; i < field.length; i++){
        if (field[i].type=='checkbox'){
            if (!field[i].disabled)
                field[i].checked = val ;
        }
    }
}


function changeDisplay(hidden){
    var tab = $('tbArbre');
    var disp='none';
    if (!hidden){
        disp='block';
    }
    var lstLignes=tab.getElementsByTagName("div");
    for (var i=0;i<lstLignes.length;i++){
        if (lstLignes[i].getAttribute('cachable')=='true'){
            lstLignes[i].style.display = disp;
        }
    }
}

function stripCote(str){
    return str.replace(/'/g, '\'');
}

function disabledField(lstFields,dFields){    
    var lst = lstFields.split(',');
    var lstDfields=dFields.split(',');
    var elem;
    for (var i=0;i<lst.length;i++){        
        var nameF='field'+lst[i];        
        elem=document.getElementById(nameF);
        alert('name:'+nameF+'-'+lst[i]+'  n:'+elem.nodeName);
        if (lstDfields.indexOf(lst[i])>=0)
            elem.disabled=true;
        else
            elem.disabled=false;
    }
}

/*----------------Verification des doublons creation enseignant externe------*/
var stHtml='\n';

function checkDoublonsEns(nom,prenom){
    var msg='';
    if ((!nom)||(nom=='')) {
        msg+='Veuillez saisir un nom !!\n';
    }
    if ((!prenom)||(prenom=='')) {
        msg+='Veuillez saisir un prenom !!';
    }
    if (!msg=='') {
        alert(msg);
        return;
    }
    var url = 'AjaxActions';
    var pars = 'action=verifDoublons&nom='+nom.toUpperCase()+'&prenom='+prenom.toUpperCase();
    var myAjax = new Ajax.Request( url, {
        method: 'get',
        parameters: pars,
        onComplete: handleDoublons
    } );
}

/*----handle pour creation-----*/
function handleDoublons(xmlEns){        
    /*parse le retour*/
    /* $('debug').value=xmlEns.responseText;*/
    var lstEns = xmlEns.responseXML.getElementsByTagName('enseignant');
    /*si liste vide -> pas de doublons -> continu creation*/
    if ((lstEns!=null)&&(lstEns.length>0)) {
        /*construction de la reponse*/
        var cod_ens='';
        stHtml="  <table border=\"1\" width=\"98%\" cellpadding=\"0\" cellspacing=\"0\">\n"
        +"      <thead><tr class=\"title\"><td align=\"center\" width=\"50\">code ens</td><td>&nbsp;&nbsp;Enseignant</td><td align=\"center\" width=\"50\">cmp grille</td><td align=\"center\" width=\"50\">cmp enseignant</td></tr></thead>\n"
        +"      <tbody>\n";
            
        for (var i = 0; i < lstEns.length; i++) {
            cod_ens=lstEns[i].getElementsByTagName("cod_ens")[0].firstChild.nodeValue;
            stHtml+="       <tr onmouseover = \"this.style.background='#F7F5EE';\" "
            +" onmouseout=\"this.style.background='#FFFFFF';\" "
            +" onclick=\"majOpener("+cod_ens+");\" style=\"cursor:pointer;\"><td align=\"center\" >"
            +cod_ens+"</td>"
            +"<td>&nbsp;"+lstEns[i].getElementsByTagName("nom_ens")[0].firstChild.nodeValue+"</td>"
            +"<td align=\"center\">"+lstEns[i].getElementsByTagName("cod_cmp_gri")[0].firstChild.nodeValue+"</td>"
            +"<td align=\"center\">"+lstEns[i].getElementsByTagName("cod_cmp_ens")[0].firstChild.nodeValue+"</td></tr>\n";
        }
        stHtml+="       </tbody>\n  </table><br>\n";
        var haut=300;
        var larg=510;
        var y=(screen.height-haut)/2;
        var x=(screen.width-larg)/2;
        var options = "height="+haut+",width="+larg+",top="+y+",left="+x;
        options +=",status=no, location=no, toolbar=no,directories=no";
        options+=",resizable=yes";
        options+=",scrollbars=yes";
        //creation de la fenetre
        var msgPage = window.open('checkDoublons.jsp', 'uniprof', options);
        if (!msgPage.opener)
            msgPage.opener = self;
        //positionnement du focus
        if (window.focus)
            msgPage.focus();
        return false;
        msgPage.onload();
    }else{
        $('checkDoublons').value="O";
        document.gestensext.submit();
        return false;
    }
}

function getHtml(){
    return stHtml;
}
/*------------------------FIN CHECK DOUBLONS------------------------------------*/


/*-------------------ProgressBar-------------------*/
var isIE = false;
var req;
var messageHash = -1;
var targetId = -1;
var centerCell;
var size=40;
var increment = 100/size;
var tmpUrlTab=new Array();
var urlTab=new Array();

function pollTaskmaster() {
    var urlLong = urlTab[targetId]+"?messageHash=" + escape(messageHash) + "&targetId=" + targetId;
    initRequest(urlLong);
    req.onreadystatechange = processPollRequest;
    req.send(null);
}

function initRequest(url) {
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        isIE = true;
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    req.open("GET", url, true);
}

function submitTask(url) {
    var urlLong = url+"?action=startTask";
    tmpUrlTab.push(url);
    initRequest(urlLong);
    // set callback function
    req.onreadystatechange = processInitialRequest;
    req.send(null);
}

function processPollRequest() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            var item = req.responseXML.getElementsByTagName("message")[0];
            var message = item.firstChild.nodeValue;
            if (message != "END") {
                var item = req.responseXML.getElementsByTagName("pourcent")[0];
                var message = item.firstChild.nodeValue;
                var occur = req.responseXML.getElementsByTagName("occur")[0];
                var occurValue = occur.firstChild.nodeValue;
                var total = req.responseXML.getElementsByTagName("total")[0];
                var totalValue = total.firstChild.nodeValue;
                showProgress(message,occurValue,totalValue);
            }
            messageHash = message;
        } else {
            window.status = "No Update for " + targetId;
        }
        window.status = "Processing requestId=" + targetId + " value=" + messageHash;    
        if (messageHash != "END") {
            setTimeout("pollTaskmaster()", 1000);
        } else {
            setTimeout("complete('"+targetId+"')", 1000);

        }
    }
}

function complete(targetId) {
    var idivD = window.document.getElementById("progressDynamic");
    idivD.innerHTML = "Complete";
    window.status = "Task Complete";
    window.opener.location.replace(urlTab[targetId]+"?action=getPDF&targetId="+targetId);
    /*var bttn = window.document.getElementById("taskbutton");
    bttn.disabled = false;*/
    setTimeout("window.close()", 1000);
}

// callback function for intial request to schedule a task
function processInitialRequest() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            var item = req.responseXML.getElementsByTagName("message")[0];
            var message = item.firstChild.nodeValue;
            var total = req.responseXML.getElementsByTagName("total")[0];
            var totalValue = total.firstChild.nodeValue;
            // the initial requests gets the targetId
            targetId = message;
            urlTab[targetId]=tmpUrlTab[0];
            tmpUrlTab.shift();
            messageHash = 0;
            window.status = "";
            createProgressBar(totalValue);
            showProgress(0,0,totalValue);
        }        
        // do the initial poll in 2 seconds
        setTimeout("pollTaskmaster()", 1000);
    }
}

// create the progress bar
function createProgressBar(total) {
    var centerCellName;
    var tableText = "";
    var idivS = window.document.getElementById("progressStatic");
    var idivD = window.document.getElementById("progressDynamic");
    if (total>1){
        for (x = 0; x < size; x++) {
            tableText += "<td id=\"progress_" + x + "\" width=\"10\" height=\"10\" bgcolor=\"#FBB100\"/>";
            if (x == (size/2)) {
                centerCellName = "progress_" + x;
            }
        }        
        idivD.innerHTML = "<fieldset>\n   <legend id='titreBar' style=\"font-weight: bold;\">%</legend><table with=\"95%\" border=\"0\" cellspacing=\"1\" cellpadding=\"1\"><tr>" + tableText + "</tr></table>\n</fieldset>";
        centerCell = window.document.getElementById('titreBar');
        idivS.style.visibility='hidden';
        idivD.style.visibility='visible';
    }else{
        idivD.style.visibility='hidden';
        idivS.style.visibility='visible';
    }
}

// show the current percentage
function showProgress(percentage,occur,total) {
    if (total>1){
        var percentageText = "";
        if (percentage < 10) {
            percentageText = "&nbsp;" + percentage;
        } else if (percentage=="END"){
            percentageText = "100";
        } else {
            percentageText = percentage;
        }
        centerCell.innerHTML = percentageText + "% - Fait : "+occur+"/"+total;
        var tableText = "";
        for (x = 0; x < size; x++) {
            var cell = window.document.getElementById("progress_" + x);
            if ((cell) && percentage/x < increment) {
                cell.style.backgroundColor = "#FBB100";
            } else {
                cell.style.backgroundColor = "#D03815";
            }
        }
    }
}
/*-------------------FIN PROGRESS BAR----------------*/
