<commit_before>
/* à intégrer dans chaque jeu
var modeDifficulty = 1; //0 pour adaptation de la difficulté en fonction win/fail, 1 pour courbe bonds

function changeMetaDiff() {
    if (modeDifficulty === 0) {
        // reprendre code actuel fonctionnement diff

    } else if (modeDifficulty === 1 && modeTest === true) {
        // reprendre code actuel fonctionnement diff

    } else if (modeDifficulty === 1 && modeTest === false) {
        // envoyer vers contenu de courbeDiff.js
        selectbondDiff();
        difficulty = newDiff;
    }
    console.log("difficulté du jeu:" + difficulty);
}
*/

// conserver le nombre de tours gagnants d'affilé
var lastWinFail = [];
var cumulWin = [];
var cumulFail = [];

var firstBondDiff = false; //false : premier bond de difficulté non sélectionné ; true, premier bond sélectionné

var bondDiffLittle = 0.1;
var bondDiffMedium = 0.3;
var bondDiffHigh = 0.6;
var bondDiffActual = 0;

var bondDiffNoLittle = [0.3, 0.6];
var bondDiffNoMedium = [0.1, 0.6];
var bondDiffNoHigh = [0.3, 0.6];
var bondDiffAll = [0.1, 0.3, 0.6];

var newDiff = 0;
var bondDiff = 0;

var compareArrayWin = 0;
var compareArrayFail = 0;

var compteurTours = 0; //compteur qui augmente après chaque tour
var toursBeforeChange = 2; //nbre de tours avant changement de comportement de la courbe de difficulté

//générer aléatoirement premier bond de difficulté après la fin des tours de chauffe
function selectFirstBondDiff() {
    if (modeTest === false && firstBondDiff === false) {
        bondDiffActual = bondDiffAll[Math.floor(bondDiffAll.length * Math.random())];

        bondDiff = bondDiffActual;
        newDiff = bondDiff;

        firstBondDiff = true;
        console.log("premier bond de difficulté: " + bondDiff);
    }
}

function selectbondDiff() {
    if (modeTest === false && firstBondDiff === true) {
        if (bondDiffActual === bondDiffLittle) {
            bondDiff = bondDiffNoLittle[Math.floor(bondDiffNoLittle.length * Math.random())];
        } else if (bondDiffActual === bondDiffMedium) {
            bondDiff = bondDiffNoMedium[Math.floor(bondDiffNoMedium.length * Math.random())];
        } else if (bondDiffActual === bondDiffHigh) {
            bondDiff = bondDiffNoHigh[Math.floor(bondDiffNoHigh.length * Math.random())];
        }
        console.log("nouveau bond de difficulté: " + bondDiff);

        changeDifficulty();
    }
    selectFirstBondDiff();

}

function changeDifficulty() {
    var array = [0, 1];
    var addOrSub = array[Math.floor(array.length * Math.random())];
    console.log("progression de la difficulté: " + addOrSub);

    if (addOrSub === 0) { //changement de difficulté par soustraction
        newDiff = difficulty - bondDiff;
        console.log("newDiff = " + newDiff);

        if (newDiff < 0) {
            newDiff = 0;
            console.log("newDiff corrected = " + newDiff);
        }
    } else if (addOrSub === 1) { //changement de difficulté par addition
        newDiff = difficulty + bondDiff;
        console.log("newDiff = " + newDiff);

        if (newDiff >= 1) {
            newDiff = 1;
            console.log("newDiff corrected = " + newDiff);
        }
    }

}

/*function cumulTours() {
    if (winState === true) {
        lastWinFail.push("true");
        compteurTours++;

        console.log("dernier win:" + lastWinFail)

    } else if (winState === false) {
        lastWinFail.push("fail");
        compteurTours++;

        console.log("dernier fail:" + lastWinFail)

    }

    checkWinFail();
}

function clearArray() {
    if (compteurTours === toursBeforeChange) {
        lastWinFail = [];
        compteurTours = 0;
    }
}

function checkWinFail() {
    var idx = lastWinFail.indexOf("true");
    while (idx != -1) {
        cumulWin.push("true");
        idx = lastWinFail.indexOf("true", idx + 1);
    }
    console.log("cumul des win:" + cumulWin);

    var idx2 = lastWinFail.indexOf("fail");
    while (idx2 != -1) {
        cumulFail.push("fail");
        idx2 = lastWinFail.indexOf("fail", idx2 + 1);
    }
    console.log("cumul des fail:" + cumulFail);

    behaviorDiff();
}

//comparer les tableaux pour vérifier la présence de trois win
compareArrayWin = function (lastWinFail, cumulWin) {
    if (lastWinFail.length !== cumulWin.length) {
        return false;
    } else if (lastWinFail.length === cumulWin.length) {
        for (var i = 0; i < lastWinFail.length; i++) {
            if (lastWinFail[i] !== cumulWin[i]) {
                return false;
            }
        }
    console.log("coucou1");
    return true;
    }
};

//comparer les tableaux pour vérifier la présence de trois fail
compareArrayFail = function (lastWinFail, cumulFail) {
    if (lastWinFail.length !== cumulFail.length) {
        return false;
    } else if (lastWinFail.length === cumulFail.length) {
        for (var i = 0; i < lastWinFail.length; i++) {
            if (lastWinFail[i] !== cumulFail[i]) {
                return true;
            }
        }
    console.log("coucou2");
    return true;
    }
};

function behaviorDiff() {
    if (compareArrayWin(lastWinFail, cumulWin) === true && compteurTours === toursBeforeChange) {
        var tailleBondDiff = bondDiff[Math.floor(bondDiff.length * Math.random())];
        console.log("taille du bond de difficulté win" + tailleBondDiff);
        newDiff = difficulty + tailleBondDiff;
        console.log("newDiff = " + newDiff);

        if (newDiff >= 1) {
            newDiff = 1;
            //difficulty = newDiff;
        }

    } else if (compareArrayFail(lastWinFail, cumulFail) === true && compteurTours === toursBeforeChange) {
        var tailleBondDiff = bondDiff[Math.floor(bondDiff.length * Math.random())];
        console.log("taille du bond de difficulté fail" + tailleBondDiff);
        newDiff = difficulty - tailleBondDiff;
        console.log("newDiff = " + newDiff);

        if (newDiff < 0) {
            newDiff = 0;
            //difficulty = newDiff;
        }

    } else {

    }

    cumulWin = [];
    cumulFail = [];
    clearArray();
}*/

<commit_msg>correction code<commit_after>
/* à intégrer dans chaque jeu
var modeDifficulty = 1; //0 pour adaptation de la difficulté en fonction win/fail, 1 pour courbe bonds

function changeMetaDiff() {
    if (modeDifficulty === 0) {
        // reprendre code actuel fonctionnement diff

    } else if (modeDifficulty === 1 && modeTest === true) {
        // reprendre code actuel fonctionnement diff

    } else if (modeDifficulty === 1 && modeTest === false) {
        // envoyer vers contenu de courbeDiff.js
        selectbondDiff();
        difficulty = newDiff;
    }
    console.log("difficulté du jeu:" + difficulty);
}
*/

// conserver le nombre de tours gagnants d'affilé
var lastWinFail = [];
var cumulWin = [];
var cumulFail = [];

var firstBondDiff = false; //false : premier bond de difficulté non sélectionné ; true, premier bond sélectionné

var bondDiffLittle = 0.1;
var bondDiffMedium = 0.3;
var bondDiffHigh = 0.6;
var bondDiffActual = 0;

var bondDiffNoLittle = [0.3, 0.6];
var bondDiffNoMedium = [0.1, 0.6];
var bondDiffNoHigh = [0.3, 0.6];
var bondDiffAll = [0.1, 0.3, 0.6];

var newDiff = 0;
var bondDiff = 0;

var compareArrayWin = 0;
var compareArrayFail = 0;

var compteurTours = 0; //compteur qui augmente après chaque tour
var toursBeforeChange = 2; //nbre de tours avant changement de comportement de la courbe de difficulté

//générer aléatoirement premier bond de difficulté après la fin des tours de chauffe
function selectFirstBondDiff() {
    if (modeTest === false && firstBondDiff === false) {
        bondDiffActual = bondDiffAll[Math.floor(bondDiffAll.length * Math.random())];

        bondDiff = bondDiffActual;
        newDiff = bondDiff;

        firstBondDiff = true;
        console.log("premier bond de difficulté: " + bondDiff);
    }
}

function selectbondDiff() {
    if (modeTest === false && firstBondDiff === true) {
        if (bondDiff === bondDiffLittle) {
            bondDiff = bondDiffNoLittle[Math.floor(bondDiffNoLittle.length * Math.random())];
        } else if (bondDiff === bondDiffMedium) {
            bondDiff = bondDiffNoMedium[Math.floor(bondDiffNoMedium.length * Math.random())];
        } else if (bondDiff === bondDiffHigh) {
            bondDiff = bondDiffNoHigh[Math.floor(bondDiffNoHigh.length * Math.random())];
        }
        console.log("nouveau bond de difficulté: " + bondDiff);

        changeDifficulty();
    } else {
        selectFirstBondDiff();
    }

}

function changeDifficulty() {
    var array = [0, 1];
    var addOrSub = array[Math.floor(array.length * Math.random())];
    if (addOrSub === 1) {
        console.log("progression de la difficulté vers le haut");
    } else {
        console.log("progression de la difficulté vers le bas");
    }

    if (addOrSub === 0) { //changement de difficulté par soustraction
        newDiff = difficulty - bondDiff;
        console.log("newDiff = " + newDiff);

        if (newDiff < 0) {
            newDiff = 0;
            console.log("newDiff corrected = " + newDiff);
        }
    } else if (addOrSub === 1) { //changement de difficulté par addition
        newDiff = difficulty + bondDiff;
        console.log("newDiff = " + newDiff);

        if (newDiff >= 1) {
            newDiff = 1;
            console.log("newDiff corrected = " + newDiff);
        }
    }

}

/*function cumulTours() {
    if (winState === true) {
        lastWinFail.push("true");
        compteurTours++;

        console.log("dernier win:" + lastWinFail)

    } else if (winState === false) {
        lastWinFail.push("fail");
        compteurTours++;

        console.log("dernier fail:" + lastWinFail)

    }

    checkWinFail();
}

function clearArray() {
    if (compteurTours === toursBeforeChange) {
        lastWinFail = [];
        compteurTours = 0;
    }
}

function checkWinFail() {
    var idx = lastWinFail.indexOf("true");
    while (idx != -1) {
        cumulWin.push("true");
        idx = lastWinFail.indexOf("true", idx + 1);
    }
    console.log("cumul des win:" + cumulWin);

    var idx2 = lastWinFail.indexOf("fail");
    while (idx2 != -1) {
        cumulFail.push("fail");
        idx2 = lastWinFail.indexOf("fail", idx2 + 1);
    }
    console.log("cumul des fail:" + cumulFail);

    behaviorDiff();
}

//comparer les tableaux pour vérifier la présence de trois win
compareArrayWin = function (lastWinFail, cumulWin) {
    if (lastWinFail.length !== cumulWin.length) {
        return false;
    } else if (lastWinFail.length === cumulWin.length) {
        for (var i = 0; i < lastWinFail.length; i++) {
            if (lastWinFail[i] !== cumulWin[i]) {
                return false;
            }
        }
    console.log("coucou1");
    return true;
    }
};

//comparer les tableaux pour vérifier la présence de trois fail
compareArrayFail = function (lastWinFail, cumulFail) {
    if (lastWinFail.length !== cumulFail.length) {
        return false;
    } else if (lastWinFail.length === cumulFail.length) {
        for (var i = 0; i < lastWinFail.length; i++) {
            if (lastWinFail[i] !== cumulFail[i]) {
                return true;
            }
        }
    console.log("coucou2");
    return true;
    }
};

function behaviorDiff() {
    if (compareArrayWin(lastWinFail, cumulWin) === true && compteurTours === toursBeforeChange) {
        var tailleBondDiff = bondDiff[Math.floor(bondDiff.length * Math.random())];
        console.log("taille du bond de difficulté win" + tailleBondDiff);
        newDiff = difficulty + tailleBondDiff;
        console.log("newDiff = " + newDiff);

        if (newDiff >= 1) {
            newDiff = 1;
            //difficulty = newDiff;
        }

    } else if (compareArrayFail(lastWinFail, cumulFail) === true && compteurTours === toursBeforeChange) {
        var tailleBondDiff = bondDiff[Math.floor(bondDiff.length * Math.random())];
        console.log("taille du bond de difficulté fail" + tailleBondDiff);
        newDiff = difficulty - tailleBondDiff;
        console.log("newDiff = " + newDiff);

        if (newDiff < 0) {
            newDiff = 0;
            //difficulty = newDiff;
        }

    } else {

    }

    cumulWin = [];
    cumulFail = [];
    clearArray();
}*/

