<commit_before>;(function () {
  var langPickerTogglerElement = document.querySelector('.lang-picker-toggler')
  var langPickerElement = document.querySelector('.lang-picker')
  var langElements = langPickerElement.querySelectorAll('button')
  // Get the current URL language
  var currentLang = window.location.pathname.split('/')[1] || 'en'
  var currentLangElement = null

  Array.prototype.forEach.call(langElements, function (el) {
    if (el.getAttribute('data-lang') !== currentLang) {
      el.addEventListener('click', function (e) {
        var newLocale = (e.target && e.target.dataset && e.target.dataset.lang) || 'en'
        window.location.assign(window.location.pathname.replace(/\/[a-zA-Z-]+/, '/' + newLocale))
      })
    } else {
      currentLangElement = el
    }
  })

  langPickerTogglerElement.setAttribute('title', currentLangElement.textContent)

  // Remove the current selected language item, because we don't need to choose it
  // any more unless we want to switch to a new language
  langPickerElement.removeChild(currentLangElement.parentNode)

  langPickerTogglerElement.addEventListener('click', function () {
    langPickerElement.classList.toggle('hidden')
    const isAriaExpanded = langPickerTogglerElement.getAttribute('aria-expanded') === 'true'
    langPickerTogglerElement.setAttribute('aria-expanded', !isAriaExpanded)
  })
})()

;(function () {
  var scrollToTop = document.getElementById('scroll-to-top');

  (window.onscroll = function () {
    window.requestAnimationFrame(function () {
      scrollToTop.style.display = window.pageYOffset > window.innerHeight ? 'block' : 'none'
    })
  })()

  scrollToTop.addEventListener('click', function (e) {
    e.preventDefault()
    window.scrollTo(0, 0)
  })
})()

;(function () {
  var contributorCard = document.querySelector('.contributor-card')

  if (!contributorCard) {
    return
  }

  var contributorAvatar = contributorCard.querySelector('#contributor-avatar')
  var contributorUsername = contributorCard.querySelector('#contributor-username')
  var contributorContributions = contributorCard.querySelector('#contributor-contributions')
  var loadingSpinner = contributorCard.querySelector('.spinner-border')

  if (window.IntersectionObserver) {
    var observer = new window.IntersectionObserver(function (entries) {
      entries.forEach(function (entry) {
        if (entry.intersectionRatio > 0.5) {
          // In viewport, fetch a random contributor
          fetchRandomContributor()

          observer.unobserve(entry.target)
        }
      })
    },
    { threshold: 0.5 }
    )

    observer.observe(document.querySelector('footer'))
  } else {
    // Does not support IntersectionObserver
    fetchRandomContributor()
  }

  function fetchRandomContributor () {
    var maxContributors
    var fetchDate
    var needToRefetch = false

    if (window.localStorage) {
      maxContributors = window.localStorage.getItem('max_contributors')
      fetchDate = parseInt(window.localStorage.getItem('fetch_date'), 10)
    }

    // If fetch date is a month old (2592000000 ms === 30 days)
    if (Date.now() - fetchDate >= 2592000000) {
      needToRefetch = true
    }

    // If localStorage and data is less than 1 month old, fetch 1 time
    if (maxContributors && !needToRefetch) {
      getContributor(Math.floor(Math.random() * Math.floor(parseInt(maxContributors))) + 1)
    } else {
      getMaxContributors(function (randomPage, lastPage) {
        getContributor(randomPage)

        if (window.localStorage) {
          window.localStorage.setItem('max_contributors', lastPage)
        }
      })
    }
  }

  function getMaxContributors (callback) {
    var xhr = new window.XMLHttpRequest()
    xhr.open('GET', 'https://api.github.com/repos/nodejs/node/contributors?per_page=1', true)

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          // Get Headers Links last page to generate a random contributor
          var links = linkParser(xhr.getResponseHeader('Link'))
          var randomPage = Math.floor(Math.random() * Math.floor(parseInt(links.last.page, 10))) + 1

          if (window.localStorage) {
            window.localStorage.setItem('fetch_date', Date.now())
          }
          callback(randomPage, links.last.page)
        } else {
          return contributorCard.parentNode.removeChild(contributorCard)
        }
      }
    }

    xhr.send()
  }

  function getContributor (randomPage) {
    var xhr = new window.XMLHttpRequest()
    xhr.open('GET', 'https://api.github.com/repos/nodejs/node/contributors?per_page=1&page=' + randomPage, true)

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          var contributor = JSON.parse(xhr.responseText)[0]

          // Remove loading spinner and show avatar
          loadingSpinner.parentNode.removeChild(loadingSpinner)
          contributorAvatar.classList.remove('hidden')
          // Set new values
          contributorAvatar.src = contributor.avatar_url + '&s=80'
          contributorAvatar.parentElement.href = contributor.html_url
          contributorUsername.textContent = contributor.login
          contributorUsername.href = contributor.html_url
          contributorContributions.textContent = contributor.contributions + ' contributions'
          contributorContributions.parentElement.href = 'https://github.com/nodejs/node/commits?author=' + contributor.login
        } else {
          return contributorCard.parentNode.removeChild(contributorCard)
        }
      }
    }

    xhr.send()
  }

  function linkParser (linkHeader) {
    var regex = /<([^?]+\?per_page=1&[a-z]+=([\d]+))>;[\s]*rel="([a-z]+)"/g
    var array = []
    var object = {}

    while ((array = regex.exec(linkHeader)) !== null) {
      object[array[3]] = {
        url: array[1],
        page: array[2]
      }
    }

    return object
  }
})()

