<commit_before>/* ShowOff JS Logic */

var ShowOff = {};

var preso_started = false
var slidenum = 0
var slideTotal = 0
var slides
var currentSlide
var totalslides = 0
var slidesLoaded = false
var incrSteps = 0
var incrElem
var incrCurr = 0
var incrCode = false
var debugMode = false
var gotoSlidenum = 0
var shiftKeyActive = false

var loadSlidesBool
var loadSlidesPrefix

function setupPreso(load_slides, prefix) {
  if (preso_started)
  {
     alert("already started")
     return
  }
  preso_started = true

  loadSlidesBool = load_slides
  loadSlidesPrefix = prefix
  loadSlides(loadSlidesBool, loadSlidesPrefix)

  doDebugStuff()

  // bind event handlers
  document.onkeydown = keyDown
  document.onkeyup = keyUp
  /* window.onresize  = resized; */
  /* window.onscroll = scrolled; */
  /* window.onunload = unloaded; */
}

function loadSlides(load_slides, prefix) {
  //load slides offscreen, wait for images and then initialize
  if (load_slides) {
  	$("#slides").load("/slides", false, function(){
    	$("#slides img").batchImageLoad({
			loadingCompleteCallback: initializePresentation(prefix)
		})
  	})
  } else {
	$("#slides img").batchImageLoad({
		loadingCompleteCallback: initializePresentation(prefix)
	})
  }
}

function initializePresentation(prefix) {
  //center slides offscreen
  centerSlides($('#slides > .slide'))

  //copy into presentation area
  $("#preso").empty()
  $('#slides > .slide').appendTo($("#preso"))

  //populate vars
  slides = $('#preso > .slide')
  slideTotal = slides.size()

  //setup manual jquery cycle
  $('#preso').cycle({
    timeout: 0
  })

  setupMenu()
  if (slidesLoaded) {
    showSlide()
    alert('slides loaded')
  } else {
    showFirstSlide();
    slidesLoaded = true
  }
  setupSlideParamsCheck();
  sh_highlightDocument(prefix+'/js/sh_lang/', '.min.js')
}

function centerSlides(slides) {
  slides.each(function(s, slide) {
    centerSlide(slide)
  })
}

function centerSlide(slide) {
  var slide_content = $(slide).children(".content").first()
  var height = slide_content.height()
  var mar_top = (0.5 * parseFloat($(slide).height())) - (0.5 * parseFloat(height))
  if (mar_top < 0) {
    mar_top = 0
  }
  slide_content.css('margin-top', mar_top)
}

function setupMenu() {
  $('#navmenu').hide();

  var currSlide = 0
  var menu = new ListMenu()

  slides.each(function(s, elem) {
    content = $(elem).children(".content")
    shortTxt = $(content).text().substr(0, 20)
    path = $(content).attr('ref').split('/')
    currSlide += 1
    menu.addItem(path, shortTxt, currSlide)
  })

  $('#navigation').html(menu.getList())
  $('#navmenu').menu({
    content: $('#navigation').html(),
    flyOut: true
  });
}

function checkSlideParameter() {
  if (slideParam = currentSlideFromParams()) {
    slidenum = slideParam;
  }
}

