<commit_before>(function() {
  'use strict';
  /*global require,phantom,console,setInterval,clearInterval */

  /**
   * Borrowed from https://github.com/ariya/phantomjs/blob/master/examples/waitfor.js
   *
   * Wait until the test condition is true or a timeout occurs. Useful for waiting
   * on a server response or for a ui change (fadeIn, etc.) to occur.
   *
   * @param testFx javascript condition that evaluates to a boolean,
   * it can be passed in as a string (e.g.: '1 == 1' or '$('#bar').is(':visible')' or
   * as a callback function.
   * @param onReady what to do when testFx condition is fulfilled,
   * it can be passed in as a string (e.g.: '1 == 1' or '$('#bar').is(':visible')' or
   * as a callback function.
   * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used.
   */
  function waitFor(testFx, onReady, timeOutMillis) {
    var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s
    start = new Date().getTime(),
    condition = false,
    interval = setInterval(function() {
      if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
        // If not time-out yet and condition not yet fulfilled
        condition = testFx(); //< defensive code
      } else {
        if(!condition) {
          // If condition still not fulfilled (timeout but condition is 'false')
          console.log('"waitFor()" timeout');
          phantom.exit(1);
        } else {
          // Condition fulfilled (timeout and/or condition is 'true')
          console.log('"waitFor()" finished in ' + (new Date().getTime() - start) + 'ms.');
          onReady(); //< Do what it's supposed to do once the condition is fulfilled
          clearInterval(interval); //< Stop this interval
        }
      }
    }, 10000); //< repeat check every 10s
  }

  var poster = require('webpage').create(),
  system = require('system'), fs = require('fs');

  var processedCount = 0;

  poster.onResourceError = function(resourceError) {
    console.log('Error submit data to ' + resourceError.url + ', error ' + resourceError.errorCode + ': ' + resourceError.errorString);
  };

  function postData(country, site, version, loadTime, failed, size) {
    var instance = country + '-' + site + '-' + version;
    var settings = {
      operation: 'POST',
      encoding: 'utf8',
      headers: {
        'Content-Type': 'application/json'
      },
      data: JSON.stringify({
        dims: {
          sonar: instance
        },
        increments: { failCount : failed ? 1 : 0, totalSize: size },
        gauges: { loadTime: loadTime}
      })
    };

    poster.open('http://pure-journey-3547.herokuapp.com/stats/' + instance, settings, function(postStatus) {
      console.log('Submit to statshub: ' + postStatus + ', data = ' + settings.data);
      processedCount = processedCount + 1;
    });
  }

  function process(country, site, url, version) {
    var page = require('webpage').create();
    var size = 0;

    page.onResourceError = function(resourceError) {
      console.log('Error load resource #' + resourceError.id + ', ' + resourceError.url + ', error ' + resourceError.errorCode + ': ' + resourceError.errorString);
      page.stop();
      processedCount = processedCount + 1;
    };
    page.onResourceReceived = function(response) {
      if (response.bodySize !== undefined) {
        size = size + response.bodySize;
      }
    };
    var started = Date.now();
    page.onLoadFinished = function (status) {
      var loadTime = Date.now() - started;
      console.log(site + ' (' + url + '): ' + status + ', takes ' + loadTime + 'ms, size = ' + size + ' bytes');
      postData(country, site, version, loadTime, status === 'fail', size);
    };
    page.open(url);
  }

  function main(version, sleepMinutes) {
    var content = fs.read('config.json');
    var config = JSON.parse(content);
    var country = config.country;
    if (country === undefined) {
      console.log('Please specify country in config');
      phantom.exit(1);
    }
    for (var i in config.sites) {
      process(country, config.sites[i][0], config.sites[i][1], version);
    }
    if (sleepMinutes > 0) {
      console.log('Sleep ' +  sleepMinutes + ' minutes before next round');
      setTimeout(function() {main(version, sleepMinutes); }, sleepMinutes*60*1000);
    } else {
      waitFor(function() {
        return processedCount === config.sites.length;
      }, function() { phantom.exit(); },
      4*60*1000); // wait for at most 4 min
    }

  }

  if (system.args.length < 2) {
    console.log('Usage: sonar.js <lantern version> [sleep minutes before next round]');
    phantom.exit(1);
  } else {
    var version = system.args[1];
    var sleepMinutes = 0;
    if (system.args.length === 3) {
      sleepMinutes = parseInt(system.args[2], 10);
    }

    main(version, sleepMinutes);
  }

}());
<commit_msg>post to influx<commit_after>(function() {
  'use strict';
  /*global require,phantom,console,setInterval,clearInterval */

  /**
   * Borrowed from https://github.com/ariya/phantomjs/blob/master/examples/waitfor.js
   *
   * Wait until the test condition is true or a timeout occurs. Useful for waiting
   * on a server response or for a ui change (fadeIn, etc.) to occur.
   *
   * @param testFx javascript condition that evaluates to a boolean,
   * it can be passed in as a string (e.g.: '1 == 1' or '$('#bar').is(':visible')' or
   * as a callback function.
   * @param onReady what to do when testFx condition is fulfilled,
   * it can be passed in as a string (e.g.: '1 == 1' or '$('#bar').is(':visible')' or
   * as a callback function.
   * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used.
   */
  function waitFor(testFx, onReady, timeOutMillis) {
    var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s
    start = new Date().getTime(),
    condition = false,
    interval = setInterval(function() {
      if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
        // If not time-out yet and condition not yet fulfilled
        condition = testFx(); //< defensive code
      } else {
        if(!condition) {
          // If condition still not fulfilled (timeout but condition is 'false')
          console.log('"waitFor()" timeout');
          phantom.exit(1);
        } else {
          // Condition fulfilled (timeout and/or condition is 'true')
          console.log('"waitFor()" finished in ' + (new Date().getTime() - start) + 'ms.');
          onReady(); //< Do what it's supposed to do once the condition is fulfilled
          clearInterval(interval); //< Stop this interval
        }
      }
    }, 10000); //< repeat check every 10s
  }

  var poster = require('webpage').create(),
  system = require('system'), fs = require('fs');

  var processedCount = 0;

  poster.onResourceError = function(resourceError) {
    console.log('Error submit data to ' + resourceError.url + ', error ' + resourceError.errorCode + ': ' + resourceError.errorString);
  };

  function post2Influx(country, site, version, loadTime, failed, size) {
    var settings = {
      operation: 'POST',
      encoding: 'utf8',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    };
    var ts = Date.now();
    var tags = 'country='+country+',site='+site+',version='+version;
    settings.data = 'load_time,'+tags+' value=' +loadTime +' ' + ts;
    poster.open('http://influx.getlantern.org:8086/write?db=sonar', settings, function(postStatus) {
      settings.data = 'fail_count,'+tags+' value=' + (failed?1:0) +' ' + ts;
      poster.open('http://influx.getlantern.org:8086/write?db=sonar', settings, function(postStatus) {
        settings.data = 'size,'+tags+' value=' + size +' ' + ts;
        poster.open('http://influx.getlantern.org:8086/write?db=sonar', settings, function(postStatus) {
        });
      });
    });
  }

  function postData(country, site, version, loadTime, failed, size) {
    var instance = country + '-' + site + '-' + version;
    var settings = {
      operation: 'POST',
      encoding: 'utf8',
      headers: {
        'Content-Type': 'application/json'
      },
      data: JSON.stringify({
        dims: {
          sonar: instance
        },
        increments: { failCount : failed ? 1 : 0, totalSize: size },
        gauges: { loadTime: loadTime}
      })
    };

    poster.open('http://pure-journey-3547.herokuapp.com/stats/' + instance, settings, function(postStatus) {
      console.log('Submit to statshub: ' + postStatus + ', data = ' + settings.data);
      processedCount = processedCount + 1;
      post2Influx(country, site, version, loadTime, failed, size);
    });
  }

  function process(country, site, url, version) {
    var page = require('webpage').create();
    var size = 0;

    page.onResourceError = function(resourceError) {
      console.log('Error load resource #' + resourceError.id + ', ' + resourceError.url + ', error ' + resourceError.errorCode + ': ' + resourceError.errorString);
      page.stop();
      processedCount = processedCount + 1;
    };
    page.onResourceReceived = function(response) {
      if (response.bodySize !== undefined) {
        size = size + response.bodySize;
      }
    };
    var started = Date.now();
    page.onLoadFinished = function (status) {
      var loadTime = Date.now() - started;
      console.log(site + ' (' + url + '): ' + status + ', takes ' + loadTime + 'ms, size = ' + size + ' bytes');
      postData(country, site, version, loadTime, status === 'fail', size);
    };
    page.open(url);
  }

  function main(version, sleepMinutes) {
    var content = fs.read('config.json');
    var config = JSON.parse(content);
    var country = config.country;
    if (country === undefined) {
      console.log('Please specify country in config');
      phantom.exit(1);
    }
    for (var i in config.sites) {
      process(country, config.sites[i][0], config.sites[i][1], version);
    }
    if (sleepMinutes > 0) {
      console.log('Sleep ' +  sleepMinutes + ' minutes before next round');
      setTimeout(function() {main(version, sleepMinutes); }, sleepMinutes*60*1000);
    } else {
      waitFor(function() {
        return processedCount === config.sites.length;
      }, function() { phantom.exit(); },
      4*60*1000); // wait for at most 4 min
    }

  }

  if (system.args.length < 2) {
    console.log('Usage: sonar.js <lantern version> [sleep minutes before next round]');
    phantom.exit(1);
  } else {
    var version = system.args[1];
    var sleepMinutes = 0;
    if (system.args.length === 3) {
      sleepMinutes = parseInt(system.args[2], 10);
    }

    main(version, sleepMinutes);
  }

}());
<|endoftext|>


<commit_before>import URLSearchParams from 'url-search-params';
import * as Axis from '../../node_modules/axis.js';
import {GITHUB_STATUS_STATES} from '../constants/constants';

export function getRepoById(repos, id){
  const repo = repos.find(repo => repo.id == id);

  if (repo){
    return repo;
  }else{
    return {};
  }
}

export function getBranchByName(branches, branchName){
  const branch = branches.find(branch => branch.name == branchName);

  if (branch){
    return branch;
  }else{
    return {};
  }
}

export function findCommitBySha(commits, sha){
  const commit = commits.find(commit => commit.sha == sha);

  if (commit){
    return commit;
  }else{
    return {};
  }
}

export function firstSevenOfSha(sha){
  return sha.slice(0, 7);
}

export function makeOptionsArrayFromStrings(stringArray){
  let optionsArray = stringArray.map(string => {
    return {
      value: string,
      text: string
    };
  });

  return optionsArray;
}

