<commit_before>var parser = require('raml-1-parser'),
    Endpoint = require('../entities/endpoint'),
    Importer = require('./importer'),
    Project = require('../entities/project'),
    jsonHelper = require('../utils/json'),
    ramlHelper = require('../helpers/raml'),
    url = require('url'),
    _ = require('lodash');

//TODO multi file support isn't justified

function RAML() {
  this.schemas = [];
}
RAML.prototype = new Importer();

RAML.prototype._getSecuritySchemeSettingsByName = function(schemeName) {
  var securitySchemes = this.data.securitySchemes();
  for(var i in securitySchemes) {
    if (schemeName === securitySchemes[i].name()) {
      return securitySchemes[i];
    }
  }
};

RAML.prototype._mapSecuritySchemes = function (securitySchemes) {
  var slSecurityScheme = {};
  for(var i in securitySchemes) {
    if (!securitySchemes.hasOwnProperty(i)) continue;
    var securityScheme = securitySchemes[i];
    for (var name in securityScheme) {
      if (!securityScheme.hasOwnProperty(name)) continue;
      var scheme = securityScheme[name];
      switch(scheme.type) {
        case 'OAuth 2.0':
          var oauth = {
            name: name, //not used in stoplight designer
            authorizationUrl: scheme.settings.authorizationUri || '',
            tokenUrl: scheme.settings.accessTokenUri || '',
            scopes: []
          };
          if (Array.isArray(scheme.scopes)) {
            for(var scopeIndex in scheme.scopes) {
              if (!scheme.scopes.hasOwnProperty(scopeIndex)) continue;
              oauth.scopes.push({
                name: scheme.scopes[scopeIndex],
                value: ''
              });
            }
          }
          //authorizationGrants are flow, only one supported in stoplight
          var flow = !_.isEmpty(scheme.settings.authorizationGrants) ? scheme.settings.authorizationGrants[0]:'code';

          switch(flow) {
            case 'code':
              oauth.flow = 'accessCode';
              break;
            case 'token':
              oauth.flow = 'implicit';
              break;
            case 'owner':
              oauth.flow = 'application';
              break;
            case 'credentials':
              oauth.flow = 'password';
              break;
          }
          slSecurityScheme['oauth2'] = oauth;
          break;
        case 'Basic Authentication':
          slSecurityScheme['basic'] = {
            name: name,
            value: '',
            description: scheme.description || ''
          };
          break;
        default:
          //TODO not supported
      }
    }
  }
  return slSecurityScheme;
};

RAML.prototype._mapRequestBody = function (methodBody) {
  return this.mapRequestBody(methodBody);
};

RAML.prototype._mapQueryString = function(queryParameters) {
  var queryString = {type:'object', properties: {}, required: []};
  for (var key in queryParameters) {
    if (!queryParameters.hasOwnProperty(key)) continue;
    var qp = queryParameters[key];
    queryString.properties[key] = ramlHelper.setParameterFields(qp, {});
    if (qp.required()) {
      queryString.required.push(key);
    }
  }
  return queryString;
};

RAML.prototype._mapRequestHeaders = function (data) {
  return this._mapQueryString(data);
};

RAML.prototype._mapURIParams = function (uriParams) {
  var pathParams = {type:'object', properties: {}, required: []};

  for (var i in uriParams) {
    if (!uriParams.hasOwnProperty(i)) continue;
    var key = uriParams[i];

    pathParams.properties[key.name()] = {
      description: key.displayName() || key.description() || '',
      type: key.type() || 'string'
    };
  }
  return pathParams;
};

RAML.prototype._mapResponseBody = function(responses) {
  var data = [];
  for(var code in responses) {
    if (!responses.hasOwnProperty(code)) continue;
    var response = responses[code];

    if (!response || !response.body || !response.body()) {
      continue;
    }

    var result = this._mapRequestBody(response.body());
    result.codes = [response.code().value()];
    if (result.body) {
      result.body = jsonHelper.cleanSchema(result.body);
    }

    if (result.example) {
      result.example = jsonHelper.stringify(result.example, 4);
    }

    if(response.description() && response.description().value) {
      result.description = response.description().value();
    }
    data.push(result);
  }
  return data;
};

RAML.prototype._mapSchema = function(schemData) {
  return this.mapSchema(schemData);
};

// from type=type1 to ref=type1
RAML.prototype.convertRefToModel = function(object) {
  for (var id in object) {
    if (object.hasOwnProperty(id)) {
      var val = object[id];
      if (id == 'type' && typeof val === 'string' && ramlHelper.getScalarTypes.indexOf(val) < 0 && val !== 'object') {
        object.ref = val;
        delete object[id];
      } else if (typeof val === 'object') {
				if (val.type == 'date-only') {
					object[id] = {
						type: 'string',
						format: 'date'
					};
				} else if (val.type == 'datetime') {
					object[id] = {
						type: 'string',
						format: 'date-time'
					};
				}
				else {
        	object[id] = this.convertRefToModel(val);
				}
      }
    }
  }

  return object;
};

RAML.prototype.mapMimeTypes = function(body, skip) {
  var result = [];
  var skipMimeTypes = [];
  for (var i in skip) {
    if (_.isFunction(skip[i].value)) {
      skipMimeTypes.push(skip[i].value());
    }
  }

  for (var i in body) {
    var b = body[i];
    if (_.isFunction(b.name)) {
      var mimeType = b.name();
      if (skipMimeTypes.indexOf(mimeType) === -1) {
        result.push(mimeType);
      }
    }
  }
  return _.uniq(result);
};

RAML.prototype._mapEndpoint = function(resource, baseURI, pathParams) {
  if(resource.uriParameters().length > 0) {
    pathParams = _.merge(pathParams, this._mapURIParams(resource.uriParameters()));
  }

  var methods = resource.methods();
  for (var i in methods) {
    if (!methods.hasOwnProperty(i)) continue;
    var method = methods[i];

    var summary = method.name ? method.name() : ''; // do we ever have a name or summary?
    var endpoint = new Endpoint(summary);
    endpoint.Method = method.method();
    endpoint.Path = baseURI + resource.relativeUri().value();
    endpoint.Description = method.description() ? method.description().value() : '';

    endpoint.SetOperationId(method.displayName ? method.displayName() : method.displayName, endpoint.Method, endpoint.Path);

    if (method.body()) {
      var c = this.mapMimeTypes(method.body(), this.data.mediaType());
      endpoint.Consumes = c.length > 0 ? c:null;
      endpoint.Body = this._mapRequestBody(method.body());
    }

    if (method.queryParameters()) {
      endpoint.QueryString = this._mapQueryString(method.queryParameters());
    }

    if (method.headers()) {
      endpoint.Headers = this._mapRequestHeaders(method.headers());
    }

    if (method.responses()) {
      var produces = [];
      for(var code in method.responses()) {
        if (!method.responses()[code] || !method.responses()[code].body()) {
          continue;
        }
        produces = produces.concat(this.mapMimeTypes(method.responses()[code].body(), this.data.mediaType()));
      }
      var p = _.uniq(produces);
      endpoint.Produces = p.length > 0 ? p:null;
      endpoint.Responses = this._mapResponseBody(method.responses());
    }

    endpoint.traits = [];
    var isMethod = method.is();
    if (isMethod) {
      if (isMethod instanceof Array) {
        endpoint.traits = isMethod;
      } else if (isMethod instanceof Object) {
        endpoint.traits = Object.keys(isMethod);
      }
    }

    endpoint.PathParams = pathParams;

    //endpoint security
    var securedBy = method.securedBy();
    if (Array.isArray(securedBy)) {
      endpoint.securedBy = {};
      for(var si in securedBy) {
        if (!securedBy.hasOwnProperty(si)) continue;
        var schemeSettings = this._getSecuritySchemeSettingsByName(securedBy[si].name());
        switch(schemeSettings.type()) {
          case 'OAuth 2.0':
            endpoint.securedBy['oauth2'] = true;
            break;
          case 'Basic Authentication':
            endpoint.securedBy['basic'] = true;
            break;
          default:
            //TODO not supported
            break;
        }
      }
    }

    //TODO endpoint security

    this.project.addEndpoint(endpoint);
  }

  var resources = resource.resources();
  if(resources && resources.length > 0) {
    for (var j = 0; j < resources.length; j++) {
      this._mapEndpoint(resources[j], baseURI + resource.relativeUri().value(), pathParams);
    }
  }
};

RAML.prototype.loadFile = function (filePath, cb) {
  var me = this;
  parser.loadApi(filePath).then(function(api) {
    me.data = parser.expander.expandTraitsAndResourceTypes(api);
    cb();
  }, function(error) {
    cb(error);
  });
};

RAML.prototype.loadFileWithOptions = function (filePath, options, cb) {
  var me = this;
  parser.loadApi(filePath, options).then(function(api) {
    me.data = parser.expander.expandTraitsAndResourceTypes(api);
    cb();
  }, function(error) {
    cb(error);
  });
};

RAML.prototype.loadData = function (data, options) {
  var me = this;
  return new Promise(function(resolve, reject){
    try {
      var parsedData = parser.parseRAMLSync(data, options);
      if (parsedData.name === 'Error') {
        reject(error);
      } else {
        me.data = parser.expander.expandTraitsAndResourceTypes(parsedData);
        //me.data = parsedData.expand(true);
        resolve();
      }
    } catch (e) {
      console.error('raml#loadData', e, data, options);
      reject(e);
    }
  });
};

RAML.prototype._mapHost = function() {
  var parsedURL = url.parse(this.data.baseUri ? this.data.baseUri().value() : '');
  this.project.Environment.Host = (parsedURL.protocol && parsedURL.host)? (parsedURL.protocol + '//' + parsedURL.host) : null;
  this.project.Environment.BasePath = parsedURL.path;
};

RAML.prototype._mapTraits = function(traitGroups) {
  var slTraits = [];

  for (var i in traitGroups) {
    if (!traitGroups.hasOwnProperty(i)) continue;
    var traitGroup = traitGroups[i];

    for (var k in traitGroup) {
      if (!traitGroup.hasOwnProperty(k)) continue;

      var trait = traitGroup[k];
      var slTrait = {
        _id: k,
        name: trait.name(),
        description: '',
        request: {},
        responses: []
      };

      if (!_.isEmpty(trait.usage())) {
        slTrait.description = trait.usage();
      } else {
        delete slTrait.description;
      }

      if (trait.queryParameters()) {
        slTrait.request.queryString = this._mapQueryString(trait.queryParameters());
      }

      if (trait.headers()) {
        slTrait.request.headers = this._mapRequestHeaders(trait.headers());
      }

      if (trait.responses()) {
        slTrait.responses = this._mapResponseBody(trait.responses);
      } else {
        delete slTrait.responses;
      }

      slTraits.push(slTrait);
    }
  }

  return slTraits;
};

