<commit_before>const Provider = require('./provider')
const {getProjectPaths, scanItemsForFilePath, scanItemsForBuffer} = require('../utils')

const Searcher = require('../searcher')
const Path = require('path')
const _ = require('underscore-plus')
let searcherIsAvailable = false

const Config = {
  supportDirectEdit: true,
  showColumnOnLineHeader: true,
  showProjectHeader: true,
  showFileHeader: true,
  itemHaveRange: true,
  showSearchOption: true,
  supportCacheItems: true,
  useFirstQueryAsSearchTerm: true,
  supportFilePathOnlyItemsUpdate: true,
  refreshOnDidStopChanging: true
}

module.exports = class Search {
  constructor (state) {
    // FIXME: This is set to true in spec to test easily
    // this.searchInOrdered = atom.inSpecMode()

    this.provider = Provider.create({
      name: this.constructor.name,
      state: state,
      config: Config,
      getItems: this.getItems.bind(this),
      willOpenUi: () => {
        // FIXME: Just to wait for initialization of provider.searchOptions
        this.searcher = new Searcher(this.provider.searchOptions)
      },
      didDestroy: () => {
        if (this.searcher) {
          this.searcher.cancel()
          this.searcher = null
        }
      },
      willSaveState: () => {
        return {projects: this.projects}
      }
    })
  }

  start (options = {}) {
    this.projects = this.projects || getProjectPaths(options.currentProject ? this.provider.editor : null)
    if (this.projects) {
      return this.provider.start(options)
    }
  }

  // Return promise
  search () {
    const projectsToSearch = this.projects.slice()
    const modifiedBuffers = atom.project.getBuffers().filter(buffer => buffer.isModified() && buffer.getPath())
    const modifiedBuffersScanned = new Set()
    const {searchRegex} = this.provider.searchOptions

    const scanBuffer = buffer => {
      if (!modifiedBuffersScanned.has(buffer)) {
        this.updateItems(scanItemsForBuffer(buffer, searchRegex))
        modifiedBuffersScanned.add(buffer)
      }
    }

    let resolveSearchPromise
    const searchPromise = new Promise(resolve => {
      resolveSearchPromise = resolve
    })

    let finished = 0
    const onFinish = project => {
      finished++
      // Append directory separator to avoid unwanted partial match.
      // make `atom` to `atom/` to avoid matches to project name like `atom-keymaps`.
      const isSameProject = buffer => buffer.getPath().startsWith(project + Path.sep)
      modifiedBuffers.filter(isSameProject).forEach(scanBuffer)

      if (projectsToSearch.length) {
        searchNextProject()
        return
      }

      if (finished === this.projects.length) {
        resolveSearchPromise()
      }
    }

    const updateItemsIfNotModified = items => {
      items = items.filter(item => !atom.project.isPathModified(item.filePath))
      this.updateItems(items)
    }

    const searchNextProject = () => {
      this.searcher.searchProject(projectsToSearch.shift(), updateItemsIfNotModified, onFinish)
    }

    if (this.searchInOrdered) {
      searchNextProject()
    } else {
      while (projectsToSearch.length) searchNextProject()
    }

    return searchPromise
  }

  updateItems (items) {
    if (this.searchInOrdered) items = _.sortBy(items, item => item.filePath)
    this.provider.updateItems(items)
  }

  async getItems ({filePath}) {
    this.searcher.cancel()
    const searcher = this.provider.getConfig('searcher')

    const executable = await this.isExecutable(searcher)
    if (!executable) {
      return []
    }

    const {searchRegex} = this.provider.searchOptions
    if (!searchRegex) {
      return []
    }

    this.searcher.setCommand(searcher)
    if (filePath) {
      if (atom.project.contains(filePath)) {
        return scanItemsForFilePath(filePath, searchRegex)
      } else {
        return []
      }
    } else {
      await this.search()
      return []
    }
  }

  async isExecutable (searcherCommand) {
    if (!searcherIsAvailable) {
      const status = await this.searcher.runCommandPromisified(searcherCommand)
      searcherIsAvailable = status === 0
      if (!searcherIsAvailable) {
        const message = [
          `atom-arrow`,
          `- \`${searcherCommand}\` is not available in your PATH.`,
          `- You can choose another searcherCommand from setting of narrow.`,
          `- Or install/add \`${searcherCommand}\` to PATH`
        ].join('\n')
        atom.notifications.addWarning(message, {dismissable: true})
      }
    }
    return searcherIsAvailable
  }
}
<commit_msg>cleanup<commit_after>const Provider = require('./provider')
const {getProjectPaths, scanItemsForFilePath, scanItemsForBuffer} = require('../utils')

const Searcher = require('../searcher')
const Path = require('path')
const _ = require('underscore-plus')
let searcherIsAvailable = false

const Config = {
  supportDirectEdit: true,
  showColumnOnLineHeader: true,
  showProjectHeader: true,
  showFileHeader: true,
  itemHaveRange: true,
  showSearchOption: true,
  supportCacheItems: true,
  useFirstQueryAsSearchTerm: true,
  supportFilePathOnlyItemsUpdate: true,
  refreshOnDidStopChanging: true
}

module.exports = class Search {
  constructor (state) {
    this.provider = Provider.create({
      name: this.constructor.name,
      state: state,
      config: Config,
      getItems: this.getItems.bind(this),
      willOpenUi: () => {
        // FIXME: Just to wait for initialization of provider.searchOptions
        this.searcher = new Searcher(this.provider.searchOptions)
      },
      didDestroy: () => {
        if (this.searcher) {
          this.searcher.cancel()
          this.searcher = null
        }
      },
      willSaveState: () => {
        return {projects: this.projects}
      }
    })
  }

  start (options = {}) {
    this.projects = this.projects || getProjectPaths(options.currentProject ? this.provider.editor : null)
    if (this.projects) {
      return this.provider.start(options)
    }
  }

  // Return promise
  search () {
    const modifiedBuffers = atom.project.getBuffers().filter(buffer => buffer.isModified() && buffer.getPath())
    const unscannedModifiedBuffers = new Set(modifiedBuffers)
    const filePathsForModifiedBuffer = new Set(modifiedBuffers.map(buffer => buffer.getPath()))
    const {searchRegex} = this.provider.searchOptions

    let resolveSearchPromise
    const searchPromise = new Promise(resolve => {
      resolveSearchPromise = resolve
    })

    let finished = 0
    const onFinish = project => {
      // Append directory separator to avoid unwanted partial match.
      // make `atom` to `atom/` to avoid matches to project name like `atom-keymaps`.
      const projectPrefix = project + Path.sep
      for (const buffer of unscannedModifiedBuffers) {
        if (buffer.getPath().startsWith(projectPrefix)) {
          this.provider.updateItems(scanItemsForBuffer(buffer, searchRegex))
          unscannedModifiedBuffers.delete(buffer)
        }
      }

      finished++
      if (finished === this.projects.length) {
        resolveSearchPromise()
      }
    }

    const onItems = items => {
      const itemsForNonModifiedFile = items.filter(item => !filePathsForModifiedBuffer.has(item.filePath))
      this.provider.updateItems(itemsForNonModifiedFile)
    }

    for (const project of this.projects) {
      this.searcher.searchProject(project, onItems, onFinish)
    }
    return searchPromise
  }

  async getItems ({filePath}) {
    this.searcher.cancel()
    const searcher = this.provider.getConfig('searcher')

    const executable = await this.isExecutable(searcher)
    if (!executable) {
      return []
    }

    const {searchRegex} = this.provider.searchOptions
    if (!searchRegex) {
      return []
    }

    this.searcher.setCommand(searcher)
    if (filePath) {
      if (atom.project.contains(filePath)) {
        return scanItemsForFilePath(filePath, searchRegex)
      } else {
        return []
      }
    } else {
      await this.search()
      return []
    }
  }

  async isExecutable (searcherCommand) {
    if (!searcherIsAvailable) {
      const status = await this.searcher.runCommandPromisified(searcherCommand)
      searcherIsAvailable = status === 0
      if (!searcherIsAvailable) {
        const message = [
          `atom-arrow`,
          `- \`${searcherCommand}\` is not available in your PATH.`,
          `- You can choose another searcherCommand from setting of narrow.`,
          `- Or install/add \`${searcherCommand}\` to PATH`
        ].join('\n')
        atom.notifications.addWarning(message, {dismissable: true})
      }
    }
    return searcherIsAvailable
  }
}
<|endoftext|>


<commit_before>const Promise = require('bluebird');
const request = Promise.promisify(require("request"));
const TorrentProvider = require('../torrent-provider');

class Rarbg extends TorrentProvider {

  _getScrapeDatas() {
    return {
      name: 'Rarbg',
      baseUrl: 'https://torrentapi.org',
      getTokenUrl: '/pubapi_v2.php?get_token=get_token&app_id=NodeTorrentSearchApi',
      searchUrl: '/pubapi_v2.php?app_id=NodeTorrentSearchApi&search_string={query}&category={cat}&mode=search&format=json_extended&sort=seeders&limit=100&token=',
      categories: {
        'All': '1;4;14;15;16;17;21;22;42;18;19;41;27;28;29;30;31;32;40;23;24;25;26;33;34;43;44;45;46;47;48;49;50;51;52',
        'Movies': '14;17;42;44;45;46;47;48;50;51;52',
        'XXX': '1;4',
        'Games': '1;27;28;29;30;31;32;40',
        'TV': '1;18;41;49',
        'Music': '1;23;24;25;26',
        'Apps': '1;33;34;43',
        'Books': '35'
      },
      defaultCategory: 'All',
      resultsPerPageCount: 100
    };
  }

  search(query, category, limit) {

    return this._ensureLogin()
      .then(() => {
        let url = this._getUrl(category, query);
        if (url === null) {
          return;
        }
        return request({url: url, headers: {'User-Agent': 'curl/7.37.0'}});
      })
      .then(response => {
        let results = JSON.parse(response.body).torrent_results;
        return results && results.map(r => {
          return {
            provider: this.scrapeDatas.name,
            title: r.title,
            time: r.pubdate,
            seeds: r.seeders,
            peers: r.leechers,
            size: this._humanFileSize(r.size),
            magnet: r.download,
            desc: r.info_page
          };
        });
      });
  }

  getTorrentDetails(torrent) {
    throw new Error("Not implemented");
  }

  _ensureLogin() {
    if (!this.lastLoginTime || (Date.now() - this.lastLoginTime) > 840000) {
       return request({url: this.scrapeDatas.baseUrl + this.scrapeDatas.getTokenUrl, headers: {'User-Agent': 'curl/7.37.0'}})
        .then(r => {
          this.lastLoginTime = Date.now();
          let searchUrl = this.scrapeDatas.searchUrl;
          this.scrapeDatas.searchUrl = searchUrl.substr(0, searchUrl.lastIndexOf('=') + 1) + JSON.parse(r.body).token;
        });
    }
    return Promise.resolve();
  }

  _downloadTorrent(torrent) {
    throw new Error("Not implemented");
  }

  _humanFileSize(bytes, si) {
    let thresh = si ? 1000 : 1024;
    if (bytes < thresh) return bytes + ' B';
    let units = si ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
    let u = -1;
    do {
      bytes /= thresh;
      ++u;
    } while (bytes >= thresh);
    return bytes.toFixed(1) + ' ' + units[u];
  }

}

module.exports = Rarbg;
<commit_msg>Add wait time of 2 seconds<commit_after>const Promise = require('bluebird');
const request = Promise.promisify(require("request"));
const TorrentProvider = require('../torrent-provider');

class Rarbg extends TorrentProvider {