export function validateObjectExists(obj){
  let isValid = true;

  if(obj === null){
    isValid = false;
  }

  if(obj === undefined){
    isValid = false;
  }

  return isValid;
}

export function isEmpty(obj) {
  for(let key in obj) {
    if(obj.hasOwnProperty(key)) {
      return false;
    }
  }
  return true;
}

/**
 * Checks if input is a valid string
 *
 *  The input variable is valid if it is ALL of the following:
 *      1) variable is a string
 *      2) variable string length > 0
 *
 * @param inVar - input variable to check
 * @returns {boolean}
 */
export function isValidString(inVar){
  let isValid = false;

  if(Axis.isString(inVar)){
    if(inVar.length > 0){
      isValid = true;
    }
  }

  return isValid;
}

/**
 * Checks if a commit reference input value is valid.
 *
 * @param {String} ref - The commit reference input to be validated.
 * @returns {boolean} True if commit reference is valid, false otherwise.
 */
export function validateCommitReference(ref){
  // TODO: Improve validation of ref parameter input value
  let isRefParamValid = isValidString(ref);

  return isRefParamValid;
}

/**
 * Validates a GitHub status state input value against defined
 * constant values in the GITHUB_STATUS_STATES constant object.
 *
 * @param {String} statusState - The status state input to be validated.
 * @returns {boolean} True if statusState equals one of the constants defined in GITHUB_STATUS_STATES, false otherwise.
 */
export function validateGitHubStatusState(statusState){
  let isValid = false;

  for(let prop in GITHUB_STATUS_STATES){
    if(GITHUB_STATUS_STATES.hasOwnProperty(prop)){
      if(GITHUB_STATUS_STATES[prop] == statusState){
        isValid = true;
      }
    }
  }

  return isValid;
}

/**
 * Removes all duplicate elements from an array.
 *
 *  Reference: https://www.codementor.io/tips/8243973127/how-to-remove-duplicates-within-a-javascript-array-using-es6-in-just-one-line
 *
 * @param {Array} inputArray - The raw array to be deduplicated
 * @returns {Array} The deduplicated array
 */
export function deduplicateArray(inputArray){
  return Array.from(new Set(inputArray));
}

/**
 *
 * @param {string} paramName - The name of the parameter to extract
 * @param {string} urlString - The full url as a string from which to extract the parameter
 * @return {*} The extracted parameter value
 */
export function extractParamFromURL(paramName, urlString){
  /* Since URLSearchParams will ignore a param that starts with '?', we have to remove the '?'
   (and everything before it) from the link string before creating the URLSearchParams object. */
  let urlParamsString = urlString.slice(urlString.indexOf("?") + 1);
  let urlParams = new URLSearchParams(urlParamsString);

  return urlParams.get(paramName).toString();
}

/**
 * Validates that the requested pagination page number falls within the expected range
 *
 * @param {Number} requestedPageNum - The requested page number to validate
 * @param {Number} totalNumPages - The total number of pages available
 * @return {boolean} True if requested page number is valid; false otherwise
 */
export function validateRequestedPageNum(requestedPageNum, totalNumPages){
  let isValid = true;

  // TODO: Once a better error logger has been implemented, change all of the following console.log statements to only display when logging is set to DEBUG

  if(!Axis.isNumber(requestedPageNum)){
    isValid = false;
    console.log("Validation Failed: requestedPageNum is not a Number");
  }else{
    // Requesting page number 1 should always be valid
    if(requestedPageNum != 1) {
      if(requestedPageNum < 1){
        isValid = false;
        console.log("Validation Failed: requestedPageNum is less than 1");
      } else {
        if (!Axis.isNumber(totalNumPages)) {
          isValid = false;
          console.log("Validation Failed: totalNumPages is not a Number");
        } else {
          if (requestedPageNum > totalNumPages) {
            isValid = false;
            console.log("Validation Failed: requestedPageNum is greater than totalNumPages");
          }
        }
      }
    }
  }

  return isValid;
}

/**
 * ES6 Generator function which returns the numerical sequence of integers in the specified range
 *
 * @param inStartInt - The first integer to be in the generated sequence
 * @param inEndInt - The last integer to be in the generated sequence (must be greater than or equal to inStartInt)
 */
export function* genIntegerSequence(inStartInt, inEndInt){
  const startInt = inStartInt;
  const endInt = inEndInt;

  let curInt = startInt;

  if(!Axis.isNumber(startInt)){
    console.log("Value of startInt: " + startInt);
    console.log("Value of endInt: " + endInt);
    throw new TypeError("The value of startInt in the genIntegerSequence generator was not type Number");
  }

  if(!Axis.isNumber(endInt)){
    console.log("Value of startInt: " + startInt);
    console.log("Value of endInt: " + endInt);
    throw new TypeError("The value of endInt in the genIntegerSequence generator was not type Number");
  }

  if(startInt > endInt){
    console.log("Value of startInt: " + startInt);
    console.log("Value of endInt: " + endInt);
    throw new RangeError("The value of endInt in the genIntegerSequence generator was less than the value of starInt.");
  }

  while(curInt <= endInt){
    yield curInt++;
  }
}
<commit_msg>Fix import statement of axis.js dependency in utilityMethods.js<commit_after>import URLSearchParams from 'url-search-params';
import * as Axis from 'axis.js';
import {GITHUB_STATUS_STATES} from '../constants/constants';

export function getRepoById(repos, id){
  const repo = repos.find(repo => repo.id == id);

  if (repo){
    return repo;
  }else{
    return {};
  }
}

export function getBranchByName(branches, branchName){
  const branch = branches.find(branch => branch.name == branchName);

  if (branch){
    return branch;
  }else{
    return {};
  }
}

export function findCommitBySha(commits, sha){
  const commit = commits.find(commit => commit.sha == sha);

  if (commit){
    return commit;
  }else{
    return {};
  }
}

export function firstSevenOfSha(sha){
  return sha.slice(0, 7);
}

export function makeOptionsArrayFromStrings(stringArray){
  let optionsArray = stringArray.map(string => {
    return {
      value: string,
      text: string
    };
  });

  return optionsArray;
}

export function validateObjectExists(obj){
  let isValid = true;

  if(obj === null){
    isValid = false;
  }

  if(obj === undefined){
    isValid = false;
  }

  return isValid;
}

export function isEmpty(obj) {
  for(let key in obj) {
    if(obj.hasOwnProperty(key)) {
      return false;
    }
  }
  return true;
}

/**
 * Checks if input is a valid string
 *
 *  The input variable is valid if it is ALL of the following:
 *      1) variable is a string
 *      2) variable string length > 0
 *
 * @param inVar - input variable to check
 * @returns {boolean}
 */
export function isValidString(inVar){
  let isValid = false;

  if(Axis.isString(inVar)){
    if(inVar.length > 0){
      isValid = true;
    }
  }

  return isValid;
}

/**
 * Checks if a commit reference input value is valid.
 *
 * @param {String} ref - The commit reference input to be validated.
 * @returns {boolean} True if commit reference is valid, false otherwise.
 */
export function validateCommitReference(ref){
  // TODO: Improve validation of ref parameter input value
  let isRefParamValid = isValidString(ref);

  return isRefParamValid;
}

/**
 * Validates a GitHub status state input value against defined
 * constant values in the GITHUB_STATUS_STATES constant object.
 *
 * @param {String} statusState - The status state input to be validated.
 * @returns {boolean} True if statusState equals one of the constants defined in GITHUB_STATUS_STATES, false otherwise.
 */
export function validateGitHubStatusState(statusState){
  let isValid = false;

  for(let prop in GITHUB_STATUS_STATES){
    if(GITHUB_STATUS_STATES.hasOwnProperty(prop)){
      if(GITHUB_STATUS_STATES[prop] == statusState){
        isValid = true;
      }
    }
  }

  return isValid;
}

/**
 * Removes all duplicate elements from an array.
 *
 *  Reference: https://www.codementor.io/tips/8243973127/how-to-remove-duplicates-within-a-javascript-array-using-es6-in-just-one-line
 *
 * @param {Array} inputArray - The raw array to be deduplicated
 * @returns {Array} The deduplicated array
 */
export function deduplicateArray(inputArray){
  return Array.from(new Set(inputArray));
}

/**
 *
 * @param {string} paramName - The name of the parameter to extract
 * @param {string} urlString - The full url as a string from which to extract the parameter
 * @return {*} The extracted parameter value
 */
export function extractParamFromURL(paramName, urlString){
  /* Since URLSearchParams will ignore a param that starts with '?', we have to remove the '?'
   (and everything before it) from the link string before creating the URLSearchParams object. */
  let urlParamsString = urlString.slice(urlString.indexOf("?") + 1);
  let urlParams = new URLSearchParams(urlParamsString);

  return urlParams.get(paramName).toString();
}

/**
 * Validates that the requested pagination page number falls within the expected range
 *
 * @param {Number} requestedPageNum - The requested page number to validate
 * @param {Number} totalNumPages - The total number of pages available
 * @return {boolean} True if requested page number is valid; false otherwise
 */
export function validateRequestedPageNum(requestedPageNum, totalNumPages){
  let isValid = true;

  // TODO: Once a better error logger has been implemented, change all of the following console.log statements to only display when logging is set to DEBUG

  if(!Axis.isNumber(requestedPageNum)){
    isValid = false;
    console.log("Validation Failed: requestedPageNum is not a Number");
  }else{
    // Requesting page number 1 should always be valid
    if(requestedPageNum != 1) {
      if(requestedPageNum < 1){
        isValid = false;
        console.log("Validation Failed: requestedPageNum is less than 1");
      } else {
        if (!Axis.isNumber(totalNumPages)) {
          isValid = false;
          console.log("Validation Failed: totalNumPages is not a Number");
        } else {
          if (requestedPageNum > totalNumPages) {
            isValid = false;
            console.log("Validation Failed: requestedPageNum is greater than totalNumPages");
          }
        }
      }
    }
  }

  return isValid;
}

/**
 * ES6 Generator function which returns the numerical sequence of integers in the specified range
 *
 * @param inStartInt - The first integer to be in the generated sequence
 * @param inEndInt - The last integer to be in the generated sequence (must be greater than or equal to inStartInt)
 */
