<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/download/';
      $(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/2.0.3/Das-Keyboard-Q-x64-Setup-2.0.3.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/2.0.3/Das-Keyboard-Q-ia32-Setup-2.0.3.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/2.0.3/DasKeyboardQ-2.0.3-beta.pkg");
    $('#software-download-button').append(" 64 bit");
    $('#software-version-number').append("-beta");
    $('#software-version-number').append(" Mac");
    return;
  }

  $('#software-version-number').append(" Windows");

}

/**
 * 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);
  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");
      break;
    case 'X50QPID':
      $('#firmware-download-button').attr("href", "https://s3-us-west-2.amazonaws.com/q-desktop/DasKeyboard+X50+-+Firmware+Updater+-+57.0.0.exe");
      $('#firmware-download-button').text("Download X50Q firmware installer");
      break;
    default:
      $('#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");
      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>changed dynamic firmare version number<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/download/';
      $(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/2.0.3/Das-Keyboard-Q-x64-Setup-2.0.3.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/2.0.3/Das-Keyboard-Q-ia32-Setup-2.0.3.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/2.0.3/DasKeyboardQ-2.0.3-beta.pkg");
    $('#software-download-button').append(" 64 bit");
    $('#software-version-number').append("-beta");
    $('#software-version-number').append(" Mac");
    return;
  }

  $('#software-version-number').append(" Windows");

}

/**
 * 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);
  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-desktop/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;
    default:
      $('#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;
  }
}

$(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>// The default path used by the Grunfile
var path = '';

// Set by /public_html/jadu/assets/js/config.js
if (window.jadu.requireJsPath) {
    path = window.jadu.requireJsPath;
}

requirejs.config({
    paths: {
        'actions-menu'      : path + '/js/actions-menu',
        'bootstrap-tour'    : path + '/libs/bootstrap-tour/build/js/bootstrap-tour.min',
        'choice-matrix'     : path + '/js/choice-matrix',
        'console-js'        : path + '/libs/console-js/console',
        'codemirror'        : path + '/libs/codemirror/lib/codemirror',
        'dashboard'         : path + '/js/dashboard',
        'data-ui'           : path + '/js/data-ui',
        'datagrid'          : path + '/js/datagrid',
        'daterange'         : path + '/libs/bootstrap-daterangepicker/daterangepicker',
        'deck'              : path + '/js/deck',
        'dropdown'          : path + '/js/dropdown',
        'flash'             : path + '/js/flash',
        'highcharts'        : path + '/libs/highcharts/highcharts',
        'highcharts-more'   : path + '/libs/highcharts/highcharts-more',
        'highcharts-mono'   : path + '/js/highcharts-mono',
        'highcharts-theme'  : path + '/js/highcharts-theme',
        'highlightjs'       : path + '/libs/highlightjs/highlight.pack',
        'homepages'         : path + '/js/homepages',
        'jquery'            : path + '/libs/jquery/dist/jquery.min',
        'jquery-ui'         : path + '/libs/jqueryui/js/jquery-ui-1.10.4.custom.min',
        'jquery-ui-touch'   : path + '/libs/jqueryui-touch-punch/jquery.ui.touch-punch.min',
        'jquery-mousewheel' : path + '/libs/jquery-mousewheel/jquery.mousewheel',
        'jquery-placeholder': path + '/libs/jquery-placeholder/jquery.placeholder',
        'matchMedia'        : path + '/libs/matchMedia/matchMedia',
        'modal'             : path + '/js/modal',
        'moment'            : path + '/libs/moment/moment',
        'navigation'        : path + '/js/navigation',
        'order'             : path + '/libs/order/index',
        'pikaday'           : path + '/libs/pikaday/pikaday',
        'popover'           : path + '/js/popover',
        'pulsar'            : path + '/js/pulsar',
        'quantum'           : path + '/js/quantum',
        'sticky'            : path + '/libs/sticky/jquery.sticky',
        'store-js'          : path + '/libs/store.js/store',
        'summernote'        : path + '/libs/summernote/dist/summernote.min',
        'tab'               : path + '/js/tab',
        'tooltip'           : path + '/js/tooltip',
        'tray'              : path + '/js/tray',
        'vague'             : path + '/libs/Vague.js/Vague',
        'zeroclipboard'     : path + '/libs/zeroclipboard/dist/ZeroClipboard.min'
    },
    shim: {
        'daterange': {
            deps: ['jquery', 'moment'],
            exports: 'daterange'
        },
        'highcharts': {
            deps: ['jquery']
        },
        'highcharts-more': {
            deps: ['jquery', 'highcharts']
        },
        'jquery-ui': {
            deps: ['jquery']
        },
        'pikaday': {
            deps: ['moment']
        }
    }
});

require([
    'console-js',
    'jquery',
    'dashboard',
    'data-ui',
    'deck',
    'dropdown',
    'flash',
    'homepages',
    'matchMedia',
    'modal',
    'navigation',
    'tab',
    'popover',
    'tooltip',
    'pulsar',
    'quantum'
], function($) {
    'use strict';
    // $();
});
<commit_msg>Fix matchMedia path<commit_after>// The default path used by the Grunfile
var path = '';

// Set by /public_html/jadu/assets/js/config.js
if (window.jadu.requireJsPath) {
    path = window.jadu.requireJsPath;
}

requirejs.config({
    paths: {
        'actions-menu'      : path + '/js/actions-menu',
        'bootstrap-tour'    : path + '/libs/bootstrap-tour/build/js/bootstrap-tour.min',
        'choice-matrix'     : path + '/js/choice-matrix',
        'console-js'        : path + '/libs/console-js/console',
        'codemirror'        : path + '/libs/codemirror/lib/codemirror',
        'dashboard'         : path + '/js/dashboard',
        'data-ui'           : path + '/js/data-ui',
        'datagrid'          : path + '/js/datagrid',
        'daterange'         : path + '/libs/bootstrap-daterangepicker/daterangepicker',
        'deck'              : path + '/js/deck',
        'dropdown'          : path + '/js/dropdown',
        'flash'             : path + '/js/flash',
        'highcharts'        : path + '/libs/highcharts/highcharts',
        'highcharts-more'   : path + '/libs/highcharts/highcharts-more',
        'highcharts-mono'   : path + '/js/highcharts-mono',
        'highcharts-theme'  : path + '/js/highcharts-theme',
        'highlightjs'       : path + '/libs/highlightjs/highlight.pack',
        'homepages'         : path + '/js/homepages',
        'jquery'            : path + '/libs/jquery/dist/jquery.min',
        'jquery-ui'         : path + '/libs/jqueryui/js/jquery-ui-1.10.4.custom.min',
        'jquery-ui-touch'   : path + '/libs/jqueryui-touch-punch/jquery.ui.touch-punch.min',
        'jquery-mousewheel' : path + '/libs/jquery-mousewheel/jquery.mousewheel',
        'jquery-placeholder': path + '/libs/jquery-placeholder/jquery.placeholder',
        'matchMedia'        : path + '/js/polyfills/matchMedia',
        'modal'             : path + '/js/modal',
        'moment'            : path + '/libs/moment/moment',
        'navigation'        : path + '/js/navigation',
        'order'             : path + '/libs/order/index',
        'pikaday'           : path + '/libs/pikaday/pikaday',
        'popover'           : path + '/js/popover',
        'pulsar'            : path + '/js/pulsar',
        'quantum'           : path + '/js/quantum',
        'sticky'            : path + '/libs/sticky/jquery.sticky',
        'store-js'          : path + '/libs/store.js/store',
        'summernote'        : path + '/libs/summernote/dist/summernote.min',
        'tab'               : path + '/js/tab',
        'tooltip'           : path + '/js/tooltip',
        'tray'              : path + '/js/tray',
        'vague'             : path + '/libs/Vague.js/Vague',
        'zeroclipboard'     : path + '/libs/zeroclipboard/dist/ZeroClipboard.min'
    },
    shim: {
        'daterange': {
            deps: ['jquery', 'moment'],
            exports: 'daterange'
        },
        'highcharts': {
            deps: ['jquery']
        },
        'highcharts-more': {
            deps: ['jquery', 'highcharts']
        },
        'jquery-ui': {
            deps: ['jquery']
        },
        'pikaday': {
            deps: ['moment']
        }
    }
});

require([
    'console-js',
    'jquery',
    'dashboard',
    'data-ui',
    'deck',
    'dropdown',
    'flash',
    'homepages',
    'matchMedia',
    'modal',
    'navigation',
    'tab',
    'popover',
    'tooltip',
    'pulsar',
    'quantum'
], function($) {
    'use strict';
    // $();
});
<|endoftext|>


<commit_before>'use strict';

// Declare app level module which has no dependencies.
// AngjularJS is a client side javascript MVC.
angular.module('mainApp', [])
    .controller('main', function($scope) {

        $scope.objectTypes = [];
        $scope.objectTypes.push({name: 'Cube'},{name: 'Sphere'});
        $scope.selectedObjectType = 'Cube';

        $scope.objects = [];
        $scope.objects.push({id:-1, name: 'Select an Object', data: {}});
        $scope.objectCounter = 0;

        $scope.raycaster = new THREE.Raycaster();
        $scope.projector = new THREE.Projector();
        $scope.mouse = new THREE.Vector2()

        // This is the main init of the ThreeJS library.  It sets up the scene / camera and adds the objects
        $scope.initCanvas = function() {

            var camera, scene, renderer, controls;
            var mesh;

            // This project is going to be using WebGL so this requests a WebGLRenderer
            renderer = new THREE.WebGLRenderer();

            // Hard codes the size of the div containing the ThreeJS drawing area.  Later versions will scale with window sizing
            renderer.setSize( 1070, 500 );

            // Get the Div element from the HTML
            var mainDiv = $('#mainDrawLocation');

            // Add the domElement that the WebGLRendered has created.
            mainDiv.append(renderer.domElement);

            // This creates a camera that is controlled by the user
            //camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
            camera = new THREE.PerspectiveCamera( 70, 1070 / 500, 1, 3000 );
            $scope.nearString = 1;
            $scope.farString = 3000;
            camera.position.set( 0, 1000, 1000 );
            camera.lookAt( new THREE.Vector3( 0,0, 0 ) );

            // Set the depth where the camera starts. This can be changed with the user control zoom level
            //camera.position.z = 400;

            // This creates a Scene.  ThreeJS has a specific concept of a Scene which is a container for all things
            // in the viewable space.  Later meshes / camera will be added to the scene.
            scene = new THREE.Scene();

            var grid = new THREE.GridHelper( 600, 30 );
            scene.add(grid);

            var light = new THREE.DirectionalLight( 0xffffff, 2 );
            light.position.set( 1, 1, 1 );

            scene.add(light);

            // Use scene and the camera to render what is viewable by the user.
            renderer.render(scene, camera);

            // This is just doing some heavy lifting with making the scene / camera / rendered which are all local
            // variables accessiable on the scope to other functions.
            $scope.scene = scene;
            $scope.camera = camera;
            $scope.renderer = renderer;

//            controls = new THREE.OrbitControls( camera );
//            controls.addEventListener( 'change', $scope.renderer );

        }

        // There is a checkbox enabled within the HTML which controls if the sphere on the left automatically
        // rotates.  Just defaulting to true.
        $scope.rotate = true;
        $scope.animate = function() {

            // This is setting up a looping callback.  What that means is there is a recursive set of
            // callbacks that will get called so that the drawing continuously updates without blocking
            requestAnimationFrame( animate );

            // Regardless of if the user initialized rotation or the automatic rotation occurred go ahead and render again
            // If nothing has changed this is an idempotent call.
            $scope.renderer.render( $scope.scene, $scope.camera );

        }

        // The requestAnimationFrame is expecting to recursively call a function called animation. This is hard coded
        // into ThreeJS.  Since I'm using AngularJS to reduce scope to more local methods I have to expose the animation
        // function to global scope so that requestAnimationFrame will work.
        var animate = $scope.animate;

        // All the functions that have been defined are called later. They are just setting up what can be called.
        // This actually starts the whole process.
        $scope.initCanvas();

        // Start calling the animation cycle.  In order for the recurvie call to work you must call it at least once so that
        // it becomes a cycle.
        $scope.animate();

        $scope.$watch('camera.position.x', function(newValue) {
            if (angular.isDefined(newValue) && $scope.lookAt000 === true)
                $scope.camera.lookAt( new THREE.Vector3( 0,0, 0 ) );
        })
        $scope.$watch('camera.position.y', function(newValue) {
            if (angular.isDefined(newValue) && $scope.lookAt000 === true)
                $scope.camera.lookAt( new THREE.Vector3( 0,0, 0 ) );
        })
        $scope.$watch('camera.position.z', function(newValue) {
            if (angular.isDefined(newValue) && $scope.lookAt000 === true)
                $scope.camera.lookAt( new THREE.Vector3( 0,0, 0 ) );
        })

//        $scope.$watch('camera.near', function(newValue){
//            if (angular.isDefined(newValue)) {
//                $scope.camera.near =
//                $scope.camera.updateProjectionMatrix();
//            }
//        })
        $scope.$watch('fovString', function(newValue) {
            if (angular.isDefined(newValue)) {
                $scope.camera.fov = parseFloat(newValue);
                $scope.camera.updateProjectionMatrix();
            }
        })

        $scope.$watch('nearString', function(newValue) {
            if (angular.isDefined(newValue)) {
                $scope.camera.near = parseFloat(newValue);
                $scope.camera.updateProjectionMatrix();
            }
        })

        $scope.$watch('farString', function(newValue) {
            if (angular.isDefined(newValue)) {
                $scope.camera.far = parseFloat(newValue);
                $scope.camera.updateProjectionMatrix();
            }
        })

        $scope.$watch('camera.aspect', function(newValue) {
            if (angular.isDefined(newValue))
                $scope.camera.updateProjectionMatrix();
        })

        $scope.addObject = function() {
            if ($scope.selectedObjectType == 'Cube')
                $scope.addCube();
            else if ($scope.selectedObjectType == 'Sphere')
                $scope.addSphere();
        }

        $scope.addCube = function() {
            var geometry = new THREE.CubeGeometry( $scope.xValue, $scope.yValue, $scope.zValue );

//            for ( var i = 0; i < geometry.faces.length; i += 2 ) {
//
//                var hex = Math.random() * 0xffffff;
//                geometry.faces[ i ].color.setHex( hex );
//                geometry.faces[ i + 1 ].color.setHex( hex );
//
//            }
//
            var material = new THREE.MeshBasicMaterial( { color: 'red'} );
//
            var cube = new THREE.Mesh( geometry, material );
            cube.position.y = 150;
            cube.geometry.dynamic = true
            $scope.scene.add( cube );
            $scope.objects.push({id: $scope.objectCounter, name: 'Cube', data: cube});
            $scope.objectCounter++;

        }

        $scope.addSphere = function() {

            // create a new mesh with sphere geometry -
            var sphereGeometry = new THREE.SphereGeometry($scope.radius, $scope.segments, $scope.rings);
            var material = new THREE.MeshBasicMaterial({color: 'blue'});
            var sphere = new THREE.Mesh(sphereGeometry, material);
            sphere.geometry.dynamic = true;
            $scope.scene.add(sphere);
            $scope.objects.push({id:$scope.objectCounter, name: 'Sphere', data: sphere});
            $scope.objectCounter++;
        }

        $scope.$watch('selectedObject', function(newValue) {
            if (!angular.isDefined(newValue))
                return;

            angular.forEach($scope.objects, function(localObject) {
                if (localObject.id == newValue)
                    $scope.editableObject = localObject.data;
                    $scope.editableObjectId = newValue;
            })
        })

        $scope.test = function(event) {

            var divElement = event.currentTarget;
            var rect = divElement.getBoundingClientRect();

            $scope.mouse.x = ( (event.clientX - rect.left)/ 1070 ) * 2 - 1;
            $scope.mouse.y = - ( (event.clientY - rect.top)/ 500) * 2 + 1;

            console.log("X: " + $scope.mouse.x + " Y: " + $scope.mouse.y);
            var vector = new THREE.Vector3( $scope.mouse.x, $scope.mouse.y, 0.5 );
            $scope.projector.unprojectVector( vector, $scope.camera );

            $scope.raycaster.set( $scope.camera.position, vector.sub($scope.camera.position ).normalize() );

            var intersects = $scope.raycaster.intersectObjects( $scope.scene.children );
            if (intersects.length > 0){
                console.log('I have found it!!!!' + new Date().getTime());
                $scope.editableObject = intersects[0];
            }

        }

//        $scope.logPosition = function(event) {
//            var divElement = event.currentTarget;
//            var rect = divElement.getBoundingClientRect();
//
//            var x = ( (event.clientX - rect.left)/ 1070 ) * 2 - 1;
//            var y = - ( (event.clientY - rect.top)/ 500) * 2 + 1;
//            console.log ('event.clientX: ' + event.clientX + "        event.clientY: " + event.clientY);
//            console.log ('x: ' + x + "        y: " + y);
//        }

    })

;

<commit_msg>Trying to get the object picker working<commit_after>'use strict';

// Declare app level module which has no dependencies.
// AngjularJS is a client side javascript MVC.
angular.module('mainApp', [])
    .controller('main', function($scope) {

        $scope.objectTypes = [];
        $scope.objectTypes.push({name: 'Cube'},{name: 'Sphere'});
        $scope.selectedObjectType = 'Cube';

        $scope.objects = [];
        $scope.objects.push({id:-1, name: 'Select an Object', data: {}});
        $scope.objectCounter = 0;

        $scope.raycaster = new THREE.Raycaster();
        $scope.projector = new THREE.Projector();
        $scope.mouse = new THREE.Vector2()

        $scope.cameraRepresentation = {};

        // This is the main init of the ThreeJS library.  It sets up the scene / camera and adds the objects
        $scope.initCanvas = function() {

            var camera, scene, renderer, controls;
            var mesh;

            // This project is going to be using WebGL so this requests a WebGLRenderer
            renderer = new THREE.WebGLRenderer();

            // Hard codes the size of the div containing the ThreeJS drawing area.  Later versions will scale with window sizing
            renderer.setSize( 1070, 500 );

            // Get the Div element from the HTML
            var mainDiv = $('#mainDrawLocation');

            // Add the domElement that the WebGLRendered has created.
            mainDiv.append(renderer.domElement);

            // This creates a camera that is controlled by the user
            //camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
            camera = new THREE.PerspectiveCamera( 70, 1070 / 500, 1, 10000 );
            $scope.nearString = 1;
            $scope.farString = 3000;
            camera.position.set( 0, 1000, 100 );
            camera.lookAt( new THREE.Vector3( 0,0, 0 ) );

            // Set the depth where the camera starts. This can be changed with the user control zoom level
            //camera.position.z = 400;

            // This creates a Scene.  ThreeJS has a specific concept of a Scene which is a container for all things
            // in the viewable space.  Later meshes / camera will be added to the scene.
            scene = new THREE.Scene();

            var grid = new THREE.GridHelper( 600, 30 );
            scene.add(grid);

            var light = new THREE.DirectionalLight( 0xffffff, 2 );
            light.position.set( 1, 1, 1 );

            scene.add(light);

            // Use scene and the camera to render what is viewable by the user.
            renderer.render(scene, camera);

            // This is just doing some heavy lifting with making the scene / camera / rendered which are all local
            // variables accessiable on the scope to other functions.
            $scope.scene = scene;
            $scope.camera = camera;
            $scope.renderer = renderer;

//            controls = new THREE.OrbitControls( camera );
//            controls.addEventListener( 'change', $scope.renderer );

        }

        // There is a checkbox enabled within the HTML which controls if the sphere on the left automatically
        // rotates.  Just defaulting to true.
        $scope.rotate = true;
        $scope.animate = function() {

            // This is setting up a looping callback.  What that means is there is a recursive set of
            // callbacks that will get called so that the drawing continuously updates without blocking
            requestAnimationFrame( animate );

            // Regardless of if the user initialized rotation or the automatic rotation occurred go ahead and render again
            // If nothing has changed this is an idempotent call.
            $scope.renderer.render( $scope.scene, $scope.camera );

        }

        // The requestAnimationFrame is expecting to recursively call a function called animation. This is hard coded
        // into ThreeJS.  Since I'm using AngularJS to reduce scope to more local methods I have to expose the animation
        // function to global scope so that requestAnimationFrame will work.
        var animate = $scope.animate;

        // All the functions that have been defined are called later. They are just setting up what can be called.
        // This actually starts the whole process.
        $scope.initCanvas();

        // Start calling the animation cycle.  In order for the recurvie call to work you must call it at least once so that
        // it becomes a cycle.
        $scope.animate();

        $scope.$watch('camera.position.x', function(newValue) {
            if (angular.isDefined(newValue) && $scope.lookAt000 === true)
                $scope.camera.lookAt( new THREE.Vector3( 0,0, 0 ) );

            $scope.camera.updateProjectionMatrix();
        })
        $scope.$watch('camera.position.y', function(newValue) {
            if (angular.isDefined(newValue) && $scope.lookAt000 === true)
                $scope.camera.lookAt( new THREE.Vector3( 0,0, 0 ) );

            $scope.camera.updateProjectionMatrix();
        })
        $scope.$watch('camera.position.z', function(newValue) {
            if (angular.isDefined(newValue) && $scope.lookAt000 === true)
                $scope.camera.lookAt( new THREE.Vector3( 0,0, 0 ) );

            $scope.camera.updateProjectionMatrix();
        })

//        $scope.$watch('camera.near', function(newValue){
//            if (angular.isDefined(newValue)) {
//                $scope.camera.near =
//                $scope.camera.updateProjectionMatrix();
//            }
//        })
        $scope.$watch('fovString', function(newValue) {
            if (angular.isDefined(newValue)) {
                $scope.camera.fov = parseFloat(newValue);
                $scope.camera.updateProjectionMatrix();
            }
        })

        $scope.$watch('nearString', function(newValue) {
            if (angular.isDefined(newValue)) {
                $scope.camera.near = parseFloat(newValue);
                $scope.camera.updateProjectionMatrix();
            }
        })

        $scope.$watch('farString', function(newValue) {
            if (angular.isDefined(newValue)) {
                $scope.camera.far = parseFloat(newValue);
                $scope.camera.updateProjectionMatrix();
            }
        })

        $scope.$watch('camera.aspect', function(newValue) {
            if (angular.isDefined(newValue))
                $scope.camera.updateProjectionMatrix();
        })

        $scope.addObject = function() {
            if ($scope.selectedObjectType == 'Cube')
                $scope.addCube();
            else if ($scope.selectedObjectType == 'Sphere')
                $scope.addSphere();
        }

        $scope.addCube = function() {
            var geometry = new THREE.CubeGeometry( $scope.xValue, $scope.yValue, $scope.zValue );

//            for ( var i = 0; i < geometry.faces.length; i += 2 ) {
//
//                var hex = Math.random() * 0xffffff;
//                geometry.faces[ i ].color.setHex( hex );
//                geometry.faces[ i + 1 ].color.setHex( hex );
//
//            }
//
            var material = new THREE.MeshBasicMaterial( { color: 'red'} );
//
            var cube = new THREE.Mesh( geometry, material );
            cube.position.y = 150;
            cube.geometry.dynamic = true
            $scope.scene.add( cube );
            $scope.objects.push({id: $scope.objectCounter, name: 'Cube', data: cube});
            $scope.objectCounter++;

        }

        $scope.addSphere = function() {

            // create a new mesh with sphere geometry -
            var sphereGeometry = new THREE.SphereGeometry($scope.radius, $scope.segments, $scope.rings);
            var material = new THREE.MeshBasicMaterial({color: 'blue'});
            var sphere = new THREE.Mesh(sphereGeometry, material);
            sphere.geometry.dynamic = true;
            $scope.scene.add(sphere);
            $scope.objects.push({id:$scope.objectCounter, name: 'Sphere', data: sphere});
            $scope.objectCounter++;
        }

        $scope.$watch('selectedObject', function(newValue) {
            if (!angular.isDefined(newValue))
                return;

            angular.forEach($scope.objects, function(localObject) {
                if (localObject.id == newValue)
                    $scope.editableObject = localObject.data;
                    $scope.editableObjectId = newValue;
            })
        })

        $scope.test = function(event) {

            var divElement = event.currentTarget;
            var rect = divElement.getBoundingClientRect();

            $scope.mouse.x = ( (event.clientX - rect.left)/ 1070 ) * 2 - 1;
            $scope.mouse.y = - ( (event.clientY - rect.top)/ 500) * 2 + 1;

            console.log("X: " + $scope.mouse.x + " Y: " + $scope.mouse.y);
            var vector = new THREE.Vector3( $scope.mouse.x, $scope.mouse.y, 0.5 );
            $scope.camera.updateProjectionMatrix();
            $scope.projector.unprojectVector( vector, $scope.camera );

            $scope.raycaster.set( $scope.camera.position, vector.sub($scope.camera.position ).normalize() );

            var intersects = $scope.raycaster.intersectObjects( $scope.scene.children );
            if (intersects.length > 0){
                console.log('I have found it!!!!' + new Date().getTime());
                $scope.editableObject = intersects[0];
            }

        }

        $scope.logPosition = function(event) {
            var divElement = event.currentTarget;
            var rect = divElement.getBoundingClientRect();

            $scope.mouse.x = ( (event.clientX - rect.left - 20)/ 1070 ) * 2 - 1;
            $scope.mouse.y = - ( (event.clientY - rect.top)/ 500) * 2 + 1;

            console.log("X: " + $scope.mouse.x + " Y: " + $scope.mouse.y);
            var vector = new THREE.Vector3( $scope.mouse.x, $scope.mouse.y, 0.5 );
            $scope.projector.unprojectVector( vector, $scope.camera );
            var vector = new THREE.Vector3($scope.camera.position.x)
            $scope.raycaster.set($scope.cleanVector($scope.camera.position), vector.sub(cleanVector($scope.camera.position) ).normalize() );

            var intersects = $scope.raycaster.intersectObjects( $scope.scene.children );
            if (intersects.length > 0){
                angular.forEach(intersects, function(intersect) {
                    if (intersect.object.type != 1){
                        console.log('I have found it!!!!' + new Date().getTime());

                        $scope.editableObject = intersects[0].object;
                        $scope.editableObject.material.color =  new THREE.Color( "blue");

                    }
                })

            }
            else {
                if (angular.isDefined($scope.editableObject))
                    $scope.editableObject.material.color =  new THREE.Color("red");
            }

            console.log($scope.camera.position)
        }

        $scope.cleanVector = function(vector) {
            return new THREE.Vector3(parseInt(vector.x), parseInt(vector.y), parseInt(vector.z));
        }

    })

;

<|endoftext|>


<commit_before>

var inAnimation = false;
var currentLocation = 1;
var seq1Start = 1;
var seq1Finish = 121;
var seq2Start = 122;
var seq2Finish = 242;
var seq3Start = 243;
var seq3Finish = 362;
var seq4Start = 363;
var seq4Finish = 482;
var seq5Start = 483;
var seq5Finish = 546;
var seq6Start = 547;
var seq6Finish = 656;
var seq7Start = 657;
var seq7Finish = 777;
var seq8Start = 778;
var seq8Finish = 869;
var seq9Start = 870;
var seq9Finish = 1019;
// var refreshIntervalId = null;

//Hide Main Content
//content.hide
   $( '.canvas_wrapper' ).hide();
//perload images
  var totalImages = 1019; // Wow, so many images for such a short clip
  var images = new Array();
  for(var i = 1; i <= totalImages; i++) {
    var filename = '/ducerodsGIT/rod-jpg/rod_' + ('000' + i).slice(-4) + '.jpg'; // Filename of each image
    var img = new Image;
    if ( i == 500) {
      img.onload = function() {
        setTimeout(function(){
          $( '.loader' ).fadeOut(150);
          $( '.canvas_wrapper' ).delay(550).fadeIn();
          rodIntro();
        }, 4000);
      };
    }
    img.src = filename;
    images.push(img);
  }
//Setup canv
var canv = document.getElementById('background');
// Redefine canvas size on browser resize
$( window ).resize(function(event) {
  setCanvasSize();
});
//Set Canvas Size
function setCanvasSize(){
  $windowWidth = $(window).width();
  $windowHeight = $(window).height();
  $(canv)
      .width($windowWidth)
      .height($windowWidth / 1.95);
}
//Set Initial Canvas Size
setCanvasSize();
//Rod animate through images
function rodIntro() {
  var refreshIntervalId = setInterval(function(){
    context.clearRect(0, 0, canv.width, canv.height);
    setImage(currentLocation);
  	currentLocation = currentLocation + 1;
  	// console.log(currentLocation);
  	if(currentLocation == '121'){
    	// console.log('here');
      $( '#content' ).fadeIn();
      $( '.load_1' ).fadeIn(700);
      $( '.load_2' ).delay(1000).fadeIn(700);
      $( '.load_3' ).delay(2500).fadeIn(700);
    	clearInterval(refreshIntervalId);
  	}
  },35);
}

function getNextStop(currLocation, direction) {
  // if scroll is up
  if(direction == 1) {
    if(seq1Start <= currLocation <= seq1Finish)
      return false;
    else if(seq2Start <= currLocation <= seq2Finish)
      return seq1Finish;
    else if(seq3Start <= currLocation <= seq3Finish)
      return seq2Finish;
    else if(seq4Start <= currLocation <= seq4Finish)
      return seq3Finish;
    else if(seq5Start <= currLocation <= seq5Finish)
      return seq4Finish;
    else if(seq6Start <= currLocation <= seq6Finish)
      return seq5Finish;
    else if(seq7Start <= currLocation <= seq7Finish)
      return seq6Finish;
    else if(seq8Start <= currLocation <= seq8Finish)
      return seq7Finish;
    else if(seq9Start <= currLocation <= seq9Finish)
      return seq8Finish;
    else
      return false;
  }
  // if scoll is down
  else {
    if(seq1Start <= currLocation <= seq1Finish)
      return seq2Finish;
    else if(seq2Start <= currLocation <= seq2Finish)
      return seq3Finish;
    else if(seq3Start <= currLocation <= seq3Finish)
      return seq4Finish;
    else if(seq4Start <= currLocation <= seq4Finish)
      return seq5Finish;
    else if(seq5Start <= currLocation <= seq5Finish)
      return seq6Finish;
    else if(seq6Start <= currLocation <= seq6Finish)
      return seq7Finish;
    else if(seq7Start <= currLocation <= seq7Finish)
      return seq8Finish;
    else if(seq8Start <= currLocation <= seq8Finish)
      return seq9Finish;
    else if(seq9Start <= currLocation <= seq9Finish)
      return false;
    else
      return false;
  }
}

function animateFrames(start, finish){
  console.log(currentLocation + '=' + finish);
  var refreshIntervalId = setInterval(function(){

    // clear the previous photo
    context.clearRect(0, 0, canv.width, canv.height);
    // draw next photo
    setImage(currentLocation);
    // add 1 to current location
    currentLocation = currentLocation + 1;
    console.log(currentLocation + '=' + finish);
    // stop when current location equals finish
    if(currentLocation >= finish){
      clearInterval(refreshIntervalId);
      inAnimation = false;
    }
  },35);
};

window.addEventListener('mousewheel', function(e) {
  console.log('inside scroll function');
  if(inAnimation == false) {
    console.log('inside animation');
    inAnimation = true;
    e.preventDefault(); // No scroll

    // The following equation will return either a 1 for scroll down
    // or -1 for a scroll up
    var delta = Math.max(-1, Math.min(1, e.wheelDelta));
    console.log(delta);

    // find the next stopping piont frame based on the current
    // location and scroll direction
    var nextStop = getNextStop(currentLocation, delta);
    console.log(nextStop);
    // animate frames
    if(nextStop != false) {
      animateFrames(currentLocation, nextStop);
    }
  }
});

var context = canv.getContext('2d');

// See above for where this gets called
function setImage(newLocation) {
  // drawImage takes 5 arguments: image, x, y, width, height
  context.drawImage(images[newLocation], 0, 0, 1280, 720);
}

var currentMousePos = false;
/*
window.addEventListener('mousemove', function(e) {
  currentMousePos = e.x;
  currentLocation = Math.floor(
    (images.length / $(window).width()) *
    currentMousePos
  );
  context.clearRect(0, 0, canv.width, canv.height);
  setImage(currentLocation);

});
*/

        <commit_msg>Finish animation<commit_after>//Initiate Variables