<|endoftext|>


<commit_before>/*
 * Qanimationframe.js - Promisified requestAnimationFrame with Q
 */
/*jslint newcap: true */
(function (definition) {
    if (typeof exports === "object") {
        module.exports = definition();
    } else {
        window.QanimationFrame = definition();
    }
})(function () {
  "use strict";

  // Import Q
  var Q = window.Q || require("q");

  // requestAnimationFrame polyfill
  var requestAnimationFrame = (function(){
    return window.requestAnimationFrame       ||
           window.oRequestAnimationFrame      ||
           window.msRequestAnimationFrame     ||
           window.mozRequestAnimationFrame    ||
           window.webkitRequestAnimationFrame ||
           function (callback) {
             window.setTimeout(callback, 1000 / 60);
           };
  })();

  // QanimationFrame(elt: DOM.Element) => Promise[DOM.Element]
  // ---
  //
  var QanimationFrame = function (elt) {
    var d = Q.defer();
    requestAnimationFrame(function () {
      d.resolve(elt);
    }, elt);
    return d.promise;
  };

  return QanimationFrame;
});
<commit_msg>fix qanimationframe -> new api<commit_after>/*
 * Qanimationframe.js - Promisified requestAnimationFrame with Q
 */
/*jslint newcap: true */
(function (definition) {
    if (typeof exports === "object") {
        module.exports = definition();
    } else {
        window.QanimationFrame = definition();
    }
})(function () {
  "use strict";

  // Import Q
  var Q = window.Q || require("q");

  // requestAnimationFrame polyfill
  var requestAnimationFrame = (function(){
    return window.requestAnimationFrame       ||
           window.oRequestAnimationFrame      ||
           window.msRequestAnimationFrame     ||
           window.mozRequestAnimationFrame    ||
           window.webkitRequestAnimationFrame ||
           function (callback) {
             window.setTimeout(callback, 1000 / 60);
           };
  })();

  // QanimationFrame(f: function) => DOM.Element
  // ---
  //
  var QanimationFrame = function (f) {
    var d = Q.defer();
    requestAnimationFrame(function () {
      d.resolve(f());
    });
    return d.promise;
  };

  return QanimationFrame;
});
<|endoftext|>


<commit_before>var nomDuJeu = "Logique";
var IDjoueur = localStorage.getItem("joueur");
var scoreJoueurHugh = 0; //Score du joueur à renseigner en fin de session de jeu

var figures = [
    "../src/img/cool.svg",
    "../src/img/deg.svg",
    "../src/img/triste.svg",
    "../src/img/haha.svg",
    "../src/img/meh.svg",
    "../src/img/cheveux.svg",
    "../src/img/smile.svg"]
var order = [0,1,2,3,4,5,6];
var me;
var him;

var score = 0; //Score actuel
var mise = 0; //Combien le joueur a misé
var tours = 5; //Nombre de tours restants
var miseValide = false; //Si la mise n'est pas validée par le joueur

var difficulte = 0; //de 0 à order.length - 2

function init() {
    document.getElementById("tours").innerHTML = tours;
    document.getElementById("score").innerHTML = score;
    document.getElementById("mise").innerHTML = mise;
}

//récupérer mise
function recupMise () {
    if(document.getElementById('mise1').checked) {
        //boutton de mise 1 est validé
        mise = 1;

    }else if(document.getElementById('mise2').checked) {
        mise = 2;
    }else if(document.getElementById('mise3').checked) {
        mise = 3;
    }else if(document.getElementById('mise4').checked) {
        mise = 4;
    }else if(document.getElementById('mise5').checked) {
        mise = 5;
    }else if(document.getElementById('mise6').checked) {
        mise = 6;
    }else if(document.getElementById('mise7').checked) {
        mise = 7;
    }
    //afficher mise
    showMise();

    //verrouiller boutons de mise
    document.getElementById("mise1").disabled = true;
    document.getElementById("mise2").disabled = true;
    document.getElementById("mise3").disabled = true;
    document.getElementById("mise4").disabled = true;
    document.getElementById("mise5").disabled = true;
    document.getElementById("mise6").disabled = true;
    document.getElementById("mise7").disabled = true;

    //enregistrer mise dans csv
    //enregistrerDonnees(0, mise);

    //acter la mise du joueur pour déverouiller jeu
    miseValide = true;

}

function showMise() {
    document.getElementById("tableMise").style.visibility = "visible";
    document.getElementById("tours").innerHTML = tours;
    document.getElementById("score").innerHTML = score;
    document.getElementById("mise").innerHTML = mise;
}

function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

      // Pick a remaining element...
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;

      // And swap it with the current element.
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }

  return array;
}

function shuffleOrder(){
    order = shuffle(order);
}

function doIBeatHim(me, him) {
    for(var i=0;i<order.length;i++){
            if(order[i] == me)
                    return false;
            if (order[i] == him)
                    return true;
	}
}

function newRound(){
    var nbElts = 2 + difficulte;
    console.log("NbElts="+nbElts);
    var meBefore = me;
    me = Math.floor(Math.random() * nbElts);
    while (me == meBefore)
            me = Math.floor(Math.random() * nbElts);
    him = Math.floor(Math.random() * nbElts);
    while (him == me)
            him = Math.floor(Math.random() * nbElts);

    document.getElementById("me").innerHTML = '';
    document.getElementById("him").innerHTML = '';

    /*if(miseValide) {
        //déverrouiller boutons figures
        document.getElementById("me").disabled = false;
        document.getElementById("him").disabled = false;
    }*/
}

function go(){
    shuffleOrder();
    newRound();
}

function diff(sens){
    difficulte += sens;
    difficulte = Math.max(2,difficulte);
    difficulte = Math.min(order.length-2,difficulte);
    newRound();
}

function res(win) {
    var msg;
    if(miseValide && doIBeatHim(me,him) == win){
        score+=mise;
        tours--;
        document.getElementById("res").innerHTML = "Vous avez trouvé la figure gagnante. \n"+ score + " chaton(s) de sauvé(s) !";

    } else if (miseValide) {
        score+=mise;
        tours--;
        document.getElementById("res").innerHTML = "Vous avez trouvé la figure gagnante. \n"+ score + " chaton(s) de perdu(s) !";
    }

    //score = Math.max(0,score);

    //reset de la mise et affichage résultat
    mise = "?";
    document.getElementById("tours").innerHTML = tours;
    document.getElementById("score").innerHTML = score;
    document.getElementById("mise").innerHTML = mise;

    //déverrouiller boutons de mise
    document.getElementById("mise1").disabled = false;
    document.getElementById("mise2").disabled = false;
    document.getElementById("mise3").disabled = false;
    document.getElementById("mise4").disabled = false;
    document.getElementById("mise5").disabled = false;
    document.getElementById("mise6").disabled = false;
    document.getElementById("mise7").disabled = false;

    if (miseValide && tours > 0) {
        newRound();
    } else {
        finDePartie();
    }

    miseValide=false;

    //verrouiller boutons figures
    document.getElementById("me").disabled = true;
    document.getElementById("him").disabled = true;
}

function finDePartie() {
    if (tours == 0){
        //récupérer score final du joueur
        scoreJoueurHugh = score;
        localStorage.scoreJoueurTom = scoreJoueurHugh;
        console.log(scoreJoueurHugh);
        //créer le bouton
        var boutton = document.createElement("input");
        boutton.type = "button";
        boutton.value = "Fin de partie.";
        boutton.name = "FIN";
        var results = function resultat(){
            var messageFinPartie = confirm("Votre partie est terminée. Votre score est de " + score +" Cliquez pour passer au jeu suivant.");
            if (messageFinPartie==true) {
                x = "Prototype en cours de développement, veuillez patienter.";
                enregistrerDonnees(1,nomDuJeu + ";" + resultatJoueur);
                var jeuMotriceTermine = true;
                localStorage.getItem("hughlaurie", jeuLogicTermine);

            } else {
                x = "Ah, d'accord.";
            }
            document.getElementById("retourProto").innerHTML = x;
        }
        boutton.onclick = results;
        document.body.appendChild(boutton);
    } else{

    }
}

// enregistrer données du joueur dans fichier csv
function enregistrerDonnees (type, data) {
    var xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            //console.log(xhttp.response);
        }
    };

    if (type == 0) {
        xhttp.open("POST", "http://localhost/sorcerer/src/php/toto.php", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send("joueur=" + data);
    } else if (type == 1) {
        xhttp.open("POST", "http://localhost/sorcerer/src/php/toto.php", true );
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send("data=" + data);
    }

    //xhttp.open("POST", "http://localhost:63342/Bandit2/src/php/toto.php", true);
    //xhttp.setRequestHeader("Content-type", "text/plain");
    //xhttp.send("data=\"" + donneesJoueur + "\"");
    //xhttp.send("data=15");

    console.log("Sent data " + data);
}<commit_msg>ajout fonction pour générer tableau avec figures prédicats et tableau avec figures bruits<commit_after>var nomDuJeu = "Logique";
var IDjoueur = localStorage.getItem("joueur");
var scoreJoueurHugh = 0; //Score du joueur à renseigner en fin de session de jeu

var figures = [
    "../src/img/cool.svg",
    "../src/img/deg.svg",
    "../src/img/triste.svg",
    "../src/img/haha.svg",
    "../src/img/meh.svg",
    "../src/img/cheveux.svg",
    "../src/img/smile.svg"]
var order = [0,1,2,3,4,5,6];
var predicats = []; //Tableau dans lequel seront injectées les figures prédicats
var bruits = []; //Tableau dans lequel le reste des figures seront injectées (hors prédicats)
var me;
var him;

var score = 0; //Score actuel
var mise = 0; //Combien le joueur a misé
var tours = 5; //Nombre de tours restants
var miseValide = false; //Si la mise n'est pas validée par le joueur

var difficulte = 0; //de 0 à order.length - 2

