<commit_before>import Ember from 'ember';
import ENUMS from 'irene/enums';
import ENV from 'irene/config/environment';
import { translationMacro as t } from 'ember-i18n';

const ProjectPreferencesComponent = Ember.Component.extend({

  project: null,
  selectVersion: 0,
  isSavingPreference: false,
  i18n: Ember.inject.service(),
  ajax: Ember.inject.service(),
  notify: Ember.inject.service('notification-messages-service'),
  selectedDeviceType: ENUMS.DEVICE_TYPE.NO_PREFERENCE,
  deviceTypes: ENUMS.DEVICE_TYPE.CHOICES.slice(1, -1),

  tDeviceSelected: t("deviceSelected"),
  tPleaseTryAgain: t("pleaseTryAgain"),

  devicePreference: (function() {
    return this.get("store").queryRecord('device-preference', {id: this.get("project.activeProfileId")});
  }).property(),

  devices: (function() {
    return this.get("store").findAll("device");
  }).property(),

  availableDevices: Ember.computed.filter('devices', function(device) {
    return device.get("platform") === this.get("project.platform");
  }),

  filteredDevices: Ember.computed("availableDevices", "selectedDeviceType", function() {
    const availableDevices = this.get("availableDevices");
    const selectedDeviceType = this.get("selectedDeviceType");
    return availableDevices.filter(function(device) {
      switch (selectedDeviceType) {
        case ENUMS.DEVICE_TYPE.NO_PREFERENCE:
          return true;
        case ENUMS.DEVICE_TYPE.TABLET_REQUIRED:
          return device.get("isTablet");
        case ENUMS.DEVICE_TYPE.PHONE_REQUIRED:
          return !device.get("isTablet");
      }
    });
  }),

  uniqueDevices: Ember.computed.uniqBy("filteredDevices", 'version'),

  actions: {

    selectDeviceType() {
      this.set("selectedDeviceType", parseInt(this.$('#project-device-preference').val()));
      this.set("selectVersion", 0);
    },

    selectVersion() {
      this.set("selectVersion", this.$('#project-version-preference').val());
    },

    versionSelected() {
      const selectVersion = this.get("selectVersion");
      const tDeviceSelected = this.get("tDeviceSelected");
      const tPleaseTryAgain = this.get("tPleaseTryAgain");
      const selectedDeviceType = this.get("selectedDeviceType");

      const profileId = this.get("project.activeProfileId");
      const devicePreferences = [ENV.endpoints.profiles, profileId, ENV.endpoints.devicePreferences].join('/');
      const data = {
        device_type: selectedDeviceType,
        platform_version: selectVersion
      };
      this.set("isSavingPreference", true);
      this.get("ajax").put(devicePreferences, {data})
      .then(() => {
        this.get("notify").success(tDeviceSelected);
        if(!this.isDestroyed) {
          this.set("isSavingPreference", false);
          this.set("projectPreferenceModal", false);
          this.set("devicePreference.deviceType", selectedDeviceType);
          this.set("devicePreference.platformVersion", selectVersion);
        }
      }, () => {
        if(!this.isDestroyed) {
          this.set("isSavingPreference", false);
          this.get("notify").error(tPleaseTryAgain);
        }
      });
    },

    openProjectPreferenceModal() {
      this.set("projectPreferenceModal", true);
    },

    closeProjectPreferenceModal() {
      this.set("projectPreferenceModal", false);
    }
  }
});

export default ProjectPreferencesComponent;
<commit_msg>fix: set initial value of version to "0"<commit_after>import Ember from 'ember';
import ENUMS from 'irene/enums';
import ENV from 'irene/config/environment';
import { translationMacro as t } from 'ember-i18n';

const ProjectPreferencesComponent = Ember.Component.extend({

  project: null,
  selectVersion: "0",
  isSavingPreference: false,
  i18n: Ember.inject.service(),
  ajax: Ember.inject.service(),
  notify: Ember.inject.service('notification-messages-service'),
  selectedDeviceType: ENUMS.DEVICE_TYPE.NO_PREFERENCE,
  deviceTypes: ENUMS.DEVICE_TYPE.CHOICES.slice(1, -1),

  tDeviceSelected: t("deviceSelected"),
  tPleaseTryAgain: t("pleaseTryAgain"),

  devicePreference: (function() {
    return this.get("store").queryRecord('device-preference', {id: this.get("project.activeProfileId")});
  }).property(),

  devices: (function() {
    return this.get("store").findAll("device");
  }).property(),

  availableDevices: Ember.computed.filter('devices', function(device) {
    return device.get("platform") === this.get("project.platform");
  }),

  filteredDevices: Ember.computed("availableDevices", "selectedDeviceType", function() {
    const availableDevices = this.get("availableDevices");
    const selectedDeviceType = this.get("selectedDeviceType");
    return availableDevices.filter(function(device) {
      switch (selectedDeviceType) {
        case ENUMS.DEVICE_TYPE.NO_PREFERENCE:
          return true;
        case ENUMS.DEVICE_TYPE.TABLET_REQUIRED:
          return device.get("isTablet");
        case ENUMS.DEVICE_TYPE.PHONE_REQUIRED:
          return !device.get("isTablet");
      }
    });
  }),

  uniqueDevices: Ember.computed.uniqBy("filteredDevices", 'version'),

  actions: {

    selectDeviceType() {
      this.set("selectedDeviceType", parseInt(this.$('#project-device-preference').val()));
      this.set("selectVersion", 0);
    },

    selectVersion() {
      this.set("selectVersion", this.$('#project-version-preference').val());
    },

    versionSelected() {
      const selectVersion = this.get("selectVersion");
      const tDeviceSelected = this.get("tDeviceSelected");
      const tPleaseTryAgain = this.get("tPleaseTryAgain");
      const selectedDeviceType = this.get("selectedDeviceType");

      const profileId = this.get("project.activeProfileId");
      const devicePreferences = [ENV.endpoints.profiles, profileId, ENV.endpoints.devicePreferences].join('/');
      const data = {
        device_type: selectedDeviceType,
        platform_version: selectVersion
      };
      this.set("isSavingPreference", true);
      this.get("ajax").put(devicePreferences, {data})
      .then(() => {
        this.get("notify").success(tDeviceSelected);
        if(!this.isDestroyed) {
          this.set("isSavingPreference", false);
          this.set("projectPreferenceModal", false);
          this.set("devicePreference.deviceType", selectedDeviceType);
          this.set("devicePreference.platformVersion", selectVersion);
        }
      }, () => {
        if(!this.isDestroyed) {
          this.set("isSavingPreference", false);
          this.get("notify").error(tPleaseTryAgain);
        }
      });
    },

    openProjectPreferenceModal() {
      this.set("projectPreferenceModal", true);
    },

    closeProjectPreferenceModal() {
      this.set("projectPreferenceModal", false);
    }
  }
});

export default ProjectPreferencesComponent;
<|endoftext|>


<commit_before>import Ember from "ember"
import _ from "npm:lodash"
import rpc from "../lib/rpc"
import idGen from "../lib/id-gen"
import hbs from "htmlbars-inline-precompile"
import Fetcher from "../lib/fetcher"
import { storageFor } from "ember-local-storage"

export default Ember.Component.extend({
  authenticate: Ember.inject.service(),
  session: storageFor("persistedSession"),

  isAuthenticated: Ember.computed("session.authenticatedAt", function() {
    return Date.now() - this.get("session.authenticatedAt") < 3100000
  }),

  pullRequests: Ember.computed("session.id", function() {
    var ObjectPromiseProxy = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin)
    return ObjectPromiseProxy.create({
      promise: Fetcher.find("userPullRequests", this.get("session.id")),
    })
  }),

  isAuthenticatedWatcher: Ember.observer("isAuthenticated", function() {
    if (this.get("isAuthenticated") === true) $(window).scrollTop(0)
  }),

  jurisdictions: Ember.computed(function() {
    var ObjectPromiseProxy = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin)
    return ObjectPromiseProxy.create({
      promise: Fetcher.find("jurisdiction", "index", true),
    })
  }),

  jurisdiction: Ember.computed("jurisdictionId", function() {
    var ObjectPromiseProxy = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin)
    return ObjectPromiseProxy.create({
      promise: Fetcher.find("jurisdiction", this.get("jurisdictionId")),
    })
  }),

  standardSet: Ember.computed("standardSetId", function() {
    var ObjectPromiseProxy = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin)
    return ObjectPromiseProxy.create({
      promise: Fetcher.find("standardSet", this.get("standardSetId")),
    })
  }),

  paneObserver: Ember.observer("pane", function() {
    $(window).scrollTop(0)
  }),

  scrollOnStart: Ember.on("didInsertElement", function() {
    $(window).scrollTop(0)
  }),

  actions: {
    signIn() {
      this.get("authenticate").show()
    },
    showReset() {
      this.get("authenticate").logout()
    },
    selectJurisdiction(id) {
      this.set("jurisdictionId", id)
      this.set("pane", "jurisdiction")
    },
    selectStandardSet(id) {
      this.set("standardSetId", id)
      this.set("pane", "standard-set")
    },
    goToPane(pane) {
      this.set("pane", pane)
    },
    createPullRequest() {
      Ember.set(this, "isCreatingPullRequest", true)
      rpc["pullRequest:create"](
        {},
        function(data) {
          Ember.getOwner(this)
            .lookup("router:main")
            .transitionTo("edit.pull-requests", data.data.id)
          Ember.set(this, "isCreatingPullRequest", false)
        }.bind(this),
        function(error) {
          Ember.set(this, "isCreatingPullRequest", false)
          console.error(error)
        }
      )
    },
  },

  layout: hbs`
  {{partial "navbar"}}

        Standards Creator & Editor

        Are we missing standards you rely on? Found a typo? Has your school, district or charter network created their own custom standards? Add them to the database and make them searchable!

          Welcome to the Common Standards Project editing interface. Here, you can add or edit any standard in the database or add your own. Once your standards are in the database, you can share them so your colleagues can easily search them.

How does this work?

          First, log in or sign up below. Then, add or edit standars using the easy interface. Each time someone submits a change to  the standards, we review it and then save a version. This way, if someone makes a mistake (or edits with the standards you spent hours adding), we can rollback the change. Educator rely on standards to be accurate, so we take the integrity of standards very seriously.

Who can use the standards?

          Anyone. For free! All standards that published to Common Standards Project are licensed under a Creative Commons Attribution license. This means anyone who uses standards on Common Standards Project can use them and do whatever they like with them for free! For more details, click the link.

        {{#if isAuthenticated}}

My Changes/Additions

          {{#if pullRequests.isPending}}

{{partial "icons/ripple"}}

          {{/if}}

          {{#each pullRequests.list as |pullRequest|}}

{{#link-to 'edit.pull-requests' pullRequest.id}}{{pullRequest.title}}{{/link-to}}

          {{/each}}

          {{#if isCreatingPullRequest}}

{{partial "icons/ripple"}}

          {{else}}

Create Standards

          {{/if}}
        {{else}}

Get Started!

        {{/if}}

  `,
})
<commit_msg>[front] Fix typos in copy.<commit_after>import Ember from "ember"
import _ from "npm:lodash"
import rpc from "../lib/rpc"
import idGen from "../lib/id-gen"
import hbs from "htmlbars-inline-precompile"
import Fetcher from "../lib/fetcher"
import { storageFor } from "ember-local-storage"