export function* genIntegerSequence(inStartInt, inEndInt){
  const startInt = inStartInt;
  const endInt = inEndInt;

  let curInt = startInt;

  if(!Axis.isNumber(startInt)){
    console.log("Value of startInt: " + startInt);
    console.log("Value of endInt: " + endInt);
    throw new TypeError("The value of startInt in the genIntegerSequence generator was not type Number");
  }

  if(!Axis.isNumber(endInt)){
    console.log("Value of startInt: " + startInt);
    console.log("Value of endInt: " + endInt);
    throw new TypeError("The value of endInt in the genIntegerSequence generator was not type Number");
  }

  if(startInt > endInt){
    console.log("Value of startInt: " + startInt);
    console.log("Value of endInt: " + endInt);
    throw new RangeError("The value of endInt in the genIntegerSequence generator was less than the value of starInt.");
  }

  while(curInt <= endInt){
    yield curInt++;
  }
}
<|endoftext|>


<commit_before>import Vue from 'vue'

describe('check for window.Vue fallback', () => {
  beforeEach(() => {
    window.Vue = new Vue()
  })
  describe('Vue attached to window not global vm', () => {
    it('should apply to alternate vue implementation', done => {
      nextTick(() => {
        function defined (x) {
          return x !== undefined
        }
        assert(defined(window.Vue.$browserStore), 'Not working')
      }).then(done)
    })
  })
})

describe('check initialization of .localStore & .sessionStore', () => {
  let vm
  beforeEach(() => {
    vm = new Vue()
  })
  describe('sessionStore', () => {
    it('should be defined', done => {
      nextTick(() => {
        function defined (x) {
          return x !== undefined
        }
        assert(defined(vm.$browserStore.browserState.sessionStore), 'Not working')
      }).then(done)
    })
  })
  describe('localStore', () => {
    it('should be defined', done => {
      nextTick(() => {
        function defined (x) {
          return x !== undefined
        }
        assert(defined(vm.$browserStore.browserState.localStore), 'Not working')
      }).then(done)
    })
  })
})
<commit_msg>Add tests for new vbs object<commit_after>import Vue from 'vue'
import VueBrowserstore from '../../src'

describe('check for window.Vue fallback', () => {
  beforeEach(() => {
    window.Vue = new Vue()
    window.localStorage.setItem('foo', 'baz')
    window.sessionStorage.setItem('foo', 'baz')
  })
  describe('Vue attached to window not global vm', () => {
    it('should apply to alternate vue implementation', done => {
      nextTick(() => {
        function defined (x) {
          return x !== undefined
        }
        assert(defined(window.Vue.$browserStore), 'Not working')
      }).then(done)
    })
  })
})
describe('check initialization of .localStore & .sessionStore', () => {
  let vm
  beforeEach(() => {
    vm = new Vue()
  })
  describe('sessionStore', () => {
    it('should exist with a value of undefined', done => {
      nextTick(() => {
        function defined (x) {
          return x !== undefined
        }
        let vbs = new VueBrowserstore()
        assert(!defined(vbs.sessionStore), 'Not working')
      }).then(done)
    })
  })
  describe('localStore', () => {
    it('should exist with a value of undefined', done => {
      nextTick(() => {
        function defined (x) {
          return x !== undefined
        }
        let vbs = new VueBrowserstore()
        assert(!defined(vbs.localStore), 'Not working')
      }).then(done)
    })
  })
})
<|endoftext|>


<commit_before>var App = window.election;

function findZIP(){
	var psc = $("#addressslovakia-zip").val().replace(' ','');
	if(psc in App.psc){
		kraj = App.psc[psc][2] + " kraj";
		okres = "Okres "+ App.psc[psc][1];
		obec = App.psc[psc][0];

		if($("#addressslovakia-kraj option[value='"+kraj+"']").length > 0){
			$("#addressslovakia-kraj").val(kraj).trigger("change");
		}
		if($("#addressslovakia-okres option[value='"+okres+"']").length > 0){
			$("#addressslovakia-okres").val(okres).trigger("change");
		}
		if($("#addressslovakia-city option[value='"+obec+"']").length > 0){
			$("#addressslovakia-city").val(obec).trigger("change");
		}
	}
}

function getAddressOneLine(id) {
  var ret = "";
  var format = $('#' + id + '-format').val();
  if(!format) format = "sk";

  if ($('#' + id + '-street').val()) {
	if(format=="sk"){
     ret += $('#' + id + '-street').val() + " " + $('#' + id + '-streetno').val();
	}else if(format == "usa"){
     ret += $('#' + id + '-streetno').val() + " " + $('#' + id + '-street').val();
	}
  } else {
    if (id == "addressslovakia") {
      getObec() + " " + $('#' + id + '-streetno').val();
    } else {

 	 if(format=="sk"){
      ret += $('#' + id + '-city').val() + " " + $('#' + id + '-streetno').val();
	 }else if(format == "usa"){
      ret += $('#' + id + '-streetno').val() + " " + $('#' + id + '-city').val();
	 }
    }

  }
  if (ret != " ") ret += ", ";

  if (id == "addressslovakia") {
	ret += $('#' + id + '-zip').val() + " " + getObec();
  } else {
   if(format=="sk"){
    ret += $('#' + id + '-zip').val() + " " + $('#' + id + '-city').val();
   }else if(format == "usa"){
    ret += $('#' + id + '-city').val() + " " + $('#' + id + '-zip').val();
   }
  }

  if (ret != " ") ret += ", ";

  if (id == "addressslovakia") {
    ret += "Slovenská republika";
  } else {
    ret += $('#' + id + '-country').val();
  }
  return ret;
}

function nacitajKraje(){
	var options = $("#addressslovakia-kraj");
	options.find('option').remove();
	for (var key in election.cities) {
		options.append($("<option />").val(key).text(key));
	}
	if(!iOSversion()){
		options.select2({width:"100%"});
	}
	nastavKraj();
}
function nastavKraj(){
	var options = $("#addressslovakia-okres");
	options.find('option').remove();
    var kraj = $("#addressslovakia-kraj").val();
	for (var key in election.cities[kraj]) {
		options.append($("<option />").val(key).text(key));
	}
	nastavOkres();
	if(!iOSversion()){
		options.select2({width:"100%"});
	}
}
function nastavOkres(){
	var options = $("#addressslovakia-city");
	options.find('option').remove();
    var kraj = $("#addressslovakia-kraj").val();
    var okres = $("#addressslovakia-okres").val();
	for (var key in election.cities[kraj][okres]) {
		options.append($("<option />").val(key).text(election.cities[kraj][okres][key][10]));
	}
	nastavObec();
	if(!iOSversion()){
		options.select2({width:"100%"});
	}
}
function getObec(){

  var ico = $("#addressslovakia-city").val();
  var kraj = $("#addressslovakia-kraj").val();
  var okres = $("#addressslovakia-okres").val();
  var o = election.cities;

  if (ico && o[kraj] && o[kraj][okres] && o[kraj][okres][ico]) {
	return o[kraj][okres][ico][10];
  }
  return "Nepodarilo sa načítať obec";
}
function nastavObec(obec) {

	// list/db of all cities comes from external file (js/cities)
  var o = election.cities;

  var adresa = "";
  var ico = $("#addressslovakia-city").val();
  var kraj = $("#addressslovakia-kraj").val();
  var okres = $("#addressslovakia-okres").val();

  if (ico) {

    if (o[kraj] && o[kraj][okres] && o[kraj][okres][ico]) {
	  var data = o[kraj][okres][ico];
      adresa = data[0] + "\n";
      if (data[1] != "") {
        adresa += data[1] + "\n";
      }
      if (data[2] != "" || data[3] != "") {
        if (data[2]) {
          adresa += data[2] + " ";
        }
        if (data[3]) {
          adresa += data[3];
        }
        adresa += "\n";
      }
      adresa += data[4] + " " + data[5] + "\n" + data[6].replace(/;/i, "\n");

    if(App.request_form == 'volbaPostouBezTrvalehoPobytu'){
  	  $("#adresa").val("Ministerstvo vnútra Slovenskej republiky\nodbor volieb, referenda a politických strán\nDrieňová 22\n826 86  Bratislava 29\nSLOVAK REPUBLIC");
      $("#sendto").html("volby@minv.sk");
	  $("#phone").html("");
	  $("#phonetext").hide();
    }else{
      $("#adresa").val(adresa);
	  $("#sendto").html(data[6]);
	  if(data[8] != ""){
		  $("#phone").html(data[7] + " / " + data[8]);
		  $("#phonetext").show();
	  }else{
		  $("#phone").html("");
		  $("#phonetext").hide();
	  }
    }
	if($("#sendto").html().indexOf("@") == -1){
		$("#sendemail").hide();
		$("#noemail").show();
	}else{
		$("#sendemail").show();
		$("#noemail").hide();
	}

	var subj = "Ziadost";
    var textemailu = "";
	var meno = $('#basicinfo-name').val()+" "+$('#basicinfo-lastname').val();
    if(App.request_form == 'volbaPostouSTrvalymPobytom'){
      var subj = "Žiadosť o voľbu poštou pre voľby do NRSR";
      var textemailu = "Dobrý deň, "+decodeURIComponent("%0D%0A%0D%0A")+"podľa § 60 ods. 1 zákona č. 180/2014 Z. z. o podmienkach výkonu volebného práva a o zmene a doplnení niektorých zákonov žiadam o voľbu poštou pre voľby do Národnej rady Slovenskej republiky v roku 2016. Zároveň Vás chcem poprosiť o potvrdenie e-mailom že žiadosť bola prijatá a spracovaná. "+decodeURIComponent("%0D%0A%0D%0A")+"V prílohe zasielam podpísanú žiadosť. "+decodeURIComponent("%0D%0A%0D%0A")+"Ďakujem,"+decodeURIComponent("%0D%0A%0D%0A")+" "+meno;
    }else if(App.request_form == 'volbaPostouBezTrvalehoPobytu'){
      var subj = "Žiadosť o voľbu poštou pre voľby do NRSR";
      var textemailu = "Dobrý deň, "+decodeURIComponent("%0D%0A%0D%0A")+"podľa   § 59 ods. 1   zákona   č. 180/2014 Z. z. o podmienkach výkonu volebného práva a o zmene a doplnení niektorých zákonov žiadam o voľbu poštou pre voľby do Národnej rady Slovenskej republiky v roku 2016 a o zaslanie hlasovacích lístkov a obálok na adresu uvedenú v žiadosti. Zároveň Vás chcem poprosiť o potvrdenie e-mailom že žiadosť bola prijatá a spracovaná. "+decodeURIComponent("%0D%0A%0D%0A")+"V prílohe zasielam podpísanú žiadosť. "+decodeURIComponent("%0D%0A%0D%0A")+"Ďakujem,"+decodeURIComponent("%0D%0A%0D%0A")+" "+meno;
    }else if(App.request_form == "ziadostOPreukazPostou"){
      var subj = "Žiadosť o hlasovací preukaz";
      var textemailu = "Dobrý deň, "+decodeURIComponent("%0D%0A%0D%0A")+"podľa § 46 zákona č. 180/2014 Z. z. o podmienkach výkonu volebného práva a o zmene a doplnení niektorých zákonov žiadam o vydanie hlasovacieho preukazu pre voľby do Národnej rady Slovenskej republiky v roku 2016. Hlasovací preukaz si želám odoslať na adresu uvedenú v žiadosti. Zároveň Vás chcem poprosiť o potvrdenie e-mailom že žiadosť bola prijatá a spracovaná. "+decodeURIComponent("%0D%0A%0D%0A")+"V prílohe zasielam podpísanú žiadosť. "+decodeURIComponent("%0D%0A%0D%0A")+"Ďakujem,"+decodeURIComponent("%0D%0A%0D%0A")+" "+meno;
    }else if(App.request_form =="ziadostOPreukaPreSplnomocnenca"){
      var subj = "Žiadosť o hlasovací preukaz";
      var textemailu = "Dobrý deň, "+decodeURIComponent("%0D%0A%0D%0A")+"podľa § 46 zákona č. 180/2014 Z. z. o podmienkach výkonu volebného práva a o zmene a doplnení niektorých zákonov žiadam o vydanie hlasovacieho preukazu pre voľby do Národnej rady Slovenskej republiky v roku 2016. Hlasovací preukaz za mňa preberie splnomocnenec. Zároveň Vás chcem poprosiť o potvrdenie e-mailom že žiadosť bola prijatá a spracovaná. "+decodeURIComponent("%0D%0A%0D%0A")+"V prílohe zasielam podpísanú žiadosť. "+decodeURIComponent("%0D%0A%0D%0A")+"Ďakujem,"+decodeURIComponent("%0D%0A%0D%0A")+" "+meno;
    }

    $("#emailsubject").html(subj);
    $("#emailbody").html(textemailu);
	if(jQuery.data( document.body, "psc-locked")){}else{
		//$("#addressslovakia-zip").val(data[4]);
	}
    $("#send").attr("href", "mailto:" + $("#sendto").html() + "?subject=" + encodeURIComponent(subj) + "&body=" + encodeURIComponent(textemailu));

    }
  }
}<commit_msg>Doplnenie Poste Restante, Textov, formatovanie<commit_after>var App = window.election;