function genererPredicatsBruits () {
    var i=0;
    var j=0;
    while (i<=2) {
        var tirageAleatoire = order[Math.floor(Math.random()*order.length)];
        if (predicats.includes(tirageAleatoire) === false) {
            predicats.push(tirageAleatoire);
            i++;
        }
    }

    while (j<=3) {
        var tirageAleatoire = order[Math.floor(Math.random()*order.length)];
        if (bruits.includes(tirageAleatoire) === false && predicats.includes(tirageAleatoire) === false) {
            bruits.push(tirageAleatoire);
            j++;
        }
    }

    console.log(predicats);
    console.log(bruits);

    /*for (var i=0; i<=2; i++) {
        var tirageAleatoire = order[Math.floor(Math.random()*order.length)];
        if (predicats.includes(tirageAleatoire) === false) {
            predicats.push(tirageAleatoire);
        }else {
            i--;
        }
    }
    console.log(predicats);

    for (var j=0; j<=3; j++){
        var tirageAleatoireBruits = order[Math.floor(Math.random()*order.length)];
        if (predicats.includes(tirageAleatoireBruits) === false && bruits.includes(tirageAleatoireBruits) === false){
            bruits.push(tirageAleatoireBruits);
        }else {
            j--;
        }
    }
    console.log(bruits);*/
}

function init() {
    document.getElementById("tours").innerHTML = tours;
    document.getElementById("score").innerHTML = score;
    document.getElementById("mise").innerHTML = mise;
}

//récupérer mise
function recupMise () {
    if(document.getElementById('mise1').checked) {
        //boutton de mise 1 est validé
        mise = 1;

    }else if(document.getElementById('mise2').checked) {
        mise = 2;
    }else if(document.getElementById('mise3').checked) {
        mise = 3;
    }else if(document.getElementById('mise4').checked) {
        mise = 4;
    }else if(document.getElementById('mise5').checked) {
        mise = 5;
    }else if(document.getElementById('mise6').checked) {
        mise = 6;
    }else if(document.getElementById('mise7').checked) {
        mise = 7;
    }
    //afficher mise
    showMise();

    //verrouiller boutons de mise
    document.getElementById("mise1").disabled = true;
    document.getElementById("mise2").disabled = true;
    document.getElementById("mise3").disabled = true;
    document.getElementById("mise4").disabled = true;
    document.getElementById("mise5").disabled = true;
    document.getElementById("mise6").disabled = true;
    document.getElementById("mise7").disabled = true;

    //enregistrer mise dans csv
    //enregistrerDonnees(0, mise);

    //acter la mise du joueur pour déverouiller jeu
    miseValide = true;

}

function showMise() {
    document.getElementById("tableMise").style.visibility = "visible";
    document.getElementById("tours").innerHTML = tours;
    document.getElementById("score").innerHTML = score;
    document.getElementById("mise").innerHTML = mise;
}

function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

      // Pick a remaining element...
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;

      // And swap it with the current element.
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }

  return array;
}

function shuffleOrder(){
    order = shuffle(order);
}

function doIBeatHim(me, him) {
    for(var i=0;i<order.length;i++){
            if(order[i] == me)
                    return false;
            if (order[i] == him)
                    return true;
	}
}

function newRound(){
    var nbElts = 2 + difficulte;
    console.log("NbElts="+nbElts);
    var meBefore = me;
    me = Math.floor(Math.random() * nbElts);
    while (me == meBefore)
            me = Math.floor(Math.random() * nbElts);
    him = Math.floor(Math.random() * nbElts);
    while (him == me)
            him = Math.floor(Math.random() * nbElts);

    document.getElementById("me").innerHTML = '';
    document.getElementById("him").innerHTML = '';

    /*if(miseValide) {
        //déverrouiller boutons figures
        document.getElementById("me").disabled = false;
        document.getElementById("him").disabled = false;
    }*/
}

function go(){
    shuffleOrder();
    newRound();
}

function diff(sens){
    difficulte += sens;
    difficulte = Math.max(2,difficulte);
    difficulte = Math.min(order.length-2,difficulte);
    newRound();
}

function res(win) {
    var msg;
    if(miseValide && doIBeatHim(me,him) == win){
        score+=mise;
        tours--;
        document.getElementById("res").innerHTML = "Vous avez trouvé la figure gagnante. \n"+ score + " chaton(s) de sauvé(s) !";

    } else if (miseValide) {
        score+=mise;
        tours--;
        document.getElementById("res").innerHTML = "Vous avez trouvé la figure gagnante. \n"+ score + " chaton(s) de perdu(s) !";
    }

    //score = Math.max(0,score);

    //reset de la mise et affichage résultat
    mise = "?";
    document.getElementById("tours").innerHTML = tours;
    document.getElementById("score").innerHTML = score;
    document.getElementById("mise").innerHTML = mise;

    //déverrouiller boutons de mise
    document.getElementById("mise1").disabled = false;
    document.getElementById("mise2").disabled = false;
    document.getElementById("mise3").disabled = false;
    document.getElementById("mise4").disabled = false;
    document.getElementById("mise5").disabled = false;
    document.getElementById("mise6").disabled = false;
    document.getElementById("mise7").disabled = false;

    if (miseValide && tours > 0) {
        newRound();
    } else {
        finDePartie();
    }

    miseValide=false;

    //verrouiller boutons figures
    document.getElementById("me").disabled = true;
    document.getElementById("him").disabled = true;
}

function finDePartie() {
    if (tours == 0){
        //récupérer score final du joueur
        scoreJoueurHugh = score;
        localStorage.scoreJoueurTom = scoreJoueurHugh;
        console.log(scoreJoueurHugh);
        //créer le bouton
        var boutton = document.createElement("input");
        boutton.type = "button";
        boutton.value = "Fin de partie.";
        boutton.name = "FIN";
        var results = function resultat(){
            var messageFinPartie = confirm("Votre partie est terminée. Votre score est de " + score +" Cliquez pour passer au jeu suivant.");
            if (messageFinPartie==true) {
                x = "Prototype en cours de développement, veuillez patienter.";
                enregistrerDonnees(1,nomDuJeu + ";" + resultatJoueur);
                var jeuMotriceTermine = true;
                localStorage.getItem("hughlaurie", jeuLogicTermine);

            } else {
                x = "Ah, d'accord.";
            }
            document.getElementById("retourProto").innerHTML = x;
        }
        boutton.onclick = results;
        document.body.appendChild(boutton);
    } else{

    }
}

// enregistrer données du joueur dans fichier csv
function enregistrerDonnees (type, data) {
    var xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            //console.log(xhttp.response);
        }
    };

    if (type == 0) {
        xhttp.open("POST", "http://localhost/sorcerer/src/php/toto.php", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send("joueur=" + data);
    } else if (type == 1) {
        xhttp.open("POST", "http://localhost/sorcerer/src/php/toto.php", true );
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send("data=" + data);
    }

    //xhttp.open("POST", "http://localhost:63342/Bandit2/src/php/toto.php", true);
    //xhttp.setRequestHeader("Content-type", "text/plain");
    //xhttp.send("data=\"" + donneesJoueur + "\"");
    //xhttp.send("data=15");

    console.log("Sent data " + data);
}<|endoftext|>