RAML.prototype._import = function() {
  try {
    this.project = new Project(this.data.title());
    this.project.Environment.Version = this.data.version();
    if (!this.project.Environment.Version) {
      delete this.project.Environment.Version;
    }

    // TODO set project description from documentation
    // How to know which documentation describes the project briefly?
    this.description(this.project, this.data);

    this._mapHost();

    if (!_.isEmpty(this.data.protocols())) {
      this.project.Environment.Protocols = this.data.protocols();
      for (var i in this.project.Environment.Protocols) {
        this.project.Environment.Protocols[i] = this.project.Environment.Protocols[i].toLowerCase();
      }
    }

    var mimeTypes = [];
    var mediaType = this.data.mediaType();
    if (mediaType) {
      if (!_.isArray(mediaType)) {
        mediaType = [mediaType];
      }
      for (var i in mediaType) {
        if (_.isFunction(mediaType[i].value)) {
          if (mediaType[i].value()) {
            mimeTypes.push(mediaType[i].value());
          }
        }
      }
    }
    if (mimeTypes.length) {
      this.project.Environment.Produces = mimeTypes;
      this.project.Environment.Consumes = mimeTypes;
    }

    this.project.Environment.SecuritySchemes = this._mapSecuritySchemes(this.data.securitySchemes());

    var resources = this.data.resources();
    for (var i = 0; i < resources.length; i++) {
      this._mapEndpoint(resources[i], '', {});
    }

    var schemas = this._mapSchema(this.getSchema(this.data));
    for(var s in schemas) {
      if (!schemas.hasOwnProperty(s)) continue;
      this.project.addSchema(schemas[s]);
    }

    this.project.traits = this._mapTraits(this.data.traits());
  } catch (e) {
    console.error('raml#import', e);
    throw e;
  }
};

RAML.prototype.description = function(project, data) { throw new Error('description method not implemented'); };

RAML.prototype.mapRequestBody = function(methodBody) { throw new Error('mapRequestBody method not implemented'); };

RAML.prototype.mapSchema = function(schema) { throw new Error('mapSchema method not implemented'); };

RAML.prototype.getSchema = function(data) { throw new Error('getSchema method not implemented'); };

module.exports = RAML;
<commit_msg>raml, don’t attempt to import traits right now<commit_after>var parser = require('raml-1-parser'),
    Endpoint = require('../entities/endpoint'),
    Importer = require('./importer'),
    Project = require('../entities/project'),
    jsonHelper = require('../utils/json'),
    ramlHelper = require('../helpers/raml'),
    url = require('url'),
    _ = require('lodash');

//TODO multi file support isn't justified

function RAML() {
  this.schemas = [];
}
RAML.prototype = new Importer();

RAML.prototype._getSecuritySchemeSettingsByName = function(schemeName) {
  var securitySchemes = this.data.securitySchemes();
  for(var i in securitySchemes) {
    if (schemeName === securitySchemes[i].name()) {
      return securitySchemes[i];
    }
  }
};

RAML.prototype._mapSecuritySchemes = function (securitySchemes) {
  var slSecurityScheme = {};
  for(var i in securitySchemes) {
    if (!securitySchemes.hasOwnProperty(i)) continue;
    var securityScheme = securitySchemes[i];
    for (var name in securityScheme) {
      if (!securityScheme.hasOwnProperty(name)) continue;
      var scheme = securityScheme[name];
      switch(scheme.type) {
        case 'OAuth 2.0':
          var oauth = {
            name: name, //not used in stoplight designer
            authorizationUrl: scheme.settings.authorizationUri || '',
            tokenUrl: scheme.settings.accessTokenUri || '',
            scopes: []
          };
          if (Array.isArray(scheme.scopes)) {
            for(var scopeIndex in scheme.scopes) {
              if (!scheme.scopes.hasOwnProperty(scopeIndex)) continue;
              oauth.scopes.push({
                name: scheme.scopes[scopeIndex],
                value: ''
              });
            }
          }
          //authorizationGrants are flow, only one supported in stoplight
          var flow = !_.isEmpty(scheme.settings.authorizationGrants) ? scheme.settings.authorizationGrants[0]:'code';

          switch(flow) {
            case 'code':
              oauth.flow = 'accessCode';
              break;
            case 'token':
              oauth.flow = 'implicit';
              break;
            case 'owner':
              oauth.flow = 'application';
              break;
            case 'credentials':
              oauth.flow = 'password';
              break;
          }
          slSecurityScheme['oauth2'] = oauth;
          break;
        case 'Basic Authentication':
          slSecurityScheme['basic'] = {
            name: name,
            value: '',
            description: scheme.description || ''
          };
          break;
        default:
          //TODO not supported
      }
    }
  }
  return slSecurityScheme;
};

RAML.prototype._mapRequestBody = function (methodBody) {
  return this.mapRequestBody(methodBody);
};

RAML.prototype._mapQueryString = function(queryParameters) {
  var queryString = {type:'object', properties: {}, required: []};
  for (var key in queryParameters) {
    if (!queryParameters.hasOwnProperty(key)) continue;
    var qp = queryParameters[key];
    queryString.properties[key] = ramlHelper.setParameterFields(qp, {});
    if (qp.required()) {
      queryString.required.push(key);
    }
  }
  return queryString;
};

RAML.prototype._mapRequestHeaders = function (data) {
  return this._mapQueryString(data);
};

RAML.prototype._mapURIParams = function (uriParams) {
  var pathParams = {type:'object', properties: {}, required: []};

  for (var i in uriParams) {
    if (!uriParams.hasOwnProperty(i)) continue;
    var key = uriParams[i];

    pathParams.properties[key.name()] = {
      description: key.displayName() || key.description() || '',
      type: key.type() || 'string'
    };
  }
  return pathParams;
};

RAML.prototype._mapResponseBody = function(responses) {
  var data = [];
  for(var code in responses) {
    if (!responses.hasOwnProperty(code)) continue;
    var response = responses[code];

    if (!response || !response.body || !response.body()) {
      continue;
    }

    var result = this._mapRequestBody(response.body());
    result.codes = [response.code().value()];
    if (result.body) {
      result.body = jsonHelper.cleanSchema(result.body);
    }

    if (result.example) {
      result.example = jsonHelper.stringify(result.example, 4);
    }

    if(response.description() && response.description().value) {
      result.description = response.description().value();
    }
    data.push(result);
  }
  return data;
};

RAML.prototype._mapSchema = function(schemData) {
  return this.mapSchema(schemData);
};

// from type=type1 to ref=type1
RAML.prototype.convertRefToModel = function(object) {
  for (var id in object) {
    if (object.hasOwnProperty(id)) {
      var val = object[id];
      if (id == 'type' && typeof val === 'string' && ramlHelper.getScalarTypes.indexOf(val) < 0 && val !== 'object') {
        object.ref = val;
        delete object[id];
      } else if (typeof val === 'object') {
				if (val.type == 'date-only') {
					object[id] = {
						type: 'string',
						format: 'date'
					};
				} else if (val.type == 'datetime') {
					object[id] = {
						type: 'string',
						format: 'date-time'
					};
				}
				else {
        	object[id] = this.convertRefToModel(val);
				}
      }
    }
  }

  return object;
};

RAML.prototype.mapMimeTypes = function(body, skip) {
  var result = [];
  var skipMimeTypes = [];
  for (var i in skip) {
    if (_.isFunction(skip[i].value)) {
      skipMimeTypes.push(skip[i].value());
    }
  }

  for (var i in body) {
    var b = body[i];
    if (_.isFunction(b.name)) {
      var mimeType = b.name();
      if (skipMimeTypes.indexOf(mimeType) === -1) {
        result.push(mimeType);
      }
    }
  }
  return _.uniq(result);
};

RAML.prototype._mapEndpoint = function(resource, baseURI, pathParams) {
  if(resource.uriParameters().length > 0) {
    pathParams = _.merge(pathParams, this._mapURIParams(resource.uriParameters()));
  }

  var methods = resource.methods();
  for (var i in methods) {
    if (!methods.hasOwnProperty(i)) continue;
    var method = methods[i];

    var summary = method.name ? method.name() : ''; // do we ever have a name or summary?
    var endpoint = new Endpoint(summary);
    endpoint.Method = method.method();
    endpoint.Path = baseURI + resource.relativeUri().value();
    endpoint.Description = method.description() ? method.description().value() : '';

    endpoint.SetOperationId(method.displayName ? method.displayName() : method.displayName, endpoint.Method, endpoint.Path);

    if (method.body()) {
      var c = this.mapMimeTypes(method.body(), this.data.mediaType());
      endpoint.Consumes = c.length > 0 ? c:null;
      endpoint.Body = this._mapRequestBody(method.body());
    }

    if (method.queryParameters()) {
      endpoint.QueryString = this._mapQueryString(method.queryParameters());
    }

    if (method.headers()) {
      endpoint.Headers = this._mapRequestHeaders(method.headers());
    }

    if (method.responses()) {
      var produces = [];
      for(var code in method.responses()) {
        if (!method.responses()[code] || !method.responses()[code].body()) {
          continue;
        }
        produces = produces.concat(this.mapMimeTypes(method.responses()[code].body(), this.data.mediaType()));
      }
      var p = _.uniq(produces);
      endpoint.Produces = p.length > 0 ? p:null;
      endpoint.Responses = this._mapResponseBody(method.responses());
    }

    endpoint.traits = [];
    var isMethod = method.is();
    if (isMethod) {
      if (isMethod instanceof Array) {
        endpoint.traits = isMethod;
      } else if (isMethod instanceof Object) {
        endpoint.traits = Object.keys(isMethod);
      }
    }

    endpoint.PathParams = pathParams;

    //endpoint security
    var securedBy = method.securedBy();
    if (Array.isArray(securedBy)) {
      endpoint.securedBy = {};
      for(var si in securedBy) {
        if (!securedBy.hasOwnProperty(si)) continue;
        var schemeSettings = this._getSecuritySchemeSettingsByName(securedBy[si].name());
        switch(schemeSettings.type()) {
          case 'OAuth 2.0':
            endpoint.securedBy['oauth2'] = true;
            break;
          case 'Basic Authentication':
            endpoint.securedBy['basic'] = true;
            break;
          default:
            //TODO not supported
            break;
        }
      }
    }

    //TODO endpoint security

    this.project.addEndpoint(endpoint);
  }

  var resources = resource.resources();
  if(resources && resources.length > 0) {
    for (var j = 0; j < resources.length; j++) {
      this._mapEndpoint(resources[j], baseURI + resource.relativeUri().value(), pathParams);
    }
  }
};

RAML.prototype.loadFile = function (filePath, cb) {
  var me = this;
  parser.loadApi(filePath).then(function(api) {
    me.data = parser.expander.expandTraitsAndResourceTypes(api);
    cb();
  }, function(error) {
    cb(error);
  });
};

RAML.prototype.loadFileWithOptions = function (filePath, options, cb) {
  var me = this;
  parser.loadApi(filePath, options).then(function(api) {
    me.data = parser.expander.expandTraitsAndResourceTypes(api);
    cb();
  }, function(error) {
    cb(error);
  });
};