export default Ember.Component.extend({
  authenticate: Ember.inject.service(),
  session: storageFor("persistedSession"),

  isAuthenticated: Ember.computed("session.authenticatedAt", function() {
    return Date.now() - this.get("session.authenticatedAt") < 3100000
  }),

  pullRequests: Ember.computed("session.id", function() {
    var ObjectPromiseProxy = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin)
    return ObjectPromiseProxy.create({
      promise: Fetcher.find("userPullRequests", this.get("session.id")),
    })
  }),

  isAuthenticatedWatcher: Ember.observer("isAuthenticated", function() {
    if (this.get("isAuthenticated") === true) $(window).scrollTop(0)
  }),

  jurisdictions: Ember.computed(function() {
    var ObjectPromiseProxy = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin)
    return ObjectPromiseProxy.create({
      promise: Fetcher.find("jurisdiction", "index", true),
    })
  }),

  jurisdiction: Ember.computed("jurisdictionId", function() {
    var ObjectPromiseProxy = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin)
    return ObjectPromiseProxy.create({
      promise: Fetcher.find("jurisdiction", this.get("jurisdictionId")),
    })
  }),

  standardSet: Ember.computed("standardSetId", function() {
    var ObjectPromiseProxy = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin)
    return ObjectPromiseProxy.create({
      promise: Fetcher.find("standardSet", this.get("standardSetId")),
    })
  }),

  paneObserver: Ember.observer("pane", function() {
    $(window).scrollTop(0)
  }),

  scrollOnStart: Ember.on("didInsertElement", function() {
    $(window).scrollTop(0)
  }),

  actions: {
    signIn() {
      this.get("authenticate").show()
    },
    showReset() {
      this.get("authenticate").logout()
    },
    selectJurisdiction(id) {
      this.set("jurisdictionId", id)
      this.set("pane", "jurisdiction")
    },
    selectStandardSet(id) {
      this.set("standardSetId", id)
      this.set("pane", "standard-set")
    },
    goToPane(pane) {
      this.set("pane", pane)
    },
    createPullRequest() {
      Ember.set(this, "isCreatingPullRequest", true)
      rpc["pullRequest:create"](
        {},
        function(data) {
          Ember.getOwner(this)
            .lookup("router:main")
            .transitionTo("edit.pull-requests", data.data.id)
          Ember.set(this, "isCreatingPullRequest", false)
        }.bind(this),
        function(error) {
          Ember.set(this, "isCreatingPullRequest", false)
          console.error(error)
        }
      )
    },
  },

  layout: hbs`
  {{partial "navbar"}}

        Standards Creator & Editor

        Are we missing standards you rely on? Found a typo? Has your school, district or charter network created their own custom standards? Add them to the database and make them searchable!

          Welcome to the Common Standards Project editing interface. Here, you can add or edit any standard in the database or add your own. Once your standards are in the database, you can share them so your colleagues can easily search them.

How does this work?

          First, log in or sign up below. Then, add or edit standards using the easy interface. Each time someone submits a change to  the standards, we review it and then save a version. This way, if someone makes a mistake (or edits with the standards you spent hours adding), we can rollback the change. Educators rely on standards to be accurate, so we take the integrity of standards very seriously.

Who can use the standards?

          Anyone. For free! All standards that published to Common Standards Project are licensed under a Creative Commons Attribution license. This means anyone who uses standards on Common Standards Project can use them and do whatever they like with them for free! For more details, click the link.

        {{#if isAuthenticated}}

My Changes/Additions

          {{#if pullRequests.isPending}}

{{partial "icons/ripple"}}

          {{/if}}

          {{#each pullRequests.list as |pullRequest|}}

{{#link-to 'edit.pull-requests' pullRequest.id}}{{pullRequest.title}}{{/link-to}}

          {{/each}}

          {{#if isCreatingPullRequest}}

{{partial "icons/ripple"}}

          {{else}}

Create Standards

          {{/if}}
        {{else}}

Get Started!

        {{/if}}

  `,
})
<|endoftext|>


<commit_before>DrawingBoard.Control.Size = DrawingBoard.Control.extend({

	name: 'size',

	defaults: {
		type: "auto",
		dropdownValues: [1, 3, 6, 10, 20, 30, 40, 50]
	},

	types: ['dropdown', 'range'],

	initialize: function() {
		if (this.opts.type == "auto")
			this.opts.type = this._iHasRangeInput() ? 'range' : 'dropdown';
		var tpl = $.inArray(this.opts.type, this.types) > -1 ? this['_' + this.opts.type + 'Template']() : false;
		if (!tpl) return false;

		this.val = this.board.opts.size;

		this.$el.append( $( tpl ) );
		this.$el.attr('data-drawing-board-type', this.opts.type);
		this.updateView();

		var that = this;

		if (this.opts.type == "range") {
			this.$el.on('change', '.drawing-board-control-size-range-input', function(e) {
				that.val = $(this).val();
				that.updateView();

				that.board.ev.trigger('size:changed', that.val);

				e.preventDefault();
			});
		}

		if (this.opts.type == "dropdown") {
			this.$el.on('click', '.drawing-board-control-size-dropdown-current', $.proxy(function(e) {
				this.$el.find('.drawing-board-control-size-dropdown').toggleClass('drawing-board-utils-hidden');
			}, this));

			this.$el.on('click', '[data-size]', function(e) {
				that.val = parseInt($(this).attr('data-size'), 0);
				that.updateView();

				that.board.ev.trigger('size:changed', that.val);

				e.preventDefault();
			});
		}
	},

	_rangeTemplate: function() {
		var tpl = '
' +
			'<input type="range" min="1" max="50" value="{{size}}" step="1" class="drawing-board-control-size-range-input">' +
			'' +
			'
';
		return DrawingBoard.Utils.tpl(tpl, { size: this.board.opts.size });
	},

	_dropdownTemplate: function() {
		var tpl = '
' +
			'

' +
			'
';
		$.each(this.opts.dropdownValues, function(i, size) {
			tpl += DrawingBoard.Utils.tpl(
				'

',
				{ size: size }
			);
		});
		tpl += '

';
		return tpl;
	},

	onBoardReset: function(opts) {
		this.updateView();
	},

	updateView: function() {
		var val = this.val;
		this.board.ctx.lineWidth = val;

		this.$el.find('.drawing-board-control-size-range-current, .drawing-board-control-size-dropdown-current span').css({
			width: val + 'px',
			height: val + 'px',
			borderRadius: val + 'px',
			marginLeft: -1*val/2 + 'px',
			marginTop: -1*val/2 + 'px'
		});

		if (this.opts.type == 'dropdown') {
			var closest = null;
			$.each(this.opts.dropdownValues, function(i, size) {
				if (closest === null || Math.abs(size - val) < Math.abs(closest - val))
					closest = size;
			});
			this.$el.find('.drawing-board-control-size-dropdown').addClass('drawing-board-utils-hidden');
		}
	},

	_iHasRangeInput: function() {
		var inputElem  = document.createElement('input'),
			smile = ':)',
			docElement = document.documentElement,
			inputElemType = 'range',
			available;
		inputElem.setAttribute('type', inputElemType);
		available = inputElem.type !== 'text';
		inputElem.value         = smile;
		inputElem.style.cssText = 'position:absolute;visibility:hidden;';
		if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) {
			docElement.appendChild(inputElem);
			defaultView = document.defaultView;
			available = defaultView.getComputedStyle &&
				defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' &&
				(inputElem.offsetHeight !== 0);
			docElement.removeChild(inputElem);
		}
		return !!available;
	}
});<commit_msg>size control: the size value is on the control's title<commit_after>DrawingBoard.Control.Size = DrawingBoard.Control.extend({

	name: 'size',

	defaults: {
		type: "auto",
		dropdownValues: [1, 3, 6, 10, 20, 30, 40, 50]
	},

	types: ['dropdown', 'range'],

	initialize: function() {
		if (this.opts.type == "auto")
			this.opts.type = this._iHasRangeInput() ? 'range' : 'dropdown';
		var tpl = $.inArray(this.opts.type, this.types) > -1 ? this['_' + this.opts.type + 'Template']() : false;
		if (!tpl) return false;

		this.val = this.board.opts.size;

		this.$el.append( $( tpl ) );
		this.$el.attr('data-drawing-board-type', this.opts.type);
		this.updateView();

		var that = this;

		if (this.opts.type == "range") {
			this.$el.on('change', '.drawing-board-control-size-range-input', function(e) {
				that.val = $(this).val();
				that.updateView();

				that.board.ev.trigger('size:changed', that.val);

				e.preventDefault();
			});
		}

		if (this.opts.type == "dropdown") {
			this.$el.on('click', '.drawing-board-control-size-dropdown-current', $.proxy(function(e) {
				this.$el.find('.drawing-board-control-size-dropdown').toggleClass('drawing-board-utils-hidden');
			}, this));

			this.$el.on('click', '[data-size]', function(e) {
				that.val = parseInt($(this).attr('data-size'), 0);
				that.updateView();

				that.board.ev.trigger('size:changed', that.val);

				e.preventDefault();
			});
		}
	},

	_rangeTemplate: function() {
		var tpl = '
' +
			'<input type="range" min="1" max="50" value="{{size}}" step="1" class="drawing-board-control-size-range-input">' +
			'' +
			'
';
		return DrawingBoard.Utils.tpl(tpl, { size: this.board.opts.size });
	},

	_dropdownTemplate: function() {
		var tpl = '
' +
			'

' +
			'
';
		$.each(this.opts.dropdownValues, function(i, size) {
			tpl += DrawingBoard.Utils.tpl(
				'

',
				{ size: size }
			);
		});
		tpl += '

';
		return tpl;
	},

	onBoardReset: function(opts) {
		this.updateView();
	},

	updateView: function() {
		var val = this.val;
		this.board.ctx.lineWidth = val;

		this.$el.find('.drawing-board-control-size-range-current, .drawing-board-control-size-dropdown-current span').css({
			width: val + 'px',
			height: val + 'px',
			borderRadius: val + 'px',
			marginLeft: -1*val/2 + 'px',
			marginTop: -1*val/2 + 'px'
		});

		this.$el.find('.drawing-board-control-inner').attr('title', val);

		if (this.opts.type == 'dropdown') {
			var closest = null;
			$.each(this.opts.dropdownValues, function(i, size) {
				if (closest === null || Math.abs(size - val) < Math.abs(closest - val))
					closest = size;
			});
			this.$el.find('.drawing-board-control-size-dropdown').addClass('drawing-board-utils-hidden');
		}
	},

	_iHasRangeInput: function() {
		var inputElem  = document.createElement('input'),
			smile = ':)',
			docElement = document.documentElement,
			inputElemType = 'range',
			available;
		inputElem.setAttribute('type', inputElemType);
		available = inputElem.type !== 'text';
		inputElem.value         = smile;
		inputElem.style.cssText = 'position:absolute;visibility:hidden;';
		if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) {
			docElement.appendChild(inputElem);
			defaultView = document.defaultView;
			available = defaultView.getComputedStyle &&
				defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' &&
				(inputElem.offsetHeight !== 0);
			docElement.removeChild(inputElem);
		}
		return !!available;
	}
});<|endoftext|>


<commit_before>var http = require("http");
var sys = require("sys");

module.exports = (function (api_key, options) {
  if (typeof api_key == undefined)  {
    throw("You must provide your postmark API key");
  }
  if (typeof options === 'undefined')  { options = {}; }
  if (options.ssl && options.ssl !== true) { options.ssl = false; }

  return {
    send: function(message, callback) {

      var valid_parameters = ["From", "To", "Cc", "Bcc", "Subject", "Tag", "HtmlBody", "TextBody", "ReplyTo", "Headers", "Attachments"]
      var valid_attachment_parameters = ["Name", "Content", "ContentType"];
      var attr, attach;
      for (attr in message) {
        if (valid_parameters.indexOf(attr) < 0)  {
          throw("You can only provide attributes that work with the Postmark JSON message format. Details: http://developer.postmarkapp.com/developer-build.html#message-format");
        }
        if (attr == "Attachments") {
          for(attach in message[attr])  {
            var attach_attr;
            for (attach_attr in message[attr][attach])  {
              if (valid_attachment_parameters.indexOf(attach_attr) < 0)  {
                throw("You can only provide attributes for attachments that work with the Postmark JSON message format. Details: http://developer.postmarkapp.com/developer-build.html#attachments");
              }
            }
          }
        }
      }

      postmark_headers = {
        "Accept":  "application/json",
        "Content-Type":  "application/json",
        "X-Postmark-Server-Token":  api_key
      }

      var req = http.request({
        host: "api.postmarkapp.com",
        path: "/email",
        method: "POST",
        headers: postmark_headers,
        port: (options.ssl ? 443 : 80)
      }, function (error, response, body) {
        if (response.statusCode == 401) {
          throw("Incorrect Postmark API Key header")
        } else if (response.statusCode == 422)  {
          throw("Incorrect or Malformed JSON message: "+JSON.parse(body["Message"]))
        } else if (response.statusCode == 200) {
          return true;
        } else  {
          throw("Something wrong with Postmark");
        }
      });

      req.write(JSON.stringify(message));
      req.end();
    }
  }
});<commit_msg>Fixed issue with http request callback parameter order.<commit_after>var http = require("http");
var sys = require("sys");