var inAnimation = false;
var currentLocation = 1;

var totalImages = 1019;
var images = new Array();

var seqStart = [0, 1, 122,243,363,483,547,657,778,870];
var seqFinish = [0,121,242,362,482,546,656,777,869,1019];

// Setup canv
var canv = document.getElementById('background');
var context = canv.getContext('2d');

// -------------------------
// Defind Function
// -------------------------

// Set Canvas size based on browser width
function setCanvasSize(){
  $windowWidth = $(window).width();
  $windowHeight = $(window).height();
  $(canv)
      .width($windowWidth)
      .height($windowWidth / 1.95);
}

//Rod Introduction animate through images
function rodIntro() {
  var refreshIntervalId = setInterval(function(){
    context.clearRect(0, 0, canv.width, canv.height);
    setImage(currentLocation);
    currentLocation = currentLocation + 1;
    // console.log(currentLocation);
    if(currentLocation == '121'){
      // console.log('here');
      $( '#content' ).fadeIn();
      $( '.load_1' ).fadeIn(700);
      $( '.load_2' ).delay(1000).fadeIn(700);
      $( '.load_3' ).delay(2500).fadeIn(700);
      clearInterval(refreshIntervalId);
    }
  },35);
}

// Get Next Sequence
function getNextStop(currLocation, direction) {

    // Find which current sequence we are in by looping
    // through start and finish frames
    for(var index = 1; index < seqStart.length; ++index){
      console.log('GNS Index: '+ index);
      // If the current location is in between the start and finish frame
      // return the next frame end
      console.log(parseInt(seqStart[index]) + ' <= ' + parseInt(currLocation) + ' <= ' + parseInt(seqFinish[index]));
      if(seqStart[index].valueOf() <= currLocation.valueOf() &&  currLocation.valueOf() <= seqFinish[index].valueOf()) {
        console.log('SeqFound: ' + index);
        // if scroll is up
        if(direction == 1){

          if(index ==1){
            //Return false if index is 1
            return false;
          } else {
            //Return previous sequence finish to animate back too
            return seqFinish[index-1];
          }

        } else {

          if(index >= seqStart.length -1){
            //Return false if index is last frame
            return false;
          } else {
            //Return previous sequence finish to animate back too
            return seqFinish[index+1];
          }

        }

      }
    }
    //Return false if currentlLocation is out of bounds
    return false;
}