RAML.prototype.loadData = function (data, options) {
  var me = this;
  return new Promise(function(resolve, reject){
    try {
      var parsedData = parser.parseRAMLSync(data, options);
      if (parsedData.name === 'Error') {
        reject(error);
      } else {
        me.data = parser.expander.expandTraitsAndResourceTypes(parsedData);
        //me.data = parsedData.expand(true);
        resolve();
      }
    } catch (e) {
      console.error('raml#loadData', e, data, options);
      reject(e);
    }
  });
};

RAML.prototype._mapHost = function() {
  var parsedURL = url.parse(this.data.baseUri ? this.data.baseUri().value() : '');
  this.project.Environment.Host = (parsedURL.protocol && parsedURL.host)? (parsedURL.protocol + '//' + parsedURL.host) : null;
  this.project.Environment.BasePath = parsedURL.path;
};

RAML.prototype._mapTraits = function(traitGroups) {
  var slTraits = [];

  for (var i in traitGroups) {
    if (!traitGroups.hasOwnProperty(i)) continue;
    var traitGroup = traitGroups[i];

    for (var k in traitGroup) {
      if (!traitGroup.hasOwnProperty(k)) continue;

      var trait = traitGroup[k];
      var slTrait = {
        _id: k,
        name: trait.name(),
        description: '',
        request: {},
        responses: []
      };

      if (!_.isEmpty(trait.usage())) {
        slTrait.description = trait.usage();
      } else {
        delete slTrait.description;
      }

      if (trait.queryParameters()) {
        slTrait.request.queryString = this._mapQueryString(trait.queryParameters());
      }

      if (trait.headers()) {
        slTrait.request.headers = this._mapRequestHeaders(trait.headers());
      }

      if (trait.responses()) {
        slTrait.responses = this._mapResponseBody(trait.responses);
      } else {
        delete slTrait.responses;
      }

      slTraits.push(slTrait);
    }
  }

  return slTraits;
};

RAML.prototype._import = function() {
  try {
    this.project = new Project(this.data.title());
    this.project.Environment.Version = this.data.version();
    if (!this.project.Environment.Version) {
      delete this.project.Environment.Version;
    }

    // TODO set project description from documentation
    // How to know which documentation describes the project briefly?
    this.description(this.project, this.data);

    this._mapHost();

    if (!_.isEmpty(this.data.protocols())) {
      this.project.Environment.Protocols = this.data.protocols();
      for (var i in this.project.Environment.Protocols) {
        this.project.Environment.Protocols[i] = this.project.Environment.Protocols[i].toLowerCase();
      }
    }

    var mimeTypes = [];
    var mediaType = this.data.mediaType();
    if (mediaType) {
      if (!_.isArray(mediaType)) {
        mediaType = [mediaType];
      }
      for (var i in mediaType) {
        if (_.isFunction(mediaType[i].value)) {
          if (mediaType[i].value()) {
            mimeTypes.push(mediaType[i].value());
          }
        }
      }
    }
    if (mimeTypes.length) {
      this.project.Environment.Produces = mimeTypes;
      this.project.Environment.Consumes = mimeTypes;
    }

    this.project.Environment.SecuritySchemes = this._mapSecuritySchemes(this.data.securitySchemes());

    var resources = this.data.resources();
    for (var i = 0; i < resources.length; i++) {
      this._mapEndpoint(resources[i], '', {});
    }

    var schemas = this._mapSchema(this.getSchema(this.data));
    for(var s in schemas) {
      if (!schemas.hasOwnProperty(s)) continue;
      this.project.addSchema(schemas[s]);
    }

    // this.project.traits = this._mapTraits(this.data.traits());
  } catch (e) {
    console.error('raml#import', e);
    throw e;
  }
};

RAML.prototype.description = function(project, data) { throw new Error('description method not implemented'); };

RAML.prototype.mapRequestBody = function(methodBody) { throw new Error('mapRequestBody method not implemented'); };

RAML.prototype.mapSchema = function(schema) { throw new Error('mapSchema method not implemented'); };

RAML.prototype.getSchema = function(data) { throw new Error('getSchema method not implemented'); };

module.exports = RAML;
<|endoftext|>