module.exports = (function (api_key, options) {
  if (typeof api_key == undefined)  {
    throw("You must provide your postmark API key");
  }
  if (typeof options === 'undefined')  { options = {}; }
  if (options.ssl && options.ssl !== true) { options.ssl = false; }

  return {
    send: function(message, callback) {

      var valid_parameters = ["From", "To", "Cc", "Bcc", "Subject", "Tag", "HtmlBody", "TextBody", "ReplyTo", "Headers", "Attachments"]
      var valid_attachment_parameters = ["Name", "Content", "ContentType"];
      var attr, attach;
      for (attr in message) {
        if (valid_parameters.indexOf(attr) < 0)  {
          throw("You can only provide attributes that work with the Postmark JSON message format. Details: http://developer.postmarkapp.com/developer-build.html#message-format");
        }
        if (attr == "Attachments") {
          for(attach in message[attr])  {
            var attach_attr;
            for (attach_attr in message[attr][attach])  {
              if (valid_attachment_parameters.indexOf(attach_attr) < 0)  {
                throw("You can only provide attributes for attachments that work with the Postmark JSON message format. Details: http://developer.postmarkapp.com/developer-build.html#attachments");
              }
            }
          }
        }
      }

      postmark_headers = {
        "Accept":  "application/json",
        "Content-Type":  "application/json",
        "X-Postmark-Server-Token":  api_key
      }

      var req = http.request({
        host: "api.postmarkapp.com",
        path: "/email",
        method: "POST",
        headers: postmark_headers,
        port: (options.ssl ? 443 : 80)
      }, function (response) {
        if (response.statusCode == 401) {
          throw("Incorrect Postmark API Key header")
        } else if (response.statusCode == 422)  {
          throw("Incorrect or Malformed JSON message: "+JSON.parse(body["Message"]))
        } else if (response.statusCode == 200) {
          return true;
        } else  {
          throw("Something wrong with Postmark");
        }
      });

      req.write(JSON.stringify(message));
      req.end();
    }
  }
});
<|endoftext|>


<commit_before>$(function() {
	var today = new Date();

	$("#data").datepicker({
		dateFormat: "dd/mm/yy",
		minDate: validaMinDate(),
		maxDate: today
	});

	$('#lancarDiario').click(function(){
		var form = $('#data-form');

		if ($('select[name="fal_quantidade_aulas"]').val() != '')
       		submitAjax(form);
       	else
       		alert('showMsgQtdAulas');
	})

	$('#buscarAlunos').click(function(){
		removeValoresEditar();

		$(".alert-success, .alert-danger").addClass('hide');
		if(validaFormDiario()){
			$('#lancarDiario').removeAttr('disabled');
			buscarAlunos();
			validaDiarioEditar();
		}
	})

	$('#data').change(function(){
		$('#auxLancamentos').html('');
		validaDiaLetivo($(this).val());
	})

	buscarTurmas();

	$('select[name="tur_id"]').on('change', function(){
		$('#auxLancamentos').html('');
		buscarDisciplinaPorTurmaProfessor($(this).val());
	})

	$('select[name="dis_id"]').on('change', function(){
		$('#auxLancamentos').html('');
	})
});

function submitAjax(form){
	$.ajax({
		data: form.serialize(),
		url: '../diario/salvar',
		type: 'POST',
		dataType: 'json',
		async: false,
		success: function(r){
			if(r == 'editado')
				$(".alert-success.editado").removeClass('hide');
			else if (r)
				$(".alert-success.inserido").removeClass('hide');
			else
				$(".alert-danger").removeClass('hide');

			$('#auxLancamentos').html('');
		}
	})
}

function buscarAlunos(){
	var turma = $('select[name="tur_id"]').val();

	$.ajax({
		data: 'tur_id='+turma,
		url: '../turma/buscarTurma',
		type: 'POST',
		dataType: 'json',
		async: false,
		success: function(r){
			if(r){
				preencheAlunos(r);
			}
		}
	})
}

function preencheAlunos(dados){
	var cont = dados.alunos.length;
	var alunos = '';
	var faltas = '';
	var mtop = '';
	var aniversario = '';
	var year = $('#data').val().substr(6, 4);
	var dia = $('#data').val().substr(0, 2);
	var mes = $('#data').val().substr(3, 2);
	var dataPrincipal = new Date(year, mes - 1, dia);
	var auxSunday = dataPrincipal.getDate() - dataPrincipal.getDay();
	var dataAluno = '';
	auxSunday = dataPrincipal.getDay() == 0 ? auxSunday - 6 : auxSunday + 1;

	var lastSunday = new Date(dataPrincipal.setDate(auxSunday));
	var nextMonday = new Date(dataPrincipal.setDate(auxSunday + 6));

	for(var i = 0; i < cont; i++){
		mtop = (i > 0) ? ' style="margin-top: 5px" ' : '';

		alunos += '<input disabled="disabled" class="form-control" value="'+ dados.alunos[i].alu_nome +'" '+ mtop +'>';

		faltas += '<input class="form-control" maxlength="2" name="faltas['+ dados.alunos[i].alu_id +']" value="0" '+ mtop +'>';

		dataAluno = new Date(dados.alunos[i].alu_data_nascimento + ' 00:00:00');
		dataAluno = new Date(dataAluno.setFullYear(year));

		var auxData = dados.alunos[i].alu_data_nascimento.split('-');
		var data = auxData[2] + '/' + auxData[1];
		var icon = '';
		var pull = '';

		var first = i == 0 ? 'first' : '';
		if(dataAluno >= lastSunday && dataAluno <= nextMonday){
			icon = '';
			pull = ' pull-left ';
		}

		aniversario += '
<input disabled="disabled" class="form-control '+ pull +' input-mini" value="'+ data +'" '+ mtop +'>';

		aniversario += icon + '
';
	}

	var html = '
'+
                    'Conteúdo: '+
                    '<textarea class="form-control" name="conteudo" rows="3" style="resize: none"></textarea>'+
                '
'+
                '

'+
                '
'+
                    'Tarefa/Casa: '+
                    '<textarea class="form-control" name="tarefa" rows="2" style="resize: none"></textarea>'+
                '
'+
                '

'+
                '
'+
                    'Observações: '+
                    '<textarea class="form-control" name="observacao" rows="2" style="resize: none"></textarea>'+
                '
'+
                '

'+
                '

'+
                ''+
                '
'+
                ''+
				'Aniversariantes da Semana'+
				'
'+
                '
'+
                    'Aluno: '+
                    alunos+
                '
'+
                '
'+
                    'Faltas: '+
                    faltas+
                '
'+
                '
'+
                	'Aniversário: '+
                    aniversario+
                '
'+
                '

'+
                '
'+
                	'Quantidade de Aulas * '+
                	'<select data-required="true" class="form-control" name="fal_quantidade_aulas">'+
                		'<option value="">Selecione</option>'+
                		'<option value="1">1</option>'+
                		'<option value="2">2</option>'+
                		'<option value="3">3</option>'+
                	'</select>'+
                '
';

    $('#auxLancamentos').html(html);
}

function validaFormDiario(){
	var retorno = true;

	$('.form-group input, .form-group select').css('border-color', '#ccc');

	$('input[data-required="true"], select[data-required="true"]').each(function(){
		if ($(this).val() == ''){
			$(this).css('border-color', '#a94442');
			retorno = false;
		}
	})

	return retorno;
}

function validaDiaLetivo(dia_letivo){
	var tur_id = $('select[name="tur_id"]').val();

	if (tur_id){
		$.ajax({
			data: 'dia_letivo='+dia_letivo+'&tur_id='+tur_id,
			url: '../dia_letivo/buscarDiaLetivo',
			type: 'POST',
			dataType: 'json',
			async: false,
			success: function(r){
				if (r.length < 1){
					$('#data').val('');
					alert('A data selecionada não é um dia letivo.');
				}
			}
		})
	} else {
		alert('Selecione uma turma antes de selcionar uma data');
		$('#data').val('');
	}
}

function validaMinDate(){
	var perfil = $('input[name="per"]').val();
	var minDate = new Date(new Date().getFullYear(), 0, 1);

	//if (perfil == 4){
	if (4==5){
		var today = new Date();
		var first = today.getDate() - today.getDay();
		first = today.getDay() == 0 ? first - 6 : first + 1;

		minDate = new Date(today.setDate(first));
	}

	return minDate;
}

function buscarTurmas(){
	$.ajax({
		url: '../turma/buscarTurmaPerfil',
		type: 'POST',
		dataType: 'json',
		async: false,
		success: function(r){
			if (r){
				var html = '<option value="">Selecione</option>';
				var cont = r.length;

				for(var i = 0; i < cont; i++){
					html += "<option value='"+ r[i].tur_id +"'>"+ r[i].tur_nome +" "+ r[i].tur_ano +"</option>";
				}

				$('select[name="tur_id"]').html(html);
			}
		}
	})
}

function buscarDisciplinaPorTurmaProfessor(tur_id){
	$('#data').val('');

	if(tur_id){
		$.ajax({
			data: 'tur_id='+tur_id,
			url: '../disciplina/buscarDisciplinaPorTurmaProfessor',
			type: 'POST',
			dataType: 'json',
			async: false,
			success: function(r){
				if (r){
					var html = '<option value="">Selecione</option>';
					var cont = r.length;

					for(var i = 0; i < cont; i++){
						html += "<option value='"+ r[i].dis_id +"'>"+ r[i].dis_nome +"</option>";
					}

					$('select[name="dis_id"]').html(html);
				}
			}
		})
	}
}

function validaDiarioEditar(){

	var tur_id = $('select[name="tur_id"]').val();
	var dis_id = $('select[name="dis_id"]').val();
	var dia = $('input[name="dia_letivo"]').val();
	var perfil = $('input[name="per"]').val();

	$.ajax({
		data: 'tur_id='+tur_id+'&dis_id='+dis_id+'&dia='+dia,
		url: '../diario/buscarDiario',
		type: 'POST',
		dataType: 'json',
		async: false,
		success: function(r){
			if (r && r.conteudo){
				preencheCamposEditar(r);
				if(perfil == 4)
					removeValoresEditar();
			}
		}
	})
}

function preencheCamposEditar(dados){
	var cont = dados.faltas.length;
	var faltas = '';

	$('textarea[name="conteudo"]').val(dados.conteudo.con_conteudo);
	$('input[name="con_id"]').val(dados.conteudo.con_id);

	$('textarea[name="observacao"]').val(dados.observacao.obs_observacao);
	$('input[name="obs_id"]').val(dados.observacao.obs_id);

	$('textarea[name="tarefa"]').val(dados.tarefa.tar_tarefa);
	$('input[name="tar_id"]').val(dados.tarefa.tar_id);

	$('select[name="fal_quantidade_aulas"]').val(dados.faltas[0].fal_quantidade_aulas);

	for(var i = 0; i < cont; i++){
		$('input[name="faltas['+ dados.faltas[i].alu_id +']"]').val(dados.faltas[i].fal_falta);
		faltas = $('input[name="atds_id"]').val();
		$('input[name="atds_id"]').val(dados.faltas[i].fal_id + '/' + dados.faltas[i].alu_id + '@' + faltas);
	}
}