function findZIP(){
	var psc = $("#addressslovakia-zip").val().replace(' ','');
	if(psc in App.psc){
		kraj = App.psc[psc][2] + " kraj";
		okres = "Okres "+ App.psc[psc][1];
		obec = App.psc[psc][0];

		if($("#addressslovakia-kraj option[value='"+kraj+"']").length > 0){
			$("#addressslovakia-kraj").val(kraj).trigger("change");
		}
		if($("#addressslovakia-okres option[value='"+okres+"']").length > 0){
			$("#addressslovakia-okres").val(okres).trigger("change");
		}
		if($("#addressslovakia-city option[value='"+obec+"']").length > 0){
			$("#addressslovakia-city").val(obec).trigger("change");
		}
	}
}

function getAddressOneLine(id) {
  var ret = "";
  var format = getAdressFormat(id);

  if ($('#' + id + '-street').val()) {
	if(format=="sk" || format=="sk-poste-restante" ){
     ret += $('#' + id + '-street').val() + " " + $('#' + id + '-streetno').val();
	}else if(format == "usa" || format=="usa-poste-restante" ){
     ret += $('#' + id + '-streetno').val() + " " + $('#' + id + '-street').val();
	}
  } else {
    if (id == "addressslovakia") {
      getObec() + " " + $('#' + id + '-streetno').val();
    } else {

 	 if(format=="sk" || format=="sk-poste-restante"){
      ret += $('#' + id + '-city').val() + " " + $('#' + id + '-streetno').val();
	 }else if(format == "usa" || format=="usa-poste-restante"){
      ret += $('#' + id + '-streetno').val() + " " + $('#' + id + '-city').val();
	 }
    }

  }
  if (ret != " ") ret += ", ";

  if (id == "addressslovakia") {
	ret += $('#' + id + '-zip').val() + " " + getObec();
  } else {
   if(format=="sk" || format=="sk-poste-restante"){
    ret += $('#' + id + '-zip').val() + " " + $('#' + id + '-city').val();
   }else if(format == "usa" || format=="usa-poste-restante"){
    ret += $('#' + id + '-city').val() + " " + $('#' + id + '-zip').val();
   }
  }

  if (ret != " ") ret += ", ";

  if (id == "addressslovakia") {
    ret += "Slovenská republika";
  } else {
    ret += $('#' + id + '-country').val();
  }
  return ret;
}

function nacitajKraje(){
	var options = $("#addressslovakia-kraj");
	options.find('option').remove();
	for (var key in election.cities) {
		options.append($("<option />").val(key).text(key));
	}
	if(!iOSversion()){
		options.select2({width:"100%"});
	}
	nastavKraj();
}
function nastavKraj(){
	var options = $("#addressslovakia-okres");
	options.find('option').remove();
    var kraj = $("#addressslovakia-kraj").val();
	for (var key in election.cities[kraj]) {
		options.append($("<option />").val(key).text(key));
	}
	nastavOkres();
	if(!iOSversion()){
		options.select2({width:"100%"});
	}
}
function nastavOkres(){
	var options = $("#addressslovakia-city");
	options.find('option').remove();
    var kraj = $("#addressslovakia-kraj").val();
    var okres = $("#addressslovakia-okres").val();
	for (var key in election.cities[kraj][okres]) {
		options.append($("<option />").val(key).text(election.cities[kraj][okres][key][10]));
	}
	nastavObec();
	if(!iOSversion()){
		options.select2({width:"100%"});
	}
}
function getObec(){

  var ico = $("#addressslovakia-city").val();
  var kraj = $("#addressslovakia-kraj").val();
  var okres = $("#addressslovakia-okres").val();
  var o = election.cities;

  if (ico && o[kraj] && o[kraj][okres] && o[kraj][okres][ico]) {
	return o[kraj][okres][ico][10];
  }
  return "Nepodarilo sa načítať obec";
}
function nastavObec(obec) {

	// list/db of all cities comes from external file (js/cities)
  var o = election.cities;

  var adresa = "";
  var ico = $("#addressslovakia-city").val();
  var kraj = $("#addressslovakia-kraj").val();
  var okres = $("#addressslovakia-okres").val();

  if (ico) {

    if (o[kraj] && o[kraj][okres] && o[kraj][okres][ico]) {
	  var data = o[kraj][okres][ico];
      adresa = data[0] + "\n";
      if (data[1] != "") {
        adresa += data[1] + "\n";
      }
      if (data[2] != "" || data[3] != "") {
        if (data[2]) {
          adresa += data[2] + " ";
        }
        if (data[3]) {
          adresa += data[3];
        }
        adresa += "\n";
      }
      adresa += data[4] + " " + data[5] + "\n" + data[6].replace(/;/i, "\n");

    if(App.request_form == 'volbaPostouBezTrvalehoPobytu'){
  	  $("#adresa").val("Ministerstvo vnútra Slovenskej republiky\nodbor volieb, referenda a politických strán\nDrieňová 22\n826 86  Bratislava 29\nSLOVAK REPUBLIC");
      $("#sendto").html("volby@minv.sk");
	  $("#phone").html("");
	  $("#phonetext").hide();
    }else{
      $("#adresa").val(adresa);
	  $("#sendto").html(data[6]);
	  if(data[8] != ""){
		  $("#phone").html(data[7] + " / " + data[8]);
		  $("#phonetext").show();
	  }else{
		  $("#phone").html("");
		  $("#phonetext").hide();
	  }
    }
	if($("#sendto").html().indexOf("@") == -1){
		$("#sendemail").hide();
		$("#noemail").show();
	}else{
		$("#sendemail").show();
		$("#noemail").hide();
	}

	var subj = "Ziadost";
    var textemailu = "";
	var meno = $('#basicinfo-name').val()+" "+$('#basicinfo-lastname').val();
    if(App.request_form == 'volbaPostouSTrvalymPobytom'){
      var subj = "Žiadosť o voľbu poštou pre voľby do NRSR";
      var textemailu = "Dobrý deň, "+decodeURIComponent("%0D%0A%0D%0A")+"podľa § 60 ods. 1 zákona č. 180/2014 Z. z. o podmienkach výkonu volebného práva a o zmene a doplnení niektorých zákonov žiadam o voľbu poštou pre voľby do Národnej rady Slovenskej republiky v roku 2016. Zároveň Vás chcem poprosiť o potvrdenie e-mailom že žiadosť bola prijatá a spracovaná. "+decodeURIComponent("%0D%0A%0D%0A")+"V prílohe zasielam podpísanú žiadosť. "+decodeURIComponent("%0D%0A%0D%0A")+"Ďakujem,"+decodeURIComponent("%0D%0A%0D%0A")+" "+meno;
    }else if(App.request_form == 'volbaPostouBezTrvalehoPobytu'){
      var subj = "Žiadosť o voľbu poštou pre voľby do NRSR";
      var textemailu = "Dobrý deň, "+decodeURIComponent("%0D%0A%0D%0A")+"podľa § 59 ods. 1 zákona č. 180/2014 Z. z. o podmienkach výkonu volebného práva a o zmene a doplnení niektorých zákonov žiadam o voľbu poštou pre voľby do Národnej rady Slovenskej republiky v roku 2016 a o zaslanie hlasovacích lístkov a obálok na adresu uvedenú v žiadosti. Zároveň Vás chcem poprosiť o potvrdenie e-mailom že žiadosť bola prijatá a spracovaná. "+decodeURIComponent("%0D%0A%0D%0A")+"V prílohe zasielam podpísanú žiadosť. "+decodeURIComponent("%0D%0A%0D%0A")+"Ďakujem,"+decodeURIComponent("%0D%0A%0D%0A")+" "+meno;
    }else if(App.request_form == "ziadostOPreukazPostou"){
      var subj = "Žiadosť o hlasovací preukaz";
      var textemailu = "Dobrý deň, "+decodeURIComponent("%0D%0A%0D%0A")+"podľa § 46 zákona č. 180/2014 Z. z. o podmienkach výkonu volebného práva a o zmene a doplnení niektorých zákonov žiadam o vydanie hlasovacieho preukazu pre voľby do Národnej rady Slovenskej republiky v roku 2016. Hlasovací preukaz si želám odoslať na adresu uvedenú v žiadosti. Zároveň Vás chcem poprosiť o potvrdenie e-mailom že žiadosť bola prijatá a spracovaná. "+decodeURIComponent("%0D%0A%0D%0A")+"V prílohe zasielam podpísanú žiadosť. "+decodeURIComponent("%0D%0A%0D%0A")+"Ďakujem,"+decodeURIComponent("%0D%0A%0D%0A")+" "+meno;
    }else if(App.request_form =="ziadostOPreukaPreSplnomocnenca"){
      var subj = "Žiadosť o hlasovací preukaz";
      var textemailu = "Dobrý deň, "+decodeURIComponent("%0D%0A%0D%0A")+"podľa § 46 zákona č. 180/2014 Z. z. o podmienkach výkonu volebného práva a o zmene a doplnení niektorých zákonov žiadam o vydanie hlasovacieho preukazu pre voľby do Národnej rady Slovenskej republiky v roku 2016. Hlasovací preukaz za mňa preberie splnomocnenec. Zároveň Vás chcem poprosiť o potvrdenie e-mailom že žiadosť bola prijatá a spracovaná. "+decodeURIComponent("%0D%0A%0D%0A")+"V prílohe zasielam podpísanú žiadosť. "+decodeURIComponent("%0D%0A%0D%0A")+"Ďakujem,"+decodeURIComponent("%0D%0A%0D%0A")+" "+meno;
    }

    $("#emailsubject").html(subj);
    $("#emailbody").html(textemailu);
	if(jQuery.data( document.body, "psc-locked")){}else{
		//$("#addressslovakia-zip").val(data[4]);
	}
    $("#send").attr("href", "mailto:" + $("#sendto").html() + "?subject=" + encodeURIComponent(subj) + "&body=" + encodeURIComponent(textemailu));

    }
  }
}