;(function (d, n) {
  'use strict'

  var osMatch = n.platform.match(/(Win|Mac|Linux)/)
  var os = (osMatch && osMatch[1]) || ''
  var arch = n.userAgent.match(/x86_64|Win64|WOW64/) ||
    n.cpuClass === 'x64'
    ? 'x64'
    : 'x86'
  var text = 'textContent' in d ? 'textContent' : 'innerText'
  var buttons = d.querySelectorAll('.home-downloadbutton')
  var downloadHead = d.getElementById('home-downloadhead')
  var dlLocal

  function versionIntoHref (nodeList, filename) {
    var linkEls = Array.prototype.slice.call(nodeList)
    var version
    var el

    for (var i = 0; i < linkEls.length; i++) {
      version = linkEls[i].getAttribute('data-version')
      el = linkEls[i]

      // Windows 64-bit files for 0.x.x need to be prefixed with 'x64/'
      if (os === 'Win' && (version[1] === '0' && arch === 'x64')) {
        el.href += arch + '/'
      }

      el.href += filename.replace('%version%', version)
    }
  }

  if (downloadHead && buttons) {
    dlLocal = downloadHead.getAttribute('data-dl-local')
    switch (os) {
      case 'Mac':
        versionIntoHref(buttons, 'node-%version%.pkg')
        downloadHead[text] = dlLocal + ' macOS (x64)'
        break
      case 'Win':
        versionIntoHref(buttons, 'node-%version%-' + arch + '.msi')
        downloadHead[text] = dlLocal + ' Windows (' + arch + ')'
        break
      case 'Linux':
        versionIntoHref(buttons, 'node-%version%-linux-x64.tar.xz')
        downloadHead[text] = dlLocal + ' Linux (x64)'
        break
    }
  }

  // Windows button on download page
  var winButton = d.getElementById('windows-downloadbutton')
  if (winButton && os === 'Win') {
    var winText = winButton.getElementsByTagName('p')[0]
    winButton.href = winButton.href.replace(/x(86|64)/, arch)
    winText[text] = winText[text].replace(/x(86|64)/, arch)
  }
})(document, navigator)
<commit_msg>fixture of warnings in standard check of js (#3697)<commit_after>/* eslint-disable no-var */
// Notice: IE 10 and below is still supported, so disable eslint for the file
// when checking the "var"
;(function () {
  var langPickerTogglerElement = document.querySelector('.lang-picker-toggler')
  var langPickerElement = document.querySelector('.lang-picker')
  var langElements = langPickerElement.querySelectorAll('button')
  // Get the current URL language
  var currentLang = window.location.pathname.split('/')[1] || 'en'
  var currentLangElement = null

  Array.prototype.forEach.call(langElements, function (el) {
    if (el.getAttribute('data-lang') !== currentLang) {
      el.addEventListener('click', function (e) {
        var newLocale = (e.target && e.target.dataset && e.target.dataset.lang) || 'en'
        window.location.assign(window.location.pathname.replace(/\/[a-zA-Z-]+/, '/' + newLocale))
      })
    } else {
      currentLangElement = el
    }
  })

  langPickerTogglerElement.setAttribute('title', currentLangElement.textContent)

  // Remove the current selected language item, because we don't need to choose it
  // any more unless we want to switch to a new language
  langPickerElement.removeChild(currentLangElement.parentNode)

  langPickerTogglerElement.addEventListener('click', function () {
    langPickerElement.classList.toggle('hidden')
    const isAriaExpanded = langPickerTogglerElement.getAttribute('aria-expanded') === 'true'
    langPickerTogglerElement.setAttribute('aria-expanded', !isAriaExpanded)
  })
})()

;(function () {
  var scrollToTop = document.getElementById('scroll-to-top');

  (window.onscroll = function () {
    window.requestAnimationFrame(function () {
      scrollToTop.style.display = window.pageYOffset > window.innerHeight ? 'block' : 'none'
    })
  })()

  scrollToTop.addEventListener('click', function (e) {
    e.preventDefault()
    window.scrollTo(0, 0)
  })
})()

;(function () {
  var contributorCard = document.querySelector('.contributor-card')

  if (!contributorCard) {
    return
  }

  var contributorAvatar = contributorCard.querySelector('#contributor-avatar')
  var contributorUsername = contributorCard.querySelector('#contributor-username')
  var contributorContributions = contributorCard.querySelector('#contributor-contributions')
  var loadingSpinner = contributorCard.querySelector('.spinner-border')

  if (window.IntersectionObserver) {
    var observer = new window.IntersectionObserver(function (entries) {
      entries.forEach(function (entry) {
        if (entry.intersectionRatio > 0.5) {
          // In viewport, fetch a random contributor
          fetchRandomContributor()

          observer.unobserve(entry.target)
        }
      })
    },
    { threshold: 0.5 }
    )

    observer.observe(document.querySelector('footer'))
  } else {
    // Does not support IntersectionObserver
    fetchRandomContributor()
  }

  function fetchRandomContributor () {
    var maxContributors
    var fetchDate
    var needToRefetch = false

    if (window.localStorage) {
      maxContributors = window.localStorage.getItem('max_contributors')
      fetchDate = parseInt(window.localStorage.getItem('fetch_date'), 10)
    }

    // If fetch date is a month old (2592000000 ms === 30 days)
    if (Date.now() - fetchDate >= 2592000000) {
      needToRefetch = true
    }

    // If localStorage and data is less than 1 month old, fetch 1 time
    if (maxContributors && !needToRefetch) {
      getContributor(Math.floor(Math.random() * Math.floor(parseInt(maxContributors))) + 1)
    } else {
      getMaxContributors(function (randomPage, lastPage) {
        getContributor(randomPage)

        if (window.localStorage) {
          window.localStorage.setItem('max_contributors', lastPage)
        }
      })
    }
  }

  function getMaxContributors (callback) {
    var xhr = new window.XMLHttpRequest()
    xhr.open('GET', 'https://api.github.com/repos/nodejs/node/contributors?per_page=1', true)

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          // Get Headers Links last page to generate a random contributor
          var links = linkParser(xhr.getResponseHeader('Link'))
          var randomPage = Math.floor(Math.random() * Math.floor(parseInt(links.last.page, 10))) + 1

          if (window.localStorage) {
            window.localStorage.setItem('fetch_date', Date.now())
          }
          callback(randomPage, links.last.page)
        } else {
          return contributorCard.parentNode.removeChild(contributorCard)
        }
      }
    }

    xhr.send()
  }

  function getContributor (randomPage) {
    var xhr = new window.XMLHttpRequest()
    xhr.open('GET', 'https://api.github.com/repos/nodejs/node/contributors?per_page=1&page=' + randomPage, true)

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          var contributor = JSON.parse(xhr.responseText)[0]

          // Remove loading spinner and show avatar
          loadingSpinner.parentNode.removeChild(loadingSpinner)
          contributorAvatar.classList.remove('hidden')
          // Set new values
          contributorAvatar.src = contributor.avatar_url + '&s=80'
          contributorAvatar.parentElement.href = contributor.html_url
          contributorUsername.textContent = contributor.login
          contributorUsername.href = contributor.html_url
          contributorContributions.textContent = contributor.contributions + ' contributions'
          contributorContributions.parentElement.href = 'https://github.com/nodejs/node/commits?author=' + contributor.login
        } else {
          return contributorCard.parentNode.removeChild(contributorCard)
        }
      }
    }

    xhr.send()
  }

  function linkParser (linkHeader) {
    var regex = /<([^?]+\?per_page=1&[a-z]+=([\d]+))>;[\s]*rel="([a-z]+)"/g
    var array = []
    var object = {}

    while ((array = regex.exec(linkHeader)) !== null) {
      object[array[3]] = {
        url: array[1],
        page: array[2]
      }
    }

    return object
  }
})()

;(function (d, n) {
  'use strict'

  var osMatch = n.platform.match(/(Win|Mac|Linux)/)
  var os = (osMatch && osMatch[1]) || ''
  var arch = n.userAgent.match(/x86_64|Win64|WOW64/) ||
    n.cpuClass === 'x64'
    ? 'x64'
    : 'x86'
  var text = 'textContent' in d ? 'textContent' : 'innerText'
  var buttons = d.querySelectorAll('.home-downloadbutton')
  var downloadHead = d.getElementById('home-downloadhead')
  var dlLocal

  function versionIntoHref (nodeList, filename) {
    var linkEls = Array.prototype.slice.call(nodeList)
    var version
    var el

    for (var i = 0; i < linkEls.length; i++) {
      version = linkEls[i].getAttribute('data-version')
      el = linkEls[i]

      // Windows 64-bit files for 0.x.x need to be prefixed with 'x64/'
      if (os === 'Win' && (version[1] === '0' && arch === 'x64')) {
        el.href += arch + '/'
      }

      el.href += filename.replace('%version%', version)
    }
  }

  if (downloadHead && buttons) {
    dlLocal = downloadHead.getAttribute('data-dl-local')
    switch (os) {
      case 'Mac':
        versionIntoHref(buttons, 'node-%version%.pkg')
        downloadHead[text] = dlLocal + ' macOS (x64)'
        break
      case 'Win':
        versionIntoHref(buttons, 'node-%version%-' + arch + '.msi')
        downloadHead[text] = dlLocal + ' Windows (' + arch + ')'
        break
      case 'Linux':
        versionIntoHref(buttons, 'node-%version%-linux-x64.tar.xz')
        downloadHead[text] = dlLocal + ' Linux (x64)'
        break
    }
  }

  // Windows button on download page
  var winButton = d.getElementById('windows-downloadbutton')
  if (winButton && os === 'Win') {
    var winText = winButton.getElementsByTagName('p')[0]
    winButton.href = winButton.href.replace(/x(86|64)/, arch)
    winText[text] = winText[text].replace(/x(86|64)/, arch)
  }
})(document, navigator)
<|endoftext|>