function removeValoresEditar(){
	$('input[name="con_id"], input[name="atds_id"], input[name="obs_id"], input[name="tar_id"]').val('');
	$('#lancarDiario').attr('disabled', 'disabled');
}<commit_msg>correção msg qtd aulas diario js7<commit_after>$(function() {
	var today = new Date();

	$("#data").datepicker({
		dateFormat: "dd/mm/yy",
		minDate: validaMinDate(),
		maxDate: today
	});

	$('#lancarDiario').click(function(){
		var form = $('#data-form');

		if ($('select[name="fal_quantidade_aulas"]').val() != '')
       		submitAjax(form);
       	else
       		alert('Selecione a quantidade de aulas.');
	})

	$('#buscarAlunos').click(function(){
		removeValoresEditar();

		$(".alert-success, .alert-danger").addClass('hide');
		if(validaFormDiario()){
			$('#lancarDiario').removeAttr('disabled');
			buscarAlunos();
			validaDiarioEditar();
		}
	})

	$('#data').change(function(){
		$('#auxLancamentos').html('');
		validaDiaLetivo($(this).val());
	})

	buscarTurmas();

	$('select[name="tur_id"]').on('change', function(){
		$('#auxLancamentos').html('');
		buscarDisciplinaPorTurmaProfessor($(this).val());
	})

	$('select[name="dis_id"]').on('change', function(){
		$('#auxLancamentos').html('');
	})
});

function submitAjax(form){
	$.ajax({
		data: form.serialize(),
		url: '../diario/salvar',
		type: 'POST',
		dataType: 'json',
		async: false,
		success: function(r){
			if(r == 'editado')
				$(".alert-success.editado").removeClass('hide');
			else if (r)
				$(".alert-success.inserido").removeClass('hide');
			else
				$(".alert-danger").removeClass('hide');

			$('#auxLancamentos').html('');
		}
	})
}

function buscarAlunos(){
	var turma = $('select[name="tur_id"]').val();

	$.ajax({
		data: 'tur_id='+turma,
		url: '../turma/buscarTurma',
		type: 'POST',
		dataType: 'json',
		async: false,
		success: function(r){
			if(r){
				preencheAlunos(r);
			}
		}
	})
}

function preencheAlunos(dados){
	var cont = dados.alunos.length;
	var alunos = '';
	var faltas = '';
	var mtop = '';
	var aniversario = '';
	var year = $('#data').val().substr(6, 4);
	var dia = $('#data').val().substr(0, 2);
	var mes = $('#data').val().substr(3, 2);
	var dataPrincipal = new Date(year, mes - 1, dia);
	var auxSunday = dataPrincipal.getDate() - dataPrincipal.getDay();
	var dataAluno = '';
	auxSunday = dataPrincipal.getDay() == 0 ? auxSunday - 6 : auxSunday + 1;

	var lastSunday = new Date(dataPrincipal.setDate(auxSunday));
	var nextMonday = new Date(dataPrincipal.setDate(auxSunday + 6));

	for(var i = 0; i < cont; i++){
		mtop = (i > 0) ? ' style="margin-top: 5px" ' : '';

		alunos += '<input disabled="disabled" class="form-control" value="'+ dados.alunos[i].alu_nome +'" '+ mtop +'>';

		faltas += '<input class="form-control" maxlength="2" name="faltas['+ dados.alunos[i].alu_id +']" value="0" '+ mtop +'>';

		dataAluno = new Date(dados.alunos[i].alu_data_nascimento + ' 00:00:00');
		dataAluno = new Date(dataAluno.setFullYear(year));

		var auxData = dados.alunos[i].alu_data_nascimento.split('-');
		var data = auxData[2] + '/' + auxData[1];
		var icon = '';
		var pull = '';

		var first = i == 0 ? 'first' : '';
		if(dataAluno >= lastSunday && dataAluno <= nextMonday){
			icon = '';
			pull = ' pull-left ';
		}

		aniversario += '
<input disabled="disabled" class="form-control '+ pull +' input-mini" value="'+ data +'" '+ mtop +'>';

		aniversario += icon + '
';
	}

	var html = '
'+
                    'Conteúdo: '+
                    '<textarea class="form-control" name="conteudo" rows="3" style="resize: none"></textarea>'+
                '
'+
                '

'+
                '
'+
                    'Tarefa/Casa: '+
                    '<textarea class="form-control" name="tarefa" rows="2" style="resize: none"></textarea>'+
                '
'+
                '

'+
                '
'+
                    'Observações: '+
                    '<textarea class="form-control" name="observacao" rows="2" style="resize: none"></textarea>'+
                '
'+
                '

'+
                '

'+
                ''+
                '
'+
                ''+
				'Aniversariantes da Semana'+
				'
'+
                '
'+
                    'Aluno: '+
                    alunos+
                '
'+
                '
'+
                    'Faltas: '+
                    faltas+
                '
'+
                '
'+
                	'Aniversário: '+
                    aniversario+
                '
'+
                '

'+
                '
'+
                	'Quantidade de Aulas * '+
                	'<select data-required="true" class="form-control" name="fal_quantidade_aulas">'+
                		'<option value="">Selecione</option>'+
                		'<option value="1">1</option>'+
                		'<option value="2">2</option>'+
                		'<option value="3">3</option>'+
                	'</select>'+
                '
';

    $('#auxLancamentos').html(html);
}

function validaFormDiario(){
	var retorno = true;

	$('.form-group input, .form-group select').css('border-color', '#ccc');

	$('input[data-required="true"], select[data-required="true"]').each(function(){
		if ($(this).val() == ''){
			$(this).css('border-color', '#a94442');
			retorno = false;
		}
	})

	return retorno;
}

function validaDiaLetivo(dia_letivo){
	var tur_id = $('select[name="tur_id"]').val();

	if (tur_id){
		$.ajax({
			data: 'dia_letivo='+dia_letivo+'&tur_id='+tur_id,
			url: '../dia_letivo/buscarDiaLetivo',
			type: 'POST',
			dataType: 'json',
			async: false,
			success: function(r){
				if (r.length < 1){
					$('#data').val('');
					alert('A data selecionada não é um dia letivo.');
				}
			}
		})
	} else {
		alert('Selecione uma turma antes de selcionar uma data');
		$('#data').val('');
	}
}

function validaMinDate(){
	var perfil = $('input[name="per"]').val();
	var minDate = new Date(new Date().getFullYear(), 0, 1);

	//if (perfil == 4){
	if (4==5){
		var today = new Date();
		var first = today.getDate() - today.getDay();
		first = today.getDay() == 0 ? first - 6 : first + 1;

		minDate = new Date(today.setDate(first));
	}

	return minDate;
}

function buscarTurmas(){
	$.ajax({
		url: '../turma/buscarTurmaPerfil',
		type: 'POST',
		dataType: 'json',
		async: false,
		success: function(r){
			if (r){
				var html = '<option value="">Selecione</option>';
				var cont = r.length;

				for(var i = 0; i < cont; i++){
					html += "<option value='"+ r[i].tur_id +"'>"+ r[i].tur_nome +" "+ r[i].tur_ano +"</option>";
				}

				$('select[name="tur_id"]').html(html);
			}
		}
	})
}

function buscarDisciplinaPorTurmaProfessor(tur_id){
	$('#data').val('');

	if(tur_id){
		$.ajax({
			data: 'tur_id='+tur_id,
			url: '../disciplina/buscarDisciplinaPorTurmaProfessor',
			type: 'POST',
			dataType: 'json',
			async: false,
			success: function(r){
				if (r){
					var html = '<option value="">Selecione</option>';
					var cont = r.length;

					for(var i = 0; i < cont; i++){
						html += "<option value='"+ r[i].dis_id +"'>"+ r[i].dis_nome +"</option>";
					}

					$('select[name="dis_id"]').html(html);
				}
			}
		})
	}
}

function validaDiarioEditar(){

	var tur_id = $('select[name="tur_id"]').val();
	var dis_id = $('select[name="dis_id"]').val();
	var dia = $('input[name="dia_letivo"]').val();
	var perfil = $('input[name="per"]').val();

	$.ajax({
		data: 'tur_id='+tur_id+'&dis_id='+dis_id+'&dia='+dia,
		url: '../diario/buscarDiario',
		type: 'POST',
		dataType: 'json',
		async: false,
		success: function(r){
			if (r && r.conteudo){
				preencheCamposEditar(r);
				if(perfil == 4)
					removeValoresEditar();
			}
		}
	})
}

function preencheCamposEditar(dados){
	var cont = dados.faltas.length;
	var faltas = '';

	$('textarea[name="conteudo"]').val(dados.conteudo.con_conteudo);
	$('input[name="con_id"]').val(dados.conteudo.con_id);

	$('textarea[name="observacao"]').val(dados.observacao.obs_observacao);
	$('input[name="obs_id"]').val(dados.observacao.obs_id);

	$('textarea[name="tarefa"]').val(dados.tarefa.tar_tarefa);
	$('input[name="tar_id"]').val(dados.tarefa.tar_id);

	$('select[name="fal_quantidade_aulas"]').val(dados.faltas[0].fal_quantidade_aulas);

	for(var i = 0; i < cont; i++){
		$('input[name="faltas['+ dados.faltas[i].alu_id +']"]').val(dados.faltas[i].fal_falta);
		faltas = $('input[name="atds_id"]').val();
		$('input[name="atds_id"]').val(dados.faltas[i].fal_id + '/' + dados.faltas[i].alu_id + '@' + faltas);
	}
}

function removeValoresEditar(){
	$('input[name="con_id"], input[name="atds_id"], input[name="obs_id"], input[name="tar_id"]').val('');
	$('#lancarDiario').attr('disabled', 'disabled');
}<|endoftext|>