  _getScrapeDatas() {
    return {
      name: 'Rarbg',
      baseUrl: 'https://torrentapi.org',
      getTokenUrl: '/pubapi_v2.php?get_token=get_token&app_id=NodeTorrentSearchApi',
      searchUrl: '/pubapi_v2.php?app_id=NodeTorrentSearchApi&search_string={query}&category={cat}&mode=search&format=json_extended&sort=seeders&limit=100&token=',
      categories: {
        'All': '1;4;14;15;16;17;21;22;42;18;19;41;27;28;29;30;31;32;40;23;24;25;26;33;34;43;44;45;46;47;48;49;50;51;52',
        'Movies': '14;17;42;44;45;46;47;48;50;51;52',
        'XXX': '1;4',
        'Games': '1;27;28;29;30;31;32;40',
        'TV': '1;18;41;49',
        'Music': '1;23;24;25;26',
        'Apps': '1;33;34;43',
        'Books': '35'
      },
      defaultCategory: 'All',
      resultsPerPageCount: 100
    };
  }

  search(query, category, limit) {

    return this._ensureLogin()
      .then(() => {
        let url = this._getUrl(category, query);
        if (url === null) {
          return;
        }
        return request({url: url, headers: {'User-Agent': 'curl/7.37.0'}});
      })
      .then(response => {
        let results = JSON.parse(response.body).torrent_results;
        return results && results.map(r => {
          return {
            provider: this.scrapeDatas.name,
            title: r.title,
            time: r.pubdate,
            seeds: r.seeders,
            peers: r.leechers,
            size: this._humanFileSize(r.size),
            magnet: r.download,
            desc: r.info_page
          };
        });
      });
  }

  getTorrentDetails(torrent) {
    throw new Error("Not implemented");
  }

  _ensureLogin() {
    if (!this.lastLoginTime || (Date.now() - this.lastLoginTime) > 840000) {
       return request({url: this.scrapeDatas.baseUrl + this.scrapeDatas.getTokenUrl, headers: {'User-Agent': 'curl/7.37.0'}})
        .then(r => {
            //wait 2 seconds to avoid doing more than 1 req per 2 secs
          const waitTill = new Date(new Date().getTime() + 2 * 1000);
          while(waitTill > new Date()){}

          this.lastLoginTime = Date.now();
          let searchUrl = this.scrapeDatas.searchUrl;
          this.scrapeDatas.searchUrl = searchUrl.substr(0, searchUrl.lastIndexOf('=') + 1) + JSON.parse(r.body).token;
        });
    }
    return Promise.resolve();
  }

  _downloadTorrent(torrent) {
    throw new Error("Not implemented");
  }

  _humanFileSize(bytes, si) {
    let thresh = si ? 1000 : 1024;
    if (bytes < thresh) return bytes + ' B';
    let units = si ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
    let u = -1;
    do {
      bytes /= thresh;
      ++u;
    } while (bytes >= thresh);
    return bytes.toFixed(1) + ' ' + units[u];
  }

}

module.exports = Rarbg;
<|endoftext|>


<commit_before>  function initAutocomplete() {
    // Create the autocomplete object, restricting the search to geographical
    // location types.
    autocomplete = new google.maps.places.Autocomplete(
        (document.getElementById('autocomplete')),
        {types: ['geocode']});

    // When the user selects an address from the dropdown, populate the address
    // fields in the form.
    autocomplete.addListener('place_changed', searchFromAddress);
  }

  function searchFromAddress() {
    var place = autocomplete.getPlace();
    var coords  = { lat: place.geometry.location.lat(), lng: place.geometry.location.lng() },
        query   = jQuery.param(coords);
    window.location = window.location + 'search?' + query;
  }

$(document).ready(function() {
  function getLocation() {
    if (navigator.geolocation) {
      var spinner = ''
      $('button.geolocation').html(spinner)

      navigator.geolocation.getCurrentPosition(showPosition, showError)
    } else {
      var error = " Not supported by your browser.";
      $('button.geolocation').html(error)
    }
  }

  function showPosition(position) {
    if (position.coords) {
      var coords  = { lat: position.coords.latitude, lng: position.coords.longitude },
          query   = jQuery.param(coords);
      window.location = window.location + 'search?' + query;
    } else {
      var error = " Couldn't find your location.";
      $('button.geolocation').html(error);
    }
  }

  function showError(error) {
    switch(error.code) {
      case error.PERMISSION_DENIED:
        var error = " Browser denied location lookup.";
        break;
      case error.POSITION_UNAVAILABLE:
        var error = " Location information is unavailable.";
        break;
      case error.TIMEOUT:
        var error = " Timeout when looking up location.";
        break;
      case error.UNKNOWN_ERROR:
        var error = " Unknown error :-(";
        break;
    }
    $('button.geolocation').html(error);
  }

  $('button.geolocation').on('click', function() {
    getLocation()
  })

})
<commit_msg>Fix indentation<commit_after>function initAutocomplete() {
  // Create the autocomplete object, restricting the search to geographical
  // location types.
  autocomplete = new google.maps.places.Autocomplete(
      (document.getElementById('autocomplete')),
      {types: ['geocode']});

  // When the user selects an address from the dropdown, populate the address
  // fields in the form.
  autocomplete.addListener('place_changed', searchFromAddress);
}

function searchFromAddress() {
  var place = autocomplete.getPlace();
  var coords  = { lat: place.geometry.location.lat(), lng: place.geometry.location.lng() },
      query   = jQuery.param(coords);
  window.location = window.location + 'search?' + query;
}

  function searchFromAddress() {
    var place = autocomplete.getPlace();
    var coords  = { lat: place.geometry.location.lat(), lng: place.geometry.location.lng() },
        query   = jQuery.param(coords);
    window.location = window.location + 'search?' + query;
  }

$(document).ready(function() {
  function getLocation() {
    if (navigator.geolocation) {
      var spinner = ''
      $('button.geolocation').html(spinner)

      navigator.geolocation.getCurrentPosition(showPosition, showError)
    } else {
      var error = " Not supported by your browser.";
      $('button.geolocation').html(error)
    }
  }

  function showPosition(position) {
    if (position.coords) {
      var coords  = { lat: position.coords.latitude, lng: position.coords.longitude },
          query   = jQuery.param(coords);
      window.location = window.location + 'search?' + query;
    } else {
      var error = " Couldn't find your location.";
      $('button.geolocation').html(error);
    }
  }

  function showError(error) {
    switch(error.code) {
      case error.PERMISSION_DENIED:
        var error = " Browser denied location lookup.";
        break;
      case error.POSITION_UNAVAILABLE:
        var error = " Location information is unavailable.";
        break;
      case error.TIMEOUT:
        var error = " Timeout when looking up location.";
        break;
      case error.UNKNOWN_ERROR:
        var error = " Unknown error :-(";
        break;
    }
    $('button.geolocation').html(error);
  }

  $('button.geolocation').on('click', function() {
    getLocation()
  })

})
<|endoftext|>


<commit_before>/* call using the following enclosure:
(function(){
  var url = 'https://rawgit.com/jamesona/SEO-Tools/master/am-dashboard/dashboard.js';
  document.head.appendChild(document.createElement('script')).src=url;
  function initialize(){if (typeof(Dashboard) !== 'undefined') {var db = new Dashboard()} else {setTimeout(function(){initialize()}, 100);}}
  initialize();
})();
*/

function Dashboard() {
	var self = this;
	window.addEventListener("beforeunload", function(){
		if (self.Tickets.ticketArray) {
			localStorage.ticketCache = JSON.stringify(self.Tickets.ticketArray);
		}
	});
	if (localStorage.ticketCache) self.Tickets.ticketArray = JSON.parse(localStorage.ticketCache);
	this.createElement = function(parent, tag, attributes) {
		var element = parent.appendChild(document.createElement(tag));
		for (var attribute in attributes) {
			if (attributes.hasOwnProperty(attribute)) {
				element[attribute] = attributes[attribute];
			}
		}
		return element;
	};

	this.openClient = function(client) {
		ko.dataFor(app).showManageCustomer(client);
	};

	this.closeClient = function() {
		var buttons = document.getElementsByClassName('close'),
		i = buttons.length - 1;
		if (i >= 1) buttons[i - 1].click();
	};

	this.calendar = function(month, year, data) {
		if (typeof(month) == Object) data = month, month = null;
		this.current_date = new Date();
		this.day_labels = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
		this.month_labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
		this.month = (isNaN(month) || month === null) ? this.current_date.getMonth() : month;
		this.year = (isNaN(year) || year === null) ? this.current_date.getFullYear() : year;
		this.draw = function(ele){
	  		if (this.month > 11) {
	  			this.month -= 12;
	  			this.year += 1;
	  		} else if (month < 0) {
	  			this.month += 12;
	  			this.year -= 1;
	  		}
	  		// get dates
	  		var startingDay = new Date(this.year, this.month, 1).getDay(),
	  		endingDate = new Date(this.year, this.month + 1, 0),
	  		monthLength = endingDate.getDate(),
	  		inLastRow = 6 - endingDate.getDay();

	  		// generate header
	  	  	this.table = document.createElement('table');
	  		this.head = document.createElement('thead');
	  		this.prev = document.createElement('th');
	  		this.next = document.createElement('th');
	  		this.title = document.createElement('th');
	  		this.days = document.createElement('tr');
	  		this.body = document.createElement('tbody');
	  		this.cells = '';
	  		this.table.setAttribute('class', 'calendar');
	  		this.table.appendChild(this.head);
	  		this.head.appendChild(this.prev);
	  		this.prev.innerHTML = "«";
	  		this.prev.id = 'prev';
	  		this.head.appendChild(this.title);
	  		this.head.appendChild(this.next);
	  		this.next.innerHTML = "»";
	  		this.next.id = 'next';
	  		this.table.appendChild(this.days);
	  		this.title.innerHTML = this.month_labels[this.month] + " " + this.year;
	  		this.title.setAttribute('colspan', '5');
	  		this.days.setAttribute('class', 'header');
	  		for (var i = 0; i <= 6; i++ ) this.cells += '' + this.day_labels[i] + '	';
	  		this.days.innerHTML = this.cells;

	  		//generate calendar
	  		var html = '
';
	  		if ( startingDay ) html += '	';
	  		for (var day = 1; day <= monthLength; day++) {
	  		html += '
' + day + '
';
	  		//if data argument present, append key value for current day
	  		if (data) {
	  			var today = (this.month+1)+'/'+day+'/'+this.year;
	  			if (data[today]) html += '
'+Object.keys(data[today]).length+' Clients
';
	  		}
	  		html += '	';
	  		if ( (day + startingDay) % 7 === 0 && day != monthLength ) html += '

';
	  		}
	  		if ( inLastRow ) html += '	';
	  		html += '
';
	  		this.table.innerHTML += html;
	  		if (ele) {
	  			ele.innerHTML = this.table.outerHTML
	  		} else {
	  			return this.table.outerHTML
	  		}
	  		// save reference to dom node in object
	  		this.node = ele;
	  		// save reference to calendar object for enclosure scope
	  		var cal = this;
	      		(function(){
	  			// save calendar object reference for listeners
	  			var self = this;
	        		self.prev.addEventListener('click', function(){
	  				cal.month--;
	          			cal.draw(cal.node);
	        		});
	  			self.next.addEventListener('click', function(){
	          			cal.month++;
	  				cal.draw(cal.node);
	        		});
			      	document.onkeydown = function(e) {
			        	e = e || window.event;
			          	if (e.keyCode == '37') {
			        		// left arrow
			        		cal.month--;
			        		cal.draw(cal.node);
			          	} else if (e.keyCode == '39') {
			            		// right arrow
			            		cal.month++;
			        		cal.draw(cal.node);
			          	}
			        };
	      		})();
	  	};
	};
	this.HTML = {};
	this.HTML.dashboard = this.createElement(document.body, 'div', {
		className: 'navbar navbar-inverse navbar-fixed-bottom',
		id: 'dashboard',
	});
	this.HTML.style = this.createElement(this.HTML.dashboard, 'link', {
		rel: 'stylesheet',
		type: 'text/css',
		href: 'https://rawgit.com/jamesona/SEO-Tools/master/am-dashboard/dashboard.css',
	});
	this.HTML.nav = this.createElement(this.HTML.dashboard, 'ul', {
		className: 'nav navbar-nav',
	});
	this.HTML.tools = this.createElement(this.HTML.nav, 'li', {
		innerHTML: 'Tools',
		className: 'dropup',
	});
	this.HTML.toolsMenu = this.createElement(this.HTML.tools, 'ul', {
		className: 'dropdown-menu',
	});
	this.HTML.tickets = this.createElement(this.HTML.nav, 'li', {
		innerHTML: 'Tickets',
		className: 'dropup',
	});
	this.HTML.ticketsMenu = this.createElement(this.HTML.tickets, 'ul', {
		className: 'dropdown-menu',
	});
	this.HTML.ticketCalendar = this.createElement(this.HTML.ticketsMenu, 'li', {
		innerHTML: 'Calendar',
		onclick: function(){
			var node = bootbox.alert('none')[0].children[0].children[0].children[0],
			data = self.Tickets.sortTickets(),
			calendar = new self.calendar(data);
			calendar.draw(node);
		}
	});
	this.HTML.critical = this.createElement(this.HTML.nav, 'li', {
		innerHTML: 'Click to get Critical',
		id: 'critical',
		onclick: function() {
			var criticals = self.Tickets.getCritical();
			if (criticals) {
				this.innerHTML = 'Critical Tickets: ' + criticals.length + '';
			} else {
				this.innerHTML = 'Error loading tickets!';
			}

		},
	});

	this.Tickets = {
		getTickets: function() {
			//get tickets
			if (typeof(ko.dataFor(app).contentViewModel().myTickets) === "function"){
				self.Tickets.ticketArray = ko.dataFor(app).contentViewModel().myTickets();
			} else if (localStorage.ticketCache) {
				self.Tickets.ticketArray = JSON.parse(localStorage.ticketCache);
			}
			//return results
			if (self.Tickets.ticketArray) {
				localStorage.ticketCache = JSON.stringify(self.Tickets.ticketArray);
				return self.Tickets.ticketArray;
			} else {
				alert('Unable to access tickets at this time!');
				return [];
			}
		},
		getCritical: function() {
			var tickets = this.getTickets(),
			critical = [];
			for (var i = 0; i < tickets.length; i++) {
				if (tickets[i].ScheduledEndDate < new Date()) {
					critical.push(tickets[i]);
				}
			}
			if (tickets.length > 0){
				return critical;
			} else {
				return false;
			}
		},
		sortTickets: function(tickets){
			if (! tickets){
				var tickets = this.getTickets();
			}
			var data = {};
			for (var i=0;i<tickets.length;i++){
				var ticket = tickets[i],
				date = new Date(ticket.ScheduledEndDate),
				day = date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear();
				if (! data[day]){ data[day] = []};
				data[day].push(ticket);
			}
			return data;
		},
		listTickets: function(tickets){
			var list = document.createElement('ul');
			for (var i=0;i<tickets.length;i++){
				var ticket = tickets[i],
				listItem = document.createElement('li'),
				text = ticket.CompanyName+': '+ticket.TicketTypeName;
				text += ' (Due: '+(ticket.ScheduledEndDate.getMonth()+1);
				text += '/'+ticket.ScheduledEndDate.getDate()+'/';
				text += ticket.ScheduledEndDate.getFullYear()+')';
				listItem.innerHTML = text;
				list.appendChild(listItem);
			}
			return list;
		},
	}
}
<commit_msg>Update dashboard.js<commit_after>/* call using the following enclosure:
(function(){
  var url = 'https://rawgit.com/jamesona/SEO-Tools/master/am-dashboard/dashboard.js';
  document.head.appendChild(document.createElement('script')).src=url;
  function initialize(){if (typeof(Dashboard) !== 'undefined') {var db = new Dashboard()} else {setTimeout(function(){initialize()}, 100);}}
  initialize();
})();
*/