function getAdressFormat(id){
  var format = $('#' + id + '-format').val();
  if(!format) format = "sk";
  return format;
}

function isPosRes(format){
	return ( format.indexOf('poste-restante') !== -1 );
}

function nastavPosteRestante(){
	App.poste_res = isPosRes( getAdressFormat('addressforeign') );

	if( App.poste_res ) {
	  	$('.field-addressforeign-street label:first').html('Poste Restante');
	  	$('#addressforeign-street').val('Poste Restante');
	  	$('.field-addressforeign-streetno label:first').html('Adresa Pošty');
	  	$('.field-addressforeign-city label:first').html('Mesto');
	  	$('.field-addressforeign-zip label:first').html('PSČ Pošty');
	} else {
	  	$('.field-addressforeign-street label:first').html('Ulica');
	  	$('#addressforeign-street').val('');
	  	$('.field-addressforeign-streetno label:first').html('Číslo domu');
	  	$('.field-addressforeign-city label:first').html('Mesto');
	  	$('.field-addressforeign-zip label:first').html('PSČ');
	}
}
<|endoftext|>


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

    angular
        .module('app')
        .controller('ApplicationController', ApplicationController);

    ApplicationController.$inject = ['$state', '$rootScope', 'CredentialService'];
    function ApplicationController($state, $rootScope, CredentialService) {
        var vm = this;

        activate();

        function activate() {
            console.info('app - activate - token present:' + CredentialService.isTokenPresent());
            if (!CredentialService.isTokenPresent()) {
                $state.go('main.login');
            }
            else {
                $state.go('main.step1');
            }
        }

        function preventAndGo(stateName, event) {
            event.preventDefault();
            $state.go(stateName);
        }

        function checkProtectedRoutes(toState, event) {
            if (toState.data.protected) {
                console.info('app - protected route - token present:' + CredentialService.isTokenPresent());
                if (!CredentialService.isTokenPresent()) {
                    preventAndGo('main.login', event);
                }
            }
        }

        function checkSpecificRoutes(toState, event) {
            if (toState.name === 'main.login' && CredentialService.isTokenPresent()) {
                preventAndGo('main.step1', event);
            }

            if (toState.name === 'main') {
                preventAndGo('main.step1', event);
            }
        }

        function checkCallbackRoute(toState, toParams, event) {
            if (toState.name === 'main.callback') {
                var redirectFlag = false;

                if (CredentialService.isTokenPresent()) {
                    console.info('callback route check - istokenpresent fired');
                    redirectFlag = true;
                }
                else if (toParams.code === undefined || toParams.state === undefined) {
                    console.info('callback route check - code:' + toParams.code + ' state:' + toParams.state);
                    redirectFlag = true;
                }
                else if (!CredentialService.isStatePresent()) {
                    console.info('callback route check - state is not present');
                    redirectFlag = true;
                }
                else if (toParams.state !== CredentialService.getState()) {
                    console.info('callback route check - state does not match');
                    redirectFlag = true;
                }

                if (redirectFlag) {
                    preventAndGo('main.step1', event);
                }
            }
        }

        $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
            checkProtectedRoutes(toState, event);
            checkSpecificRoutes(toState, event);
            checkCallbackRoute(toState, toParams, event);
        });

        $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
            $rootScope.pageTitle = toState.data.title;
        });
    }
})();<commit_msg>Added debug code to test login on Heroku<commit_after>(function () {
    'use strict';

    angular
        .module('app')
        .controller('ApplicationController', ApplicationController);

    ApplicationController.$inject = ['$state', '$rootScope', 'CredentialService'];
    function ApplicationController($state, $rootScope, CredentialService) {
        var vm = this;

        activate();

        function activate() {
            console.info('app - activate - token present:' + CredentialService.isTokenPresent());
            if (!CredentialService.isTokenPresent()) {
                $state.go('main.login');
            }
            else {
                $state.go('main.step1');
            }
        }

        function preventAndGo(stateName, event) {
            event.preventDefault();
            $state.go(stateName);
        }

        function checkProtectedRoutes(toState, event) {
            if (toState.data.protected) {
                console.info('app - protected route - token present:' + CredentialService.isTokenPresent());
                if (!CredentialService.isTokenPresent()) {
                    preventAndGo('main.login', event);
                }
            }
        }

        function checkSpecificRoutes(toState, event) {
            if (toState.name === 'main.login' && CredentialService.isTokenPresent()) {
                preventAndGo('main.step1', event);
            }

            if (toState.name === 'main') {
                preventAndGo('main.step1', event);
            }
        }

        function checkCallbackRoute(toState, toParams, event) {
            if (toState.name === 'main.callback') {
                var redirectFlag = false;

                if (CredentialService.isTokenPresent()) {
                    console.info('callback route check - istokenpresent fired');
                    redirectFlag = true;
                }
                else if (toParams.code === undefined || toParams.state === undefined) {
                    console.info('callback route check - code:' + toParams.code + ' state:' + toParams.state);
                    redirectFlag = true;
                }
                else if (!CredentialService.isStatePresent()) {
                    console.info('callback route check - state is not present');
                    redirectFlag = true;
                }
                else if (toParams.state !== CredentialService.getState()) {
                    console.info('callback route check - state does not match');
                    console.info('passed state:' + toParams.state);
                    console.info('stored state:' + CredentialService.getState());
                    redirectFlag = true;
                }

                if (redirectFlag) {
                    preventAndGo('main.step1', event);
                }
            }
        }

        $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
            checkProtectedRoutes(toState, event);
            checkSpecificRoutes(toState, event);
            checkCallbackRoute(toState, toParams, event);
        });

        $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
            $rootScope.pageTitle = toState.data.title;
        });
    }
})();<|endoftext|>


<commit_before>(function() {
    'use strict';
    angular.module('plotly', []).directive('plotly', [
        '$window',
        function($window) {
            return {
                restrict: 'E',
                template: '

',
                scope: {
                    data: '=',
                    layout: '=',
                    options: '='
                },
                link: function(scope, element) {
                    var graph = element[0].children[0];
                    var initialized = false;

                    function onUpdate() {
                        //No data yet, or clearing out old data
                        if (!(scope.data)) {
                            if (initialized) {
                                Plotly.Plots.purge(graph);
                                graph.innerHTML = '';
                            }
                            return;
                        }
                        //If this is the first run with data, initialize
                        if (!initialized) {
                            initialized = true;
                            Plotly.newPlot(graph, scope.data, scope.layout, scope.options);
                        }
                        graph.layout = scope.layout;
                        graph.data = scope.data;
                        Plotly.redraw(graph);
                        Plotly.Plots.resize(graph);
                    }

                    function onResize() {
                        if (!(initialized && scope.data)) return;
                        Plotly.Plots.resize(graph);
                    }

                    scope.$watchGroup([
                        function() {
                            return scope.layout;
                        },
                        function() {
                            return scope.data;
                        }
                    ], function(newValue, oldValue) {
                        if (angular.equals(newValue, oldValue)) return;
                        onUpdate();
                    }, true);

                    scope.$watch(function() {
                        return {
                            'h': element[0].offsetHeight,
                            'w': element[0].offsetWidth
                        };
                    }, function(newValue, oldValue) {
                        if (angular.equals(newValue, oldValue)) return;
                        onResize();
                    }, true);

                    angular.element($window).bind('resize', function() {
                        onResize();
                    });
                }
            };
        }
    ]);
})();<commit_msg>The bind of OnResize can be shorter and better<commit_after>(function() {
    'use strict';
    angular.module('plotly', []).directive('plotly', [
        '$window',
        function($window) {
            return {
                restrict: 'E',
                template: '

',
                scope: {
                    data: '=',
                    layout: '=',
                    options: '='
                },
                link: function(scope, element) {
                    var graph = element[0].children[0];
                    var initialized = false;

                    function onUpdate() {
                        //No data yet, or clearing out old data
                        if (!(scope.data)) {
                            if (initialized) {
                                Plotly.Plots.purge(graph);
                                graph.innerHTML = '';
                            }
                            return;
                        }
                        //If this is the first run with data, initialize
                        if (!initialized) {
                            initialized = true;
                            Plotly.newPlot(graph, scope.data, scope.layout, scope.options);
                        }
                        graph.layout = scope.layout;
                        graph.data = scope.data;
                        Plotly.redraw(graph);
                        Plotly.Plots.resize(graph);
                    }

                    function onResize() {
                        if (!(initialized && scope.data)) return;
                        Plotly.Plots.resize(graph);
                    }

                    scope.$watchGroup([
                        function() {
                            return scope.layout;
                        },
                        function() {
                            return scope.data;
                        }
                    ], function(newValue, oldValue) {
                        if (angular.equals(newValue, oldValue)) return;
                        onUpdate();
                    }, true);

                    scope.$watch(function() {
                        return {
                            'h': element[0].offsetHeight,
                            'w': element[0].offsetWidth
                        };
                    }, function(newValue, oldValue) {
                        if (angular.equals(newValue, oldValue)) return;
                        onResize();
                    }, true);

                    angular.element($window).bind('resize', onResize);
                }
            };
        }
    ]);
})();
<|endoftext|>