<commit_before>// Grouping module
;(function($){
$.jgrid.extend({
	groupingSetup : function () {
		return this.each(function (){
			var $t = this,
			grp = $t.p.groupingView;
			if(grp !== null && ( (typeof grp === 'object') || $.isFunction(grp) ) ) {
				if(!grp.groupField.length) {
					$t.p.grouping = false;
				} else {
					if ( typeof(grp.visibiltyOnNextGrouping) == 'undefined') {
						grp.visibiltyOnNextGrouping = [];
					}
					for(var i=0;i<grp.groupField.length;i++) {
						if(!grp.groupOrder[i]) {
							grp.groupOrder[i] = 'asc';
						}
						if(!grp.groupText[i]) {
							grp.groupText[i] = '{0}';
						}
						if( typeof(grp.groupColumnShow[i]) != 'boolean') {
							grp.groupColumnShow[i] = true;
						}
						if( typeof(grp.groupSummary[i]) != 'boolean') {
							grp.groupSummary[i] = false;
						}
						if(grp.groupColumnShow[i] === true) {
							grp.visibiltyOnNextGrouping[i] = true;
							$($t).jqGrid('showCol',grp.groupField[i]);
						} else {
							grp.visibiltyOnNextGrouping[i] = $("#"+$t.p.id+"_"+grp.groupField[i]).is(":visible");
							$($t).jqGrid('hideCol',grp.groupField[i]);
						}
						grp.sortitems[i] = [];
						grp.sortnames[i] = [];
						grp.summaryval[i] = [];
						if(grp.groupSummary[i]) {
							grp.summary[i] =[];
							var cm = $t.p.colModel;
							for(var j=0, cml = cm.length; j < cml; j++) {
								if(cm[j].summaryType) {
									grp.summary[i].push({nm:cm[j].name,st:cm[j].summaryType, v:''});
								}
							}
						}
					}
					$t.p.scroll = false;
					$t.p.rownumbers = false;
					$t.p.subGrid = false;
					$t.p.treeGrid = false;
					$t.p.gridview = true;
				}
			} else {
				$t.p.grouping = false;
			}
		});
	},
	groupingPrepare : function (rData, items, gdata, record) {
		this.each(function(){
			// currently only one level
			// Is this a good idea to do it so!!!!?????
			items[0]  += "";
			var itm = items[0].toString().split(' ').join('');

			var grp = this.p.groupingView, $t= this;
			if(gdata.hasOwnProperty(itm)) {
				gdata[itm].push(rData);
			} else {
				gdata[itm] = [];
				gdata[itm].push(rData);
				grp.sortitems[0].push(itm);
				grp.sortnames[0].push($.trim(items[0].toString()));
				grp.summaryval[0][itm] = $.extend(true,[],grp.summary[0]);
			}
			if(grp.groupSummary[0]) {
				$.each(grp.summaryval[0][itm],function(i,n) {
					if ($.isFunction(this.st)) {
						this.v = this.st.call($t, this.v, this.nm, record);
					} else {
						this.v = $($t).jqGrid('groupingCalculations.'+this.st, this.v, this.nm, record);
					}
				});
			}
		});
		return gdata;
	},
	groupingToggle : function(hid){
		this.each(function(){
			var $t = this,
			grp = $t.p.groupingView,
			strpos = hid.lastIndexOf('_'),
			uid = hid.substring(0,strpos+1),
			num = parseInt(hid.substring(strpos+1),10)+1,
			minus = grp.minusicon,
			plus = grp.plusicon,
			tar = $("#"+hid),
			r = tar[0].nextSibling,
			tarspan = $("#"+hid+" span."+"tree-wrap-"+$t.p.direction),
			collapsed = false;
			if( tarspan.hasClass(minus) ) {
				if(grp.showSummaryOnHide && grp.groupSummary[0]) {
					if(r){
						while(r) {
							if($(r).hasClass('jqfoot') ) { break; }
							$(r).hide();
							r = r.nextSibling;
						}
					}
				} else  {
					if(r){
						while(r) {
							if($(r).attr('id') ==uid+String(num) ) { break; }
							$(r).hide();
							r = r.nextSibling;
				}
					}
				}
				tarspan.removeClass(minus).addClass(plus);
				collapsed = true;
			} else {
				if(r){
					while(r) {
						if($(r).attr('id') ==uid+String(num) ) { break; }
						$(r).show();
						r = r.nextSibling;
					}
				}
				tarspan.removeClass(plus).addClass(minus);
				collapsed = false;
			}
			if( $.isFunction($t.p.onClickGroup)) { $t.p.onClickGroup.call($t, hid , collapsed); }

		});
		return false;
	},
	groupingRender : function (grdata, colspans ) {
		return this.each(function(){
			var $t = this,
			grp = $t.p.groupingView,
			str = "", icon = "", hid, pmrtl ="", gv, cp, ii;
			//only one level for now
			if(!grp.groupDataSorted) {
				// ???? TO BE IMPROVED
				grp.sortitems[0].sort();
				grp.sortnames[0].sort();
				if(grp.groupOrder[0].toLowerCase() == 'desc')
				{
					grp.sortitems[0].reverse();
					grp.sortnames[0].reverse();
				}
			}
			if(grp.groupCollapse) { pmrtl = grp.plusicon; }
			else {pmrtl = grp.minusicon;}
			pmrtl += " tree-wrap-"+$t.p.direction;
			ii = 0;
			while(ii < colspans) {
				if($t.p.colModel[ii].name == grp.groupField[0]) {
					cp = ii;
					break;
				}
				ii++;
			}
			$.each(grp.sortitems[0],function(i,n){
				hid = $t.p.id+"ghead_"+i;
				icon = "";
				try {
					gv = $t.formatter(hid, grp.sortnames[0][i], cp, grp.sortitems[0] );
				} catch (egv) {
					gv = grp.sortnames[0][i];
				}
				str += "
"+icon+$.jgrid.format(grp.groupText[0], gv, grdata[n].length)+"
";
				for(var kk=0;kk<grdata[n].length;kk++) {
					str += grdata[n][kk].join('');
				}
				if(grp.groupSummary[0]) {
					var hhdr = "";
					if(grp.groupCollapse && !grp.showSummaryOnHide) {
						hhdr = " style=\"display:none;\"";
					}
					str += "
";
					var fdata = grp.summaryval[0][n],
					cm = $t.p.colModel,
					vv, grlen = grdata[n].length;
					for(var k=0; k<colspans;k++) {
						var tmpdata = " 	",
						tplfld = "{0}";
						$.each(fdata,function(){
							if(this.nm == cm[k].name) {
								if(cm[k].summaryTpl)  {
									tplfld = cm[k].summaryTpl;
								}
								if(this.st == 'avg') {
									if(this.v && grlen > 0) {
										this.v = (this.v/grlen);
									}
								}
								try {
									vv = $t.formatter('', this.v, k, this);
								} catch (ef) {
									vv = this.v;
								}
								tmpdata= ""+$.jgrid.format(tplfld,vv)+ "	";
								return false;
							}
						});
						str += tmpdata;
					}
					str += "
";
				}
			});
			$("#"+$t.p.id+" tbody:first").append(str);
			// free up memory
			str = null;
		});
	},
	groupingGroupBy : function (name, options, current) {
		return this.each(function(){
			var $t = this;
			if(typeof(name) == "string") {
				name = [name];
			}
			var grp = $t.p.groupingView;
			$t.p.grouping = true;
      // show previous hidden groups if they are hidden and weren't removed yet
      for(var i=0;i<grp.groupField.length;i++) {
        if(!grp.groupColumnShow[i] && grp.visibiltyOnNextGrouping[i]) {
          $($t).jqGrid('showCol',grp.groupField[i]);
        }
      }
      // set visibility status of current group columns on next grouping
      for(var i=0;i<name.length;i++) {
        grp.visibiltyOnNextGrouping[i] = $("#"+$t.p.id+"_"+name[i]).is(":visible");
      }
			$t.p.groupingView = $.extend($t.p.groupingView, options || {});
			grp.groupField = name;
			$($t).trigger("reloadGrid");
		});
	},
	groupingRemove : function (current) {
		return this.each(function(){
			var $t = this;
			if(typeof(current) == 'undefined') {
				current = true;
			}
			$t.p.grouping = false;
			if(current===true) {
        var grp = $t.p.groupingView;
        // show previous hidden groups if they are hidden and weren't removed yet
        for(var i=0;i<grp.groupField.length;i++) {
          if (!grp.groupColumnShow[i] && grp.visibiltyOnNextGrouping[i]) {
            $($t).jqGrid('showCol', grp.groupField);
          }
        }
				$("tr.jqgroup, tr.jqfoot","#"+$t.p.id+" tbody:first").remove();
				$("tr.jqgrow:hidden","#"+$t.p.id+" tbody:first").show();
			} else {
				$($t).trigger("reloadGrid");
			}
		});
	},
	groupingCalculations : {
		"sum" : function(v, field, rc) {
			return parseFloat(v||0) + parseFloat((rc[field]||0));
		},
		"min" : function(v, field, rc) {
			if(v==="") {
				return parseFloat(rc[field]||0);
			}
			return Math.min(parseFloat(v),parseFloat(rc[field]||0));
		},
		"max" : function(v, field, rc) {
			if(v==="") {
				return parseFloat(rc[field]||0);
			}
			return Math.max(parseFloat(v),parseFloat(rc[field]||0));
		},
		"count" : function(v, field, rc) {
			if(v==="") {v=0;}
			if(rc.hasOwnProperty(field)) {
				return v+1;
			} else {
				return 0;
			}
		},
		"avg" : function(v, field, rc) {
			// the same as sum, but at end we divide it
			return parseFloat(v||0) + parseFloat((rc[field]||0));
		}
	}
});
})(jQuery);
<commit_msg>checking for existence of underlying element before referencing it (there was an error in IE7/8)<commit_after>// Grouping module
;(function($){
$.jgrid.extend({
	groupingSetup : function () {
		return this.each(function (){
			var $t = this,
			grp = $t.p.groupingView;
			if(grp !== null && ( (typeof grp === 'object') || $.isFunction(grp) ) ) {
				if(!grp.groupField.length) {
					$t.p.grouping = false;
				} else {
					if ( typeof(grp.visibiltyOnNextGrouping) == 'undefined') {
						grp.visibiltyOnNextGrouping = [];
					}
					for(var i=0;i<grp.groupField.length;i++) {
						if(!grp.groupOrder[i]) {
							grp.groupOrder[i] = 'asc';
						}
						if(!grp.groupText[i]) {
							grp.groupText[i] = '{0}';
						}
						if( typeof(grp.groupColumnShow[i]) != 'boolean') {
							grp.groupColumnShow[i] = true;
						}
						if( typeof(grp.groupSummary[i]) != 'boolean') {
							grp.groupSummary[i] = false;
						}
						if(grp.groupColumnShow[i] === true) {
							grp.visibiltyOnNextGrouping[i] = true;
							$($t).jqGrid('showCol',grp.groupField[i]);
						} else {
							grp.visibiltyOnNextGrouping[i] = $("#"+$t.p.id+"_"+grp.groupField[i]).is(":visible");
							$($t).jqGrid('hideCol',grp.groupField[i]);
						}
						grp.sortitems[i] = [];
						grp.sortnames[i] = [];
						grp.summaryval[i] = [];
						if(grp.groupSummary[i]) {
							grp.summary[i] =[];
							var cm = $t.p.colModel;
							for(var j=0, cml = cm.length; j < cml; j++) {
								if(cm[j].summaryType) {
									grp.summary[i].push({nm:cm[j].name,st:cm[j].summaryType, v:''});
								}
							}
						}
					}
					$t.p.scroll = false;
					$t.p.rownumbers = false;
					$t.p.subGrid = false;
					$t.p.treeGrid = false;
					$t.p.gridview = true;
				}
			} else {
				$t.p.grouping = false;
			}
		});
	},
	groupingPrepare : function (rData, items, gdata, record) {
		this.each(function(){
			// currently only one level
			// Is this a good idea to do it so!!!!?????
			items[0]  += "";
			var itm = items[0].toString().split(' ').join('');

			var grp = this.p.groupingView, $t= this;
			if(gdata.hasOwnProperty(itm)) {
				gdata[itm].push(rData);
			} else {
				gdata[itm] = [];
				gdata[itm].push(rData);
				grp.sortitems[0].push(itm);
				grp.sortnames[0].push($.trim(items[0].toString()));
				grp.summaryval[0][itm] = $.extend(true,[],grp.summary[0]);
			}
			if(grp.groupSummary[0]) {
				$.each(grp.summaryval[0][itm],function(i,n) {
					if ($.isFunction(this.st)) {
						this.v = this.st.call($t, this.v, this.nm, record);
					} else {
						this.v = $($t).jqGrid('groupingCalculations.'+this.st, this.v, this.nm, record);
					}
				});
			}
		});
		return gdata;
	},
	groupingToggle : function(hid){
		this.each(function(){
			var $t = this,
			grp = $t.p.groupingView,
			strpos = hid.lastIndexOf('_'),
			uid = hid.substring(0,strpos+1),
			num = parseInt(hid.substring(strpos+1),10)+1,
			minus = grp.minusicon,
			plus = grp.plusicon,
			tar = $("#"+hid),
			r = tar.length ? tar[0].nextSibling : null,
			tarspan = $("#"+hid+" span."+"tree-wrap-"+$t.p.direction),
			collapsed = false;
			if( tarspan.hasClass(minus) ) {
				if(grp.showSummaryOnHide && grp.groupSummary[0]) {
					if(r){
						while(r) {
							if($(r).hasClass('jqfoot') ) { break; }
							$(r).hide();
							r = r.nextSibling;
						}
					}
				} else  {
					if(r){
						while(r) {
							if($(r).attr('id') ==uid+String(num) ) { break; }
							$(r).hide();
							r = r.nextSibling;
				}
					}
				}
				tarspan.removeClass(minus).addClass(plus);
				collapsed = true;
			} else {
				if(r){
					while(r) {
						if($(r).attr('id') ==uid+String(num) ) { break; }
						$(r).show();
						r = r.nextSibling;
					}
				}
				tarspan.removeClass(plus).addClass(minus);
				collapsed = false;
			}
			if( $.isFunction($t.p.onClickGroup)) { $t.p.onClickGroup.call($t, hid , collapsed); }

		});
		return false;
	},
	groupingRender : function (grdata, colspans ) {
		return this.each(function(){
			var $t = this,
			grp = $t.p.groupingView,
			str = "", icon = "", hid, pmrtl ="", gv, cp, ii;
			//only one level for now
			if(!grp.groupDataSorted) {
				// ???? TO BE IMPROVED
				grp.sortitems[0].sort();
				grp.sortnames[0].sort();
				if(grp.groupOrder[0].toLowerCase() == 'desc')
				{
					grp.sortitems[0].reverse();
					grp.sortnames[0].reverse();
				}
			}
			if(grp.groupCollapse) { pmrtl = grp.plusicon; }
			else {pmrtl = grp.minusicon;}
			pmrtl += " tree-wrap-"+$t.p.direction;
			ii = 0;
			while(ii < colspans) {
				if($t.p.colModel[ii].name == grp.groupField[0]) {
					cp = ii;
					break;
				}
				ii++;
			}
			$.each(grp.sortitems[0],function(i,n){
				hid = $t.p.id+"ghead_"+i;
				icon = "";
				try {
					gv = $t.formatter(hid, grp.sortnames[0][i], cp, grp.sortitems[0] );
				} catch (egv) {
					gv = grp.sortnames[0][i];
				}
				str += "
"+icon+$.jgrid.format(grp.groupText[0], gv, grdata[n].length)+"
";
				for(var kk=0;kk<grdata[n].length;kk++) {
					str += grdata[n][kk].join('');
				}
				if(grp.groupSummary[0]) {
					var hhdr = "";
					if(grp.groupCollapse && !grp.showSummaryOnHide) {
						hhdr = " style=\"display:none;\"";
					}
					str += "
";
					var fdata = grp.summaryval[0][n],
					cm = $t.p.colModel,
					vv, grlen = grdata[n].length;
					for(var k=0; k<colspans;k++) {
						var tmpdata = " 	",
						tplfld = "{0}";
						$.each(fdata,function(){
							if(this.nm == cm[k].name) {
								if(cm[k].summaryTpl)  {
									tplfld = cm[k].summaryTpl;
								}
								if(this.st == 'avg') {
									if(this.v && grlen > 0) {
										this.v = (this.v/grlen);
									}
								}
								try {
									vv = $t.formatter('', this.v, k, this);
								} catch (ef) {
									vv = this.v;
								}
								tmpdata= ""+$.jgrid.format(tplfld,vv)+ "	";
								return false;
							}
						});
						str += tmpdata;
					}
					str += "
";
				}
			});
			$("#"+$t.p.id+" tbody:first").append(str);
			// free up memory
			str = null;
		});
	},
	groupingGroupBy : function (name, options, current) {
		return this.each(function(){
			var $t = this;
			if(typeof(name) == "string") {
				name = [name];
			}
			var grp = $t.p.groupingView;
			$t.p.grouping = true;
      // show previous hidden groups if they are hidden and weren't removed yet
      for(var i=0;i<grp.groupField.length;i++) {
        if(!grp.groupColumnShow[i] && grp.visibiltyOnNextGrouping[i]) {
          $($t).jqGrid('showCol',grp.groupField[i]);
        }
      }
      // set visibility status of current group columns on next grouping
      for(var i=0;i<name.length;i++) {
        grp.visibiltyOnNextGrouping[i] = $("#"+$t.p.id+"_"+name[i]).is(":visible");
      }
			$t.p.groupingView = $.extend($t.p.groupingView, options || {});
			grp.groupField = name;
			$($t).trigger("reloadGrid");
		});
	},
	groupingRemove : function (current) {
		return this.each(function(){
			var $t = this;
			if(typeof(current) == 'undefined') {
				current = true;
			}
			$t.p.grouping = false;
			if(current===true) {
        var grp = $t.p.groupingView;
        // show previous hidden groups if they are hidden and weren't removed yet
        for(var i=0;i<grp.groupField.length;i++) {
          if (!grp.groupColumnShow[i] && grp.visibiltyOnNextGrouping[i]) {
            $($t).jqGrid('showCol', grp.groupField);
          }
        }
				$("tr.jqgroup, tr.jqfoot","#"+$t.p.id+" tbody:first").remove();
				$("tr.jqgrow:hidden","#"+$t.p.id+" tbody:first").show();
			} else {
				$($t).trigger("reloadGrid");
			}
		});
	},
	groupingCalculations : {
		"sum" : function(v, field, rc) {
			return parseFloat(v||0) + parseFloat((rc[field]||0));
		},
		"min" : function(v, field, rc) {
			if(v==="") {
				return parseFloat(rc[field]||0);
			}
			return Math.min(parseFloat(v),parseFloat(rc[field]||0));
		},
		"max" : function(v, field, rc) {
			if(v==="") {
				return parseFloat(rc[field]||0);
			}
			return Math.max(parseFloat(v),parseFloat(rc[field]||0));
		},
		"count" : function(v, field, rc) {
			if(v==="") {v=0;}
			if(rc.hasOwnProperty(field)) {
				return v+1;
			} else {
				return 0;
			}
		},
		"avg" : function(v, field, rc) {
			// the same as sum, but at end we divide it
			return parseFloat(v||0) + parseFloat((rc[field]||0));
		}
	}
});
})(jQuery);
<|endoftext|>