<commit_before>//
// HLF Media Grid Extensions
// =========================
// [Styles](../css/media-grid.html) | [Tests](../../tests/js/media-grid.html)
//
// The `mediaGrid` extension, inspired by the Cargo Voyager design template, can
// expand an item inline without affecting the position of its siblings. The
// extension tries to add the minimal amount of DOM elements and styles. So the
// layout rules are mostly defined in the styles, and initial html for items is
// required (see the tests for an example). The extension also handles additional
// effects like focusing on the expanded item and dimming its siblings.
//
(function(root, attach) {
  //
  // § __UMD__
  // - When AMD, register the attacher as an anonymous module.
  // - When Node or Browserify, set module exports to the attach result.
  // - When browser globals (root is window), Just run the attach function.
  //
  if (typeof define === 'function' && define.amd) {
    define(['hlf/core'], attach);
  } else if (typeof exports === 'object') {
    module.exports = attach(require('hlf/core'));
  } else {
    attach(hlf);
  }
})(this, function(hlf) {
  //
  // Namespace
  // ---------
  //
  // It takes some more boilerplate to write the extension. Any of this additional
  // support API is put into a extension specific namespace under `hlf`, which in
  // this case is __hlf.mediaGrid__.
  //
  // - __debug__ toggles debug logging for all instances of an extension.
  // - __toString__ helps to namespace when registering any DOM names.
  // - __attrName__, __className__, __eventName__ helpers are all attached to
  //   the namespace on extension creation, along with the __extension__ itself.
  //
  // The extension's __defaults__ are available as reference. Also note that _the
  // extension instance gets extended with the options_.
  //
  // - __autoReady__ is `false` by default, as recommended. Turning it on means
  //   the `ready` event gets triggered immediately, synchronously, and is only
  //   recommended if your grid doesn't have images and such that require a wait
  //   before being fully loaded and sized.
  //
  // - __resizeDelay__ is the millis to wait for window resizing to stop before
  //   doing a re-layout. `100` is the default to balance responsiveness and
  //   performance.
  //
  // - Note: for these extensions, the majority of presentation state logic is
  //   in the extension stylesheet. We update the presentation state by using
  //   namespaced __classNames__ generated in a closure.
  //
  hlf.mediaGrid = {
    debug: false,
    toString(context) {
      switch (context) {
        case 'event': return 'hlfmg';
        case 'data': return 'hlf-mg';
        case 'class': return 'mg';
        default: return 'hlf-mg';
      }
    },
    defaults: {
      autoReady: false,
      resizeDelay: 100,
      undimDelay: 1000,
    },
  };
  //
  // MediaGrid
  // ---------
  //
  class MediaGrid {
    constructor(element, options) {
      this.eventListeners = { mouseleave: this._onMouseLeave };
      this.eventListeners[this.eventName('expand')] = this._onItemExpand;
    }
    //
    // __init__ completes the setup:
    // 1. Select `itemElements` and `sampleItemElement`.
    // 2. Get `expandDuration` from styles, create event bindings for expansion.
    //    This also relies on the `expandedItemElement` state.
    // 3. Create event bindings for dimming on expansion, hovering expanded item.
    // 4. Set up initial layout for running when `ready`.
    // 5. Set up re-layout for running on window resize.
    //
    init() {
      if (!this.itemElements) {
        this._selectItemElements();
      }
      this.itemElements.forEach(this._toggleItemEventListeners.bind(this, true));
      window.addEventListener('resize', this._onWindowResize);
      this.sampleItemElement = this.itemElements[0];
      this.expandDuration = 1000 * parseFloat(
        getComputedStyle(this.sampleItemElement).transitionDuration
      );
      this.expandedItemElement = null;
      this._itemsObserver = new MutationObserver(this._onItemsMutation);
      this._itemsObserver.connect = () => {
        this._itemsObserver.observe(this.element, { childList: true });
      };
      this.metrics = {};
      if (this.autoLoad) {
        this.performLoad();
      }
    }
    deinit() {
      this.itemElements.forEach(this._toggleItemEventListeners.bind(this, false));
      window.removeEventListener('resize', this._onWindowResize);
      this._itemsObserver.disconnect();
    }
    performLoad() {
      this._updateMetrics({ hard: true });
      this._layoutItems();
      this._itemsObserver.connect();
      this.element.classList.add(this.className('ready'));
      this.dispatchCustomEvent('ready');
    }
    //
    // § __Public__
    //
    // You are welcome to call these methods from your own code, though currently
    // there is no intended use case for that.
    //
    // __toggleItemExpansion__ basically toggles the `-expanded` class on the
    // given `itemElement` to `expanded` and triggers the `expand` event. To allow
    // styling or scripting during the transition, it adds the `-transitioning`
    // class and removes it afterwards per `expandDuration`.
    //
    toggleItemExpansion(itemElement, expanded, completion) {
      if (typeof expanded === 'undefined') {
        expanded = !itemElement.classList.contains(this.className('expanded'));
      }
      let index = this.itemElements.indexOf(itemElement);
      if (expanded) {
        if (this.expandedItemElement) {
          this.toggleItemExpansion(this.expandedItemElement, false);
        }
        if (this._isRightEdgeItem(index)) {
          this._adjustItemToRightEdge(itemElement);
        }
        if (this._isBottomEdgeItem(index)) {
          this._adjustItemToBottomEdge(itemElement);
        }
      }
      this._toggleNeighborItemsRecessed(index, expanded);
      itemElement.classList.add(this.className('transitioning'));
      clearTimeout(itemElement.getAttribute(this.attrName('expand-timeout')));
      itemElement.setAttribute(this.attrName('expand-timeout'),
        setTimeout(() => {
          itemElement.classList.remove(this.className('transitioning'));
          if (completion) {
            completion();
          }
        }, this.expandDuration)
      );

      itemElement.classList.toggle(this.className('expanded'), expanded);
      this.expandedItemElement = expanded ? itemElement : null;

      itemElement.dispatchEvent(this.createCustomEvent('expand', { expanded }));
    }
    //
    // __toggleExpandedItemFocus__ wraps `toggleItemFocus` to factor in
    // `undimDelay` when toggling off `focus`. Focusing dims without delay.
    //
    toggleExpandedItemFocus(itemElement, focused) {
      if (!itemElement.classList.contains(this.className('expanded'))) { return; }
      let delay = focused ? 0 : this.undimDelay;
      this.toggleItemFocus(itemElement, focused, delay);
    }
    //
    // __toggleItemFocus__ basically toggles the `-focused` class on the given
    // `itemElement` to `focused` and the `-dimmed` class on the root element
    // after any given `delay`.
    //
    toggleItemFocus(itemElement, focused, delay = 0) {
      if (focused) {
        this.itemElements.forEach((itemElement) => {
          itemElement.classList.remove(this.className('focused'));
        });
      }
      itemElement.classList.toggle(this.className('focused'), focused);
      clearTimeout(this._dimTimeout);
      this._dimTimeout = setTimeout(() => {
        this.element.classList.toggle(this.className('dimmed'), focused);
      }, delay);
    }
    //
    // § __Internal__
    //
    _onItemClick(event) {
      const actionElementTags = ['a', 'audio', 'button', 'input', 'video'];
      if (actionElementTags.indexOf(event.target.tagName.toLowerCase()) !== -1) { return; }
      this.toggleItemExpansion(event.currentTarget);
    }
    _onItemExpand(event) {
      const { target } = event;
      if (!this._isItemElement(target)) { return; }
      const { expanded } = event.detail;
      this.toggleItemFocus(target, expanded, this.expandDuration);
    }
    _onItemMouseEnter(event) {
      this.toggleExpandedItemFocus(event.currentTarget, true);
    }
    _onItemMouseLeave(event) {
      this.toggleExpandedItemFocus(event.currentTarget, false);
    }
    _onItemsMutation(mutations) {
      this._itemsObserver.disconnect();
      this._reLayoutItems();
      mutations
        .filter(m => !!m.addedNodes.length)
        .forEach((mutation) => {
          Array.from(mutation.addedNodes)
            .filter(this._isItemElement)
            .forEach(this._toggleItemEventListeners.bind(this, true));
        });
      this._itemsObserver.connect();
    }
    _onMouseLeave(_) {
      if (!this.expandedItemElement) { return; }
      this.toggleItemFocus(this.expandedItemElement, false);
    }
    _onWindowResize(_) {
      const now = Date.now();
      if (this._ran && now < this._ran + this.resizeDelay) { return; }
      this._ran = now;
      this._reLayoutItems();
    }
    _isItemElement(node) {
      return (node instanceof HTMLElement &&
        node.classList.contains(this.className('item')));
    }
    _selectItemElements() {
      this.itemElements = Array.from(this.element.querySelectorAll(
        `.${this.className('item')}:not(.${this.className('sample')})`
      ));
    }
    _toggleItemEventListeners(on, itemElement) {
      this.toggleEventListeners(on, {
        'click': this._onItemClick,
        'mouseenter': this._onItemMouseEnter,
        'mouseleave': this._onItemMouseLeave,
      }, itemElement);
    }
    //
    // These are layout helpers for changing offset for an `itemElement`.
    //
    _adjustItemToBottomEdge(itemElement) {
      let { style } = itemElement;
      style.top = 'auto';
      style.bottom = '0px';
    }
    _adjustItemToRightEdge(itemElement) {
      let { style } = itemElement;
      style.left = 'auto';
      style.right = '0px';
    }
    //
    // ___getMetricSamples__ returns cloned `itemElement` and `expandedItemElement`
    // mainly for calculating initial metrics. For them to have the right sizes,
    // they're attached to an invisible container appended to the root element.
    //
    _getMetricSamples() {
      let containerElement = this.selectByClass('samples');
      if (containerElement) {
        containerElement.parentNode.removeChild(containerElement);
      }
      let itemElement = this.sampleItemElement.cloneNode(true);
      itemElement.classList.add(this.className('sample'));
      let expandedItemElement = this.sampleItemElement.cloneNode(true);
      expandedItemElement.classList.add(
        this.className('expanded'), this.className('sample')
      );
      containerElement = document.createElement('div');
      containerElement.classList.add(this.className('samples'));
      let { style } = containerElement;
      style.left = style.right = style.top = '0px';
      style.position = 'absolute';
      style.visibility = 'hidden';
      style.zIndex = 0;
      containerElement.appendChild(itemElement);
      containerElement.appendChild(expandedItemElement);
      this.element.appendChild(containerElement);
      return { itemElement, expandedItemElement };
    }
    //
    // These are layout helpers for checking item position based on index and the
    // current `rowSize` metric.
    //
    _isBottomEdgeItem(i) {
      const { rowSize } = this.metrics;
      let lastRowSize = (this.itemElements.length % rowSize) || rowSize;
      let untilLastRow = this.itemElements.length - lastRowSize;
      return (i + 1) > untilLastRow;
    }
    _isRightEdgeItem(i) {
      return ((i + 1) % this.metrics.rowSize) === 0;
    }
    //
    // ___layoutItems__ occurs once `metrics` is updated. With the latest
    // `wrapWidth` and `wrapHeight` metrics, the root element is resized. Each
    // element in `itemElements` gets its position style set to `absolute` non-
    // destructively; this method assumes the original is `float`, and so
    // iterates in reverse.
    //
    _layoutItems() {
      Array.from(this.itemElements).reverse().forEach((itemElement) => {
        if (!itemElement.hasAttribute(this.attrName('original-position'))) {
          itemElement.setAttribute(this.attrName('original-position'),
            getComputedStyle(itemElement).position);
        }
        let { offsetLeft, offsetTop, style } = itemElement;
        style.position = 'absolute';
        style.left = `${offsetLeft}px`;
        style.top = `${offsetTop}px`;
      });
      let { style } = this.element;
      style.width = `${this.metrics.wrapWidth}px`;
      style.height = `${this.metrics.wrapHeight}px`;
    }
    //
    // ___reLayoutItems__ wraps `_layoutItems` to be its idempotent version by
    // first resetting each item's to its `original-position`.
    //
    _reLayoutItems() {
      if (this.expandedItemElement) {
        this.toggleItemExpansion(this.expandedItemElement, false, () => {
          this._reLayoutItems();
        });
        return;
      }
      this._selectItemElements();
      this._updateMetrics();
      this.itemElements.forEach((itemElement) => {
        let { style } = itemElement;
        style.bottom = style.left = style.right = style.top = 'auto';
        style.position = itemElement.getAttribute(this.attrName('original-position'));
        itemElement.classList.remove(this.className('raw'));
      });
      this._layoutItems();
    }
    //
    // ___toggleNeighborItemsRecessed__ toggles the `-recessed` class on items
    // per the occlusion-causing expansion of the item at `index`.
    //
    _toggleNeighborItemsRecessed(index, recessed) {
      const { expandedScale, rowSize } = this.metrics;
      let dx = this._isRightEdgeItem(index) ? -1 : 1;
      let dy = this._isBottomEdgeItem(index) ? -1 : 1;
      let level = 1;
      let neighbors = [];
      while (level < expandedScale) {
        neighbors.push(
          this.itemElements[index + level * dx],
          this.itemElements[index + level * dy * rowSize],
          this.itemElements[index + level * (dy * rowSize + dx)]
        );
        level += 1;
      }
      neighbors.filter(n => !!n).forEach((itemElement) => {
        itemElement.classList.toggle(this.className('recessed'));
      });
    }
    //
    // ___updateMetrics__ builds the `metrics` around item and wrap as well as
    // row and column sizes. It does so by measuring sample elements and their
    // margins, as well as sizing the wrap (root element) to fit its items. As
    // such, this method isn't idempotent and expects to be followed by a call
    // to `_layoutItems`.
    //
    _updateMetrics({ hard } = { hard: false }) {
      if (hard) {
        const { itemElement, expandedItemElement } = this._getMetricSamples();
        this.metrics = {
          itemWidth: itemElement.offsetWidth,
          itemHeight: itemElement.offsetHeight,
          expandedWidth: expandedItemElement.offsetWidth,
          expandedHeight: expandedItemElement.offsetHeight,
          expandedScale: parseInt(this.cssVariable('item-expanded-scale')),
        };
      }
      let gutter = Math.round(parseFloat(
        getComputedStyle(this.sampleItemElement).marginRight
      ));
      let fullWidth = this.metrics.itemWidth + gutter;
      let fullHeight = this.metrics.itemHeight + gutter;

      let { style } = this.element;
      style.height = style.width = 'auto';

      let rowSize = parseInt(((this.element.offsetWidth + gutter) / fullWidth));
      let colSize = Math.ceil(this.itemElements.length / rowSize);
      Object.assign(this.metrics, { gutter, rowSize, colSize }, {
        wrapWidth: fullWidth * rowSize,
        wrapHeight: fullHeight * colSize,
      });
    }
  }
  //
  // § __Attaching__
  //
  return hlf.createExtension({
    name: 'mediaGrid',
    namespace: hlf.mediaGrid,
    apiClass: MediaGrid,
    autoBind: true,
    autoListen: true,
    baseMethodGroups: ['css', 'selection'],
    compactOptions: true,
  });
});
<commit_msg>Auto-scroll media-grid on mutation, w/ refactor.<commit_after>//
// HLF Media Grid Extensions
// =========================
// [Styles](../css/media-grid.html) | [Tests](../../tests/js/media-grid.html)
//
// The `mediaGrid` extension, inspired by the Cargo Voyager design template, can
// expand an item inline without affecting the position of its siblings. The
// extension tries to add the minimal amount of DOM elements and styles. So the
// layout rules are mostly defined in the styles, and initial html for items is
// required (see the tests for an example). The extension also handles additional
// effects like focusing on the expanded item and dimming its siblings.
//
(function(root, attach) {
  //
  // § __UMD__
  // - When AMD, register the attacher as an anonymous module.
  // - When Node or Browserify, set module exports to the attach result.
  // - When browser globals (root is window), Just run the attach function.
  //
  if (typeof define === 'function' && define.amd) {
    define(['hlf/core'], attach);
  } else if (typeof exports === 'object') {
    module.exports = attach(require('hlf/core'));
  } else {
    attach(hlf);
  }
})(this, function(hlf) {
  //
  // Namespace
  // ---------
  //
  // It takes some more boilerplate to write the extension. Any of this additional
  // support API is put into a extension specific namespace under `hlf`, which in
  // this case is __hlf.mediaGrid__.
  //
  // - __debug__ toggles debug logging for all instances of an extension.
  // - __toString__ helps to namespace when registering any DOM names.
  // - __attrName__, __className__, __eventName__ helpers are all attached to
  //   the namespace on extension creation, along with the __extension__ itself.
  //
  // The extension's __defaults__ are available as reference. Also note that _the
  // extension instance gets extended with the options_.
  //
  // - __autoReady__ is `false` by default, as recommended. Turning it on means
  //   the `ready` event gets triggered immediately, synchronously, and is only
  //   recommended if your grid doesn't have images and such that require a wait
  //   before being fully loaded and sized.
  //
  // - __resizeDelay__ is the millis to wait for window resizing to stop before
  //   doing a re-layout. `100` is the default to balance responsiveness and
  //   performance.
  //
  // - Note: for these extensions, the majority of presentation state logic is
  //   in the extension stylesheet. We update the presentation state by using
  //   namespaced __classNames__ generated in a closure.
  //
  hlf.mediaGrid = {
    debug: false,
    toString(context) {
      switch (context) {
        case 'event': return 'hlfmg';
        case 'data': return 'hlf-mg';
        case 'class': return 'mg';
        default: return 'hlf-mg';
      }
    },
    defaults: {
      autoReady: false,
      resizeDelay: 100,
      undimDelay: 1000,
    },
  };
  //
  // MediaGrid
  // ---------
  //
  class MediaGrid {
    constructor(element, options) {
      this.eventListeners = { mouseleave: this._onMouseLeave };
      this.eventListeners[this.eventName('expand')] = this._onItemExpand;
    }
    //
    // __init__ completes the setup:
    // 1. Select `itemElements` and `sampleItemElement`.
    // 2. Get `expandDuration` from styles, create event bindings for expansion.
    //    This also relies on the `expandedItemElement` state.
    // 3. Create event bindings for dimming on expansion, hovering expanded item.
    // 4. Set up initial layout for running when `ready`.
    // 5. Set up re-layout for running on window resize.
    //
    init() {
      if (!this.itemElements) {
        this._selectItemElements();
      }
      this.itemElements.forEach(this._toggleItemEventListeners.bind(this, true));
      window.addEventListener('resize', this._onWindowResize);
      this.sampleItemElement = this.itemElements[0];
      this.expandDuration = 1000 * parseFloat(
        getComputedStyle(this.sampleItemElement).transitionDuration
      );
      this.expandedItemElement = null;
      this._itemsObserver = new MutationObserver(this._onItemsMutation);
      this._itemsObserver.connect = () => {
        this._itemsObserver.observe(this.element, { childList: true });
      };
      this.metrics = {};
      if (this.autoLoad) {
        this.performLoad();
      }
    }
    deinit() {
      this.itemElements.forEach(this._toggleItemEventListeners.bind(this, false));
      window.removeEventListener('resize', this._onWindowResize);
      this._itemsObserver.disconnect();
    }
    performLoad() {
      this._updateMetrics({ hard: true });
      this._layoutItems();
      this._itemsObserver.connect();
      this.element.classList.add(this.className('ready'));
      this.dispatchCustomEvent('ready');
    }
    //
    // § __Public__
    //
    // You are welcome to call these methods from your own code, though currently
    // there is no intended use case for that.
    //
    // __toggleItemExpansion__ basically toggles the `-expanded` class on the
    // given `itemElement` to `expanded` and triggers the `expand` event. To allow
    // styling or scripting during the transition, it adds the `-transitioning`
    // class and removes it afterwards per `expandDuration`.
    //
    toggleItemExpansion(itemElement, expanded, completion) {
      if (typeof expanded === 'undefined') {
        expanded = !itemElement.classList.contains(this.className('expanded'));
      }
      let index = this.itemElements.indexOf(itemElement);
      if (expanded) {
        if (this.expandedItemElement) {
          this.toggleItemExpansion(this.expandedItemElement, false);
        }
        if (this._isRightEdgeItem(index)) {
          this._adjustItemToRightEdge(itemElement);
        }
        if (this._isBottomEdgeItem(index)) {
          this._adjustItemToBottomEdge(itemElement);
        }
      }
      this._toggleNeighborItemsRecessed(index, expanded);
      itemElement.classList.add(this.className('transitioning'));
      clearTimeout(itemElement.getAttribute(this.attrName('expand-timeout')));
      itemElement.setAttribute(this.attrName('expand-timeout'),
        setTimeout(() => {
          itemElement.classList.remove(this.className('transitioning'));
          if (completion) {
            completion();
          }
        }, this.expandDuration)
      );

      itemElement.classList.toggle(this.className('expanded'), expanded);
      this.expandedItemElement = expanded ? itemElement : null;

      itemElement.dispatchEvent(this.createCustomEvent('expand', { expanded }));
    }
    //
    // __toggleExpandedItemFocus__ wraps `toggleItemFocus` to factor in
    // `undimDelay` when toggling off `focus`. Focusing dims without delay.
    //
    toggleExpandedItemFocus(itemElement, focused) {
      if (!itemElement.classList.contains(this.className('expanded'))) { return; }
      let delay = focused ? 0 : this.undimDelay;
      this.toggleItemFocus(itemElement, focused, delay);
    }
    //
    // __toggleItemFocus__ basically toggles the `-focused` class on the given
    // `itemElement` to `focused` and the `-dimmed` class on the root element
    // after any given `delay`.
    //
    toggleItemFocus(itemElement, focused, delay = 0) {
      if (focused) {
        this.itemElements.forEach((itemElement) => {
          itemElement.classList.remove(this.className('focused'));
        });
      }
      itemElement.classList.toggle(this.className('focused'), focused);
      clearTimeout(this._dimTimeout);
      this._dimTimeout = setTimeout(() => {
        this.element.classList.toggle(this.className('dimmed'), focused);
      }, delay);
    }
    //
    // § __Internal__
    //
    _onItemClick(event) {
      const actionElementTags = ['a', 'audio', 'button', 'input', 'video'];
      if (actionElementTags.indexOf(event.target.tagName.toLowerCase()) !== -1) { return; }
      this.toggleItemExpansion(event.currentTarget);
    }
    _onItemExpand(event) {
      const { target } = event;
      if (!this._isItemElement(target)) { return; }
      const { expanded } = event.detail;
      this.toggleItemFocus(target, expanded, this.expandDuration);
    }
    _onItemMouseEnter(event) {
      this.toggleExpandedItemFocus(event.currentTarget, true);
    }
    _onItemMouseLeave(event) {
      this.toggleExpandedItemFocus(event.currentTarget, false);
    }
    _onItemsMutation(mutations) {
      let addedItemElements = mutations
        .filter(m => !!m.addedNodes.length)
        .reduce((allElements, m) => {
          let elements = Array.from(m.addedNodes).filter(this._isItemElement);
          return allElements.concat(elements);
        }, []);
      addedItemElements.forEach(this._toggleItemEventListeners.bind(this, true));
      this._itemsObserver.disconnect();
      this._reLayoutItems(() => {
        addedItemElements[0].scrollIntoView();
      });
      this._itemsObserver.connect();
    }
    _onMouseLeave(_) {
      if (!this.expandedItemElement) { return; }
      this.toggleItemFocus(this.expandedItemElement, false);
    }
    _onWindowResize(_) {
      const now = Date.now();
      if (this._ran && now < this._ran + this.resizeDelay) { return; }
      this._ran = now;
      this._reLayoutItems();
    }
    _isItemElement(node) {
      return (node instanceof HTMLElement &&
        node.classList.contains(this.className('item')));
    }
    _selectItemElements() {
      this.itemElements = Array.from(this.element.querySelectorAll(
        `.${this.className('item')}:not(.${this.className('sample')})`
      ));
    }
    _toggleItemEventListeners(on, itemElement) {
      this.toggleEventListeners(on, {
        'click': this._onItemClick,
        'mouseenter': this._onItemMouseEnter,
        'mouseleave': this._onItemMouseLeave,
      }, itemElement);
    }
    //
    // These are layout helpers for changing offset for an `itemElement`.
    //
    _adjustItemToBottomEdge(itemElement) {
      let { style } = itemElement;
      style.top = 'auto';
      style.bottom = '0px';
    }
    _adjustItemToRightEdge(itemElement) {
      let { style } = itemElement;
      style.left = 'auto';
      style.right = '0px';
    }
    //
    // ___getMetricSamples__ returns cloned `itemElement` and `expandedItemElement`
    // mainly for calculating initial metrics. For them to have the right sizes,
    // they're attached to an invisible container appended to the root element.
    //
    _getMetricSamples() {
      let containerElement = this.selectByClass('samples');
      if (containerElement) {
        containerElement.parentNode.removeChild(containerElement);
      }
      let itemElement = this.sampleItemElement.cloneNode(true);
      itemElement.classList.add(this.className('sample'));
      let expandedItemElement = this.sampleItemElement.cloneNode(true);
      expandedItemElement.classList.add(
        this.className('expanded'), this.className('sample')
      );
      containerElement = document.createElement('div');
      containerElement.classList.add(this.className('samples'));
      let { style } = containerElement;
      style.left = style.right = style.top = '0px';
      style.position = 'absolute';
      style.visibility = 'hidden';
      style.zIndex = 0;
      containerElement.appendChild(itemElement);
      containerElement.appendChild(expandedItemElement);
      this.element.appendChild(containerElement);
      return { itemElement, expandedItemElement };
    }
    //
    // These are layout helpers for checking item position based on index and the
    // current `rowSize` metric.
    //
    _isBottomEdgeItem(i) {
      const { rowSize } = this.metrics;
      let lastRowSize = (this.itemElements.length % rowSize) || rowSize;
      let untilLastRow = this.itemElements.length - lastRowSize;
      return (i + 1) > untilLastRow;
    }
    _isRightEdgeItem(i) {
      return ((i + 1) % this.metrics.rowSize) === 0;
    }
    //
    // ___layoutItems__ occurs once `metrics` is updated. With the latest
    // `wrapWidth` and `wrapHeight` metrics, the root element is resized. Each
    // element in `itemElements` gets its position style set to `absolute` non-
    // destructively; this method assumes the original is `float`, and so
    // iterates in reverse.
    //
    _layoutItems() {
      Array.from(this.itemElements).reverse().forEach((itemElement) => {
        if (!itemElement.hasAttribute(this.attrName('original-position'))) {
          itemElement.setAttribute(this.attrName('original-position'),
            getComputedStyle(itemElement).position);
        }
        let { offsetLeft, offsetTop, style } = itemElement;
        style.position = 'absolute';
        style.left = `${offsetLeft}px`;
        style.top = `${offsetTop}px`;
      });
      let { style } = this.element;
      style.width = `${this.metrics.wrapWidth}px`;
      style.height = `${this.metrics.wrapHeight}px`;
    }
    //
    // ___reLayoutItems__ wraps `_layoutItems` to be its idempotent version by
    // first resetting each item's to its `original-position`.
    //
    _reLayoutItems(completion) {
      if (this.expandedItemElement) {
        this.toggleItemExpansion(this.expandedItemElement, false, () => {
          this._reLayoutItems(completion);
        });
        return;
      }
      this._selectItemElements();
      this._updateMetrics();
      this.itemElements.forEach((itemElement) => {
        let { style } = itemElement;
        style.bottom = style.left = style.right = style.top = 'auto';
        style.position = itemElement.getAttribute(this.attrName('original-position'));
        itemElement.classList.remove(this.className('raw'));
      });
      this._layoutItems();
      if (completion) {
        completion();
      }
    }
    //
    // ___toggleNeighborItemsRecessed__ toggles the `-recessed` class on items
    // per the occlusion-causing expansion of the item at `index`.
    //
    _toggleNeighborItemsRecessed(index, recessed) {
      const { expandedScale, rowSize } = this.metrics;
      let dx = this._isRightEdgeItem(index) ? -1 : 1;
      let dy = this._isBottomEdgeItem(index) ? -1 : 1;
      let level = 1;
      let neighbors = [];
      while (level < expandedScale) {
        neighbors.push(
          this.itemElements[index + level * dx],
          this.itemElements[index + level * dy * rowSize],
          this.itemElements[index + level * (dy * rowSize + dx)]
        );
        level += 1;
      }
      neighbors.filter(n => !!n).forEach((itemElement) => {
        itemElement.classList.toggle(this.className('recessed'));
      });
    }
    //
    // ___updateMetrics__ builds the `metrics` around item and wrap as well as
    // row and column sizes. It does so by measuring sample elements and their
    // margins, as well as sizing the wrap (root element) to fit its items. As
    // such, this method isn't idempotent and expects to be followed by a call
    // to `_layoutItems`.
    //
    _updateMetrics({ hard } = { hard: false }) {
      if (hard) {
        const { itemElement, expandedItemElement } = this._getMetricSamples();
        this.metrics = {
          itemWidth: itemElement.offsetWidth,
          itemHeight: itemElement.offsetHeight,
          expandedWidth: expandedItemElement.offsetWidth,
          expandedHeight: expandedItemElement.offsetHeight,
          expandedScale: parseInt(this.cssVariable('item-expanded-scale')),
        };
      }
      let gutter = Math.round(parseFloat(
        getComputedStyle(this.sampleItemElement).marginRight
      ));
      let fullWidth = this.metrics.itemWidth + gutter;
      let fullHeight = this.metrics.itemHeight + gutter;

      let { style } = this.element;
      style.height = style.width = 'auto';

      let rowSize = parseInt(((this.element.offsetWidth + gutter) / fullWidth));
      let colSize = Math.ceil(this.itemElements.length / rowSize);
      Object.assign(this.metrics, { gutter, rowSize, colSize }, {
        wrapWidth: fullWidth * rowSize,
        wrapHeight: fullHeight * colSize,
      });
    }
  }
  //
  // § __Attaching__
  //
  return hlf.createExtension({
    name: 'mediaGrid',
    namespace: hlf.mediaGrid,
    apiClass: MediaGrid,
    autoBind: true,
    autoListen: true,
    baseMethodGroups: ['css', 'selection'],
    compactOptions: true,
  });
});
<|endoftext|>