// Animate Frames from Start to Finish
function animateFrames(start, finish, direction){
  console.log(currentLocation + '=' + finish);
  var refreshIntervalId = setInterval(function(){

    // clear the previous photo
    context.clearRect(0, 0, canv.width, canv.height);
    // draw next photo
    setImage(currentLocation);
    // add or subtract 1 to current location
    // 1 for scroll down or -1 for a scroll up
    if(direction == 1){
      currentLocation = currentLocation - 1;
      if(parseInt(currentLocation) < parseInt(finish)){
        clearInterval(refreshIntervalId);
        inAnimation = false;
      }
    } else {
      currentLocation = currentLocation + 1;
      if(parseInt(currentLocation) >= parseInt(finish)){
        clearInterval(refreshIntervalId);
        inAnimation = false;
      }
    }

    console.log(currentLocation, direction);
    console.log(currentLocation + '=' + finish);
    // stop when current location equals finish

  },35);
};

// Draws the current image
function setImage(newLocation) {
  // drawImage takes 5 arguments: image, x, y, width, height
  context.drawImage(images[newLocation], 0, 0, 1280, 720);
}

// --------------------------
// Load Sequence
// --------------------------

//Hide Main Content
$( '.canvas_wrapper' ).hide();

//perload images
for(var i = 1; i <= totalImages; i++) {
  var filename = '/ducerodsGIT/rod-jpg/rod_' + ('000' + i).slice(-4) + '.jpg'; // Filename of each image
  var img = new Image;
  if ( i == 500) {
    img.onload = function() {
      setTimeout(function(){
        $( '.loader' ).fadeOut(150);
        $( '.canvas_wrapper' ).delay(550).fadeIn();
        rodIntro();
      }, 4000);
    };
  }
  img.src = filename;
  images.push(img);
}