<commit_before>var classes = {
      String                   :  's'
    , Number                   :  'f'

    , Keyword                  :  'k'
    , 'Keyword.Constant'       :  'kc'
    , 'Keyword.Declaration'    :  'kd'
    , 'Keyword.Namespace'      :  'kn'
    , 'Keyword.Pseudo'         :  'kp'
    , 'Keyword.Reserved'       :  'kr'
    , 'Keyword.Type'           :  'kt'

    , Name                     :  'n'
    , 'Name.Attribute'         :  'na'
    , 'Name.Builtin'           :  'nb'
    , 'Name.Builtin.Pseudo'    :  'bp'
    , 'Name.Class'             :  'nc'
    , 'Name.Constant'          :  'no'
    , 'Name.Decorator'         :  'nd'
    , 'Name.Entity'            :  'ni'
    , 'Name.Exception'         :  'ne'
    , 'Name.Function'          :  'nf'
    , 'Name.Property'          :  'py'
    , 'Name.Label'             :  'nl'
    , 'Name.Namespace'         :  'nn'
    , 'Name.Other'             :  'nx'
    , 'Name.Tag'               :  'nt'
    , 'Name.Variable'          :  'nv'
    , 'Name.Variable.Class'    :  'vc'
    , 'Name.Variable.Global'   :  'vg'
    , 'Name.Variable.Instance' :  'vi'

    , Literal                  :  'l'
    , 'Literal.Date'           :  'ld'

    , Operator                 :  'o'
    , Punctuation              :  'p'

    , Comment                  :  'c'
    , 'Comment.Multiline'      :  'cm'
    , 'Comment.Preproc'        :  'cp'
    , 'Comment.Single'         :  'c1'
    , 'Comment.Special'        :  'cs'

    , Generic                  :  'g'
    , 'Generic.Deleted'        :  'gd'
    , 'Generic.Emph'           :  'ge'
    , 'Generic.Error'          :  'gr'
    , 'Generic.Heading'        :  'gh'
    , 'Generic.Inserted'       :  'gi'
    , 'Generic.Output'         :  'go'
    , 'Generic.Prompt'         :  'gp'
    , 'Generic.Strong'         :  'gs'
    , 'Generic.Subheading'     :  'gu'
    , 'Generic.Traceback'      :  'gt'
    }
  , spans = {};

Object.keys(classes)
  .forEach(function (k) {
    spans[k] = ':';
  });

module.exports = spans;
<commit_msg>escaping html in strings and comments<commit_after>var classes = {
      String                   :  's'
    , Number                   :  'f'

    , Keyword                  :  'k'
    , 'Keyword.Constant'       :  'kc'
    , 'Keyword.Declaration'    :  'kd'
    , 'Keyword.Namespace'      :  'kn'
    , 'Keyword.Pseudo'         :  'kp'
    , 'Keyword.Reserved'       :  'kr'
    , 'Keyword.Type'           :  'kt'

    , Name                     :  'n'
    , 'Name.Attribute'         :  'na'
    , 'Name.Builtin'           :  'nb'
    , 'Name.Builtin.Pseudo'    :  'bp'
    , 'Name.Class'             :  'nc'
    , 'Name.Constant'          :  'no'
    , 'Name.Decorator'         :  'nd'
    , 'Name.Entity'            :  'ni'
    , 'Name.Exception'         :  'ne'
    , 'Name.Function'          :  'nf'
    , 'Name.Property'          :  'py'
    , 'Name.Label'             :  'nl'
    , 'Name.Namespace'         :  'nn'
    , 'Name.Other'             :  'nx'
    , 'Name.Tag'               :  'nt'
    , 'Name.Variable'          :  'nv'
    , 'Name.Variable.Class'    :  'vc'
    , 'Name.Variable.Global'   :  'vg'
    , 'Name.Variable.Instance' :  'vi'

    , Literal                  :  'l'
    , 'Literal.Date'           :  'ld'

    , Operator                 :  'o'
    , Punctuation              :  'p'

    , Comment                  :  'c'
    , 'Comment.Multiline'      :  'cm'
    , 'Comment.Preproc'        :  'cp'
    , 'Comment.Single'         :  'c1'
    , 'Comment.Special'        :  'cs'

    , Generic                  :  'g'
    , 'Generic.Deleted'        :  'gd'
    , 'Generic.Emph'           :  'ge'
    , 'Generic.Error'          :  'gr'
    , 'Generic.Heading'        :  'gh'
    , 'Generic.Inserted'       :  'gi'
    , 'Generic.Output'         :  'go'
    , 'Generic.Prompt'         :  'gp'
    , 'Generic.Strong'         :  'gs'
    , 'Generic.Subheading'     :  'gu'
    , 'Generic.Traceback'      :  'gt'
    }
  , spans = {};

// strings and comments can contain html that needs to be escaped
var escapees = [
    'String'
  , 'Comment'
  , 'Comment.Multiline'
  , 'Comment.Preproc'
  , 'Comment.Single'
  , 'Comment.Special'
  ];

function escapeHtml (s) {
  return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
}

function escaperWrapper (clazz) {
  return function escapeAndWrap (s) {
    return [
        ''
      , escapeHtml(s)
      , ''
      ].join('');
  };
}

Object.keys(classes)
  .forEach(function (k) {
    spans[k] = ~escapees.indexOf(k)   ?
      escaperWrapper(classes[k])      :
      ':';
  });

console.log(spans);

module.exports = spans;
<|endoftext|>


