<commit_before>function redirectToHomePage() {
  window.location.pathname = 'index';
}

/**
 * Look for a query param in an url
 * return this param or undefined if not found
 * @param {*} name of the query param
 * @param {*} url url
 */
function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

function getApiKeyIfOneTimeLoginTokenIsPresent() {
  const oneTimeLoginToken = getParameterByName('oneTimeLoginToken', window.location.href);
  removeQueryParamsFromUrl();
  if (oneTimeLoginToken) {
    console.log('getting api key from q-cloud');
    getAPIKeyWithOneTimeLoginToken(oneTimeLoginToken);
  } else {
    updateLoginDisplayElements(undefined);
    replaceALLApiKeyByStoredApiKey(undefined);
  }
}

function getCurrentUser() {
  const localAPIKey = getStoredAPIKey();
  $.getJSON("https://q.daskeyboard.com/api/1.0/users/me", localAPIKey)
    // post request success
    .done(function (data) {
      // store email
      localStorage.setItem('email', data.email);
      // update the view with the new user info
      updateLoginDisplayElements(data.email);
      replaceALLApiKeyByStoredApiKey(localAPIKey);
    })
    // error with POST request
    .fail(function () {
      // notify user that error happened
      logout();
    });
}

function onLoginToQCloud() {
  const callbackUrl = window.location.pathname;
  window.location = "https://qapp.daskeyboard.com?source=q-documentation"
    + '&callbackUrl=' + callbackUrl;
}

/**
 *
 * redefine jquery post request to use application/json and stringify the data
 */
$.postJSON = function (url, data, callback) {
  return jQuery.ajax({
    'type': 'POST',
    'url': url,
    'contentType': 'application/json',
    'data': JSON.stringify(data),
    'dataType': 'json',
    'success': callback
  });
};

/**
 *
 * redefine jquery post request to use application/json and stringify the data
 */
$.getJSON = function (url, apiKey, callback) {
  return jQuery.ajax({
    'type': 'GET',
    'url': url,
    headers: { 'X-API-KEY': apiKey },
    'contentType': 'application/json',
    'dataType': 'json',
    'success': callback
  });
};

/**
 * Get API key from the Q Cloud using a one time login token and store it in the local
 * storage
 * @param {*} loginToken
 */
function getAPIKeyWithOneTimeLoginToken(loginToken) {
  if (!loginToken) {
    console.error('no login token provided');
    return;
  }
  $.postJSON("https://q.daskeyboard.com/api/1.0/users/api_key", { oneTimeLoginToken: loginToken })
    // post request success
    .done(function (data) {
      // store apiKey in local storage
      const apiKey = data.value;
      localStorage.setItem('APIKey', apiKey);
      // notify user that the API key was fetched
      displayFlashNotice('info',
        'You are  logged in: sample code will contain your API key so you can copy paste and experiment easily. Enjoy!');
      getCurrentUser();
    })
    // error with POST request
    .fail(function () {
      // notify user that error happened
      updateLoginDisplayElements(undefined);
      replaceALLApiKeyByStoredApiKey(undefined);
      displayFlashNotice('error', 'Error while fetching API KEY');
    });
}

function getStoredAPIKey() {
  const apiKey = localStorage.getItem('APIKey');
  return apiKey;
}

/************************************************************************
 *
 *  code used to display a notice popover for the user
 *
 *
 * ***********************************************************************
 */

/**
 * Displays a bootstrap alert depending on the noticeType
 * noticeType can be 'info' and the bootstrap alert will be blue
 * or can be 'error' and the bootstrap alert will be red
 * @param {*} noticeType
 * @param {*} message
 */
function displayFlashNotice(noticeType, message) {
  // get the bootstrap alert div
  const flashNoticeDivId = '#flash-notice-section';
  const flashNoticeMessageId = '#flash-notice-message';
  const alertDiv = $(flashNoticeDivId);
  const alertMessage = $(flashNoticeMessageId);

  if (alertDiv && alertMessage) {
    // populate the content of the div with the message
    alertMessage.html(message);
    // remove the previous class lists
    alertDiv.removeClass(['alert-info', 'alert-danger']);
    switch (noticeType) {
      case 'info':
        alertDiv.addClass(['alert-primary']);
        break;

      case 'error':
        alertDiv.addClass(['alert-danger']);
        break;
    }

    // show the div
    alertDiv.css('display', 'block');

  }
}

/**
 * closes the flash notice component by hiding the element in the DOM
 */
function onCloseFlashNotice() {
  const flashNoticeDivId = 'flash-notice-section';
  const alertDiv = document.getElementById(flashNoticeDivId);
  if (alertDiv) {
    alertDiv.style.display = 'none';
  }
}

/************************************************************************
 *
 *  END OF code used to display a notice popover for the user
 *
 *
 * ***********************************************************************
 */

function removeQueryParamsFromUrl() {
  var newurl = window.location.pathname;
  window.history.pushState({ path: newurl }, '', newurl);
}

/**
 * Remove the stored apiKey
 * and update the views to display a none logged user
 */
function logout() {

  // remove api key and email from local storage
  localStorage.removeItem('APIKey');
  localStorage.removeItem('email');

  // reload page
  window.location.reload();
}

function updateLoginDisplayElements(currentUserEmail) {
  if (currentUserEmail) {
    // hide login message
    $('#header-login-message').css('display', 'none');
    // display welcome message
    $('#header-welcome-message').text('Welcome ' + currentUserEmail);
    $('#header-welcome-message').css('display', 'inline-block');
    $('#header-welcome-message').css('font-weight', 'bold');
    // display logout action
    $('#logout-action').css('display', 'inline-block');
  } else {
    // hide logout action
    $('#logout-action').css('display', 'none');
    // hide welcome message
    $('#header-welcome-message').css('display', 'none');
    // display login message
    $('#header-login-message').css('display', 'inline-block');
  }
}

/************************************************************************
 *
 *  code used to display the dynamic content in the code pages
 *
 *
 * ***********************************************************************
 */

function formatJSONCode() {
  var jsonCode = document.getElementsByClassName('json-code');
  for (var i = 0; i < jsonCode.length; i++) {
    var content = jsonCode[i].textContent;
    jsonCode[i].innerHTML = syntaxHighlight(content);
  }
};

function replaceALLApiKeyByStoredApiKey(apiKey) {
  $("body").children().each(function () {
    if (!apiKey) {

      // TODO change with the root to the API Key explanation page
      const apiKeyMoreDetails = window.location.origin + '/get-started/software/';
      $(this).html($(this).html().replace(/\$API_KEY/g,
        // ""
        // + "login to retrieve your api-key"));
        "<button class='login-code-button' data-toggle='tooltip' data-html='true' title='This is a sample API key. Login to see examples "
        + "pre-filled with your keys.'>login to retrieve your api-key</button>"));
    } else {
      $(this).html($(this).html().replace(/\$API_KEY/g, apiKey));
    }
  });
}

/**
 * Use to beautify json code
 * @param {*} json
 */
function syntaxHighlight(json) {
  if (typeof json != 'string') {
    json = JSON.stringify(json, undefined, 2);
  }
  json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
  return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
    var cls = 'number';
    if (/^"/.test(match)) {
      if (/:$/.test(match)) {
        cls = 'key';
      } else {
        cls = 'string';
      }
    } else if (/true|false/.test(match)) {
      cls = 'boolean';
    } else if (/null/.test(match)) {
      cls = 'null';
    }
    // if (cls === 'string') {
    //   return '' + match + '
';
    // } else {
    //   return '' + match + '';
    // }
    return '' + match + '';
  });
}

/************************************************************************
 *
 *  End of code used to display the dynamic content in the code pages
 *
 *
 * ***********************************************************************
 */

/**
 * Detects the os platform and architechture and change the download link of the Q software
 * depending on this informations
 */