// Redefine canvas size on browser resize
$( window ).resize(function(event) {
  setCanvasSize();
});

// Set Initial Canvas Size
setCanvasSize();

// Add Event Listener to mousewheel
window.addEventListener('mousewheel', function(e) {
  if(inAnimation == false) {
    inAnimation = true;
    e.preventDefault(); // No scroll

    // The following equation will return either a 1 for scroll down
    // or -1 for a scroll up
    var delta = Math.max(-1, Math.min(1, e.wheelDelta));

    // find the next stopping piont frame based on the current
    // location and scroll direction
    var nextStop = getNextStop(currentLocation, delta);
    console.log('Nextstop: '+ nextStop);
    // animate frames
    if(nextStop != false) {
      animateFrames(currentLocation, nextStop, delta);
    } else {
      inAnimation = false;
    }
  }
});

/*var currentMousePos = false;

window.addEventListener('mousemove', function(e) {
  currentMousePos = e.x;
  currentLocation = Math.floor(
    (images.length / $(window).width()) *
    currentMousePos
  );
  context.clearRect(0, 0, canv.width, canv.height);
  setImage(currentLocation);

});
*/

        <|endoftext|>


<commit_before>var model = {};

// Get browser width and height...
model.browserWidth = 200; //window.innerWidth;
model.browserHeight = 200; //window.innerHeight;