<commit_before>/*
 * env.js: Commands related to environment variables for Nodejitsu applications.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var jitsu = require('../../jitsu'),
    fs = require('fs'),
    utile = jitsu.common;

var env = exports;

env.usage = [
  '`jitsu env *` commands enable management of environment',
  'variables for the app. Valid commands are:',
  '',
  'jitsu env list',
  'jitsu env list   <app>',
  'jitsu env set    <key> <value>',
  'jitsu env get    <key>',
  'jitsu env delete <key>',
  'jitsu env clear',
  'jitsu env save  [<app>] [<file>]',
  'jitsu env load  [<app>] [<file>]'
];

//
// ### function set (key, value, callback)
// #### @key {string} Key to set in jitsu config.
// #### @value {string} Value to set the key to.
// #### @callback {function} Continuation to pass control to when complete
// Sets the specified `key` in the environment variables to `value` for
// the application in the current directory.
//
env.set = function (appName, key, value, callback) {
  //
  // Allows arbitrary amount of arguments
  //
  if(arguments.length) {
    var args = utile.args(arguments);
    callback = args.callback;
    appName  = args[0] || null;
    key      = args[1] || null;
    value    = args[2] || null;
  }

  if (value === null) {
		if (key === null) {
		  jitsu.log.error(
        'Environment variable name and value and both required'
      );
      return callback({});
		}

    value = key;
    key = appName;
    return viewApp(callback, update);
  }

  viewAppByName(appName, callback, update);

  function update(err, app) {

    app.env = app.env || {};
    app.env[key] = value;
    jitsu.apps.update(app.name, { env: app.env }, callback);
  }
};

//
// Usage for `jitsu env set <key> <value>`
//
env.set.usage = [
  'Sets the specified `key` in the environment variables to `value`',
  'for the application in the current directory.',
  '',
  'jitsu env set <key> <value>'
];

//
// ### function get (key, callback)
// #### @key {string} Key to get in jitsu config.
// #### @callback {function} Continuation to pass control to when complete
// Gets the specified `key` in the environment variables for the
// application in the current directory.
//
env.get = function (appName, key, callback) {
  //
  // Allows arbitrary amount of arguments
  //
  if(arguments.length) {
    var args = utile.args(arguments);
    callback = args.callback;
    appName  = args[0] || null;
    key      = args[1] || null;
  }

  if (key === null) {
    key = appName;
    return viewApp(callback, gotEnv);
  }

  viewAppByName(appName, callback, gotEnv);

  function gotEnv(err, app) {
    if (!app.env[key]) {
      jitsu.log.warn('No environment variables for ' + key.yellow);
      return callback();
    }

    jitsu.log.data([key.yellow, app.env[key].toString().magenta].join(' '));
    callback();
  }
};

//
// Usage for `jitsu config get <key>`
//
env.get.usage = [
  'Gets the specified `key` in the environment variables for the',
  'application in the current directory.',
  '',
  'jitsu env get <key>'
];

//
// ### function delete (key, callback)
// #### @key {string} Key to delete, in jitsu config.
// #### @callback {function} Continuation to pass control to when complete
// Deletes the specified `key` in the environment variables for the
// application in the current directory.
//
env.delete = function (appName, key, callback) {
  //
  // Allows arbitrary amount of arguments
  //
  if(arguments.length) {
    var args = utile.args(arguments);
    callback = args.callback;
    appName  = args[0] || null;
    key      = args[1] || null;
  }

  if (key === null) {
    key = appName;
    return viewApp(callback, deleteKey);
  }

  viewAppByName(appName, callback, deleteKey);

  function deleteKey(err, app) {
    if (!app.env[key]) {
      jitsu.log.warn('No environment variables for ' + key.yellow);
      return callback();
    }

    delete app.env[key];
    jitsu.apps.update(app.name, { env: app.env }, callback);
  }
};

//
// Usage for `jitsu env delete <key>`
//
env.delete.usage = [
  'Deletes the specified `key` in the environment variables for the',
  'application in the current directory.',
  '',
  'jitsu env delete <key>'
];

//
// ### function list (callback)
// #### @callback {function} Continuation to pass control to when complete
// Lists all environment variables for the application in the
// current directory.
//
env.list = function (appName, callback) {
  //
  // Allows arbitrary amount of arguments
  //
  if(arguments.length) {
    var args = utile.args(arguments);
    callback = args.callback;
    appName  = args[0] || null;
  }

  function executeList(err, app) {
    if (!app.env || Object.keys(app.env).length === 0) {
      jitsu.log.warn('No environment variables for ' + app.name.magenta);
      return callback();
    }

    jitsu.log.info('Listing all environment variables for ' + app.name.magenta);
    jitsu.inspect.putObject(app.env);
    callback();
  }

  if (!appName) {
    viewApp(callback, executeList);
  }
  else {
    viewAppByName(appName, callback, executeList);
  }
};

//
// Alias `env ls` to `env list`
//
// Remark: Attempting to put this alias in `alias.js` file did not work.
//
env.ls = env.list;

//
// Usage for `jitsu env list`
//
env.list.usage = [
  'Lists all environment variables for the application in the',
  'current directory.',
  '',
  'jitsu env list'
];

env.clear = function (appName, callback) {
  //
  // Allows arbitrary amount of arguments
  //
  if(arguments.length) {
    var args = utile.args(arguments);
    callback = args.callback;
    appName  = args[0] || null;
  }

  if (appName === null) {
    return viewApp(callback, clearEnv);
  }

  viewAppByName(appName, callback, clearEnv);

  function clearEnv(err, app) {
    if (!app.env || Object.keys(app.env).length === 0) {
      jitsu.log.warn('No environment variables for ' + app.name.magenta);
      return callback();
    }

    jitsu.log.warn('All environment variables for ' + app.name.magenta + ' will be deleted.');
    jitsu.prompt.confirm('yes/no', { default: 'yes'}, function (err, result) {
      return (err || !result)
        ? callback(err)
        : jitsu.apps.update(app.name, { env: {} }, callback);
    });
  }
};

//
// ### function save (callback)
// #### @callback {function} Continuation to pass control to when complete
// Outputs all environment variables into env.json for the application in the
// current directory.
//
env.save = function (appName, file, callback) {
  //
  // Allows arbitrary amount of arguments
  //
  if(arguments.length) {
    var args = utile.args(arguments);
    callback = args.callback;
    appName  = args[0] || null;
    file     = args[1] || 'env.json';
    if (appName === null){
      viewApp(callback, executeSave);
    } else{
      viewAppByName(appName, function(){jitsu.commands.env.save(null, appName, callback);}, executeSave);
    }
  }

  function executeSave(err, app) {
    if (!app.env || Object.keys(app.env).length === 0) {
      jitsu.log.warn('No environment variables for ' + app.name.magenta);
      return callback();
    }

    jitsu.log.info('Saving all environment variables for ' + app.name.magenta
        + ' to ' + file);
    jitsu.log.warn('This may contain sensitive data. Be sure not to commit this'
        + ' file to some public repository. YOU HAVE BEEN WARNED.');
    jitsu.log.info('Is this okay?');
    jitsu.prompt.confirm('yes/no', { default: 'yes'}, function (err, result) {
      if (result) {
        fs.writeFile(file, JSON.stringify(app.env, null, 2), function (err) {
          if (!err) {
            jitsu.log.info(file.yellow + ' written!');
          }
          callback(err);
        });
      }
      else {
        jitsu.log.info(file + ' not written.');
      }
    });
  }
};

//
// Usage for `jitsu env save`
//
env.save.usage = [
  'Save all environment variables to env.json, or to <file> if specified, for the',
  'application in the current directory, or the specified <app>.',
  '',
  'jitsu env save',
  'jitsu env save <file>',
  'jitsu env save <file> <app>',
];

//
// ### function load (callback)
// #### @callback {function} Continuation to pass control to when complete
// Loads all environment variables from a json file for the application in the
// current directory.
//
env.load = function (appName, file, callback) {
  //
  // Allows arbitrary amount of arguments
  //
  if(arguments.length) {
    var args = utile.args(arguments);
    callback = args.callback;
    file     = args[0] || 'env.json';
    appName  = args[1] || null;
  }

  function executeLoad(err, app) {
    var env;
    jitsu.log.info('Replacing all environment variables for ' + app.name.magenta
        + ' from variables in ' + file);
    fs.readFile(file, function (err, data) {
      if (err) {
        return callback(err);
      }

      try {
        env = JSON.parse(data);
      }
      catch (err) {
        jitsu.log.error('Error parsing ' + file);
        return callback(err);
      }

      if (env.SUBDOMAIN !== app.env.SUBDOMAIN) {
        jitsu.log.error('Refusing to change SUBDOMAIN environment variable.');
        return callback(null);
      }

      jitsu.log.info('Old environment variables: ');
      jitsu.inspect.putObject(app.env);
      jitsu.log.info('New environment variables: ');
      jitsu.inspect.putObject(env);
      jitsu.log.warn('YOU CAN LOSE ENVIRONMENT VARIABLES IF YOU ARE NOT CAREFUL.');
      jitsu.log.info('Is this okay?');
      jitsu.prompt.confirm('yes/no', { default: 'yes'}, function (err, result) {
        if (result) {
          jitsu.apps.update(app.name, { env: env }, callback);
        } else {
          jitsu.log.info('Environment vaiables for ' + app.name.magenta +
            ' were not replaced.');
          callback(null);
        }
      });
    });
  }

  if (!appName) {
    viewApp(callback, executeLoad);
  }
  else {
    viewAppByName(appName, callback, executeLoad);
  }
};

//
// Usage for `jitsu env load`
//
env.load.usage = [
  'Replaces all environment variables from env.json, or from <file> if specified,',
  'for the application in the current directory, or the specified <app>. Suggested',
  'for use with `jitsu env save`. See `jitsu help env save` for more info.',
  '',
  'jitsu env load',
  'jitsu env load <file>',
  'jitsu env load <file> <app>',
];

//
// ### @private viewApp (callback, success)
// #### @callback {function} Continuation to respond to on error.
// #### @success {function} Continuation to respond to on success.
// Attempts to read the package.json for the current directory
// and retrieve it from Nodejitsu.
//
function viewApp(callback, success) {
  jitsu.package.tryRead(process.cwd(), callback, function (pkg) {
    jitsu.log.info('Attempting to load env variables for app ' + (process.cwd()+ '/package.json').grey);
    jitsu.apps.view(pkg.name, function (err, app) {
      //
      // TODO: replace this error handling with errs library
      //
      if (err && err.result && err.result.error === "not_found") {
        jitsu.log.error('app ' + pkg.name.magenta + ' doesn\'t exist on Nodejitsu yet!');
        return callback({});
      }
      return err ? callback(err) : success(null, app);
    });
  });
}

//
// ### @private viewAppByName (appName, callback, success)
// #### @callback {function} Continuation to respond to on error.
// #### @success {function} Continuation to respond to on success.
// Attempts to retrieve the application from Nodejitsu with the given name.
//
function viewAppByName(appName, callback, success) {
  jitsu.apps.view(appName, function (err, app) {
    return err ? callback(err) : success(null, app);
  });
}
<commit_msg>[doc] updated env.save usage<commit_after>/*
 * env.js: Commands related to environment variables for Nodejitsu applications.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var jitsu = require('../../jitsu'),
    fs = require('fs'),
    utile = jitsu.common;

var env = exports;

env.usage = [
  '`jitsu env *` commands enable management of environment',
  'variables for the app. Valid commands are:',
  '',
  'jitsu env list',
  'jitsu env list   <app>',
  'jitsu env set    <key> <value>',
  'jitsu env get    <key>',
  'jitsu env delete <key>',
  'jitsu env clear',
  'jitsu env save  [<app>] [<file>]',
  'jitsu env load  [<app>] [<file>]'
];

//
// ### function set (key, value, callback)
// #### @key {string} Key to set in jitsu config.
// #### @value {string} Value to set the key to.
// #### @callback {function} Continuation to pass control to when complete
// Sets the specified `key` in the environment variables to `value` for
// the application in the current directory.
//
env.set = function (appName, key, value, callback) {
  //
  // Allows arbitrary amount of arguments
  //
  if(arguments.length) {
    var args = utile.args(arguments);
    callback = args.callback;
    appName  = args[0] || null;
    key      = args[1] || null;
    value    = args[2] || null;
  }

  if (value === null) {
		if (key === null) {
		  jitsu.log.error(
        'Environment variable name and value and both required'
      );
      return callback({});
		}

    value = key;
    key = appName;
    return viewApp(callback, update);
  }

  viewAppByName(appName, callback, update);

  function update(err, app) {

    app.env = app.env || {};
    app.env[key] = value;
    jitsu.apps.update(app.name, { env: app.env }, callback);
  }
};

//
// Usage for `jitsu env set <key> <value>`
//
env.set.usage = [
  'Sets the specified `key` in the environment variables to `value`',
  'for the application in the current directory.',
  '',
  'jitsu env set <key> <value>'
];

//
// ### function get (key, callback)
// #### @key {string} Key to get in jitsu config.
// #### @callback {function} Continuation to pass control to when complete
// Gets the specified `key` in the environment variables for the
// application in the current directory.
//
env.get = function (appName, key, callback) {
  //
  // Allows arbitrary amount of arguments
  //
  if(arguments.length) {
    var args = utile.args(arguments);
    callback = args.callback;
    appName  = args[0] || null;
    key      = args[1] || null;
  }

  if (key === null) {
    key = appName;
    return viewApp(callback, gotEnv);
  }

  viewAppByName(appName, callback, gotEnv);

  function gotEnv(err, app) {
    if (!app.env[key]) {
      jitsu.log.warn('No environment variables for ' + key.yellow);
      return callback();
    }

    jitsu.log.data([key.yellow, app.env[key].toString().magenta].join(' '));
    callback();
  }
};

//
// Usage for `jitsu config get <key>`
//
env.get.usage = [
  'Gets the specified `key` in the environment variables for the',
  'application in the current directory.',
  '',
  'jitsu env get <key>'
];

//
// ### function delete (key, callback)
// #### @key {string} Key to delete, in jitsu config.
// #### @callback {function} Continuation to pass control to when complete
// Deletes the specified `key` in the environment variables for the
// application in the current directory.
//
env.delete = function (appName, key, callback) {
  //
  // Allows arbitrary amount of arguments
  //
  if(arguments.length) {
    var args = utile.args(arguments);
    callback = args.callback;
    appName  = args[0] || null;
    key      = args[1] || null;
  }

  if (key === null) {
    key = appName;
    return viewApp(callback, deleteKey);
  }

  viewAppByName(appName, callback, deleteKey);

  function deleteKey(err, app) {
    if (!app.env[key]) {
      jitsu.log.warn('No environment variables for ' + key.yellow);
      return callback();
    }

    delete app.env[key];
    jitsu.apps.update(app.name, { env: app.env }, callback);
  }
};

//
// Usage for `jitsu env delete <key>`
//
env.delete.usage = [
  'Deletes the specified `key` in the environment variables for the',
  'application in the current directory.',
  '',
  'jitsu env delete <key>'
];

//
// ### function list (callback)
// #### @callback {function} Continuation to pass control to when complete
// Lists all environment variables for the application in the
// current directory.
//
env.list = function (appName, callback) {
  //
  // Allows arbitrary amount of arguments
  //
  if(arguments.length) {
    var args = utile.args(arguments);
    callback = args.callback;
    appName  = args[0] || null;
  }

  function executeList(err, app) {
    if (!app.env || Object.keys(app.env).length === 0) {
      jitsu.log.warn('No environment variables for ' + app.name.magenta);
      return callback();
    }

    jitsu.log.info('Listing all environment variables for ' + app.name.magenta);
    jitsu.inspect.putObject(app.env);
    callback();
  }

  if (!appName) {
    viewApp(callback, executeList);
  }
  else {
    viewAppByName(appName, callback, executeList);
  }
};

//
// Alias `env ls` to `env list`
//
// Remark: Attempting to put this alias in `alias.js` file did not work.
//
env.ls = env.list;

//
// Usage for `jitsu env list`
//
env.list.usage = [
  'Lists all environment variables for the application in the',
  'current directory.',
  '',
  'jitsu env list'
];

env.clear = function (appName, callback) {
  //
  // Allows arbitrary amount of arguments
  //
  if(arguments.length) {
    var args = utile.args(arguments);
    callback = args.callback;
    appName  = args[0] || null;
  }

  if (appName === null) {
    return viewApp(callback, clearEnv);
  }

  viewAppByName(appName, callback, clearEnv);

  function clearEnv(err, app) {
    if (!app.env || Object.keys(app.env).length === 0) {
      jitsu.log.warn('No environment variables for ' + app.name.magenta);
      return callback();
    }

    jitsu.log.warn('All environment variables for ' + app.name.magenta + ' will be deleted.');
    jitsu.prompt.confirm('yes/no', { default: 'yes'}, function (err, result) {
      return (err || !result)
        ? callback(err)
        : jitsu.apps.update(app.name, { env: {} }, callback);
    });
  }
};

//
// ### function save (callback)
// #### @callback {function} Continuation to pass control to when complete
// Outputs all environment variables into env.json for the application in the
// current directory.
//
env.save = function (appName, file, callback) {
  //
  // Allows arbitrary amount of arguments
  //
  if(arguments.length) {
    var args = utile.args(arguments);
    callback = args.callback;
    appName  = args[0] || null;
    file     = args[1] || 'env.json';
    if (appName === null){
      viewApp(callback, executeSave);
    } else{
      viewAppByName(appName, function(){jitsu.commands.env.save(null, appName, callback);}, executeSave);
    }
  }

  function executeSave(err, app) {
    if (!app.env || Object.keys(app.env).length === 0) {
      jitsu.log.warn('No environment variables for ' + app.name.magenta);
      return callback();
    }

    jitsu.log.info('Saving all environment variables for ' + app.name.magenta
        + ' to ' + file);
    jitsu.log.warn('This may contain sensitive data. Be sure not to commit this'
        + ' file to some public repository. YOU HAVE BEEN WARNED.');
    jitsu.log.info('Is this okay?');
    jitsu.prompt.confirm('yes/no', { default: 'yes'}, function (err, result) {
      if (result) {
        fs.writeFile(file, JSON.stringify(app.env, null, 2), function (err) {
          if (!err) {
            jitsu.log.info(file.yellow + ' written!');
          }
          callback(err);
        });
      }
      else {
        jitsu.log.info(file + ' not written.');
      }
    });
  }
};

//
// Usage for `jitsu env save`
//
env.save.usage = [
  'Save all environment variables to env.json, or to <file> if specified, for the',
  'application in the current directory, or the specified <app>.',
  '',
  'jitsu env save',
  'jitsu env save [<app>]',
  'jitsu env save [<file>]',
  'jitsu env save [<app>] [<file>]',
];

//
// ### function load (callback)
// #### @callback {function} Continuation to pass control to when complete
// Loads all environment variables from a json file for the application in the
// current directory.
//
env.load = function (appName, file, callback) {
  //
  // Allows arbitrary amount of arguments
  //
  if(arguments.length) {
    var args = utile.args(arguments);
    callback = args.callback;
    file     = args[0] || 'env.json';
    appName  = args[1] || null;
  }

  function executeLoad(err, app) {
    var env;
    jitsu.log.info('Replacing all environment variables for ' + app.name.magenta
        + ' from variables in ' + file);
    fs.readFile(file, function (err, data) {
      if (err) {
        return callback(err);
      }

      try {
        env = JSON.parse(data);
      }
      catch (err) {
        jitsu.log.error('Error parsing ' + file);
        return callback(err);
      }

      if (env.SUBDOMAIN !== app.env.SUBDOMAIN) {
        jitsu.log.error('Refusing to change SUBDOMAIN environment variable.');
        return callback(null);
      }

      jitsu.log.info('Old environment variables: ');
      jitsu.inspect.putObject(app.env);
      jitsu.log.info('New environment variables: ');
      jitsu.inspect.putObject(env);
      jitsu.log.warn('YOU CAN LOSE ENVIRONMENT VARIABLES IF YOU ARE NOT CAREFUL.');
      jitsu.log.info('Is this okay?');
      jitsu.prompt.confirm('yes/no', { default: 'yes'}, function (err, result) {
        if (result) {
          jitsu.apps.update(app.name, { env: env }, callback);
        } else {
          jitsu.log.info('Environment vaiables for ' + app.name.magenta +
            ' were not replaced.');
          callback(null);
        }
      });
    });
  }

  if (!appName) {
    viewApp(callback, executeLoad);
  }
  else {
    viewAppByName(appName, callback, executeLoad);
  }
};

//
// Usage for `jitsu env load`
//
env.load.usage = [
  'Replaces all environment variables from env.json, or from <file> if specified,',
  'for the application in the current directory, or the specified <app>. Suggested',
  'for use with `jitsu env save`. See `jitsu help env save` for more info.',
  '',
  'jitsu env load',
  'jitsu env load <file>',
  'jitsu env load <file> <app>',
];

//
// ### @private viewApp (callback, success)
// #### @callback {function} Continuation to respond to on error.
// #### @success {function} Continuation to respond to on success.
// Attempts to read the package.json for the current directory
// and retrieve it from Nodejitsu.
//
function viewApp(callback, success) {
  jitsu.package.tryRead(process.cwd(), callback, function (pkg) {
    jitsu.log.info('Attempting to load env variables for app ' + (process.cwd()+ '/package.json').grey);
    jitsu.apps.view(pkg.name, function (err, app) {
      //
      // TODO: replace this error handling with errs library
      //
      if (err && err.result && err.result.error === "not_found") {
        jitsu.log.error('app ' + pkg.name.magenta + ' doesn\'t exist on Nodejitsu yet!');
        return callback({});
      }
      return err ? callback(err) : success(null, app);
    });
  });
}

//
// ### @private viewAppByName (appName, callback, success)
// #### @callback {function} Continuation to respond to on error.
// #### @success {function} Continuation to respond to on success.
// Attempts to retrieve the application from Nodejitsu with the given name.
//
function viewAppByName(appName, callback, success) {
  jitsu.apps.view(appName, function (err, app) {
    return err ? callback(err) : success(null, app);
  });
}
<|endoftext|>


<commit_before>/*

 bootpag - jQuery plugin for dynamic pagination

 Copyright (c) 2013 botmonster@7items.com

 Licensed under the MIT license:
   http://www.opensource.org/licenses/mit-license.php

 Project home:
   http://botmonster.com/jquery-bootpag/

 Version:  1.0.4

*/
(function(f,q){f.fn.bootpag=function(p){function k(e,b){var c,d=0==a.maxVisible?1:a.maxVisible,n=1==a.maxVisible?0:1,m=Math.floor((b-1)/d)*d,g=e.find("li");a.page=b=0>b?0:b>a.total?a.total:b;g.removeClass("disabled");c=1>b-1?1:a.leaps&&b-1>=a.maxVisible?Math.floor((b-1)/d)*d:b-1;g.first().toggleClass("disabled",1===b).attr("data-lp",c).find("a").attr("href",h(c));n=1==a.maxVisible?0:1;c=b+1>a.total?a.total:a.leaps&&b+1<a.total-a.maxVisible?m+a.maxVisible+n:b+1;g.last().toggleClass("disabled",b===
a.total).attr("data-lp",c).find("a").attr("href",h(c));d=g.filter("[data-lp="+b+"]");if(!d.not(".next,.prev").length){var k=b<=m?-a.maxVisible:0;g.not(".next,.prev").each(function(b){c=b+1+m+k;f(this).attr("data-lp",c).toggle(c<=a.total).find("a").html(c).attr("href",h(c))});d=g.filter("[data-lp="+b+"]")}d.addClass("disabled");l.trigger("page",b);l.data("settings",a)}function h(e){return a.href.replace(a.hrefVariable,e)}var l=this,a=f.extend({total:0,page:1,maxVisible:null,leaps:!0,href:"javascript:void(0);",
hrefVariable:"{{number}}",next:"»",prev:"«"},l.data("settings")||{},p||{});if(0>=a.total)return this;!f.isNumeric(a.maxVisible)&&!a.maxVisible&&(a.maxVisible=a.total);l.data("settings",a);return this.each(function(){var e,b,c=f(this),d=['
'];a.prev&&d.push('
'+a.prev+"
");for(b=1;b<=Math.min(a.total,a.maxVisible);b++)d.push('
'+b+"
");a.next&&(b=a.leaps&&a.total>a.maxVisible?
Math.min(a.maxVisible+1,a.total):2,d.push('
'+a.next+"
"));d.push("
");c.find("ul.bootpag").remove();c.append(d.join("")).addClass("pagination");e=c.find("ul.bootpag");c.find("li").click(function(){var a=f(this);a.hasClass("disabled")||k(e,parseInt(a.attr("data-lp"),10))});k(e,a.page)})}})(jQuery,window);
<commit_msg>compress<commit_after>/*

 bootpag - jQuery plugin for dynamic pagination

 Copyright (c) 2013 botmonster@7items.com

 Licensed under the MIT license:
   http://www.opensource.org/licenses/mit-license.php

 Project home:
   http://botmonster.com/jquery-bootpag/

 Version:  1.0.4

*/
(function(b,a){b.fn.bootpag=function(d){var g=this,e=b.extend({total:0,page:1,maxVisible:null,leaps:true,href:"javascript:void(0);",hrefVariable:"{{number}}",next:"»",prev:"«",firstLastUse:false,first:"First",last:"Last"},g.data("settings")||{},d||{});if(e.total<=0){return this}if(!b.isNumeric(e.maxVisible)&&!e.maxVisible){e.maxVisible=e.total}g.data("settings",e);function f(h,r){var o,j=e.maxVisible==0?1:e.maxVisible,l=e.maxVisible==1?0:1,i=Math.floor((r-1)/j)*j,n=h.find("li");e.page=r=r<0?0:r>e.total?e.total:r;n.removeClass("active");o=r-1<1?1:e.leaps&&r-1>=e.maxVisible?Math.floor((r-1)/j)*j:r-1;if(e.firstLastUse){n.first().toggleClass("disabled",r===1)}var p=n.first();if(e.firstLastUse){p=p.next()}p.toggleClass("disabled",r===1).attr("data-lp",o).find("a").attr("href",c(o));var l=e.maxVisible==1?0:1;o=r+1>e.total?e.total:e.leaps&&r+1<e.total-e.maxVisible?i+e.maxVisible+l:r+1;var m=n.last();if(e.firstLastUse){m=m.prev()}m.toggleClass("disabled",r===e.total).attr("data-lp",o).find("a").attr("href",c(o));n.last().toggleClass("disabled",r===e.total);var k=n.filter("[data-lp="+r+"]");if(!k.not(".next,.prev,.last,.first").length){var q=r<=i?-e.maxVisible:0;n.not(".next,.prev,.last,.first").each(function(s){o=s+1+i+q;b(this).attr("data-lp",o).toggle(o<=e.total).find("a").html(o).attr("href",c(o))});k=n.filter("[data-lp="+r+"]")}k.addClass("active");g.trigger("page",r);g.data("settings",e)}function c(h){return e.href.replace(e.hrefVariable,h)}return this.each(function(){var j,i,k=b(this),l=['
'];if(e.firstLastUse){l.push('
'+e.first+"
")}if(e.prev){l.push('
'+e.prev+"
")}for(var m=1;m<=Math.min(e.total,e.maxVisible);m++){l.push('
'+m+"
")}if(e.next){i=e.leaps&&e.total>e.maxVisible?Math.min(e.maxVisible+1,e.total):2;l.push('
'+e.next+"
")}if(e.firstLastUse){l.push('
'+e.last+"
")}l.push("
");k.find("ul.bootpag").remove();k.append(l.join("")).addClass("pagination");j=k.find("ul.bootpag");k.find("li").click(function h(){var n=b(this);if(n.hasClass("active")||n.hasClass("disabled")){return}f(j,parseInt(n.attr("data-lp"),10))});f(j,e.page)})}})(jQuery,window);
<|endoftext|>


<commit_before>/*
 * Another In Place Editor - a jQuery edit in place plugin
 *
 * Copyright (c) 2009 Dave Hauenstein
 *
 * License:
 * This source file is subject to the BSD license bundled with this package.
 * Available online: {@link http://www.opensource.org/licenses/bsd-license.php}
 * If you did not receive a copy of the license, and are unable to obtain it,
 * email davehauenstein@gmail.com,
 * and I will send you a copy.
 *
 * Project home:
 * http://code.google.com/p/jquery-in-place-editor/
 *
 */

/*
 * Version 1.0.2
 *
 * bg_out (string) default: transparent hex code of background color on restore from hover
 * bg_over (string) default: #ffc hex code of background color on hover
 * callback (function) default: null function to be called when editing is complete; cancels ajax submission to the url param
 * cancel_button (string) default: <input type=”submit” class=”inplace_cancel” value=”Cancel”/> image button tag to use as “Cancel” button
 * default_text (string) default: “(Click here to add text)” text to show up if the element that has this functionality is empty
 * element_id (string) default: element_id name of parameter holding element_id
 * error (function) this function gets called if server responds with an error
 * field_type (string) “text”, “textarea”, or “select”; default: “text” The type of form field that will appear on instantiation
 * on_blur (string) “save” or null; default: “save” what to do on blur; will be overridden if $param show_buttons is true
 * original_html (string) default: original_html name of parameter holding original_html
 * params (string) example: first_name=dave&last_name=hauenstein paramters sent via the post request to the server
 * save_button (string) default: <input type=”submit” class=”inplace_save” value=”Save”/> image button tag to use as “Save” button
 * saving_image (string) default: uses saving text specify an image location instead of text while server is saving
 * saving_text (string) default: “Saving…” text to be used when server is saving information
 * select_options (string) comma delimited list of options if field_type is set to select
 * select_text (string)default text to show up in select box
 * show_buttons (boolean) default: false will show the buttons: cancel or save; will automatically cancel out the onBlur functionality
 * success (function) default: null this function gets called if server responds with a success
 * textarea_cols (integer) default: 25 set cols attribute of textarea, if field_type is set to textarea
 * textarea_rows (integer) default: 10 set rows attribute of textarea, if field_type is set to textarea
 * update_value (string) default: update_value name of parameter holding update_value
 * url (string) POST URL to send edited content
 * value_required (string) default: false if set to true, the element will not be saved unless a value is entered
 *
 */

jQuery.fn.editInPlace = function(options) {

	/* DEFINE THE DEFAULT SETTINGS, SWITCH THEM WITH THE OPTIONS USER PROVIDES */
	var settings = {
		url:				"",
		params:				"",
		field_type:			"text",
		select_options:		"",
		textarea_cols:		"25",
		textarea_rows:		"10",
		bg_over:			"#ffc",
		bg_out:				"transparent",
		saving_text:		"Saving...",
		saving_image:		"",
		default_text:		"(Click here to add text)",
		select_text:		"Choose new value",
		value_required:		null,
		element_id:			"element_id",
		update_value:		"update_value",
		original_html:		"original_html",
		save_button:		'<button class="inplace_save">Save</button>',
		cancel_button:		'<button class="inplace_cancel">Cancel</button>',
		show_buttons:		false,
		on_blur:			"save",
		callback:			null,
		callbackShowErrors: true,
		success:			null,
		error:				function(request){
                                alert("Failed to save value: " + request.responseText || 'Unspecified Error');
                            }
	};

	if(options) {
		jQuery.extend(settings, options);
	}

	/* preload the loading icon if it exists */
	if(settings.saving_image != ""){
		var loading_image = new Image();
		loading_image.src = settings.saving_image;
	}

	/* THIS FUNCTION WILL TRIM WHITESPACE FROM BEFORE/AFTER A STRING */
	String.prototype.trim = function() {
		return this.replace(/^\s+/, '')
							 .replace(/\s+$/, '');
	};

	/* THIS FUNCTION WILL ESCAPE ANY HTML ENTITIES SO "Quoted Values" work */
	String.prototype.escape_html = function() {
		return this.replace(/&/g, "&")
							 .replace(/</g, "<")
							 .replace(/>/g, ">")
							 .replace(/"/g, """);
  };

	/* CREATE THE INPLACE EDITOR */
	return this.each(function(){

		if(jQuery(this).html() == "") jQuery(this).html(settings.default_text);

		var editing = false;

		//save the original element - for change of scope
		var original_element = jQuery(this);

		var click_count = 0;

		jQuery(this)

		.mouseover(function(){
			jQuery(this).css("background", settings.bg_over);
		})

		.mouseout(function(){
			jQuery(this).css("background", settings.bg_out);
		})

		.click(function(){
			click_count++;

			if(!editing)
			{
				editing = true;

				//save original text - for cancellation functionality
				var original_html = jQuery(this).html();
				var buttons_code  = (settings.show_buttons) ? settings.save_button + ' ' + settings.cancel_button : '';

				//if html is our default text, clear it out to prevent saving accidentally
				if (original_html == settings.default_text) jQuery(this).html('');

				if (settings.field_type == "textarea")
				{
					var use_field_type = '<textarea name="inplace_value" class="inplace_field" rows="' + settings.textarea_rows + '" cols="' + settings.textarea_cols + '">' + jQuery(this).text().trim().escape_html() + '</textarea>';
				}
				else if(settings.field_type == "text")
				{
					var use_field_type = '<input type="text" name="inplace_value" class="inplace_field" value="' +
											jQuery(this).text().trim().escape_html() + '" />';
				}
				else if(settings.field_type == "select")
				{
					var optionsArray = settings.select_options.split(',');
					var use_field_type = '<select name="inplace_value" class="inplace_field"><option value="">' + settings.select_text + '</option>';
						for(var i=0; i<optionsArray.length; i++){
							var optionsValuesArray = optionsArray[i].split(':');
							var use_value = optionsValuesArray[1] || optionsValuesArray[0];
							var selected = use_value == original_html ? 'selected="selected" ' : '';
							use_field_type += '<option ' + selected + 'value="' + use_value.trim().escape_html() + '">' + optionsValuesArray[0].trim().escape_html() + '</option>';
                        }
						use_field_type += '</select>';
				}

				/* insert the new in place form after the element they click, then empty out the original element */
				jQuery(this).html('<form class="inplace_form" style="display: inline; margin: 0; padding: 0;">' + use_field_type + ' ' + buttons_code + '</form>');

			}/* END- if(!editing) -END */

			if(click_count == 1)
			{
				function cancelAction()
				{
					editing = false;
					click_count = 0;

					/* put the original background color in */
					original_element.css("background", settings.bg_out);

					/* put back the original text */
					original_element.html(original_html);

					return false;
				}

				function saveAction()
				{
					/* put the original background color in */
					original_element.css("background", settings.bg_out);

                    var this_elem = jQuery(this);

					var new_html = (this_elem.is('form')) ? this_elem.children(0).val() : this_elem.parent().children(0).val();

					/* set saving message */
					if(settings.saving_image != ""){
						var saving_message = '';
					} else {
						var saving_message = settings.saving_text;
					}

					/* place the saving text/image in the original element */
					original_element.html(saving_message);

					if(settings.params != ""){
						settings.params = "&" + settings.params;
					}

					if(settings.callback) {
						html = settings.callback(original_element.attr("id"), new_html, original_html, settings.params);
						editing = false;
						click_count = 0;
						if (html) {
							/* put the newly updated info into the original element */
							original_element.html(html || new_html);
						} else {
							/* failure; put original back */
							if(settings.callbackShowErrors)
							{
							    alert("Failed to save value: " + new_html);
							}
							original_element.html(original_html);
						}
					} else if (settings.value_required && (new_html == "" || new_html == undefined)) {
						editing = false;
						click_count = 0;
						original_element.html(original_html);
						alert("Error: You must enter a value to save this field");
					} else {
						jQuery.ajax({
							url: settings.url,
							type: "POST",
							data: settings.update_value + '=' + new_html + '&' + settings.element_id + '=' + original_element.attr("id") + settings.params + '&' + settings.original_html + '=' + original_html,
							dataType: "html",
							complete: function(request){
								editing = false;
								click_count = 0;
							},
							success: function(html){
								/* if the text returned by the server is empty, */
   								/* put a marker as text in the original element */
								var new_text = html || settings.default_text;

								/* put the newly updated info into the original element */
								original_element.html(new_text);
								if (settings.success) settings.success(html, original_element);
							},
							error: function(request) {
								original_element.html(original_html);
								if (settings.error) settings.error(request, original_element);
							}
						});
					}

					return false;
				}

				/* set the focus to the new input element */
				original_element.children("form").children(".inplace_field").focus().select();

				/* CLICK CANCEL BUTTON functionality */
				original_element.children("form").children(".inplace_cancel").click(cancelAction);

				/* CLICK SAVE BUTTON functionality */
				original_element.children("form").children(".inplace_save").click(saveAction);

                /* if cancel/save buttons should be shown, cancel blur functionality */
                if(!settings.show_buttons){
                    /* if on_blur is set to save, set the save funcion */
    				if(settings.on_blur == "save")
    					original_element.children("form").children(".inplace_field").blur(saveAction);
    				/* if on_blur is set to cancel, set the cancel funcion */
    				else
    					original_element.children("form").children(".inplace_field").blur(cancelAction);
                }

				/* hit esc key */
				$(document).keyup(function(event){
				    if (event.keyCode == 27) {
						cancelAction();
				    }
				});

                original_element.children("form").submit(saveAction);

			}/* END- if(click_count == 1) -END */
		});
	});
};<commit_msg>added some todos<commit_after>/*
 * Another In Place Editor - a jQuery edit in place plugin
 *
 * Copyright (c) 2009 Dave Hauenstein
 *
 * License:
 * This source file is subject to the BSD license bundled with this package.
 * Available online: {@link http://www.opensource.org/licenses/bsd-license.php}
 * If you did not receive a copy of the license, and are unable to obtain it,
 * email davehauenstein@gmail.com,
 * and I will send you a copy.
 *
 * Project home:
 * http://code.google.com/p/jquery-in-place-editor/
 *
 */

/*
 * Version 1.0.2
 *
 * bg_out (string) default: transparent hex code of background color on restore from hover
 * bg_over (string) default: #ffc hex code of background color on hover
 * callback (function) default: null function to be called when editing is complete; cancels ajax submission to the url param
 * cancel_button (string) default: <input type=”submit” class=”inplace_cancel” value=”Cancel”/> image button tag to use as “Cancel” button
 * default_text (string) default: “(Click here to add text)” text to show up if the element that has this functionality is empty
 * element_id (string) default: element_id name of parameter holding element_id
 * error (function) this function gets called if server responds with an error
 * field_type (string) “text”, “textarea”, or “select”; default: “text” The type of form field that will appear on instantiation
 * on_blur (string) “save” or null; default: “save” what to do on blur; will be overridden if $param show_buttons is true
 * original_html (string) default: original_html name of parameter holding original_html
 * params (string) example: first_name=dave&last_name=hauenstein paramters sent via the post request to the server
 * save_button (string) default: <input type=”submit” class=”inplace_save” value=”Save”/> image button tag to use as “Save” button
 * saving_image (string) default: uses saving text specify an image location instead of text while server is saving
 * saving_text (string) default: “Saving…” text to be used when server is saving information
 * select_options (string) comma delimited list of options if field_type is set to select
 * select_text (string)default text to show up in select box
 * show_buttons (boolean) default: false will show the buttons: cancel or save; will automatically cancel out the onBlur functionality
 * success (function) default: null this function gets called if server responds with a success
 * textarea_cols (integer) default: 25 set cols attribute of textarea, if field_type is set to textarea
 * textarea_rows (integer) default: 10 set rows attribute of textarea, if field_type is set to textarea
 * update_value (string) default: update_value name of parameter holding update_value
 * url (string) POST URL to send edited content
 * value_required (string) default: false if set to true, the element will not be saved unless a value is entered
 *
 */

jQuery.fn.editInPlace = function(options) {

	/* DEFINE THE DEFAULT SETTINGS, SWITCH THEM WITH THE OPTIONS USER PROVIDES */
	// TODO: expose default settings
	// TODO: Support setting stuff via metadata plugin
	var settings = {
		url:				"",
		params:				"",
		field_type:			"text",
		select_options:		"",
		textarea_cols:		"25",
		textarea_rows:		"10",
		bg_over:			"#ffc",
		bg_out:				"transparent",
		saving_text:		"Saving...",
		saving_image:		"",
		default_text:		"(Click here to add text)",
		select_text:		"Choose new value",
		value_required:		null,
		element_id:			"element_id",
		update_value:		"update_value",
		original_html:		"original_html",
		save_button:		'<button class="inplace_save">Save</button>',
		cancel_button:		'<button class="inplace_cancel">Cancel</button>',
		show_buttons:		false,
		on_blur:			"save",
		callback:			null,
		callbackShowErrors: true,
		success:			null,
		error:				function(request){
                                alert("Failed to save value: " + request.responseText || 'Unspecified Error');
                            }
	};

	if(options) {
		jQuery.extend(settings, options);
	}

	/* preload the loading icon if it exists */
	if(settings.saving_image != ""){
		var loading_image = new Image();
		loading_image.src = settings.saving_image;
	}

	/* THIS FUNCTION WILL TRIM WHITESPACE FROM BEFORE/AFTER A STRING */
	String.prototype.trim = function() {
		return this.replace(/^\s+/, '')
							 .replace(/\s+$/, '');
	};

	/* THIS FUNCTION WILL ESCAPE ANY HTML ENTITIES SO "Quoted Values" work */
	String.prototype.escape_html = function() {
		return this.replace(/&/g, "&")
							 .replace(/</g, "<")
							 .replace(/>/g, ">")
							 .replace(/"/g, """);
  };

	/* CREATE THE INPLACE EDITOR */
	return this.each(function(){

		if(jQuery(this).html() == "") jQuery(this).html(settings.default_text);

		var editing = false;

		//save the original element - for change of scope
		var original_element = jQuery(this);

		var click_count = 0;

		jQuery(this)

		.mouseover(function(){
			jQuery(this).css("background", settings.bg_over);
		})

		.mouseout(function(){
			jQuery(this).css("background", settings.bg_out);
		})

		.click(function(){
			click_count++;

			if(!editing)
			{
				editing = true;

				//save original text - for cancellation functionality
				var original_html = jQuery(this).html();
				var buttons_code  = (settings.show_buttons) ? settings.save_button + ' ' + settings.cancel_button : '';

				//if html is our default text, clear it out to prevent saving accidentally
				if (original_html == settings.default_text) jQuery(this).html('');

				if (settings.field_type == "textarea")
				{
					var use_field_type = '<textarea name="inplace_value" class="inplace_field" rows="' + settings.textarea_rows + '" cols="' + settings.textarea_cols + '">' + jQuery(this).text().trim().escape_html() + '</textarea>';
				}
				else if(settings.field_type == "text")
				{
					var use_field_type = '<input type="text" name="inplace_value" class="inplace_field" value="' +
											jQuery(this).text().trim().escape_html() + '" />';
				}
				else if(settings.field_type == "select")
				{
					var optionsArray = settings.select_options.split(',');
					var use_field_type = '<select name="inplace_value" class="inplace_field"><option value="">' + settings.select_text + '</option>';
						for(var i=0; i<optionsArray.length; i++){
							var optionsValuesArray = optionsArray[i].split(':');
							var use_value = optionsValuesArray[1] || optionsValuesArray[0];
							var selected = use_value == original_html ? 'selected="selected" ' : '';
							use_field_type += '<option ' + selected + 'value="' + use_value.trim().escape_html() + '">' + optionsValuesArray[0].trim().escape_html() + '</option>';
                        }
						use_field_type += '</select>';
				}

				/* insert the new in place form after the element they click, then empty out the original element */
				jQuery(this).html('<form class="inplace_form" style="display: inline; margin: 0; padding: 0;">' + use_field_type + ' ' + buttons_code + '</form>');

			}/* END- if(!editing) -END */

			if(click_count == 1)
			{
				function cancelAction()
				{
					editing = false;
					click_count = 0;

					/* put the original background color in */
					original_element.css("background", settings.bg_out);

					/* put back the original text */
					original_element.html(original_html);

					return false;
				}

				function saveAction()
				{
					/* put the original background color in */
					original_element.css("background", settings.bg_out);

                    var this_elem = jQuery(this);

					var new_html = (this_elem.is('form')) ? this_elem.children(0).val() : this_elem.parent().children(0).val();

					/* set saving message */
					if(settings.saving_image != ""){
						var saving_message = '';
					} else {
						var saving_message = settings.saving_text;
					}

					/* place the saving text/image in the original element */
					original_element.html(saving_message);

					if(settings.params != ""){
						settings.params = "&" + settings.params;
					}

					if(settings.callback) {
						html = settings.callback(original_element.attr("id"), new_html, original_html, settings.params);
						editing = false;
						click_count = 0;
						if (html) {
							/* put the newly updated info into the original element */
							original_element.html(html || new_html);
						} else {
							/* failure; put original back */
							if(settings.callbackShowErrors)
							{
							    alert("Failed to save value: " + new_html);
							}
							original_element.html(original_html);
						}
					} else if (settings.value_required && (new_html == "" || new_html == undefined)) {
						editing = false;
						click_count = 0;
						original_element.html(original_html);
						alert("Error: You must enter a value to save this field");
					} else {
						jQuery.ajax({
							url: settings.url,
							type: "POST",
							data: settings.update_value + '=' + new_html + '&' + settings.element_id + '=' + original_element.attr("id") + settings.params + '&' + settings.original_html + '=' + original_html,
							dataType: "html",
							complete: function(request){
								editing = false;
								click_count = 0;
							},
							success: function(html){
								/* if the text returned by the server is empty, */
   								/* put a marker as text in the original element */
								var new_text = html || settings.default_text;

								/* put the newly updated info into the original element */
								original_element.html(new_text);
								if (settings.success) settings.success(html, original_element);
							},
							error: function(request) {
								original_element.html(original_html);
								if (settings.error) settings.error(request, original_element);
							}
						});
					}

					return false;
				}

				/* set the focus to the new input element */
				original_element.children("form").children(".inplace_field").focus().select();

				/* CLICK CANCEL BUTTON functionality */
				original_element.children("form").children(".inplace_cancel").click(cancelAction);

				/* CLICK SAVE BUTTON functionality */
				original_element.children("form").children(".inplace_save").click(saveAction);

                /* if cancel/save buttons should be shown, cancel blur functionality */
                if(!settings.show_buttons){
                    /* if on_blur is set to save, set the save funcion */
    				if(settings.on_blur == "save")
    					original_element.children("form").children(".inplace_field").blur(saveAction);
    				/* if on_blur is set to cancel, set the cancel funcion */
    				else
    					original_element.children("form").children(".inplace_field").blur(cancelAction);
                }

				/* hit esc key */
				$(document).keyup(function(event){
				    if (event.keyCode == 27) {
						cancelAction();
				    }
				});

                original_element.children("form").submit(saveAction);

			}/* END- if(click_count == 1) -END */
		});
	});
};<|endoftext|>


<commit_before>/*
	Glean.js - the final product from the ShopDown.js tests.
	proposed use.
  ----
  	var Glean 	= $("thiselement.section").Glean(),
  			link 		= Glean.get("link");
  	console.log(link);
	----
	output: http://danieltamkin.com
*/
$.fn.Glean = function(data) {
	$this = $(this);
	$data = [];
	$data.settings = datacheck(data);
	$data.html = {
		cullTo: $data.settings.cullTo,
		get: false,
		taken: null
	}
	/*data*/
	function datacheck(data){
	  return datascrub(data);
	}
	function datatemplate(){
	  return {
	    content: $this,
	    cull: true,
			cullTo: "#glean-cull"
		}
	}
	function datascrub(data){
	  template = datatemplate();
		if(data == undefined || $.isEmptyObject(data) == true){
			data = template;
		}
		else{
		  $.each(template,function(key,value){
		    $.each(data,function(bravokey,bravovalue){
		      if(bravokey == key){
		        if(bravovalue.length === -1){
		          value = value;
		        }
		        else{
		          // do nothing, bravovalue is in bravokey
		        }
		      }
		      else{
		        if(!(key in data)){// that key doesnt exist? make it.
		          data[key] = value;
		        }
		      }
		    });
		  });
		}
		return data;
	}
/*> syntax*/
	function syntaxGather(){
		$("h1, h2, h3, h4, h5, h6").addClass("glean-possible");
		var html = htmlGet();
		$('.glean-possible').each(function(i, obj) {
    	console.log(obj);
    	console.log(obj.textContent);
		});
		console.log("syntaxGather() = "+html);
	}
	function syntaxApprove(){}
/*> html*/
	/*
	 Checks to see if the get is true or not,
	 if its false then we read the html.
	*/
	function htmlGet(){
		var html = "1";
		if($data.html.get != true){
			$data.html.taken 	= $($data.settings.content).html();
			$data.html.get 		= true;
			html = $data.html.taken;
		}
		else{
			html = $data.html.taken;
		}
		return html;
	}
	function htmlSiftTo(id){
		var data = {
			h1: 'h1#'+id,
			h2: 'h2#'+id,
			h3: 'h3#'+id,
			h4: 'h4#'+id,
			h5: 'h5#'+id,
			h6: 'h6#'+id
		};
		var	content		= htmlGet(),
				SiftedTo 	= null;
		$.each(data,function(key,value){
			Sift = content.find(value);
			if(Sift.length < 1){
				// continue to find the proper value, this one doesn't exist.
			}
			else{
				SiftedTo = value;
				return false;// break out of loop
			}
		});
		return SiftedTo;
	}
	function htmlCull(){
		if($data.settings.cull != true){
			return null;// dont do anything.
		}
		else{
			syntaxGather();
			var html = htmlGet();
		}
	}
/*> app*/
	function app(){
		appCalculation();
	}
	function appCalculation(){
		htmlCull();
	}
	function appGet(){
		return $data.html;
	}
/*> objective functions / Runnables*/
	app();
	return {
	  get: function(data) {
	    return appGet(data);
	  },
		reload: function(){
			app();// just reloads the app model to get new info.
		}
	}
};
<commit_msg>syntaxApprove() and syntaxGather() worked on<commit_after>/*
	Glean.js - the final product from the ShopDown.js tests.
	proposed use.
  ----
  	var Glean 	= $("thiselement.section").Glean(),
  			link 		= Glean.get("link");
  	console.log(link);
	----
	output: http://danieltamkin.com
*/
$.fn.Glean = function(data) {
	$this = $(this);
	$data = [];
	$data.settings = datacheck(data);
	$data.html = {
		cullTo: $data.settings.cullTo,
		get: false,
		taken: null
	}
	$data.syntax = {
		opening: "!/",
		closing: "/!"
	}
/*> data*/
	function datacheck(data){
	  return datascrub(data);
	}
	function datatemplate(){
	  return {
	    content: $this,
	    cull: true,
			cullTo: "#glean-cull"
		}
	}
	function datascrub(data){
	  template = datatemplate();
		if(data == undefined || $.isEmptyObject(data) == true){
			data = template;
		}
		else{
		  $.each(template,function(key,value){
		    $.each(data,function(bravokey,bravovalue){
		      if(bravokey == key){
		        if(bravovalue.length === -1){
		          value = value;
		        }
		        else{
		          // do nothing, bravovalue is in bravokey
		        }
		      }
		      else{
		        if(!(key in data)){// that key doesnt exist? make it.
		          data[key] = value;
		        }
		      }
		    });
		  });
		}
		return data;
	}
/*> syntax*/
	function syntaxGather(){
		$("h1, h2, h3, h4, h5, h6").addClass("glean-possible");
		$('.glean-possible').each(function(i, node) {
			var approv = syntaxApprove($(this).text());
			if(approv == 100){
				console.log("syntax approved: "+ $(this).text());
				$(this).removeClass("glean-possible");
				// add to cull que
			}
			else if(approv == 206){
				// warn and remove
			}
			else{
				// remove possible class
			}
		});
		var html = htmlGet();
		console.log("syntaxGather() = "+html);
	}
	function syntaxApprove(content){
		console.log(content)
		if(content.indexOf($data.syntax.opening) == 0){
			if(content.lastIndexOf($data.syntax.closing) == content.length - $data.syntax.closing.length){
				return 100;
			}
			else{
				return 206;
			}
		}
		else{
			return 406;
		}
	}
/*> html*/
	/*
	 Checks to see if the get is true or not,
	 if its false then we read the html.
	*/
	function htmlGet(){
		var html = "1";
		if($data.html.get != true){
			$data.html.taken 	= $($data.settings.content).html();
			$data.html.get 		= true;
			html = $data.html.taken;
		}
		else{
			html = $data.html.taken;
		}
		return html;
	}
	function htmlSiftTo(id){
		var data = {
			h1: 'h1#'+id,
			h2: 'h2#'+id,
			h3: 'h3#'+id,
			h4: 'h4#'+id,
			h5: 'h5#'+id,
			h6: 'h6#'+id
		};
		var	content		= htmlGet(),
				SiftedTo 	= null;
		$.each(data,function(key,value){
			Sift = content.find(value);
			if(Sift.length < 1){
				// continue to find the proper value, this one doesn't exist.
			}
			else{
				SiftedTo = value;
				return false;// break out of loop
			}
		});
		return SiftedTo;
	}
	function htmlCull(){
		if($data.settings.cull != true){
			return null;// dont do anything.
		}
		else{
			syntaxGather();
			var html = htmlGet();
		}
	}
/*> app*/
	function app(){
		appCalculation();
	}
	function appCalculation(){
		htmlCull();
	}
	function appGet(){
		return $data.html;
	}
/*> objective functions / Runnables*/
	app();
	return {
	  get: function(data) {
	    return appGet(data);
	  },
		reload: function(){
			app();// just reloads the app model to get new info.
		}
	}
};
<|endoftext|>


<commit_before>define(function (require, exports, module) {
  'use strict';

  var L20n = require('../../l20n').L20n;
  var Promise = require('../promise').Promise;
  var IO = require('./html/io').IO;
  var Intl = require('../intl').Intl;

  var ctx = L20n.getContext(document.location.host);

  function bootstrap() {
    var headNode = document.head;
    var data = headNode.querySelector('script[type="application/l10n-data+json"]');

    if (data) {
      ctx.data = JSON.parse(data.textContent);
    }

    var scripts = headNode.querySelectorAll('script[type="application/l20n"]');
    if (scripts.length) {
      for (var i = 0; i < scripts.length; i++) {
        if (scripts[i].hasAttribute('src')) {
          ctx.linkResource(scripts[i].getAttribute('src'));
        } else {
          ctx.addResource(scripts[i].textContent);
        }
      }
      initializeDocumentContext();
    } else {
      var link = headNode.querySelector('link[rel="localization"]');
      if (link) {
        loadManifest(link.getAttribute('href')).then(
          initializeDocumentContext
        );
      } else {
        console.log("L20n error: You're using l20n without any resources! Please, link them above l20n.js");
      }
    }
    return true;
  }

  bootstrap();

  function initializeDocumentContext() {
    localizeDocument();

    ctx.addEventListener('ready', function() {
      var event = document.createEvent('Event');
      event.initEvent('LocalizationReady', false, false);
      document.dispatchEvent(event);
    });

    ctx.addEventListener('error', function(e) {
      // XXX should we even emit this?
      if (false) {
        var event = document.createEvent('Event');
        event.initEvent('LocalizationFailed', false, false);
        document.dispatchEvent(event);
      }
    });

    ctx.freeze();
  }

  function loadManifest(url) {
    var deferred = new Promise();
    IO.load(url, true).then(
      function(text) {
        var manifest = JSON.parse(text);
        var langList = Intl.prioritizeLocales(manifest.languages);
        ctx.registerLocales.apply(this, langList);
        ctx.linkResource(function(lang) {
          return manifest.resources[0].replace("{{lang}}", lang);
        });
        deferred.fulfill();
      }
    );
    return deferred;
  }

  function fireLocalizedEvent() {
    var event = document.createEvent('Event');
    event.initEvent('DocumentLocalized', false, false);
    document.dispatchEvent(event);
  }

  function onDocumentBodyReady() {
    if (document.readyState === 'interactive') {
      localizeNode(document);
      fireLocalizedEvent();
      document.removeEventListener('readystatechange', onDocumentBodyReady);
    }
  }

  function localizeDocument() {
    if (document.body) {
      localizeNode(document);
      fireLocalizedEvent();
    } else {
      document.addEventListener('readystatechange', onDocumentBodyReady);
    }
    HTMLDocument.prototype.__defineGetter__('l10n', function() {
      return ctx;
    });
  }

  function retranslate(node, l10n) {
    var nodes = node.querySelectorAll('[data-l10n-id]');
    var entity;
    for (var i = 0; i < nodes.length; i++) {
      var id = nodes[i].getAttribute('data-l10n-id');
      var entity = l10n.entities[id];
      var node = nodes[i];
      if (entity.value) {
        node.textContent = entity.value;
      }
      for (var key in entity.attributes) {
        node.setAttribute(key, entity.attributes[key]);
      }
    }
    // readd data-l10n-attrs
    // readd data-l10n-overlay
    // secure attribute access
  }

  function localizeNode(node) {
    var nodes = node.querySelectorAll('[data-l10n-id]');
    var ids = [];
    for (var i = 0; i < nodes.length; i++) {
      if (nodes[i].hasAttribute('data-l10n-args')) {
        ids.push([nodes[i].getAttribute('data-l10n-id'),
                  JSON.parse(nodes[i].getAttribute('data-l10n-args'))]);
      } else {
        ids.push(nodes[i].getAttribute('data-l10n-id'));
      }
    }
    ctx.localize(ids, retranslate.bind(this, node));
  }

  exports.L20n = L20n;

});
<commit_msg>keep var outside of loops<commit_after>define(function (require, exports, module) {
  'use strict';

  var L20n = require('../../l20n').L20n;
  var Promise = require('../promise').Promise;
  var IO = require('./html/io').IO;
  var Intl = require('../intl').Intl;

  var ctx = L20n.getContext(document.location.host);

  function bootstrap() {
    var headNode = document.head;
    var data = headNode.querySelector('script[type="application/l10n-data+json"]');

    if (data) {
      ctx.data = JSON.parse(data.textContent);
    }

    var scripts = headNode.querySelectorAll('script[type="application/l20n"]');
    if (scripts.length) {
      for (var i = 0; i < scripts.length; i++) {
        if (scripts[i].hasAttribute('src')) {
          ctx.linkResource(scripts[i].getAttribute('src'));
        } else {
          ctx.addResource(scripts[i].textContent);
        }
      }
      initializeDocumentContext();
    } else {
      var link = headNode.querySelector('link[rel="localization"]');
      if (link) {
        loadManifest(link.getAttribute('href')).then(
          initializeDocumentContext
        );
      } else {
        console.log("L20n error: You're using l20n without any resources! Please, link them above l20n.js");
      }
    }
    return true;
  }

  bootstrap();

  function initializeDocumentContext() {
    localizeDocument();

    ctx.addEventListener('ready', function() {
      var event = document.createEvent('Event');
      event.initEvent('LocalizationReady', false, false);
      document.dispatchEvent(event);
    });

    ctx.addEventListener('error', function(e) {
      // XXX should we even emit this?
      if (false) {
        var event = document.createEvent('Event');
        event.initEvent('LocalizationFailed', false, false);
        document.dispatchEvent(event);
      }
    });

    ctx.freeze();
  }

  function loadManifest(url) {
    var deferred = new Promise();
    IO.load(url, true).then(
      function(text) {
        var manifest = JSON.parse(text);
        var langList = Intl.prioritizeLocales(manifest.languages);
        ctx.registerLocales.apply(this, langList);
        ctx.linkResource(function(lang) {
          return manifest.resources[0].replace("{{lang}}", lang);
        });
        deferred.fulfill();
      }
    );
    return deferred;
  }

  function fireLocalizedEvent() {
    var event = document.createEvent('Event');
    event.initEvent('DocumentLocalized', false, false);
    document.dispatchEvent(event);
  }

  function onDocumentBodyReady() {
    if (document.readyState === 'interactive') {
      localizeNode(document);
      fireLocalizedEvent();
      document.removeEventListener('readystatechange', onDocumentBodyReady);
    }
  }

  function localizeDocument() {
    if (document.body) {
      localizeNode(document);
      fireLocalizedEvent();
    } else {
      document.addEventListener('readystatechange', onDocumentBodyReady);
    }
    HTMLDocument.prototype.__defineGetter__('l10n', function() {
      return ctx;
    });
  }

  function retranslate(node, l10n) {
    var nodes = node.querySelectorAll('[data-l10n-id]');
    var entity, id, entity, node, i, key;

    for (i = 0; i < nodes.length; i++) {
      id = nodes[i].getAttribute('data-l10n-id');
      entity = l10n.entities[id];
      node = nodes[i];
      if (entity.value) {
        node.textContent = entity.value;
      }
      for (key in entity.attributes) {
        node.setAttribute(key, entity.attributes[key]);
      }
    }
    // readd data-l10n-attrs
    // readd data-l10n-overlay
    // secure attribute access
  }

  function localizeNode(node) {
    var nodes = node.querySelectorAll('[data-l10n-id]');
    var ids = [];
    for (var i = 0; i < nodes.length; i++) {
      if (nodes[i].hasAttribute('data-l10n-args')) {
        ids.push([nodes[i].getAttribute('data-l10n-id'),
                  JSON.parse(nodes[i].getAttribute('data-l10n-args'))]);
      } else {
        ids.push(nodes[i].getAttribute('data-l10n-id'));
      }
    }
    ctx.localize(ids, retranslate.bind(this, node));
  }

  exports.L20n = L20n;

});
<|endoftext|>