<commit_before>/*======================================================
************   Messagebar   ************
======================================================*/
var Messagebar = function (container, params) {
    var defaults = {
        textarea: null,
        maxHeight: null,
    };
    params = params || {};
    for (var def in defaults) {
        if (typeof params[def] === 'undefined' || params[def] === null) {
            params[def] = defaults[def];
        }
    }

    // Instance
    var m = this;

    // Params
    m.params = params;

    // Container
    m.container = $(container);
    if (m.container.length === 0) return;

    // Textarea
    m.textarea = m.params.textarea ? $(m.params.textarea) : m.container.find('textarea');

    // Is In Page
    m.pageContainer = m.container.parents('.page').eq(0);
    m.pageContent = m.pageContainer.find('.page-content');

    // Initial Sizes
    m.pageContentPadding = parseInt(m.pageContent.css('padding-bottom'));
    m.initialBarHeight = m.container[0].offsetHeight;
    m.initialAreaHeight = m.textarea[0].offsetHeight;

    // Resize textarea
    m.sizeTextarea = function () {
        // Reset
        m.textarea.css({'height': ''});

        var height = m.textarea[0].offsetHeight;
        var diff = height - m.textarea[0].clientHeight;
        var scrollHeight = m.textarea[0].scrollHeight;

        // Update
        if (scrollHeight + diff > height) {
            var newAreaHeight = scrollHeight + diff;
            var newBarHeight = m.initialBarHeight + (newAreaHeight - m.initialAreaHeight);
            var maxBarHeight = m.params.maxHeight || m.container.parents('.view')[0].offsetHeight - 88;
            if (newBarHeight > maxBarHeight) {
                newBarHeight = parseInt(maxBarHeight, 10);
                newAreaHeight = newBarHeight - m.initialBarHeight + m.initialAreaHeight;
            }
            m.textarea.css('height', newAreaHeight + 'px');
            m.container.css('height', newBarHeight + 'px');
            if (m.pageContent.length > 0) {
                m.pageContent.css('padding-bottom', newBarHeight + 'px');
                m.pageContent.scrollTop(m.pageContent[0].scrollHeight - m.pageContent[0].offsetHeight);
            }
        }
        else {
            if (m.pageContent.length > 0) {
                m.container.css({'height': '', 'bottom': ''});
                m.pageContent.css({'padding-bottom': ''});
            }
        }
    };

    // Clear
    m.clear = function () {
        m.textarea.val('').trigger('change');
    };
    m.value = function (value) {
        if (typeof value === 'undefined') return m.textarea.val();
        else m.textarea.val(value).trigger('change');
    };

    // Handle textarea
    m.textareaTimeout = undefined;
    m.handleTextarea = function (e) {
        clearTimeout(m.textareaTimeout);
        m.textareaTimeout = setTimeout(function () {
            m.sizeTextarea();
        }, 0);
    };

    //Events
    function preventSubmit(e) {
        e.preventDefault();
    }

    m.attachEvents = function (destroy) {
        var method = destroy ? 'off' : 'on';
        m.container[method]('submit', preventSubmit);
        m.textarea[method]('change keydown keypress keyup paste cut', m.handleTextarea);
    };
    m.detachEvents = function () {
        m.attachEvents(true);
    };

    // Init Destroy
    m.init = function () {
        m.attachEvents();
    };
    m.destroy = function () {
        m.detachEvents();
        m = null;
    };

    // Init
    m.init();

    m.container[0].f7Searchbar = m;
    return m;
};
app.messagebar = function (container, params) {
    return new Messagebar(container, params);
};
app.initPageMessagebar = function (pageContainer) {
    pageContainer = $(pageContainer);
    var messagebar = pageContainer.hasClass('messagebar') ? pageContainer : pageContainer.find('.messagebar');
    if (messagebar.length === 0) return;
    if (!messagebar.hasClass('messagebar-init')) return;
    var mb = app.messagebar(messagebar, messagebar.dataset());

    // Destroy on page remove
    function pageBeforeRemove() {
        mb.destroy();
        pageContainer.off('pageBeforeRemove', pageBeforeRemove);
    }
    if (pageContainer.hasClass('page')) {
        pageContainer.on('pageBeforeRemove', pageBeforeRemove);
    }
};
app.destroyMessagebar = function (pageContainer) {
    pageContainer = $(pageContainer);
    var messagebar = pageContainer.hasClass('messagebar') ? pageContainer : pageContainer.find('.messagebar');
    if (messagebar.length === 0) return;
    if (messagebar[0].f7Messagebar) messagebar[0].f7Messagebar.destroy();
};<commit_msg>Fix instance name and remove method<commit_after>/*======================================================
************   Messagebar   ************
======================================================*/
var Messagebar = function (container, params) {
    var defaults = {
        textarea: null,
        maxHeight: null,
    };
    params = params || {};
    for (var def in defaults) {
        if (typeof params[def] === 'undefined' || params[def] === null) {
            params[def] = defaults[def];
        }
    }

    // Instance
    var m = this;

    // Params
    m.params = params;

    // Container
    m.container = $(container);
    if (m.container.length === 0) return;

    // Textarea
    m.textarea = m.params.textarea ? $(m.params.textarea) : m.container.find('textarea');

    // Is In Page
    m.pageContainer = m.container.parents('.page').eq(0);
    m.pageContent = m.pageContainer.find('.page-content');

    // Initial Sizes
    m.pageContentPadding = parseInt(m.pageContent.css('padding-bottom'));
    m.initialBarHeight = m.container[0].offsetHeight;
    m.initialAreaHeight = m.textarea[0].offsetHeight;

    // Resize textarea
    m.sizeTextarea = function () {
        // Reset
        m.textarea.css({'height': ''});

        var height = m.textarea[0].offsetHeight;
        var diff = height - m.textarea[0].clientHeight;
        var scrollHeight = m.textarea[0].scrollHeight;

        // Update
        if (scrollHeight + diff > height) {
            var newAreaHeight = scrollHeight + diff;
            var newBarHeight = m.initialBarHeight + (newAreaHeight - m.initialAreaHeight);
            var maxBarHeight = m.params.maxHeight || m.container.parents('.view')[0].offsetHeight - 88;
            if (newBarHeight > maxBarHeight) {
                newBarHeight = parseInt(maxBarHeight, 10);
                newAreaHeight = newBarHeight - m.initialBarHeight + m.initialAreaHeight;
            }
            m.textarea.css('height', newAreaHeight + 'px');
            m.container.css('height', newBarHeight + 'px');
            if (m.pageContent.length > 0) {
                m.pageContent.css('padding-bottom', newBarHeight + 'px');
                m.pageContent.scrollTop(m.pageContent[0].scrollHeight - m.pageContent[0].offsetHeight);
            }
        }
        else {
            if (m.pageContent.length > 0) {
                m.container.css({'height': '', 'bottom': ''});
                m.pageContent.css({'padding-bottom': ''});
            }
        }
    };

    // Clear
    m.clear = function () {
        m.textarea.val('').trigger('change');
    };
    m.value = function (value) {
        if (typeof value === 'undefined') return m.textarea.val();
        else m.textarea.val(value).trigger('change');
    };

    // Handle textarea
    m.textareaTimeout = undefined;
    m.handleTextarea = function (e) {
        clearTimeout(m.textareaTimeout);
        m.textareaTimeout = setTimeout(function () {
            m.sizeTextarea();
        }, 0);
    };

    //Events
    function preventSubmit(e) {
        e.preventDefault();
    }

    m.attachEvents = function (destroy) {
        var method = destroy ? 'off' : 'on';
        m.container[method]('submit', preventSubmit);
        m.textarea[method]('change keydown keypress keyup paste cut', m.handleTextarea);
    };
    m.detachEvents = function () {
        m.attachEvents(true);
    };

    // Init Destroy
    m.init = function () {
        m.attachEvents();
    };
    m.destroy = function () {
        m.detachEvents();
        m = null;
    };

    // Init
    m.init();

    m.container[0].f7Messagebar = m;
    return m;
};
app.messagebar = function (container, params) {
    return new Messagebar(container, params);
};
app.initPageMessagebar = function (pageContainer) {
    pageContainer = $(pageContainer);
    var messagebar = pageContainer.hasClass('messagebar') ? pageContainer : pageContainer.find('.messagebar');
    if (messagebar.length === 0) return;
    if (!messagebar.hasClass('messagebar-init')) return;
    var mb = app.messagebar(messagebar, messagebar.dataset());

    // Destroy on page remove
    function pageBeforeRemove() {
        mb.destroy();
        pageContainer.off('pageBeforeRemove', pageBeforeRemove);
    }
    if (pageContainer.hasClass('page')) {
        pageContainer.on('pageBeforeRemove', pageBeforeRemove);
    }
};<|endoftext|>