<commit_before>$(document).ready(function () {

	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
	/* # Variables globales */
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
	lastNumberAssigned = 0;

	/* # Initialisation de la partie */
	gameInit();

	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
	/* # Gestionnaires d'événements */
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

	/* # Rejoindre une partie */
	$( "#formGameJoin" ).submit(function( event ) {
	  event.preventDefault();

	  /* # le joueur rejoin la partie */
	  var playerName = $('#playerName').val();
	  gameRejoin(playerName);

	  /* # liste de joueur */
	  getPlayers();

	});

	/* # Ajouter une recette dans le panier du joueur */
	$( "#formproduction" ).submit(function( event ) {
	  event.preventDefault();

	  var recette = $('#recettadd').val();
	  var prixu = $('#prixunitaire').text()
	  var quantite = parseInt($('#quantity').val());
	  var prixvente = parseFloat($('#prixvente').val());

	  if(Number.isInteger(quantite)){
	  	addPlayerPipe(recette,prixu,quantite,prixvente);
	  }

	});

	/* # raffraichir les données */
	$('#btnRefreshGameInfo').click(function() {
		getMetrology();
	})

	/* # Choix d'une recette */
	if($('#recettadd') != undefined){
		$('#recettadd').change(function() {
			getRepiceByName($(this).val())
		})
	}

	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
	/* # Les fonctions */
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

	var rand = function() {
	    return Math.random().toString(36).substr(2); // remove `0.`
	};

	var token = function() {
	    return rand() + rand(); // to make it longer
	};

	/**
	*
	*/
	function addPlayerPipe(recette,prixu,quantite,prixvente) {
		//console.log(recette)

		var token = lastNumberAssigned++;
		var elemTr = $('

');
		elemTr.append($('	').html(recette));
		elemTr.append($('	').html(prixu));
		elemTr.append($('	').html(prixvente));
		elemTr.append($('	').html(quantite));
		elemTr.append($('	').html(quantite*prixu));
		elemTr.append($('	').html(quantite*prixvente));
		elemTr.append($('	').html($('')));
		$('#playerpipe').append(elemTr);

		callbackDelPlayerPipe()
	}

	/**
	*
	*/
	function getMetrology () {
		$.ajax({
			url: "/metrology",
			type: "GET",
			contentType: 'application/json',
			success: function(result){
				$('#timer').html(result.timestamp);
	        	$('#weatherToday').html(result.weatherToday);
	        	$('#weatherTomorrow').html(result.weatherTomorow);
	    	}
		});
	}

	/**
	*
	*/
	function getPlayers() {
		$.ajax({
			url: "/players",
			type: "GET",
			contentType: 'application/json',
			success: function(result){
				//console.log(result)
				if(result.length > 0){
					var item = $('

');

					$('#playerList').html("");
					for (var i = 0; i < result.length; i++) {
						item.append($('
'+ result[i].pl_pseudo +'
'))
					};
					$('#playerList').append(item);
				}else{
					$('#playerList').html("Liste vide :(");
				}
	    	}
		});
	}

	function getRepices() {
		$.ajax({
			url: "/recipes",
			type: "GET",
			contentType: 'application/json',
			success: function(result){

				$.each(result.recipes, function( index, value ) {
					//console.log(value)
					$('#recettadd').append($('<option value="'+ value['rec_id'] +'">'+ value['rec_nom'] +'</option>'))
				});

				//$('#recipes').html("");
				/*for (var i = 0; i < result.length; i++) {

				};*/
	    	}
		});
	}

	function getRepiceByName(rc_id) {
		$.ajax({
			url: "/recipe/"+rc_id,
			type: "GET",
			contentType: 'application/json',
			success: function(result){
				var totalCost = 0;
				$.each(result.ingredients, function( index, value ) {
					totalCost += value['ing_prix'];
				});
				$('#prixunitaire').html(totalCost)
	    	}
		});
	}

	/**
	*
	*/
	function gameRejoin(playerName) {
		var data = {"playerName": playerName}
		$.ajax({
			url: "/players",
			data : JSON.stringify(data),
			type: "POST",
			contentType: 'application/json',
			success: function(result){
	        	resetFormGameJoin()
	    	}
		});
	}

	/**
	*
	*/
	function resetFormGameJoin () {
		$('#playerName').val("");
	}

	/**
	*
	*/
	function gameInit () {
		/* # récupération de la météo */
	  	getMetrology ();

	  	/* # Liste de joueurs */
	  	getPlayers();

	  	if($('#blocSimul') != undefined)
	 		getRepices();
	}

	function callbackDelPlayerPipe () {
		/* # supprimer une recette dans le pipe */
		$('.btnSuppRecette').click(function (event) {
			console.log($('#'+event.target.id.split()[0]).parent())
			$('#'+event.target.id.split()[0]).remove()
		})
	}

})
<commit_msg>supp pipe - TEST 3<commit_after>$(document).ready(function () {

	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
	/* # Variables globales */
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
	lastNumberAssigned = 0;

	/* # Initialisation de la partie */
	gameInit();

	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
	/* # Gestionnaires d'événements */
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

	/* # Rejoindre une partie */
	$( "#formGameJoin" ).submit(function( event ) {
	  event.preventDefault();

	  /* # le joueur rejoin la partie */
	  var playerName = $('#playerName').val();
	  gameRejoin(playerName);

	  /* # liste de joueur */
	  getPlayers();

	});

	/* # Ajouter une recette dans le panier du joueur */
	$( "#formproduction" ).submit(function( event ) {
	  event.preventDefault();

	  var recette = $('#recettadd').val();
	  var prixu = $('#prixunitaire').text()
	  var quantite = parseInt($('#quantity').val());
	  var prixvente = parseFloat($('#prixvente').val());

	  if(Number.isInteger(quantite)){
	  	addPlayerPipe(recette,prixu,quantite,prixvente);
	  }

	});

	/* # raffraichir les données */
	$('#btnRefreshGameInfo').click(function() {
		getMetrology();
	})

	/* # Choix d'une recette */
	if($('#recettadd') != undefined){
		$('#recettadd').change(function() {
			getRepiceByName($(this).val())
		})
	}

	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
	/* # Les fonctions */
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

	var rand = function() {
	    return Math.random().toString(36).substr(2); // remove `0.`
	};

	var token = function() {
	    return rand() + rand(); // to make it longer
	};

	/**
	*
	*/
	function addPlayerPipe(recette,prixu,quantite,prixvente) {
		//console.log(recette)

		var token = lastNumberAssigned++;
		var elemTr = $('

');
		elemTr.append($('	').html(recette));
		elemTr.append($('	').html(prixu));
		elemTr.append($('	').html(prixvente));
		elemTr.append($('	').html(quantite));
		elemTr.append($('	').html(quantite*prixu));
		elemTr.append($('	').html(quantite*prixvente));
		elemTr.append($('	').html($('')));
		$('#playerpipe').append(elemTr);

		callbackDelPlayerPipe()
	}

	/**
	*
	*/
	function getMetrology () {
		$.ajax({
			url: "/metrology",
			type: "GET",
			contentType: 'application/json',
			success: function(result){
				$('#timer').html(result.timestamp);
	        	$('#weatherToday').html(result.weatherToday);
	        	$('#weatherTomorrow').html(result.weatherTomorow);
	    	}
		});
	}

	/**
	*
	*/
	function getPlayers() {
		$.ajax({
			url: "/players",
			type: "GET",
			contentType: 'application/json',
			success: function(result){
				//console.log(result)
				if(result.length > 0){
					var item = $('

');

					$('#playerList').html("");
					for (var i = 0; i < result.length; i++) {
						item.append($('
'+ result[i].pl_pseudo +'
'))
					};
					$('#playerList').append(item);
				}else{
					$('#playerList').html("Liste vide :(");
				}
	    	}
		});
	}

	function getRepices() {
		$.ajax({
			url: "/recipes",
			type: "GET",
			contentType: 'application/json',
			success: function(result){

				$.each(result.recipes, function( index, value ) {
					//console.log(value)
					$('#recettadd').append($('<option value="'+ value['rec_id'] +'">'+ value['rec_nom'] +'</option>'))
				});

				//$('#recipes').html("");
				/*for (var i = 0; i < result.length; i++) {

				};*/
	    	}
		});
	}

	function getRepiceByName(rc_id) {
		$.ajax({
			url: "/recipe/"+rc_id,
			type: "GET",
			contentType: 'application/json',
			success: function(result){
				var totalCost = 0;
				$.each(result.ingredients, function( index, value ) {
					totalCost += value['ing_prix'];
				});
				$('#prixunitaire').html(totalCost)
	    	}
		});
	}

	/**
	*
	*/
	function gameRejoin(playerName) {
		var data = {"playerName": playerName}
		$.ajax({
			url: "/players",
			data : JSON.stringify(data),
			type: "POST",
			contentType: 'application/json',
			success: function(result){
	        	resetFormGameJoin()
	    	}
		});
	}

	/**
	*
	*/
	function resetFormGameJoin () {
		$('#playerName').val("");
	}

	/**
	*
	*/
	function gameInit () {
		/* # récupération de la météo */
	  	getMetrology ();

	  	/* # Liste de joueurs */
	  	getPlayers();

	  	if($('#blocSimul') != undefined)
	 		getRepices();
	}

	function callbackDelPlayerPipe () {
		/* # supprimer une recette dans le pipe */
		$('.btnSuppRecette').click(function (event) {
			var tmp  = '#'+event.target.id.split()[0];
			console.log(tmp)

			$(tmp).remove()
		})
	}

})
<|endoftext|>


<commit_before>String.prototype.hashCode = function() {
    var hash = 0, i, chr, len;
    if (this.length === 0) return hash;
    for (i = 0, len = this.length; i < len; i++) {
        chr   = this.charCodeAt(i);
        hash  = ((hash << 5) - hash) + chr;
        hash |= 0; // Convert to 32bit integer
    }
    return hash;
};

var TutuWebSocket = TutuWebSocket || (function() {
    var ws = undefined;
    var topicRegistry = {};

    function initTopics() {
        onTopic('cmd_result', function(data) {
            Tutu.addMsgForTutu(data);
        });
        onTopic('ws_close', function() {
            Tutu.addMsgForTutu({
                "shareCode": "",
                "message": "The connection seems closed, please refresh your browser to re-connect"
            });
        });
        onTopic('ws_error', function() {
            Tutu.addMsgForTutu({
                "shareCode": "",
                "message": "Some error seems just happened, please retry or refresh your browser"
            });
        });
        onTopic('ws_open', function(data) {
            Tutu.addMsgForTutu({
                "shareCode": "",
                "message": "Available commands: " + data['message']
            });
        });
        onTopic('share', function(data) {
            var shareCode = data['shareCode'];
            Tutu.addMsgForUser({
                "shareCode": shareCode,
                "message": data['cmd']
            });
            Tutu.addMsgForTutu({
                "shareCode": shareCode,
                "message": data['message']
            });
        });
        onTopic("internal_error", function(data) {
            Tutu.addMsgForTutu({
                "shareCode": "",
                "message": data['message']
            });
        });
    }

    function init() {
        if (!ws) {
            ws = new WebSocket("ws://" + location.host +  "/ws/invoke");
            ws.onmessage = function(evt) {
                var result = JSON.parse(evt.data);
                var topic = result['topic'];
                topicRegistry[topic]({
                    "cmd": result['cmd'],
                    "shareCode": result['share_code'],
                    "message": result['data']
                });
            };
            ws.onclose = function(evt) {
                topicRegistry['ws_close']();
            };
            ws.onerror = function(evt) {
                topicRegistry['ws_error']();
            };
            ws.onopen = function() {
                if (Cookies.get('share_code')) {
                    var shareCode = Cookies.get('share_code');
                    var cmd = "share " + shareCode;
                    Cookies.remove('share_code');
                    send({
                        'shareCode': cmd.hashCode(),
                        'command': cmd
                    });
                }
            };
        }
        initTopics();
    }

    function onTopic(topic, func) {
        topicRegistry = topicRegistry || {};
        topicRegistry[topic] = func;
    }

    function send(msg) {
        ws.send(JSON.stringify(msg));
    }

    return {
        "init": init,
        "onTopic": onTopic,
        "send": send
    };
})();

var Tutu = Tutu || (function() {
    function rawInput() {
        return $('#message-input').val();
    };

    function clearInput() {
        return $('#message-input').val('');
    };

    function setSuggestedInput(sInput) {
        $('.typeahead').typeahead('val', sInput);
    };

    function suggestionMenuVisible() {
        return $('div.tt-menu').is(":visible");
    }

    function buildSuggestionCmd(rawInput, suggestion) {
        var cmdSegs = rawInput.split(/\W+/);
        return $.trim([].slice.call(cmdSegs, 0, -1).concat([suggestion]).join(' '));
    }

    function removeSuggestionMenu(e) {
        if (suggestionMenuVisible()) {
            var suggestions = $('div.tt-menu div.tt-suggestion');

            if (suggestions.length == 1) {
                var cmdSegs = rawInput().split(/\W+/);
                var lastCmdSeg = $.trim(cmdSegs[cmdSegs.length - 1]);
                var suggestion = $.trim(suggestions.text());
                if (lastCmdSeg == suggestion) {
                    setSuggestedInput(buildSuggestionCmd(rawInput(), suggestion));
                    $('.typeahead').typeahead('close');
                }
            }
        }
    }

    function addMsgForTutu(data) {
        addMessage({
            user: "Tutu",
            uicon: "tutu_icon",
            shareCode: data['shareCode'],
            content: data['message']
        });
    }

    function addMsgForUser(data) {
        addMessage({
            user: "You",
            uicon: "user_icon",
            shareCode: data['shareCode'],
            content: data['message']
        });
    }

    function addMessage(ctx) {
        if (ctx['shareCode']) {
            ctx['shareLink'] = "http://" + location.host + '/share/' + ctx['shareCode'];
        }
        var msgsDiv = $('#msgs_div');
        var template = Handlebars.compile($('#message_tmpl').html());

        function shareLink(container) {
            return $('a[share-link*="share"]', container).attr('share-link');
        }

        function hasShareLink(container) {
            return !!shareLink(container);
        }

        var tmpl = $(template(ctx)).hide().appendTo(msgsDiv).fadeIn(500).hover(function() {
            if (hasShareLink($(this))) {
                var ci = $('a[class*="copy_icon"]', $(this));
                ci.removeClass('hidden');
            }
        }, function() {
            if (hasShareLink($(this))) {
                $('a[class*="copy_icon"]', $(this)).addClass('hidden');
            }
        });

        if (ctx['shareCode']) {
            var ci = $('a[class*="copy_icon"]', tmpl);
            new Clipboard(ci[0], {
                text: function(trigger) {
                    return trigger.getAttribute('share-link');
                }
            });
        }

        var msgsScrollDiv = $('#msgs_scroller_div');
        msgsScrollDiv.animate({
            scrollTop: msgsScrollDiv.prop('scrollHeight')
        }, "slow");
    }

    function initHotkeyBindings() {
        var msg_box = $('#message-input')[0];

        Mousetrap(msg_box).bind('enter', function(e) {
            removeSuggestionMenu();
            if (!suggestionMenuVisible()) {
                var cmd = rawInput();
                var shareCode = cmd.hashCode();
                addMsgForUser({
                    "shareCode": shareCode,
                    "message": cmd
                });
                clearInput();
                TutuWebSocket.send({
                    "shareCode": shareCode,
                    "command": cmd
                });
            }
        });

        Mousetrap(msg_box).bind(['alt+backspace'], function() {
            setSuggestedInput(buildSuggestionCmd(rawInput(), ''));
        });
    }

    function initTypeahead() {
        var initTabKeyed = function() {
            var rInput;
            $('.typeahead').bind('typeahead:beforeselect typeahead:beforeautocomplete', function(e, suggestion) {
                rInput = rawInput();
            });

            $('.typeahead').bind('typeahead:select typeahead:autocomplete', function(e, suggestion) {
                setSuggestedInput(buildSuggestionCmd(rInput, suggestion.name));
            });
        };

        var initSuggestionEngine = function() {
            var commands = new Bloodhound({
                datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
                queryTokenizer: function(str) {
                    if (str.endsWith(' ')) {
                        // don't show menu when enter whitespace
                        return ['_impossible_token_'];
                    }
                    // Only return the last word as query token
                    return [].slice.call($.trim(str).split(/\W+/), -1);
                },
                prefetch: '/api/commands'
            });

            $('.typeahead').typeahead({
                hint: true,
                highlight: true,
                minLength: 1,
                menuConfig: {
                    position: 'top'
                }
            }, {
                name: 'commands',
                display: 'name',
                source: commands,
                templates: {
                    header: '
Commands
'
                }
            });
        };

        initTabKeyed();
        initSuggestionEngine();
    }

    function initFocus() {
        $('#message-input').focus();
    }

    $(function() {
        TutuWebSocket.init();
        initHotkeyBindings();
        initTypeahead();
        initFocus();
    });

    // API
    return {
        'addMessage': addMessage,
        'addMsgForTutu': addMsgForTutu,
        'addMsgForUser': addMsgForUser
    };
})();
<commit_msg>Auto-complete for apps<commit_after>String.prototype.hashCode = function() {
    var hash = 0,
        i, chr, len;
    if (this.length === 0) return hash;
    for (i = 0, len = this.length; i < len; i++) {
        chr = this.charCodeAt(i);
        hash = ((hash << 5) - hash) + chr;
        hash |= 0; // Convert to 32bit integer
    }
    return hash;
};

var TutuWebSocket = TutuWebSocket || (function() {
    var ws = undefined;
    var topicRegistry = {};

    function initTopics() {
        onTopic('cmd_result', function(data) {
            Tutu.addMsgForTutu(data);
        });
        onTopic('ws_close', function() {
            Tutu.addMsgForTutu({
                "shareCode": "",
                "message": "The connection seems closed, please refresh your browser to re-connect"
            });
        });
        onTopic('ws_error', function() {
            Tutu.addMsgForTutu({
                "shareCode": "",
                "message": "Some error seems just happened, please retry or refresh your browser"
            });
        });
        onTopic('ws_open', function(data) {
            Tutu.addMsgForTutu({
                "shareCode": "",
                "message": "Available commands: " + data['message']
            });
        });
        onTopic('share', function(data) {
            var shareCode = data['shareCode'];
            Tutu.addMsgForUser({
                "shareCode": shareCode,
                "message": data['cmd']
            });
            Tutu.addMsgForTutu({
                "shareCode": shareCode,
                "message": data['message']
            });
        });
        onTopic("internal_error", function(data) {
            Tutu.addMsgForTutu({
                "shareCode": "",
                "message": data['message']
            });
        });
    }

    function init() {
        if (!ws) {
            ws = new WebSocket("ws://" + location.host + "/ws/invoke");
            ws.onmessage = function(evt) {
                var result = JSON.parse(evt.data);
                var topic = result['topic'];
                topicRegistry[topic]({
                    "cmd": result['cmd'],
                    "shareCode": result['share_code'],
                    "message": result['data']
                });
            };
            ws.onclose = function(evt) {
                topicRegistry['ws_close']();
            };
            ws.onerror = function(evt) {
                topicRegistry['ws_error']();
            };
            ws.onopen = function() {
                if (Cookies.get('share_code')) {
                    var shareCode = Cookies.get('share_code');
                    var cmd = "share " + shareCode;
                    Cookies.remove('share_code');
                    send({
                        'shareCode': cmd.hashCode(),
                        'command': cmd
                    });
                }
            };
        }
        initTopics();
    }

    function onTopic(topic, func) {
        topicRegistry = topicRegistry || {};
        topicRegistry[topic] = func;
    }

    function send(msg) {
        ws.send(JSON.stringify(msg));
    }

    return {
        "init": init,
        "onTopic": onTopic,
        "send": send
    };
})();

var Tutu = Tutu || (function() {
    function rawInput() {
        return $('#message-input').val();
    };

    function clearInput() {
        return $('#message-input').val('');
    };

    function setSuggestedInput(sInput) {
        $('.typeahead').typeahead('val', sInput);
    };

    function suggestionMenuVisible() {
        return $('div.tt-menu').is(":visible");
    }

    function buildSuggestionCmd(rawInput, suggestion) {
        var cmdSegs = rawInput.split(/\W+/);
        return $.trim([].slice.call(cmdSegs, 0, -1).concat([suggestion]).join(' '));
    }

    function removeSuggestionMenu(e) {
        if (suggestionMenuVisible()) {
            var suggestions = $('div.tt-menu div.tt-suggestion');

            if (suggestions.length == 1) {
                var cmdSegs = rawInput().split(/\W+/);
                var lastCmdSeg = $.trim(cmdSegs[cmdSegs.length - 1]);
                var suggestion = $.trim(suggestions.text());
                if (lastCmdSeg == suggestion) {
                    setSuggestedInput(buildSuggestionCmd(rawInput(), suggestion));
                    $('.typeahead').typeahead('close');
                }
            }
        }
    }

    function addMsgForTutu(data) {
        addMessage({
            user: "Tutu",
            uicon: "tutu_icon",
            shareCode: data['shareCode'],
            content: data['message']
        });
    }

    function addMsgForUser(data) {
        addMessage({
            user: "You",
            uicon: "user_icon",
            shareCode: data['shareCode'],
            content: data['message']
        });
    }

    function addMessage(ctx) {
        if (ctx['shareCode']) {
            ctx['shareLink'] = "http://" + location.host + '/share/' + ctx['shareCode'];
        }
        var msgsDiv = $('#msgs_div');
        var template = Handlebars.compile($('#message_tmpl').html());

        function shareLink(container) {
            return $('a[share-link*="share"]', container).attr('share-link');
        }

        function hasShareLink(container) {
            return !!shareLink(container);
        }

        var tmpl = $(template(ctx)).hide().appendTo(msgsDiv).fadeIn(500).hover(function() {
            if (hasShareLink($(this))) {
                var ci = $('a[class*="copy_icon"]', $(this));
                ci.removeClass('hidden');
            }
        }, function() {
            if (hasShareLink($(this))) {
                $('a[class*="copy_icon"]', $(this)).addClass('hidden');
            }
        });

        if (ctx['shareCode']) {
            var ci = $('a[class*="copy_icon"]', tmpl);
            new Clipboard(ci[0], {
                text: function(trigger) {
                    return trigger.getAttribute('share-link');
                }
            });
        }

        var msgsScrollDiv = $('#msgs_scroller_div');
        msgsScrollDiv.animate({
            scrollTop: msgsScrollDiv.prop('scrollHeight')
        }, "slow");
    }

    function initHotkeyBindings() {
        var msg_box = $('#message-input')[0];

        Mousetrap(msg_box).bind('enter', function(e) {
            removeSuggestionMenu();
            if (!suggestionMenuVisible()) {
                var cmd = rawInput();
                var shareCode = cmd.hashCode();
                addMsgForUser({
                    "shareCode": shareCode,
                    "message": cmd
                });
                clearInput();
                TutuWebSocket.send({
                    "shareCode": shareCode,
                    "command": cmd
                });
            }
        });

        Mousetrap(msg_box).bind(['alt+backspace'], function() {
            setSuggestedInput(buildSuggestionCmd(rawInput(), ''));
        });
    }

    function initTypeahead() {
        var initTabKeyed = function() {
            var rInput;
            $('.typeahead').bind('typeahead:beforeselect typeahead:beforeautocomplete', function(e, suggestion) {
                rInput = rawInput();
            });

            $('.typeahead').bind('typeahead:select typeahead:autocomplete', function(e, suggestion) {
                setSuggestedInput(buildSuggestionCmd(rInput, suggestion.name));
            });
        };

        var initSuggestionEngine = function() {
            var commands = new Bloodhound({
                datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
                queryTokenizer: function(str) {
                    if (str.endsWith(' ')) {
                        // don't show menu when enter whitespace
                        return ['_impossible_token_'];
                    }
                    // Only return the last word as query token
                    return [].slice.call($.trim(str).split(/\W+/), -1);
                },
                prefetch: '/api/commands'
            });

            var apps = new Bloodhound({
                datumTokenizer: Bloodhound.tokenizers.obj.whitespace,
                queryTokenizer: Bloodhound.tokenizers.obj.whitespace,
                remote: '/api/marathon/apps'
            });

            $('.typeahead').typeahead({
                    hint: true,
                    highlight: true,
                    minLength: 1,
                    menuConfig: {
                        position: 'top'
                    }
                }, {
                    name: 'commands',
                    display: 'name',
                    source: commands,
                    templates: {
                        header: '
Commands
'
                    }
                }
//                                      ,{
//                    name: 'apps',
//                    source: apps,
//                    templates: {
//                        header: '
Apps
'
//                    }
//                                      }
                                     );
        };

        initTabKeyed();
        initSuggestionEngine();
    }

    function initFocus() {
        $('#message-input').focus();
    }

    $(function() {
        TutuWebSocket.init();
        initHotkeyBindings();
        initTypeahead();
        initFocus();
    });

    // API
    return {
        'addMessage': addMessage,
        'addMsgForTutu': addMsgForTutu,
        'addMsgForUser': addMsgForUser
    };
})();
<|endoftext|>


<commit_before>import React from 'react';
import PropTable from './components/propTable';
import { storiesOf } from '@storybook/react';
import { withInfo } from '@storybook/addon-info';
import { withKnobs, boolean, select } from '@storybook/addon-knobs/react';
import { Island, IslandGroup, Link, TextBody, TextSmall, Heading3 } from '../components';
import {
  IllustrationInvoices120X120Static,
  IllustrationMeetings120X120Static,
  IllustrationDeals120X120Static,
} from '@teamleader/ui-illustrations';

import { IconChevronRightSmallOutline } from '@teamleader/ui-icons';

const colors = ['neutral', 'mint', 'violet', 'ruby', 'gold', 'aqua', 'white'];
const sizes = ['small', 'medium', 'large'];

storiesOf('Island', module)
  .addDecorator((story, context) =>
    withInfo({
      TableComponent: PropTable,
      propTablesExclude: [
        TextBody,
        TextSmall,
        Heading3,
        Link,
        IconChevronRightSmallOutline,
        IllustrationInvoices120X120Static,
        IllustrationMeetings120X120Static,
        IllustrationDeals120X120Static,
      ],
    })(story)(context),
  )
  .addDecorator(withKnobs)
  .add('Basic', () => (
    <Island
      color={select('Color', colors, 'white')}
      dark={boolean('Dark', false)}
      size={select('Size', sizes, 'medium')}
    >
      <TextBody>I am an island.</TextBody>
    </Island>
  ))
  .add('Segmented horizontal', () => (
    <IslandGroup
      dark={boolean('Dark', false)}
      color={select('Color', colors, 'white')}
      size={select('Size', sizes, 'medium')}
    >
      <Island>
        <IllustrationInvoices120X120Static />
        <Heading3 marginBottom={3}>Invoices</Heading3>
        <TextBody>Send invoices to your clients straight from Teamleader.</TextBody>
      </Island>
      <Island>
        <IllustrationMeetings120X120Static />
        <Heading3 marginBottom={3}>Meetings</Heading3>
        <TextBody>Plan meetings and see them straight away in your favourite calendar.</TextBody>
      </Island>
      <Island>
        <IllustrationDeals120X120Static />
        <Heading3 marginBottom={3}>Deals</Heading3>
        <TextBody>Keep track of all your deals with our fully integrated module.</TextBody>
      </Island>
    </IslandGroup>
  ))
  .add('Segmented vertical', () => (
    <IslandGroup
      dark={boolean('Dark', false)}
      color={select('Color', colors, 'neutral')}
      direction="vertical"
      size={select('Size', sizes, 'medium')}
    >
      <Island>
        <TextBody>kanye.west@goodmusic.com</TextBody>
      </Island>
      <Island display="flex" alignItems="center">
        <IconChevronRightSmallOutline />
        <TextBody marginHorizontal={2}>
          <Link href="https://www.teamleader.be" target="_blank" inherit={false}>
            Good music Ltd.
          </Link>
        </TextBody>
        <TextSmall color="neutral">Company</TextSmall>
      </Island>
    </IslandGroup>
  ));
<commit_msg>Island: update story<commit_after>import React from 'react';
import { storiesOf } from '@storybook/react';
import { boolean, select } from '@storybook/addon-knobs/react';
import { Island, IslandGroup, Link, TextBody, TextSmall, Heading3 } from '../components';
import {
  IllustrationInvoices120X120Static,
  IllustrationMeetings120X120Static,
  IllustrationDeals120X120Static,
} from '@teamleader/ui-illustrations';

import { IconChevronRightSmallOutline } from '@teamleader/ui-icons';

const colors = ['neutral', 'mint', 'violet', 'ruby', 'gold', 'aqua', 'white'];
const sizes = ['small', 'medium', 'large'];

storiesOf('Island', module)
  .addParameters({
    info: {
      propTablesExclude: [
        TextBody,
        TextSmall,
        Heading3,
        Link,
        IconChevronRightSmallOutline,
        IllustrationInvoices120X120Static,
        IllustrationMeetings120X120Static,
        IllustrationDeals120X120Static,
      ],
    },
  })
  .add('Basic', () => (
    <Island
      color={select('Color', colors, 'white')}
      dark={boolean('Dark', false)}
      size={select('Size', sizes, 'medium')}
    >
      <TextBody>I am an island.</TextBody>
    </Island>
  ))
  .add('Segmented horizontal', () => (
    <IslandGroup
      dark={boolean('Dark', false)}
      color={select('Color', colors, 'white')}
      size={select('Size', sizes, 'medium')}
    >
      <Island>
        <IllustrationInvoices120X120Static />
        <Heading3 marginBottom={3}>Invoices</Heading3>
        <TextBody>Send invoices to your clients straight from Teamleader.</TextBody>
      </Island>
      <Island>
        <IllustrationMeetings120X120Static />
        <Heading3 marginBottom={3}>Meetings</Heading3>
        <TextBody>Plan meetings and see them straight away in your favourite calendar.</TextBody>
      </Island>
      <Island>
        <IllustrationDeals120X120Static />
        <Heading3 marginBottom={3}>Deals</Heading3>
        <TextBody>Keep track of all your deals with our fully integrated module.</TextBody>
      </Island>
    </IslandGroup>
  ))
  .add('Segmented vertical', () => (
    <IslandGroup
      dark={boolean('Dark', false)}
      color={select('Color', colors, 'neutral')}
      direction="vertical"
      size={select('Size', sizes, 'medium')}
    >
      <Island>
        <TextBody>kanye.west@goodmusic.com</TextBody>
      </Island>
      <Island display="flex" alignItems="center">
        <IconChevronRightSmallOutline />
        <TextBody marginHorizontal={2}>
          <Link href="https://www.teamleader.be" target="_blank" inherit={false}>
            Good music Ltd.
          </Link>
        </TextBody>
        <TextSmall color="neutral">Company</TextSmall>
      </Island>
    </IslandGroup>
  ));
<|endoftext|>


<commit_before>console.log('partners_become.js');

$('.join-link.technology-form').on('click', function(e){
  e.preventDefault();
  w.optly.mrkt.modal.open({ modalType: 'become-partner-technology' });
});

$('.join-link.solutions-form').on('click', function(e){
  e.preventDefault();
  w.optly.mrkt.modal.open({ modalType: 'become-partner-solutions' });
});

$('.become-partner-fields select#company_type').on('change', function(e, a){
  if (e.target.value === 'Subsidiary'){
    $('.parent-company-row').removeClass('hidden');
  } else {
    $('.parent-company-row').addClass('hidden');
  }
});
<commit_msg>trivial commit<commit_after>console.log('partners_become.js');

$('.join-link.technology-form').on('click', function(e){
  e.preventDefault();
  w.optly.mrkt.modal.open({ modalType: 'become-partner-technology' });
});

$('.join-link.solutions-form').on('click', function(e){
  e.preventDefault();
  w.optly.mrkt.modal.open({ modalType: 'become-partner-solutions' });
});

//Reveal follow up field
$('.become-partner-fields select#company_type').on('change', function(e, a){
  if (e.target.value === 'Subsidiary'){
    $('.parent-company-row').removeClass('hidden');
  } else {
    $('.parent-company-row').addClass('hidden');
  }
});
<|endoftext|>


<commit_before>'use strict';

var $ = require('jquery');
var bootbox = require('bootbox');
var $osf = require('js/osfHelpers');

var nodeApiUrl = window.contextVars.node.urls.api;

var GithubConfigHelper = (function() {

    var updateHidden = function(val) {
        var repoParts = val.split('/');
        $('#githubUser').val($.trim(repoParts[0]));
        $('#githubRepo').val($.trim(repoParts[1]));
    };

    var displayError = function(msg) {
        $('#addonSettingsGithub').find('.addon-settings-message')
            .text('Error: ' + msg)
            .removeClass('text-success').addClass('text-danger')
            .fadeOut(100).fadeIn();
    };

    var createRepo = function() {

        var $elm = $('#addonSettingsGithub');
        var $select = $elm.find('select');

        bootbox.prompt({
            title: 'Name your new repo',
            callback: function (repoName) {
                // Return if cancelled
                if (repoName === null) {
                    return;
                }

                if (repoName === '') {
                    displayError('Your repo must have a name');
                    return;
                }

                $osf.postJSON(
                    '/api/v1/github/repo/create/',
                    {name: repoName}
                ).done(function (response) {
                        var repoName = response.user + ' / ' + response.repo;
                        $select.append('<option value="' + repoName + '">' + repoName + '</option>');
                        $select.val(repoName);
                        updateHidden(repoName);
                    }).fail(function () {
                        displayError('Could not create repository');
                    });
            },
            buttons:{
                confirm:{
                    label: 'Save',
                    className:'btn-success'
                }
            }
        });
    };

    $(document).ready(function() {
        $('#githubSelectRepo').on('change', function() {
            var value = $(this).val();
            if (value) {
                updateHidden(value);
            }
        });

        $('#githubCreateRepo').on('click', function() {
            createRepo();
        });

        $('#githubImportToken').on('click', function() {
            $osf.postJSON(
                nodeApiUrl + 'github/user_auth/',
                {}
            ).done(function() {
                    if($osf.isIE()){
                        window.location.hash = "#configureAddonsAnchor";
                    }
                    window.location.reload();
            }).fail(
                $osf.handleJSONError
            );
        });

        $('#githubCreateToken').on('click', function() {
            window.location.href = nodeApiUrl + 'github/oauth/';
        });

        $('#githubRemoveToken').on('click', function() {
            bootbox.confirm({
                title: 'Disconnect GitHub Account?',
                message: 'Are you sure you want to remove this GitHub account?',
                callback: function(confirm) {
                    if(confirm) {
                        $.ajax({
                        type: 'DELETE',
                        url: nodeApiUrl + 'github/oauth/'
                    }).done(function() {
                        window.location.reload();
                    }).fail(
                        $osf.handleJSONError
                    );
                    }
                },
                buttons:{
                    confirm:{
                        label: 'Disconnect',
                        className: 'btn-danger'
                    }
                }
            });
        });

        $('#addonSettingsGithub .addon-settings-submit').on('click', function() {
            if (!$('#githubRepo').val()) {
                return false;
            }
        });

    });

})();

module.exports = GithubConfigHelper;
<commit_msg>Add placeholder<commit_after>'use strict';

var $ = require('jquery');
var bootbox = require('bootbox');
var $osf = require('js/osfHelpers');

var nodeApiUrl = window.contextVars.node.urls.api;

var GithubConfigHelper = (function() {

    var updateHidden = function(val) {
        var repoParts = val.split('/');
        $('#githubUser').val($.trim(repoParts[0]));
        $('#githubRepo').val($.trim(repoParts[1]));
    };

    var displayError = function(msg) {
        $('#addonSettingsGithub').find('.addon-settings-message')
            .text('Error: ' + msg)
            .removeClass('text-success').addClass('text-danger')
            .fadeOut(100).fadeIn();
    };

    var createRepo = function() {

        var $elm = $('#addonSettingsGithub');
        var $select = $elm.find('select');

        bootbox.prompt({
            title: 'Name your new repo',
            placeholder: 'Repo name',
            callback: function (repoName) {
                // Return if cancelled
                if (repoName === null) {
                    return;
                }

                if (repoName === '') {
                    displayError('Your repo must have a name');
                    return;
                }

                $osf.postJSON(
                    '/api/v1/github/repo/create/',
                    {name: repoName}
                ).done(function (response) {
                        var repoName = response.user + ' / ' + response.repo;
                        $select.append('<option value="' + repoName + '">' + repoName + '</option>');
                        $select.val(repoName);
                        updateHidden(repoName);
                    }).fail(function () {
                        displayError('Could not create repository');
                    });
            },
            buttons:{
                confirm:{
                    label: 'Save',
                    className:'btn-success'
                }
            }
        });
    };

    $(document).ready(function() {
        $('#githubSelectRepo').on('change', function() {
            var value = $(this).val();
            if (value) {
                updateHidden(value);
            }
        });

        $('#githubCreateRepo').on('click', function() {
            createRepo();
        });

        $('#githubImportToken').on('click', function() {
            $osf.postJSON(
                nodeApiUrl + 'github/user_auth/',
                {}
            ).done(function() {
                    if($osf.isIE()){
                        window.location.hash = "#configureAddonsAnchor";
                    }
                    window.location.reload();
            }).fail(
                $osf.handleJSONError
            );
        });

        $('#githubCreateToken').on('click', function() {
            window.location.href = nodeApiUrl + 'github/oauth/';
        });

        $('#githubRemoveToken').on('click', function() {
            bootbox.confirm({
                title: 'Disconnect GitHub Account?',
                message: 'Are you sure you want to remove this GitHub account?',
                callback: function(confirm) {
                    if(confirm) {
                        $.ajax({
                        type: 'DELETE',
                        url: nodeApiUrl + 'github/oauth/'
                    }).done(function() {
                        window.location.reload();
                    }).fail(
                        $osf.handleJSONError
                    );
                    }
                },
                buttons:{
                    confirm:{
                        label: 'Disconnect',
                        className: 'btn-danger'
                    }
                }
            });
        });

        $('#addonSettingsGithub .addon-settings-submit').on('click', function() {
            if (!$('#githubRepo').val()) {
                return false;
            }
        });

    });

})();

module.exports = GithubConfigHelper;
<|endoftext|>


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

var Twit = require('twit'),
    T = new Twit(require('./secret')),
    stream = T.stream('user'),
    generateTweetMessage = function(user) {
        "use strict";

        return "@" + user.name + " grazie... anche tu sei nei nostri cuori!";
    },
    generateTweetPost = function(reply) {
        "use strict";

        T.post('statuses/update', { status: reply }, function(err, data, http_response) {
            if (err) {
                console.log('error ' + err);
            } else {
                // console.log(data);
                console.log('statuses replies to user');
            }
        });
    },
    addUserToList = function(data, list) {
        "use strict";

        var status = {
            'slug': list,
            'owner_screen_name' : data.user.name,
            'screen_name': data.member.name
        };

        T.post('lists/members/create', status, function(err, data, http_response) {
            if (err) {
                console.log('error ' + err);
            } else {
                console.log(user.screen_name + ' is now added to list' + status.slug);
            }
        });
    },
    generateTweet = function(data) {
        "use strict";

        generateTweetPost(generateTweetMessage(data.user));
    },
    evaluateAction = function(data) {
        "use strict";

        if (user.id === data.user.id ) {
            addUserToList(data, user.selected_list);
            generateTweet(data);
        }

        return false;
    };

stream.on('favorite', function (response) {
    //console.log(response);
    /* RESPONSE PROPERTY
     *  event --> event name
     *  source
     *    id --> user id
     *    screen_name --> handle of user that perfomed an action
     *  target_object
     *    id --> status id
     *    text --> text of status
     */

    var data = {
        event_name: response.event,
        post: {
          id: response.target_object.id,
          text: response.target_object.text
        },
        member: {
            id: response.target_object.user.id,
            name: response.target_object.user.screen_name
        },
        user: {
            id: response.source.id,
            name: response.source.screen_name
        }
    };

    console.log(data.user.name + ' perform ' + data.event_name + ' for statuses ' + data.post.text);

    evaluateAction(data);
});

stream.on('error', function (error) {
   console.error(error);
});
<commit_msg>some check<commit_after>const user = require('./user');

var Twit = require('twit'),
    T = new Twit(require('./secret')),
    stream = T.stream('user'),
    generateTweetMessage = function(user) {
        "use strict";

        return "@" + user.name + " grazie... anche tu sei nei nostri cuori!";
    },
    generateTweetPost = function(reply) {
        "use strict";

        T.post('statuses/update', { status: reply }, function(err, data, http_response) {
            if (err) {
                console.log('error ' + err);
            } else {
                // console.log(data);
                console.log('statuses replies to user');
            }
        });
    },
    addUserToList = function(data, list) {
        "use strict";

        var status = {
            'slug': list,
            'owner_screen_name' : data.user.name,
            'screen_name': data.member.name
        };

        T.post('lists/members/create', status, function(err, data, http_response) {
            if (err) {
                console.log('error ' + err);
            } else {
                console.log(user.screen_name + ' is now added to list' + status.slug);
            }
        });
    },
    generateTweet = function(data) {
        "use strict";

        generateTweetPost(generateTweetMessage(data.user));
    },
    evaluateAction = function(data) {
        "use strict";

        console.log('const ' + user.id + ' === ' + data.user.id);

        if (user.id === data.user.id ) {
            addUserToList(data, user.selected_list);
            generateTweet(data);
        }

        return false;
    };

stream.on('favorite', function (response) {
    //console.log(response);
    /* RESPONSE PROPERTY
     *  event --> event name
     *  source
     *    id --> user id
     *    screen_name --> handle of user that perfomed an action
     *  target_object
     *    id --> status id
     *    text --> text of status
     */

    var data = {
        event_name: response.event,
        post: {
          id: response.target_object.id,
          text: response.target_object.text
        },
        member: {
            id: response.target_object.user.id,
            name: response.target_object.user.screen_name
        },
        user: {
            id: response.source.id,
            name: response.source.screen_name
        }
    };

    console.log(data.user.name + ' perform ' + data.event_name + ' for statuses ' + data.post.text);

    evaluateAction(data);
});

stream.on('error', function (error) {
   console.error(error);
});
<|endoftext|>