<commit_before>/* fix element position and size in this file */
$(function() {
    $('html').removeClass('client-nojs');
    setInterval(function(){
        if(window.innerWidth>=1366){
            $('#wrapper').removeClass('smtoggled');
        }
    },500);
    $('.subnav .nav .dropdown:first').addClass('phone-active');
    $('.subnav .nav .dropdown-menu:first').addClass('phone-active');
    // bell animation
    if($('#pt-notifications-alert .mw-echo-notifications-badge').text()!=0){
        $('#pt-notifications-alert .mw-echo-notifications-badge').css({'color':'#fff','background':'rgba(220, 0, 0, 1)'});
    }
    if($('#pt-notifications-message .mw-echo-notifications-badge').text()!=0){
        $('#pt-notifications-message .mw-echo-notifications-badge').css({'color':'#fff','background':'rgba(248,172,5,1)'});
    }
    $('.navbar-user').on('click','.mw-echo-notifications-badge',function(){
        if(window.innerWidth>=768){
            $(this).css({'color':'#fff','background':'#fff'});
        }else{
            $(this).css({'color':'#333','background':'#333'});
        }
    });
    $('table.article-table')
        .each(function() {
            var $el = $(this);

            if( $el.closest('form').length == 0 ) {
                $el.addClass('table')
                     .addClass('table-striped')
                     .addClass('table-bordered');
            }//end if
        });

    // $('pre:not([data-raw="true"])').addClass('prettyprint linenums');
    // $('.jumbotron pre').removeClass('prettyprint linenums');

    $('input[type=submit]:not(".keep"),input[type=button]:not(".keep"),input[type=reset]:not(".keep")').addClass('mw-ui-button');
    $('input[type=submit]:not(".keep")').addClass('mw-ui-progressive');

    // $('input[type=checkbox],input[type=radio]').each(function() {
    //  var $el = $(this);

    //  var id = $el.attr('id');
    //  $( 'label[for=' + id + ']' ).each(function() {
    //      var $label = $(this);
    //      if( $.trim( $label.text() ) != '' ) {
    //          $el.prependTo( $label );
    //      }//end if

    //      $label.wrap( '
' );
    //  });

    //  $el.closest('label').addClass($el.attr('type'));
    // });

    //Temperory fix
    $('.mw-ui-vform-field div').removeClass('mw-ui-checkbox');
    $('#wpRemember').css('margin-right','5px');
    if ( 0 === $('#toc').length ) {
        $('.toc-sidebar').remove();

    } else {
	    if ( !is_mobile_device() ) {

	        $('.wiki-body-section').removeClass('col-md-12').addClass('col-md-10');
	        $('.toc-sidebar').removeClass('hidden-md').addClass('col-md-2');
	        // $('.toc-sidebar').append('
摘要
');
	        $('#toc').each(function() {
	            $(this).find('ul:first').appendTo( '.toc-sidebar' );
	            $(this).remove();
	        });
	        $('aside.toc-sidebar > ul').append('
回到顶部
');
	        $('aside.toc-sidebar > ul').addClass('hidden-sm hidden-xs hidden-print').attr('data-spy','affix');
	        $('aside.toc-sidebar > ul').affix({
	          offset: {
	            top: 0,
	            bottom: function () {
	              return (this.bottom = $('.bottom').outerHeight(true))
	            }
	          }
	        });
	        $('aside.toc-sidebar ul').addClass('nav nav-list');
	        $('.toc-sidebar').attr('id', 'toc');
	        $('body').scrollspy({target: '#toc', offset:230});

	    } else {
	        // TODO do something to add a floating navigation bar.

	    }//end if
    }

    // prettyPrint();

    /* add missing icons caused by visual editor */
    // $('#ca-edit.collapsible > a:nth-child(1)').prepend(' ');

    //parallax Jumbotron
    var jumboHeight = $('.parallax-jumbotron').outerHeight();
    if (jumboHeight > 0){
        $('#firstHeading').hide();
        $('#firstHeading').css('border-bottom', 'none');
        if ($('.heading-hero-image a').length){
            var bg_image = $('.heading-hero-image a').attr('href');
            $('.parallax-bg').css('background', 'url(\"'+bg_image+'\") no-repeat center center');
        }
        parallax();
    }
    function parallax(){
        var scrolled = $(window).scrollTop();
        $('.parallax-bg').css('height', (jumboHeight-scrolled+100) + 'px');
    }
    function is_mobile_device() {
        var check = false;
        (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
        return check;
    }
    if (!is_mobile_device()){
        $(window).scroll(function(e){
            parallax();
        });
    } else {
        $('.parallax-bg').css({'position': 'absolute','height':'300px','top':'-10px'});
        $('.parallax-jumbotron').css('height', '300px');
    }

    //fix thumbinner
    $('.thumbinner').each(function(){
        $(this).width($(this).width()+6);
    });
    $('.internal').each(function(){
	   $(this).html('');
    });

    //need login
//    $('body').on('click','.need-login',function(e){
//        if(!mw.config.get("wgUserName")){
//            e.preventDefault();
//            e.stopPropagation();
//            $('.user-login').modal();
//        }
//    });

    // // done for preload. Let's show the page.
    // $('#wiki-outer-body').show();
});
<commit_msg>need login<commit_after>/* fix element position and size in this file */
$(function() {
    $('html').removeClass('client-nojs');
    setInterval(function(){
        if(window.innerWidth>=1366){
            $('#wrapper').removeClass('smtoggled');
        }
    },500);
    $('.subnav .nav .dropdown:first').addClass('phone-active');
    $('.subnav .nav .dropdown-menu:first').addClass('phone-active');
    // bell animation
    if($('#pt-notifications-alert .mw-echo-notifications-badge').text()!=0){
        $('#pt-notifications-alert .mw-echo-notifications-badge').css({'color':'#fff','background':'rgba(220, 0, 0, 1)'});
    }
    if($('#pt-notifications-message .mw-echo-notifications-badge').text()!=0){
        $('#pt-notifications-message .mw-echo-notifications-badge').css({'color':'#fff','background':'rgba(248,172,5,1)'});
    }
    $('.navbar-user').on('click','.mw-echo-notifications-badge',function(){
        if(window.innerWidth>=768){
            $(this).css({'color':'#fff','background':'#fff'});
        }else{
            $(this).css({'color':'#333','background':'#333'});
        }
    });
    $('table.article-table')
        .each(function() {
            var $el = $(this);

            if( $el.closest('form').length == 0 ) {
                $el.addClass('table')
                     .addClass('table-striped')
                     .addClass('table-bordered');
            }//end if
        });

    // $('pre:not([data-raw="true"])').addClass('prettyprint linenums');
    // $('.jumbotron pre').removeClass('prettyprint linenums');

    $('input[type=submit]:not(".keep"),input[type=button]:not(".keep"),input[type=reset]:not(".keep")').addClass('mw-ui-button');
    $('input[type=submit]:not(".keep")').addClass('mw-ui-progressive');

    // $('input[type=checkbox],input[type=radio]').each(function() {
    //  var $el = $(this);

    //  var id = $el.attr('id');
    //  $( 'label[for=' + id + ']' ).each(function() {
    //      var $label = $(this);
    //      if( $.trim( $label.text() ) != '' ) {
    //          $el.prependTo( $label );
    //      }//end if

    //      $label.wrap( '
' );
    //  });

    //  $el.closest('label').addClass($el.attr('type'));
    // });

    //Temperory fix
    $('.mw-ui-vform-field div').removeClass('mw-ui-checkbox');
    $('#wpRemember').css('margin-right','5px');
    if ( 0 === $('#toc').length ) {
        $('.toc-sidebar').remove();

    } else {
	    if ( !is_mobile_device() ) {

	        $('.wiki-body-section').removeClass('col-md-12').addClass('col-md-10');
	        $('.toc-sidebar').removeClass('hidden-md').addClass('col-md-2');
	        // $('.toc-sidebar').append('
摘要
');
	        $('#toc').each(function() {
	            $(this).find('ul:first').appendTo( '.toc-sidebar' );
	            $(this).remove();
	        });
	        $('aside.toc-sidebar > ul').append('
回到顶部
');
	        $('aside.toc-sidebar > ul').addClass('hidden-sm hidden-xs hidden-print').attr('data-spy','affix');
	        $('aside.toc-sidebar > ul').affix({
	          offset: {
	            top: 0,
	            bottom: function () {
	              return (this.bottom = $('.bottom').outerHeight(true))
	            }
	          }
	        });
	        $('aside.toc-sidebar ul').addClass('nav nav-list');
	        $('.toc-sidebar').attr('id', 'toc');
	        $('body').scrollspy({target: '#toc', offset:230});

	    } else {
	        // TODO do something to add a floating navigation bar.

	    }//end if
    }

    // prettyPrint();

    /* add missing icons caused by visual editor */
    // $('#ca-edit.collapsible > a:nth-child(1)').prepend(' ');

    //parallax Jumbotron
    var jumboHeight = $('.parallax-jumbotron').outerHeight();
    if (jumboHeight > 0){
        $('#firstHeading').hide();
        $('#firstHeading').css('border-bottom', 'none');
        if ($('.heading-hero-image a').length){
            var bg_image = $('.heading-hero-image a').attr('href');
            $('.parallax-bg').css('background', 'url(\"'+bg_image+'\") no-repeat center center');
        }
        parallax();
    }
    function parallax(){
        var scrolled = $(window).scrollTop();
        $('.parallax-bg').css('height', (jumboHeight-scrolled+100) + 'px');
    }
    function is_mobile_device() {
        var check = false;
        (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
        return check;
    }
    if (!is_mobile_device()){
        $(window).scroll(function(e){
            parallax();
        });
    } else {
        $('.parallax-bg').css({'position': 'absolute','height':'300px','top':'-10px'});
        $('.parallax-jumbotron').css('height', '300px');
    }

    //fix thumbinner
    $('.thumbinner').each(function(){
        $(this).width($(this).width()+6);
    });
    $('.internal').each(function(){
	   $(this).html('');
    });

//    need login
    $('body').on('click','.need-login',function(e){
        if(!mw.config.get("wgUserName")){
            e.preventDefault();
            e.stopPropagation();
            $('.user-login').modal();
        }
    });

    // // done for preload. Let's show the page.
    // $('#wiki-outer-body').show();
});
<|endoftext|>


<commit_before>'use strict';
/**
 * dynamically wrap lob, mesh, and util functions for javascript
**/
var th = require("./thc.js");

const returntypes = {
  "_lob_json" : "json",
  "_hashname_short" : "string",
  "_lob_get" : "string"
};

const Unwrappers = {
  pointer : (_val) => _val,
  number : (_val) => _val,
  string : th.UTF8ToString,
  json : (_val) => JSON.parse(th.UTF8ToString(_val))
}

const makeVarPointer = (_arg, write, mallextra) => {
  var ptr = th._malloc(_arg.length + mallextra);
  write(_arg, ptr);
  return ptr;
}

const Wrappers = {
  number : (_val) => _val,
  function : (_fun) => th.Runtime.addFunction(_fun),
  string : (_string) => makeVarPointer(_string, th.writeStringToMemory, 1),
  object : (_buf) => (Buffer.isBuffer(_buf)) ?  makeVarPointer(_buf, th.writeArrayToMemory, 0) : _buf === null ? 0 :  new Error("only numbers, strings, functions, and buffers accepted")
}

const wrapFun = (_fun, returntype) => function() {
  let args = [];
  for(let i = 0; i < arguments.length; i++){
    let _arg = arguments[i];
    args.push( Wrappers[typeof _arg](_arg) );
  }
  return Unwrappers[returntype || "number"]( _fun.apply(null,args) );
}

Object.keys(th).filter(key => key.indexOf("_") == 0).forEach((key) => {
  let fn = key.substr(1);
  th[fn] = wrapFun(th[key], returntypes[key]);
  // globalize all the funthings!
  if(fn.indexOf("_") > 0) global[fn] = th[fn];
})

th.CALLBACK = (fun, types) => function(){
  let args = [];
  for(let i = 0; i < arguments.length; i++){
    args[i] = Unwrappers[types[i] || "number"](arguments[i]);
  }
  return _fun.apply(null,args);
}

th.BUFFER = (ptr, len) => {
  let buf = new Buffer(len);
  for (let i =0; i < len; i++){
    buf[i] = th.getValue(ptr + i)
  }
  return buf;
}

module.exports = th;<commit_msg>deal with dir for thx<commit_after>'use strict';
/**
 * dynamically wrap lob, mesh, and util functions for javascript
**/
var cwd = process.cwd()
process.chdir(__dirname)
var th = require("./thc.js");
process.chdir(cwd);

const returntypes = {
  "_lob_json" : "json",
  "_hashname_short" : "string",
  "_lob_get" : "string"
};

const Unwrappers = {
  pointer : (_val) => _val,
  number : (_val) => _val,
  string : th.UTF8ToString,
  json : (_val) => JSON.parse(th.UTF8ToString(_val))
}

const makeVarPointer = (_arg, write, mallextra) => {
  var ptr = th._malloc(_arg.length + mallextra);
  write(_arg, ptr);
  return ptr;
}

const Wrappers = {
  number : (_val) => _val,
  function : (_fun) => th.Runtime.addFunction(_fun),
  string : (_string) => makeVarPointer(_string, th.writeStringToMemory, 1),
  object : (_buf) => (Buffer.isBuffer(_buf)) ?  makeVarPointer(_buf, th.writeArrayToMemory, 0) : _buf === null ? 0 :  new Error("only numbers, strings, functions, and buffers accepted")
}

const wrapFun = (_fun, returntype) => function() {
  let args = [];
  for(let i = 0; i < arguments.length; i++){
    let _arg = arguments[i];
    args.push( Wrappers[typeof _arg](_arg) );
  }
  return Unwrappers[returntype || "number"]( _fun.apply(null,args) );
}

Object.keys(th).filter(key => key.indexOf("_") == 0).forEach((key) => {
  let fn = key.substr(1);
  th[fn] = wrapFun(th[key], returntypes[key]);
  // globalize all the funthings!
  if(fn.indexOf("_") > 0) global[fn] = th[fn];
})

th.CALLBACK = (fun, types) => function(){
  let args = [];
  for(let i = 0; i < arguments.length; i++){
    args[i] = Unwrappers[types[i] || "number"](arguments[i]);
  }
  return _fun.apply(null,args);
}

th.BUFFER = (ptr, len) => {
  let buf = new Buffer(len);
  for (let i =0; i < len; i++){
    buf[i] = th.getValue(ptr + i)
  }
  return buf;
}

module.exports = th;<|endoftext|>


<commit_before>/*!
 * jQuery Chrony - A Count Down Plugin - http://wbotelhos.com/chrony
 * ------------------------------------------------------------------
 *
 * jQuery Chrony is a plugin that creates a chronometer.
 *
 * Licensed under The MIT License
 *
 * @version        0.1.0
 * @since          2011.10.23
 * @author         Washington Botelho
 * @documentation  wbotelhos.com/chrony
 * @twitter        twitter.com/wbotelhos
 *
 * Usage with default values:
 * ------------------------------------------------------------------
 * $('#time').chrony({ hour: 1, minute: 2, second: 3 });
 *
 *

 *
 */

;(function($) {

	var methods = {
		init: function(options) {
			return this.each(function() {

				var $this		= $(this),
					opt			= $.extend({}, $.fn.chrony.defaults, options),
					id			= $this.data('options', opt).attr('id'),
					separator	= ':';

				if (opt.text) {
					var text = opt.text.split(':');

					if (text.length != 3) {
						$.error('The format must be the following HH:mm:ss!');
					}

					opt.second = text[2];
					opt.minute = text[1];
					opt.hour = text[0];
				} else if (opt.hours) {
					if (opt.hours >= 24) {
						opt.hour = 23;
						opt.minute = 59;
						opt.second = 59;
					} else {
						opt.second = 0;
						opt.minute = 0;
						opt.hour = opt.hours;
					}
				} else if (opt.minutes) {
					opt.second = 0;
					opt.minute = opt.minutes % 60;
					opt.hour = (opt.minutes - opt.minute) / 60;
				} else if (opt.seconds) {
					opt.second = opt.seconds % 60;
					opt.minute = ((opt.seconds - opt.second) / 60) % 60;
					opt.hour = ((opt.seconds - opt.second) - (opt.minute * 60)) / 60 / 60;
				}

				var message = methods.checkTime(opt.hour, opt.minute, opt.second);

				if (message) {
					$this.html('
Number out of range!
');
					$.error(message);
				}

				var hour		= methods.getNumber(opt.hour),
					minute		= methods.getNumber(opt.minute),
					second		= methods.getNumber(opt.second),
					$hour		= $('
', { id: 'hour', html: hour, style: 'float: left;' }),
					$minute		= $('
', { id: 'minute', html: minute, style: 'float: left;' }),
					$second		= $('
', { id: 'second', html: second, style: 'float: left;' }),
					timer		= 0;

				if (id === undefined) {
					id = 'chrony-' + $this.index();
					$this.attr('id', id);
				}

				if (opt.displayHours) {
					$this.append($hour);

					if (opt.displayMinutes || opt.displaySeconds) {
						$this.append(separator);
					}
				}

				if (opt.displayMinutes) {
					$this.append($minute);

					if (opt.displaySeconds) {
						$this.append(separator);
					}
				}

				if (opt.displaySeconds) {
					$this.append($second);
				}

				var $separators = $this.children('span');

				if (opt.alert) {
					if (!opt.alert.color) {
						opt.alert.color = '#F00';
					}

					if (!opt.alert.hour) {
						opt.alert.hour = 0;
					}

					if (!opt.alert.minute) {
						opt.alert.minute = 0;
					}

					if (!opt.alert.second) {
						opt.alert.second = 0;
					}
				}

				methods.checkAlert.apply($this, [opt.alert, hour, minute, second]);

				timer = setInterval(function() {
					if (opt.blink) {
						$separators.fadeOut(opt.blinkTime, function() {
						    $(this).fadeIn(opt.blinkTime);
						});
					}

					if (second == 0) {
						if (minute == 0) {
							if (hour > 0) {
								hour = methods.getNumber(hour - opt.decrement);
								minute = 59;
								second = 59;

								$hour.html(hour);
								$minute.html(minute);
								$second.html(second);
							}
						} else {
							minute = methods.getNumber(minute - opt.decrement);
							second = 59;

							$minute.html(minute);
							$second.html(second);
						}
					} else {
						second = methods.getNumber(second - opt.decrement);
						$second.html(second);
					}

					if (opt.finish && second == 0 && minute == 0 && hour == 0) {
						opt.finish.call($this);

						clearInterval(timer);
					}

					methods.checkAlert.apply($this, [opt.alert, hour, minute, second]);
				}, 1000);
			});
		}, checkAlert: function(alert, hour, minute, second) {
			if (alert && this.css('color') != '') {
				if (hour <= alert.hour && minute <= alert.minute && second <= alert.second) {
					this.css('color', alert.color);
				}
			}
		}, checkTime: function(hour, minute, second) {
			if (hour < 0 || hour > 24) {
				return 'The hour must be >= 0 or <= 24';
			}

			if (minute < 0 || minute > 59) {
				return 'The minute must be >= 0 or <= 59';
			}

			if (second < 0 || second > 59) {
				return 'The second must be >= 0 or <= 59';
			}
		}, getNumber: function(number) {
			return (number < 10) ? '0' + ((number < 0) ? '0' : number) : number;
		}
	};

	$.fn.chrony = function(method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist!');
		}
	};

	$.fn.chrony.defaults = {
		alert			: { color: '#F00', hour: 0, minute: 0, second: 10 },
		blink			: false,
		blinkTime		: 130,
		finish			: undefined,
		decrement		: 1,
		displayHours	: true,
		displayMinutes	: true,
		displaySeconds	: true,
		hour			: 0,
		hours			: undefined,
		minute			: 0,
		minutes			: undefined,
		second			: 0,
		seconds			: undefined,
		text			: undefined
	};

})(jQuery);
<commit_msg>Not more necessary as long we work like widget style.<commit_after>/*!
 * jQuery Chrony - A Count Down Plugin - http://wbotelhos.com/chrony
 * ------------------------------------------------------------------
 *
 * jQuery Chrony is a plugin that creates a chronometer.
 *
 * Licensed under The MIT License
 *
 * @version        0.1.0
 * @since          2011.10.23
 * @author         Washington Botelho
 * @documentation  wbotelhos.com/chrony
 * @twitter        twitter.com/wbotelhos
 *
 * Usage with default values:
 * ------------------------------------------------------------------
 * $('#time').chrony({ hour: 1, minute: 2, second: 3 });
 *
 *

 *
 */

;(function($) {

	var methods = {
		init: function(options) {
			return this.each(function() {

				var $this		= $(this),
					opt			= $.extend({}, $.fn.chrony.defaults, options),
					separator	= ':';

				if (opt.text) {
					var text = opt.text.split(':');

					if (text.length != 3) {
						$.error('The format must be the following HH:mm:ss!');
					}

					opt.second = text[2];
					opt.minute = text[1];
					opt.hour = text[0];
				} else if (opt.hours) {
					if (opt.hours >= 24) {
						opt.hour = 23;
						opt.minute = 59;
						opt.second = 59;
					} else {
						opt.second = 0;
						opt.minute = 0;
						opt.hour = opt.hours;
					}
				} else if (opt.minutes) {
					opt.second = 0;
					opt.minute = opt.minutes % 60;
					opt.hour = (opt.minutes - opt.minute) / 60;
				} else if (opt.seconds) {
					opt.second = opt.seconds % 60;
					opt.minute = ((opt.seconds - opt.second) / 60) % 60;
					opt.hour = ((opt.seconds - opt.second) - (opt.minute * 60)) / 60 / 60;
				}

				var message = methods.checkTime(opt.hour, opt.minute, opt.second);

				if (message) {
					$this.html('
Number out of range!
');
					$.error(message);
				}

				var hour		= methods.getNumber(opt.hour),
					minute		= methods.getNumber(opt.minute),
					second		= methods.getNumber(opt.second),
					$hour		= $('
', { id: 'hour', html: hour, style: 'float: left;' }),
					$minute		= $('
', { id: 'minute', html: minute, style: 'float: left;' }),
					$second		= $('
', { id: 'second', html: second, style: 'float: left;' }),
					timer		= 0;

				if (opt.displayHours) {
					$this.append($hour);

					if (opt.displayMinutes || opt.displaySeconds) {
						$this.append(separator);
					}
				}

				if (opt.displayMinutes) {
					$this.append($minute);

					if (opt.displaySeconds) {
						$this.append(separator);
					}
				}

				if (opt.displaySeconds) {
					$this.append($second);
				}

				var $separators = $this.children('span');

				if (opt.alert) {
					if (!opt.alert.color) {
						opt.alert.color = '#F00';
					}

					if (!opt.alert.hour) {
						opt.alert.hour = 0;
					}

					if (!opt.alert.minute) {
						opt.alert.minute = 0;
					}

					if (!opt.alert.second) {
						opt.alert.second = 0;
					}
				}

				methods.checkAlert.apply($this, [opt.alert, hour, minute, second]);

				timer = setInterval(function() {
					if (opt.blink) {
						$separators.fadeOut(opt.blinkTime, function() {
						    $(this).fadeIn(opt.blinkTime);
						});
					}

					if (second == 0) {
						if (minute == 0) {
							if (hour > 0) {
								hour = methods.getNumber(hour - opt.decrement);
								minute = 59;
								second = 59;

								$hour.html(hour);
								$minute.html(minute);
								$second.html(second);
							}
						} else {
							minute = methods.getNumber(minute - opt.decrement);
							second = 59;

							$minute.html(minute);
							$second.html(second);
						}
					} else {
						second = methods.getNumber(second - opt.decrement);
						$second.html(second);
					}

					if (opt.finish && second == 0 && minute == 0 && hour == 0) {
						opt.finish.call($this);

						clearInterval(timer);
					}

					methods.checkAlert.apply($this, [opt.alert, hour, minute, second]);
				}, 1000);
			});
		}, checkAlert: function(alert, hour, minute, second) {
			if (alert && this.css('color') != '') {
				if (hour <= alert.hour && minute <= alert.minute && second <= alert.second) {
					this.css('color', alert.color);
				}
			}
		}, checkTime: function(hour, minute, second) {
			if (hour < 0 || hour > 24) {
				return 'The hour must be >= 0 or <= 24';
			}

			if (minute < 0 || minute > 59) {
				return 'The minute must be >= 0 or <= 59';
			}

			if (second < 0 || second > 59) {
				return 'The second must be >= 0 or <= 59';
			}
		}, getNumber: function(number) {
			return (number < 10) ? '0' + ((number < 0) ? '0' : number) : number;
		}
	};

	$.fn.chrony = function(method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist!');
		}
	};

	$.fn.chrony.defaults = {
		alert			: { color: '#F00', hour: 0, minute: 0, second: 10 },
		blink			: false,
		blinkTime		: 130,
		finish			: undefined,
		decrement		: 1,
		displayHours	: true,
		displayMinutes	: true,
		displaySeconds	: true,
		hour			: 0,
		hours			: undefined,
		minute			: 0,
		minutes			: undefined,
		second			: 0,
		seconds			: undefined,
		text			: undefined
	};

})(jQuery);
<|endoftext|>


<commit_before>'use strict';

module.exports = function (nitro) {

  var uglify = nitro.require('uglify-js'),
      _ = nitro.tools,
      color = require('../color'),
      getRatioLog = function (ratio) {
        var ratio_color = 'cyan', compression = 1 - ratio;
        if( compression < 0.2 ) ratio_color = 'yellow';
        else if( compression > 0.7 ) ratio_color = 'green';
        return color[ratio_color]('[' + Math.round(10000*compression)/100 + '%]');
      },
      sizeK = function (o) {
        if( !o || !o.length ) return o;
        return Math.round(o.length/1000) + 'k';
      };

  return function (list, options) {
    options = _.extend({ expand: true }, options || {}, { fromString: true });

    list.forEach(function (f) {
      var o = {}, result;
      o[f.path] = f.src;

      // @TODO imeplemt sourceMap
      // o[f.path] = f.src + f.map ? ( '//# sourceMappingURL=data:application/json;charset=utf-8;base64,' +  ) : '';
      // if( f.map ) console.log('map', typeof f.map );

      try{
        console.log('\nuglifing', color.yellow(f.path), f.src.split('\n').length + color.grey(' lines') );
        result = uglify.minify(o);

        if (result.error) throw result.error;
        console.log( '\n' + getRatioLog(result.code.length/f.src.length), color.magenta( sizeK(f.src) ) + color.grey(' => ') + color.cyan( sizeK(result.code) ) + '\n' );

      } catch(err) {
        var code_lines = f.src.split('\n');

        console.log( '\n' + color.red(err.message) );
        console.log( '\nfile: ' + color.grey( f.cwd + ( /\/$/.test(f.cwd) ? '' : '/' ) ) + color.yellow(err.filename) );

        if( err.line ) {
          console.log( color.grey('\n--------------------------------------------------------------------------------') );
          console.log('line: ', color.cyan(err.line) + ' col: ' + color.magenta(err.col) );
          console.log( color.grey('--------------------------------------------------------------------------------\n') );
          console.log( code_lines.slice(err.line - 5, err.line).join('\n') );
        }

        if( err.col ) console.log(' '.repeat(err.col) + color.yellow('^') );
        console.log( color.grey('--------------------------------------------------------------------------------\n') );

        console.log('\n', err );

        throw err;
      }

      if( options.sourceMap ) {
        f.src = result.code.replace(/\n\/\/[^\n]+\.js\.map$/, '');
        f.map = result.map;
      } else {
        f.src = result.code;
      }

    });

    return list;

  };

};
<commit_msg>BLACK UP POINTING BACKHAND INDEX (U+1F5A2)<commit_after>'use strict';

module.exports = function (nitro) {

  var uglify = nitro.require('uglify-js'),
      _ = nitro.tools,
      color = require('../color'),
      getRatioLog = function (ratio) {
        var ratio_color = 'cyan', compression = 1 - ratio;
        if( compression < 0.2 ) ratio_color = 'yellow';
        else if( compression > 0.7 ) ratio_color = 'green';
        return color[ratio_color]('[' + Math.round(10000*compression)/100 + '%]');
      },
      sizeK = function (o) {
        if( !o || !o.length ) return o;
        return Math.round(o.length/1000) + 'k';
      };

  return function (list, options) {
    options = _.extend({ expand: true }, options || {}, { fromString: true });

    list.forEach(function (f) {
      var o = {}, result;
      o[f.path] = f.src;

      // @TODO imeplemt sourceMap
      // o[f.path] = f.src + f.map ? ( '//# sourceMappingURL=data:application/json;charset=utf-8;base64,' +  ) : '';
      // if( f.map ) console.log('map', typeof f.map );

      try{
        console.log('\nuglifing', color.yellow(f.path), f.src.split('\n').length + color.grey(' lines') );
        result = uglify.minify(o);

        if (result.error) throw result.error;
        console.log( '\n' + getRatioLog(result.code.length/f.src.length), color.magenta( sizeK(f.src) ) + color.grey(' => ') + color.cyan( sizeK(result.code) ) + '\n' );

      } catch(err) {
        var code_lines = f.src.split('\n');

        console.log( '\n' + color.red(err.message) );
        console.log( '\nfile: ' + color.grey( f.cwd + ( /\/$/.test(f.cwd) ? '' : '/' ) ) + color.yellow(err.filename) );

        if( err.line ) {
          console.log( color.grey('\n--------------------------------------------------------------------------------') );
          console.log('line: ', color.cyan(err.line) + ' col: ' + color.magenta(err.col) );
          console.log( color.grey('--------------------------------------------------------------------------------\n') );
          console.log( code_lines.slice(err.line - 5, err.line).join('\n') );
        }

        if( err.col ) console.log(' '.repeat(err.col) + color.yellow('🖢') );
        console.log( color.grey('--------------------------------------------------------------------------------\n') );

        console.log('\n', err );

        throw err;
      }

      if( options.sourceMap ) {
        f.src = result.code.replace(/\n\/\/[^\n]+\.js\.map$/, '');
        f.map = result.map;
      } else {
        f.src = result.code;
      }

    });

    return list;

  };

};
<|endoftext|>