// Draw a box for the game area...
var gameArea = document.createElement("div");
gameArea.setAttribute('style', "position: absolute; top: 0; left: 0; width: " + model.browserWidth + "px; height: " + model.browserHeight + "px; background-color; red; border: 1px solid black;");

document.body.appendChild(gameArea);
<commit_msg>Created basic game area, mouse and time boxes and event handlers.<commit_after>var model = {};

// Get browser width and height...
model.browserWidth = window.innerWidth - 20;
model.browserHeight = (window.innerHeight / 2 ) - 20;
model.gameStarted = false;

// Draw a DIV for the game area...
var gameArea = document.createElement("div");
gameArea.setAttribute('style', "position: absolute; top: 10px; left: 10px; width: " + model.browserWidth + "px; height: " + model.browserHeight + "px; background-color: #FFFFFF; border: 1px solid black;");
gameArea.addEventListener('click', gameAreaClickHandler);
gameArea.addEventListener('mousemove', gameAreaMouseMoveHandler);

var loadInterval = window.setInterval(function () {
    gameArea.style.backgroundColor = (generateRandomNumber(0, 2) === 0 ? 'blue' : 'red');
}, 100);

document.body.appendChild(gameArea);

var timeLapseTextMessage = document.createElement("span");
timeLapseTextMessage.style.position = 'absolute';
timeLapseTextMessage.style.top = '5px';
timeLapseTextMessage.style.left = '10px';
timeLapseTextMessage.style.color = '#FFFFFF';
timeLapseTextMessage.style.fontFamily = 'Courier New';
timeLapseTextMessage.style.fontSize = '18px';
timeLapseTextMessage.innerText = "Time: 0 ms";

var mousePointTextMessage = document.createElement("span");
mousePointTextMessage.style.position = 'absolute';
mousePointTextMessage.style.top = '5px';
mousePointTextMessage.style.right = '10px';
mousePointTextMessage.style.color = '#FFFFFF';
mousePointTextMessage.style.fontFamily = 'Courier New';
mousePointTextMessage.style.fontSize = '18px';
mousePointTextMessage.innerText = "Mouse: 0000,0000";

gameArea.appendChild(mousePointTextMessage);
gameArea.appendChild(timeLapseTextMessage);

// Randomly pick a cv:Point
model.cvPoint = {
    'x': generateRandomNumber(1, model.browserWidth),
    'y': generateRandomNumber(1, model.browserHeight)
};

console.log(model.cvPoint);

function generateRandomNumber(fromAndIncluding, upToAndExcluding) {
    return Math.floor(Math.random() * (upToAndExcluding + fromAndIncluding) + fromAndIncluding)
}

function startGame() {
    model.startTime = new Date();
    model.gameStarted = true;
    model.timerUpdate = setInterval(timerUpdateChangeHandler, 100);
}

function endGame() {
    model.gameStarted = false;
    window.clearInterval(model.timerUpdate);
    model.endTime = new Date();
    updateTime(model.endTime);
}

function updateTime(timeNow) {
    var timeLapse = timeNow - model.startTime;

    timeLapseTextMessage.innerText = "Time: " + timeLapse + " ms";
}

function gameAreaClickHandler(evt) {
    if ( !model.gameStarted ) {
        startGame(); //  At the moment, start game when you click.
        window.clearInterval(loadInterval);
    }
    else {
        endGame();
    }
}

function gameAreaMouseMoveHandler(evt) {
    mousePointTextMessage.innerText = "Mouse: " + evt.offsetX + ", " + evt.offsetY;
}

function timerUpdateChangeHandler(evt) {
    updateTime(new Date());
}
<|endoftext|>


<commit_before>var map;
function initialize() {
  var mapOptions = {
    zoom: 10,
    center: new google.maps.LatLng(34.399, -77.755),
    scaleControl: true,
    zoomControl: true,
    zoomControlOptions: {
        style: google.maps.ZoomControlStyle.SMALL,
        position: google.maps.ControlPosition.RIGHT_TOP
    },
    panControl: false,
    streetViewControl: true,
    streetViewControlOptions: {
    	position: google.maps.ControlPosition.RIGHT_TOP
    }
  };

  google.maps.visualRefresh=true;
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  // Load a GeoJSON from the same server as our demo.
  var jsonData = "data/ncVacationData.json";
  map.data.loadGeoJson(jsonData);

  // Add some style
  map.data.setStyle(function(feature) {
    var color = feature.getProperty("Color");
    if(color == "blue"){
      return{
        setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png')
      }
    },
    if(color == "blueviolet"){
      return{
        setIcon('http://maps.google.com/mapfiles/ms/icons/purple-dot.png')
    }

  });

  var infoWindow = new google.maps.InfoWindow({
    pixelOffset: new google.maps.Size(0,-25),
  });

  // Set mouseover event for each feature.
  map.data.addListener('click', function(event) {
    fam = event.feature.getProperty("Family");
    name = event.feature.getProperty("Name");
    address = event.feature.getProperty("Address");
    city = event.feature.getProperty("City");
    phone = event.feature.getProperty("Phone");
    web = event.feature.getProperty("Website");

    content = "" + name + "" + "
" + address + "
" + city + "
" + phone + "
" + "Website";

    infoWindow.setContent(content);

    var anchor = new google.maps.MVCObject();
	anchor.set("position",event.latLng);
	infoWindow.open(map,anchor);
  });

}
// Load google map
google.maps.event.addDomListener(window, 'load', initialize);
// resize google map on screen change
google.maps.event.addDomListener(window, "resize", function() {
 var center = map.getCenter();
 google.maps.event.trigger(map, "resize");
 map.setCenter(center);
});
<commit_msg>Update main.js<commit_after>var map;
function initialize() {
  var mapOptions = {
    zoom: 10,
    center: new google.maps.LatLng(34.399, -77.755),
    scaleControl: true,
    zoomControl: true,
    zoomControlOptions: {
        style: google.maps.ZoomControlStyle.SMALL,
        position: google.maps.ControlPosition.RIGHT_TOP
    },
    panControl: false,
    streetViewControl: true,
    streetViewControlOptions: {
    	position: google.maps.ControlPosition.RIGHT_TOP
    }
  };

  google.maps.visualRefresh=true;
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  // Load a GeoJSON from the same server as our demo.
  var jsonData = "data/ncVacationData.json";
  map.data.loadGeoJson(jsonData);

  // Add some style
  map.data.setStyle(function(feature) {
    var color = feature.getProperty("Color");
    if(color == "blue"){
      return{
        icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
      }
    },
    if(color == "blueviolet"){
      return{
        icon: 'http://maps.google.com/mapfiles/ms/icons/purple-dot.png'
    }

  });

  var infoWindow = new google.maps.InfoWindow({
    pixelOffset: new google.maps.Size(0,-25),
  });

  // Set mouseover event for each feature.
  map.data.addListener('click', function(event) {
    fam = event.feature.getProperty("Family");
    name = event.feature.getProperty("Name");
    address = event.feature.getProperty("Address");
    city = event.feature.getProperty("City");
    phone = event.feature.getProperty("Phone");
    web = event.feature.getProperty("Website");

    content = "" + name + "" + "
" + address + "
" + city + "
" + phone + "
" + "Website";

    infoWindow.setContent(content);

    var anchor = new google.maps.MVCObject();
	anchor.set("position",event.latLng);
	infoWindow.open(map,anchor);
  });

}
// Load google map
google.maps.event.addDomListener(window, 'load', initialize);
// resize google map on screen change
google.maps.event.addDomListener(window, "resize", function() {
 var center = map.getCenter();
 google.maps.event.trigger(map, "resize");
 map.setCenter(center);
});
<|endoftext|>


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

   });
   $('#formThing').submit(function(event){
      event.preventDefault();
      getData();
   });
});
function getData(){
    $.get('https://beam.pro/api/v1/channels/' + $('#inputText').val(), "", function(data){
         var Avatar = "https://beam.pro/api/v1/users/" + data['user']['id'] + "/avatar";
         var Username = data['user']['username'];
         var Followers = data['numFollowers'];
         var Partnered = data['partnered'];
         var Tetris = data['interactive'];
         var Audience = data['audience'];
         var Experience = data['user']['experience'];
         var lvls = data['user']['level'];
         var Sparks = data['user']['sparks'];
         var ChannelID = data['user']['id'];
         var HostID = data['hosteeId'];
         var Tetrisid = data['tetrisGameId'];
         var Coverid = data['coverId'];
         var Thumbnail = data['thumbnailId'];
         var StreamMute = data['preferences']['channel:player:muteOwn'];
         var FollowNotify = data['preferences']['channel:notify:follow'];
         var SubscribeNotify = data['preferences']['channel:notify:subscribe'];
         var TweetNotify = data['preferences']['channel:tweet:enabled'];
         var TotalViews = data['viewersTotal'];
         var te = data['transcodingEnabled'];
         var Online = data['online'];
         if(data['type'] != null){
            var lastPlayed = data['type']['name'];
         }else{
            var lastPlayed = "None";
         }
         var joined = data['createdAt'];

         var html = '';

         html += '
' + Username + '
';
         html += '
----------'
          html += '
Url Link: Beam.pro/'+ Username +'';
         html += '
Followers: ' + Followers+ '';
         html += '
Partnered: ' + Partnered +'';
         html += '
Total Views: ' + TotalViews +'';
         html += '
---Points---'
         html += '
Level: ' + lvls +'';
         html += '
Experience: ' + Experience +'';
         html += '
Sparks: ' + Sparks +'';
         html += '
---ID---'
         html += '
Tetris Game ID: ' + Tetrisid+ '';
         html += '
Host ID: ' + HostID+ '';
         html += '
Channel ID: ' + ChannelID+ '';
         html += '
Cover ID: ' + Coverid+ '';
         html += '
Thumbnail ID: ' + Thumbnail+ '';
         html += '
---Preference---'
         html += '
interactive:' + Tetris +'';
         html += '
Audience:' + Audience +'';
         html += '
SelfStreamMute:' + StreamMute +'';
         html += '
BeamBot FollowNotify:' + FollowNotify +'';
         html += '
BeamBot SubNotify:' + SubscribeNotify +'';
         html += '
TweetNotify:' + TweetNotify +'';
         html += '
Transcoding:' + te +'';
         html += '
------------'
         html += "
";
         if(Online){
             html += '
Online';
         }else{
             html += '
Offline';
         }
         html+= '
Last Played:'+lastPlayed+'';
         html += '
Joined on: '+joined+' '.replace('T', ' at ');
         $('.profile').html(html);
      }).fail(function(data){
            html = '
A Beam user with that name does not exist.';
             $('.profile').html(html);
            return;
      });;
}
<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://beam.pro/api/v1/channels/' + $('#inputText').val(), "", function(data){
         var Avatar = "https://beam.pro/api/v1/users/" + data['user']['id'] + "/avatar";
         var Username = data['user']['username'];
         var Followers = data['numFollowers'];
         var Partnered = data['partnered'];
         var Tetris = data['interactive'];
         var Audience = data['audience'];
         var Experience = data['user']['experience'];
         var lvls = data['user']['level'];
         var Sparks = data['user']['sparks'];
         var ChannelID = data['user']['id'];
         var HostID = data['hosteeId'];
         var Tetrisid = data['tetrisGameId'];
         var Coverid = data['coverId'];
         var Thumbnail = data['thumbnailId'];
         var StreamMute = data['preferences']['channel:player:muteOwn'];
         var FollowNotify = data['preferences']['channel:notify:follow'];
         var SubscribeNotify = data['preferences']['channel:notify:subscribe'];
         var TweetNotify = data['preferences']['channel:tweet:enabled'];
         var TotalViews = data['viewersTotal'];
         var te = data['transcodingEnabled'];
         var Online = data['online'];
         if(data['type'] != null){
            var lastPlayed = data['type']['name'];
         }else{
            var lastPlayed = "None";
         }
         if(HostID = null){
            var HostID = null;
         }else{
            var HostID = "None";
         }
         var joined = data['createdAt'];

         var html = '';

         html += '