<commit_before>/*
 * markdown_highlight_rules.js
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * The Initial Developer of the Original Code is
 * Ajax.org B.V.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define("mode/markdown_highlight_rules", function(require, exports, module) {

var oop = require("ace/lib/oop");
var lang = require("ace/lib/lang");
var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;
var JavaScriptHighlightRules = require("ace/mode/javascript_highlight_rules").JavaScriptHighlightRules;
var XmlHighlightRules = require("ace/mode/xml_highlight_rules").XmlHighlightRules;
var HtmlHighlightRules = require("ace/mode/html_highlight_rules").HtmlHighlightRules;
var CssHighlightRules = require("ace/mode/css_highlight_rules").CssHighlightRules;

var escaped = function(ch) {
    return "(?:[^" + lang.escapeRegExp(ch) + "\\\\]|\\\\.)*";
}

function github_embed(tag, prefix) {
    return { // Github style block
        token : "support.function",
        regex : "^\\s*```" + tag + "\\s*$",
        push  : prefix + "start"
    };
}

var MarkdownHighlightRules = function() {

    var slideFields = lang.arrayToMap(
        ("title|author|date|rtl|depends|autosize|width|height|transition|transition-speed|font-family|css|class|navigation|incremental|left|right|id|audio|video|type|at|help-doc|help-topic|source|console|console-input|execute|pause")
            .split("|")
    );

    // regexp must not have capturing parentheses
    // regexps are ordered -> the first match is used

    this.$rules = {

        "basic" : [{
            token : "constant.language.escape",
            regex : /\\[\\`*_{}\[\]()#+\-.!]/
        }, { // code span `
            token : ["support.function", "support.function", "support.function"],
            regex : "(`+)(.*?[^`])(\\1)"
        }, { // reference
            token : ["text", "constant", "text", "url", "string", "text"],
            regex : "^([ ]{0,3}\\[)([^\\]]+)(\\]:\\s*)([^ ]+)(\\s*(?:[\"][^\"]+[\"])?(\\s*))$"
        }, { // link by reference
            token : ["text", "keyword", "text", "constant", "text"],
            regex : "(\\[)(" + escaped("]") + ")(\\]\s*\\[)("+ escaped("]") + ")(\\])"
        }, { // link by url
            token : ["text", "keyword", "text", "markup.underline", "string", "text"],
            regex : "(\\[)(" +                                        // [
                escaped("]") +                                    // link text
                ")(\\]\\()"+                                      // ](
                '((?:[^\\)\\s\\\\]|\\\\.|\\s(?=[^"]))*)' +        // href
                '(\\s*"' +  escaped('"') + '"\\s*)?' +            // "title"
                "(\\))"                                           // )
        }, { // strong ** __
            token : ["constant.numeric", "constant.numeric", "constant.numeric"],
            regex : "([*]{2}|[_]{2}(?=\\S))(.*?\\S[*_]*)(\\1)"
        }, { // emphasis * _
            token : ["constant.language.boolean", "constant.language.boolean", "constant.language.boolean"],
            regex : "([*]|[_](?=\\S))(.*?\\S[*_]*)(\\1)"
        }, { //
            token : ["text", "keyword", "text"],
            regex : "(<)("+
                "(?:https?|ftp|dict):[^'\">\\s]+"+
                "|"+
                "(?:mailto:)?[-.\\w]+\\@[-a-z0-9]+(?:\\.[-a-z0-9]+)*\\.[a-z]+"+
                ")(>)"
        }],

        start: [{
           token : "empty_line",
           regex : '^$',
           next: "allowBlock"
        }, { // code span
            token : ["support.function", "support.function", "support.function"],
            regex : "(`+)([^\\r]*?[^`])(\\1)"
        }, { // h1 with equals
            token: "markup.heading.1",
            regex: "^\\={3,}\\s*$",
            next: "fieldblock"
        }, { // h1
            token: "markup.heading.1",
            regex: "^=+(?=\\s*$)"
        }, { // h2
            token: "markup.heading.2",
            regex: "^\\-+(?=\\s*$)"
        }, {
            token : function(value) {
                return "markup.heading." + value.length;
            },
            regex : /^#{1,6}(?=\s*[^ #]|\s+#.)/,
            next : "header"
        },

        github_embed("(?:javascript|js)", "jscode-"),
        github_embed("xml", "xmlcode-"),
        github_embed("html", "htmlcode-"),
        github_embed("css", "csscode-"),

        { // Github style block
            token : "support.function",
            regex : "^\\s*```\\s*\\S*(?:{.*?\\})?\\s*$",
            next  : "githubblock"
        }, { // block quote
            token : "string.blockquote",
            regex : "^\\s*>\\s*(?:[*+-]|\\d+\\.)?\\s+",
            next  : "blockquote"
        },
        { // reference
            token : ["text", "constant", "text", "url", "string", "text"],
            regex : "^([ ]{0,3}\\[)([^\\]]+)(\\]:\\s*)([^ ]+)(\\s*(?:[\"][^\"]+[\"])?(\\s*))$"
        }, { // link by reference
            token : ["text", "keyword", "text", "constant", "text"],
            regex : "(\\[)((?:[[^\\]]*\\]|[^\\[\\]])*)(\\][ ]?(?:\\n[ ]*)?\\[)(.*?)(\\])"
        }, { // link by url
            token : ["text", "keyword", "text", "markup.underline", "string", "text"],
            regex : "(\\[)"+
                "(\\[[^\\]]*\\]|[^\\[\\]]*)"+
                "(\\]\\([ \\t]*)"+
                "(<?(?:(?:[^\\(]*?\\([^\\)]*?\\)\\S*?)|(?:.*?))>?)"+
                "((?:[ \t]*\"(?:.*?)\"[ \\t]*)?)"+
                "(\\))"
        }, { // HR *
            token : "constant",
            regex : "^[ ]{0,2}(?:[ ]?\\*[ ]?){3,}\\s*$"
        }, { // HR -
            token : "constant",
            regex : "^[ ]{0,2}(?:[ ]?\\-[ ]?){3,}\\s*$"
        }, { // HR _
            token : "constant",
            regex : "^[ ]{0,2}(?:[ ]?\\_[ ]?){3,}\\s*$"
        }, { // MathJax native display \[ ... \]
            token : "markup.list",
            regex : "\\\\\\[",
            next  : "mathjaxnativedisplay"
        }, { // MathJax native inline \( ... \)
            token : "markup.list",
            regex : "\\\\\\(",
            next  : "mathjaxnativeinline"
        }, { // $ escape
            token : "text",
            regex : "\\\\\\$"
        }, { // MathJax $$
            token : "markup.list",
            regex : "\\${2}",
            next  : "mathjaxdisplay"
        }, { // MathJax $...$ (org-mode style)
            token : ["markup.list","support.function","markup.list"],
            regex : "(\\$)" + "((?!\\s)[^$]*[^$\\s])" + "(\\$)" + "(?![\\w\\d`])"
        }, { // strong ** __
            token : ["constant.numeric", "constant.numeric", "constant.numeric"],
            regex : "([*]{2}|[_]{2}(?=\\S))([^\\r]*?\\S[*_]*)(\\1)"
        }, { // emphasis * _
            token : ["constant.language.boolean", "constant.language.boolean", "constant.language.boolean"],
            regex : "([*]|[_](?=\\S))([^\\r]*?\\S[*_]*)(\\1)"
        }, { // simple links <url>
            token : ["text", "keyword", "text"],
            regex : "(<)("+
                "(?:https?|ftp|dict):[^'\">\\s]+"+
                "|"+
                "(?:mailto:)?[-.\\w]+\\@[-a-z0-9]+(?:\\.[-a-z0-9]+)*\\.[a-z]+"+
                ")(>)"
        }, {
            // embedded latex command
            token : "keyword",
            regex : "\\\\(?:[a-zA-z0-9]+|[^a-zA-z0-9])"
        }, {
            // embedded latex arg
            token : ["paren.keyword.operator", "text", "paren.keyword.operator"],
            regex : "(\\{)([^\\}]*)(\\})"
        }, {
            // pandoc citation with brackets
            token : "markup.list",
            regex : "\\[-?\\@[\\w\\d-]+\\]"
        }, {
            // pandoc citation
            token : "markup.list",
            regex : "-?\\@[\\w\\d-]+"
        }, {
            token : "text",
            regex : "[^\\*_%$`\\[#<>\\\\]+"
        }, {
            token : "text",
            regex : "\\\\"
        }, { // HR * - _
            token : "constant",
            regex : "^ {0,2}(?:(?: ?\\* ?){3,}|(?: ?\\- ?){3,}|(?: ?\\_ ?){3,})\\s*$",
            next: "allowBlock"
        }, { // list
            token : "text",
            regex : "^\\s{0,3}(?:[*+-]|\\d+\\.)\\s+",
            next  : "listblock-start"
        }, { // html comment
            token : "comment",
            regex : "<\\!--",
            next  : "html-comment"
        }, {
            include : "basic"
        }],

        "html-comment" : [{
           token: "comment",
           regex: "-->",
           next: "start"
        }, {
           defaultToken: "comment"
        }],

        // code block
        "allowBlock": [{
           token : "support.function",
           regex : "^ {4}.+",
           next : "allowBlock"
        }, {
           token : "empty",
           regex : "",
           next : "start"
        }],

        "header" : [{
            regex: "$",
            next : "start"
        }, {
            include: "basic"
        }, {
            defaultToken : "heading"
        }],

        "listblock-start" : [{
            token : "text",
            regex : /(?:\[[ x]\])?/,
            next  : "listblock"
        }],

        "listblock" : [ { // Lists only escape on completely blank lines.
            token : "empty_line",
            regex : "^$",
            next  : "start"
        }, { // list
            token : "text",
            regex : "^\\s{0,3}(?:[*+-]|\\d+\\.)\\s+",
            next  : "listblock-start"
        }, {
            include : "basic", noEscape: true
        }, { // Github style block
            token : "support.function",
            regex : "^\\s*```\\s*[a-zA-Z]*(?:{.*?\\})?\\s*$",
            next  : "githubblock"
        }, {
            defaultToken : "text" //do not use markup.list to allow stling leading `*` differntly
        }],

        "blockquote" : [ { // Blockquotes only escape on blank lines.
            token : "empty_line",
            regex : "^\\s*$",
            next  : "start"
        }, { // block quote
            token : "string.blockquote",
            regex : "^\\s*>\\s*(?:[*+-]|\\d+\\.)?\\s+",
            next  : "blockquote"
        }, {
            include : "basic", noEscape: true
        }, {
            defaultToken : "string.blockquote"
        }],

        "githubblock" : [ {
            token : "support.function",
            regex : "^\\s*```",
            next  : "start"
        }, {
            token : "support.function",
            regex : ".+"
        }],

         "fieldblock" : [{
            token : function(value) {
                var field = value.slice(0,-1);
                if (slideFields[field])
                    return "comment.doc.tag";
                else
                    return "text";
            },
            regex : "^" +"[\\w-]+\\:",
            next  : "fieldblockvalue"
        }, {
            token : "text",
            regex : "(?=.+)",
            next  : "start"
        }],

        "fieldblockvalue" : [{
            token : "text",
            regex : "$",
            next  : "fieldblock"
        }, {
            token : "text",
            regex : ".+"
        }],

        "mathjaxdisplay" : [{
            token : "markup.list",
            regex : "\\${2}",
            next  : "start"
        }, {
            token : "support.function",
            regex : "[^\\$]+"
        }],

        "mathjaxnativedisplay" : [{
            token : "markup.list",
            regex : "\\\\\\]",
            next  : "start"
        }, {
            token : "support.function",
            regex : "[\\s\\S]+?"
        }],

        "mathjaxinline" : [{
            token : "markup.list",
            regex : "\\$",
            next  : "start"
        }, {
            token : "support.function",
            regex : "[^\\$]+"
        }],

        "mathjaxnativeinline" : [{
            token : "markup.list",
            regex : "\\\\\\)",
            next  : "start"
        }, {
            token : "support.function",
            regex : "[\\s\\S]+?"
        }]

    };

    this.embedRules(JavaScriptHighlightRules, "jscode-", [{
        token : "support.function",
        regex : "^\\s*```",
        next  : "pop"
    }]);

    this.embedRules(HtmlHighlightRules, "htmlcode-", [{
        token : "support.function",
        regex : "^\\s*```",
        next  : "pop"
    }]);

    this.embedRules(CssHighlightRules, "csscode-", [{
        token : "support.function",
        regex : "^\\s*```",
        next  : "pop"
    }]);

    this.embedRules(XmlHighlightRules, "xmlcode-", [{
        token : "support.function",
        regex : "^\\s*```",
        next  : "pop"
    }]);

    this.normalizeRules();
};
oop.inherits(MarkdownHighlightRules, TextHighlightRules);

exports.MarkdownHighlightRules = MarkdownHighlightRules;
});
<commit_msg>allow lines containing only spaces to exit listblock state<commit_after>/*
 * markdown_highlight_rules.js
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * The Initial Developer of the Original Code is
 * Ajax.org B.V.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define("mode/markdown_highlight_rules", function(require, exports, module) {

var oop = require("ace/lib/oop");
var lang = require("ace/lib/lang");
var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;
var JavaScriptHighlightRules = require("ace/mode/javascript_highlight_rules").JavaScriptHighlightRules;
var XmlHighlightRules = require("ace/mode/xml_highlight_rules").XmlHighlightRules;
var HtmlHighlightRules = require("ace/mode/html_highlight_rules").HtmlHighlightRules;
var CssHighlightRules = require("ace/mode/css_highlight_rules").CssHighlightRules;

var escaped = function(ch) {
    return "(?:[^" + lang.escapeRegExp(ch) + "\\\\]|\\\\.)*";
}

function github_embed(tag, prefix) {
    return { // Github style block
        token : "support.function",
        regex : "^\\s*```" + tag + "\\s*$",
        push  : prefix + "start"
    };
}

var MarkdownHighlightRules = function() {

    var slideFields = lang.arrayToMap(
        ("title|author|date|rtl|depends|autosize|width|height|transition|transition-speed|font-family|css|class|navigation|incremental|left|right|id|audio|video|type|at|help-doc|help-topic|source|console|console-input|execute|pause")
            .split("|")
    );

    // regexp must not have capturing parentheses
    // regexps are ordered -> the first match is used

    this.$rules = {

        "basic" : [{
            token : "constant.language.escape",
            regex : /\\[\\`*_{}\[\]()#+\-.!]/
        }, { // code span `
            token : ["support.function", "support.function", "support.function"],
            regex : "(`+)(.*?[^`])(\\1)"
        }, { // reference
            token : ["text", "constant", "text", "url", "string", "text"],
            regex : "^([ ]{0,3}\\[)([^\\]]+)(\\]:\\s*)([^ ]+)(\\s*(?:[\"][^\"]+[\"])?(\\s*))$"
        }, { // link by reference
            token : ["text", "keyword", "text", "constant", "text"],
            regex : "(\\[)(" + escaped("]") + ")(\\]\s*\\[)("+ escaped("]") + ")(\\])"
        }, { // link by url
            token : ["text", "keyword", "text", "markup.underline", "string", "text"],
            regex : "(\\[)(" +                                        // [
                escaped("]") +                                    // link text
                ")(\\]\\()"+                                      // ](
                '((?:[^\\)\\s\\\\]|\\\\.|\\s(?=[^"]))*)' +        // href
                '(\\s*"' +  escaped('"') + '"\\s*)?' +            // "title"
                "(\\))"                                           // )
        }, { // strong ** __
            token : ["constant.numeric", "constant.numeric", "constant.numeric"],
            regex : "([*]{2}|[_]{2}(?=\\S))(.*?\\S[*_]*)(\\1)"
        }, { // emphasis * _
            token : ["constant.language.boolean", "constant.language.boolean", "constant.language.boolean"],
            regex : "([*]|[_](?=\\S))(.*?\\S[*_]*)(\\1)"
        }, { //
            token : ["text", "keyword", "text"],
            regex : "(<)("+
                "(?:https?|ftp|dict):[^'\">\\s]+"+
                "|"+
                "(?:mailto:)?[-.\\w]+\\@[-a-z0-9]+(?:\\.[-a-z0-9]+)*\\.[a-z]+"+
                ")(>)"
        }],

        start: [{
           token : "empty_line",
           regex : '^$',
           next: "allowBlock"
        }, { // code span
            token : ["support.function", "support.function", "support.function"],
            regex : "(`+)([^\\r]*?[^`])(\\1)"
        }, { // h1 with equals
            token: "markup.heading.1",
            regex: "^\\={3,}\\s*$",
            next: "fieldblock"
        }, { // h1
            token: "markup.heading.1",
            regex: "^=+(?=\\s*$)"
        }, { // h2
            token: "markup.heading.2",
            regex: "^\\-+(?=\\s*$)"
        }, {
            token : function(value) {
                return "markup.heading." + value.length;
            },
            regex : /^#{1,6}(?=\s*[^ #]|\s+#.)/,
            next : "header"
        },

        github_embed("(?:javascript|js)", "jscode-"),
        github_embed("xml", "xmlcode-"),
        github_embed("html", "htmlcode-"),
        github_embed("css", "csscode-"),

        { // Github style block
            token : "support.function",
            regex : "^\\s*```\\s*\\S*(?:{.*?\\})?\\s*$",
            next  : "githubblock"
        }, { // block quote
            token : "string.blockquote",
            regex : "^\\s*>\\s*(?:[*+-]|\\d+\\.)?\\s+",
            next  : "blockquote"
        },
        { // reference
            token : ["text", "constant", "text", "url", "string", "text"],
            regex : "^([ ]{0,3}\\[)([^\\]]+)(\\]:\\s*)([^ ]+)(\\s*(?:[\"][^\"]+[\"])?(\\s*))$"
        }, { // link by reference
            token : ["text", "keyword", "text", "constant", "text"],
            regex : "(\\[)((?:[[^\\]]*\\]|[^\\[\\]])*)(\\][ ]?(?:\\n[ ]*)?\\[)(.*?)(\\])"
        }, { // link by url
            token : ["text", "keyword", "text", "markup.underline", "string", "text"],
            regex : "(\\[)"+
                "(\\[[^\\]]*\\]|[^\\[\\]]*)"+
                "(\\]\\([ \\t]*)"+
                "(<?(?:(?:[^\\(]*?\\([^\\)]*?\\)\\S*?)|(?:.*?))>?)"+
                "((?:[ \t]*\"(?:.*?)\"[ \\t]*)?)"+
                "(\\))"
        }, { // HR *
            token : "constant",
            regex : "^[ ]{0,2}(?:[ ]?\\*[ ]?){3,}\\s*$"
        }, { // HR -
            token : "constant",
            regex : "^[ ]{0,2}(?:[ ]?\\-[ ]?){3,}\\s*$"
        }, { // HR _
            token : "constant",
            regex : "^[ ]{0,2}(?:[ ]?\\_[ ]?){3,}\\s*$"
        }, { // MathJax native display \[ ... \]
            token : "markup.list",
            regex : "\\\\\\[",
            next  : "mathjaxnativedisplay"
        }, { // MathJax native inline \( ... \)
            token : "markup.list",
            regex : "\\\\\\(",
            next  : "mathjaxnativeinline"
        }, { // $ escape
            token : "text",
            regex : "\\\\\\$"
        }, { // MathJax $$
            token : "markup.list",
            regex : "\\${2}",
            next  : "mathjaxdisplay"
        }, { // MathJax $...$ (org-mode style)
            token : ["markup.list","support.function","markup.list"],
            regex : "(\\$)" + "((?!\\s)[^$]*[^$\\s])" + "(\\$)" + "(?![\\w\\d`])"
        }, { // strong ** __
            token : ["constant.numeric", "constant.numeric", "constant.numeric"],
            regex : "([*]{2}|[_]{2}(?=\\S))([^\\r]*?\\S[*_]*)(\\1)"
        }, { // emphasis * _
            token : ["constant.language.boolean", "constant.language.boolean", "constant.language.boolean"],
            regex : "([*]|[_](?=\\S))([^\\r]*?\\S[*_]*)(\\1)"
        }, { // simple links <url>
            token : ["text", "keyword", "text"],
            regex : "(<)("+
                "(?:https?|ftp|dict):[^'\">\\s]+"+
                "|"+
                "(?:mailto:)?[-.\\w]+\\@[-a-z0-9]+(?:\\.[-a-z0-9]+)*\\.[a-z]+"+
                ")(>)"
        }, {
            // embedded latex command
            token : "keyword",
            regex : "\\\\(?:[a-zA-z0-9]+|[^a-zA-z0-9])"
        }, {
            // embedded latex arg
            token : ["paren.keyword.operator", "text", "paren.keyword.operator"],
            regex : "(\\{)([^\\}]*)(\\})"
        }, {
            // pandoc citation with brackets
            token : "markup.list",
            regex : "\\[-?\\@[\\w\\d-]+\\]"
        }, {
            // pandoc citation
            token : "markup.list",
            regex : "-?\\@[\\w\\d-]+"
        }, {
            token : "text",
            regex : "[^\\*_%$`\\[#<>\\\\]+"
        }, {
            token : "text",
            regex : "\\\\"
        }, { // HR * - _
            token : "constant",
            regex : "^ {0,2}(?:(?: ?\\* ?){3,}|(?: ?\\- ?){3,}|(?: ?\\_ ?){3,})\\s*$",
            next: "allowBlock"
        }, { // list
            token : "text",
            regex : "^\\s{0,3}(?:[*+-]|\\d+\\.)\\s+",
            next  : "listblock-start"
        }, { // html comment
            token : "comment",
            regex : "<\\!--",
            next  : "html-comment"
        }, {
            include : "basic"
        }],

        "html-comment" : [{
           token: "comment",
           regex: "-->",
           next: "start"
        }, {
           defaultToken: "comment"
        }],

        // code block
        "allowBlock": [{
           token : "support.function",
           regex : "^ {4}.+",
           next : "allowBlock"
        }, {
           token : "empty",
           regex : "",
           next : "start"
        }],

        "header" : [{
            regex: "$",
            next : "start"
        }, {
            include: "basic"
        }, {
            defaultToken : "heading"
        }],

        "listblock-start" : [{
            token : "text",
            regex : /(?:\[[ x]\])?/,
            next  : "listblock"
        }],

        "listblock" : [ { // Lists only escape on completely blank lines.
            token : "empty_line",
            regex : "^\\s*$",
            next  : "start"
        }, { // list
            token : "text",
            regex : "^\\s{0,3}(?:[*+-]|\\d+\\.)\\s+",
            next  : "listblock-start"
        }, {
            include : "basic", noEscape: true
        }, { // Github style block
            token : "support.function",
            regex : "^\\s*```\\s*[a-zA-Z]*(?:{.*?\\})?\\s*$",
            next  : "githubblock"
        }, {
            defaultToken : "text" //do not use markup.list to allow stling leading `*` differntly
        }],

        "blockquote" : [ { // Blockquotes only escape on blank lines.
            token : "empty_line",
            regex : "^\\s*$",
            next  : "start"
        }, { // block quote
            token : "string.blockquote",
            regex : "^\\s*>\\s*(?:[*+-]|\\d+\\.)?\\s+",
            next  : "blockquote"
        }, {
            include : "basic", noEscape: true
        }, {
            defaultToken : "string.blockquote"
        }],

        "githubblock" : [ {
            token : "support.function",
            regex : "^\\s*```",
            next  : "start"
        }, {
            token : "support.function",
            regex : ".+"
        }],

         "fieldblock" : [{
            token : function(value) {
                var field = value.slice(0,-1);
                if (slideFields[field])
                    return "comment.doc.tag";
                else
                    return "text";
            },
            regex : "^" +"[\\w-]+\\:",
            next  : "fieldblockvalue"
        }, {
            token : "text",
            regex : "(?=.+)",
            next  : "start"
        }],

        "fieldblockvalue" : [{
            token : "text",
            regex : "$",
            next  : "fieldblock"
        }, {
            token : "text",
            regex : ".+"
        }],

        "mathjaxdisplay" : [{
            token : "markup.list",
            regex : "\\${2}",
            next  : "start"
        }, {
            token : "support.function",
            regex : "[^\\$]+"
        }],

        "mathjaxnativedisplay" : [{
            token : "markup.list",
            regex : "\\\\\\]",
            next  : "start"
        }, {
            token : "support.function",
            regex : "[\\s\\S]+?"
        }],

        "mathjaxinline" : [{
            token : "markup.list",
            regex : "\\$",
            next  : "start"
        }, {
            token : "support.function",
            regex : "[^\\$]+"
        }],

        "mathjaxnativeinline" : [{
            token : "markup.list",
            regex : "\\\\\\)",
            next  : "start"
        }, {
            token : "support.function",
            regex : "[\\s\\S]+?"
        }]

    };

    this.embedRules(JavaScriptHighlightRules, "jscode-", [{
        token : "support.function",
        regex : "^\\s*```",
        next  : "pop"
    }]);

    this.embedRules(HtmlHighlightRules, "htmlcode-", [{
        token : "support.function",
        regex : "^\\s*```",
        next  : "pop"
    }]);

    this.embedRules(CssHighlightRules, "csscode-", [{
        token : "support.function",
        regex : "^\\s*```",
        next  : "pop"
    }]);

    this.embedRules(XmlHighlightRules, "xmlcode-", [{
        token : "support.function",
        regex : "^\\s*```",
        next  : "pop"
    }]);

    this.normalizeRules();
};
oop.inherits(MarkdownHighlightRules, TextHighlightRules);

exports.MarkdownHighlightRules = MarkdownHighlightRules;
});
<|endoftext|>