<commit_before>'use strict'

import React, { Component } from 'react'
import snippet from './snippet'

export class Navigation extends Component {
  static propTypes = {
    page: React.PropTypes.string
  }

  constructor (props) {
    super(props)

    this.state = {
      page: this.props.page
    }
  }

  navigateTabs (evt) {
    evt = evt || window.event

    evt.preventDefault()

    this.changeTabs()
    window.history.pushState({
      page: this.state.page
    }, null, evt.target.href)
  }

  changeTabs () {
    let bookmarks = document.querySelector('[data-hook="bookmarks"]')
    let colophon = document.querySelector('[data-hook="colophon"]')

    if (this.state.page === '') {
      bookmarks.classList.remove('active')
      colophon.classList.add('active')
      window.document.title = 'Colophon – bkmrkd'
      this.setState({
        page: 'colophon'
      })
    } else {
      colophon.classList.remove('active')
      bookmarks.classList.add('active')
      window.document.title = 'bkmrkd'
      this.setState({
        page: ''
      })
    }
  }

  componentWillMount () {
    if (typeof window !== 'undefined') {
      window.addEventListener('popstate', function (evt) {
        evt = evt || window.event

        this.changeTabs()
      }.bind(this))
    }
  }

  render () {
    const bkmrkClassString = this.state.page === '' ? 'active' : ''
    const colophonClassString = this.state.page === 'colophon' ? 'active' : ''

    return (

          bkmrks

          colophon

          bookmarklet

    )
  }
}
<commit_msg>ES6 classes -> CreateClass<commit_after>'use strict'