function Dashboard() {
	var self = this;
	this.createElement = function(parent, tag, attributes) {
		var element = parent.appendChild(document.createElement(tag));
		for (var attribute in attributes) {
			if (attributes.hasOwnProperty(attribute)) {
				element[attribute] = attributes[attribute];
			}
		}
		return element;
	};

	this.openClient = function(client) {
		ko.dataFor(app).showManageCustomer(client);
	};

	this.closeClient = function() {
		var buttons = document.getElementsByClassName('close'),
		i = buttons.length - 1;
		if (i >= 1) buttons[i - 1].click();
	};

	this.calendar = function(month, year, data) {
		if (typeof(month) == Object) data = month, month = null;
		this.current_date = new Date();
		this.day_labels = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
		this.month_labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
		this.month = (isNaN(month) || month === null) ? this.current_date.getMonth() : month;
		this.year = (isNaN(year) || year === null) ? this.current_date.getFullYear() : year;
		this.draw = function(ele){
	  		if (this.month > 11) {
	  			this.month -= 12;
	  			this.year += 1;
	  		} else if (month < 0) {
	  			this.month += 12;
	  			this.year -= 1;
	  		}
	  		// get dates
	  		var startingDay = new Date(this.year, this.month, 1).getDay(),
	  		endingDate = new Date(this.year, this.month + 1, 0),
	  		monthLength = endingDate.getDate(),
	  		inLastRow = 6 - endingDate.getDay();

	  		// generate header
	  	  	this.table = document.createElement('table');
	  		this.head = document.createElement('thead');
	  		this.prev = document.createElement('th');
	  		this.next = document.createElement('th');
	  		this.title = document.createElement('th');
	  		this.days = document.createElement('tr');
	  		this.body = document.createElement('tbody');
	  		this.cells = '';
	  		this.table.setAttribute('class', 'calendar');
	  		this.table.appendChild(this.head);
	  		this.head.appendChild(this.prev);
	  		this.prev.innerHTML = "«";
	  		this.prev.id = 'prev';
	  		this.head.appendChild(this.title);
	  		this.head.appendChild(this.next);
	  		this.next.innerHTML = "»";
	  		this.next.id = 'next';
	  		this.table.appendChild(this.days);
	  		this.title.innerHTML = this.month_labels[this.month] + " " + this.year;
	  		this.title.setAttribute('colspan', '5');
	  		this.days.setAttribute('class', 'header');
	  		for (var i = 0; i <= 6; i++ ) this.cells += '' + this.day_labels[i] + '	';
	  		this.days.innerHTML = this.cells;

	  		//generate calendar
	  		var html = '
';
	  		if ( startingDay ) html += '	';
	  		for (var day = 1; day <= monthLength; day++) {
	  		html += '
' + day + '
';
	  		//if data argument present, append key value for current day
	  		if (data) {
	  			var today = (this.month+1)+'/'+day+'/'+this.year;
	  			if (data[today]) html += '
'+Object.keys(data[today]).length+' Clients
';
	  		}
	  		html += '	';
	  		if ( (day + startingDay) % 7 === 0 && day != monthLength ) html += '

';
	  		}
	  		if ( inLastRow ) html += '	';
	  		html += '
';
	  		this.table.innerHTML += html;
	  		if (ele) {
	  			ele.innerHTML = this.table.outerHTML
	  		} else {
	  			return this.table.outerHTML
	  		}
	  		// save reference to dom node in object
	  		this.node = ele;
	  		// save reference to calendar object for enclosure scope
	  		var cal = this;
	      		(function(){
	  			// save calendar object reference for listeners
	  			var self = this;
	        		self.prev.addEventListener('click', function(){
	  				cal.month--;
	          			cal.draw(cal.node);
	        		});
	  			self.next.addEventListener('click', function(){
	          			cal.month++;
	  				cal.draw(cal.node);
	        		});
			      	document.onkeydown = function(e) {
			        	e = e || window.event;
			          	if (e.keyCode == '37') {
			        		// left arrow
			        		cal.month--;
			        		cal.draw(cal.node);
			          	} else if (e.keyCode == '39') {
			            		// right arrow
			            		cal.month++;
			        		cal.draw(cal.node);
			          	}
			        };
	      		})();
	  	};
	};
	this.HTML = {};
	this.HTML.dashboard = this.createElement(document.body, 'div', {
		className: 'navbar navbar-inverse navbar-fixed-bottom',
		id: 'dashboard',
	});
	this.HTML.style = this.createElement(this.HTML.dashboard, 'link', {
		rel: 'stylesheet',
		type: 'text/css',
		href: 'https://rawgit.com/jamesona/SEO-Tools/master/am-dashboard/dashboard.css',
	});
	this.HTML.nav = this.createElement(this.HTML.dashboard, 'ul', {
		className: 'nav navbar-nav',
	});
	this.HTML.tools = this.createElement(this.HTML.nav, 'li', {
		innerHTML: 'Tools',
		className: 'dropup',
	});
	this.HTML.toolsMenu = this.createElement(this.HTML.tools, 'ul', {
		className: 'dropdown-menu',
	});
	this.HTML.tickets = this.createElement(this.HTML.nav, 'li', {
		innerHTML: 'Tickets',
		className: 'dropup',
	});
	this.HTML.ticketsMenu = this.createElement(this.HTML.tickets, 'ul', {
		className: 'dropdown-menu',
	});
	this.HTML.ticketCalendar = this.createElement(this.HTML.ticketsMenu, 'li', {
		innerHTML: 'Calendar',
		onclick: function(){
			var node = bootbox.alert('none')[0].children[0].children[0].children[0],
			data = self.Tickets.sortTickets(),
			calendar = new self.calendar(data);
			calendar.draw(node);
		}
	});
	this.HTML.critical = this.createElement(this.HTML.nav, 'li', {
		innerHTML: 'Click to get Critical',
		id: 'critical',
		onclick: function() {
			var criticals = self.Tickets.getCritical();
			if (criticals) {
				this.innerHTML = 'Critical Tickets: ' + criticals.length + '';
			} else {
				this.innerHTML = 'Error loading tickets!';
			}

		},
	});

	this.Tickets = {
		getTickets: function() {
			//get tickets
			if (typeof(ko.dataFor(app).contentViewModel().myTickets) === "function"){
				self.Tickets.ticketArray = ko.dataFor(app).contentViewModel().myTickets();
			} else if (localStorage.ticketCache) {
				self.Tickets.ticketArray = JSON.parse(localStorage.ticketCache);
			}
			//return results
			if (self.Tickets.ticketArray) {
				localStorage.ticketCache = JSON.stringify(self.Tickets.ticketArray);
				return self.Tickets.ticketArray;
			} else {
				alert('Unable to access tickets at this time!');
				return [];
			}
		},
		getCritical: function() {
			var tickets = this.getTickets(),
			critical = [];
			for (var i = 0; i < tickets.length; i++) {
				if (tickets[i].ScheduledEndDate < new Date()) {
					critical.push(tickets[i]);
				}
			}
			if (tickets.length > 0){
				return critical;
			} else {
				return false;
			}
		},
		sortTickets: function(tickets){
			if (! tickets){
				var tickets = this.getTickets();
			}
			var data = {};
			for (var i=0;i<tickets.length;i++){
				var ticket = tickets[i],
				date = new Date(ticket.ScheduledEndDate),
				day = date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear();
				if (! data[day]){ data[day] = []};
				data[day].push(ticket);
			}
			return data;
		},
		listTickets: function(tickets){
			var list = document.createElement('ul');
			for (var i=0;i<tickets.length;i++){
				var ticket = tickets[i],
				listItem = document.createElement('li'),
				text = ticket.CompanyName+': '+ticket.TicketTypeName;
				text += ' (Due: '+(ticket.ScheduledEndDate.getMonth()+1);
				text += '/'+ticket.ScheduledEndDate.getDate()+'/';
				text += ticket.ScheduledEndDate.getFullYear()+')';
				listItem.innerHTML = text;
				list.appendChild(listItem);
			}
			return list;
		},
	}
	window.addEventListener("beforeunload", function(){
		if (self.Tickets.ticketArray) {
			localStorage.ticketCache = JSON.stringify(self.Tickets.ticketArray);
		}
	});
	if (localStorage.ticketCache) self.Tickets.ticketArray = JSON.parse(localStorage.ticketCache);
}
<|endoftext|>