function currentSlideFromParams() {
  var result;
  if (result = window.location.hash.match(/#([0-9]+)/)) {
    return result[result.length - 1] - 1;
  }
}

function setupSlideParamsCheck() {
  var check = function() {
    var currentSlide = currentSlideFromParams();
    if (slidenum != currentSlide) {
      slidenum = currentSlide;
      showSlide();
    }
    setTimeout(check, 100);
  }
  setTimeout(check, 100);
}

function gotoSlide(slideNum) {
  slidenum = parseInt(slideNum)
  if (!isNaN(slidenum)) {
    showSlide()
  }
}

function showFirstSlide() {
  slidenum = 0
  checkSlideParameter();
  showSlide()
}

function showSlide(back_step) {

  if(slidenum < 0) {
    slidenum = 0
    return
  }

  if(slidenum > (slideTotal - 1)) {
    slidenum = slideTotal - 1
    return
  }

  currentSlide = slides.eq(slidenum)

  var transition = currentSlide.attr('data-transition')
  var fullPage = currentSlide.find(".content").is('.full-page');

  if (back_step || fullPage) {
    transition = 'none'
  }

  $('#preso').cycle(slidenum, transition)

  if (fullPage) {
    $('#preso').css({'width' : '100%', 'overflow' : 'visible'});
    currentSlide.css({'width' : '100%', 'text-align' : 'center', 'overflow' : 'visible'});
  } else {
    $('#preso').css({'width' : '1020px', 'overflow' : 'hidden'});
  }

  percent = getSlidePercent()
  $("#slideInfo").text((slidenum + 1) + '/' + slideTotal + '  - ' + percent + '%')

  if(!back_step) {
    // determine if there are incremental bullets to show
    // unless we are moving backward
    determineIncremental()
  } else {
    incrCurr = 0
    incrSteps = 0
  }
  location.hash = slidenum + 1;
  $('body').addSwipeEvents().
    bind('swipeleft',  swipeLeft).
    bind('swiperight', swipeRight)
  removeResults()

  return getCurrentNotes()
}

function getSlideProgress()
{
  return (slidenum + 1) + '/' + slideTotal
}

function getCurrentNotes()
{
  return currentSlide.find("p.notes").text()
}

function getSlidePercent()
{
  return Math.ceil(((slidenum + 1) / slideTotal) * 100)
}

function determineIncremental()
{
  incrCurr = 0
  incrCode = false
  incrElem = currentSlide.find(".incremental > ul > li")
  incrSteps = incrElem.size()
  if(incrSteps == 0) {
    // also look for commandline
    incrElem = currentSlide.find(".incremental > pre > code > code")
    incrSteps = incrElem.size()
    incrCode = true
  }
  incrElem.each(function(s, elem) {
    $(elem).hide()
  })
}

function prevStep()
{
  slidenum--
  return showSlide(true) // We show the slide fully loaded
}

function nextStep()
{
  if (incrCurr >= incrSteps) {
    slidenum++
    return showSlide()
  } else {
    elem = incrElem.eq(incrCurr)
    if (incrCode && elem.hasClass('command')) {
      incrElem.eq(incrCurr).show().jTypeWriter({duration:1.0})
    } else {
      incrElem.eq(incrCurr).show()
    }
    incrCurr++
  }
}

function prevStep() {
  slidenum--
  return showSlide(true) // We show the slide fully loaded
}

function doDebugStuff()
{
  if (debugMode) {
    $('#debugInfo').show()
    debug('debug mode on')
  } else {
    $('#debugInfo').hide()
  }
}

function debug(data)
{
  $('#debugInfo').text(data)
}

//  See e.g. http://www.quirksmode.org/js/keys.html for keycodes
function keyDown(event)
{
    var key = event.keyCode;

    if (event.ctrlKey || event.altKey || event.metaKey)
       return true;

    debug('keyDown: ' + key)

    if (key >= 48 && key <= 57) // 0 - 9
    {
      gotoSlidenum = gotoSlidenum * 10 + (key - 48);
      return true;
    }

    if (key == 13){
        if (gotoSlidenum > 0) {
            debug('go to ' + gotoSlidenum);
            slidenum = gotoSlidenum - 1;
            showSlide(true);
            gotoSlidenum = 0;
        } else {
            debug('executeCode');
            executeCode.call($('.sh_javaScript code:visible'));
        }

    }

    if (key == 16) // shift key
    {
      shiftKeyActive = true;
    }
    if (key == 32) // space bar
    {
      if (shiftKeyActive) { prevStep() }
      else                { nextStep() }
    }
    else if (key == 68) // 'd' for debug
    {
      debugMode = !debugMode
      doDebugStuff()
    }
    else if (key == 37 || key == 33) // Left arrow or page up
    {
      prevStep()
    }
    else if (key == 39 || key == 34) // Right arrow or page down
    {
      nextStep()
    }
    else if (key == 82) // R for reload
    {
      if (confirm('really reload slides?')) {
        loadSlides(loadSlidesBool, loadSlidesPrefix)
        showSlide()
      }
    }
    else if (key == 84 || key == 67)  // T or C for table of contents
    {
      $('#navmenu').toggle().trigger('click')
    }
    else if (key == 90) // z for help
    {
      $('#help').toggle()
    }
    else if (key == 66 || key == 70) // f for footer (also "b" which is what kensington remote "stop" button sends
    {
      toggleFooter()
    }
	else if (key == 27) // esc
	{
		removeResults();
	}
    return true
}

function toggleFooter()
{
  $('#footer').toggle()
}

function keyUp(event) {
  var key = event.keyCode;
  debug('keyUp: ' + key);
  if (key == 16) // shift key
  {
    shiftKeyActive = false;
  }
}

function swipeLeft() {
  nextStep()
}

function swipeRight() {
  prevStep()
}

function ListMenu(s)
{
  this.slide = s
  this.typeName = 'ListMenu'
  this.itemLength = 0;
  this.items = new Array();
  this.addItem = function (key, text, slide) {
    if (key.length > 1) {
      thisKey = key.shift()
      if (!this.items[thisKey]) {
        this.items[thisKey] = new ListMenu(slide)
      }
      this.items[thisKey].addItem(key, text, slide)
    } else {
      thisKey = key.shift()
      this.items[thisKey] = new ListMenuItem(text, slide)
    }
  }
  this.getList = function() {
    var newMenu = $("
")
    for(var i in this.items) {
      var item = this.items[i]
      var domItem = $("
")
      if (item.typeName == 'ListMenu') {
        choice = $("" + i + "")
        domItem.append(choice)
        domItem.append(item.getList())
      }
      if (item.typeName == 'ListMenuItem') {
        choice = $("" + item.slide + '. ' + item.textName + "")
        domItem.append(choice)
      }
      newMenu.append(domItem)
    }
    return newMenu
  }
}

function ListMenuItem(t, s)
{
  this.typeName = "ListMenuItem"
  this.slide = s
  this.textName = t
}

var removeResults = function() {
  $('.results').remove();
};

var print = function(text) {
  removeResults();
  var _results = $('
').addClass('results').html($.print(text, {max_string:500}));
  $('body').append(_results);
  _results.click(removeResults);
};

function executeCode () {
    result = null;
    var codeDiv = $(this);
    codeDiv.addClass("executing");
    eval(codeDiv.text());
    setTimeout(function() { codeDiv.removeClass("executing");}, 250 );
    if (result != null) print(result);
}
$('.sh_javaScript code').live("click", executeCode);
<commit_msg>Add down arrow to advance and up arrow for previous slide, for 'out of the box' compatibility with Targus Bluetooth Presenter for Mac.<commit_after>/* ShowOff JS Logic */

var ShowOff = {};

var preso_started = false
var slidenum = 0
var slideTotal = 0
var slides
var currentSlide
var totalslides = 0
var slidesLoaded = false
var incrSteps = 0
var incrElem
var incrCurr = 0
var incrCode = false
var debugMode = false
var gotoSlidenum = 0
var shiftKeyActive = false

var loadSlidesBool
var loadSlidesPrefix

function setupPreso(load_slides, prefix) {
  if (preso_started)
  {
     alert("already started")
     return
  }
  preso_started = true

  loadSlidesBool = load_slides
  loadSlidesPrefix = prefix
  loadSlides(loadSlidesBool, loadSlidesPrefix)

  doDebugStuff()

  // bind event handlers
  document.onkeydown = keyDown
  document.onkeyup = keyUp
  /* window.onresize  = resized; */
  /* window.onscroll = scrolled; */
  /* window.onunload = unloaded; */
}

function loadSlides(load_slides, prefix) {
  //load slides offscreen, wait for images and then initialize
  if (load_slides) {
  	$("#slides").load("/slides", false, function(){
    	$("#slides img").batchImageLoad({
			loadingCompleteCallback: initializePresentation(prefix)
		})
  	})
  } else {
	$("#slides img").batchImageLoad({
		loadingCompleteCallback: initializePresentation(prefix)
	})
  }
}

function initializePresentation(prefix) {
  //center slides offscreen
  centerSlides($('#slides > .slide'))

  //copy into presentation area
  $("#preso").empty()
  $('#slides > .slide').appendTo($("#preso"))

  //populate vars
  slides = $('#preso > .slide')
  slideTotal = slides.size()

  //setup manual jquery cycle
  $('#preso').cycle({
    timeout: 0
  })

  setupMenu()
  if (slidesLoaded) {
    showSlide()
    alert('slides loaded')
  } else {
    showFirstSlide();
    slidesLoaded = true
  }
  setupSlideParamsCheck();
  sh_highlightDocument(prefix+'/js/sh_lang/', '.min.js')
}

function centerSlides(slides) {
  slides.each(function(s, slide) {
    centerSlide(slide)
  })
}

function centerSlide(slide) {
  var slide_content = $(slide).children(".content").first()
  var height = slide_content.height()
  var mar_top = (0.5 * parseFloat($(slide).height())) - (0.5 * parseFloat(height))
  if (mar_top < 0) {
    mar_top = 0
  }
  slide_content.css('margin-top', mar_top)
}

function setupMenu() {
  $('#navmenu').hide();

  var currSlide = 0
  var menu = new ListMenu()

  slides.each(function(s, elem) {
    content = $(elem).children(".content")
    shortTxt = $(content).text().substr(0, 20)
    path = $(content).attr('ref').split('/')
    currSlide += 1
    menu.addItem(path, shortTxt, currSlide)
  })

  $('#navigation').html(menu.getList())
  $('#navmenu').menu({
    content: $('#navigation').html(),
    flyOut: true
  });
}

function checkSlideParameter() {
  if (slideParam = currentSlideFromParams()) {
    slidenum = slideParam;
  }
}

function currentSlideFromParams() {
  var result;
  if (result = window.location.hash.match(/#([0-9]+)/)) {
    return result[result.length - 1] - 1;
  }
}

function setupSlideParamsCheck() {
  var check = function() {
    var currentSlide = currentSlideFromParams();
    if (slidenum != currentSlide) {
      slidenum = currentSlide;
      showSlide();
    }
    setTimeout(check, 100);
  }
  setTimeout(check, 100);
}

function gotoSlide(slideNum) {
  slidenum = parseInt(slideNum)
  if (!isNaN(slidenum)) {
    showSlide()
  }
}

function showFirstSlide() {
  slidenum = 0
  checkSlideParameter();
  showSlide()
}

function showSlide(back_step) {

  if(slidenum < 0) {
    slidenum = 0
    return
  }

  if(slidenum > (slideTotal - 1)) {
    slidenum = slideTotal - 1
    return
  }

  currentSlide = slides.eq(slidenum)

  var transition = currentSlide.attr('data-transition')
  var fullPage = currentSlide.find(".content").is('.full-page');

  if (back_step || fullPage) {
    transition = 'none'
  }

  $('#preso').cycle(slidenum, transition)

  if (fullPage) {
    $('#preso').css({'width' : '100%', 'overflow' : 'visible'});
    currentSlide.css({'width' : '100%', 'text-align' : 'center', 'overflow' : 'visible'});
  } else {
    $('#preso').css({'width' : '1020px', 'overflow' : 'hidden'});
  }

  percent = getSlidePercent()
  $("#slideInfo").text((slidenum + 1) + '/' + slideTotal + '  - ' + percent + '%')

  if(!back_step) {
    // determine if there are incremental bullets to show
    // unless we are moving backward
    determineIncremental()
  } else {
    incrCurr = 0
    incrSteps = 0
  }
  location.hash = slidenum + 1;
  $('body').addSwipeEvents().
    bind('swipeleft',  swipeLeft).
    bind('swiperight', swipeRight)
  removeResults()

  return getCurrentNotes()
}

function getSlideProgress()
{
  return (slidenum + 1) + '/' + slideTotal
}

function getCurrentNotes()
{
  return currentSlide.find("p.notes").text()
}

function getSlidePercent()
{
  return Math.ceil(((slidenum + 1) / slideTotal) * 100)
}

function determineIncremental()
{
  incrCurr = 0
  incrCode = false
  incrElem = currentSlide.find(".incremental > ul > li")
  incrSteps = incrElem.size()
  if(incrSteps == 0) {
    // also look for commandline
    incrElem = currentSlide.find(".incremental > pre > code > code")
    incrSteps = incrElem.size()
    incrCode = true
  }
  incrElem.each(function(s, elem) {
    $(elem).hide()
  })
}

function prevStep()
{
  slidenum--
  return showSlide(true) // We show the slide fully loaded
}

function nextStep()
{
  if (incrCurr >= incrSteps) {
    slidenum++
    return showSlide()
  } else {
    elem = incrElem.eq(incrCurr)
    if (incrCode && elem.hasClass('command')) {
      incrElem.eq(incrCurr).show().jTypeWriter({duration:1.0})
    } else {
      incrElem.eq(incrCurr).show()
    }
    incrCurr++
  }
}

function prevStep() {
  slidenum--
  return showSlide(true) // We show the slide fully loaded
}

function doDebugStuff()
{
  if (debugMode) {
    $('#debugInfo').show()
    debug('debug mode on')
  } else {
    $('#debugInfo').hide()
  }
}

function debug(data)
{
  $('#debugInfo').text(data)
}

//  See e.g. http://www.quirksmode.org/js/keys.html for keycodes
function keyDown(event)
{
    var key = event.keyCode;

    if (event.ctrlKey || event.altKey || event.metaKey)
       return true;

    debug('keyDown: ' + key)

    if (key >= 48 && key <= 57) // 0 - 9
    {
      gotoSlidenum = gotoSlidenum * 10 + (key - 48);
      return true;
    }

    if (key == 13){
        if (gotoSlidenum > 0) {
            debug('go to ' + gotoSlidenum);
            slidenum = gotoSlidenum - 1;
            showSlide(true);
            gotoSlidenum = 0;
        } else {
            debug('executeCode');
            executeCode.call($('.sh_javaScript code:visible'));
        }

    }

    if (key == 16) // shift key
    {
      shiftKeyActive = true;
    }
    if (key == 32) // space bar
    {
      if (shiftKeyActive) { prevStep() }
      else                { nextStep() }
    }
    else if (key == 68) // 'd' for debug
    {
      debugMode = !debugMode
      doDebugStuff()
    }
    else if (key == 37 || key == 33 || key == 38) // Left arrow, page up, or up arrow
    {
      prevStep()
    }
    else if (key == 39 || key == 34 || key == 40) // Right arrow, page down, or down arrow
    {
      nextStep()
    }
    else if (key == 82) // R for reload
    {
      if (confirm('really reload slides?')) {
        loadSlides(loadSlidesBool, loadSlidesPrefix)
        showSlide()
      }
    }
    else if (key == 84 || key == 67)  // T or C for table of contents
    {
      $('#navmenu').toggle().trigger('click')
    }
    else if (key == 90) // z for help
    {
      $('#help').toggle()
    }
    else if (key == 66 || key == 70) // f for footer (also "b" which is what kensington remote "stop" button sends
    {
      toggleFooter()
    }
	else if (key == 27) // esc
	{
		removeResults();
	}
    return true
}

function toggleFooter()
{
  $('#footer').toggle()
}

function keyUp(event) {
  var key = event.keyCode;
  debug('keyUp: ' + key);
  if (key == 16) // shift key
  {
    shiftKeyActive = false;
  }
}

function swipeLeft() {
  nextStep()
}

function swipeRight() {
  prevStep()
}

function ListMenu(s)
{
  this.slide = s
  this.typeName = 'ListMenu'
  this.itemLength = 0;
  this.items = new Array();
  this.addItem = function (key, text, slide) {
    if (key.length > 1) {
      thisKey = key.shift()
      if (!this.items[thisKey]) {
        this.items[thisKey] = new ListMenu(slide)
      }
      this.items[thisKey].addItem(key, text, slide)
    } else {
      thisKey = key.shift()
      this.items[thisKey] = new ListMenuItem(text, slide)
    }
  }
  this.getList = function() {
    var newMenu = $("
")
    for(var i in this.items) {
      var item = this.items[i]
      var domItem = $("
")
      if (item.typeName == 'ListMenu') {
        choice = $("" + i + "")
        domItem.append(choice)
        domItem.append(item.getList())
      }
      if (item.typeName == 'ListMenuItem') {
        choice = $("" + item.slide + '. ' + item.textName + "")
        domItem.append(choice)
      }
      newMenu.append(domItem)
    }
    return newMenu
  }
}

function ListMenuItem(t, s)
{
  this.typeName = "ListMenuItem"
  this.slide = s
  this.textName = t
}

var removeResults = function() {
  $('.results').remove();
};

var print = function(text) {
  removeResults();
  var _results = $('
').addClass('results').html($.print(text, {max_string:500}));
  $('body').append(_results);
  _results.click(removeResults);
};

function executeCode () {
    result = null;
    var codeDiv = $(this);
    codeDiv.addClass("executing");
    eval(codeDiv.text());
    setTimeout(function() { codeDiv.removeClass("executing");}, 250 );
    if (result != null) print(result);
}
$('.sh_javaScript code').live("click", executeCode);
<|endoftext|>


<commit_before>
var EscSidebar = function() {
    var toggleMinus = '/images/minus.jpg';
    var togglePlus = '/images/plus.jpg';

    return {
        toggleMinus : toggleMinus,
        togglePlus : togglePlus,

        clearDefault : function(what) {
            if (what.value == what.defaultValue) {
                what.value = "";
            }
        },

        setDefault : function(what) {
            if (what.value == "") {
                what.value = what.defaultValue;
            }
        },

        loadApplicationsForEnvironment : function(envId, envName) {
            var url = "/environments/" + envName;
            $.getJSON(url, function(appData) {
                var appList = '<ul class="application_list" style="display: none;"';
                $.each(appData, function(appId, thisApp) {
                    appList += "
" + thisApp + "
";
                });
                appList += '
<form id="' + envName + '_new_app_form" class="new_app_form" action="javascript:void(0);"> <input type="text" onFocus="EscSidebar.clearDefault(this)" onBlur="EscSidebar.setDefault(this)" id="new_app_name" value="Add Application"/></form>
';
                appList += '
<form id="' + envName + '_copy_form" class="copy_form" action="javascript:void(0);"> <input type="text" onFocus="EscSidebar.clearDefault(this)" onBlur="EscSidebar.setDefault(this)" id="copy_env_name" value="Copy Environment"/></form>
';
                appList += "
";
                var envObj = $('#sidebar .environment:eq(' + envId + ')');
                envObj.append(appList);
                envObj.children('ul').slideDown('fast');
                $('#sidebar' + " .new_app_form").submit(EscSidebar.createNewApp);
				$('#sidebar' + " .copy_form").submit(EscSidebar.copyEnvironment);
            });
        },

        loadEnvironments : function() {
            $.getJSON("/environments", function(envData) {
                var envList = "
";
                $.each(envData, function(envId, envName) {
                    var toggleState;
                    if ($('#sidebar').data(envName + '_expanded')) {
                        toggleState = toggleMinus;
                        EscSidebar.loadApplicationsForEnvironment(envId, envName);
                    } else {
                        toggleState = togglePlus;
                    };
					envList += ('
');
					envList += ("");
					envList += ('');
                    envList += ('' + envName + '');
                    envList += ('
');
                });
                envList += '
<form id="new_env_form" action="javascript:void(0);"> <input type="text" onFocus="EscSidebar.clearDefault(this)" onBlur="EscSidebar.setDefault(this)" id="new_env_name" name="new_env_name" value="Add Environment"/></form>
';
                envList += "
";
                $('#sidebar').html(envList);
                $('#sidebar' + " #new_env_form").submit(EscSidebar.createNewEnv);
            });
        },

        createNewEnv : function() {
            var newName = $('#new_env_name').val();
            $('#new_env_name').val("");
            $.ajax({
                type: "PUT",
                url: "/environments/" + newName,
                data: {},
                success: function(data, textStatus) {
                    EscSidebar.loadEnvironments();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error creating new environment '" + newName +"': " + XMLHttpRequest.responseText);
                },
            });
        },

        createNewApp : function() {
            var envName = $(this).attr("id").replace('_new_app_form', '');
            var newName = $(this).find(":input").val();
            $(this).find(":input").val("");
            $.ajax({
                type: "PUT",
                url: "/environments/" + envName + "/" + newName,
                data: {},
                success: function(data, textStatus) {
                    EscSidebar.loadEnvironments();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error creating new application '" + newName +"': " + XMLHttpRequest.responseText);
                },
            });
        },

        copyEnvironment : function() {
            var envName = $(this).attr("id").replace('_copy_form', '');
            var newEnvName = $(this).find(":input").val();
            $(this).find(":input").val("");
            $.ajax({
                type: "POST",
                url: "/environments/" + envName,
                data: {},
				headers:{},
                success: function(data, textStatus) {
                    EscSidebar.loadEnvironments();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error copying " + envName + " to " + newEnvName + ": " + XMLHttpRequest.responseText);
                },
            });
        },

        expandAll : function() {
            $('img', $('#sidebar > ul > li')).attr('src', EscSidebar.toggleMinus);
            // Loop through all envs, set collapsed = true
            $.each($('#sidebar > ul > li > span'), function(id, span) {
                var name = $(span).text();
                if (! $('#sidebar').data(name + '_expanded')) {
                    $('#sidebar').data(name + '_expanded', true);
                    EscSidebar.loadApplicationsForEnvironment(id, name);
                };
            });
            EscSidebar.loadEnvironments();
        },

        contractAll : function() {
            $('#sidebar > ul > li > ul').slideUp('fast');
            $('img', $('#sidebar > ul > li')).attr('src', EscSidebar.togglePlus);
            // Loop through all envs, set collapsed = true
            $.each($('#sidebar > ul > li > span'), function(id, span) {
                var myEnv = $(span).text();
                $('#sidebar').data(myEnv + '_expanded', false);
                $(this).siblings('ul').empty();
            });
            EscSidebar.loadEnvironments();
        },

        showEditor : function(env, app) {
            if ((app != null) && (app != "") && (env != null) && (env != "")) {
                EscEditor.editPropertiesFor(env, app);
                $('#new_key').show();
                $('#editor').show();
            } else {
                $('#new_key').hide();
                $('#editor').hide();
            };
        },

        toggleEnv : function(env, img) {
            if ($(img).attr('src') == EscSidebar.toggleMinus) {
                $('#sidebar').data(env + '_expanded', false);
                $(img).attr('src', EscSidebar.togglePlus).siblings('ul').slideUp('fast');
                $(img).siblings('ul').empty();
            } else {
                $('#sidebar').data(env + '_expanded', true);
                $(img).attr('src', EscSidebar.toggleMinus).siblings('ul').slideDown('fast');
                $.each($('.environment > span'), function(id, span) {
                    var name = $(span).text();
                    if (name == env) {
                        EscSidebar.loadApplicationsForEnvironment(id, name);
                    };
                });
            };
        },

// End of namespace
    };
}();

$(document).ready(function() {
    $('#refresh_env').click(function() {
        EscSidebar.loadEnvironments();
    })

    // Expand All
    $('.expand').live("click", function() { EscSidebar.expandAll() });

    // Contract All
    $('.contract').live("click", function() { EscSidebar.contractAll() });

    // Expand or Contract one particular env
    $('.expander_img').live("click", function() {
        var thisEnv = $(this).siblings("span").text();
        EscSidebar.toggleEnv(thisEnv, this);
    });

    $('.envName').live("click", function() {
        EscSidebar.toggleEnv($(this).text(), $(this).siblings('.expander_img'));
    });

    $('.appName').live("click", function() {
        var thisEnv = $(this).parent().parent().siblings("span").text();
        var thisApp = $(this).text();
        EscSidebar.showEditor(thisEnv, thisApp);
    });

    // Click on an app edit button to get stuff in the content pane
    $('.appedit').live("click", function() {
        var thisEnv = $(this).parent().parent().siblings("span").text();
        var thisApp = $(this).parent().text();
        EscSidebar.showEditor(thisEnv, thisApp);
    });

    // Click on an app delete button
    $('.appdelete').live("click", function() {
        var thisEnv = $(this).parent().parent().siblings("span").text();
        var thisApp = $(this).parent().text();
		var confirmation = confirm('Are you sure you want to delete ' + thisApp + '?');

        if ((confirmation) && (thisApp != null) && (thisApp != "")) {
			// Delete the app
			$.ajax({
                type: "DELETE",
                url: "/environments/" + thisEnv + "/" + thisApp,
                data: {},
                success: function(data, textStatus) {
                    EscSidebar.loadEnvironments();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error deleting '" + thisApp +"': " + XMLHttpRequest.responseText);
                },
            })
        };
    });

    // Click on an env delete button
    $('.envdelete').live("click", function() {
        var thisEnv = $(this).siblings("span").text();
		var confirmation = confirm('Are you sure you want to delete ' + thisEnv + '?');
        if ( (confirmation) && (thisEnv != null) && (thisEnv!= "")) {
			// Delete the env
			$.ajax({
                type: "DELETE",
                url: "/environments/" + thisEnv,
                data: {},
                success: function(data, textStatus) {
                    EscSidebar.loadEnvironments();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error deleting '" + thisEnv +"': " + XMLHttpRequest.responseText);
                },
            })
        };
    });

    EscSidebar.loadEnvironments();
    $('#new_key').hide();
    $('#editor').hide();
});

<commit_msg>TS: POSTs a Location: header when trying to copy an environment<commit_after>
var EscSidebar = function() {
    var toggleMinus = '/images/minus.jpg';
    var togglePlus = '/images/plus.jpg';

    return {
        toggleMinus : toggleMinus,
        togglePlus : togglePlus,

        clearDefault : function(what) {
            if (what.value == what.defaultValue) {
                what.value = "";
            }
        },

        setDefault : function(what) {
            if (what.value == "") {
                what.value = what.defaultValue;
            }
        },

        loadApplicationsForEnvironment : function(envId, envName) {
            var url = "/environments/" + envName;
            $.getJSON(url, function(appData) {
                var appList = '<ul class="application_list" style="display: none;"';
                $.each(appData, function(appId, thisApp) {
                    appList += "
" + thisApp + "
";
                });
                appList += '
<form id="' + envName + '_new_app_form" class="new_app_form" action="javascript:void(0);"> <input type="text" onFocus="EscSidebar.clearDefault(this)" onBlur="EscSidebar.setDefault(this)" id="new_app_name" value="Add Application"/></form>
';
                appList += '
<form id="' + envName + '_copy_form" class="copy_form" action="javascript:void(0);"> <input type="text" onFocus="EscSidebar.clearDefault(this)" onBlur="EscSidebar.setDefault(this)" id="copy_env_name" value="Copy Environment"/></form>
';
                appList += "
";
                var envObj = $('#sidebar .environment:eq(' + envId + ')');
                envObj.append(appList);
                envObj.children('ul').slideDown('fast');
                $('#sidebar' + " .new_app_form").submit(EscSidebar.createNewApp);
				$('#sidebar' + " .copy_form").submit(EscSidebar.copyEnvironment);
            });
        },

        loadEnvironments : function() {
            $.getJSON("/environments", function(envData) {
                var envList = "
";
                $.each(envData, function(envId, envName) {
                    var toggleState;
                    if ($('#sidebar').data(envName + '_expanded')) {
                        toggleState = toggleMinus;
                        EscSidebar.loadApplicationsForEnvironment(envId, envName);
                    } else {
                        toggleState = togglePlus;
                    };
					envList += ('
');
					envList += ("");
					envList += ('');
                    envList += ('' + envName + '');
                    envList += ('
');
                });
                envList += '
<form id="new_env_form" action="javascript:void(0);"> <input type="text" onFocus="EscSidebar.clearDefault(this)" onBlur="EscSidebar.setDefault(this)" id="new_env_name" name="new_env_name" value="Add Environment"/></form>
';
                envList += "
";
                $('#sidebar').html(envList);
                $('#sidebar' + " #new_env_form").submit(EscSidebar.createNewEnv);
            });
        },

        createNewEnv : function() {
            var newName = $('#new_env_name').val();
            $('#new_env_name').val("");
            $.ajax({
                type: "PUT",
                url: "/environments/" + newName,
                data: {},
                success: function(data, textStatus) {
                    EscSidebar.loadEnvironments();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error creating new environment '" + newName +"': " + XMLHttpRequest.responseText);
                },
            });
        },

        createNewApp : function() {
            var envName = $(this).attr("id").replace('_new_app_form', '');
            var newName = $(this).find(":input").val();
            $(this).find(":input").val("");
            $.ajax({
                type: "PUT",
                url: "/environments/" + envName + "/" + newName,
                data: {},
                success: function(data, textStatus) {
                    EscSidebar.loadEnvironments();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error creating new application '" + newName +"': " + XMLHttpRequest.responseText);
                },
            });
        },

        copyEnvironment : function() {
            var envName = $(this).attr("id").replace('_copy_form', '');
            var newEnvName = $(this).find(":input").val();
            $(this).find(":input").val("");
			// Warning! Magic!
			$.ajaxSetup({ 'beforeSend': function(header) {header.setRequestHeader("Location", newEnvName)} })
			// /Magic
            $.ajax({
                type: "POST",
                url: "/environments/" + envName,
                data: {},
				header:":Location " + newEnvName,
                success: function(data, textStatus) {
                    EscSidebar.loadEnvironments();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error copying " + envName + " to " + newEnvName + ": " + XMLHttpRequest.responseText);
                },
            });
        },

        expandAll : function() {
            $('img', $('#sidebar > ul > li')).attr('src', EscSidebar.toggleMinus);
            // Loop through all envs, set collapsed = true
            $.each($('#sidebar > ul > li > span'), function(id, span) {
                var name = $(span).text();
                if (! $('#sidebar').data(name + '_expanded')) {
                    $('#sidebar').data(name + '_expanded', true);
                    EscSidebar.loadApplicationsForEnvironment(id, name);
                };
            });
            EscSidebar.loadEnvironments();
        },

        contractAll : function() {
            $('#sidebar > ul > li > ul').slideUp('fast');
            $('img', $('#sidebar > ul > li')).attr('src', EscSidebar.togglePlus);
            // Loop through all envs, set collapsed = true
            $.each($('#sidebar > ul > li > span'), function(id, span) {
                var myEnv = $(span).text();
                $('#sidebar').data(myEnv + '_expanded', false);
                $(this).siblings('ul').empty();
            });
            EscSidebar.loadEnvironments();
        },

        showEditor : function(env, app) {
            if ((app != null) && (app != "") && (env != null) && (env != "")) {
                EscEditor.editPropertiesFor(env, app);
                $('#new_key').show();
                $('#editor').show();
            } else {
                $('#new_key').hide();
                $('#editor').hide();
            };
        },

        toggleEnv : function(env, img) {
            if ($(img).attr('src') == EscSidebar.toggleMinus) {
                $('#sidebar').data(env + '_expanded', false);
                $(img).attr('src', EscSidebar.togglePlus).siblings('ul').slideUp('fast');
                $(img).siblings('ul').empty();
            } else {
                $('#sidebar').data(env + '_expanded', true);
                $(img).attr('src', EscSidebar.toggleMinus).siblings('ul').slideDown('fast');
                $.each($('.environment > span'), function(id, span) {
                    var name = $(span).text();
                    if (name == env) {
                        EscSidebar.loadApplicationsForEnvironment(id, name);
                    };
                });
            };
        },

// End of namespace
    };
}();

$(document).ready(function() {
    $('#refresh_env').click(function() {
        EscSidebar.loadEnvironments();
    })

    // Expand All
    $('.expand').live("click", function() { EscSidebar.expandAll() });

    // Contract All
    $('.contract').live("click", function() { EscSidebar.contractAll() });

    // Expand or Contract one particular env
    $('.expander_img').live("click", function() {
        var thisEnv = $(this).siblings("span").text();
        EscSidebar.toggleEnv(thisEnv, this);
    });

    $('.envName').live("click", function() {
        EscSidebar.toggleEnv($(this).text(), $(this).siblings('.expander_img'));
    });

    $('.appName').live("click", function() {
        var thisEnv = $(this).parent().parent().siblings("span").text();
        var thisApp = $(this).text();
        EscSidebar.showEditor(thisEnv, thisApp);
    });

    // Click on an app edit button to get stuff in the content pane
    $('.appedit').live("click", function() {
        var thisEnv = $(this).parent().parent().siblings("span").text();
        var thisApp = $(this).parent().text();
        EscSidebar.showEditor(thisEnv, thisApp);
    });

    // Click on an app delete button
    $('.appdelete').live("click", function() {
        var thisEnv = $(this).parent().parent().siblings("span").text();
        var thisApp = $(this).parent().text();
		var confirmation = confirm('Are you sure you want to delete ' + thisApp + '?');

        if ((confirmation) && (thisApp != null) && (thisApp != "")) {
			// Delete the app
			$.ajax({
                type: "DELETE",
                url: "/environments/" + thisEnv + "/" + thisApp,
                data: {},
                success: function(data, textStatus) {
                    EscSidebar.loadEnvironments();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error deleting '" + thisApp +"': " + XMLHttpRequest.responseText);
                },
            })
        };
    });

    // Click on an env delete button
    $('.envdelete').live("click", function() {
        var thisEnv = $(this).siblings("span").text();
		var confirmation = confirm('Are you sure you want to delete ' + thisEnv + '?');
        if ( (confirmation) && (thisEnv != null) && (thisEnv!= "")) {
			// Delete the env
			$.ajax({
                type: "DELETE",
                url: "/environments/" + thisEnv,
                data: {},
                success: function(data, textStatus) {
                    EscSidebar.loadEnvironments();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error deleting '" + thisEnv +"': " + XMLHttpRequest.responseText);
                },
            })
        };
    });

    EscSidebar.loadEnvironments();
    $('#new_key').hide();
    $('#editor').hide();
});

<|endoftext|>


<commit_before>// ERPNext - web based ERP (http://erpnext.com)
// Copyright (C) 2012 Web Notes Technologies Pvt Ltd
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

var current_module;
var is_system_manager = 0;

wn.provide('erpnext.startup');

erpnext.startup.set_globals = function() {
	if(inList(user_roles,'System Manager')) is_system_manager = 1;
}

erpnext.startup.start = function() {
	console.log('Starting up...');
	$('#startup_div').html('Starting up...').toggle(true);

	erpnext.startup.set_globals();

	if(user != 'Guest'){
		if(wn.boot.user_background) {
			erpnext.set_user_background(wn.boot.user_background);
		}
		if(wn.boot.profile.defaults.theme) {
			erpnext.set_theme(wn.boot.profile.defaults.theme[0]);
		}

		erpnext.setup_mousetrap();

		// always allow apps
		wn.boot.profile.allow_modules = wn.boot.profile.allow_modules.concat(
			['To Do', 'Knowledge Base', 'Calendar', 'Activity', 'Messages'])

		// setup toolbar
		erpnext.toolbar.setup();

		// set interval for updates
		erpnext.startup.set_periodic_updates();

		// border to the body
		// ------------------
		$('footer').html('
\
			ERPNext | Attributions and License
');

		// complete registration
		if(in_list(user_roles,'System Manager') && (wn.boot.setup_complete=='No')) {
			wn.require("app/js/complete_setup.js");
			erpnext.complete_setup.show();
		}
		if(wn.boot.expires_on && in_list(user_roles, 'System Manager')) {
			var today = dateutil.str_to_obj(dateutil.get_today());
			var expires_on = dateutil.str_to_obj(wn.boot.expires_on);
			var diff = dateutil.get_diff(expires_on, today);
			if (0 <= diff && diff <= 15) {
				var expiry_string = diff==0 ? "today" : repl("in %(diff)s day(s)", { diff: diff });
				$('header').append(repl('
 \
					Your ERPNext subscription will expire %(expiry_string)s. \
					Please renew your subscription to continue using ERPNext \
					(and remove this annoying banner). \

', { expiry_string: expiry_string }));
			} else if (diff < 0) {
				$('header').append(repl('
 \
					This ERPNext subscription has expired. \

', { expiry_string: expiry_string }));
			}
		}
		erpnext.set_about();
		if(wn.control_panel.custom_startup_code)
			eval(wn.control_panel.custom_startup_code);
	}
}

// ========== Update Messages ============
erpnext.update_messages = function(reset) {
	// Updates Team Messages

	if(inList(['Guest'], user) || !wn.session_alive) { return; }

	if(!reset) {
		var set_messages = function(r) {
			if(!r.exc) {
				// This function is defined in toolbar.js
				erpnext.toolbar.set_new_comments(r.message.unread_messages);

				var show_in_circle = function(parent_id, msg) {
					var parent = $('#'+parent_id);
					if(parent) {
						if(msg) {
							parent.find('span:first').text(msg);
							parent.toggle(true);
						} else {
							parent.toggle(false);
						}
					}
				}

				show_in_circle('unread_messages', r.message.unread_messages.length);
				show_in_circle('open_support_tickets', r.message.open_support_tickets);
				show_in_circle('things_todo', r.message.things_todo);
				show_in_circle('todays_events', r.message.todays_events);
				show_in_circle('open_tasks', r.message.open_tasks);
				show_in_circle('unanswered_questions', r.message.unanswered_questions);

			} else {
				clearInterval(wn.updates.id);
			}
		}

		wn.call({
			method: 'startup.startup.get_global_status_messages',
			callback: set_messages
		});

	} else {
		erpnext.toolbar.set_new_comments(0);
		$('#unread_messages').toggle(false);
	}
}

erpnext.startup.set_periodic_updates = function() {
	// Set interval for periodic updates of team messages
	wn.updates = {};

	if(wn.updates.id) {
		clearInterval(wn.updates.id);
	}

	wn.updates.id = setInterval(erpnext.update_messages, 60000);
}

erpnext.set_user_background = function(src) {
	set_style(repl('#body_div { background: url("files/%(src)s") repeat fixed;}',
		{src:src}))
}

// subject, sender, description
erpnext.send_message = function(opts) {
	if(opts.btn) {
		$(opts.btn).start_working();
	}
	wn.call({
		method: 'website.send_message',
		args: opts,
		callback: function(r) {
			if(opts.btn) {
				$(opts.btn).done_working();
			}
			if(opts.callback)opts.callback(r)
		}
	});
}

erpnext.hide_naming_series = function() {
	if(cur_frm.fields_dict.naming_series) {
		hide_field('naming_series');
		if(cur_frm.doc.__islocal) {
			unhide_field('naming_series');
		}
	}
}

erpnext.setup_mousetrap = function() {
	Mousetrap.bind(["command+g", "ctrl+g"], function() {
		wn.ui.toolbar.search.show();
		return false;
	});

	Mousetrap.bind(["command+s", "ctrl+s"], function() {
		if(cur_frm)
			cur_frm.save();
		else if(wn.container.page.save_action)
			wn.container.page.save_action();
		return false;
	});
}

// start
$(document).bind('startup', function() {
	erpnext.startup.start();
});
<commit_msg>passing server date in boot and checking expiry against the server date<commit_after>// ERPNext - web based ERP (http://erpnext.com)
// Copyright (C) 2012 Web Notes Technologies Pvt Ltd
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

var current_module;
var is_system_manager = 0;

wn.provide('erpnext.startup');

erpnext.startup.set_globals = function() {
	if(inList(user_roles,'System Manager')) is_system_manager = 1;
}

erpnext.startup.start = function() {
	console.log('Starting up...');
	$('#startup_div').html('Starting up...').toggle(true);

	erpnext.startup.set_globals();

	if(user != 'Guest'){
		if(wn.boot.user_background) {
			erpnext.set_user_background(wn.boot.user_background);
		}
		if(wn.boot.profile.defaults.theme) {
			erpnext.set_theme(wn.boot.profile.defaults.theme[0]);
		}

		erpnext.setup_mousetrap();

		// always allow apps
		wn.boot.profile.allow_modules = wn.boot.profile.allow_modules.concat(
			['To Do', 'Knowledge Base', 'Calendar', 'Activity', 'Messages'])

		// setup toolbar
		erpnext.toolbar.setup();

		// set interval for updates
		erpnext.startup.set_periodic_updates();

		// border to the body
		// ------------------
		$('footer').html('
\
			ERPNext | Attributions and License
');

		// complete registration
		if(in_list(user_roles,'System Manager') && (wn.boot.setup_complete=='No')) {
			wn.require("app/js/complete_setup.js");
			erpnext.complete_setup.show();
		}
		if(wn.boot.expires_on && in_list(user_roles, 'System Manager')) {
			var today = dateutil.str_to_obj(wn.boot.server_date);
			var expires_on = dateutil.str_to_obj(wn.boot.expires_on);
			var diff = dateutil.get_diff(expires_on, today);
			if (0 <= diff && diff <= 15) {
				var expiry_string = diff==0 ? "today" : repl("in %(diff)s day(s)", { diff: diff });
				$('header').append(repl('
 \
					Your ERPNext subscription will expire %(expiry_string)s. \
					Please renew your subscription to continue using ERPNext \
					(and remove this annoying banner). \

', { expiry_string: expiry_string }));
			} else if (diff < 0) {
				$('header').append(repl('
 \
					This ERPNext subscription has expired. \

', { expiry_string: expiry_string }));
			}
		}
		erpnext.set_about();
		if(wn.control_panel.custom_startup_code)
			eval(wn.control_panel.custom_startup_code);
	}
}

// ========== Update Messages ============
erpnext.update_messages = function(reset) {
	// Updates Team Messages

	if(inList(['Guest'], user) || !wn.session_alive) { return; }

	if(!reset) {
		var set_messages = function(r) {
			if(!r.exc) {
				// This function is defined in toolbar.js
				erpnext.toolbar.set_new_comments(r.message.unread_messages);

				var show_in_circle = function(parent_id, msg) {
					var parent = $('#'+parent_id);
					if(parent) {
						if(msg) {
							parent.find('span:first').text(msg);
							parent.toggle(true);
						} else {
							parent.toggle(false);
						}
					}
				}

				show_in_circle('unread_messages', r.message.unread_messages.length);
				show_in_circle('open_support_tickets', r.message.open_support_tickets);
				show_in_circle('things_todo', r.message.things_todo);
				show_in_circle('todays_events', r.message.todays_events);
				show_in_circle('open_tasks', r.message.open_tasks);
				show_in_circle('unanswered_questions', r.message.unanswered_questions);

			} else {
				clearInterval(wn.updates.id);
			}
		}

		wn.call({
			method: 'startup.startup.get_global_status_messages',
			callback: set_messages
		});

	} else {
		erpnext.toolbar.set_new_comments(0);
		$('#unread_messages').toggle(false);
	}
}

erpnext.startup.set_periodic_updates = function() {
	// Set interval for periodic updates of team messages
	wn.updates = {};

	if(wn.updates.id) {
		clearInterval(wn.updates.id);
	}

	wn.updates.id = setInterval(erpnext.update_messages, 60000);
}

erpnext.set_user_background = function(src) {
	set_style(repl('#body_div { background: url("files/%(src)s") repeat fixed;}',
		{src:src}))
}

// subject, sender, description
erpnext.send_message = function(opts) {
	if(opts.btn) {
		$(opts.btn).start_working();
	}
	wn.call({
		method: 'website.send_message',
		args: opts,
		callback: function(r) {
			if(opts.btn) {
				$(opts.btn).done_working();
			}
			if(opts.callback)opts.callback(r)
		}
	});
}

erpnext.hide_naming_series = function() {
	if(cur_frm.fields_dict.naming_series) {
		hide_field('naming_series');
		if(cur_frm.doc.__islocal) {
			unhide_field('naming_series');
		}
	}
}

erpnext.setup_mousetrap = function() {
	Mousetrap.bind(["command+g", "ctrl+g"], function() {
		wn.ui.toolbar.search.show();
		return false;
	});

	Mousetrap.bind(["command+s", "ctrl+s"], function() {
		if(cur_frm)
			cur_frm.save();
		else if(wn.container.page.save_action)
			wn.container.page.save_action();
		return false;
	});
}

// start
$(document).bind('startup', function() {
	erpnext.startup.start();
});
<|endoftext|>


<commit_before>$(document).ready(function(){
  var survey_id = $("#SI").attr("survey-id")
  var completion_id = $("#SI").attr("completion-id")

  $.when (
        $.ajax({
            url: "/surveys/" + survey_id + "/comparison/" + completion_id,
            method: 'get',
            dataType: "json"
        })
    ).done(function(response){
      var my_data = [];

      for(var i = 0; i < response[0].length; i++){

        var my_data_total = 0;
        var my_ticks = []

        for(var ii = 0; ii < response[0][i][1].length; ii++){
            my_data_total += response[0][i][1][ii][1];
        }

        for(var ii = 0; ii < response[0][i][1].length; ii++){
          debugger;
          if(response[0][i][1][ii][0] == response[1][i]){
            my_data.push((response[0][i][1][ii][1]/ my_data_total));
          }
        }
        $(".compare-" + String(i))[0].innerHTML = String(Math.round(my_data[i] * 100))
      }
    }
  )
})
<commit_msg>remove debugger<commit_after>$(document).ready(function(){
  var survey_id = $("#SI").attr("survey-id")
  var completion_id = $("#SI").attr("completion-id")

  $.when (
        $.ajax({
            url: "/surveys/" + survey_id + "/comparison/" + completion_id,
            method: 'get',
            dataType: "json"
        })
    ).done(function(response){
      var my_data = [];

      for(var i = 0; i < response[0].length; i++){

        var my_data_total = 0;
        var my_ticks = []

        for(var ii = 0; ii < response[0][i][1].length; ii++){
            my_data_total += response[0][i][1][ii][1];
        }

        for(var ii = 0; ii < response[0][i][1].length; ii++){
          if(response[0][i][1][ii][0] == response[1][i]){
            my_data.push((response[0][i][1][ii][1]/ my_data_total));
          }
        }
        $(".compare-" + String(i))[0].innerHTML = String(Math.round(my_data[i] * 100))
      }
    }
  )
})
<|endoftext|>


<commit_before>var id;
var array;
var game;
var newTables;
var push = true;
var timeLock = false;

function sync_sv() {
	var = lockTimer;
    socket.emit("get seated players");
    socket.on("chrono", function(i, str) {
        $("#chrono").html(str + '
' + i + ' sec remaining
to add more players');
        var chrono = setInterval(function() {
            i--;
            $("#sec").html(i);
            if (i == 0) {
                clearInterval(chrono);
            }
        }, 1000);
    });
    socket.on("chrono off", function() {
        $("#chrono").empty();
    });
	socket.on("action is true", function() {
		timeLock = true;
	});
	socket.on("timer action", function(table, nick) {
		var sec = 0;

		console.log("Start timer");
		lockTimer = setInterval(function() {
			sec++;
			console.log('Statut '+timeLock + ' ' + sec);
			if (timeLock && sec != 30) {
				clearInterval(lockTimer);
				timeLock = false;
				return;
			} else if (sec == 30) {
				clearInterval(lockTimer);
				timeLock = false;
				socket.emit("stop timer action", table, nick);
				//stop_timer(table, nick);
			}
		}, 1000);
	});
    socket.on("seated players info", function(seat, seat_idx) {
        $("#qr" + seat_idx).css("visibility", "hidden");
        $("#qr_spot" + seat_idx).css("visibility", "hidden");
        $("#scan_msg" + seat_idx).css("visibility", "hidden");
        $("#player_name" + seat_idx).css("visibility", "visible");
        $("#player_name" + seat_idx).text(seat.player.nickname);
        $("#player_bankroll" + seat_idx).css("visibility", "visible");
        $("#player_bankroll" + seat_idx).text((Math.floor(+seat.player.bankroll * 100)) / 100 + "$");
        $("#player_cards" + seat_idx).css("visibility", "visible");
    });
    socket.on("new player", function(player) {
        $("#qr" + player.seat_nb).css("visibility", "hidden");
        $("#qr_spot" + player.seat_nb).css("visibility", "hidden");
        $("#scan_msg" + player.seat_nb).css("visibility", "hidden");
        $("#player_name" + player.seat_nb).css("visibility", "visible");
        $("#player_name" + player.seat_nb).text(player.nickname);
        $("#player_bankroll" + player.seat_nb).css("visibility", "visible");
        $("#player_bankroll" + player.seat_nb).text((Math.floor(+player.bankroll * 100)) / 100 + "$");
        $("#player_cards" + player.seat_nb).css("visibility", "visible");
    });
    socket.on("kick player", function(seat_nb) {
        $("#qr" + seat_nb).css("visibility", "visible");
        $("#qr_spot" + seat_nb).css("visibility", "visible");
        $("#scan_msg" + seat_nb).css("visibility", "visible");
        $("#player_name" + seat_nb).css("visibility", "hidden");
        $("#player_name" + seat_nb).text("");
        $("#player_bankroll" + seat_nb).css("visibility", "hidden");
        $("#player_bankroll" + seat_nb).text("");
        $("#player_cards" + seat_nb).css("visibility", "hidden");
        $("#btn" + seat_nb).attr("src", "");
        $("#btn" + seat_nb).css("visibility", "hidden");
		$("#card1_" + seat_nb).css("visibility", "hidden");
		$("#card2_" + seat_nb).css("visibility", "hidden");
		$("#last_action"+ seat_nb).css("visibility", "hidden");
    });
    socket.emit("ask buttons");
    socket.on("place button", function(type, seat_nb) {
        if (seat_nb <= 0 || seat_nb >= 7)
            return;
        if (type == "dealer") {
            $("#btn" + seat_nb).attr("src", "../img/Dealer.png")
            $("#btn" + seat_nb).css("visibility", "visible");
        } else if (type == "sb") {
            $("#btn" + seat_nb).attr("src", "../img/sb.png")
            $("#btn" + seat_nb).css("visibility", "visible");
        } else if (type == "bb") {
            $("#btn" + seat_nb).attr("src", "../img/bb.png")
            $("#btn" + seat_nb).css("visibility", "visible");
        }
        $("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
    });
    socket.on("give cards", function(seat_nb) {
        $("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
    });
    socket.on("highlights", function(seat_idx, new_state) {
        if (new_state == "off")
            $("#seat" + seat_idx).css("background-color", "#006F60");
        else if (new_state == "on")
            $("#seat" + seat_idx).css("background-color", "#FE554C");
    });
    socket.on("bankroll modification", function(seat_idx, player) {
        if (player.bankroll == "ALL IN")
            $("#player_bankroll" + seat_idx).text("ALL IN");
        else
            $("#player_bankroll" + seat_idx).text((Math.floor(player.bankroll * 100)) / 100 + "$");
    });
    socket.on("pot modification", function(pot_amount) {
        $("#pot").text(Math.floor(+pot_amount * 100) / 100 + "$");
    });
    socket.on("bet", function(seat_idx, amount) {
        if (!amount)
            $("#bet_val" + seat_idx).text('');
        else {
            $("#bet_val" + seat_idx).text((Math.floor(amount * 100)) / 100 + "$");
        }
    });

    socket.on("last action", function(decision, seat_nb, amount) {
        amount == 0 ? amount = "" : amount = " " + amount + "$";
        var nick = $("#player_name" + seat_nb).text();
        var str = decision.split(" ");
        var text = "
" + nick + " " + str[0] + amount + "
";

        $("#last_action" + seat_nb).text(str[0]);
        $("#histoContent").empty();
        $("#histoContent").append(text);
    });
    socket.on("fold", function(seat_nb) {
        $("#btn" + seat_nb).css("visibility", "hidden");
        $("#bet_val" + seat_nb).text('');
        $("#player_cards" + seat_nb).attr("src", "../img/avatar.png");
        $("#last_action" + seat_nb).text('');
    });
    socket.emit("get board");
    socket.on("send flop", function(card1, card2, card3) {
        $("#b1").attr("src", "img/cards/" + card1 + ".png");
        $("#b2").attr("src", "img/cards/" + card2 + ".png");
        $("#b3").attr("src", "img/cards/" + card3 + ".png");
        $("#b1, #b2, #b3").css("visibility", "visible");
    });
    socket.on("send turn", function(card4) {
        $("#b4").attr("src", "img/cards/" + card4 + ".png");
        $("#b4").css("visibility", "visible");
    });
    socket.on("send river", function(card5) {
        $("#b5").attr("src", "img/cards/" + card5 + ".png");
        $("#b5").css("visibility", "visible");
    });
    socket.on("remove last actions", function() {
        for (var idx = 1; idx <= 6; ++idx)
            $("#last_action" + idx).remove();
    });
    socket.on("remove board", function() {
        $("#b1, #b2, #b3, #b4, #b5").css("visibility", "hidden");
        for (var idx = 1; idx <= 6; ++idx)
            $("#player_cards" + idx).attr("src", "../img/avatar.png");
    });
    socket.on("remove emplacements", function() {
        for (var idx = 1; idx <= 6; ++idx)
            $("#btn" + idx).css("visibility", "hidden");
    });
    socket.on("show down", function(card1, card2, seat_nb) {
        if ($('#qr_spot' + seat_nb).css('visibility') == 'hidden') {
			if (card1 && card2) {
            	$("#card1_" + seat_nb).attr("src", "../img/cards/" + card1 + ".png");
            	$("#card2_" + seat_nb).attr("src", "../img/cards/" + card2 + ".png");
	            $("#card1_" + seat_nb).css("visibility", "visible");
	            $("#card2_" + seat_nb).css("visibility", "visible");
			}
        }
    });
    socket.on("show down off", function(seat_nb) {
        $("#card1_" + seat_nb).css("visibility", "hidden");
        $("#card2_" + seat_nb).css("visibility", "hidden");
    });
    socket.on("winner", function(seat_nb, rank_name) {
        var disconnect = '
' + $("#player_name" + seat_nb).text() + ' won because player ' + rank_name + ' or folded
';
        var won = '
' + $("#player_name" + seat_nb).text() + ' won with ' + rank_name + '
';

        if (rank_name == 'disconnected') {
            //$("#winner_msg").text($("#player_name" + seat_nb).text());
            $('#histoContent').empty();
            $('#histoContent').append(disconnect);
        } else if (seat_nb == 42 && rank_name == 'null') {
            //$("#winner_msg").text("Split!");
            $('#histoContent').empty();
            $('#histoContent').append('
Split !
');
        } else {
            $('#histoContent').empty();
            $('#histoContent').append(won);
        }
        //$("#winner").css("visibility", "visible");
    });
    socket.on("win off", function() {
        $("#winner, #card1_1, #card2_1, #card1_2, #card2_2, #card1_3, #card2_3, #card1_4, #card2_4, #card1_5, #card2_5, #card1_6, #card2_6").css("visibility", "hidden");
    });
}

function check_timeLock(action) {
    timeLock = action;
}

function get_seat(seats, idx) {
    if (idx == 1)
        return seats.seat1;
    else if (idx == 2)
        return seats.seat2;
    else if (idx == 3)
        return seats.seat3;
    else if (idx == 4)
        return seats.seat4;
    else if (idx == 5)
        return seats.seat5;
    else if (idx == 6)
        return seats.seat6;
    return 0;
}

function get_table(table_id, tables) {
    var idx = 0;

    while (idx < tables.length) {
        if (tables[idx].id == table_id)
            return tables[idx];
        ++idx;
    }
    return "not found";
}

socket.on('tableId', function(tableId, tables, tableGame) {
    id = tableId;
    array = tables;
    game = tableGame;
});

function restart() {
    socket.emit('get tableId and tableGame', id);
    socket.on('give tableId and tableGame', function(tables, tableGame) {
        array = tables;
        game = tableGame;
    });
    console.log(array, game);
    push = false;
}

function confirm() {
    push = true;
    socket.emit('get tableId and tableGame', id);
    socket.on('give tableId and tableGame', function(tables, tableGame) {
        array = tables;
        game = tableGame;
    });
    console.log(array, game);
	socket.emit("to preflop", 1);
    socket.emit('re init', array, game);
}
<commit_msg>refix<commit_after>var id;
var array;
var game;
var newTables;
var push = true;
var timeLock = false;

function sync_sv() {
	var lockTimer;
    socket.emit("get seated players");
    socket.on("chrono", function(i, str) {
        $("#chrono").html(str + '
' + i + ' sec remaining
to add more players');
        var chrono = setInterval(function() {
            i--;
            $("#sec").html(i);
            if (i == 0) {
                clearInterval(chrono);
            }
        }, 1000);
    });
    socket.on("chrono off", function() {
        $("#chrono").empty();
    });
	socket.on("action is true", function() {
		timeLock = true;
	});
	socket.on("timer action", function(table, nick) {
		var sec = 0;

		console.log("Start timer");
		lockTimer = setInterval(function() {
			sec++;
			console.log('Statut '+timeLock + ' ' + sec);
			if (timeLock && sec != 30) {
				clearInterval(lockTimer);
				timeLock = false;
				return;
			} else if (sec == 30) {
				clearInterval(lockTimer);
				timeLock = false;
				socket.emit("stop timer action", table, nick);
				//stop_timer(table, nick);
			}
		}, 1000);
	});
    socket.on("seated players info", function(seat, seat_idx) {
        $("#qr" + seat_idx).css("visibility", "hidden");
        $("#qr_spot" + seat_idx).css("visibility", "hidden");
        $("#scan_msg" + seat_idx).css("visibility", "hidden");
        $("#player_name" + seat_idx).css("visibility", "visible");
        $("#player_name" + seat_idx).text(seat.player.nickname);
        $("#player_bankroll" + seat_idx).css("visibility", "visible");
        $("#player_bankroll" + seat_idx).text((Math.floor(+seat.player.bankroll * 100)) / 100 + "$");
        $("#player_cards" + seat_idx).css("visibility", "visible");
    });
    socket.on("new player", function(player) {
        $("#qr" + player.seat_nb).css("visibility", "hidden");
        $("#qr_spot" + player.seat_nb).css("visibility", "hidden");
        $("#scan_msg" + player.seat_nb).css("visibility", "hidden");
        $("#player_name" + player.seat_nb).css("visibility", "visible");
        $("#player_name" + player.seat_nb).text(player.nickname);
        $("#player_bankroll" + player.seat_nb).css("visibility", "visible");
        $("#player_bankroll" + player.seat_nb).text((Math.floor(+player.bankroll * 100)) / 100 + "$");
        $("#player_cards" + player.seat_nb).css("visibility", "visible");
    });
    socket.on("kick player", function(seat_nb) {
        $("#qr" + seat_nb).css("visibility", "visible");
        $("#qr_spot" + seat_nb).css("visibility", "visible");
        $("#scan_msg" + seat_nb).css("visibility", "visible");
        $("#player_name" + seat_nb).css("visibility", "hidden");
        $("#player_name" + seat_nb).text("");
        $("#player_bankroll" + seat_nb).css("visibility", "hidden");
        $("#player_bankroll" + seat_nb).text("");
        $("#player_cards" + seat_nb).css("visibility", "hidden");
        $("#btn" + seat_nb).attr("src", "");
        $("#btn" + seat_nb).css("visibility", "hidden");
		$("#card1_" + seat_nb).css("visibility", "hidden");
		$("#card2_" + seat_nb).css("visibility", "hidden");
		$("#last_action"+ seat_nb).css("visibility", "hidden");
    });
    socket.emit("ask buttons");
    socket.on("place button", function(type, seat_nb) {
        if (seat_nb <= 0 || seat_nb >= 7)
            return;
        if (type == "dealer") {
            $("#btn" + seat_nb).attr("src", "../img/Dealer.png")
            $("#btn" + seat_nb).css("visibility", "visible");
        } else if (type == "sb") {
            $("#btn" + seat_nb).attr("src", "../img/sb.png")
            $("#btn" + seat_nb).css("visibility", "visible");
        } else if (type == "bb") {
            $("#btn" + seat_nb).attr("src", "../img/bb.png")
            $("#btn" + seat_nb).css("visibility", "visible");
        }
        $("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
    });
    socket.on("give cards", function(seat_nb) {
        $("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
    });
    socket.on("highlights", function(seat_idx, new_state) {
        if (new_state == "off")
            $("#seat" + seat_idx).css("background-color", "#006F60");
        else if (new_state == "on")
            $("#seat" + seat_idx).css("background-color", "#FE554C");
    });
    socket.on("bankroll modification", function(seat_idx, player) {
        if (player.bankroll == "ALL IN")
            $("#player_bankroll" + seat_idx).text("ALL IN");
        else
            $("#player_bankroll" + seat_idx).text((Math.floor(player.bankroll * 100)) / 100 + "$");
    });
    socket.on("pot modification", function(pot_amount) {
        $("#pot").text(Math.floor(+pot_amount * 100) / 100 + "$");
    });
    socket.on("bet", function(seat_idx, amount) {
        if (!amount)
            $("#bet_val" + seat_idx).text('');
        else {
            $("#bet_val" + seat_idx).text((Math.floor(amount * 100)) / 100 + "$");
        }
    });

    socket.on("last action", function(decision, seat_nb, amount) {
        amount == 0 ? amount = "" : amount = " " + amount + "$";
        var nick = $("#player_name" + seat_nb).text();
        var str = decision.split(" ");
        var text = "
" + nick + " " + str[0] + amount + "
";

        $("#last_action" + seat_nb).text(str[0]);
        $("#histoContent").empty();
        $("#histoContent").append(text);
    });
    socket.on("fold", function(seat_nb) {
        $("#btn" + seat_nb).css("visibility", "hidden");
        $("#bet_val" + seat_nb).text('');
        $("#player_cards" + seat_nb).attr("src", "../img/avatar.png");
        $("#last_action" + seat_nb).text('');
    });
    socket.emit("get board");
    socket.on("send flop", function(card1, card2, card3) {
        $("#b1").attr("src", "img/cards/" + card1 + ".png");
        $("#b2").attr("src", "img/cards/" + card2 + ".png");
        $("#b3").attr("src", "img/cards/" + card3 + ".png");
        $("#b1, #b2, #b3").css("visibility", "visible");
    });
    socket.on("send turn", function(card4) {
        $("#b4").attr("src", "img/cards/" + card4 + ".png");
        $("#b4").css("visibility", "visible");
    });
    socket.on("send river", function(card5) {
        $("#b5").attr("src", "img/cards/" + card5 + ".png");
        $("#b5").css("visibility", "visible");
    });
    socket.on("remove last actions", function() {
        for (var idx = 1; idx <= 6; ++idx)
            $("#last_action" + idx).remove();
    });
    socket.on("remove board", function() {
        $("#b1, #b2, #b3, #b4, #b5").css("visibility", "hidden");
        for (var idx = 1; idx <= 6; ++idx)
            $("#player_cards" + idx).attr("src", "../img/avatar.png");
    });
    socket.on("remove emplacements", function() {
        for (var idx = 1; idx <= 6; ++idx)
            $("#btn" + idx).css("visibility", "hidden");
    });
    socket.on("show down", function(card1, card2, seat_nb) {
        if ($('#qr_spot' + seat_nb).css('visibility') == 'hidden') {
			if (card1 && card2) {
            	$("#card1_" + seat_nb).attr("src", "../img/cards/" + card1 + ".png");
            	$("#card2_" + seat_nb).attr("src", "../img/cards/" + card2 + ".png");
	            $("#card1_" + seat_nb).css("visibility", "visible");
	            $("#card2_" + seat_nb).css("visibility", "visible");
			}
        }
    });
    socket.on("show down off", function(seat_nb) {
        $("#card1_" + seat_nb).css("visibility", "hidden");
        $("#card2_" + seat_nb).css("visibility", "hidden");
    });
    socket.on("winner", function(seat_nb, rank_name) {
        var disconnect = '
' + $("#player_name" + seat_nb).text() + ' won because player ' + rank_name + ' or folded
';
        var won = '
' + $("#player_name" + seat_nb).text() + ' won with ' + rank_name + '
';

        if (rank_name == 'disconnected') {
            //$("#winner_msg").text($("#player_name" + seat_nb).text());
            $('#histoContent').empty();
            $('#histoContent').append(disconnect);
        } else if (seat_nb == 42 && rank_name == 'null') {
            //$("#winner_msg").text("Split!");
            $('#histoContent').empty();
            $('#histoContent').append('
Split !
');
        } else {
            $('#histoContent').empty();
            $('#histoContent').append(won);
        }
        //$("#winner").css("visibility", "visible");
    });
    socket.on("win off", function() {
        $("#winner, #card1_1, #card2_1, #card1_2, #card2_2, #card1_3, #card2_3, #card1_4, #card2_4, #card1_5, #card2_5, #card1_6, #card2_6").css("visibility", "hidden");
    });
}

function check_timeLock(action) {
    timeLock = action;
}

function get_seat(seats, idx) {
    if (idx == 1)
        return seats.seat1;
    else if (idx == 2)
        return seats.seat2;
    else if (idx == 3)
        return seats.seat3;
    else if (idx == 4)
        return seats.seat4;
    else if (idx == 5)
        return seats.seat5;
    else if (idx == 6)
        return seats.seat6;
    return 0;
}

function get_table(table_id, tables) {
    var idx = 0;

    while (idx < tables.length) {
        if (tables[idx].id == table_id)
            return tables[idx];
        ++idx;
    }
    return "not found";
}

socket.on('tableId', function(tableId, tables, tableGame) {
    id = tableId;
    array = tables;
    game = tableGame;
});

function restart() {
    socket.emit('get tableId and tableGame', id);
    socket.on('give tableId and tableGame', function(tables, tableGame) {
        array = tables;
        game = tableGame;
    });
    console.log(array, game);
    push = false;
}

function confirm() {
    push = true;
    socket.emit('get tableId and tableGame', id);
    socket.on('give tableId and tableGame', function(tables, tableGame) {
        array = tables;
        game = tableGame;
    });
    console.log(array, game);
	socket.emit("to preflop", 1);
    socket.emit('re init', array, game);
}
<|endoftext|>


<commit_before>function	sync_sv()
{
	socket.emit("get seated players");
	socket.on("seated players info", function(seat, seat_idx)
	{
		$("#qr" + seat_idx).css("visibility", "hidden");
		$("#qr_spot" + seat_idx).css("visibility", "hidden");
		$("#scan_msg" + seat_idx).css("visibility", "hidden");
		$("#player_name" + seat_idx).css("visibility", "visible");
		$("#player_name" + seat_idx).text(seat.player.nickname);
		$("#player_bankroll" + seat_idx).css("visibility", "visible");
		$("#player_bankroll" + seat_idx).text((Math.floor(+seat.player.bankroll * 100)) / 100 + "$");
		$("#player_cards"+ seat_idx).css("visibility", "visible");
	});
	socket.on("new player", function(player)
	{
		$("#qr" + player.seat_nb).css("visibility", "hidden");
		$("#qr_spot" + player.seat_nb).css("visibility", "hidden");
		$("#scan_msg" + player.seat_nb).css("visibility", "hidden");
		$("#player_name" + player.seat_nb).css("visibility", "visible");
		$("#player_name" + player.seat_nb).text(player.nickname);
		$("#player_bankroll" + player.seat_nb).css("visibility", "visible");
		$("#player_bankroll" + player.seat_nb).text((Math.floor(+player.bankroll * 100)) / 100 + "$");
		$("#player_cards"+ player.seat_nb).css("visibility", "visible");
	});
	socket.on("kick player", function(seat_nb)
	{
		$("#qr" + seat_nb).css("visibility", "visible");
		$("#qr_spot" + seat_nb).css("visibility", "visible");
		$("#scan_msg" + seat_nb).css("visibility", "visible");
		$("#player_name" + seat_nb).css("visibility", "hidden");
		$("#player_name" + seat_nb).text("");
		$("#player_bankroll" + seat_nb).css("visibility", "hidden");
		$("#player_bankroll" + seat_nb).text("");
		$("#player_cards"+ seat_nb).css("visibility", "hidden");
		$("#btn" + seat_nb).attr("src", "");
		$("#btn" + seat_nb).css("visibility", "hidden");
	});
	socket.emit("ask buttons");
	socket.on("place button", function(type, seat_nb)
	{
		if (seat_nb <= 0 || seat_nb >= 7)
			return ;
		if (type == "dealer")
		{
			$("#btn" + seat_nb).attr("src", "../img/Dealer.png")
			$("#btn" + seat_nb).css("visibility", "visible");
		}
		else if (type == "sb")
		{
			$("#btn" + seat_nb).attr("src", "../img/sb.png")
			$("#btn" + seat_nb).css("visibility", "visible");
		}
		else if (type == "bb")
		{
			$("#btn" + seat_nb).attr("src", "../img/bb.png")
			$("#btn" + seat_nb).css("visibility", "visible");
		}
		$("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
	});
	socket.on("give cards", function(seat_nb)
	{
		$("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
	});
	socket.on("highlights", function(seat_idx, new_state)
	{
		if (new_state == "off")
			$("#seat" + seat_idx).css("background-color", "#006F60");
		else if (new_state == "on")
			$("#seat" + seat_idx).css("background-color", "#FE554C");
	});
	socket.on("bankroll modification", function(seat_idx, player)
	{
		if (player.bankroll == "ALL IN")
			$("#player_bankroll" + seat_idx).text("ALL IN");
		else
			$("#player_bankroll" + seat_idx).text((Math.floor(player.bankroll * 100)) / 100 + "$");
	});
	socket.on("pot modification", function(pot_amount)
	{
		$("#pot").text(Math.floor(+pot_amount * 100) / 100 + "$");
	});
	socket.on("bet", function(seat_idx, amount)
	{
		if (!amount)
			$("#bet_val" + seat_idx).text('');
		else {
			$("#bet_val" + seat_idx).text((Math.floor(amount * 100)) / 100 + "$");
		}
	});

	socket.on("last action", function(decision, seat_nb)
	{
		$("#last_action" + seat_nb).text(decision);
	});
	socket.on("fold", function(seat_nb)
	{
		$("#btn" + seat_nb).css("visibility", "hidden");
		$("#bet_val" + seat_nb).text('');
		$("#player_cards" + seat_nb).attr("src", "../img/avatar.png");
		$("#last_action" + seat_nb).text('');
	});
	socket.emit("get board");
	socket.on("send flop", function(card1, card2, card3)
	{
		$("#b1").attr("src", "img/cards/" + card1 + ".png");
		$("#b2").attr("src", "img/cards/" + card2 + ".png");
		$("#b3").attr("src", "img/cards/" + card3 + ".png");
		$("#b1, #b2, #b3").css("visibility", "visible");
	});
	socket.on("send turn", function(card4)
	{
		$("#b4").attr("src", "img/cards/" + card4 + ".png");
		$("#b4").css("visibility", "visible");
	});
	socket.on("send river", function(card5)
	{
		$("#b5").attr("src", "img/cards/" + card5 + ".png");
		$("#b5").css("visibility", "visible");
	});
	socket.on("remove last actions", function()
	{
		for (var idx = 1; idx <= 6; ++idx)
			$("#last_action" + idx).remove();
	});
	socket.on("remove board", function()
	{
		$("#b1, #b2, #b3, #b4, #b5").css("visibility", "hidden");
		for (var idx = 1; idx <= 6; ++idx)
			$("#player_cards" + idx).attr("src", "../img/avatar.png");
	});
	socket.on("remove emplacements", function()
	{
		for (var idx = 1; idx <= 6; ++idx)
			$("#btn" + idx).css("visibility", "hidden");
	});
	socket.on("show down", function(card1, card2, seat_nb)
	{
		if ($('#qr_spot' + seat_nb).css('visibility') == 'hidden') {
			$("#card1_" + seat_nb).attr("src", "../img/cards/" + card1 + ".png");
			$("#card2_" + seat_nb).attr("src", "../img/cards/" + card2 + ".png");
			$("#card1_" + seat_nb).css("visibility", "visible");
			$("#card2_" + seat_nb).css("visibility", "visible");
		}
	});
	socket.on("show down off", function(seat_nb)
	{
		$("#card1_" + seat_nb).css("visibility", "hidden");
		$("#card2_" + seat_nb).css("visibility", "hidden");
	});
	socket.on("winner", function(seat_nb, rank_name)
	{
		var disconnect = '
' + $("#player_name" + seat_nb).text() + ' won because player ' + rank_name + ' or folded
';
		var won = '
' + $("#player_name" + seat_nb).text() + ' won with ' + rank_name + '
';

		if (rank_name == 'disconnected') {
			//$("#winner_msg").text($("#player_name" + seat_nb).text());
			$('#histoContent').empty();
			$('#histoContent').append(disconnect);
		}
		else if (seat_nb == 42 && rank_name == 'null') {
			//$("#winner_msg").text("Split!");
			$('#histoContent').empty();
			$('#histoContent').append('
Split !
');
		}
		else {
			$('#histoContent').empty();
			$('#histoContent').append(won);
		}
		//$("#winner").css("visibility", "visible");
	});
	socket.on("win off", function()
	{
		$("#winner, #card1_1, #card2_1, #card1_2, #card2_2, #card1_3, #card2_3, #card1_4, #card2_4, #card1_5, #card2_5, #card1_6, #card2_6").css("visibility", "hidden");
	});
}

var aTable = [];
var aGame = [];
var tables = [];

function restart() {
	//fonction reinitialiser la game
	var i;
	var id;

	socket.emit('get table');
	socket.on('your table', function(table, game){
		aTable = table;
		aGame = game;
		id = aTable.id;

		for (i = 0; i <= tables.length; i++) {
			tables.push(id);
		}
	});

	console.log(tables);
}

socket.on('refresh game', function(){
	console.log('Ca refresh');
});
<commit_msg>tables fix<commit_after>function	sync_sv()
{
	socket.emit("get seated players");
	socket.on("seated players info", function(seat, seat_idx)
	{
		$("#qr" + seat_idx).css("visibility", "hidden");
		$("#qr_spot" + seat_idx).css("visibility", "hidden");
		$("#scan_msg" + seat_idx).css("visibility", "hidden");
		$("#player_name" + seat_idx).css("visibility", "visible");
		$("#player_name" + seat_idx).text(seat.player.nickname);
		$("#player_bankroll" + seat_idx).css("visibility", "visible");
		$("#player_bankroll" + seat_idx).text((Math.floor(+seat.player.bankroll * 100)) / 100 + "$");
		$("#player_cards"+ seat_idx).css("visibility", "visible");
	});
	socket.on("new player", function(player)
	{
		$("#qr" + player.seat_nb).css("visibility", "hidden");
		$("#qr_spot" + player.seat_nb).css("visibility", "hidden");
		$("#scan_msg" + player.seat_nb).css("visibility", "hidden");
		$("#player_name" + player.seat_nb).css("visibility", "visible");
		$("#player_name" + player.seat_nb).text(player.nickname);
		$("#player_bankroll" + player.seat_nb).css("visibility", "visible");
		$("#player_bankroll" + player.seat_nb).text((Math.floor(+player.bankroll * 100)) / 100 + "$");
		$("#player_cards"+ player.seat_nb).css("visibility", "visible");
	});
	socket.on("kick player", function(seat_nb)
	{
		$("#qr" + seat_nb).css("visibility", "visible");
		$("#qr_spot" + seat_nb).css("visibility", "visible");
		$("#scan_msg" + seat_nb).css("visibility", "visible");
		$("#player_name" + seat_nb).css("visibility", "hidden");
		$("#player_name" + seat_nb).text("");
		$("#player_bankroll" + seat_nb).css("visibility", "hidden");
		$("#player_bankroll" + seat_nb).text("");
		$("#player_cards"+ seat_nb).css("visibility", "hidden");
		$("#btn" + seat_nb).attr("src", "");
		$("#btn" + seat_nb).css("visibility", "hidden");
	});
	socket.emit("ask buttons");
	socket.on("place button", function(type, seat_nb)
	{
		if (seat_nb <= 0 || seat_nb >= 7)
			return ;
		if (type == "dealer")
		{
			$("#btn" + seat_nb).attr("src", "../img/Dealer.png")
			$("#btn" + seat_nb).css("visibility", "visible");
		}
		else if (type == "sb")
		{
			$("#btn" + seat_nb).attr("src", "../img/sb.png")
			$("#btn" + seat_nb).css("visibility", "visible");
		}
		else if (type == "bb")
		{
			$("#btn" + seat_nb).attr("src", "../img/bb.png")
			$("#btn" + seat_nb).css("visibility", "visible");
		}
		$("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
	});
	socket.on("give cards", function(seat_nb)
	{
		$("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
	});
	socket.on("highlights", function(seat_idx, new_state)
	{
		if (new_state == "off")
			$("#seat" + seat_idx).css("background-color", "#006F60");
		else if (new_state == "on")
			$("#seat" + seat_idx).css("background-color", "#FE554C");
	});
	socket.on("bankroll modification", function(seat_idx, player)
	{
		if (player.bankroll == "ALL IN")
			$("#player_bankroll" + seat_idx).text("ALL IN");
		else
			$("#player_bankroll" + seat_idx).text((Math.floor(player.bankroll * 100)) / 100 + "$");
	});
	socket.on("pot modification", function(pot_amount)
	{
		$("#pot").text(Math.floor(+pot_amount * 100) / 100 + "$");
	});
	socket.on("bet", function(seat_idx, amount)
	{
		if (!amount)
			$("#bet_val" + seat_idx).text('');
		else {
			$("#bet_val" + seat_idx).text((Math.floor(amount * 100)) / 100 + "$");
		}
	});

	socket.on("last action", function(decision, seat_nb)
	{
		$("#last_action" + seat_nb).text(decision);
	});
	socket.on("fold", function(seat_nb)
	{
		$("#btn" + seat_nb).css("visibility", "hidden");
		$("#bet_val" + seat_nb).text('');
		$("#player_cards" + seat_nb).attr("src", "../img/avatar.png");
		$("#last_action" + seat_nb).text('');
	});
	socket.emit("get board");
	socket.on("send flop", function(card1, card2, card3)
	{
		$("#b1").attr("src", "img/cards/" + card1 + ".png");
		$("#b2").attr("src", "img/cards/" + card2 + ".png");
		$("#b3").attr("src", "img/cards/" + card3 + ".png");
		$("#b1, #b2, #b3").css("visibility", "visible");
	});
	socket.on("send turn", function(card4)
	{
		$("#b4").attr("src", "img/cards/" + card4 + ".png");
		$("#b4").css("visibility", "visible");
	});
	socket.on("send river", function(card5)
	{
		$("#b5").attr("src", "img/cards/" + card5 + ".png");
		$("#b5").css("visibility", "visible");
	});
	socket.on("remove last actions", function()
	{
		for (var idx = 1; idx <= 6; ++idx)
			$("#last_action" + idx).remove();
	});
	socket.on("remove board", function()
	{
		$("#b1, #b2, #b3, #b4, #b5").css("visibility", "hidden");
		for (var idx = 1; idx <= 6; ++idx)
			$("#player_cards" + idx).attr("src", "../img/avatar.png");
	});
	socket.on("remove emplacements", function()
	{
		for (var idx = 1; idx <= 6; ++idx)
			$("#btn" + idx).css("visibility", "hidden");
	});
	socket.on("show down", function(card1, card2, seat_nb)
	{
		if ($('#qr_spot' + seat_nb).css('visibility') == 'hidden') {
			$("#card1_" + seat_nb).attr("src", "../img/cards/" + card1 + ".png");
			$("#card2_" + seat_nb).attr("src", "../img/cards/" + card2 + ".png");
			$("#card1_" + seat_nb).css("visibility", "visible");
			$("#card2_" + seat_nb).css("visibility", "visible");
		}
	});
	socket.on("show down off", function(seat_nb)
	{
		$("#card1_" + seat_nb).css("visibility", "hidden");
		$("#card2_" + seat_nb).css("visibility", "hidden");
	});
	socket.on("winner", function(seat_nb, rank_name)
	{
		var disconnect = '
' + $("#player_name" + seat_nb).text() + ' won because player ' + rank_name + ' or folded
';
		var won = '
' + $("#player_name" + seat_nb).text() + ' won with ' + rank_name + '
';

		if (rank_name == 'disconnected') {
			//$("#winner_msg").text($("#player_name" + seat_nb).text());
			$('#histoContent').empty();
			$('#histoContent').append(disconnect);
		}
		else if (seat_nb == 42 && rank_name == 'null') {
			//$("#winner_msg").text("Split!");
			$('#histoContent').empty();
			$('#histoContent').append('
Split !
');
		}
		else {
			$('#histoContent').empty();
			$('#histoContent').append(won);
		}
		//$("#winner").css("visibility", "visible");
	});
	socket.on("win off", function()
	{
		$("#winner, #card1_1, #card2_1, #card1_2, #card2_2, #card1_3, #card2_3, #card1_4, #card2_4, #card1_5, #card2_5, #card1_6, #card2_6").css("visibility", "hidden");
	});
}

var aTable = [];
var aGame = [];
var tables = [];

function restart() {
	//fonction reinitialiser la game
	var i;
	var id;

	socket.emit('get table');
	socket.on('your table', function(table, game){
		aTable = table;
		aGame = game;
		id = aTable.id;
		tables.push(id);
	});

	console.log(tables);
}

socket.on('refresh game', function(){
	console.log('Ca refresh');
});
<|endoftext|>


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

  angular.module('RkyApp.controllers')
    .controller('selectRky', ['$scope','$http', 'partage', function($scope,$http,partage){
      var url = "/api/v1/list/scale";

      $scope.title = "selectRky";
      $scope.data = {};
$scope.myDate = new Date();
       $http.get(url).
        then(function(response) {
          $scope.data =  {
          model: null,
          availableOptions: response.data
          }
          $scope.data.model = $scope.data.availableOptions[3];
        });

      function updateCapteur() {
        partage.capteur = $scope.data.model.scale;
        console.log('update: ' + partage.capteur);
      };

      $scope.$watchCollection('data.model.scale',  updateCapteur);

}])

    .service('partage', function() {
      var Data = {
        capteur: '',
        dateFrom: '',
        dateTo: ''
      };
      return Data;
    })
//xx  } ());

    .controller('dateRky',['$scope', 'partage' , function($scope,partage) {
      $scope.fromDate = new Date();
      $scope.toDate = new Date();

      function updateDate() {
          partage.dateFrom = $scope.fromDate;
          partage.dateTo = $scope.toDate;
          console.log(partage);
      }
      $scope.$watch('fromDate',updateDate);
      $scope.$watch('toDate',updateDate);
    }])
    .config(function($mdDateLocaleProvider) {
      $mdDateLocaleProvider.formatDate = function(date) {
      return date ? moment(date).format('YYYY/MM/DD') : null;
      };

      $mdDateLocaleProvider.parseDate = function(dateString) {
      var m = moment(dateString, 'YYYY/MM/DD', true);
      return m.isValid() ? m.toDate() : new Date(NaN);
      };
    })
// --------
// recuperation des valeur depuis MongoDB
//xx(function () {
//xx  'use strict';

//xx  angular.module('RkyApp.controllers')
    .controller('httpRky', ['$scope', '$http','$filter' ,'partage', function($scope, $http, $filter, partage) {
      $scope.title = "Rky - Data Dashboard";
      $scope.partage = partage;
        var now = new Date();
        var demain = new Date();
        demain.setDate(demain.getDate() + 1);
      $scope.after = $filter('date')(now,"yyyy/MM/dd");
      $scope.before = $filter('date')(demain,"yyyy/MM/dd");
      $scope.moyenne = 0.0;
      $scope.somme = 0.0;
      $scope.nb = 0;
      var urlBase ="/api/v1/search?name=Rky_P&source=*";
      var url = urlBase + $scope.date;
      var data = [];

      function getData () {
        $http.get(url)
        .then(function(response){
        angular.forEach(response.data,function(value){
          data.push({ date: value.date, heure: value.heure, value: value.value });
          $scope.somme += parseFloat(value.value);
          $scope.nb += 1;
          $scope.moyenne = ($scope.somme / $scope.nb).toFixed(2);
         });
        });
      }

      function calculMoyenne() {
        $scope.moyenne = $scope.somme / $scope.nb;
//        console.log($scope.somme,$scope.nb,$scope.moyenne);
      }

      $scope.d3Data = data;

      function updateData() {
        urlBase = "/api/v1/search?name="+partage.capteur+"&source=*";
        url = urlBase +"&after="+ $scope.after+"&before=" +$scope.before;
          data.length = 0;
          $scope.nb=0;
          $scope.somme=0.0;
          $scope.moyenne = "waiting for data";
          getData();
      }
      function updateDate(){
        $scope.after = $filter('date')(partage.dateFrom,"yyyy/MM/dd");
        $scope.before = $filter('date')(partage.dateTo,"yyyy/MM/dd");
        console.log('update picker : ', $scope.after, $scope.before);
      }

      $scope.clickButton = function() {
          updateData();
        }

      $scope.$watch(data,calculMoyenne);

      $scope.$watchCollection('partage',updateData);
//      $scope.$watchCollection('partage.dateFrom',updateDate);
//      $scope.$watchCollection('partage.dateTo',updateDate);
      $scope.$watch('after',updateData);
      $scope.$watch('before',updateData);

  }]);

 }());<commit_msg>encore<commit_after>(function () {
  'use strict';

  angular.module('RkyApp.controllers')
    .controller('selectRky', ['$scope','$http', 'partage', function($scope,$http,partage){
      var url = "/api/v1/list/scale";

      $scope.title = "selectRky";
      $scope.data = {};
       $http.get(url).
        then(function(response) {
          $scope.data =  {
          model: null,
          availableOptions: response.data
          }
          $scope.data.model = $scope.data.availableOptions[3];
        });

      function updateCapteur() {
        partage.capteur = $scope.data.model.scale;
        console.log('update: ' + partage.capteur);
      };

      $scope.$watchCollection('data.model.scale',  updateCapteur);

}])

    .service('partage', function() {
      var Data = {
        capteur: '',
        dateFrom: '',
        dateTo: ''
      };
      return Data;
    })
//xx  } ());

    .controller('dateRky',['$scope', 'partage' , function($scope,partage) {
        var now = new Date();
        var demain = new Date();
        demain.setDate(demain.getDate() + 1);
      $scope.fromDate = now;
      $scope.toDate = demain;

      function updateDate() {
          partage.dateFrom = $scope.fromDate;
          partage.dateTo = $scope.toDate;
          console.log(partage);
      }
      $scope.$watch('fromDate',updateDate);
      $scope.$watch('toDate',updateDate);
    }])
    .config(function($mdDateLocaleProvider) {
      $mdDateLocaleProvider.formatDate = function(date) {
      return date ? moment(date).format('YYYY/MM/DD') : null;
      };

      $mdDateLocaleProvider.parseDate = function(dateString) {
      var m = moment(dateString, 'YYYY/MM/DD', true);
      return m.isValid() ? m.toDate() : new Date(NaN);
      };
    })
// --------
// recuperation des valeur depuis MongoDB
//xx(function () {
//xx  'use strict';

//xx  angular.module('RkyApp.controllers')
    .controller('httpRky', ['$scope', '$http','$filter' ,'partage', function($scope, $http, $filter, partage) {
      $scope.title = "Rky - Data Dashboard";
//      $scope.partage = partage;
        var now = new Date();
        var demain = new Date();
        demain.setDate(demain.getDate() + 1);
      $scope.after = $filter('date')(now,"yyyy/MM/dd");
      $scope.before = $filter('date')(demain,"yyyy/MM/dd");
      $scope.moyenne = 0.0;
      $scope.somme = 0.0;
      $scope.nb = 0;
      var urlBase ="/api/v1/search?name=Rky_P&source=*";
      var url = urlBase + $scope.date;
      var data = [];

      function getData () {
        $http.get(url)
        .then(function(response){
        angular.forEach(response.data,function(value){
          data.push({ date: value.date, heure: value.heure, value: value.value });
          $scope.somme += parseFloat(value.value);
          $scope.nb += 1;
          $scope.moyenne = ($scope.somme / $scope.nb).toFixed(2);
         });
        });
      }

      function calculMoyenne() {
        $scope.moyenne = $scope.somme / $scope.nb;
//        console.log($scope.somme,$scope.nb,$scope.moyenne);
      }

      $scope.d3Data = data;

      function updateData() {
        urlBase = "/api/v1/search?name="+partage.capteur+"&source=*";
        url = urlBase +"&after="+ $scope.after+"&before=" +$scope.before;
          data.length = 0;
          $scope.nb=0;
          $scope.somme=0.0;
          $scope.moyenne = "waiting for data";
          getData();
      }
      function updateDate(){
        $scope.after = $filter('date')(partage.dateFrom,"yyyy/MM/dd");
        $scope.before = $filter('date')(partage.dateTo,"yyyy/MM/dd");
        console.log('update picker : ', $scope.after, $scope.before);
      }

      $scope.clickButton = function() {
          updateData();
        }

      $scope.$watch(data,calculMoyenne);

      $scope.$watchCollection('partage',updateData);
//      $scope.$watchCollection('partage.dateFrom',updateDate);
//      $scope.$watchCollection('partage.dateTo',updateDate);
      $scope.$watch('after',updateData);
      $scope.$watch('before',updateData);

  }]);

 }());<|endoftext|>


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

  angular.module('RkyApp.controllers')
    .controller('testRky', ['$scope', function($scope){
      $scope.title = "testRky";
      $scope.d3Data = [
        {capteur: "Rky_L", score:10},
        {capteur: "Rky_L", score: 87}
      ];
    }]);

}());

// --------
// recuperation des valeur depuis MongoDB
(function () {
  'use strict';

  angular.module('RkyApp.controllers')
    .controller('httpRky', ['$scope', '$http', function($scope, $http){
      $scope.title = "httpRky ... in progress";
      $scope.date = "2016/11/01";
      var url1 = "/api/v1/list/scale";
      var url ="/api/v1/search?name=Rky_P&source=*&after=2016/11/10"; // + $scope.date;
      var data = [];

      $http.get(url)
        .then(function(response){
        angular.forEach(response.data,function(value){
          data.push({ capteur: value.heure, score: value.value });
        });
      });

      $scope.d3Data = data;

      $scope.clickButton = function() {
            console.log($scope.date);
        }

  }]);

 }());<commit_msg>button<commit_after>(function () {
  'use strict';

  angular.module('RkyApp.controllers')
    .controller('testRky', ['$scope', function($scope){
      $scope.title = "testRky";
      $scope.d3Data = [
        {capteur: "Rky_L", score:10},
        {capteur: "Rky_L", score: 87}
      ];
    }]);

}());

// --------
// recuperation des valeur depuis MongoDB
(function () {
  'use strict';

  angular.module('RkyApp.controllers')
    .controller('httpRky', ['$scope', '$http', function($scope, $http){
      $scope.title = "httpRky ... in progress";
      $scope.date = "2016/11/01";
      var url1 = "/api/v1/list/scale";
      var url ="/api/v1/search?name=Rky_P&source=*&after="+ $scope.date;
      var data = [];

      $http.get(url)
        .then(function(response){
        angular.forEach(response.data,function(value){
          data.push({ capteur: value.heure, score: value.value });
        });
      });

      $scope.d3Data = data;

      $scope.clickButton = function() {
            console.log($scope.url);
        }

  }]);

 }());<|endoftext|>