' + Username + '
';
         html += '
----------'
          html += '
Url Link: Beam.pro/'+ Username +'';
         html += '
Followers: ' + Followers+ '';
         html += '
Partnered: ' + Partnered +'';
         html += '
Total Views: ' + TotalViews +'';
         html += '
---Points---'
         html += '
Level: ' + lvls +'';
         html += '
Experience: ' + Experience +'';
         html += '
Sparks: ' + Sparks +'';
         html += '
---ID---'
         html += '
Tetris Game ID: ' + Tetrisid+ '';
         html += '
Host ID: ' + HostID+ '';
         html += '
Channel ID: ' + ChannelID+ '';
         html += '
Cover ID: ' + Coverid+ '';
         html += '
Thumbnail ID: ' + Thumbnail+ '';
         html += '
---Preference---'
         html += '
interactive:' + Tetris +'';
         html += '
Audience:' + Audience +'';
         html += '
SelfStreamMute:' + StreamMute +'';
         html += '
BeamBot FollowNotify:' + FollowNotify +'';
         html += '
BeamBot SubNotify:' + SubscribeNotify +'';
         html += '
TweetNotify:' + TweetNotify +'';
         html += '
Transcoding:' + te +'';
         html += '
------------'
         html += "
";
         if(Online){
             html += '
Online';
         }else{
             html += '
Offline';
         }
         html+= '
Last Played:'+lastPlayed+'';
         html += '
Joined on: '+joined+' '.replace('T', ' at ');
         $('.profile').html(html);
      }).fail(function(data){
            html = '
A Beam user with that name does not exist.';
             $('.profile').html(html);
            return;
      });;
}
<|endoftext|>


<commit_before>//
//    File: mgmt.js
//
//Revision:2014090401
//
//

//
// NOTE: jQuery is required
//

// Common ----------------------------------------------------------------
function before_send(id) {
	// show ajax sending indicator
	$(id).css({"display": "block"});
} // before_send

function on_complete(id) {
	// hide ajax sending indicator
	$(id).css({"display": "none"});
} // on_complete

// Roles -----------------------------------------------------------------
function edit_role() {
	console.log("edit role...");
} // edit_role

function modify_role() {
	console.log("modify role...");
} // edit_role

function edit_perm() {
	console.log("edit perm...");
} // edit_perm

function modify_perm() {
	console.log("modify perm...");
} // edit_perm