<commit_before>
<commit_msg>Update dashboard.js<commit_after>
/* call using this enclosure
  (function(){
    var url = 'https://rawgit.com/jamesona/SEO-Tools/master/am-dashboard/dashboard.js';
    document.head.appendChild(document.createElement('script')).src=url;
    function initialize(){
      if (typeof(Dashboard) !== 'undefined' && typeof(ko) !== 'undefined' && ko.dataFor(app) !== undefined) {
          //console.log('Knockout:');console.log(ko);console.log('App:');console.log(ko.dataFor(app));
          db = new Dashboard(ko.dataFor(app))
      } else {
          setTimeout(function(){initialize()}, 100);
      }
    }
    initialize();
  })();
*/

function Dashboard(app) {
  var self = this;
  this.app = app;
  console.log(this.app);
  this.Tools = {
    bobParse: function(raw){
      var clients = [], data = {};
      // exit on null entry
      if ( raw === null ) return;
      for (var cells = raw.replace(/Basic[\r\n\s\ta-z]*Partner ID[\t\s]+/i, '').split(/\t/),
        client = {}, cols = ['Account ID',	'Account Start Date',	'Account Bucket',	'Account Spend',
        'Date of Next Ticket',	'Engaged Status',	'Timezone',	'Welcome Call',	'Keyword Research',
        'Local Profile Tab',	'Obtain or Create Google Logins',	'Create and Verify Google Profile',
        'Obtain Site Access',	'Implement Onsite Edits',	'Create Yahoo Account',	'Create and Verify Yahoo Profile',
        'Create and Verify Bing Profile',	'Install Analytics',	'Company Name',	'Contact Name',	'Website URL',
        'Email Address',	'Phone Number',	'Partner ID',];
        cells.length>0;){
        var keys = Object.keys(client).length;
        if (keys<cols.length-1){
          var param = cols[keys];
          client[param] = cells[0];
          cells.shift();
        } else {
          client.count = keys;
          clients.push(client);
          client = {};
        }
      }
      for (var i=0;i<clients.length;i++){
        var date = clients[i]['Date of Next Ticket'];
        if (data[date] === undefined) data[date] = [];
        data[date].push(clients[i]);
      }
      return data;
    },
    bobCal: function(){},
    todoistExport: function(){
      if (ko.dataFor(window.app) !== undefined){
        var view = ko.dataFor(window.app).contentViewModel();
      } else if (ko.dataFor(self.app) !== undefined){
        var view = ko.dataFor(self.app).contentViewModel();
      }
      if (! view.hasOwnProperty('customersDataTable')){
        bootbox.alert('No client in active view.\nTry running this tool while viewing a client.');
        return 1;
      } else {
        var data = view.customersDataTable.dataSource(),
        taskDate = function(day){
          var days = [new Date(),new Date(),new Date()];
          if (days[0].getDay() == 5) {
            days[1].setDate(days[0].getDate()+3);
            days[2].setDate(days[0].getDate()+4);
          } else if (days[0].getDay() == 4) {
            days[1].setDate(days[0].getDate()+1);
            days[2].setDate(days[0].getDate()+4);
          } else {
            days[1].setDate(days[0].getDate()+1);
            days[2].setDate(days[0].getDate()+2);
          }
          return 'date '+days[day].toDateString().substring(4);
        },
        text = data.CustomerId+' - '+data.Name;
        text += '[[NOTE]]: https://launchpad.boostability.com/#customerservice/customersearch/'+data.CustomerId;
        text += '\n...'+data.CustomerId+' Welcome Call [['+taskDate(2)+']]';
        text += '\n......'+data.CustomerId+' 1st Welcome Call [['+taskDate(0)+']]';
        text += '\n......'+data.CustomerId+' 1st Welcome Email [['+taskDate(0)+']]';
        text += '\n......'+data.CustomerId+' 2nd Welcome Call [['+taskDate(1)+']]';
        text += '\n......'+data.CustomerId+' 2nd Welcome Email [['+taskDate(1)+']]';
        text += '\n......'+data.CustomerId+' 3rd Welcome Call [['+taskDate(2)+']]';
        text += '\n......'+data.CustomerId+' 3rd Welcome Email [['+taskDate(2)+']]';
        text += '\n...'+data.CustomerId+' Keyword Research';
        text += '\n...'+data.CustomerId+' Local Profile';
        bootbox.alert(text);
      }
    },
    openClient: function(client) {
      self.app.showManageCustomer(client);
    },
    closeClient: function() {
      var buttons = document.getElementsByClassName('close'),
      i = buttons.length - 1;
      if (i >= 1) buttons[i - 1].click();
    },
    createElement: function(parent, tag, attributes) {
      var element = parent.appendChild(document.createElement(tag));
      for (var attribute in attributes) {
        if (attributes.hasOwnProperty(attribute)) {
          element[attribute] = attributes[attribute];
        }
      }
      return element;
    },
  };
  this.Tickets = {
    calendar: function(month, year, data) {
      console.log(data);
      if (typeof(month) == Object) {data = month, month = null;}
      this.current_date = new Date();
      this.day_labels = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
      this.month_labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
      this.month = (isNaN(month) || month === null) ? this.current_date.getMonth() : month;
      this.year = (isNaN(year) || year === null) ? this.current_date.getFullYear() : year;
      this.draw = function(ele){
          if (this.month > 11) {
            this.month -= 12;
            this.year += 1;
          } else if (month < 0) {
            this.month += 12;
            this.year -= 1;
          }
          // get dates
          var startingDay = new Date(this.year, this.month, 1).getDay(),
          endingDate = new Date(this.year, this.month + 1, 0),
          monthLength = endingDate.getDate(),
          inLastRow = 6 - endingDate.getDay();

          // generate header
          this.table = document.createElement('table');
          this.head = document.createElement('thead');
          this.prev = document.createElement('th');
          this.next = document.createElement('th');
          this.title = document.createElement('th');
          this.days = document.createElement('tr');
          this.body = document.createElement('tbody');
          this.cells = '';
          this.table.setAttribute('class', 'calendar');
          this.table.appendChild(this.head);
          this.head.appendChild(this.prev);
          this.prev.innerHTML = "«";
          this.prev.id = 'prev';
          this.head.appendChild(this.title);
          this.head.appendChild(this.next);
          this.next.innerHTML = "»";
          this.next.id = 'next';
          this.table.appendChild(this.days);
          this.title.innerHTML = this.month_labels[this.month] + " " + this.year;
          this.title.setAttribute('colspan', '5');
          this.days.setAttribute('class', 'header');
          for (var i = 0; i <= 6; i++ ) this.cells += '' + this.day_labels[i] + '	';
          this.days.innerHTML = this.cells;

          //generate calendar
          var html = '
';
          if ( startingDay ) html += '	';
          for (var day = 1; day <= monthLength; day++) {
          html += '
' + day + '
';
          //if data argument present, append key value for current day
          if (data) {
            var today = (this.month+1)+'/'+day+'/'+this.year;
            if (data[today]) html += '
'+Object.keys(data[today]).length+' Clients
';
          }
          html += '	';
          if ( (day + startingDay) % 7 === 0 && day != monthLength ) html += '

';
          }
          if ( inLastRow ) html += '	';
          html += '
';
          this.table.innerHTML += html;
          if (ele) {
            ele.innerHTML = this.table.outerHTML;
          } else {
            return this.table.outerHTML;
          }
          // save reference to dom node in object
          this.node = ele;
          // save reference to calendar object for enclosure scope
          var cal = this;
              (function(){
            // save calendar object reference for listeners
            var self = this;
                self.prev.addEventListener('click', function(){
              cal.month--;
                    cal.draw(cal.node);
                });
            self.next.addEventListener('click', function(){
                    cal.month++;
              cal.draw(cal.node);
                });
                document.onkeydown = function(e) {
                  e = e || window.event;
                    if (e.keyCode == '37') {
                    // left arrow
                    cal.month--;
                    cal.draw(cal.node);
                    } else if (e.keyCode == '39') {
                        // right arrow
                        cal.month++;
                    cal.draw(cal.node);
                    }
                };
              })();
        };
    },
    getTickets: function() {
      //get tickets
      if (self.app.contentViewModel() !== undefined){
        if (typeof(self.app.contentViewModel().myTickets) === "function"){
          self.Tickets.ticketArray = self.app.contentViewModel().myTickets();
        } else if (localStorage.ticketCache) {
          self.Tickets.ticketArray = JSON.parse(localStorage.ticketCache);
        }
      } else {
        self.Tickets.ticketArray = JSON.parse(localStorage.ticketCache);
      }
      //return results
      if (self.Tickets.ticketArray) {
        localStorage.ticketCache = JSON.stringify(self.Tickets.ticketArray);
        return self.Tickets.ticketArray;
      } else {
        alert('Unable to access tickets at this time!');
        return [];
      }
    },
    getCritical: function() {
      var tickets = this.getTickets(),
      critical = [];
      for (var i = 0; i < tickets.length; i++) {
        if (tickets[i].ScheduledEndDate < new Date()) {
          critical.push(tickets[i]);
        }
      }
      if (tickets.length > 0){
        return critical;
      } else {
        return false;
      }
    },
    countCritical: function() {
      var criticals = self.Tickets.getCritical();
      if (criticals) {
        return 'Critical Tickets: ' + criticals.length + '';
      } else {
        return 'Error loading tickets!';
      }
    },
    sortTickets: function(tickets){
      if (! tickets){
        tickets = this.getTickets();
      }
      var data = {};
      for (var i=0;i<tickets.length;i++){
        var ticket = tickets[i],
        date = new Date(ticket.ScheduledEndDate),
        day = date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear();
        if (! data[day]){ data[day] = [];}
        data[day].push(ticket);
      }
      return data;
    },
    listTickets: function(tickets){
      var list = document.createElement('ul');
      for (var i=0;i<tickets.length;i++){
        var ticket = tickets[i],
        listItem = document.createElement('li'),
        text = ticket.CompanyName+': '+ticket.TicketTypeName;
        text += ' (Due: '+(ticket.ScheduledEndDate.getMonth()+1);
        text += '/'+ticket.ScheduledEndDate.getDate()+'/';
        text += ticket.ScheduledEndDate.getFullYear()+')';
        listItem.innerHTML = text;
        list.appendChild(listItem);
      }
      return list;
    },
    tryCache: function(){
      try {
        if (self.Tickets.ticketArray) {
          localStorage.setItem('ticketCache', JSON.stringify(self.Tickets.ticketArray));
        }
      } catch(err) {
        setTimeout(function(){self.Tickets.tryCache();}, 1000);
      }
    },
  };
  this.HTML = {};
  this.HTML.dashboard = this.Tools.createElement(document.body, 'div', {
        className: 'navbar navbar-inverse navbar-fixed-bottom',
        id: 'dashboard',
  });
  this.HTML.style = this.Tools.createElement(this.HTML.dashboard, 'link', {
    rel: 'stylesheet',
    type: 'text/css',
    href: 'https://rawgit.com/jamesona/SEO-Tools/master/am-dashboard/dashboard.css',
  }),
  this.HTML.nav = this.Tools.createElement(this.HTML.dashboard, 'ul', {
    className: 'nav navbar-nav',
  }),
  this.HTML.tools = this.Tools.createElement(this.HTML.nav, 'li', {
    innerHTML: 'Tools',
    className: 'dropup',
  }),
  this.HTML.toolsMenu = this.Tools.createElement(this.HTML.tools, 'ul', {
    className: 'dropdown-menu',
  }),
  this.HTML.todoistExport = this.Tools.createElement(this.HTML.toolsMenu, 'li', {
    innerHTML: 'Todoist Export',
    onclick: function(){
      self.Tools.todoistExport();
    },
  }),
  this.HTML.tickets = this.Tools.createElement(this.HTML.nav, 'li', {
    innerHTML: 'Tickets',
    className: 'dropup',
  }),
  this.HTML.ticketsMenu = this.Tools.createElement(this.HTML.tickets, 'ul', {
    className: 'dropdown-menu',
  }),
  this.HTML.ticketCalendar = this.Tools.createElement(this.HTML.ticketsMenu, 'li', {
    innerHTML: 'Calendar',
    onclick: function(){
      var node = bootbox.alert('none')[0].children[0].children[0].children[0],
      data = self.Tickets.sortTickets();
      console.log(data);
      calendar = new self.Tickets.calendar(data);
      calendar.draw(node);
    }
  }),
  this.HTML.critical = this.Tools.createElement(this.HTML.nav, 'li', {
    innerHTML: self.Tickets.countCritical(), //'Click to show Critical',
    id: 'critical',
    onclick: function(){this.innerHTML = self.Tickets.countCritical();},
  });

  window.beforeunload = function(){
    self.Tickets.tryCache();
  };
  window.onhashchange = function(){
    if (window.location.href == 'https://launchpad.boostability.com/#/customerservice/activetickets'){
      self.Tickets.tryCache();
    }
  };
  if (localStorage.ticketCache) self.Tickets.ticketArray = JSON.parse(localStorage.getItem('ticketCache'));
}
<|endoftext|>