import React, { CreateClass, PropTypes } from 'react'
import snippet from './snippet'

export default CreateClass({
  propTypes: {
    page: PropTypes.string
  },
  getInitialState: function () {
    return {
      page: this.props.page
    }
  },
  navigateTabs: function (evt) {
    evt = evt || window.event

    evt.preventDefault()

    this.changeTabs()

    window.history.pushState({
      page: this.state.page
    }, null, evt.target.href)
  },
  changeTabs: function () {
    let bookmarks = document.querySelector('[data-hook="bookmarks"]')
    let colophon = document.querySelector('[data-hook="colophon"]')

    if (this.state.page === '') {
      bookmarks.classList.remove('active')
      colophon.classList.add('active')
      window.document.title = 'Colophon – bkmrkd'
      this.setState({
        page: 'colophon'
      })
    } else {
      colophon.classList.remove('active')
      bookmarks.classList.add('active')
      window.document.title = 'bkmrkd'
      this.setState({
        page: ''
      })
    }
  },
  componentWillMount: function () {
    if (typeof window !== 'undefined') {
      window.addEventListener('popstate', function (evt) {
        evt = evt || window.event

        this.changeTabs()
      }.bind(this))
    }
  },
  render: function () {
    const bkmrkClassString = this.state.page === '' ? 'active' : ''
    const colophonClassString = this.state.page === 'colophon' ? 'active' : ''

    return (

          bkmrks

          colophon

          bookmarklet

    )
  }
})
<|endoftext|>


<commit_before>(function (){
	'use strict';

    var moduleName = 'ng-cooltip';

	angular.module(moduleName, [])

	.directive('cooltip', [function () {
		return {
			restrict: 'AE',
			scope: {
				item:    '=cooltipItem',
				content: '=cooltipContent',
				effect:  '=cooltipEffect'
			},
			controller: ['$scope', '$sce', function ($scope, $sce) {
				$scope.trustedHtmlContent = $sce.trustAsHtml($scope.content);
				$scope.effect = ($scope.effect > 0 && $scope.effect < 6) ? $scope.effect : 1;
			}],
			templateUrl: function (elem, attrs) {
				return (attrs.cooltipType || 'classic') + '.html';
			}
		};
	}])

	.run(['$templateCache', function($templateCache) {

	  $templateCache.put('classic.html', [
      '',
        '',
    	  	'',
    	  		'{{ item }}',
    	  		'',
    	  			'',
    	  		'',
    	  	'',
        '',
      ''
	  ].join('\n'));

    $templateCache.put('box.html', [
      '',
        '',
          '',
            '{{ item }}',
            '',
              '',
            '',
          '',
        '',
      ''
    ].join('\n'));

	  $templateCache.put('round.html', [
      '',
        '',
  	  	  ' {{ item }}',
  	  		 '',
  	  	  '',
        '',
      ''
	  ].join('\n'));

	}]);

	module.exports = moduleName;

})();<commit_msg>Remove module exports and used controllerAs approach<commit_after>(function (){
	'use strict';

	angular.module('ng-cooltip', [])

	.directive('cooltip', [function () {
		return {
			restrict: 'AE',
			scope: {
				item:    '=cooltipItem',
				content: '=cooltipContent',
				effect:  '=cooltipEffect'
			},
			controller: coolTipController,
      controllerAs: 'vm',
      bindToController: true,
			templateUrl: templateUrl
		};
	}])

	.run(runTemplateCache);

  coolTipController.$inject = ['$sce'];
  function coolTipController($sce) {
    this.trustedHtmlContent = $sce.trustAsHtml(this.content);
    this.effect = (this.effect > 0 && this.effect < 6) ? this.effect : 1;
  }

  function templateUrl(elem, attrs) {
    return (attrs.cooltipType || 'classic') + '.html';
  }

  runTemplateCache.$inject = ['$templateCache'];
  function runTemplateCache($templateCache) {
    $templateCache.put('classic.html', [
      '',
        '',
          '',
            '{{ vm.item }}',
            '',
              '',
            '',
          '',
        '',
      ''
    ].join('\n'));

    $templateCache.put('box.html', [
      '',
        '',
          '',
            '{{ vm.item }}',
            '',
              '',
            '',
          '',
        '',
      ''
    ].join('\n'));

    $templateCache.put('round.html', [
      '',
        '',
          ' {{ vm.item }}',
           '',
          '',
        '',
      ''
    ].join('\n'));
  }

})();
<|endoftext|>


<commit_before>// ==========================================================================
// rangetouch.js v0.0.8
// Making <input type="range"> work on touch devices
// https://github.com/selz/rangetouch
// License: The MIT License (MIT)
// ==========================================================================

;(function(root, factory) {
    'use strict';
    /*global define,module*/

    if (typeof module === 'object' && typeof module.exports === 'object') {
        // Node, CommonJS-like
        module.exports = factory(root, document);
    } else if (typeof define === 'function' && define.amd) {
        // AMD
        define(null, function() { factory(root, document); });
    } else {
        // Browser globals (root is window)
        root.rangetouch = factory(root, document);
    }
}(typeof window !== 'undefined' ? window : this, function(window, document) {
    'use strict';

    // Default config
    var settings = {
        enabled:        true,
        selectors: {
            range:      '[type="range"]'
        },
        thumbWidth:     15,
        events: {
            start:      'touchstart',
            move:       'touchmove',
            end:        'touchend'
        }
    };

    // Bind an event listener
    function _on(element, type, listener) {
        element.addEventListener(type, listener, false);
    }

    // Get the number of decimal places
    function getDecimalPlaces(value) {
        var match = ('' + value).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);

        if (!match) { return 0; }

        return Math.max(
            0,
            // Number of digits right of decimal point.
            (match[1] ? match[1].length : 0) -
            // Adjust for scientific notation.
            (match[2] ? +match[2] : 0)
        );
    }

    // Round to the nearest step
    function roundToStep(number, step) {
        if(step < 1) {
            var places = getDecimalPlaces(parseInt(step));
            return parseFloat(number.toFixed(places));
        }
        return (Math.round(number / step) * step);
    }

    // Get the value based on touch position
    function getValue(event) {
        var input   = event.target,
            touch   = event.changedTouches[0],
            min     = parseFloat(input.getAttribute('min')) || 0,
            max     = parseFloat(input.getAttribute('max')) || 100,
            step    = parseFloat(input.getAttribute('step')) || 1,
            delta   = max - min;

        // Calculate percentage
        var percent,
            clientRect   = input.getBoundingClientRect(),
            thumbWidth   = (((100 / clientRect.width) * (settings.thumbWidth / 2)) / 100);

        // Determine left percentage
        percent = ((100 / clientRect.width) * (touch.clientX - clientRect.left));

        // Don't allow outside bounds
        if (percent < 0) { percent = 0; }
        else if (percent > 100) { percent = 100; }

        // Factor in the thumb offset
        if(percent < 50) {
            percent -= ((100 - (percent * 2)) * thumbWidth);
        }
        else if(percent > 50) {
            percent += (((percent - 50) * 2) * thumbWidth);
        }

        // Find the closest step to the mouse position
        return min + roundToStep(delta * (percent / 100), step);
    }

    // Update range value based on position
    function setValue(event) {
        // If not enabled, bail
        if (!settings.enabled || event.target.type !== 'range') {
            return;
        }

        //console.log(event);

        // Prevent text highlight on iOS
        event.preventDefault();

        // Set value
        event.target.value = getValue(event);

        // Trigger input event
        _triggerEvent(event.target, (event.type === settings.events.end ? 'change' : 'input'));
    }

    // Event listeners
    function listeners() {
        _on(document.body, settings.events.start, setValue);
        _on(document.body, settings.events.move, setValue);
        _on(document.body, settings.events.end, setValue);
    }

    // Trigger event
    function _triggerEvent(element, eventName, properties) {
        element.dispatchEvent(new CustomEvent(eventName, properties));
    }

    // Expose setup function
    (function() {
        // Bail if not a touch device
        if (!('ontouchstart' in document.documentElement)) {
            return;
        }

        // Find all inputs
        var inputs = document.querySelectorAll(settings.selectors.range);

        // Set touchAction to prevent delays
        for (var i = inputs.length - 1; i >= 0; i--) {
            inputs[i].style.touchAction = 'manipulation';
            inputs[i].style.webkitUserSelect = 'none';
        }

        // Listen for events
        listeners();
    })();

    return {
        set: function(setting, value) {
            settings[setting] = value;
        }
    };
}));

// Custom event polyfill
// ---------------------------------
// https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
(function () {
    'use strict';

    if (typeof window.CustomEvent === 'function') {
        return false;
    }

    function CustomEvent (event, params) {
        params = params || { bubbles: false, cancelable: false, detail: undefined };
        var evt = document.createEvent('CustomEvent');
        evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
        return evt;
    }

    CustomEvent.prototype = window.Event.prototype;

    window.CustomEvent = CustomEvent;
})();
<commit_msg>Removed console log<commit_after>// ==========================================================================
// rangetouch.js v0.0.8
// Making <input type="range"> work on touch devices
// https://github.com/selz/rangetouch
// License: The MIT License (MIT)
// ==========================================================================