function add_new_role() {
    var new_role = encodeURIComponent( $('#new_role').val() );
    var new_role_descr = encodeURIComponent( $('#new_role_descr').val() );

    $.ajax({
        url:"./api/add_role.php?json=1&title="+new_role+"&descr="+new_role_descr,
        dataType: "json",
        beforeSend:before_send("#add_new_role_is_sending"),
        complete:on_complete("#add_new_role_is_sending"),
        success: function (response) {
		var obj = response;

		console.log("new added\nid: " + obj.ID + "\ntitle: " + obj.Title + "\ndescr: " + obj.Description);
		$('#role_msg').html("new added
id: " + obj.ID + "
title: " + obj.Title + "
descr: " + obj.Description);

		// update selection menu of rols
		var old_options = $('#rname').html();
		var new_options = old_options
			+ "<option value='"
			+ obj.ID
			+ "'>"
			+ obj.Title
			+ "("
			+ obj.Description
			+ ")"
			+ "</option>";

		$('#rname').html(new_options);
		$('#new_role').val("");
		$('#new_role_descr').val("");
		$('#rname').attr("size", $('#rname').children('option').length+1);
	},
        error: function (xhr) {
		console.log("AJAX request error (add_new_role)");
		$('#role_msg').html("AJAX request error (add_new_role)");
	}
    });
} // add_new_role

function add_new_role_path() {
    var new_role_path = encodeURIComponent( $('#new_role_path').val() );
    var new_role_path_descr = encodeURIComponent( $('#new_role_path_descr').val() );

    $.ajax({
        url:"./api/add_role_path.php?json=1&path="+new_role_path+"&descr="+new_role_path_descr,
        dataType: "json",
        beforeSend:before_send("#add_new_role_path_is_sending"),
        complete:on_complete("#add_new_role_path_is_sending"),
        success: function (response) {
		var obj = response;

		console.log("Result: " + obj.Result + "\n" + "Msg: " + obj.Msg);
		$('#role_msg').html("Result: " + obj.Result + "
" + "Msg: " + obj.Msg);
		if( obj.Result == "OK." ) {
			// update select menu of roles
			var new_options = "<option value='-1'>-- Role Name --</option>";
			var opt_cnt = 0;

			for(var r_key in obj.List) {
				opt_cnt++;
				new_options = new_options
					+ "<option value='"
					+ obj.List[r_key].ID
					+ "'>"
					+ obj.List[r_key].Title
					+ "("
					+ obj.List[r_key].Description
					+ ")"
					+ "</option>";
			}
			$('#rname').html(new_options);
			$('#new_role_path').val("");
			$('#new_role_path_descr').val("");
			$('#rname').attr("size", opt_cnt+1);
		}
	},
        error: function (xhr) {
		console.log("AJAX request error (add_new_role_path)");
		$('#role_msg').html("AJAX request error (add_new_role_path)");
	}
    });
} // add_new_role_path

function role_selected() {
	var r_id = $('#rname').find(":selected").val();

	if( r_id < 0 ) return;		// invalid value, ignore them and return

	var r_title_and_descr = $('#rname').find(":selected").html().match(/^(.+)\((.+)\)$/);
	var r_title = r_title_and_descr[1], r_descr = r_title_and_descr[2];

	console.log("role id: " + r_id + ", title: " + r_title + ", descr: " + r_descr[2] + " has been selected.");

	// update r_*_for_edit
	$('#r_id_for_edit').html(r_id);
	$('#r_title_for_edit').val(r_title);
	$('#r_descr_for_edit').val(r_descr);
} // role_selected

function remove_role(r_id) {
	$.ajax({
	        url:"./api/remove_role.php?json=1&r_id="+r_id,
	        dataType: "json",
	        beforeSend:before_send("#delete_role_is_sending"),
	        complete:on_complete("#delete_role_is_sending"),
	        success: function (response) {
			var obj = response;

			console.log("Result: " + obj.Result);
			$('#role_msg').html("Result: " + obj.Result);
			if( obj.Result == "OK." ) {
				// update select menu of roles
				var new_options = "<option value='-1'>-- Role Name --</option>";
				var opt_cnt = 0;

				for(var r_key in obj.List) {
					opt_cnt++;
					new_options = new_options
						+ "<option value='"
						+ obj.List[r_key].ID
						+ "'>"
						+ obj.List[r_key].Title
						+ "("
						+ obj.List[r_key].Description
						+ ")"
						+ "</option>";
				}
				$('#rname').html(new_options);
				$('#rname').attr("size", opt_cnt+1);
			}
		},
	        error: function (xhr) {
			console.log("AJAX request error (remove_role)");
			$('#role_msg').html("AJAX request error (remove_role)");
		}
	    });
} // remove_role

function delete_role() {
	var role_id = $('#rname').find(":selected").val();
	var role_title_and_descr = $('#rname').find(":selected").text();

	if( confirm("Are you sure to delete role id " + role_id + ": " + role_title_and_descr) ) {
		remove_role(role_id);
	}
	else {
		console.log("Canceled.");
		$('#role_msg').html("Canceled.");
	}
} // delete_role

// Permissions -------------------------------------------------------------------------------------------
function add_new_perm() {
    var new_perm = encodeURIComponent( $('#new_perm').val() );
    var new_perm_descr = encodeURIComponent( $('#new_perm_descr').val() );

    $.ajax({
        url:"./api/add_perm.php?json=1&title="+new_perm+"&descr="+new_perm_descr,
        dataType: "json",
        beforeSend:before_send("#add_new_perm_is_sending"),
        complete:on_complete("#add_new_perm_is_sending"),
        success: function (response) {
		var obj = response;

		console.log("new added\nid: " + obj.ID + "\ntitle: " + obj.Title + "\ndescr: " + obj.Description);
		$('#perm_msg').html("new added
id: " + obj.ID + "
title: " + obj.Title + "
descr: " + obj.Description);

		// update selection menu of rols
		var old_options = $('#pname').html();
		var new_options = old_options
			+ "<option value='"
			+ obj.ID
			+ "'>"
			+ obj.Title
			+ "("
			+ obj.Description
			+ ")"
			+ "</option>";

		$('#pname').html(new_options);
		$('#new_perm').val("");
		$('#new_perm_descr').val("");
		$('#pname').attr("size", $('#pname').children('option').length+1);
	},
        error: function (xhr) {
		console.log("AJAX request error (add_new_perm)");
		$('#perm_msg').html("AJAX request error (add_new_perm)");
	}
    });
} // add_new_perm

function add_new_perm_path() {
    var new_perm_path = encodeURIComponent( $('#new_perm_path').val() );
    var new_perm_path_descr = encodeURIComponent( $('#new_perm_path_descr').val() );

    $.ajax({
        url:"./api/add_perm_path.php?json=1&path="+new_perm_path+"&descr="+new_perm_path_descr,
        dataType: "json",
        beforeSend:before_send("#add_new_perm_path_is_sending"),
        complete:on_complete("#add_new_perm_path_is_sending"),
        success: function (response) {
		var obj = response;

		console.log("Result: " + obj.Result + "\n" + "Msg: " + obj.Msg);
		$('#perm_msg').html("Result: " + obj.Result + "
" + "Msg: " + obj.Msg);
		if( obj.Result == "OK." ) {
			// update select menu of roles
			var new_options = "<option value='-1'>-- Perm Name --</option>";
			var opt_cnt = 0;

			for(var p_key in obj.List) {
				opt_cnt++;
				new_options = new_options
					+ "<option value='"
					+ obj.List[p_key].ID
					+ "'>"
					+ obj.List[p_key].Title
					+ "("
					+ obj.List[p_key].Description
					+ ")"
					+ "</option>";
			}
			$('#pname').html(new_options);
			$('#new_perm_path').val("");
			$('#new_perm_path_descr').val("");
			$('#pname').attr("size", opt_cnt+1);
		}
	},
        error: function (xhr) {
		console.log("AJAX request error (add_new_perm_path)");
		$('#perm_msg').html("AJAX request error (add_new_perm_path)");
	}
    });
} // add_new_perm_path

function perm_selected() {
	var p_id = $('#pname').find(":selected").val();

	if( p_id < 0 ) return;		// invalid value, ignore them and return

	var p_title_and_descr = $('#pname').find(":selected").html().match(/^(.+)\((.+)\)$/);
	var p_title = p_title_and_descr[1], p_descr = p_title_and_descr[2];

	console.log("perm id: " + p_id + ", title: " + p_title + ", descr: " + p_descr[2] + " has been selected.");

	// update p_*_for_edit
	$('#p_id_for_edit').html(p_id);
	$('#p_title_for_edit').val(p_title);
	$('#p_descr_for_edit').val(p_descr);
} // perm_selected

function remove_perm(p_id) {
	$.ajax({
	        url:"./api/remove_perm.php?json=1&p_id="+p_id,
	        dataType: "json",
	        beforeSend:before_send("#delete_perm_is_sending"),
	        complete:on_complete("#delete_perm_is_sending"),
	        success: function (response) {
			var obj = response;

			console.log("Result: " + obj.Result);
			$('#perm_msg').html("Result: " + obj.Result);
			if( obj.Result == "OK." ) {
				// update select menu of roles
				var new_options = "<option value='-1'>-- Perm Name --</option>";
				var opt_cnt = 0;

				for(var p_key in obj.List) {
					opt_cnt++;
					new_options = new_options
						+ "<option value='"
						+ obj.List[p_key].ID
						+ "'>"
						+ obj.List[p_key].Title
						+ "("
						+ obj.List[p_key].Description
						+ ")"
						+ "</option>";
				}
				$('#pname').html(new_options);
				$('#pname').attr("size", opt_cnt+1);
			}
		},
	        error: function (xhr) {
			console.log("AJAX request error (remove_perm)");
			$('#perm_msg').html("AJAX request error (remove_perm)");
		}
	    });
} // remove_perm

function delete_perm() {
	var perm_id = $('#pname').find(":selected").val();
	var perm_title_and_descr = $('#pname').find(":selected").text();

	if( confirm("Are you sure to delete permission: " + perm_title_and_descr) ) {
		remove_perm(perm_id);
	}
	else {
		console.log("Canceled.");
		$('#perm_msg').html("Canceled.");
	}
} // delete_perm

<commit_msg>fine tunes to prevent from some ugly error<commit_after>//
//    File: mgmt.js
//
//Revision:2014090402
//
//

//
// NOTE: jQuery is required
//

// Common ----------------------------------------------------------------
function before_send(id) {
	// show ajax sending indicator
	$(id).css({"display": "block"});
} // before_send

function on_complete(id) {
	// hide ajax sending indicator
	$(id).css({"display": "none"});
} // on_complete

// Roles -----------------------------------------------------------------
function edit_role() {
	console.log("edit role...");
} // edit_role

function modify_role() {
	console.log("modify role...");
} // edit_role

function edit_perm() {
	console.log("edit perm...");
} // edit_perm

function modify_perm() {
	console.log("modify perm...");
} // edit_perm

function add_new_role() {
    var new_role = encodeURIComponent( $('#new_role').val() );
    var new_role_descr = encodeURIComponent( $('#new_role_descr').val() );

    $.ajax({
        url:"./api/add_role.php?json=1&title="+new_role+"&descr="+new_role_descr,
        dataType: "json",
        beforeSend:before_send("#add_new_role_is_sending"),
        complete:on_complete("#add_new_role_is_sending"),
        success: function (response) {
		var obj = response;

		console.log("new added\nid: " + obj.ID + "\ntitle: " + obj.Title + "\ndescr: " + obj.Description);
		$('#role_msg').html("new added
id: " + obj.ID + "
title: " + obj.Title + "
descr: " + obj.Description);

		// update selection menu of rols
		var old_options = $('#rname').html();
		var new_options = old_options
			+ "<option value='"
			+ obj.ID
			+ "'>"
			+ obj.Title
			+ "("
			+ obj.Description
			+ ")"
			+ "</option>";

		$('#rname').html(new_options);
		$('#new_role').val("");
		$('#new_role_descr').val("");
		$('#rname').attr("size", $('#rname').children('option').length+1);
	},
        error: function (xhr) {
		console.log("AJAX request error (add_new_role)");
		$('#role_msg').html("AJAX request error (add_new_role)");
	}
    });
} // add_new_role

function add_new_role_path() {
    var new_role_path = encodeURIComponent( $('#new_role_path').val() );
    var new_role_path_descr = encodeURIComponent( $('#new_role_path_descr').val() );

    $.ajax({
        url:"./api/add_role_path.php?json=1&path="+new_role_path+"&descr="+new_role_path_descr,
        dataType: "json",
        beforeSend:before_send("#add_new_role_path_is_sending"),
        complete:on_complete("#add_new_role_path_is_sending"),
        success: function (response) {
		var obj = response;

		console.log("Result: " + obj.Result + "\n" + "Msg: " + obj.Msg);
		$('#role_msg').html("Result: " + obj.Result + "
" + "Msg: " + obj.Msg);
		if( obj.Result == "OK." ) {
			// update select menu of roles
			var new_options = "<option value='-1'>-- Role Name --</option>";
			var opt_cnt = 0;

			for(var r_key in obj.List) {
				opt_cnt++;
				new_options = new_options
					+ "<option value='"
					+ obj.List[r_key].ID
					+ "'>"
					+ obj.List[r_key].Title
					+ "("
					+ obj.List[r_key].Description
					+ ")"
					+ "</option>";
			}
			$('#rname').html(new_options);
			$('#new_role_path').val("");
			$('#new_role_path_descr').val("");
			$('#rname').attr("size", opt_cnt+1);
		}
	},
        error: function (xhr) {
		console.log("AJAX request error (add_new_role_path)");
		$('#role_msg').html("AJAX request error (add_new_role_path)");
	}
    });
} // add_new_role_path

function role_selected() {
	var r_id = $('#rname').find(":selected").val();

	if( typeof r_id === 'undefined' || r_id < 0 ) return;		// invalid value, ignore them and return

	var r_title_and_descr = $('#rname').find(":selected").html().match(/^(.+)\((.+)\)$/);
	var r_title = r_title_and_descr[1], r_descr = r_title_and_descr[2];

	console.log("role id: " + r_id + ", title: " + r_title + ", descr: " + r_descr[2] + " has been selected.");

	// update r_*_for_edit
	$('#r_id_for_edit').html(r_id);
	$('#r_title_for_edit').val(r_title);
	$('#r_descr_for_edit').val(r_descr);
} // role_selected

function remove_role(r_id) {
	$.ajax({
	        url:"./api/remove_role.php?json=1&r_id="+r_id,
	        dataType: "json",
	        beforeSend:before_send("#delete_role_is_sending"),
	        complete:on_complete("#delete_role_is_sending"),
	        success: function (response) {
			var obj = response;

			console.log("Result: " + obj.Result);
			$('#role_msg').html("Result: " + obj.Result);
			if( obj.Result == "OK." ) {
				// update select menu of roles
				var new_options = "<option value='-1'>-- Role Name --</option>";
				var opt_cnt = 0;

				for(var r_key in obj.List) {
					opt_cnt++;
					new_options = new_options
						+ "<option value='"
						+ obj.List[r_key].ID
						+ "'>"
						+ obj.List[r_key].Title
						+ "("
						+ obj.List[r_key].Description
						+ ")"
						+ "</option>";
				}
				$('#rname').html(new_options);
				$('#rname').attr("size", opt_cnt+1);
			}
		},
	        error: function (xhr) {
			console.log("AJAX request error (remove_role)");
			$('#role_msg').html("AJAX request error (remove_role)");
		}
	    });
} // remove_role

function delete_role() {
	var role_id = $('#rname').find(":selected").val();
	var role_title_and_descr = $('#rname').find(":selected").text();

	if( confirm("Are you sure to delete role id " + role_id + ": " + role_title_and_descr) ) {
		remove_role(role_id);
	}
	else {
		console.log("Canceled.");
		$('#role_msg').html("Canceled.");
	}
} // delete_role

// Permissions -------------------------------------------------------------------------------------------
function add_new_perm() {
    var new_perm = encodeURIComponent( $('#new_perm').val() );
    var new_perm_descr = encodeURIComponent( $('#new_perm_descr').val() );

    $.ajax({
        url:"./api/add_perm.php?json=1&title="+new_perm+"&descr="+new_perm_descr,
        dataType: "json",
        beforeSend:before_send("#add_new_perm_is_sending"),
        complete:on_complete("#add_new_perm_is_sending"),
        success: function (response) {
		var obj = response;

		console.log("new added\nid: " + obj.ID + "\ntitle: " + obj.Title + "\ndescr: " + obj.Description);
		$('#perm_msg').html("new added
id: " + obj.ID + "
title: " + obj.Title + "
descr: " + obj.Description);

		// update selection menu of rols
		var old_options = $('#pname').html();
		var new_options = old_options
			+ "<option value='"
			+ obj.ID
			+ "'>"
			+ obj.Title
			+ "("
			+ obj.Description
			+ ")"
			+ "</option>";

		$('#pname').html(new_options);
		$('#new_perm').val("");
		$('#new_perm_descr').val("");
		$('#pname').attr("size", $('#pname').children('option').length+1);
	},
        error: function (xhr) {
		console.log("AJAX request error (add_new_perm)");
		$('#perm_msg').html("AJAX request error (add_new_perm)");
	}
    });
} // add_new_perm

function add_new_perm_path() {
    var new_perm_path = encodeURIComponent( $('#new_perm_path').val() );
    var new_perm_path_descr = encodeURIComponent( $('#new_perm_path_descr').val() );

    $.ajax({
        url:"./api/add_perm_path.php?json=1&path="+new_perm_path+"&descr="+new_perm_path_descr,
        dataType: "json",
        beforeSend:before_send("#add_new_perm_path_is_sending"),
        complete:on_complete("#add_new_perm_path_is_sending"),
        success: function (response) {
		var obj = response;

		console.log("Result: " + obj.Result + "\n" + "Msg: " + obj.Msg);
		$('#perm_msg').html("Result: " + obj.Result + "
" + "Msg: " + obj.Msg);
		if( obj.Result == "OK." ) {
			// update select menu of roles
			var new_options = "<option value='-1'>-- Perm Name --</option>";
			var opt_cnt = 0;

			for(var p_key in obj.List) {
				opt_cnt++;
				new_options = new_options
					+ "<option value='"
					+ obj.List[p_key].ID
					+ "'>"
					+ obj.List[p_key].Title
					+ "("
					+ obj.List[p_key].Description
					+ ")"
					+ "</option>";
			}
			$('#pname').html(new_options);
			$('#new_perm_path').val("");
			$('#new_perm_path_descr').val("");
			$('#pname').attr("size", opt_cnt+1);
		}
	},
        error: function (xhr) {
		console.log("AJAX request error (add_new_perm_path)");
		$('#perm_msg').html("AJAX request error (add_new_perm_path)");
	}
    });
} // add_new_perm_path

function perm_selected() {
	var p_id = $('#pname').find(":selected").val();

	if( typeof p_id === 'undefined' || p_id < 0 ) return;		// invalid value, ignore them and return

	var p_title_and_descr = $('#pname').find(":selected").html().match(/^(.+)\((.+)\)$/);
	var p_title = p_title_and_descr[1], p_descr = p_title_and_descr[2];

	console.log("perm id: " + p_id + ", title: " + p_title + ", descr: " + p_descr[2] + " has been selected.");

	// update p_*_for_edit
	$('#p_id_for_edit').html(p_id);
	$('#p_title_for_edit').val(p_title);
	$('#p_descr_for_edit').val(p_descr);
} // perm_selected

function remove_perm(p_id) {
	$.ajax({
	        url:"./api/remove_perm.php?json=1&p_id="+p_id,
	        dataType: "json",
	        beforeSend:before_send("#delete_perm_is_sending"),
	        complete:on_complete("#delete_perm_is_sending"),
	        success: function (response) {
			var obj = response;

			console.log("Result: " + obj.Result);
			$('#perm_msg').html("Result: " + obj.Result);
			if( obj.Result == "OK." ) {
				// update select menu of roles
				var new_options = "<option value='-1'>-- Perm Name --</option>";
				var opt_cnt = 0;

				for(var p_key in obj.List) {
					opt_cnt++;
					new_options = new_options
						+ "<option value='"
						+ obj.List[p_key].ID
						+ "'>"
						+ obj.List[p_key].Title
						+ "("
						+ obj.List[p_key].Description
						+ ")"
						+ "</option>";
				}
				$('#pname').html(new_options);
				$('#pname').attr("size", opt_cnt+1);
			}
		},
	        error: function (xhr) {
			console.log("AJAX request error (remove_perm)");
			$('#perm_msg').html("AJAX request error (remove_perm)");
		}
	    });
} // remove_perm

function delete_perm() {
	var perm_id = $('#pname').find(":selected").val();
	var perm_title_and_descr = $('#pname').find(":selected").text();

	if( confirm("Are you sure to delete permission: " + perm_title_and_descr) ) {
		remove_perm(perm_id);
	}
	else {
		console.log("Canceled.");
		$('#perm_msg').html("Canceled.");
	}
} // delete_perm

<|endoftext|>