<commit_before>/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
*/

var fso = WScript.CreateObject('Scripting.FileSystemObject');
var wscript_shell = WScript.CreateObject("WScript.Shell");

var args = WScript.Arguments;

// build type. Possible values: "debug", "release"
var buildType = null,
// list of build architectures. list of strings
buildArchs = null;

// working dir
var ROOT = WScript.ScriptFullName.split('\\cordova\\lib\\build.js').join('');

// help/usage function
function Usage() {
    Log("");
    Log("Usage: build [ --debug | --release ] [--archs=\"<list of architectures...>\"]");
    Log("    --help    : Displays this dialog.");
    Log("    --debug   : builds project in debug mode. (Default)");
    Log("    --release : builds project in release mode.");
    Log("    -r        : shortcut :: builds project in release mode.");
    Log("    --archs   : Builds project binaries for specific chip architectures.");
    Log("examples:");
    Log("    build ");
    Log("    build --debug");
    Log("    build --release");
    Log("    build --release --archs=\"arm x86\"");
    Log("");
}

// logs messaged to stdout and stderr
function Log(msg, error) {
    if (error) {
        WScript.StdErr.WriteLine(msg);
    }
    else {
        WScript.StdOut.WriteLine(msg);
    }
}

// executes a commmand in the shell
function exec_verbose(command) {
    //Log("Command: " + command);
    var oShell=wscript_shell.Exec(command);
    while (oShell.Status == 0) {
        //Wait a little bit so we're not super looping
        WScript.sleep(100);
        //Print any stdout output from the script
        if (!oShell.StdOut.AtEndOfStream) {
            var line = oShell.StdOut.ReadLine();
            Log(line);
        }
    }
    //Check to make sure our scripts did not encounter an error
    if (!oShell.StdErr.AtEndOfStream) {
        var line = oShell.StdErr.ReadAll();
        Log(line, true);
        WScript.Quit(2);
    }
    return oShell.ExitCode;
}

// checks to see if a .jsproj file exists in the project root
function is_cordova_project(path) {
    if (fso.FolderExists(path)) {
        var proj_folder = fso.GetFolder(path);
        var proj_files = new Enumerator(proj_folder.Files);
        for (;!proj_files.atEnd(); proj_files.moveNext()) {
            if (fso.GetExtensionName(proj_files.item()) == 'jsproj') {
                return true;
            }
        }
    }
    return false;
}

// escapes a path so that it can be passed to shell command.
function escapePath(path) {
    return '"' + path + '"';
}

// returns full path to .sln file
function getSolutionDir(path) {
    var proj_folder = fso.GetFolder(path);
    var proj_files = new Enumerator(proj_folder.Files);
    for (;!proj_files.atEnd(); proj_files.moveNext()) {
        if (fso.GetExtensionName(proj_files.item()) == 'sln') {
            return path + '\\' + fso.GetFileName(proj_files.item());
        }
    }

    return null;
}