;(function(root, factory) {
    'use strict';
    /*global define,module*/

    if (typeof module === 'object' && typeof module.exports === 'object') {
        // Node, CommonJS-like
        module.exports = factory(root, document);
    } else if (typeof define === 'function' && define.amd) {
        // AMD
        define(null, function() { factory(root, document); });
    } else {
        // Browser globals (root is window)
        root.rangetouch = factory(root, document);
    }
}(typeof window !== 'undefined' ? window : this, function(window, document) {
    'use strict';

    // Default config
    var settings = {
        enabled:        true,
        selectors: {
            range:      '[type="range"]'
        },
        thumbWidth:     15,
        events: {
            start:      'touchstart',
            move:       'touchmove',
            end:        'touchend'
        }
    };

    // Bind an event listener
    function _on(element, type, listener) {
        element.addEventListener(type, listener, false);
    }

    // Get the number of decimal places
    function getDecimalPlaces(value) {
        var match = ('' + value).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);

        if (!match) { return 0; }

        return Math.max(
            0,
            // Number of digits right of decimal point.
            (match[1] ? match[1].length : 0) -
            // Adjust for scientific notation.
            (match[2] ? +match[2] : 0)
        );
    }

    // Round to the nearest step
    function roundToStep(number, step) {
        if(step < 1) {
            var places = getDecimalPlaces(parseInt(step));
            return parseFloat(number.toFixed(places));
        }
        return (Math.round(number / step) * step);
    }

    // Get the value based on touch position
    function getValue(event) {
        var input   = event.target,
            touch   = event.changedTouches[0],
            min     = parseFloat(input.getAttribute('min')) || 0,
            max     = parseFloat(input.getAttribute('max')) || 100,
            step    = parseFloat(input.getAttribute('step')) || 1,
            delta   = max - min;

        // Calculate percentage
        var percent,
            clientRect   = input.getBoundingClientRect(),
            thumbWidth   = (((100 / clientRect.width) * (settings.thumbWidth / 2)) / 100);

        // Determine left percentage
        percent = ((100 / clientRect.width) * (touch.clientX - clientRect.left));

        // Don't allow outside bounds
        if (percent < 0) { percent = 0; }
        else if (percent > 100) { percent = 100; }

        // Factor in the thumb offset
        if(percent < 50) {
            percent -= ((100 - (percent * 2)) * thumbWidth);
        }
        else if(percent > 50) {
            percent += (((percent - 50) * 2) * thumbWidth);
        }

        // Find the closest step to the mouse position
        return min + roundToStep(delta * (percent / 100), step);
    }

    // Update range value based on position
    function setValue(event) {
        // If not enabled, bail
        if (!settings.enabled || event.target.type !== 'range') {
            return;
        }

        // Prevent text highlight on iOS
        event.preventDefault();

        // Set value
        event.target.value = getValue(event);

        // Trigger input event
        _triggerEvent(event.target, (event.type === settings.events.end ? 'change' : 'input'));
    }

    // Event listeners
    function listeners() {
        _on(document.body, settings.events.start, setValue);
        _on(document.body, settings.events.move, setValue);
        _on(document.body, settings.events.end, setValue);
    }

    // Trigger event
    function _triggerEvent(element, eventName, properties) {
        element.dispatchEvent(new CustomEvent(eventName, properties));
    }

    // Expose setup function
    (function() {
        // Bail if not a touch device
        if (!('ontouchstart' in document.documentElement)) {
            return;
        }

        // Find all inputs
        var inputs = document.querySelectorAll(settings.selectors.range);

        // Set touchAction to prevent delays
        for (var i = inputs.length - 1; i >= 0; i--) {
            inputs[i].style.touchAction = 'manipulation';
            inputs[i].style.webkitUserSelect = 'none';
        }

        // Listen for events
        listeners();
    })();

    return {
        set: function(setting, value) {
            settings[setting] = value;
        }
    };
}));

// Custom event polyfill
// ---------------------------------
// https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
(function () {
    'use strict';

    if (typeof window.CustomEvent === 'function') {
        return false;
    }

    function CustomEvent (event, params) {
        params = params || { bubbles: false, cancelable: false, detail: undefined };
        var evt = document.createEvent('CustomEvent');
        evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
        return evt;
    }

    CustomEvent.prototype = window.Event.prototype;

    window.CustomEvent = CustomEvent;
})();
<|endoftext|>


<commit_before>const RaceDates = require('./raceDates');

module.exports = function urlManager(opts) {

	const stateAbbr = opts.stateAbbr;
	const partyAbbr = opts.partyAbbr;
	const level     = opts.level;

	// get race for this state-party combination
	const date = RaceDates[`${stateAbbr}-${partyAbbr}`.toLowerCase()];

	// construct the api url
	// const baseUrl = 'http://dev.tomcat.boston.com/electionapi/elections/';
	const baseUrl = 'http://devweb.bostonglobe.com/electionapi/elections/';
	const url     = `${baseUrl}${date}?statePostal=${stateAbbr}&party=${partyAbbr}&level=${level}`;

	return url;

};
<commit_msg>Use qaweb for dev<commit_after>const RaceDates = require('./raceDates');

module.exports = function urlManager(opts) {

	const stateAbbr = opts.stateAbbr;
	const partyAbbr = opts.partyAbbr;
	const level     = opts.level;

	// get race for this state-party combination
	const date = RaceDates[`${stateAbbr}-${partyAbbr}`.toLowerCase()];

	// construct the api url
	// const baseUrl = 'http://dev.tomcat.boston.com/electionapi/elections/';
	// const baseUrl = 'http://devweb.bostonglobe.com/electionapi/elections/';
	const baseUrl = 'http://qaweb.bostonglobe.com/electionapi/elections/';
	const url     = `${baseUrl}${date}?statePostal=${stateAbbr}&party=${partyAbbr}&level=${level}`;

	return url;

};
<|endoftext|>


<commit_before>// The iFrame which holds the intermediate
var iFrame = $("
").attr({
  "id": "factlink-modal-frame"
});
iFrame.hide();
iFrame.appendTo(Factlink.el);

Factlink.hideDimmer = function () {
  iFrame.css('background', 'none');
};

Factlink.showInfo = function(factId, successCallback) {
  Factlink.remote.showFactlink(factId, function successFn() {
    Factlink.modal.show.method();
    Factlink.trigger('modalOpened');

    if ($.isFunction(successCallback)) {
      successCallback();
    }
  });
};

var clickHandler = function() {
  Factlink.modal.hide.method();
};

var bindClick = function() {
  $(document).bind('click', clickHandler);
};

var unbindClick = function() {
  $(document).unbind('click', clickHandler);
};

// Object which holds the methods that can be called from the intermediate iframe
// These methods are also used by the internal scripts and can be called through
// Factlink.modal.FUNCTION.method() because easyXDM changes the object structure
Factlink.modal = {
  hide: function() {
    unbindClick();
    iFrame.fadeOut('fast');

    Factlink.trigger('modalClosed');
  },
  show: function() {
    bindClick();
    iFrame.fadeIn('fast');
  },
  highlightNewFactlink: function(fact, id, opinions) {
    var fct = Factlink.selectRanges(Factlink.search(fact), id, opinions);

    $.merge(Factlink.Facts, fct);
    //@TODO: Authority & opinions need to be added back in

    Factlink.trigger("factlinkAdded");

    Factlink.modal.hide.method();

    $('#fl').append("
Factlink is created!
");
    $('#fl .fl-message').fadeIn('slow');
    setTimeout(function() {
      $('#fl .fl-message').fadeOut('slow');
    }, 2545);
    return fct;
  },
  stopHighlightingFactlink: function(id) {
    $('span.factlink[data-factid=' + id + ']').each(function(i, val) {
      $(val).contents().unwrap();
    });
  },
  trigger: function (e) {
    Factlink.trigger(e);
  }
};
<commit_msg>Use the new Factlink.Views.Notification<commit_after>// The iFrame which holds the intermediate
var iFrame = $("
").attr({
  "id": "factlink-modal-frame"
});
iFrame.hide();
iFrame.appendTo(Factlink.el);

Factlink.hideDimmer = function () {
  iFrame.css('background', 'none');
};

Factlink.showInfo = function(factId, successCallback) {
  Factlink.remote.showFactlink(factId, function successFn() {
    Factlink.modal.show.method();
    Factlink.trigger('modalOpened');

    if ($.isFunction(successCallback)) {
      successCallback();
    }
  });
};

var clickHandler = function() {
  Factlink.modal.hide.method();
};

var bindClick = function() {
  $(document).bind('click', clickHandler);
};

var unbindClick = function() {
  $(document).unbind('click', clickHandler);
};

// Object which holds the methods that can be called from the intermediate iframe
// These methods are also used by the internal scripts and can be called through
// Factlink.modal.FUNCTION.method() because easyXDM changes the object structure
Factlink.modal = {
  hide: function() {
    unbindClick();
    iFrame.fadeOut('fast');

    Factlink.trigger('modalClosed');
  },
  show: function() {
    bindClick();
    iFrame.fadeIn('fast');
  },
  highlightNewFactlink: function(fact, id, opinions) {
    var fct = Factlink.selectRanges(Factlink.search(fact), id, opinions);

    $.merge(Factlink.Facts, fct);
    //@TODO: Authority & opinions need to be added back in

    Factlink.trigger("factlinkAdded");

    Factlink.modal.hide.method();

    var created_message = new Factlink.Views.Notification({
      message: 'Factlink loaded!',
      type_classes: 'fl-message-success fl-message-icon-time'
    });

    created_message.render();

    return fct;
  },
  stopHighlightingFactlink: function(id) {
    $('span.factlink[data-factid=' + id + ']').each(function(i, val) {
      $(val).contents().unwrap();
    });
  },
  trigger: function (e) {
    Factlink.trigger(e);
  }
};
<|endoftext|>


<commit_before>function evaluate() {
    var anim = {};
    var ops;
    var init;

    if(window.init) {
        ops = [];
        init = window.init(cube(ops));
        anim.init = ops;
    }

    if(window.effect) {
        ops = [];
        window.effect(cube(ops), init);
        anim.effect = ops;
    }

    return anim;

    function cube(ops) {
        var ret = function() {
            var o = {};

            o.on = function() {
                ops.push('on');
            };
            o.off = function() {
                ops.push('off');
            };

            return o;
        };

        // TODO: pass dims here in some nice way
        ret.xyz = {
            x: 8,
            y: 8,
            z: 8
        };

        return ret;
    }
}

function inject(src, target) {
    for(var k in src) {
        target[k] = src[k];
    }
}
<commit_msg>Attach x, y, z properties to cube<commit_after>function evaluate() {
    var anim = {};
    var ops;
    var init;

    if(window.init) {
        ops = [];
        init = window.init(cube(ops));
        anim.init = ops;
    }

    if(window.effect) {
        ops = [];
        window.effect(cube(ops), init);
        anim.effect = ops;
    }

    return anim;

    function cube(ops) {
        // TODO: pass these as params to evaluate
        var x = 8;
        var y = 8;
        var z = 8;
        var ret = function() {
            var o = {};

            o.on = function() {
                ops.push('on');
            };
            o.off = function() {
                ops.push('off');
            };

            return o;
        };

        ret.xyz = {
            x: x,
            y: y,
            z: z
        };

        ret.x = x;
        ret.y = y;
        ret.z = z;

        return ret;
    }
}

function inject(src, target) {
    for(var k in src) {
        target[k] = src[k];
    }
}
<|endoftext|>