function loadDownloadLinkDependingOnOsArchitechture() {
  if (navigator.platform.includes('Win32')) {
    if (navigator.userAgent.indexOf("WOW64") != -1 ||
      navigator.userAgent.indexOf("Win64") != -1) {
      $('#software-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/3.0.0/Das-Keyboard-Q-x64-Setup-3.0.0.exe");
      $('#software-download-button').append(" 64 bit");
      $('#software-version-number').append(" Windows");
      return;

    } else {
      $('#software-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/3.0.0/Das-Keyboard-Q-ia32-Setup-3.0.0.exe");
      $('#software-download-button').append(" 32 bit");
      $('#software-version-number').append(" Windows");
      return;

    }
  }
  if (navigator.platform.includes('MacIntel')) {
    $('#software-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/3.0.0-beta/DasKeyboardQ_3.0.0-beta.pkg");
    $('#software-download-button').append(" 64 bit");
    $('#software-version-number').append("-beta.2");
    $('#software-version-number').append(" Mac");
    return;
  }

  if (navigator.platform.includes('Linux x86_64')) {
    $('#software-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/3.0.0-beta/das-keyboard-q_3.0.0~beta.2.deb");
    $('#software-download-button').append(" 64 bit");
    $('#software-version-number').append("-beta.2");
    $('#software-version-number').append(" Linux");
    return;
  }

}

/**
 * Detects the device pid given in param in the URL
 * and change the download fw link button depending on the pid
 */
function loadFirmwareDeviceDependingOnPidParam() {
  const pid = getParameterByName('devicePid', window.location.href);
  if (pid) {
    $('#firmware-buttons').css('display', 'flex');
    switch (pid) {
      case 'DK5QPID':
        $('#firmware-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/Firmware-releases/5Q/5Q+Flash+Upgrade.7.4.18.exe");
        $('#firmware-download-button').text("Download 5Q firmware installer");
        $('#firmware-download-version').text("Version 7.4.18");
        break;
      case 'X50QPID':
        $('#firmware-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/Firmware-releases/X50Q/DasKeyboard+X50+-+Firmware+Updater+-+57.0.0.exe");
        $('#firmware-download-button').text("Download X50Q firmware installer");
        $('#firmware-download-version').text("Version 57.0.0");
        break;
      case 'DK4QPID':
        $('#firmware-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/Firmware-releases/DK4Q/DK4Q_US_Firmware_18.23.0.exe");
        $('#firmware-download-button').text("Download DK4Q US firmware installer");
        $('#firmware-download-version').text("Version 18.23.0");
        $('#firmware-download-button-dk4-eu').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/Firmware-releases/DK4Q/DK4Q_EU_Firmware_19.23.0.exe");
        $('#firmware-download-button-dk4-eu').text("Download DK4Q EU firmware installer");
        $('#firmware-download-version-dk4-eu').text("Version 19.23.0");
        $('#firmware-download-version-dk4-eu').css('visibility', 'visible');
        $('#firmware-download-button-dk4-eu').css('visibility', 'visible');
        break;
    }
  }
}

$(document).ready(function () {
  loadFirmwareDeviceDependingOnPidParam();
  const email = localStorage.getItem('email');
  const apiKey = getStoredAPIKey();
  console.log('apiKey', apiKey);
  console.log('email', email);

  if (email && apiKey) {
    updateLoginDisplayElements(email);
    replaceALLApiKeyByStoredApiKey(apiKey);
  } else {
    //get ApiKey if one time login token present in url
    getApiKeyIfOneTimeLoginTokenIsPresent();
  }

  formatJSONCode();
  loadDownloadLinkDependingOnOsArchitechture();

  // enable bootstrap tooltips
  $('[data-toggle="tooltip"]').tooltip();

  // enable bootstrap popovers
  $('[data-toggle="popover"]').popover();

  $('.popover-dismiss').popover({
    trigger: 'focus'
  });
});
<commit_msg>updated linux  package to -beta.2<commit_after>function redirectToHomePage() {
  window.location.pathname = 'index';
}

/**
 * Look for a query param in an url
 * return this param or undefined if not found
 * @param {*} name of the query param
 * @param {*} url url
 */
function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

function getApiKeyIfOneTimeLoginTokenIsPresent() {
  const oneTimeLoginToken = getParameterByName('oneTimeLoginToken', window.location.href);
  removeQueryParamsFromUrl();
  if (oneTimeLoginToken) {
    console.log('getting api key from q-cloud');
    getAPIKeyWithOneTimeLoginToken(oneTimeLoginToken);
  } else {
    updateLoginDisplayElements(undefined);
    replaceALLApiKeyByStoredApiKey(undefined);
  }
}

function getCurrentUser() {
  const localAPIKey = getStoredAPIKey();
  $.getJSON("https://q.daskeyboard.com/api/1.0/users/me", localAPIKey)
    // post request success
    .done(function (data) {
      // store email
      localStorage.setItem('email', data.email);
      // update the view with the new user info
      updateLoginDisplayElements(data.email);
      replaceALLApiKeyByStoredApiKey(localAPIKey);
    })
    // error with POST request
    .fail(function () {
      // notify user that error happened
      logout();
    });
}

function onLoginToQCloud() {
  const callbackUrl = window.location.pathname;
  window.location = "https://qapp.daskeyboard.com?source=q-documentation"
    + '&callbackUrl=' + callbackUrl;
}

/**
 *
 * redefine jquery post request to use application/json and stringify the data
 */
$.postJSON = function (url, data, callback) {
  return jQuery.ajax({
    'type': 'POST',
    'url': url,
    'contentType': 'application/json',
    'data': JSON.stringify(data),
    'dataType': 'json',
    'success': callback
  });
};

/**
 *
 * redefine jquery post request to use application/json and stringify the data
 */
$.getJSON = function (url, apiKey, callback) {
  return jQuery.ajax({
    'type': 'GET',
    'url': url,
    headers: { 'X-API-KEY': apiKey },
    'contentType': 'application/json',
    'dataType': 'json',
    'success': callback
  });
};

/**
 * Get API key from the Q Cloud using a one time login token and store it in the local
 * storage
 * @param {*} loginToken
 */
function getAPIKeyWithOneTimeLoginToken(loginToken) {
  if (!loginToken) {
    console.error('no login token provided');
    return;
  }
  $.postJSON("https://q.daskeyboard.com/api/1.0/users/api_key", { oneTimeLoginToken: loginToken })
    // post request success
    .done(function (data) {
      // store apiKey in local storage
      const apiKey = data.value;
      localStorage.setItem('APIKey', apiKey);
      // notify user that the API key was fetched
      displayFlashNotice('info',
        'You are  logged in: sample code will contain your API key so you can copy paste and experiment easily. Enjoy!');
      getCurrentUser();
    })
    // error with POST request
    .fail(function () {
      // notify user that error happened
      updateLoginDisplayElements(undefined);
      replaceALLApiKeyByStoredApiKey(undefined);
      displayFlashNotice('error', 'Error while fetching API KEY');
    });
}

function getStoredAPIKey() {
  const apiKey = localStorage.getItem('APIKey');
  return apiKey;
}

/************************************************************************
 *
 *  code used to display a notice popover for the user
 *
 *
 * ***********************************************************************
 */

/**
 * Displays a bootstrap alert depending on the noticeType
 * noticeType can be 'info' and the bootstrap alert will be blue
 * or can be 'error' and the bootstrap alert will be red
 * @param {*} noticeType
 * @param {*} message
 */
function displayFlashNotice(noticeType, message) {
  // get the bootstrap alert div
  const flashNoticeDivId = '#flash-notice-section';
  const flashNoticeMessageId = '#flash-notice-message';
  const alertDiv = $(flashNoticeDivId);
  const alertMessage = $(flashNoticeMessageId);

  if (alertDiv && alertMessage) {
    // populate the content of the div with the message
    alertMessage.html(message);
    // remove the previous class lists
    alertDiv.removeClass(['alert-info', 'alert-danger']);
    switch (noticeType) {
      case 'info':
        alertDiv.addClass(['alert-primary']);
        break;

      case 'error':
        alertDiv.addClass(['alert-danger']);
        break;
    }

    // show the div
    alertDiv.css('display', 'block');

  }
}

/**
 * closes the flash notice component by hiding the element in the DOM
 */
function onCloseFlashNotice() {
  const flashNoticeDivId = 'flash-notice-section';
  const alertDiv = document.getElementById(flashNoticeDivId);
  if (alertDiv) {
    alertDiv.style.display = 'none';
  }
}

/************************************************************************
 *
 *  END OF code used to display a notice popover for the user
 *
 *
 * ***********************************************************************
 */

function removeQueryParamsFromUrl() {
  var newurl = window.location.pathname;
  window.history.pushState({ path: newurl }, '', newurl);
}

/**
 * Remove the stored apiKey
 * and update the views to display a none logged user
 */
function logout() {

  // remove api key and email from local storage
  localStorage.removeItem('APIKey');
  localStorage.removeItem('email');

  // reload page
  window.location.reload();
}

function updateLoginDisplayElements(currentUserEmail) {
  if (currentUserEmail) {
    // hide login message
    $('#header-login-message').css('display', 'none');
    // display welcome message
    $('#header-welcome-message').text('Welcome ' + currentUserEmail);
    $('#header-welcome-message').css('display', 'inline-block');
    $('#header-welcome-message').css('font-weight', 'bold');
    // display logout action
    $('#logout-action').css('display', 'inline-block');
  } else {
    // hide logout action
    $('#logout-action').css('display', 'none');
    // hide welcome message
    $('#header-welcome-message').css('display', 'none');
    // display login message
    $('#header-login-message').css('display', 'inline-block');
  }
}

/************************************************************************
 *
 *  code used to display the dynamic content in the code pages
 *
 *
 * ***********************************************************************
 */

function formatJSONCode() {
  var jsonCode = document.getElementsByClassName('json-code');
  for (var i = 0; i < jsonCode.length; i++) {
    var content = jsonCode[i].textContent;
    jsonCode[i].innerHTML = syntaxHighlight(content);
  }
};

function replaceALLApiKeyByStoredApiKey(apiKey) {
  $("body").children().each(function () {
    if (!apiKey) {

      // TODO change with the root to the API Key explanation page
      const apiKeyMoreDetails = window.location.origin + '/get-started/software/';
      $(this).html($(this).html().replace(/\$API_KEY/g,
        // ""
        // + "login to retrieve your api-key"));
        "<button class='login-code-button' data-toggle='tooltip' data-html='true' title='This is a sample API key. Login to see examples "
        + "pre-filled with your keys.'>login to retrieve your api-key</button>"));
    } else {
      $(this).html($(this).html().replace(/\$API_KEY/g, apiKey));
    }
  });
}

/**
 * Use to beautify json code
 * @param {*} json
 */
function syntaxHighlight(json) {
  if (typeof json != 'string') {
    json = JSON.stringify(json, undefined, 2);
  }
  json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
  return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
    var cls = 'number';
    if (/^"/.test(match)) {
      if (/:$/.test(match)) {
        cls = 'key';
      } else {
        cls = 'string';
      }
    } else if (/true|false/.test(match)) {
      cls = 'boolean';
    } else if (/null/.test(match)) {
      cls = 'null';
    }
    // if (cls === 'string') {
    //   return '' + match + '
';
    // } else {
    //   return '' + match + '';
    // }
    return '' + match + '';
  });
}

/************************************************************************
 *
 *  End of code used to display the dynamic content in the code pages
 *
 *
 * ***********************************************************************
 */

/**
 * Detects the os platform and architechture and change the download link of the Q software
 * depending on this informations
 */
function loadDownloadLinkDependingOnOsArchitechture() {
  if (navigator.platform.includes('Win32')) {
    if (navigator.userAgent.indexOf("WOW64") != -1 ||
      navigator.userAgent.indexOf("Win64") != -1) {
      $('#software-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/3.0.0/Das-Keyboard-Q-x64-Setup-3.0.0.exe");
      $('#software-download-button').append(" 64 bit");
      $('#software-version-number').append(" Windows");
      return;

    } else {
      $('#software-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/3.0.0/Das-Keyboard-Q-ia32-Setup-3.0.0.exe");
      $('#software-download-button').append(" 32 bit");
      $('#software-version-number').append(" Windows");
      return;

    }
  }
  if (navigator.platform.includes('MacIntel')) {
    $('#software-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/3.0.0-beta/DasKeyboardQ_3.0.0-beta.pkg");
    $('#software-download-button').append(" 64 bit");
    $('#software-version-number').append("-beta.2");
    $('#software-version-number').append(" Mac");
    return;
  }

  if (navigator.platform.includes('Linux x86_64')) {
    $('#software-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/3.0.0-beta/das-keyboard-q_3.0.0-beta.2.deb");
    $('#software-download-button').append(" 64 bit");
    $('#software-version-number').append("-beta.2");
    $('#software-version-number').append(" Linux");
    return;
  }

}

/**
 * Detects the device pid given in param in the URL
 * and change the download fw link button depending on the pid
 */
function loadFirmwareDeviceDependingOnPidParam() {
  const pid = getParameterByName('devicePid', window.location.href);
  if (pid) {
    $('#firmware-buttons').css('display', 'flex');
    switch (pid) {
      case 'DK5QPID':
        $('#firmware-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/Firmware-releases/5Q/5Q+Flash+Upgrade.7.4.18.exe");
        $('#firmware-download-button').text("Download 5Q firmware installer");
        $('#firmware-download-version').text("Version 7.4.18");
        break;
      case 'X50QPID':
        $('#firmware-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/Firmware-releases/X50Q/DasKeyboard+X50+-+Firmware+Updater+-+57.0.0.exe");
        $('#firmware-download-button').text("Download X50Q firmware installer");
        $('#firmware-download-version').text("Version 57.0.0");
        break;
      case 'DK4QPID':
        $('#firmware-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/Firmware-releases/DK4Q/DK4Q_US_Firmware_18.23.0.exe");
        $('#firmware-download-button').text("Download DK4Q US firmware installer");
        $('#firmware-download-version').text("Version 18.23.0");
        $('#firmware-download-button-dk4-eu').attr("href", "https://s3-us-west-2.amazonaws.com/q-software-releases/Firmware-releases/DK4Q/DK4Q_EU_Firmware_19.23.0.exe");
        $('#firmware-download-button-dk4-eu').text("Download DK4Q EU firmware installer");
        $('#firmware-download-version-dk4-eu').text("Version 19.23.0");
        $('#firmware-download-version-dk4-eu').css('visibility', 'visible');
        $('#firmware-download-button-dk4-eu').css('visibility', 'visible');
        break;
    }
  }
}

$(document).ready(function () {
  loadFirmwareDeviceDependingOnPidParam();
  const email = localStorage.getItem('email');
  const apiKey = getStoredAPIKey();
  console.log('apiKey', apiKey);
  console.log('email', email);

  if (email && apiKey) {
    updateLoginDisplayElements(email);
    replaceALLApiKeyByStoredApiKey(apiKey);
  } else {
    //get ApiKey if one time login token present in url
    getApiKeyIfOneTimeLoginTokenIsPresent();
  }

  formatJSONCode();
  loadDownloadLinkDependingOnOsArchitechture();

  // enable bootstrap tooltips
  $('[data-toggle="tooltip"]').tooltip();

  // enable bootstrap popovers
  $('[data-toggle="popover"]').popover();

  $('.popover-dismiss').popover({
    trigger: 'focus'
  });
});
<|endoftext|>


<commit_before>var value = 0;
var context;
var x=100;
var y=200;
var dx=5;
var dy=5;
function addValue(){
  value = value + 1;
  document.getElementById("value").innerHTML = value;
}
function init()
{
  context= myCanvas.getContext('2d');
  setInterval(draw,10);
}

function draw()
{
  context.clearRect(0,0, 300,300);
  context.beginPath();
  context.fillStyle="#0000ff";
  // Draws a circle of radius 20 at the coordinates 100,100 on the canvas
  context.arc(x,y,20,0,Math.PI*2,true);
  context.closePath();
  context.fill();
  // Boundary Logic
if( x=<20 || x>=280) dx=-dx;
if( y=<20 || y>=280) dy=-dy;
x+=dx;
y+=dy;
}
<commit_msg>Fixed syntax<commit_after>var value = 0;
var context;
var x=100;
var y=200;
var dx=5;
var dy=5;
function addValue(){
  value = value + 1;
  document.getElementById("value").innerHTML = value;
}
function init()
{
  context= myCanvas.getContext('2d');
  setInterval(draw,10);
}

function draw()
{
  context.clearRect(0,0, 300,300);
  context.beginPath();
  context.fillStyle="#0000ff";
  // Draws a circle of radius 20 at the coordinates 100,100 on the canvas
  context.arc(x,y,20,0,Math.PI*2,true);
  context.closePath();
  context.fill();
  // Boundary Logic
if( x<=20 || x>=280) dx=-dx;
if( y<=20 || y>=280) dy=-dy;
x+=dx;
y+=dy;
}
<|endoftext|>


<commit_before>/*
 * jQuery File Upload Plugin JS Example 6.2
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/*jslint nomen: true, unparam: true, regexp: true */
/*global $, window, document */

$(function () {
    'use strict';

    // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload();

    if (window.location.hostname === 'blueimp.github.com') {
        // Demo settings:
        $('#fileupload').fileupload('option', {
            url: '//jquery-file-upload.appspot.com',
            maxFileSize: 5000000,
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
        });
        $.get('//jquery-file-upload.appspot.com').fail(function () {
            $('')
                .text('Upload server currently unavailable - ' + new Date())
                .appendTo('#fileupload');
        });
    } else {
        // Load existing files:
        $.getJSON($('#fileupload').prop('action'), function (files) {
            var fu = $('#fileupload').data('fileupload'),
                template;
            fu._adjustMaxNumberOfFiles(-files.length);
            template = fu._renderDownload(files)
                .appendTo($('#fileupload .files'));
            // Force reflow:
            fu._reflow = $.support.transition && template.length &&
                template[0].offsetWidth;
            template.addClass('in');
        });
    }

    // Enable iframe cross-domain access via redirect page:
    var redirectPage = window.location.href.replace(
        /\/[^\/]*$/,
        '/cors/result.html?%s'
    );
    $('#fileupload').bind('fileuploadsend', function (e, data) {
        if (data.dataType.substr(0, 6) === 'iframe') {
            var target = $('').prop('href', data.url)[0];
            if (window.location.host !== target.host) {
                data.formData.push({
                    name: 'redirect',
                    value: redirectPage
                });
            }
        }
    });

    // Open download dialogs via iframes,
    // to prevent aborting current uploads:
    $('#fileupload .files').delegate(
        'a:not([rel^=gallery])',
        'click',
        function (e) {
            e.preventDefault();
            $('')
                .prop('src', this.href)
                .appendTo(document.body);
        }
    );

});
<commit_msg>Enable upload server status check only for browsers with CORS support.<commit_after>/*
 * jQuery File Upload Plugin JS Example 6.2
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/*jslint nomen: true, unparam: true, regexp: true */
/*global $, window, document, XMLHttpRequest */

$(function () {
    'use strict';

    // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload();

    if (window.location.hostname === 'blueimp.github.com') {
        // Demo settings:
        $('#fileupload').fileupload('option', {
            url: '//jquery-file-upload.appspot.com/',
            maxFileSize: 5000000,
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
        });
        // Upload server status check for browsers with CORS support:
        if (window.XDomainRequest || (window.XMLHttpRequest &&
                (new XMLHttpRequest()).withCredentials !== undefined)) {
            $.get('//jquery-file-upload.appspot.com/')
                .fail(function () {
                    $('')
                        .text('Upload server currently unavailable - ' +
                                new Date())
                        .appendTo('#fileupload');
                });
        }
    } else {
        // Load existing files:
        $.getJSON($('#fileupload').prop('action'), function (files) {
            var fu = $('#fileupload').data('fileupload'),
                template;
            fu._adjustMaxNumberOfFiles(-files.length);
            template = fu._renderDownload(files)
                .appendTo($('#fileupload .files'));
            // Force reflow:
            fu._reflow = $.support.transition && template.length &&
                template[0].offsetWidth;
            template.addClass('in');
        });
    }

    // Enable iframe cross-domain access via redirect page:
    var redirectPage = window.location.href.replace(
        /\/[^\/]*$/,
        '/cors/result.html?%s'
    );
    $('#fileupload').bind('fileuploadsend', function (e, data) {
        if (data.dataType.substr(0, 6) === 'iframe') {
            var target = $('').prop('href', data.url)[0];
            if (window.location.host !== target.host) {
                data.formData.push({
                    name: 'redirect',
                    value: redirectPage
                });
            }
        }
    });

    // Open download dialogs via iframes,
    // to prevent aborting current uploads:
    $('#fileupload .files').delegate(
        'a:not([rel^=gallery])',
        'click',
        function (e) {
            e.preventDefault();
            $('')
                .prop('src', this.href)
                .appendTo(document.body);
        }
    );

});
<|endoftext|>


<commit_before>function on_index_html(html) {
    // Look for patterns like:  href="couchbase-server-community_x86_64_2.0.0c-709-rel.rpm.manifest.xml"

    var urls = {}
    var hier = {} // Hierarchy of maps, keyed by name / version / build / arch / pkg.

    var hrefs = html.match(/href="[^\"]+\.manifest\.xml"/g);
    for (var i = 0; i < hrefs.length; i++) {
        var href = hrefs[i];
        var url = href.split('"')[1];
        var s = url.split('_');
        var name = s[0];
        var arch = s.slice(1, s.length - 1).join("_");
        var suffix = s[s.length - 1].split('-');
        var version = suffix[0];
        var build = suffix[1];
        if (suffix && suffix[2]) {
            var pkg = suffix[2].split('.')[suffix[2].split('.').length - 3];

            var p = { "url": url,
                      "name": name,
                      "version": version,
                      "build": build,
                      "arch": arch,
                      "pkg": pkg };
            urls[url] = p;

            add_entry(hier, [name, version, build, arch, pkg], p);
        }
    }

    $('#content').html(gen(hier));
}

function add_entry(hier, path, val) {
    for (var i = 0; i < path.length - 1; i++) {
        var m = hier[path[i]];
        if (!m) {
            m = hier[path[i]] = {};
        }
        hier = m;
    }
    hier[path[path.length - 1]] = val;
}

function gen(hier) {
    var r = [];
    for (var name in keys(hier).sort()) {
        hier[r.length] = '
' + name + '
';
        var versions = hier[name];
        for (var version in keys(versions).sort()) {
            r[r.length] = '
' + version + '
';
            var builds = versions[version];
            for (var build in keys(builds).sort().reverse()) {
                r[r.length] = '
' + build + '
';
                var archs = builds[build];
                for (var arch in keys(archs).sort()) {
                    r[r.length] = '
' + arch + '
';
                    var pkgs = archs[arch];
                    for (var pkg in keys(pkgs).sort()) {
                        var p = pkgs[pkg];
                        var u = (p.url || '').replace('.manifest.xml', '');
                        r[r.length] = '
' + pkg + '
';
                    }
                    r[r.length] = '

';
                }
                r[r.length] = '

';
            }
            r[r.length] = '

';
        }
        r[r.length] = '

';
    }
    return r;
}

function keys(m) {
    var keys = [];
    for (var key in m) {
        keys[keys.length] = key;
    }
    return keys;
}

function on_ready() {
    $.get("../../index.html", null,
          function(response, textStatus, jqXHR){
              on_index_html(response);
          });
}

$(document).ready(on_ready);
<commit_msg>typo in gen()<commit_after>function on_index_html(html) {
    // Look for patterns like:  href="couchbase-server-community_x86_64_2.0.0c-709-rel.rpm.manifest.xml"

    var urls = {}
    var hier = {} // Hierarchy of maps, keyed by name / version / build / arch / pkg.

    var hrefs = html.match(/href="[^\"]+\.manifest\.xml"/g);
    for (var i = 0; i < hrefs.length; i++) {
        var href = hrefs[i];
        var url = href.split('"')[1];
        var s = url.split('_');
        var name = s[0];
        var arch = s.slice(1, s.length - 1).join("_");
        var suffix = s[s.length - 1].split('-');
        var version = suffix[0];
        var build = suffix[1];
        if (suffix && suffix[2]) {
            var pkg = suffix[2].split('.')[suffix[2].split('.').length - 3];

            var p = { "url": url,
                      "name": name,
                      "version": version,
                      "build": build,
                      "arch": arch,
                      "pkg": pkg };
            urls[url] = p;

            add_entry(hier, [name, version, build, arch, pkg], p);
        }
    }

    $('#content').html(gen(hier));
}

function add_entry(hier, path, val) {
    for (var i = 0; i < path.length - 1; i++) {
        var m = hier[path[i]];
        if (!m) {
            m = hier[path[i]] = {};
        }
        hier = m;
    }
    hier[path[path.length - 1]] = val;
}

function gen(hier) {
    var r = [];
    for (var name in keys(hier).sort()) {
        r[r.length] = '
' + name + '
';
        var versions = hier[name];
        for (var version in keys(versions).sort()) {
            r[r.length] = '
' + version + '
';
            var builds = versions[version];
            for (var build in keys(builds).sort().reverse()) {
                r[r.length] = '
' + build + '
';
                var archs = builds[build];
                for (var arch in keys(archs).sort()) {
                    r[r.length] = '
' + arch + '
';
                    var pkgs = archs[arch];
                    for (var pkg in keys(pkgs).sort()) {
                        var p = pkgs[pkg];
                        var u = (p.url || '').replace('.manifest.xml', '');
                        r[r.length] = '
' + pkg + '
';
                    }
                    r[r.length] = '

';
                }
                r[r.length] = '

';
            }
            r[r.length] = '

';
        }
        r[r.length] = '

';
    }
    return r;
}

function keys(m) {
    var keys = [];
    for (var key in m) {
        keys[keys.length] = key;
    }
    return keys;
}

function on_ready() {
    $.get("../../index.html", null,
          function(response, textStatus, jqXHR){
              on_index_html(response);
          });
}

$(document).ready(on_ready);
<|endoftext|>


<commit_before>$(document).ready(function(event){
   $('#submit').click(function(event){
      getData();

   });
   $('#formThing').submit(function(event){
      event.preventDefault();
      getData();
   });
});
function getData(){
    $.get('https://player.me/api/v1/users/?username=true' + $('#inputText').val(), "", function(data){
         var avatar = "https://player.me/api/v1/users/?username=true" + data['id']['avatar'] + "/avatarId";
         var username = data['id']['username'];
         var followers = data['followers'];
         if(data['type'] != null){
            var lastPlayed = data['type']['name'];
         }else{
            var lastPlayed = "None";
         }
         var joined = data['createdAt'];
         var html = '';
         html += '
' + username + '
';
         html += '
Followers: ' + followers;
         html += '
Total Views: ' + totalViews;
         html += "
";
         if(online){
             html += '
Online';
         }else{
             html += '
Offline';
         }
         html+= '
Last Played: ' + lastPlayed;
         html += '
Joined on: ' + joined.replace('T', ' at ');
         $('.profile').html(html);
      });
}
<commit_msg>Update main.js<commit_after>$(document).ready(function(event){
   $('#submit').click(function(event){
      getData();

   });
   $('#formThing').submit(function(event){
      event.preventDefault();
      getData();
   });
});
function getData(){
    $.get('https://player.me/api/v1/users/?username=true' + $('#inputText').val(), "", function(data){
         var avatar = "https://player.me/api/v1/users/" + data['username']['avatar'] + "/?username=true";
         var username = data['id']['username'];
         var followers = data['followers_count'];
         if(data['type'] != null){
            var lastPlayed = data['type']['name'];
         }else{
            var lastPlayed = "None";
         }
         var joined = data['created_at'];
         var html = '';
         html += '
' + username + '
';
         html += '
Followers: ' + followers;
         html += '
Following: ' + totalViews;
         html += "
";
         if(online){
             html += '
Online';
         }else{
             html += '
Offline';
         }
         html+= '
Last Played: ' + lastPlayed;
         html += '
Joined on: ' + joined.replace('T', ' at ');
         $('.profile').html(html);
      });
}
<|endoftext|>


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

  function ready () {
    var i = $('img[class^=centred]');
    $.openImage(i.src);
  }

  $.register({
    rule: [
      {
        host: [
          /^(image(decode|ontime)|(zonezeed|zelje|croft|myhot|dam|bok)image|picstwist|www\.imglemon|ericsony|img(pu|slip)|wpc8)\.com$/,
          /^(img(serve|coin|fap)|gallerycloud)\.net$/,
          /^hotimages\.eu$/,
          /^(imgstudio|dragimage|imageteam)\.org$/,
        ],
        path: /^\/img-.*\.html$/,
      },
      {
        host: /^imgrun\.net$/,
        path: /^\/t\/img-.*\.html$/,
      },
    ],
    ready: ready,
  });

  $.register({
    rule: {
      host: /^www.img(adult|taxi).com$/,
      path: /^\/img-.*\.html$/,
    },
    start: function () {
      var c = $.getCookie('user');
      if (c) {
        return;
      }
      $.setCookie('user', 'true');
      window.location.reload();
    },
    ready: ready,
  });

  $.register({
    rule: {
      host: /^08lkk\.com$/,
      path: /^\/Photo\/img-.+\.html$/,
    },
    start: function () {
      // crack the shitty qqc.co visitScript 5440
      $.window.setTimeout = _.nop;

      // this site checks cookie that caculate from session
      // do an AJAX to skip checking
      $.get(window.location.toString()).then(function (data) {
        var a = $.toDOM(data);
        var i = $('img[class^=centred]', a);
        $.openImage(i.src);
      });
    },
  });

})();

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<commit_msg>uplimg.com<commit_after>(function () {
  'use strict';

  function ready () {
    var i = $('img[class^=centred]');
    $.openImage(i.src);
  }

  $.register({
    rule: [
      {
        host: [
          /^(image(decode|ontime)|(zonezeed|zelje|croft|myhot|dam|bok)image|picstwist|www\.imglemon|ericsony|img(pu|slip)|wpc8|uplimg)\.com$/,
          /^(img(serve|coin|fap)|gallerycloud)\.net$/,
          /^hotimages\.eu$/,
          /^(imgstudio|dragimage|imageteam)\.org$/,
        ],
        path: /^\/img-.*\.html$/,
      },
      {
        host: /^imgrun\.net$/,
        path: /^\/t\/img-.*\.html$/,
      },
    ],
    ready: ready,
  });

  $.register({
    rule: {
      host: /^www.img(adult|taxi).com$/,
      path: /^\/img-.*\.html$/,
    },
    start: function () {
      var c = $.getCookie('user');
      if (c) {
        return;
      }
      $.setCookie('user', 'true');
      window.location.reload();
    },
    ready: ready,
  });

  $.register({
    rule: {
      host: /^08lkk\.com$/,
      path: /^\/Photo\/img-.+\.html$/,
    },
    start: function () {
      // crack the shitty qqc.co visitScript 5440
      $.window.setTimeout = _.nop;

      // this site checks cookie that caculate from session
      // do an AJAX to skip checking
      $.get(window.location.toString()).then(function (data) {
        var a = $.toDOM(data);
        var i = $('img[class^=centred]', a);
        $.openImage(i.src);
      });
    },
  });

})();

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<|endoftext|>


<commit_before>return Byte(256-this.integer);
<commit_msg>avoid instantiation for -0<commit_after>return this.integer==0 ? this : Byte(256-this.integer);
<|endoftext|>


<commit_before>/**
 * # aliases
 * Copyright(c) 2021 Stefano Balietti
 * MIT Licensed
 *
 * Event listener aliases.
 *
 */
(function(exports, parent) {

    "use strict";

    var NGC = parent.NodeGameClient;

    /**
     * ## NodeGameClient.addDefaultAliases
     *
     * Adds a battery of setup functions
     *
     * @param {boolean} force Whether to force re-adding the aliases
     *
     * @return {boolean} TRUE on success
     */
    NGC.prototype.addDefaultAliases = function(force) {
        var that;
        if (this.conf.aliasesAdded && !force) {
            this.err('node.addDefaultAliases: aliases already ' +
                     'added. Use the force flag to re-add.');
            return false;
        }
        that = this;

        this.info('node: adding default aliases.');

        // ### node.on.txt
        this.alias('txt', 'in.say.TXT');

        // ### node.on.data
        this.alias('data', ['in.say.DATA', 'in.set.DATA'], function(text, cb) {
            if ('string' !== typeof text || text === '') {
                throw new TypeError('node.on.data: text must be a non-empty ' +
                                    'string. Found: ' + text);
            }
            return function(msg) {
                if (msg.text === text) cb.call(that.game, msg);
                else return false;
            };
        });

        // ### node.on.data
        this.alias('done', 'in.set.DATA', function(step, cb) {
            return function(msg) {
                if (!msg.data || !msg.data.done ||
                    !that.game.isStep(step, msg.stage)) {

                    return false;
                }
                cb.call(that.game, msg);
            };
        });

        // ### node.on.stage
        this.alias('stage', 'STEPPING', function(cb) {
            return function(curStep, newStep) {
                if (curStep.stage !== newStep.stage) cb(curStep, newStep);
                else return false;
            };
        });

        // ### node.on.stage
        this.alias('step', 'STEPPING');

        // ### node.on.plist
        this.alias('plist', ['in.set.PLIST', 'in.say.PLIST']);

        // ### node.on.pconnect
        this.alias('pconnect', 'in.say.PCONNECT', function(cb) {
            return function(msg) {
                cb.call(that.game, msg.data);
            };
        });

        // ### node.on.pdisconnect
        this.alias('pdisconnect', 'in.say.PDISCONNECT', function(cb) {
            return function(msg) {
                cb.call(that.game, msg.data);
            };
        });

        // ### node.on.preconnect
        this.alias('preconnect', 'in.say.PRECONNECT', function(cb) {
            return function(msg) {
                cb.call(that.game, msg.data);
            };
        });

        // ### node.on.mconnect
        this.alias('mconnect', 'in.say.MCONNECT', function(cb) {
            return function(msg) {
                cb.call(that.game, msg.data);
            };
        });

        // ### node.on.mreconnect
        this.alias('mreconnect', 'in.say.MRECONNECT', function(cb) {
            return function(msg) {
                cb.call(that.game, msg.data);
            };
        });

        // ### node.on.mdisconnect
        this.alias('mdisconnect', 'in.say.MDISCONNECT', function(cb) {
            return function(msg) {
                cb.call(that.game, msg.data);
            };
        });

        // ### node.on.lang
        // Gets language information.
        this.alias('lang','in.say.LANG');

        this.silly('node: aliases added.');
        return true;
    };

})(
    'undefined' != typeof node ? node : module.exports,
    'undefined' != typeof node ? node : module.parent.exports
);
<commit_msg>alias DONE fixed<commit_after>/**
 * # aliases
 * Copyright(c) 2021 Stefano Balietti
 * MIT Licensed
 *
 * Event listener aliases.
 *
 */
(function(exports, parent) {

    "use strict";

    var NGC = parent.NodeGameClient;

    /**
     * ## NodeGameClient.addDefaultAliases
     *
     * Adds a battery of setup functions
     *
     * @param {boolean} force Whether to force re-adding the aliases
     *
     * @return {boolean} TRUE on success
     */
    NGC.prototype.addDefaultAliases = function(force) {
        var that;
        if (this.conf.aliasesAdded && !force) {
            this.err('node.addDefaultAliases: aliases already ' +
                     'added. Use the force flag to re-add.');
            return false;
        }
        that = this;

        this.info('node: adding default aliases.');

        // ### node.on.txt
        this.alias('txt', 'in.say.TXT');

        // ### node.on.data
        this.alias('data', ['in.say.DATA', 'in.set.DATA'], function(text, cb) {
            if ('string' !== typeof text || text === '') {
                throw new TypeError('node.on.data: text must be a non-empty ' +
                                    'string. Found: ' + text);
            }
            return function(msg) {
                if (msg.text === text) cb.call(that.game, msg);
                else return false;
            };
        });

        // ### node.on.data
        this.alias('done', 'in.set.DATA', function(step, cb) {
            if ('undefined' === typeof cb && 'function' === typeof step) {
                cb = step;
                step = null;
            }
            return function(msg) {
                if (!msg.data || !msg.data.done ||
                    (step && !that.game.isStep(step, msg.stage))) {

                    return false;
                }
                cb.call(that.game, msg);
            };
        });

        // ### node.on.stage
        this.alias('stage', 'STEPPING', function(cb) {
            return function(curStep, newStep) {
                if (curStep.stage !== newStep.stage) cb(curStep, newStep);
                else return false;
            };
        });

        // ### node.on.stage
        this.alias('step', 'STEPPING');

        // ### node.on.plist
        this.alias('plist', ['in.set.PLIST', 'in.say.PLIST']);

        // ### node.on.pconnect
        this.alias('pconnect', 'in.say.PCONNECT', function(cb) {
            return function(msg) {
                cb.call(that.game, msg.data);
            };
        });

        // ### node.on.pdisconnect
        this.alias('pdisconnect', 'in.say.PDISCONNECT', function(cb) {
            return function(msg) {
                cb.call(that.game, msg.data);
            };
        });

        // ### node.on.preconnect
        this.alias('preconnect', 'in.say.PRECONNECT', function(cb) {
            return function(msg) {
                cb.call(that.game, msg.data);
            };
        });

        // ### node.on.mconnect
        this.alias('mconnect', 'in.say.MCONNECT', function(cb) {
            return function(msg) {
                cb.call(that.game, msg.data);
            };
        });

        // ### node.on.mreconnect
        this.alias('mreconnect', 'in.say.MRECONNECT', function(cb) {
            return function(msg) {
                cb.call(that.game, msg.data);
            };
        });

        // ### node.on.mdisconnect
        this.alias('mdisconnect', 'in.say.MDISCONNECT', function(cb) {
            return function(msg) {
                cb.call(that.game, msg.data);
            };
        });

        // ### node.on.lang
        // Gets language information.
        this.alias('lang','in.say.LANG');

        this.silly('node: aliases added.');
        return true;
    };

})(
    'undefined' != typeof node ? node : module.exports,
    'undefined' != typeof node ? node : module.parent.exports
);
<|endoftext|>


<commit_before>/*
File: projects.js
URL: /static/js/projects.js
Powers /projects/[List type] - template is run_dir/design/projects.html
*/

// Get pseudo-argument for this js file. projects = 'pending' | 'ongoing' | ...
var projects_page_type = $('#projects-js').attr('data-projects');

var begin = new Date(2012,0, 1);
var end = new Date();

$('#projectFilterDate').on('shown.bs.modal', function () {
 $("#OpenDateSlider").dateRangeSlider('resize');
 $("#QueueDateSlider").dateRangeSlider('resize');
 $("#CloseDateSlider").dateRangeSlider('resize');
})
$(document).ready(function() {
    //load the sliders
    $(".dateSlider").dateRangeSlider({
    range: true,
    bounds:{
      min: begin,
      max: end,
    },
    defaultValues:{
        min: begin,
        max: end,
    }
});

  // Load the presets first (to get the table headers)
  $.when(load_presets()).done(function(){
    // Show the page
    $('#loading_spinner').hide();
    $('#page_content').show();
  });

  // Prevent traditional html submit function
  $('#Search-form').submit(function(event){event.preventDefault();});

});

// Load the Projects Table
function load_table() {
  // Get the columns and write the table header
  columns = read_current_filtering();
  load_table_head(columns);

  // Display the loading spinner in the table
  $("#project_table_body").html('
 Loading..
');

    url="/api/v1/projects?list=" + projects_page_type;
    // Date filtering
    if ($("#OpenDateSlider").dateRangeSlider("values").min !==$("#OpenDateSlider").dateRangeSlider("bounds").min ||
       $("#OpenDateSlider").dateRangeSlider("values").max !==$("#OpenDateSlider").dateRangeSlider("bounds").max ){
        old_open_date=$("#OpenDateSlider").dateRangeSlider("values").min.getFullYear()+'-'+('0'+($("#OpenDateSlider").dateRangeSlider("values").min.getMonth()+1)).slice(-2)+'-'+('0'+$("#OpenDateSlider").dateRangeSlider("values").min.getDate()).slice(-2);
        new_open_date=$("#OpenDateSlider").dateRangeSlider("values").max.getFullYear()+'-'+('0'+($("#OpenDateSlider").dateRangeSlider("values").max.getMonth()+1)).slice(-2)+'-'+('0'+$("#OpenDateSlider").dateRangeSlider("values").max.getDate()).slice(-2);
        url=url+"&oldest_open_date="+old_open_date+"&youngest_open_date="+new_open_date;
       }
    if ($("#QueueDateSlider").dateRangeSlider("values").min !==$("#QueueDateSlider").dateRangeSlider("bounds").min ||
       $("#QueueDateSlider").dateRangeSlider("values").max !==$("#QueueDateSlider").dateRangeSlider("bounds").max ){
        old_queue_date=$("#QueueDateSlider").dateRangeSlider("values").min.getFullYear()+'-'+('0'+($("#QueueDateSlider").dateRangeSlider("values").min.getMonth()+1)).slice(-2)+'-'+('0'+$("#QueueDateSlider").dateRangeSlider("values").min.getDate()).slice(-2);
        new_queue_date=$("#QueueDateSlider").dateRangeSlider("values").max.getFullYear()+'-'+('0'+($("#QueueDateSlider").dateRangeSlider("values").max.getMonth()+1)).slice(-2)+'-'+('0'+$("#QueueDateSlider").dateRangeSlider("values").max.getDate()).slice(-2);
        url=url+"&oldest_queue_date="+old_queue_date+"&youngest_queue_date="+new_queue_date;
       }
    if ($("#CloseDateSlider").dateRangeSlider("values").min !==$("#CloseDateSlider").dateRangeSlider("bounds").min ||
       $("#CloseDateSlider").dateRangeSlider("values").max !==$("#CloseDateSlider").dateRangeSlider("bounds").max ){
        old_close_date=$("#CloseDateSlider").dateRangeSlider("values").min.getFullYear()+'-'+('0'+($("#CloseDateSlider").dateRangeSlider("values").min.getMonth()+1)).slice(-2)+'-'+('0'+$("#CloseDateSlider").dateRangeSlider("values").min.getDate()).slice(-2);
        new_close_date=$("#CloseDateSlider").dateRangeSlider("values").max.getFullYear()+'-'+('0'+($("#CloseDateSlider").dateRangeSlider("values").max.getMonth()+1)).slice(-2)+'-'+('0'+$("#CloseDateSlider").dateRangeSlider("values").max.getDate()).slice(-2);
        url=url+"&oldest_close_date="+old_close_date+"&youngest_close_date="+new_close_date;
       }

  //Current loaded fields :
  var fields= [];
  $("#Filter .filterCheckbox").each(function() {
    fields.push($(this).attr('name'));
  });
  return $.getJSON(url, function(data) {
    if ($.fn.dataTable.isDataTable( '#project_table' )){
        var dtbl= $('#project_table').DataTable();
        dtbl.destroy();
        $("#project_table_filter").remove();
    }
    $("#project_table_body").empty();
    var size = 0;
    undefined_fields=[];
    $.each(data, function(project_id, summary_row) {
      $.each(summary_row, function(key,value){
        //this tracks the fields existing in our projects objects, but not present in the filter tab yet.
        if ($.inArray(key, undefined_fields) == -1 && $.inArray(key, fields) == -1 ){
          undefined_fields.push(key);
        }
      });
      size++;
      var tbl_row = $('
');
      $.each(columns, function(i, column_tuple){
        tbl_row.append($('')
          .addClass(column_tuple[1])
          .html(summary_row[column_tuple[1]])
          );
      });

      // Add links to projects
      tbl_row.find('td.project').html('' + project_id + '');

      // Add links to Portal References
      var portal_name = summary_row['customer_project_reference'];
      var portal_id = summary_row['portal_id'];
      tbl_row.find('td.customer_project_reference').html('' + portal_name + '');

      //parse and display running notes
      var latest_note = tbl_row.find('td.latest_running_note');
      if (latest_note.text() !== '') {
        var note = JSON.parse(latest_note.text());
        var ndate = undefined;
        for (key in note) { ndate = key; break; }
        notedate = new Date(ndate);
        latest_note.html('
' +
            '
'+
              note[ndate]['user']+' - '+notedate.toDateString()+', ' + notedate.toLocaleTimeString(notedate)+
            '

'+make_markdown(note[ndate]['note'])+'

');

      }
      $("#project_table_body").append(tbl_row);
    });
    load_undefined_columns(undefined_fields)

    // Initialise the Javascript sorting now that we know the number of rows
    init_listjs(size, columns);
  });
}

function load_table_head(columns){
  var tbl_head = $('
');
  var tbl_foot = $('
');
  $.each(columns, function(i, column_tuple) {
    tbl_head.append($('')
      .addClass('sort a')
      .attr('data-sort', column_tuple[1])
      .text(column_tuple[0])
    );
    tbl_foot.append($('')
      .text(column_tuple[0])
    );
  });
  $("#project_table_head").html(tbl_head);
  $("#project_table_foot").html(tbl_foot);
}

// Undefined columns handled here now
function load_undefined_columns(cols) {
    var columns_html = "";
    $.each(cols, function(col_id, column) {
      $("#undefined_columns").append('
'+
          ''+
            '<input type="checkbox" class="filterCheckbox" data-columngroup="undefined-columns" data-displayname="'+column+'" name="'+column+'" id="undefined-columns-'+column+'">'+
            column+
          ''+
        '
');
    });
};

// Initialize sorting and searching javascript plugin
function init_listjs(no_items, columns) {
    // Setup - add a text input to each footer cell
    $('#project_table tfoot th').each( function () {
      var title = $('#project_table thead th').eq( $(this).index() ).text();
      $(this).html( '<input size=10 type="text" placeholder="Search '+title+'" />' );
    } );

    //initialize custom project sorting
    jQuery.extend(jQuery.fn.dataTableExt.oSort, {
            "pid-pre": function(a) {
                        var pid = $('
').html(a).find('a').first().text()
                        return parseInt(pid.replace(/P/gi, ''));
                            },
            "pid-asc": function(a,b) {
                        return a-b;
                            },
            "pid-desc": function(a,b) {
                        return b-a;
                            }
    });
    if ($.fn.dataTable.isDataTable( '#project_table' )){
        var table = $('#project_table').DataTable();
    }else{
        var table = $('#project_table').DataTable({
           "aoColumnDefs": [
              {"sType": "pid", "aTargets": [0]}
           ],
          "paging":false,
          "destroy": true,
          "info":false,
          "order": [[ 0, "desc" ]]
        });
    }

    //Add the bootstrap classes to the search thingy
    $('div.dataTables_filter input').addClass('form-control search search-query');
    $('#project_table_filter').addClass('form-inline pull-right');
    $("#project_table_filter").appendTo("h1");
    $('#project_table_filter label input').appendTo($('#project_table_filter'));
    $('#project_table_filter label').remove();
    $("#project_table_filter input").attr("placeholder", "Search..");
    // Apply the search
    table.columns().every( function () {
        var that = this;
        $( 'input', this.footer() ).on( 'keyup change', function () {
            that
            .search( this.value )
            .draw();
        } );
    } );
}

//Check or uncheck all fields from clicked category
function choose_column(col){
  var column = document.getElementById(col);
  //Get all the children (checkboxes)
  var cbs = column.getElementsByTagName('input');
  //If one of them is checked we uncheck it, if none of them are checked,
  //we check them all
  var checked = false;
  for (var i = 0; i < cbs.length; i++) {
    if (cbs[i].checked) {
      cbs[i].checked = false;
      checked = true;
    }
  }
  if (!checked) {
    for (var i = 0; i < cbs.length; i++) {
      cbs[i].checked = true;
    }
  }
}

////////////////////////////////
// Presets related functions  //
///////////////////////////////

function load_presets() {
  return $.getJSON('/api/v1/presets?presets_list=pv_presets', function (data) {
    var default_presets = data['default'];
    var user_presets = data['user'];

    // Default presets
    for (var preset in default_presets) {
      $('#default_preset_buttons').append('<button id="'+prettify(preset)+'" data-action="filterPresets" type="button" class="search-action btn btn-default">'+preset+'</button>');
    }
    // User presets, if there are any
    if (!jQuery.isEmptyObject(user_presets)) {
      for (var preset in user_presets) {
        $('#user_presets_dropdown').append('<button id="'+prettify(preset)+'" data-action="filterPresets" type="button" class="search-action btn btn-default">'+preset+'</button>');
      }
    }
    else {
      $('#user_presets_dropdown').append('No user presets');
    }

    // Check default checkboxes
    if (!$("#Filter :checked").length) {
      reset_default_checkboxes();
    }

    // Otherwise, load the table
    else {
      load_table();
    }
  });
}

// Column filtering clicks
$('body').on('click', '.search-action', function(event) {
  event.preventDefault();
  switch ($(this).data('action')) {
    case 'filterReset':
      reset_default_checkboxes(true);
    case 'filterApply':
      load_table();
      break;
    case 'filterHeader':
      choose_column($(this).parent().attr("id"));
      break;
    case 'filterPresets':
      select_from_preset($(this).parent().attr('id'), $(this).text());
      break;
  }
});

function reset_default_checkboxes(setdefault){
  setdefault = typeof setdefault !== 'undefined' ? setdefault : false;
  // Are we on a filtered page?
  if(!setdefault && $('.projects_page_heading').attr('id') == 'ongoing'){
    select_from_preset('default_preset_buttons', 'Lab personnel - Ongoing');
  } else if(!setdefault &&  $('.projects_page_heading').attr('id') == 'reception_control'){
    select_from_preset('default_preset_buttons', 'Lab personnel - Reception control');
  } else if(!setdefault &&  $('.projects_page_heading').attr('id') == 'pending'){
    select_from_preset('default_preset_buttons', 'Order Status');
  } else if(!setdefault &&  $('.projects_page_heading').attr('id') == 'pending_review'){
    select_from_preset('default_preset_buttons', 'Need Review');
  } else {
    // Sort out the button classes
    $('#default_preset_buttons button.active').removeClass('active');
    $('#resetProjectCols').addClass('active');
    // Change the checkboxes
    $('#Filter input').prop('checked', false); // uncheck everything
    $('#basic-columns input').prop('checked', true); // check the 'basic' columns

    // Apply the filter
    load_table();
  }
}

function read_current_filtering(){
  var columns = new Array();
  $("#Filter .filterCheckbox:checked").each(function() {
    columns.push([$(this).data('displayname'), $(this).attr('name')]);
  });
  return columns;
}

function select_from_preset(preset_type, preset) {
  return $.getJSON('/api/v1/presets?presets_list=pv_presets', function (data) {

    //First uncheck everything
    $('#default_preset_buttons button.active').removeClass('active');
    $('#Filter input:checkbox').removeAttr('checked');
    if (preset_type == "default_preset_buttons") {
      var choices = data['default'][preset];
      for (column in choices) {
        for (choice in choices[column]) {
          var column_id = column.toLowerCase().replace(/_/g, '-') + '-' + choice;
          prettyobj(column_id).prop('checked', choices[column][choice]);
        }
      }
      prettyobj(preset).addClass('active');

    } else if (preset_type == "users_presets_dropdown") {
      // TODO - implement this
    }

    // Apply the filter
    load_table();
  });
}

//
// HELPER FUNCTIONS
//

function prettify(s) {
  // Replaces whitespace with underscores. Replaces sequential _s with one
  // Removes trailing underscores
  return s.toLowerCase().replace(/\s+/g, "_").replace(/_+/g, "_").replace(/^_/, "").replace(/_$/, "");
}

// These functions avoid parsing errors due to jQuery not liking element
// IDs with brackets in. Otherwise eqivalent to $('#'+s)
function prettyobj(s) {
  return $(document.getElementById(prettify(s)));
}
function safeobj(s) {
  return $(document.getElementById(s));
}
<commit_msg>shorter version<commit_after>/*
File: projects.js
URL: /static/js/projects.js
Powers /projects/[List type] - template is run_dir/design/projects.html
*/

// Get pseudo-argument for this js file. projects = 'pending' | 'ongoing' | ...
var projects_page_type = $('#projects-js').attr('data-projects');

var begin = new Date(2012,0, 1);
var end = new Date();

$('#projectFilterDate').on('shown.bs.modal', function () {
 $("#OpenDateSlider").dateRangeSlider('resize');
 $("#QueueDateSlider").dateRangeSlider('resize');
 $("#CloseDateSlider").dateRangeSlider('resize');
})
$(document).ready(function() {
    //load the sliders
    $(".dateSlider").dateRangeSlider({
    range: true,
    bounds:{
      min: begin,
      max: end,
    },
    defaultValues:{
        min: begin,
        max: end,
    }
});

  // Load the presets first (to get the table headers)
  $.when(load_presets()).done(function(){
    // Show the page
    $('#loading_spinner').hide();
    $('#page_content').show();
  });

  // Prevent traditional html submit function
  $('#Search-form').submit(function(event){event.preventDefault();});

});

// Load the Projects Table
function load_table() {
  // Get the columns and write the table header
  columns = read_current_filtering();
  load_table_head(columns);

  // Display the loading spinner in the table
  $("#project_table_body").html('
 Loading..
');

    url="/api/v1/projects?list=" + projects_page_type;
    // Date filtering
    if ($("#OpenDateSlider").dateRangeSlider("values").min !==$("#OpenDateSlider").dateRangeSlider("bounds").min ||
       $("#OpenDateSlider").dateRangeSlider("values").max !==$("#OpenDateSlider").dateRangeSlider("bounds").max ){
        old_open_date=$("#OpenDateSlider").dateRangeSlider("values").min.getFullYear()+'-'+('0'+($("#OpenDateSlider").dateRangeSlider("values").min.getMonth()+1)).slice(-2)+'-'+('0'+$("#OpenDateSlider").dateRangeSlider("values").min.getDate()).slice(-2);
        new_open_date=$("#OpenDateSlider").dateRangeSlider("values").max.getFullYear()+'-'+('0'+($("#OpenDateSlider").dateRangeSlider("values").max.getMonth()+1)).slice(-2)+'-'+('0'+$("#OpenDateSlider").dateRangeSlider("values").max.getDate()).slice(-2);
        url=url+"&oldest_open_date="+old_open_date+"&youngest_open_date="+new_open_date;
       }
    if ($("#QueueDateSlider").dateRangeSlider("values").min !==$("#QueueDateSlider").dateRangeSlider("bounds").min ||
       $("#QueueDateSlider").dateRangeSlider("values").max !==$("#QueueDateSlider").dateRangeSlider("bounds").max ){
        old_queue_date=$("#QueueDateSlider").dateRangeSlider("values").min.getFullYear()+'-'+('0'+($("#QueueDateSlider").dateRangeSlider("values").min.getMonth()+1)).slice(-2)+'-'+('0'+$("#QueueDateSlider").dateRangeSlider("values").min.getDate()).slice(-2);
        new_queue_date=$("#QueueDateSlider").dateRangeSlider("values").max.getFullYear()+'-'+('0'+($("#QueueDateSlider").dateRangeSlider("values").max.getMonth()+1)).slice(-2)+'-'+('0'+$("#QueueDateSlider").dateRangeSlider("values").max.getDate()).slice(-2);
        url=url+"&oldest_queue_date="+old_queue_date+"&youngest_queue_date="+new_queue_date;
       }
    if ($("#CloseDateSlider").dateRangeSlider("values").min !==$("#CloseDateSlider").dateRangeSlider("bounds").min ||
       $("#CloseDateSlider").dateRangeSlider("values").max !==$("#CloseDateSlider").dateRangeSlider("bounds").max ){
        old_close_date=$("#CloseDateSlider").dateRangeSlider("values").min.getFullYear()+'-'+('0'+($("#CloseDateSlider").dateRangeSlider("values").min.getMonth()+1)).slice(-2)+'-'+('0'+$("#CloseDateSlider").dateRangeSlider("values").min.getDate()).slice(-2);
        new_close_date=$("#CloseDateSlider").dateRangeSlider("values").max.getFullYear()+'-'+('0'+($("#CloseDateSlider").dateRangeSlider("values").max.getMonth()+1)).slice(-2)+'-'+('0'+$("#CloseDateSlider").dateRangeSlider("values").max.getDate()).slice(-2);
        url=url+"&oldest_close_date="+old_close_date+"&youngest_close_date="+new_close_date;
       }

  //Current loaded fields :
  var fields= [];
  $("#Filter .filterCheckbox").each(function() {
    fields.push($(this).attr('name'));
  });
  return $.getJSON(url, function(data) {
    if ($.fn.dataTable.isDataTable( '#project_table' )){
        var dtbl= $('#project_table').DataTable();
        dtbl.destroy();
        $("#project_table_filter").remove();
    }
    $("#project_table_body").empty();
    var size = 0;
    undefined_fields=[];
    $.each(data, function(project_id, summary_row) {
      $.each(summary_row, function(key,value){
        //this tracks the fields existing in our projects objects, but not present in the filter tab yet.
        if ($.inArray(key, undefined_fields) == -1 && $.inArray(key, fields) == -1 ){
          undefined_fields.push(key);
        }
      });
      size++;
      var tbl_row = $('
');
      $.each(columns, function(i, column_tuple){
        tbl_row.append($('')
          .addClass(column_tuple[1])
          .html(summary_row[column_tuple[1]])
          );
      });

      // Add links to projects
      tbl_row.find('td.project').html('' + project_id + '');

      // Add links to Portal References
      var portal_name = summary_row['customer_project_reference'];
      var portal_id = summary_row['portal_id'];
      tbl_row.find('td.customer_project_reference').html('' + portal_name + '');

      //parse and display running notes
      var latest_note = tbl_row.find('td.latest_running_note');
      if (latest_note.text() !== '') {
        var note = JSON.parse(latest_note.text());
        var ndate = undefined;
        for (key in note) { ndate = key; break; }
        notedate = new Date(ndate);
        latest_note.html('
' +
            '
'+
              note[ndate]['user']+' - '+notedate.toDateString()+', ' + notedate.toLocaleTimeString(notedate)+
            '

'+make_markdown(note[ndate]['note'])+'

');

      }
      $("#project_table_body").append(tbl_row);
    });
    load_undefined_columns(undefined_fields)

    // Initialise the Javascript sorting now that we know the number of rows
    init_listjs(size, columns);
  });
}

function load_table_head(columns){
  var tbl_head = $('
');
  var tbl_foot = $('
');
  $.each(columns, function(i, column_tuple) {
    tbl_head.append($('')
      .addClass('sort a')
      .attr('data-sort', column_tuple[1])
      .text(column_tuple[0])
    );
    tbl_foot.append($('')
      .text(column_tuple[0])
    );
  });
  $("#project_table_head").html(tbl_head);
  $("#project_table_foot").html(tbl_foot);
}

// Undefined columns handled here now
function load_undefined_columns(cols) {
    var columns_html = "";
    $.each(cols, function(col_id, column) {
      $("#undefined_columns").append('
'+
          ''+
            '<input type="checkbox" class="filterCheckbox" data-columngroup="undefined-columns" data-displayname="'+column+'" name="'+column+'" id="undefined-columns-'+column+'">'+
            column+
          ''+
        '
');
    });
};

// Initialize sorting and searching javascript plugin
function init_listjs(no_items, columns) {
    // Setup - add a text input to each footer cell
    $('#project_table tfoot th').each( function () {
      var title = $('#project_table thead th').eq( $(this).index() ).text();
      $(this).html( '<input size=10 type="text" placeholder="Search '+title+'" />' );
    } );

    //initialize custom project sorting
    jQuery.extend(jQuery.fn.dataTableExt.oSort, {
            "pid-pre": function(a) {
                        return parseInt($(a).text().replace(/P/gi, ''));
                            },
            "pid-asc": function(a,b) {
                        return a-b;
                            },
            "pid-desc": function(a,b) {
                        return b-a;
                            }
    });
    if ($.fn.dataTable.isDataTable( '#project_table' )){
        var table = $('#project_table').DataTable();
    }else{
        var table = $('#project_table').DataTable({
           "aoColumnDefs": [
              {"sType": "pid", "aTargets": [0]}
           ],
          "paging":false,
          "destroy": true,
          "info":false,
          "order": [[ 0, "desc" ]]
        });
    }

    //Add the bootstrap classes to the search thingy
    $('div.dataTables_filter input').addClass('form-control search search-query');
    $('#project_table_filter').addClass('form-inline pull-right');
    $("#project_table_filter").appendTo("h1");
    $('#project_table_filter label input').appendTo($('#project_table_filter'));
    $('#project_table_filter label').remove();
    $("#project_table_filter input").attr("placeholder", "Search..");
    // Apply the search
    table.columns().every( function () {
        var that = this;
        $( 'input', this.footer() ).on( 'keyup change', function () {
            that
            .search( this.value )
            .draw();
        } );
    } );
}

//Check or uncheck all fields from clicked category
function choose_column(col){
  var column = document.getElementById(col);
  //Get all the children (checkboxes)
  var cbs = column.getElementsByTagName('input');
  //If one of them is checked we uncheck it, if none of them are checked,
  //we check them all
  var checked = false;
  for (var i = 0; i < cbs.length; i++) {
    if (cbs[i].checked) {
      cbs[i].checked = false;
      checked = true;
    }
  }
  if (!checked) {
    for (var i = 0; i < cbs.length; i++) {
      cbs[i].checked = true;
    }
  }
}

////////////////////////////////
// Presets related functions  //
///////////////////////////////

function load_presets() {
  return $.getJSON('/api/v1/presets?presets_list=pv_presets', function (data) {
    var default_presets = data['default'];
    var user_presets = data['user'];

    // Default presets
    for (var preset in default_presets) {
      $('#default_preset_buttons').append('<button id="'+prettify(preset)+'" data-action="filterPresets" type="button" class="search-action btn btn-default">'+preset+'</button>');
    }
    // User presets, if there are any
    if (!jQuery.isEmptyObject(user_presets)) {
      for (var preset in user_presets) {
        $('#user_presets_dropdown').append('<button id="'+prettify(preset)+'" data-action="filterPresets" type="button" class="search-action btn btn-default">'+preset+'</button>');
      }
    }
    else {
      $('#user_presets_dropdown').append('No user presets');
    }

    // Check default checkboxes
    if (!$("#Filter :checked").length) {
      reset_default_checkboxes();
    }

    // Otherwise, load the table
    else {
      load_table();
    }
  });
}

// Column filtering clicks
$('body').on('click', '.search-action', function(event) {
  event.preventDefault();
  switch ($(this).data('action')) {
    case 'filterReset':
      reset_default_checkboxes(true);
    case 'filterApply':
      load_table();
      break;
    case 'filterHeader':
      choose_column($(this).parent().attr("id"));
      break;
    case 'filterPresets':
      select_from_preset($(this).parent().attr('id'), $(this).text());
      break;
  }
});

function reset_default_checkboxes(setdefault){
  setdefault = typeof setdefault !== 'undefined' ? setdefault : false;
  // Are we on a filtered page?
  if(!setdefault && $('.projects_page_heading').attr('id') == 'ongoing'){
    select_from_preset('default_preset_buttons', 'Lab personnel - Ongoing');
  } else if(!setdefault &&  $('.projects_page_heading').attr('id') == 'reception_control'){
    select_from_preset('default_preset_buttons', 'Lab personnel - Reception control');
  } else if(!setdefault &&  $('.projects_page_heading').attr('id') == 'pending'){
    select_from_preset('default_preset_buttons', 'Order Status');
  } else if(!setdefault &&  $('.projects_page_heading').attr('id') == 'pending_review'){
    select_from_preset('default_preset_buttons', 'Need Review');
  } else {
    // Sort out the button classes
    $('#default_preset_buttons button.active').removeClass('active');
    $('#resetProjectCols').addClass('active');
    // Change the checkboxes
    $('#Filter input').prop('checked', false); // uncheck everything
    $('#basic-columns input').prop('checked', true); // check the 'basic' columns

    // Apply the filter
    load_table();
  }
}

function read_current_filtering(){
  var columns = new Array();
  $("#Filter .filterCheckbox:checked").each(function() {
    columns.push([$(this).data('displayname'), $(this).attr('name')]);
  });
  return columns;
}

function select_from_preset(preset_type, preset) {
  return $.getJSON('/api/v1/presets?presets_list=pv_presets', function (data) {

    //First uncheck everything
    $('#default_preset_buttons button.active').removeClass('active');
    $('#Filter input:checkbox').removeAttr('checked');
    if (preset_type == "default_preset_buttons") {
      var choices = data['default'][preset];
      for (column in choices) {
        for (choice in choices[column]) {
          var column_id = column.toLowerCase().replace(/_/g, '-') + '-' + choice;
          prettyobj(column_id).prop('checked', choices[column][choice]);
        }
      }
      prettyobj(preset).addClass('active');

    } else if (preset_type == "users_presets_dropdown") {
      // TODO - implement this
    }

    // Apply the filter
    load_table();
  });
}

//
// HELPER FUNCTIONS
//

function prettify(s) {
  // Replaces whitespace with underscores. Replaces sequential _s with one
  // Removes trailing underscores
  return s.toLowerCase().replace(/\s+/g, "_").replace(/_+/g, "_").replace(/^_/, "").replace(/_$/, "");
}

// These functions avoid parsing errors due to jQuery not liking element
// IDs with brackets in. Otherwise eqivalent to $('#'+s)
function prettyobj(s) {
  return $(document.getElementById(prettify(s)));
}
function safeobj(s) {
  return $(document.getElementById(s));
}
<|endoftext|>


<commit_before>var grunt = require('grunt'),
    glob = require('glob'),
    getFileHash = require('./file-hash'),
    getDirLabel = require('./dir-label'),
    hashPath = require('./hash-path'),
    join = require('path').join;

    var META_DIR = '.meta',
        LIST_FILE = 'files.json';

    module.exports = {
        merge: function(dest, src, options) {
            'use strict';

            var getHash = options.getHash || getFileHash,
                getLabel = options.getLabel || getDirLabel,
                getFileId = options.getFileIf || hashPath;

            // verify that dest and src are folders
            if (!grunt.file.isDir(dest)) {
                throw new Error('Invalid dest folder');
            }
            if (!grunt.file.isDir(src)) {
                throw new Error('Invalid src folder');
            }

            // get folder label
            var label = getLabel(src);
            if (typeof label !== 'string') {
                throw new Error('Invalid label');
            }

            // right now there is no support for merging folders
            // with meta info
            var srcMeta = join(src, META_DIR, LIST_FILE);
            if (grunt.file.isDir(srcMeta)) {
                throw new Error('Meta folder in ' + src);
            }

            // test if meta is available
            var destMeta = join(dest, META_DIR, LIST_FILE);
            var files = {};
            if (grunt.file.isDir(destMeta)) {
                files = grunt.file.readJSON(destMeta);
            } else {
                grunt.file.mkdir(join(dest, META_DIR));
            }

            // label must not already have been added
            if (files.labels.indexOf(label) !== -1) {
                throw new Error('Label already indexed');
            }

            // get file list
            var srcFiles = glob.sync('**', {
                cwd: src,
                dot: true,
                nodir: true
            });

            // add files to meta index, marking them for copy when needed
            var toCopy = [];
            files.labels.push(label);
            srcFiles.forEach(function addFile(relPath) {
                var absPath = join(src, relPath);
                getHash.then(function evalHash(hash) {
                    if (relPath in files) {
                        var hashMap = files[relPath];
                        if (hash in hashMap) {
                            // file with same hash already indexed, adding
                            // label to list
                            hashMap[hash].push(label);
                        } else {
                            // a new version of the file, add file and
                            // update hash list
                            hashMap[hash] = [label];
                            toCopy.push({
                                src: absPath,
                                dest: getFileId(absPath, hash)
                            });
                        }
                    } else {
                        // file never indexed, add file and update
                        // hash list
                        files[relPath] = {};
                        files[relPath][hash] = [label];
                        toCopy.push({
                            src: absPath,
                            dest: getFileId(absPath, hash)
                        });
                    }
                });
            });

            // right now, folders that don't provide new files
            // are not welcome
            if (!toCopy.length) {
                throw new Error('No new files from ' + src);
            }

            // if combining hash in file name unluckily collides with
            // another file, give up
            toCopy.forEach(function testExists(absPath) {
                if (grunt.file.exists(absPath)) {
                    throw new Error('Generated file already exists: ' + absPath);
                }
            });

            // if we reached here, everything is ready for merge

            // save meta file
            grunt.file.write(destMeta, JSON.stringify(files));

            // copy new files
            toCopy.forEach(function copyFile(mapping) {
                grunt.file.copy(mapping.src, mapping.dest);
            });
        }
    };
<commit_msg>chore(labeled-merge): convert merge to Promise<commit_after>var grunt = require('grunt'),
    Promise = require('core-js/library/es6/promise'),
    glob = require('glob'),
    getFileHash = require('./file-hash'),
    getDirLabel = require('./dir-label'),
    hashPath = require('./hash-path'),
    join = require('path').join;

var META_DIR = '.meta',
    LIST_FILE = 'files.json';

module.exports = {
    merge: function(dest, src, options) {
        'use strict';
        return new Promise( function mergePromise(resolve, reject) {
            var getHash = options.getHash || getFileHash,
                getLabel = options.getLabel || getDirLabel,
                getFileId = options.getFileIf || hashPath;

            // verify that dest and src are folders
            if (!grunt.file.isDir(dest)) {
                reject(new Error('Invalid dest folder'));
            }
            if (!grunt.file.isDir(src)) {
                reject(new Error('Invalid src folder'));
            }

            // get folder label
            var label = getLabel(src);
            if (typeof label !== 'string') {
                reject(new Error('Invalid label'));
            }

            // right now there is no support for merging folders
            // with meta info
            var srcMeta = join(src, META_DIR, LIST_FILE);
            if (grunt.file.isDir(srcMeta)) {
                reject(new Error('Meta folder in ' + src));
            }

            // test if meta is available
            var destMeta = join(dest, META_DIR, LIST_FILE);
            var files = {};
            if (grunt.file.isDir(destMeta)) {
                files = grunt.file.readJSON(destMeta);
            } else {
                grunt.file.mkdir(join(dest, META_DIR));
            }

            // label must not already have been added
            if (files.labels.indexOf(label) !== -1) {
                reject(new Error('Label already indexed'));
            }

            // get file list
            var srcFiles = glob.sync('**', {
                cwd: src,
                dot: true,
                nodir: true
            });

            // add files to meta index, marking them for copy when needed
            var toCopy = [];
            files.labels.push(label);
            srcFiles.forEach(function addFile(relPath) {
                var absPath = join(src, relPath);
                getHash.then(function evalHash(hash) {
                    if (relPath in files) {
                        var hashMap = files[relPath];
                        if (hash in hashMap) {
                            // file with same hash already indexed, adding
                            // label to list
                            hashMap[hash].push(label);
                        } else {
                            // a new version of the file, add file and
                            // update hash list
                            hashMap[hash] = [label];
                            toCopy.push({
                                src: absPath,
                                dest: getFileId(absPath, hash)
                            });
                        }
                    } else {
                        // file never indexed, add file and update
                        // hash list
                        files[relPath] = {};
                        files[relPath][hash] = [label];
                        toCopy.push({
                            src: absPath,
                            dest: getFileId(absPath, hash)
                        });
                    }
                });
            });

            // right now, folders that don't provide new files
            // are not welcome
            if (!toCopy.length) {
                reject(new Error('No new files from ' + src));
            }

            // if combining hash in file name unluckily collides with
            // another file, give up
            toCopy.forEach(function testExists(absPath) {
                if (grunt.file.exists(absPath)) {
                    reject(new Error('Generated file already exists: ' + absPath));
                }
            });

            // if we reached here, everything is ready for merge

            // save meta file
            grunt.file.write(destMeta, JSON.stringify(files));

            // copy new files
            toCopy.forEach(function copyFile(mapping) {
                grunt.file.copy(mapping.src, mapping.dest);
            });

        resolve();
        });
    }
};
<|endoftext|>


<commit_before>angular.module("noteApp")
    .factory("localService", ["$q", function($q) {
        "use strict";
        /* category's data structure

            1. category: {
                id: uuid,
                name: string,
                contains: [noteIDs]
            }

            2. categoris: [categoryIDs]

        */

        /* note's data structure

            1. note: {
                id: uuid,
                title: string,
                content: string,
                created: time,
                modified: time
            }

        */
        var ID = "poplark-angular-note-storage";
        var storage = {
            __load: function(key) {
                var result = {
                    status: 200,
                    data: null
                }
                var item = localStorage.getItem(key);
                if(!item) {
                    result.status = 404;
                } else {
                    try {
                        result.data = JSON.parse(item);
                    } catch(err) {
                        localStorage.removeItem(key);
                        result.status = 500;
                    }
                }
                return result;
            },
            __save: function(item, key) {
                var result = {
                    status: 200,
                    data: null
                }
                if(key) {
                    localStorage.setItem(key, JSON.stringify(item));
                    result.data = item;
                } else if(item.id) {
                    item.modified = Date.now();
                    localStorage.setItem(item.id, JSON.stringify(item));
                    result.data = item;
                } else {
                    item.id = UUID.generate();
                    item.created = item.modified = Date.now();
                    localStorage.setItem(item.id, JSON.stringify(item));
                    result.data = item;
                }
                return result;
            },
            queryAllCategories: function() {
                var result = {
                    status: 200,
                    data: null
                }
                var deferred = $q.defer();

                var loadedResult = this.__load(ID);
                if(404 === loadedResult.status || 500 === loadedResult.status) {
                    localStorage.setItem(ID, '[]');
                    result.data = [];
                    deferred.resolve(result);
                } else {
                    result.data = loadedResult.data;
                    deferred.resolve(result);
                }
                return deferred.promise;
            },
            addCategory: function() {
            },
            deleteCategory: function() {
            },
            queryCategory: function() {
            },
            updateCategory: function() {
            },
            queryAllNotes: function(category) {
                var deferred = $q.defer();
                var result = {
                    status: 200,
                    data: [{
                            'title': '1. Nexus S',
                            'content': 'Fast just got faster with Nexus S.'
                        }, {
                            'title': '2. Motorola XOOM™ with Wi-Fi',
                            'content': 'The Next, Next Generation tablet.'
                        }, {
                            'title': '3. MOTOROLA XOOM™',
                            'content': 'The Next, Next Generation tablet.'
                        }]
                }
                deferred.resolve(result);
                return deferred.promise;
            },
            addNote: function() {
            },
            deleteNote: function(){
            },
            queryNote: function() {
            },
            updateNote: function() {
            }
        }
        return storage;
    }]).factory("remoteService", ["$http", function($http) {
        // todo
    }]);
<commit_msg>addCategory<commit_after>angular.module("noteApp")
    .factory("localService", ["$q", function($q) {
        "use strict";
        /* category's data structure

            1. category: {
                id: uuid,
                title: string,
                contains: [noteIDs],
                created: time,
                modified: time
            }

            2. categoris: [categoryIDs]

        */

        /* note's data structure

            1. note: {
                id: uuid,
                title: string,
                content: string,
                created: time,
                modified: time
            }

        */
        var ID = "poplark-angular-note-storage";
        var storage = {
            __load: function(key) {
                var result = {
                    status: 200,
                    data: null
                }
                var item = localStorage.getItem(key);
                if(!item) {
                    result.status = 404;
                } else {
                    try {
                        result.data = JSON.parse(item);
                    } catch(err) {
                        localStorage.removeItem(key);
                        result.status = 500;
                    }
                }
                return result;
            },
            __save: function(item, key) {
                var result = {
                    status: 200,
                    data: null
                }
                if(key) {
                    localStorage.setItem(key, JSON.stringify(item));
                    result.data = item;
                } else if(item.id) {
                    item.modified = Date.now();
                    localStorage.setItem(item.id, JSON.stringify(item));
                    result.data = item;
                } else {
                    item.id = UUID.generate();
                    item.created = item.modified = Date.now();
                    localStorage.setItem(item.id, JSON.stringify(item));
                    result.data = item;
                }
                return result;
            },
            queryAllCategories: function() {
                var that = this;
                var result = {
                    status: 200,
                    data: null
                }
                var deferred = $q.defer();

                var loadedResult = that.__load(ID);
                if(404 === loadedResult.status || 500 === loadedResult.status) {
                    localStorage.setItem(ID, '[]');
                    result.data = [];
                    deferred.reject(result);
                } else {
                    result.data = loadedResult.data;
                    deferred.resolve(result);
                }
                return deferred.promise;
            },
            addCategory: function(category) {
                // category: {title, contains}
                var that = this;
                var result = {
                    status: 200,
                    data: null
                }
                var deferred = $q.defer();
                // validate - title is a none-empty string and contains is an empty Array
                // todo more validation
                if(("string" !== typeof category.title) || !category.title || !(category.contains instanceof Array) || 0 !== category.contains.length) {
                    result.status = 400;
                    deferred.reject(result);
                } else {
                    var savedResult = that.__save(category);
                    if(200 === savedResult.status) {
                        result.data = savedResult.data;
                        deferred.resolve(result);
                    } else {
                        result.status = 500;
                        deferred.reject(result);
                    }
                }
                return deferred.promise;
            },
            deleteCategory: function() {
            },
            queryCategory: function() {
            },
            updateCategory: function() {
            },
            queryAllNotes: function(category) {
                var deferred = $q.defer();
                var result = {
                    status: 200,
                    data: [{
                            'title': '1. Nexus S',
                            'content': 'Fast just got faster with Nexus S.'
                        }, {
                            'title': '2. Motorola XOOM™ with Wi-Fi',
                            'content': 'The Next, Next Generation tablet.'
                        }, {
                            'title': '3. MOTOROLA XOOM™',
                            'content': 'The Next, Next Generation tablet.'
                        }]
                }
                deferred.resolve(result);
                return deferred.promise;
            },
            addNote: function() {
            },
            deleteNote: function(){
            },
            queryNote: function() {
            },
            updateNote: function() {
            }
        }
        return storage;
    }]).factory("remoteService", ["$http", function($http) {
        // todo
    }]);
<|endoftext|>