// returns full path to msbuild tools required to build the project
function getMSBuildToolsPath(path) {
    // use the latest version of the msbuild tools available on this machine
    var toolsVersions = ['12.0', '4.0'];
    for (idx in toolsVersions) {
        try {
            return wscript_shell.RegRead('HKLM\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\' + toolsVersions[idx] + '\\MSBuildToolsPath');
        } catch(err) {}
    }
    Log('MSBuild tools have not been found. Please install Microsoft Visual Studio 2012 or later', true);
    WScript.Quit(2);
}

// builds the project and .xap in debug mode
function build_appx(path, buildtype, buildarchs) {

    if (!buildtype) {
        Log("WARNING: [ --debug | --release ] not specified, defaulting to debug...");
        buildtype = "debug";
    }

    if (!buildarchs) {
        Log("WARNING: target architecture not specified, defaulting to AnyCPU...");
        buildarchs = ["Any CPU"];
    }

    for (var i = 0; i < buildarchs.length; i++) {

        var buildarch = buildarchs[i];

        Log("\nBuilding Cordova Windows 8 Project:");
        Log("\tConfiguration : " + buildtype);
        Log("\tPlatform      : " + buildarch);
        Log("\tDirectory     : " + path);

        try {
            wscript_shell.CurrentDirectory = path;

            var MSBuildToolsPath = getMSBuildToolsPath(path);
            Log("\tMSBuildToolsPath: " + MSBuildToolsPath);
            var solutionDir = getSolutionDir(path);
            var buildCommand = escapePath(MSBuildToolsPath + 'msbuild') +
                    ' ' + escapePath(solutionDir) +
                        ' /clp:NoSummary;NoItemAndPropertyList;Verbosity=minimal' +
                        ' /nologo' +
                        ' /p:Configuration=' + buildtype +
                        ' /p:Platform="' + buildarch + '"';

            // hack to get rid of 'Access is denied.' error when running the shell w/ access to C:\path..
            buildCommand = 'cmd /c "' + buildCommand + '"';
            Log(buildCommand);
            if (exec_verbose(buildCommand) !== 0) {
                // msbuild failed
                WScript.Quit(2);
            }
        } catch (err) {
            Log("Build failed: " + err.message, true);
        }
    }

    // TODO: there could be multiple AppPackages
    // check if AppPackages created
    if (fso.FolderExists(path + '\\AppPackages')) {
        var out_folder = fso.GetFolder(path + '\\AppPackages');
        var subFolders = new Enumerator(out_folder.SubFolders);
        for(;!subFolders.atEnd();subFolders.moveNext())
        {
            var subFolder = subFolders.item();
            var files = new Enumerator(subFolder.Files);
            for(;!files.atEnd();files.moveNext())
            {
                if(fso.GetExtensionName(files.item()) == "ps1")
                {
                    // app was built, installation script exists
                    return "\nSUCCESS";
                }
            }

        }

    }
    Log("Error : AppPackages were not built");
    WScript.Quit(2);

}

// parses script args and set global variables for build
// throws error if unknown argument specified.
function parseArgs () {

    // return build type, specified by input string, or null, if not build type parameter
    function getBuildType (arg) {
        arg = arg.toLowerCase();
        if (arg == "--debug" || arg == "-d") {
            return "debug";
        }
        else if (arg == "--release" || arg == "-r") {
            return "release";
        }
        return null;
    }

    // returns build architectures list, specified by input string
    // or null if nothing specified, or not --archs parameter
    function getBuildArchs (arg) {
        arg = arg.toLowerCase();
        var archs = /--archs=(.+)/.exec(arg);
        if (archs) {
            // if architectures list contains commas, suppose that is comma delimited
            if (archs[1].indexOf(',') != -1){
                return archs[1].split(',');
            }
            // else space delimited
            return archs[1].split(/\s/);
        }
        return null;
    }

    for (var i = 0; i < args.Length; i++) {
        if (getBuildType(args(i))) {
            buildType = getBuildType(args(i));
        } else if (getBuildArchs(args(i))) {
            buildArchs = getBuildArchs(args(i));
        } else {
            Log("Error: \"" + args(i) + "\" is not recognized as a build option", true);
            Usage();
            WScript.Quit(2);
        }
    }
}

var result;
var isRelease = false;

if (args.Count() > 0) {
    // support help flags
    if (args(0) == "--help" || args(0) == "/?" ||
            args(0) == "help" || args(0) == "-help" || args(0) == "/help") {
        Usage();
        WScript.Quit(2);
    }
    else if (!fso.FolderExists(ROOT) || !is_cordova_project(ROOT)) {
        Log("Error: could not find project at " + ROOT, true);
        WScript.Quit(2);
    }

    parseArgs();
}

Log(build_appx(ROOT, buildType, buildArchs));
<commit_msg>Added list of supported architectures in help text<commit_after>/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
*/

var fso = WScript.CreateObject('Scripting.FileSystemObject');
var wscript_shell = WScript.CreateObject("WScript.Shell");

var args = WScript.Arguments;

// build type. Possible values: "debug", "release"
var buildType = null,
// list of build architectures. list of strings
buildArchs = null;

// working dir
var ROOT = WScript.ScriptFullName.split('\\cordova\\lib\\build.js').join('');

// help/usage function
function Usage() {
    Log("");
    Log("Usage: build [ --debug | --release ] [--archs=\"<list of architectures...>\"]");
    Log("    --help    : Displays this dialog.");
    Log("    --debug   : builds project in debug mode. (Default)");
    Log("    --release : builds project in release mode.");
    Log("    -r        : shortcut :: builds project in release mode.");
    Log("    --archs   : Builds project binaries for specific chip architectures. `arm` + `x86` + `x64` are supported.");
    Log("examples:");
    Log("    build ");
    Log("    build --debug");
    Log("    build --release");
    Log("    build --release --archs=\"arm x86\"");
    Log("");
}

// logs messaged to stdout and stderr
function Log(msg, error) {
    if (error) {
        WScript.StdErr.WriteLine(msg);
    }
    else {
        WScript.StdOut.WriteLine(msg);
    }
}

// executes a commmand in the shell
function exec_verbose(command) {
    //Log("Command: " + command);
    var oShell=wscript_shell.Exec(command);
    while (oShell.Status == 0) {
        //Wait a little bit so we're not super looping
        WScript.sleep(100);
        //Print any stdout output from the script
        if (!oShell.StdOut.AtEndOfStream) {
            var line = oShell.StdOut.ReadLine();
            Log(line);
        }
    }
    //Check to make sure our scripts did not encounter an error
    if (!oShell.StdErr.AtEndOfStream) {
        var line = oShell.StdErr.ReadAll();
        Log(line, true);
        WScript.Quit(2);
    }
    return oShell.ExitCode;
}

// checks to see if a .jsproj file exists in the project root
function is_cordova_project(path) {
    if (fso.FolderExists(path)) {
        var proj_folder = fso.GetFolder(path);
        var proj_files = new Enumerator(proj_folder.Files);
        for (;!proj_files.atEnd(); proj_files.moveNext()) {
            if (fso.GetExtensionName(proj_files.item()) == 'jsproj') {
                return true;
            }
        }
    }
    return false;
}

// escapes a path so that it can be passed to shell command.
function escapePath(path) {
    return '"' + path + '"';
}

// returns full path to .sln file
function getSolutionDir(path) {
    var proj_folder = fso.GetFolder(path);
    var proj_files = new Enumerator(proj_folder.Files);
    for (;!proj_files.atEnd(); proj_files.moveNext()) {
        if (fso.GetExtensionName(proj_files.item()) == 'sln') {
            return path + '\\' + fso.GetFileName(proj_files.item());
        }
    }

    return null;
}

// returns full path to msbuild tools required to build the project
function getMSBuildToolsPath(path) {
    // use the latest version of the msbuild tools available on this machine
    var toolsVersions = ['12.0', '4.0'];
    for (idx in toolsVersions) {
        try {
            return wscript_shell.RegRead('HKLM\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\' + toolsVersions[idx] + '\\MSBuildToolsPath');
        } catch(err) {}
    }
    Log('MSBuild tools have not been found. Please install Microsoft Visual Studio 2012 or later', true);
    WScript.Quit(2);
}

// builds the project and .xap in debug mode
function build_appx(path, buildtype, buildarchs) {

    if (!buildtype) {
        Log("WARNING: [ --debug | --release ] not specified, defaulting to debug...");
        buildtype = "debug";
    }

    if (!buildarchs) {
        Log("WARNING: target architecture not specified, defaulting to AnyCPU...");
        buildarchs = ["Any CPU"];
    }

    for (var i = 0; i < buildarchs.length; i++) {

        var buildarch = buildarchs[i];

        Log("\nBuilding Cordova Windows 8 Project:");
        Log("\tConfiguration : " + buildtype);
        Log("\tPlatform      : " + buildarch);
        Log("\tDirectory     : " + path);

        try {
            wscript_shell.CurrentDirectory = path;

            var MSBuildToolsPath = getMSBuildToolsPath(path);
            Log("\tMSBuildToolsPath: " + MSBuildToolsPath);
            var solutionDir = getSolutionDir(path);
            var buildCommand = escapePath(MSBuildToolsPath + 'msbuild') +
                    ' ' + escapePath(solutionDir) +
                        ' /clp:NoSummary;NoItemAndPropertyList;Verbosity=minimal' +
                        ' /nologo' +
                        ' /p:Configuration=' + buildtype +
                        ' /p:Platform="' + buildarch + '"';

            // hack to get rid of 'Access is denied.' error when running the shell w/ access to C:\path..
            buildCommand = 'cmd /c "' + buildCommand + '"';
            Log(buildCommand);
            if (exec_verbose(buildCommand) !== 0) {
                // msbuild failed
                WScript.Quit(2);
            }
        } catch (err) {
            Log("Build failed: " + err.message, true);
        }
    }

    // TODO: there could be multiple AppPackages
    // check if AppPackages created
    if (fso.FolderExists(path + '\\AppPackages')) {
        var out_folder = fso.GetFolder(path + '\\AppPackages');
        var subFolders = new Enumerator(out_folder.SubFolders);
        for(;!subFolders.atEnd();subFolders.moveNext())
        {
            var subFolder = subFolders.item();
            var files = new Enumerator(subFolder.Files);
            for(;!files.atEnd();files.moveNext())
            {
                if(fso.GetExtensionName(files.item()) == "ps1")
                {
                    // app was built, installation script exists
                    return "\nSUCCESS";
                }
            }

        }

    }
    Log("Error : AppPackages were not built");
    WScript.Quit(2);

}

// parses script args and set global variables for build
// throws error if unknown argument specified.
function parseArgs () {

    // return build type, specified by input string, or null, if not build type parameter
    function getBuildType (arg) {
        arg = arg.toLowerCase();
        if (arg == "--debug" || arg == "-d") {
            return "debug";
        }
        else if (arg == "--release" || arg == "-r") {
            return "release";
        }
        return null;
    }

    // returns build architectures list, specified by input string
    // or null if nothing specified, or not --archs parameter
    function getBuildArchs (arg) {
        arg = arg.toLowerCase();
        var archs = /--archs=(.+)/.exec(arg);
        if (archs) {
            // if architectures list contains commas, suppose that is comma delimited
            if (archs[1].indexOf(',') != -1){
                return archs[1].split(',');
            }
            // else space delimited
            return archs[1].split(/\s/);
        }
        return null;
    }

    for (var i = 0; i < args.Length; i++) {
        if (getBuildType(args(i))) {
            buildType = getBuildType(args(i));
        } else if (getBuildArchs(args(i))) {
            buildArchs = getBuildArchs(args(i));
        } else {
            Log("Error: \"" + args(i) + "\" is not recognized as a build option", true);
            Usage();
            WScript.Quit(2);
        }
    }
}

var result;
var isRelease = false;

if (args.Count() > 0) {
    // support help flags
    if (args(0) == "--help" || args(0) == "/?" ||
            args(0) == "help" || args(0) == "-help" || args(0) == "/help") {
        Usage();
        WScript.Quit(2);
    }
    else if (!fso.FolderExists(ROOT) || !is_cordova_project(ROOT)) {
        Log("Error: could not find project at " + ROOT, true);
        WScript.Quit(2);
    }

    parseArgs();
}

Log(build_appx(ROOT, buildType, buildArchs));
<|endoftext|>


<commit_before>/* call using this enclosure
  (function(){
    var url = 'https://rawgit.com/jamesona/SEO-Tools/master/am-dashboard/dashboard.js';
    document.head.appendChild(document.createElement('script')).src=url;
    function initialize(){
      if (typeof(Dashboard) !== 'undefined' && typeof(ko) !== 'undefined' && ko.dataFor(app) !== undefined) {
          //console.log('Knockout:');console.log(ko);console.log('App:');console.log(ko.dataFor(app));
          db = new Dashboard(ko.dataFor(app))
      } else {
          setTimeout(function(){initialize()}, 100);
      }
    }
    initialize();
  })();
*/

function Dashboard(app) {
  var self = this;
  this.app = app;
  console.log(this.app);
  this.Tools = {
    bobCal: function(){},
    openClient: function(client) {
      self.app.showManageCustomer(client);
    },
    closeClient: function() {
      var buttons = document.getElementsByClassName('close'),
      i = buttons.length - 1;
      if (i >= 1) buttons[i - 1].click();
    },
    createElement: function(parent, tag, attributes) {
      var element = parent.appendChild(document.createElement(tag));
      for (var attribute in attributes) {
        if (attributes.hasOwnProperty(attribute)) {
          element[attribute] = attributes[attribute];
        }
      }
      return element;
    },
    bobParse: function(raw){
      var clients = [], data = {};
      // exit on null entry
      if ( raw == null ) return;
      for (var cells = raw.replace(/Basic[\r\n\s\ta-z]*Partner ID[\t\s]+/i, '').split(/\t/),
        client = {}, cols = ['Account ID',	'Account Start Date',	'Account Bucket',	'Account Spend',
        'Date of Next Ticket',	'Engaged Status',	'Timezone',	'Welcome Call',	'Keyword Research',
        'Local Profile Tab',	'Obtain or Create Google Logins',	'Create and Verify Google Profile',
        'Obtain Site Access',	'Implement Onsite Edits',	'Create Yahoo Account',	'Create and Verify Yahoo Profile',
        'Create and Verify Bing Profile',	'Install Analytics',	'Company Name',	'Contact Name',	'Website URL',
        'Email Address',	'Phone Number',	'Partner ID',];
        cells.length>0;){
        keys = Object.keys(client).length;
        if (keys<cols.length-1){
          var param = cols[keys];
          client[param] = cells[0];
          cells.shift();
        } else {
          client.count = keys;
          clients.push(client);
          client = {};
        }
      }
      for (var i=0;i<clients.length;i++){
        var date = clients[i]['Date of Next Ticket']
        if (data[date] === undefined) data[date] = [];
        data[date].push(clients[i]);
      }
      return data;
    },
  };
  this.Tickets = {
    calendar: function(month, year, data) {
      console.log(data);
      if (typeof(month) == Object) {data = month, month = null;}
      this.current_date = new Date();
      this.day_labels = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
      this.month_labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
      this.month = (isNaN(month) || month === null) ? this.current_date.getMonth() : month;
      this.year = (isNaN(year) || year === null) ? this.current_date.getFullYear() : year;
      this.draw = function(ele){
          if (this.month > 11) {
            this.month -= 12;
            this.year += 1;
          } else if (month < 0) {
            this.month += 12;
            this.year -= 1;
          }
          // get dates
          var startingDay = new Date(this.year, this.month, 1).getDay(),
          endingDate = new Date(this.year, this.month + 1, 0),
          monthLength = endingDate.getDate(),
          inLastRow = 6 - endingDate.getDay();

          // generate header
          this.table = document.createElement('table');
          this.head = document.createElement('thead');
          this.prev = document.createElement('th');
          this.next = document.createElement('th');
          this.title = document.createElement('th');
          this.days = document.createElement('tr');
          this.body = document.createElement('tbody');
          this.cells = '';
          this.table.setAttribute('class', 'calendar');
          this.table.appendChild(this.head);
          this.head.appendChild(this.prev);
          this.prev.innerHTML = "«";
          this.prev.id = 'prev';
          this.head.appendChild(this.title);
          this.head.appendChild(this.next);
          this.next.innerHTML = "»";
          this.next.id = 'next';
          this.table.appendChild(this.days);
          this.title.innerHTML = this.month_labels[this.month] + " " + this.year;
          this.title.setAttribute('colspan', '5');
          this.days.setAttribute('class', 'header');
          for (var i = 0; i <= 6; i++ ) this.cells += '' + this.day_labels[i] + '	';
          this.days.innerHTML = this.cells;

          //generate calendar
          var html = '
';
          if ( startingDay ) html += '	';
          for (var day = 1; day <= monthLength; day++) {
          html += '
' + day + '
';
          //if data argument present, append key value for current day
          if (data) {
            var today = (this.month+1)+'/'+day+'/'+this.year;
            if (data[today]) html += '
'+Object.keys(data[today]).length+' Clients
';
          }
          html += '	';
          if ( (day + startingDay) % 7 === 0 && day != monthLength ) html += '

';
          }
          if ( inLastRow ) html += '	';
          html += '
';
          this.table.innerHTML += html;
          if (ele) {
            ele.innerHTML = this.table.outerHTML;
          } else {
            return this.table.outerHTML;
          }
          // save reference to dom node in object
          this.node = ele;
          // save reference to calendar object for enclosure scope
          var cal = this;
              (function(){
            // save calendar object reference for listeners
            var self = this;
                self.prev.addEventListener('click', function(){
              cal.month--;
                    cal.draw(cal.node);
                });
            self.next.addEventListener('click', function(){
                    cal.month++;
              cal.draw(cal.node);
                });
                document.onkeydown = function(e) {
                  e = e || window.event;
                    if (e.keyCode == '37') {
                    // left arrow
                    cal.month--;
                    cal.draw(cal.node);
                    } else if (e.keyCode == '39') {
                        // right arrow
                        cal.month++;
                    cal.draw(cal.node);
                    }
                };
              })();
        };
    },
    getTickets: function() {
      //get tickets
      if (self.app.contentViewModel() !== undefined){
        if (typeof(self.app.contentViewModel().myTickets) === "function"){
          self.Tickets.ticketArray = self.app.contentViewModel().myTickets();
        } else if (localStorage.ticketCache) {
          self.Tickets.ticketArray = JSON.parse(localStorage.ticketCache);
        }
      } else {
        self.Tickets.ticketArray = JSON.parse(localStorage.ticketCache);
      }
      //return results
      if (self.Tickets.ticketArray) {
        localStorage.ticketCache = JSON.stringify(self.Tickets.ticketArray);
        return self.Tickets.ticketArray;
      } else {
        alert('Unable to access tickets at this time!');
        return [];
      }
    },
    getCritical: function() {
      var tickets = this.getTickets(),
      critical = [];
      for (var i = 0; i < tickets.length; i++) {
        if (tickets[i].ScheduledEndDate < new Date()) {
          critical.push(tickets[i]);
        }
      }
      if (tickets.length > 0){
        return critical;
      } else {
        return false;
      }
    },
    countCritical: function() {
      var criticals = self.Tickets.getCritical();
      if (criticals) {
        return 'Critical Tickets: ' + criticals.length + '';
      } else {
        return 'Error loading tickets!';
      }
    },
    sortTickets: function(tickets){
      if (! tickets){
        tickets = this.getTickets();
      }
      var data = {};
      for (var i=0;i<tickets.length;i++){
        var ticket = tickets[i],
        date = new Date(ticket.ScheduledEndDate),
        day = date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear();
        if (! data[day]){ data[day] = [];}
        data[day].push(ticket);
      }
      return data;
    },
    listTickets: function(tickets){
      var list = document.createElement('ul');
      for (var i=0;i<tickets.length;i++){
        var ticket = tickets[i],
        listItem = document.createElement('li'),
        text = ticket.CompanyName+': '+ticket.TicketTypeName;
        text += ' (Due: '+(ticket.ScheduledEndDate.getMonth()+1);
        text += '/'+ticket.ScheduledEndDate.getDate()+'/';
        text += ticket.ScheduledEndDate.getFullYear()+')';
        listItem.innerHTML = text;
        list.appendChild(listItem);
      }
      return list;
    },
    tryCache: function(){
      try {
        if (self.Tickets.ticketArray) {
          localStorage.ticketCache = JSON.stringify(self.Tickets.ticketArray);
        }
      } catch(err) {
        setTimeout(function(){self.Tickets.tryCache()}, 1000);
      }
    },
  };
  this.HTML = {};
  this.HTML.dashboard = this.Tools.createElement(document.body, 'div', {
        className: 'navbar navbar-inverse navbar-fixed-bottom',
        id: 'dashboard',
  });
  this.HTML.style = this.Tools.createElement(this.HTML.dashboard, 'link', {
    rel: 'stylesheet',
    type: 'text/css',
    href: 'https://rawgit.com/jamesona/SEO-Tools/master/am-dashboard/dashboard.css',
  }),
  this.HTML.nav = this.Tools.createElement(this.HTML.dashboard, 'ul', {
    className: 'nav navbar-nav',
  }),
  this.HTML.tools = this.Tools.createElement(this.HTML.nav, 'li', {
    innerHTML: 'Tools',
    className: 'dropup',
  }),
  this.HTML.toolsMenu = this.Tools.createElement(this.HTML.tools, 'ul', {
    className: 'dropdown-menu',
  }),
  this.HTML.tickets = this.Tools.createElement(this.HTML.nav, 'li', {
    innerHTML: 'Tickets',
    className: 'dropup',
  }),
  this.HTML.ticketsMenu = this.Tools.createElement(this.HTML.tickets, 'ul', {
    className: 'dropdown-menu',
  }),
  this.HTML.ticketCalendar = this.Tools.createElement(this.HTML.ticketsMenu, 'li', {
    innerHTML: 'Calendar',
    onclick: function(){
      var node = bootbox.alert('none')[0].children[0].children[0].children[0],
      data = self.Tickets.sortTickets();
      console.log(data);
      calendar = new self.Tickets.calendar(data);
      calendar.draw(node);
    }
  }),
  this.HTML.critical = this.Tools.createElement(this.HTML.nav, 'li', {
    innerHTML: self.Tickets.countCritical(), //'Click to show Critical',
    id: 'critical',
    onclick: function(){this.innerHTML = self.Tickets.countCritical()},
  });

  window.beforeunload = function(){
    self.Tickets.tryCache();
  };
  window.onhashchange = function(){
    if (window.location.href == 'https://launchpad.boostability.com/#/customerservice/activetickets'){
      self.Tickets.tryCache();
    }
  };
  if (localStorage.ticketCache) self.Tickets.ticketArray = JSON.parse(localStorage.ticketCache);
}
<commit_msg>Update dashboard.js<commit_after>/* call using this enclosure
  (function(){
    var url = 'https://rawgit.com/jamesona/SEO-Tools/master/am-dashboard/dashboard.js';
    document.head.appendChild(document.createElement('script')).src=url;
    function initialize(){
      if (typeof(Dashboard) !== 'undefined' && typeof(ko) !== 'undefined' && ko.dataFor(app) !== undefined) {
          //console.log('Knockout:');console.log(ko);console.log('App:');console.log(ko.dataFor(app));
          db = new Dashboard(ko.dataFor(app))
      } else {
          setTimeout(function(){initialize()}, 100);
      }
    }
    initialize();
  })();
*/

function Dashboard(app) {
  var self = this;
  this.app = app;
  console.log(this.app);
  this.Tools = {
    bobParse: function(raw){
      var clients = [], data = {};
      // exit on null entry
      if ( raw == null ) return;
      for (var cells = raw.replace(/Basic[\r\n\s\ta-z]*Partner ID[\t\s]+/i, '').split(/\t/),
        client = {}, cols = ['Account ID',	'Account Start Date',	'Account Bucket',	'Account Spend',
        'Date of Next Ticket',	'Engaged Status',	'Timezone',	'Welcome Call',	'Keyword Research',
        'Local Profile Tab',	'Obtain or Create Google Logins',	'Create and Verify Google Profile',
        'Obtain Site Access',	'Implement Onsite Edits',	'Create Yahoo Account',	'Create and Verify Yahoo Profile',
        'Create and Verify Bing Profile',	'Install Analytics',	'Company Name',	'Contact Name',	'Website URL',
        'Email Address',	'Phone Number',	'Partner ID',];
        cells.length>0;){
        keys = Object.keys(client).length;
        if (keys<cols.length-1){
          var param = cols[keys];
          client[param] = cells[0];
          cells.shift();
        } else {
          client.count = keys;
          clients.push(client);
          client = {};
        }
      }
      for (var i=0;i<clients.length;i++){
        var date = clients[i]['Date of Next Ticket']
        if (data[date] === undefined) data[date] = [];
        data[date].push(clients[i]);
      }
      return data;
    },
    bobCal: function(){},
    todoistExport: function(){
      var data = ko.dataFor(app).contentViewModel().customersDataTable.dataSource(),
      taskDate = function(day){
        var days = [], days[0] = new Date(),
        days[1] new Date(),
        days[2] new Date();
        if (days[0].getDay() == 5) {days[1].setDate(days[0].getDate()+3);days[2].setDate(days[1].getDate(+1))}
        else if (days[0].getDay() == 4) {days[1].setDate(days[0].getDate()+1);days[2].setDate(days[1].getDate(+3))}
        else {days[1].setDate(days[0].getDate()+1);days[2].setDate(days[1].getDate(+1))}
        return 'date 'days[day].toDateString().substring(4);
      };
      export = data.CustomerId+' - '+data.Name+'[[NOTE]]: https://launchpad.boostability.com/#customerservice/customersearch/'+data.CustomerId;
      export += '\n...'+data.CustomerId+' Welcome Call [['+taskDate(2)+']]';
      export += '\n......'+data.CustomerId+' 1st Welcome Call [['+taskDate(0)+']]';
      export += '\n......'+data.CustomerId+' 1st Welcome Email [['+taskDate(0)+']]';
      export += '\n......'+data.CustomerId+' 2nd Welcome Call [['+taskDate(1)+']]';
      export += '\n......'+data.CustomerId+' 2nd Welcome Email [['+taskDate(1)+']]';
      export += '\n......'+data.CustomerId+' 3rd Welcome Call [['+taskDate(2)+']]';
      export += '\n......'+data.CustomerId+' 3rd Welcome Email [['+taskDate(2)+']]';
      export += '\n...'+data.CustomerId+' Keyword Research';
      export += '\n...'+data.CustomerId+' Local Profile';
      bootbox.alert(export);
    },
    openClient: function(client) {
      self.app.showManageCustomer(client);
    },
    closeClient: function() {
      var buttons = document.getElementsByClassName('close'),
      i = buttons.length - 1;
      if (i >= 1) buttons[i - 1].click();
    },
    createElement: function(parent, tag, attributes) {
      var element = parent.appendChild(document.createElement(tag));
      for (var attribute in attributes) {
        if (attributes.hasOwnProperty(attribute)) {
          element[attribute] = attributes[attribute];
        }
      }
      return element;
    },
  };
  this.Tickets = {
    calendar: function(month, year, data) {
      console.log(data);
      if (typeof(month) == Object) {data = month, month = null;}
      this.current_date = new Date();
      this.day_labels = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
      this.month_labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
      this.month = (isNaN(month) || month === null) ? this.current_date.getMonth() : month;
      this.year = (isNaN(year) || year === null) ? this.current_date.getFullYear() : year;
      this.draw = function(ele){
          if (this.month > 11) {
            this.month -= 12;
            this.year += 1;
          } else if (month < 0) {
            this.month += 12;
            this.year -= 1;
          }
          // get dates
          var startingDay = new Date(this.year, this.month, 1).getDay(),
          endingDate = new Date(this.year, this.month + 1, 0),
          monthLength = endingDate.getDate(),
          inLastRow = 6 - endingDate.getDay();

          // generate header
          this.table = document.createElement('table');
          this.head = document.createElement('thead');
          this.prev = document.createElement('th');
          this.next = document.createElement('th');
          this.title = document.createElement('th');
          this.days = document.createElement('tr');
          this.body = document.createElement('tbody');
          this.cells = '';
          this.table.setAttribute('class', 'calendar');
          this.table.appendChild(this.head);
          this.head.appendChild(this.prev);
          this.prev.innerHTML = "«";
          this.prev.id = 'prev';
          this.head.appendChild(this.title);
          this.head.appendChild(this.next);
          this.next.innerHTML = "»";
          this.next.id = 'next';
          this.table.appendChild(this.days);
          this.title.innerHTML = this.month_labels[this.month] + " " + this.year;
          this.title.setAttribute('colspan', '5');
          this.days.setAttribute('class', 'header');
          for (var i = 0; i <= 6; i++ ) this.cells += '' + this.day_labels[i] + '	';
          this.days.innerHTML = this.cells;

          //generate calendar
          var html = '
';
          if ( startingDay ) html += '	';
          for (var day = 1; day <= monthLength; day++) {
          html += '
' + day + '
';
          //if data argument present, append key value for current day
          if (data) {
            var today = (this.month+1)+'/'+day+'/'+this.year;
            if (data[today]) html += '
'+Object.keys(data[today]).length+' Clients
';
          }
          html += '	';
          if ( (day + startingDay) % 7 === 0 && day != monthLength ) html += '

';
          }
          if ( inLastRow ) html += '	';
          html += '
';
          this.table.innerHTML += html;
          if (ele) {
            ele.innerHTML = this.table.outerHTML;
          } else {
            return this.table.outerHTML;
          }
          // save reference to dom node in object
          this.node = ele;
          // save reference to calendar object for enclosure scope
          var cal = this;
              (function(){
            // save calendar object reference for listeners
            var self = this;
                self.prev.addEventListener('click', function(){
              cal.month--;
                    cal.draw(cal.node);
                });
            self.next.addEventListener('click', function(){
                    cal.month++;
              cal.draw(cal.node);
                });
                document.onkeydown = function(e) {
                  e = e || window.event;
                    if (e.keyCode == '37') {
                    // left arrow
                    cal.month--;
                    cal.draw(cal.node);
                    } else if (e.keyCode == '39') {
                        // right arrow
                        cal.month++;
                    cal.draw(cal.node);
                    }
                };
              })();
        };
    },
    getTickets: function() {
      //get tickets
      if (self.app.contentViewModel() !== undefined){
        if (typeof(self.app.contentViewModel().myTickets) === "function"){
          self.Tickets.ticketArray = self.app.contentViewModel().myTickets();
        } else if (localStorage.ticketCache) {
          self.Tickets.ticketArray = JSON.parse(localStorage.ticketCache);
        }
      } else {
        self.Tickets.ticketArray = JSON.parse(localStorage.ticketCache);
      }
      //return results
      if (self.Tickets.ticketArray) {
        localStorage.ticketCache = JSON.stringify(self.Tickets.ticketArray);
        return self.Tickets.ticketArray;
      } else {
        alert('Unable to access tickets at this time!');
        return [];
      }
    },
    getCritical: function() {
      var tickets = this.getTickets(),
      critical = [];
      for (var i = 0; i < tickets.length; i++) {
        if (tickets[i].ScheduledEndDate < new Date()) {
          critical.push(tickets[i]);
        }
      }
      if (tickets.length > 0){
        return critical;
      } else {
        return false;
      }
    },
    countCritical: function() {
      var criticals = self.Tickets.getCritical();
      if (criticals) {
        return 'Critical Tickets: ' + criticals.length + '';
      } else {
        return 'Error loading tickets!';
      }
    },
    sortTickets: function(tickets){
      if (! tickets){
        tickets = this.getTickets();
      }
      var data = {};
      for (var i=0;i<tickets.length;i++){
        var ticket = tickets[i],
        date = new Date(ticket.ScheduledEndDate),
        day = date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear();
        if (! data[day]){ data[day] = [];}
        data[day].push(ticket);
      }
      return data;
    },
    listTickets: function(tickets){
      var list = document.createElement('ul');
      for (var i=0;i<tickets.length;i++){
        var ticket = tickets[i],
        listItem = document.createElement('li'),
        text = ticket.CompanyName+': '+ticket.TicketTypeName;
        text += ' (Due: '+(ticket.ScheduledEndDate.getMonth()+1);
        text += '/'+ticket.ScheduledEndDate.getDate()+'/';
        text += ticket.ScheduledEndDate.getFullYear()+')';
        listItem.innerHTML = text;
        list.appendChild(listItem);
      }
      return list;
    },
    tryCache: function(){
      try {
        if (self.Tickets.ticketArray) {
          localStorage.ticketCache = JSON.stringify(self.Tickets.ticketArray);
        }
      } catch(err) {
        setTimeout(function(){self.Tickets.tryCache()}, 1000);
      }
    },
  };
  this.HTML = {};
  this.HTML.dashboard = this.Tools.createElement(document.body, 'div', {
        className: 'navbar navbar-inverse navbar-fixed-bottom',
        id: 'dashboard',
  });
  this.HTML.style = this.Tools.createElement(this.HTML.dashboard, 'link', {
    rel: 'stylesheet',
    type: 'text/css',
    href: 'https://rawgit.com/jamesona/SEO-Tools/master/am-dashboard/dashboard.css',
  }),
  this.HTML.nav = this.Tools.createElement(this.HTML.dashboard, 'ul', {
    className: 'nav navbar-nav',
  }),
  this.HTML.tools = this.Tools.createElement(this.HTML.nav, 'li', {
    innerHTML: 'Tools',
    className: 'dropup',
  }),
  this.HTML.toolsMenu = this.Tools.createElement(this.HTML.tools, 'ul', {
    className: 'dropdown-menu',
  }),
  this.HTML.todoistExport = this.Tools.createElement(this.HTML.toolsMenu, 'li', {
    innerHTML: 'Todoist Export',
    onclick: function(){
      self.Tools.todoistExport();
    },
  }),
  this.HTML.tickets = this.Tools.createElement(this.HTML.nav, 'li', {
    innerHTML: 'Tickets',
    className: 'dropup',
  }),
  this.HTML.ticketsMenu = this.Tools.createElement(this.HTML.tickets, 'ul', {
    className: 'dropdown-menu',
  }),
  this.HTML.ticketCalendar = this.Tools.createElement(this.HTML.ticketsMenu, 'li', {
    innerHTML: 'Calendar',
    onclick: function(){
      var node = bootbox.alert('none')[0].children[0].children[0].children[0],
      data = self.Tickets.sortTickets();
      console.log(data);
      calendar = new self.Tickets.calendar(data);
      calendar.draw(node);
    }
  }),
  this.HTML.critical = this.Tools.createElement(this.HTML.nav, 'li', {
    innerHTML: self.Tickets.countCritical(), //'Click to show Critical',
    id: 'critical',
    onclick: function(){this.innerHTML = self.Tickets.countCritical()},
  });

  window.beforeunload = function(){
    self.Tickets.tryCache();
  };
  window.onhashchange = function(){
    if (window.location.href == 'https://launchpad.boostability.com/#/customerservice/activetickets'){
      self.Tickets.tryCache();
    }
  };
  if (localStorage.ticketCache) self.Tickets.ticketArray = JSON.parse(localStorage.ticketCache);
}
<|endoftext|>


<commit_before>var PythonDebuggerView;

PythonDebuggerView = require('./python-debugger-view');

module.exports = {
  pythonDebuggerView: null,
  activate: function() {
    atom.commands.add('atom-workspace', "python-debugger:insert", (function(_this) {
      return function() {
        return _this.insert();
      };
    })(this));
    return atom.commands.add('atom-workspace', "python-debugger:remove", (function(_this) {
      return function() {
        return _this.remove();
      };
    })(this));
  },
  insert: function() {
    var IMPORT_STATEMENT, cursor, cursors, editor, i, index, insert_position, j, len, len1, line, options, results, saved_positions;
    IMPORT_STATEMENT = "import ipdb\n";
    editor = atom.workspace.getActivePaneItem();
    cursors = editor.getCursors();
    saved_positions = [];
    for (i = 0, len = cursors.length; i < len; i++) {
      cursor = cursors[i];
      cursor.moveToFirstCharacterOfLine();
      saved_positions.push(cursor.getBufferPosition());
    }
    editor.insertText("ipdb.set_trace()  ######### Break Point ###########\n", options = {
      "autoIndentNewline": true,
      "autoIndent": true
    });
    editor.moveToTop();
    insert_position = editor.getCursorBufferPosition();
    editor.moveToBeginningOfLine();
    editor.selectToEndOfLine();
    line = editor.getSelectedText();
    while ((line.startsWith("#")) || (line.startsWith("from __future__")) || (!line)) {
      editor.moveToBeginningOfLine();
      editor.moveDown();
      editor.selectToEndOfLine();
      if (line) {
        insert_position = editor.getCursorBufferPosition();
      }
      line = editor.getSelectedText();
    }
    editor.setCursorBufferPosition(insert_position);
    if (!(IMPORT_STATEMENT.startsWith(line))) {
      editor.moveToBeginningOfLine();
      editor.insertText(IMPORT_STATEMENT);
    }
    results = [];
    for (index = j = 0, len1 = cursors.length; j < len1; index = ++j) {
      cursor = cursors[index];
      results.push(cursor.setBufferPosition(saved_positions[index]));
    }
    return results;
  },
  remove: function() {
    var editor, i, len, match, matches, results;
    editor = atom.workspace.getActivePaneItem();
    console.log('removing all imports');
    matches = [];
    editor.buffer.backwardsScan(/ipdb/g, function(match) {
      return matches.push(match);
    });
    results = [];
    for (i = 0, len = matches.length; i < len; i++) {
      match = matches[i];
      console.log(match);
      editor.setCursorScreenPosition([match.range.start.row, 1]);
      results.push(editor.deleteLine());
    }
    return results;
  }
};
<commit_msg>Update python-debugger.js<commit_after>var PythonDebuggerView;

PythonDebuggerView = require('./python-debugger-view');

module.exports = {
  pythonDebuggerView: null,
  activate: function() {
    atom.commands.add('atom-workspace', "python-debugger:insert", (function(_this) {
      return function() {
        return _this.insert();
      };
    })(this));
    return atom.commands.add('atom-workspace', "python-debugger:remove", (function(_this) {
      return function() {
        return _this.remove();
      };
    })(this));
  },
  insert: function() {
    var IMPORT_STATEMENT, cursor, cursors, editor, i, index, insert_position, j, len, len1, line, options, results, saved_positions, former_level;
    IMPORT_STATEMENT = "import ipdb\n";
    editor = atom.workspace.getActivePaneItem();
    cursors = editor.getCursors();
    saved_positions = [];
    for (i = 0, len = cursors.length; i < len; i++) {
      cursor = cursors[i];
      cursor.moveToFirstCharacterOfLine();
      saved_positions.push(cursor.getBufferPosition());
    };
    former_level = editor.indentationForBufferRow(cursor.getScreenRow());
    editor.insertText("ipdb.set_trace()  ######### Break Point ###########\n", options = {
      "autoIndentNewline": true,
      "autoIndent": true
    });
    editor.setIndentationForBufferRow(cursor.getScreenRow(), former_level)
    editor.moveToTop();
    insert_position = editor.getCursorBufferPosition();
    editor.moveToBeginningOfLine();
    editor.selectToEndOfLine();
    line = editor.getSelectedText();
    while ((line.startsWith("#")) || (line.startsWith("from __future__")) || (!line)) {
      editor.moveToBeginningOfLine();
      editor.moveDown();
      editor.selectToEndOfLine();
      if (line) {
        insert_position = editor.getCursorBufferPosition();
      }
      line = editor.getSelectedText();
    }
    editor.setCursorBufferPosition(insert_position);
    if (!(IMPORT_STATEMENT.startsWith(line))) {
      editor.moveToBeginningOfLine();
      editor.insertText(IMPORT_STATEMENT);
    }
    results = [];
    for (index = j = 0, len1 = cursors.length; j < len1; index = ++j) {
      cursor = cursors[index];
      results.push(cursor.setBufferPosition(saved_positions[index]));
    }
    return results;
  },
  remove: function() {
    var editor, i, len, match, matches, results;
    editor = atom.workspace.getActivePaneItem();
    console.log('removing all imports');
    matches = [];
    editor.buffer.backwardsScan(/ipdb/g, function(match) {
      return matches.push(match);
    });
    results = [];
    for (i = 0, len = matches.length; i < len; i++) {
      match = matches[i];
      console.log(match);
      editor.setCursorScreenPosition([match.range.start.row, 1]);
      results.push(editor.deleteLine());
    }
    return results;
  }
};
<|endoftext|>


<commit_before>angular.module('IMPERIUM').controller('loginController', ['$scope', 'securityService', '$localStorage', '$sessionStorage', '$location', 'rolAdmin', function ($scope, security, $localStorage, $sessionStorage, $location, rolAdmin) {
    $scope.datos = {};
    $scope.submit = function () {

//      $.ajax({
//        url: 'http://localhost/cras/www/server.php/login',
//        type: 'POST',
//        data: $scope.datos,
//        success: function (response) {
//          if (response.codigo == 500) {
//            $scope.$apply(function () {
//              $scope.usuarioErroneo = true;
//              $scope.datos = {};
//            });
//          } else {
//            $scope.$apply(function () {
//              $sessionStorage.usuario = response.usuario[0];
//              if ($sessionStorage.usuario.rol_id == rolAdmin) {
//                $location.path('/menuPrincipal');
//              } else {
//                $location.path('/ces');
//              }
//            });
//          }
//        }
//      });

      security.validateUserAndPassword($scope.datos).then(function successCallback(response) {
        console.log(response);
        $scope.usuarioErroneo = false;
        if (response.data.codigo == 500) {
          $scope.usuarioErroneo = true;
          $scope.datos = {};
        } else {
          $sessionStorage.usuario = response.data.usuario[0];
          if ($sessionStorage.usuario.rol_id == rolAdmin) {
            $location.path('/menuPrincipal');
          } else {
            $location.path('/ces');
          }
        }
      }, function errorCallback(response) {
        console.error(response);
      });

    };
  }]);
<commit_msg>Modificacion de controller.login<commit_after>angular.module('IMPERIUM').controller('loginController', ['$scope', 'securityService', '$localStorage', '$sessionStorage', '$location', 'rolAdmin', function ($scope, security, $localStorage, $sessionStorage, $location, rolAdmin) {
    $scope.datos = {};
    $scope.submit = function () {

      security.validateUserAndPassword($scope.datos).then(function successCallback(response) {
        console.log(response);
        $scope.usuarioErroneo = false;
        if (response.data.codigo == 500) {
          $scope.usuarioErroneo = true;
          $scope.datos = {};
        } else {
          $sessionStorage.usuario = response.data.usuario[0];
          if ($sessionStorage.usuario.rol_id == rolAdmin) {
            $location.path('/menuPrincipal');
          } else {
            $location.path('/ces');
          }
        }
      }, function errorCallback(response) {
        console.error(response);
      });

    };
  }]);
<|endoftext|>