<commit_before>;(function(){
  var getLanguageKey = require('./no-global/get-language-key');
  var w, d;

  w = window;

  d = document;

  w.optly = w.optly || {};

  w.optly.mrkt = w.optly.mrkt || {};

  w.optly.mrkt.Oform = {};

  w.optly.mrkt.Oform.before = function(){

    d.getElementsByTagName('body')[0].classList.add('oform-processing');

    return true;

  };

  w.optly.mrkt.Oform.defaultMiddleware = function(XHR, data){
    //`this` is the oForm instance
    var isCreateAccount = /\/account\/create/.test( $(this.selector).attr('action') );
    if(isCreateAccount) {
      data += getLanguageKey();
    }
    XHR.withCredentials = true;
    return data;

  };

  w.optly.mrkt.Oform.validationError = function(element){

    w.optly.mrkt.formHadError = true;

    var elementValue = $(element).val();

    var elementHasValue = elementValue ? 'has value' : 'no value';

    w.analytics.track($(element).closest('form').attr('id') + ' ' + element.getAttribute('name') + ' error submit', {

      category: 'form error',

      label: elementHasValue,

      value: elementValue.length

    }, {

      integrations: {

        Marketo: false

      }

    });

  };

  w.optly.mrkt.Oform.done = function(){

    d.getElementsByTagName('body')[0].classList.remove('processing');

  };

  w.optly.mrkt.Oform.trackLead = function(args) {
    /*

      REPORTS NEW LEADS TO VARIOUS TRACKING PLATFORMS

        Accepts one argument (object) that should contains two properties:

          - response (object - optional): The parsed response from the parseResponse function
          - requestPayload (object): the form fields and their values

    */

    var reportingObject,
        source,
        payload = args.requestPayload,
        response = args.response || {};

    source = w.optly.mrkt.source;

    //start the reporting object with the required parameters
    reportingObject = {
      leadSource: 'Website'
    };

    //add only the values we have to the reporting object
    if(response.email){
      reportingObject.email = response.email;
    } else if(payload.email){
      reportingObject.email = payload.email;
    }
    if(response.first_name){
      reportingObject.firstName = response.first_name;
    } else if(payload.first_name){
      reportingObject.firstName = payload.first_name;
    }
    if(response.last_name){
      reportingObject.lastName = response.last_name;
    } else if(payload.last_name) {
      reportingObject.lastName = payload.last_name;
    }
    if(response.phone_number){
      reportingObject.phone = response.phone_number;
    } else if(payload.phone_number){
      reportingObject.phone = payload.phone_number;
    }
    if(payload.company){
      reportingObject.company = payload.company;
    }
    if(payload.title){
      reportingObject.title = payload.title;
    }
    if (payload.role){
      reportingObject.role = payload.role;
    }
    if(payload.website){
      reportingObject.website = payload.website;
    }
    if(payload.Tech_Partner_goal_for_partnership__c){
      reportingObject.Tech_Partner_goal_for_partnership__c = payload.Tech_Partner_goal_for_partnership__c;
    }
    if(payload.Tech_Partner_Number_of_Customers__c){
      reportingObject.Tech_Partner_Number_of_Customers__c = payload.Tech_Partner_Number_of_Customers__c;
    }
    //-- Waiting until we fix radio button integration in oform to activate this:
    // if(payload.Tech_Partner_Want_to_Build_Integration){
    //   reportingObject.Tech_Partner_Want_to_Build_Integration__c = payload.Tech_Partner_Want_to_Build_Integration;
    // }
    //-- Concatting checkbox values to report to Marketo for Tech partners target industry
    if(payload.Retail_ecommerce_target__c || payload.Travel_target__c || payload.Media_target__c || payload.B2B_Technology_target__c || payload.Other_target__c){
      reportingObject.Tech_Partner_Target_Customer__c = reportingObject.Tech_Partner_Target_Customer__c || '';
      if(payload.Retail_ecommerce_target__c){
        reportingObject.Tech_Partner_Target_Customer__c += ' Retail/E-commerce,';
      }
      if(payload.Travel_target__c){
        reportingObject.Tech_Partner_Target_Customer__c += ' Travel,';
      }
      if(payload.Media_target__c){
        reportingObject.Tech_Partner_Target_Customer__c += ' Media,';
      }
      if(payload.B2B_Technology_target__c){
        reportingObject.Tech_Partner_Target_Customer__c += ' B2B/Technology,';
      }
      if(payload.Other_target__c){
        reportingObject.Tech_Partner_Target_Customer__c += ' Other Vertical,';
      }
    }
    //--
    if(payload.Tech_Partner_Primary_Buyer__c){
      reportingObject.Tech_Partner_Primary_Buyer__c = payload.Tech_Partner_Primary_Buyer__c;
    }
    if(payload.Tech_Partner_Percent_Shared_Customers__c){
      reportingObject.Tech_Partner_Percent_Shared_Customers__c = payload.Tech_Partner_Percent_Shared_Customers__c;
    }
    if(payload.Web_Interest__c){
      reportingObject.Web_Interest__c = 'true';
    }
    if(payload.Mobile_Web_Interest__c){
      reportingObject.Mobile_Web_Interest__c = 'true';
    }
    if(payload.iOS_Interest__c){
      reportingObject.iOS_Interest__c = 'true';
    }
    if(payload.Android_Interest__c){
      reportingObject.Android_Interest__c = 'true';
    }
    if(payload.leadSource){
      reportingObject.leadSource = payload.leadSource;
    }
    if(payload.Initial_Form_Source__c){
      reportingObject.Initial_Form_Source__c = payload.Initial_Form_Source__c;
    }
    if(payload.Inbound_Lead_Form_Type__c){
      reportingObject.Inbound_Lead_Form_Type__c = payload.Inbound_Lead_Form_Type__c;
    }
    if(payload.LeadSource_Category__c){
      reportingObject.LeadSource_Category__c = payload.LeadSource_Category__c;
    }
    if(payload.Lead_Source_Category__c){
      reportingObject.Lead_Scource_Category__c = payload.Lead_Source_Category__c;
    }
    //Bradley: underscore was forgotten in oform globals, this captures all possible form fields
    if(payload.LeadSource_Category__c){
      reportingObject.Lead_Scource_Category__c = payload.LeadSource_Category__c;
    }
    if(payload.Lead_Source_Subcategory__c){
      reportingObject.Lead_Source_Subcategory__c = payload.Lead_Source_Subcategory__c;
    }
    if(payload.Existing_customers_using_Optimizely__c){
      reportingObject.Existing_customers_using_Optimizely__c = payload.Existing_customers_using_Optimizely__c;
    }
    //add source information
    //source is usually url query params from ads
    if(source.utm.campaign){
      reportingObject.utm_Campaign__c = source.utm.campaign;
    }
    if(source.utm.content){
      reportingObject.utm_Content__c = source.utm.content;
    }
    if(source.utm.medium){
      reportingObject.utm_Medium__c = source.utm.medium;
    }
    if(source.utm.source){
      reportingObject.utm_Source__c = source.utm.source;
    }
    if(source.utm.keyword){
      reportingObject.utm_Keyword__c = source.utm.keyword;
    }
    if(source.otm.campaign){
      reportingObject.otm_Campaign__c = source.otm.campaign;
    }
    if(source.otm.content){
      reportingObject.otm_Content__c = source.otm.content;
    }
    if(source.otm.medium){
      reportingObject.otm_Medium__c = source.otm.medium;
    }
    if(source.otm.source){
      reportingObject.otm_Source__c = source.otm.source;
    }
    if(source.otm.keyword){
      reportingObject.otm_Keyword__c = source.otm.keyword;
    }
    if(source.gclid){
      reportingObject.GCLID__c = source.gclid;
    }
    if(payload.Signup_Platform__c){
      reportingObject.Signup_Platform__c = payload.Signup_Platform__c;
    }
    if(payload.address){
      reportingObject.address = payload.address;
    }
    if(payload.city){
      reportingObject.City = payload.city;
    }
    if(payload.state){
      reportingObject.State = payload.state;
    }
    if(payload.country){
      reportingObject.Country = payload.country;
    }
    if(payload.Slns_Partner_goal_for_partnership__c){
      reportingObject.Slns_Partner_goal_for_partnership__c = payload.Slns_Partner_goal_for_partnership__c;
    }
    if(payload.company_type){
      reportingObject.Slns_Partner_Company_Type__c = payload.company_type;
    }
    if(payload.has_immediate_project__c){
      reportingObject.has_immediate_project__c = payload.has_immediate_project__c;
    }
    if(payload.Existing_customers_using_Optimizely__c){
      reportingObject.Existing_customers_using_Optimizely__c = payload.Existing_customers_using_Optimizely__c;
    }
    if(payload.parent_company){
      reportingObject.Slns_Partner_Subsidiary_Parent_Company__c = payload.parent_company;
    }
    if(payload.zip){
      reportingObject.PostalCode = payload.zip;
    }
    if(window.optly.l10n && window.optly.l10n.locale) {
      reportingObject.Original_Locale__c = window.optly.l10n.locale;
    }

    //set the source cookie so that the next page know where the visitor
    //came from
    $.cookie('sourceCookie',
      source.utm.campaign + '|||' +
      source.utm.content + '|||' +
      source.utm.medium + '|||' +
      source.utm.source + '|||' +
      source.utm.keyword + '|||' +
      source.otm.campaign + '|||' +
      source.otm.content + '|||' +
      source.otm.medium + '|||' +
      source.otm.source + '|||' +
      source.otm.keyword + '|||' +
      source.signup_platform + '|||'
    );

    var anonymousVisitorIdentifier = window.optly.mrkt.utils.randomString();

    w.analytics.identify(response.unique_user_id || anonymousVisitorIdentifier, reportingObject, {
      integrations: {
        Marketo: true
      }
    });

    if(w.optly.mrkt.automatedTest){
      $('body').attr('data-reporting-object', JSON.stringify(reportingObject));
    }

    /* legacy reporting - to be deprecated */

    w.analytics.track('/account/create/success', {
      category: 'account',
      label: w.optly.mrkt.utils.trimTrailingSlash(w.location.pathname)
    });

    w.analytics.track('/account/signin', {
      category: 'account',
      label: w.optly.mrkt.utils.trimTrailingSlash(w.location.pathname)
    }, {
      integrations: {
        'Marketo': false
      }
    });

    w.analytics.track('/event/plan/null', {}, {
      integrations: {
        'All': false,
        'Marketo': true
      }
    });

    var reportingPlan;

    if(typeof(response.plan) == 'string'){
      reportingPlan = response.plan;
    } else {
      reportingPlan = 'null';
    }

    w.analytics.track('/event/plan' + reportingPlan, {}, {
      integrations: {
        'All': false,
        'Marketo': true
      }
    });
    w.analytics.page('/plan/' + response.plan);

    /* new reporting */

    w.analytics.track('account created', {
      category: 'account',
      label: window.optly.mrkt.utils.trimTrailingSlash(w.location.pathname)
    }, {
      integrations: {
        'Marketo': false
      }
    });

    w.analytics.track('account signin', {
      category: 'account',
      label: window.optly.mrkt.utils.trimTrailingSlash(w.location.pathname)
    }, {
      integrations: {
        'Marketo': false
      }
    });

  };

  w.optly.mrkt.Oform.initContactForm = function(arg){

    new Oform({
      selector: arg.selector,
      middleware: w.optly.mrkt.Oform.defaultMiddleware
    })
    .on('validationerror', w.optly.mrkt.Oform.validationError)
    .on('load', function(event){
      if(event.XHR.status === 200){
        //identify user
        $('body').addClass('oform-success');
        var response = JSON.parse(event.XHR.responseText),
            email = d.querySelector('[name="email"]').value,
            traffic = d.querySelector('#traffic');
        w.analytics.identify(response.unique_user_id, {
          name: d.querySelector('[name="name"]').value,
          email: email,
          Email: email,
          phone: d.querySelector('[name="phone"]').value || '',
          company: d.querySelector('[name="company"]').value || '',
          website: d.querySelector('[name="website"]').value || '',
          utm_Medium__c: w.optly.mrkt.source.utm.medium,
          otm_Medium__c: w.optly.mrkt.source.otm.medium,
          Demo_Request_Monthly_Traffic__c: traffic.options[traffic.selectedIndex].value || '',
          Inbound_Lead_Form_Type__c: d.querySelector('[name="Inbound_Lead_Form_Type__c"]').value || '',
          token: response.token
        }, {
          integrations: {
            Marketo: true
          }
        });
        //track the event
        w.analytics.track('demo requested', {
          category: 'contact form',
          label: w.optly.mrkt.utils.trimTrailingSlash(w.location.pathname)
        }, {
          integrations: {
            Marketo: true
          }
        });
      }
    });

  };

})();
<commit_msg>fix partners reason for contact<commit_after>;(function(){
  var getLanguageKey = require('./no-global/get-language-key');
  var w, d;

  w = window;

  d = document;

  w.optly = w.optly || {};

  w.optly.mrkt = w.optly.mrkt || {};

  w.optly.mrkt.Oform = {};

  w.optly.mrkt.Oform.before = function(){

    d.getElementsByTagName('body')[0].classList.add('oform-processing');

    return true;

  };

  w.optly.mrkt.Oform.defaultMiddleware = function(XHR, data){
    //`this` is the oForm instance
    var isCreateAccount = /\/account\/create/.test( $(this.selector).attr('action') );
    if(isCreateAccount) {
      data += getLanguageKey();
    }
    XHR.withCredentials = true;
    return data;

  };

  w.optly.mrkt.Oform.validationError = function(element){

    w.optly.mrkt.formHadError = true;

    var elementValue = $(element).val();

    var elementHasValue = elementValue ? 'has value' : 'no value';

    w.analytics.track($(element).closest('form').attr('id') + ' ' + element.getAttribute('name') + ' error submit', {

      category: 'form error',

      label: elementHasValue,

      value: elementValue.length

    }, {

      integrations: {

        Marketo: false

      }

    });

  };

  w.optly.mrkt.Oform.done = function(){

    d.getElementsByTagName('body')[0].classList.remove('processing');

  };

  w.optly.mrkt.Oform.trackLead = function(args) {
    /*

      REPORTS NEW LEADS TO VARIOUS TRACKING PLATFORMS

        Accepts one argument (object) that should contains two properties:

          - response (object - optional): The parsed response from the parseResponse function
          - requestPayload (object): the form fields and their values

    */

    var reportingObject,
        source,
        payload = args.requestPayload,
        response = args.response || {};

    source = w.optly.mrkt.source;

    //start the reporting object with the required parameters
    reportingObject = {
      leadSource: 'Website'
    };

    //add only the values we have to the reporting object
    if(response.email){
      reportingObject.email = response.email;
    } else if(payload.email){
      reportingObject.email = payload.email;
    }
    if(response.first_name){
      reportingObject.firstName = response.first_name;
    } else if(payload.first_name){
      reportingObject.firstName = payload.first_name;
    }
    if(response.last_name){
      reportingObject.lastName = response.last_name;
    } else if(payload.last_name) {
      reportingObject.lastName = payload.last_name;
    }
    if(response.phone_number){
      reportingObject.phone = response.phone_number;
    } else if(payload.phone_number){
      reportingObject.phone = payload.phone_number;
    }
    if(payload.company){
      reportingObject.company = payload.company;
    }
    if(payload.title){
      reportingObject.title = payload.title;
    }
    if (payload.role){
      reportingObject.role = payload.role;
    }
    if(payload.website){
      reportingObject.website = payload.website;
    }
    if(payload.Tech_Partner_goal_for_partnership__c){
      reportingObject.Tech_Partner_goal_for_partnership__c = payload.Tech_Partner_goal_for_partnership__c;
    }
    if(payload.Tech_Partner_Number_of_Customers__c){
      reportingObject.Tech_Partner_Number_of_Customers__c = payload.Tech_Partner_Number_of_Customers__c;
    }
    //-- Waiting until we fix radio button integration in oform to activate this:
    // if(payload.Tech_Partner_Want_to_Build_Integration){
    //   reportingObject.Tech_Partner_Want_to_Build_Integration__c = payload.Tech_Partner_Want_to_Build_Integration;
    // }
    //-- Concatting checkbox values to report to Marketo for Tech partners target industry
    if(payload.Retail_ecommerce_target__c || payload.Travel_target__c || payload.Media_target__c || payload.B2B_Technology_target__c || payload.Other_target__c){
      reportingObject.Tech_Partner_Target_Customer__c = reportingObject.Tech_Partner_Target_Customer__c || '';
      if(payload.Retail_ecommerce_target__c){
        reportingObject.Tech_Partner_Target_Customer__c += ' Retail/E-commerce,';
      }
      if(payload.Travel_target__c){
        reportingObject.Tech_Partner_Target_Customer__c += ' Travel,';
      }
      if(payload.Media_target__c){
        reportingObject.Tech_Partner_Target_Customer__c += ' Media,';
      }
      if(payload.B2B_Technology_target__c){
        reportingObject.Tech_Partner_Target_Customer__c += ' B2B/Technology,';
      }
      if(payload.Other_target__c){
        reportingObject.Tech_Partner_Target_Customer__c += ' Other Vertical,';
      }
    }
    //--
    if(payload.Tech_Partner_Primary_Buyer__c){
      reportingObject.Tech_Partner_Primary_Buyer__c = payload.Tech_Partner_Primary_Buyer__c;
    }
    if(payload.Tech_Partner_Percent_Shared_Customers__c){
      reportingObject.Tech_Partner_Percent_Shared_Customers__c = payload.Tech_Partner_Percent_Shared_Customers__c;
    }
    if(payload.Web_Interest__c){
      reportingObject.Web_Interest__c = 'true';
    }
    if(payload.Mobile_Web_Interest__c){
      reportingObject.Mobile_Web_Interest__c = 'true';
    }
    if(payload.iOS_Interest__c){
      reportingObject.iOS_Interest__c = 'true';
    }
    if(payload.Android_Interest__c){
      reportingObject.Android_Interest__c = 'true';
    }
    if(payload.leadSource){
      reportingObject.leadSource = payload.leadSource;
    }
    if(payload.Initial_Form_Source__c){
      reportingObject.Initial_Form_Source__c = payload.Initial_Form_Source__c;
    }
    if(payload.Inbound_Lead_Form_Type__c){
      reportingObject.Inbound_Lead_Form_Type__c = payload.Inbound_Lead_Form_Type__c;
    }
    if(payload.LeadSource_Category__c){
      reportingObject.LeadSource_Category__c = payload.LeadSource_Category__c;
    }
    if(payload.Lead_Source_Category__c){
      reportingObject.Lead_Scource_Category__c = payload.Lead_Source_Category__c;
    }
    //Bradley: underscore was forgotten in oform globals, this captures all possible form fields
    if(payload.LeadSource_Category__c){
      reportingObject.Lead_Scource_Category__c = payload.LeadSource_Category__c;
    }
    if(payload.Lead_Source_Subcategory__c){
      reportingObject.Lead_Source_Subcategory__c = payload.Lead_Source_Subcategory__c;
    }
    if(payload.Existing_customers_using_Optimizely__c){
      reportingObject.Existing_customers_using_Optimizely__c = payload.Existing_customers_using_Optimizely__c;
    }
    //add source information
    //source is usually url query params from ads
    if(source.utm.campaign){
      reportingObject.utm_Campaign__c = source.utm.campaign;
    }
    if(source.utm.content){
      reportingObject.utm_Content__c = source.utm.content;
    }
    if(source.utm.medium){
      reportingObject.utm_Medium__c = source.utm.medium;
    }
    if(source.utm.source){
      reportingObject.utm_Source__c = source.utm.source;
    }
    if(source.utm.keyword){
      reportingObject.utm_Keyword__c = source.utm.keyword;
    }
    if(source.otm.campaign){
      reportingObject.otm_Campaign__c = source.otm.campaign;
    }
    if(source.otm.content){
      reportingObject.otm_Content__c = source.otm.content;
    }
    if(source.otm.medium){
      reportingObject.otm_Medium__c = source.otm.medium;
    }
    if(source.otm.source){
      reportingObject.otm_Source__c = source.otm.source;
    }
    if(source.otm.keyword){
      reportingObject.otm_Keyword__c = source.otm.keyword;
    }
    if(source.gclid){
      reportingObject.GCLID__c = source.gclid;
    }
    if(payload.Signup_Platform__c){
      reportingObject.Signup_Platform__c = payload.Signup_Platform__c;
    }
    if(payload.address){
      reportingObject.address = payload.address;
    }
    if(payload.city){
      reportingObject.City = payload.city;
    }
    if(payload.state){
      reportingObject.State = payload.state;
    }
    if(payload.country){
      reportingObject.Country = payload.country;
    }
    if(payload.Slns_Partner_goal_for_partnership__c){
      reportingObject.Slns_Partner_Partnership_Goal__c = payload.Slns_Partner_goal_for_partnership__c;
    }
    if(payload.company_type){
      reportingObject.Slns_Partner_Company_Type__c = payload.company_type;
    }
    if(payload.has_immediate_project__c){
      reportingObject.has_immediate_project__c = payload.has_immediate_project__c;
    }
    if(payload.Existing_customers_using_Optimizely__c){
      reportingObject.Existing_customers_using_Optimizely__c = payload.Existing_customers_using_Optimizely__c;
    }
    if(payload.parent_company){
      reportingObject.Slns_Partner_Subsidiary_Parent_Company__c = payload.parent_company;
    }
    if(payload.zip){
      reportingObject.PostalCode = payload.zip;
    }
    if(window.optly.l10n && window.optly.l10n.locale) {
      reportingObject.Original_Locale__c = window.optly.l10n.locale;
    }

    //set the source cookie so that the next page know where the visitor
    //came from
    $.cookie('sourceCookie',
      source.utm.campaign + '|||' +
      source.utm.content + '|||' +
      source.utm.medium + '|||' +
      source.utm.source + '|||' +
      source.utm.keyword + '|||' +
      source.otm.campaign + '|||' +
      source.otm.content + '|||' +
      source.otm.medium + '|||' +
      source.otm.source + '|||' +
      source.otm.keyword + '|||' +
      source.signup_platform + '|||'
    );

    var anonymousVisitorIdentifier = window.optly.mrkt.utils.randomString();

    w.analytics.identify(response.unique_user_id || anonymousVisitorIdentifier, reportingObject, {
      integrations: {
        Marketo: true
      }
    });

    if(w.optly.mrkt.automatedTest){
      $('body').attr('data-reporting-object', JSON.stringify(reportingObject));
    }

    /* legacy reporting - to be deprecated */

    w.analytics.track('/account/create/success', {
      category: 'account',
      label: w.optly.mrkt.utils.trimTrailingSlash(w.location.pathname)
    });

    w.analytics.track('/account/signin', {
      category: 'account',
      label: w.optly.mrkt.utils.trimTrailingSlash(w.location.pathname)
    }, {
      integrations: {
        'Marketo': false
      }
    });

    w.analytics.track('/event/plan/null', {}, {
      integrations: {
        'All': false,
        'Marketo': true
      }
    });

    var reportingPlan;

    if(typeof(response.plan) == 'string'){
      reportingPlan = response.plan;
    } else {
      reportingPlan = 'null';
    }

    w.analytics.track('/event/plan' + reportingPlan, {}, {
      integrations: {
        'All': false,
        'Marketo': true
      }
    });
    w.analytics.page('/plan/' + response.plan);

    /* new reporting */

    w.analytics.track('account created', {
      category: 'account',
      label: window.optly.mrkt.utils.trimTrailingSlash(w.location.pathname)
    }, {
      integrations: {
        'Marketo': false
      }
    });

    w.analytics.track('account signin', {
      category: 'account',
      label: window.optly.mrkt.utils.trimTrailingSlash(w.location.pathname)
    }, {
      integrations: {
        'Marketo': false
      }
    });

  };

  w.optly.mrkt.Oform.initContactForm = function(arg){

    new Oform({
      selector: arg.selector,
      middleware: w.optly.mrkt.Oform.defaultMiddleware
    })
    .on('validationerror', w.optly.mrkt.Oform.validationError)
    .on('load', function(event){
      if(event.XHR.status === 200){
        //identify user
        $('body').addClass('oform-success');
        var response = JSON.parse(event.XHR.responseText),
            email = d.querySelector('[name="email"]').value,
            traffic = d.querySelector('#traffic');
        w.analytics.identify(response.unique_user_id, {
          name: d.querySelector('[name="name"]').value,
          email: email,
          Email: email,
          phone: d.querySelector('[name="phone"]').value || '',
          company: d.querySelector('[name="company"]').value || '',
          website: d.querySelector('[name="website"]').value || '',
          utm_Medium__c: w.optly.mrkt.source.utm.medium,
          otm_Medium__c: w.optly.mrkt.source.otm.medium,
          Demo_Request_Monthly_Traffic__c: traffic.options[traffic.selectedIndex].value || '',
          Inbound_Lead_Form_Type__c: d.querySelector('[name="Inbound_Lead_Form_Type__c"]').value || '',
          token: response.token
        }, {
          integrations: {
            Marketo: true
          }
        });
        //track the event
        w.analytics.track('demo requested', {
          category: 'contact form',
          label: w.optly.mrkt.utils.trimTrailingSlash(w.location.pathname)
        }, {
          integrations: {
            Marketo: true
          }
        });
      }
    });

  };

})();
<|endoftext|>


<commit_before>function ComponentCkeditor( id ) {
	var self = new ComponentTextfield(id);

	self.setDefaultState('text-value');
	self.setState('text-value', '');

	self.editor = CKEDITOR.instances[id];
	self.editorIsReady = false;
	self.editorToolbar = 'OneRow';
	self.haveUnsetData = false;

	self.config = {
		skin: 'kama',
		enterMode: CKEDITOR.ENTER_BR,
		shiftEnterMode: CKEDITOR.ENTER_P,
		disableNativeSpellChecker: false,
		browserContextMenuOnCtrl: true,
		colorButton_enableMore: false,
		resize_dir: 'both',
		/*resize_enabled: true,*/
		fontSize_sizes:
			'8/8pt;' +
			'9/9pt;' +
			'10/10pt;' +
			'11/11pt;' +
			'12/12pt;' +
			'14/14pt;' +
			'16/16pt;' +
			'18/18pt;' +
			'20/20pt;' +
			'22/22pt;' +
			'24/24pt;' +
			'26/26pt;' +
			'28/28pt;' +
			'36/36pt;' +
			'48/48pt',
		font_names:
			'Arial/Arial, Helvetica, sans-serif;' +
			'Arial black;' +
			'Calibri/Calibri, sans-serif;' +
			'Comic Sans MS/Comic Sans MS, cursive;' +
			'Courier New/Courier New, Courier, monospace;' +
			'Georgia/Georgia, serif;' +
			'Lucida Console/Lucida Console, monospace;' +
			'Lucida Sans Unicode/Lucida Sans Unicode, Lucida Grande, sans-serif;' +
			'Tahoma/Tahoma, Geneva, sans-serif;' +
			'Times New Roman/Times New Roman, Times, serif;' +
			'Trebuchet MS/Trebuchet MS, Helvetica, sans-serif;' +
			'Verdana/Verdana, Geneva, sans-serif',
		toolbar_Empty: [],
		toolbar_SingleRow: [
			[ 'SpellCheckerLanguage' ],
			[ 'SpellChecker' ]
		],
		toolbar_OneRow: [
			[ 'Bold', 'Italic', 'Underline', 'Strike' ],
			[ 'NumberedList', 'BulletedList' ],
			[ 'Indent', 'Outdent', 'Blockquote' ],
			[ 'JustifyLeft', 'JustifyCenter', 'JustifyRight' ],
			[ 'Link', 'Image', 'Youtube', 'HorizontalRule' ], [ 'PasteFromWord' ],
			[ 'Font' ], [ 'FontSize' ],
			[ 'TextColor', 'BGColor' ],
			[ 'SpellCheckerLanguage' ], [ 'SpellChecker' ], [ 'Resize' ]
		],
		toolbar_TwoRow: [
			[ 'Bold', 'Italic', 'Underline', 'Strike' ],
			[ 'NumberedList', 'BulletedList' ],
			[ 'Indent', 'Outdent', 'Blockquote' ],
			[ 'JustifyLeft', 'JustifyCenter', 'JustifyRight' ], [ 'PasteFromWord' ],
			[ 'Link', 'Image', 'Youtube', 'HorizontalRule' ],
			[ 'Font' ], [ 'FontSize' ],'/',
			[ 'TextColor', 'BGColor' ],
			[ 'SpellCheckerLanguage' ], [ 'SpellChecker' ], ['Resize']
		],
		toolbar: 'OneRow',
		plugins:
			'basicstyles,' +
			'blockquote,' +
			'clipboard,' +
			'colorbutton,' +
			'contextmenu,' +
			'enterkey,' +
			'font,' +
			'horizontalrule,' +
			'htmlwriter,' +
			'indent,' +
			'justify,' +
			'link,' +
			'list,' +
			'magicline,' +
			'pastetext,' +
			/* 'removeformat,' + */
			'showborders,' +
			'tab,' +
			/*'table,' + */
			/*'tabletools,' + */
			'toolbar,' +
			'undo,' +
			'wysiwygarea,' +
			'cention_spellcheck,' +
			'cention_image,' +
			'pastefromword,' +
			'resize,' +
			'youtube',
		contentsCss: [
			WFServerURI + 'Resources/CSS/jquery.spellchecker.css',
			WFServerURI + 'Resources/Javascript/ckeditor/contents.css',
			WFServerURI + 'Support/Components/Ckeditor/Ckeditor.css',
		],
		spellCheckLanguages: []
	};

	self.setLanguage = function( language ) {
		self.config.language = language;
	}

	self.setFontSize = function( size ){
		if( size ){
			self.config.fontSize_defaultLabel = '' + size;
			CKEDITOR.addCss('.cke_editable { font-size: '+ size +'; }');
		}
	};

	self.setFontFamily = function( family ){
		if( family ){
			self.config.font_defaultLabel = '' + family;
			CKEDITOR.addCss('.cke_editable { font-family: '+ family +'; }');
		}
	}

	self.setLanguages = function( list ) {
	    self.config.spellCheckLanguages = list;
	};
	self.setImages = function( list ) {
		if( self.editor ) {
			self.editor.___fileArchiveImages = list;
		}
	};
	self.setShowResize = function( resize ) {
		if( resize == true ) {
			self.config.resize_enabled = true;
		} else {
			self.config.resize_enabled = false;
		}
	};
	self.setItemHeight = function( height ){
		self.config.height = height;
	};
	self.showBasicToolbar = function() { };
	self.showAdvancedToolbar = function() { };
	self.setTwoRowToolbar = function( value ) {
		if( value ) {
			self.editorToolbar = 'TwoRow';
			self.config.toolbar = self.editorToolbar;
		}
	};
	self.setShowToolbar = function( value ) {
		if( !value ) {
			self.editorToolbar = 'Empty';
			self.config.toolbar = self.editorToolbar;
		}
	};
	self.setSimpleToolbar = function( value ) {
		if( !value ) {
			self.editorToolbar = 'SingleRow';
			self.config.toolbar = self.editorToolbar;
		}
	};
	self.setReadOnly = function( value ) {};
	self.setEnabled = function( value ) {};

	self.empty = function() {
		if( self.editor ) {
			if( self.editor.getData() )
				return false;
		}
		return true;
	};

	var previousGetState = self.getState;
	self.getState = function( state ) {
		if( state == 'text-value' ) {
			return self.editor.getData();
		}
		return previousGetState(state);
	};

	var previousSetState = self.setState;
	self.setState = function( state, value ) {
		if( state == 'text-value' ) {
			var dataSet = false;
			self._states['text-value'] = value;
			if( self.editor ) {
				if( self.editorIsReady ) {
					self.editor.setData(value);
					self.editor.updateElement();
					dataSet = true;
				}
			}
			if( !dataSet ) {
				self.haveUnsetData = true;
			}
		} else {
			previousSetState(state, value);
		}
	};

	self.updateVisual = function() {};
	self.updateFormValue = function() {
		if( self.editor ) {
			self.editor.updateElement();
		}
	};

	var previousActivate = self.activate;
	self.activate = function() {
		self.editor = CKEDITOR.replace(self.identifier(), self.config);
		self.editor.on('contentDom', function() {
			self.editorIsReady = true;
			if( self.haveUnsetData ) {
				self.editor.setData(self._states['text-value']);
				self.editor.updateElement();
				self.haveUnsetData = false;
			}
		});

		self.editor.on('contentDomUnload', function() {
			self.editorIsReady = false;
		});
		previousActivate();
	};

	return self;
}

CKEDITOR.addCss('body { margin-left: 5px; margin-right: 5px; margin-top: 3px; margin-bottom: 3px; }');<commit_msg>Revert "FS#4002: Pressing enter should put cursor on new line"<commit_after>function ComponentCkeditor( id ) {
	var self = new ComponentTextfield(id);

	self.setDefaultState('text-value');
	self.setState('text-value', '');

	self.editor = CKEDITOR.instances[id];
	self.editorIsReady = false;
	self.editorToolbar = 'OneRow';
	self.haveUnsetData = false;

	self.config = {
		skin: 'kama',
		enterMode: ( CKEDITOR.env.gecko ? CKEDITOR.ENTER_BR : CKEDITOR.ENTER_P),
		shiftEnterMode: CKEDITOR.ENTER_P,
		disableNativeSpellChecker: false,
		browserContextMenuOnCtrl: true,
		colorButton_enableMore: false,
		resize_dir: 'both',
		/*resize_enabled: true,*/
		fontSize_sizes:
			'8/8pt;' +
			'9/9pt;' +
			'10/10pt;' +
			'11/11pt;' +
			'12/12pt;' +
			'14/14pt;' +
			'16/16pt;' +
			'18/18pt;' +
			'20/20pt;' +
			'22/22pt;' +
			'24/24pt;' +
			'26/26pt;' +
			'28/28pt;' +
			'36/36pt;' +
			'48/48pt',
		font_names:
			'Arial/Arial, Helvetica, sans-serif;' +
			'Arial black;' +
			'Calibri/Calibri, sans-serif;' +
			'Comic Sans MS/Comic Sans MS, cursive;' +
			'Courier New/Courier New, Courier, monospace;' +
			'Georgia/Georgia, serif;' +
			'Lucida Console/Lucida Console, monospace;' +
			'Lucida Sans Unicode/Lucida Sans Unicode, Lucida Grande, sans-serif;' +
			'Tahoma/Tahoma, Geneva, sans-serif;' +
			'Times New Roman/Times New Roman, Times, serif;' +
			'Trebuchet MS/Trebuchet MS, Helvetica, sans-serif;' +
			'Verdana/Verdana, Geneva, sans-serif',
		toolbar_Empty: [],
		toolbar_SingleRow: [
			[ 'SpellCheckerLanguage' ],
			[ 'SpellChecker' ]
		],
		toolbar_OneRow: [
			[ 'Bold', 'Italic', 'Underline', 'Strike' ],
			[ 'NumberedList', 'BulletedList' ],
			[ 'Indent', 'Outdent', 'Blockquote' ],
			[ 'JustifyLeft', 'JustifyCenter', 'JustifyRight' ],
			[ 'Link', 'Image', 'Youtube', 'HorizontalRule' ], [ 'PasteFromWord' ],
			[ 'Font' ], [ 'FontSize' ],
			[ 'TextColor', 'BGColor' ],
			[ 'SpellCheckerLanguage' ], [ 'SpellChecker' ], [ 'Resize' ]
		],
		toolbar_TwoRow: [
			[ 'Bold', 'Italic', 'Underline', 'Strike' ],
			[ 'NumberedList', 'BulletedList' ],
			[ 'Indent', 'Outdent', 'Blockquote' ],
			[ 'JustifyLeft', 'JustifyCenter', 'JustifyRight' ], [ 'PasteFromWord' ],
			[ 'Link', 'Image', 'Youtube', 'HorizontalRule' ],
			[ 'Font' ], [ 'FontSize' ],'/',
			[ 'TextColor', 'BGColor' ],
			[ 'SpellCheckerLanguage' ], [ 'SpellChecker' ], ['Resize']
		],
		toolbar: 'OneRow',
		plugins:
			'basicstyles,' +
			'blockquote,' +
			'clipboard,' +
			'colorbutton,' +
			'contextmenu,' +
			'enterkey,' +
			'font,' +
			'horizontalrule,' +
			'htmlwriter,' +
			'indent,' +
			'justify,' +
			'link,' +
			'list,' +
			'magicline,' +
			'pastetext,' +
			/* 'removeformat,' + */
			'showborders,' +
			'tab,' +
			/*'table,' + */
			/*'tabletools,' + */
			'toolbar,' +
			'undo,' +
			'wysiwygarea,' +
			'cention_spellcheck,' +
			'cention_image,' +
			'pastefromword,' +
			'resize,' +
			'youtube',
		contentsCss: [
			WFServerURI + 'Resources/CSS/jquery.spellchecker.css',
			WFServerURI + 'Resources/Javascript/ckeditor/contents.css',
			WFServerURI + 'Support/Components/Ckeditor/Ckeditor.css',
		],
		spellCheckLanguages: []
	};

	self.setLanguage = function( language ) {
		self.config.language = language;
	}

	self.setFontSize = function( size ){
		if( size ){
			self.config.fontSize_defaultLabel = '' + size;
			CKEDITOR.addCss('.cke_editable { font-size: '+ size +'; }');
		}
	};

	self.setFontFamily = function( family ){
		if( family ){
			self.config.font_defaultLabel = '' + family;
			CKEDITOR.addCss('.cke_editable { font-family: '+ family +'; }');
		}
	}

	self.setLanguages = function( list ) {
	    self.config.spellCheckLanguages = list;
	};
	self.setImages = function( list ) {
		if( self.editor ) {
			self.editor.___fileArchiveImages = list;
		}
	};
	self.setShowResize = function( resize ) {
		if( resize == true ) {
			self.config.resize_enabled = true;
		} else {
			self.config.resize_enabled = false;
		}
	};
	self.setItemHeight = function( height ){
		self.config.height = height;
	};
	self.showBasicToolbar = function() { };
	self.showAdvancedToolbar = function() { };
	self.setTwoRowToolbar = function( value ) {
		if( value ) {
			self.editorToolbar = 'TwoRow';
			self.config.toolbar = self.editorToolbar;
		}
	};
	self.setShowToolbar = function( value ) {
		if( !value ) {
			self.editorToolbar = 'Empty';
			self.config.toolbar = self.editorToolbar;
		}
	};
	self.setSimpleToolbar = function( value ) {
		if( !value ) {
			self.editorToolbar = 'SingleRow';
			self.config.toolbar = self.editorToolbar;
		}
	};
	self.setReadOnly = function( value ) {};
	self.setEnabled = function( value ) {};

	self.empty = function() {
		if( self.editor ) {
			if( self.editor.getData() )
				return false;
		}
		return true;
	};

	var previousGetState = self.getState;
	self.getState = function( state ) {
		if( state == 'text-value' ) {
			return self.editor.getData();
		}
		return previousGetState(state);
	};

	var previousSetState = self.setState;
	self.setState = function( state, value ) {
		if( state == 'text-value' ) {
			var dataSet = false;
			self._states['text-value'] = value;
			if( self.editor ) {
				if( self.editorIsReady ) {
					self.editor.setData(value);
					self.editor.updateElement();
					dataSet = true;
				}
			}
			if( !dataSet ) {
				self.haveUnsetData = true;
			}
		} else {
			previousSetState(state, value);
		}
	};

	self.updateVisual = function() {};
	self.updateFormValue = function() {
		if( self.editor ) {
			self.editor.updateElement();
		}
	};

	var previousActivate = self.activate;
	self.activate = function() {
		self.editor = CKEDITOR.replace(self.identifier(), self.config);
		self.editor.on('contentDom', function() {
			self.editorIsReady = true;
			if( self.haveUnsetData ) {
				self.editor.setData(self._states['text-value']);
				self.editor.updateElement();
				self.haveUnsetData = false;
			}
		});

		self.editor.on('contentDomUnload', function() {
			self.editorIsReady = false;
		});
		previousActivate();
	};

	return self;
}

CKEDITOR.addCss('body { margin-left: 5px; margin-right: 5px; margin-top: 3px; margin-bottom: 3px; }');<|endoftext|>


<commit_before>"use strict";

var dummy
  , hotplate =  require('hotplate')
  , declare = require( 'simpledeclare' )
  , SimpleDbLayer = require( 'simpledblayer' )
  , SimpleSchema = require( 'simpleschema' )
  , JsonRestStores = require( 'jsonreststores' )
  , async = require( 'async')
;

var registry = exports.registry = {};

hotplate.config.set( 'hotCoreStore.storesUrlsPrefix', "/stores" );
hotplate.config.set( 'hotCoreStore.zapIndexes', false );

/* ******************************************************** */
/* The basic stores, ready-to-use with the selected DB etc. */
/* ******************************************************** */

exports.get = hotplate.cacheable( function( done ){

  // Simple schema
  var BasicSchema =  declare( [ SimpleSchema, hotplate.config.get( 'hotplate.SchemaMixin') ] );

  // Enhanced schema (legacy)
  var HotSchema = BasicSchema;

  // Sets the DB Layer
  var DbLayer = declare([ SimpleDbLayer, hotplate.config.get('hotplate.DbLayerMixin') ], {
    db: hotplate.config.get( 'hotplate.db' )
  });

    // Creates a basic DB store based on that layer
  var BasicDbStore = declare( [ JsonRestStores, JsonRestStores.SimpleDbLayerMixin, JsonRestStores.HTTPMixin ], {
    DbLayer: DbLayer,
    chainErrors: 'all'
  });

  // Creates a basic DB store based on that layer
  var HotStore = declare( [ BasicDbStore ], { enableComet: true } );

  done( null, { BasicSchema: BasicSchema, HotSchema: HotSchema, BasicDbStore: BasicDbStore, HotStore: HotStore } );

} );

/* ******************************************************** */
/*                  Permission mixins                       */
/* ******************************************************** */

/* To WRITE (put, post, delete), userId needs to match logged in user */
exports.BasicPermissionsMixin = declare( Object, {

  _checkUserId: function( request, cb ){

    var self = this;

    // User is not logged in: fail
    if( ! request.session.userId || ! request.session.loggedIn) return cb( new self.UnauthorizedError() );

    // The request doesn't include a userId: pass it through (nothing to compare against)
    if( ! request.params.userId ) return cb( null, true );

    // userId is different to session's: fail
    if( request.params.userId.toString() !== request.session.userId.toString() ){
      return cb( null, false );
    }

    // Any other cases: pass
    cb( null, true );
  },

  checkPermissions: function f( request, method, cb ){
    var self = this;

    this.inheritedAsync( f, arguments, function( err, res ){
      if( err ) return cb( err );
      if( ! res ) return cb( null, false );

      // getXXX methods are not handled
      if( method === 'get' || method === 'getQuery' ) return cb( null, true );

      self._checkUserId( request, cb );
    });
  },

});

/* To READ (get, getQuery), userId needs to match logged in user */
exports.PrivateUserDataPermissionsMixin = declare( Object, {

  _checkUserIdForJsonRestStores: function( request, cb ){
    var self = this;

    // User is not logged in: fail
    if( ! request.session.userId ) return cb( new self.UnauthorizedError() );

    // The request doesn't include a userId: pass it through (nothing to compare against)
    if( ! request.params.userId ) return cb( null, true );

    // userId is different to session's: fail
    if( request.params.userId.toString() !== request.session.userId.toString() ){
      return cb( null, false );
    }

    // Any other cases: pass
    cb( null, true );

  },

  checkPermissions: function f( request, method, cb ){
    var self = this;

    this.inheritedAsync( f, arguments, function( err, res ){
      if( err ) return cb( err );
      if( ! res ) return cb( null, false );

      // Only getXXX methods are handled
      if( method !== 'get' && method !== 'getQuery' ) return cb( null, true );

      self._checkUserIdForJsonRestStores( request, cb );

    });
  },

});

/* ******************************************************** */
/*                  Registry                                */
/* ******************************************************** */

exports.getAllStores = hotplate.cacheable( function( done ){

  hotplate.hotEvents.emitCollect( 'stores', function( err, results){

    results.forEach( function( element ) {

      Object.keys( element.result ).forEach( function( k ){

       var store = element.result[ k ];

       // Add the module to the store registry
       registry[ store.storeName ] = store;

      });

    });
    done( null, registry );
  });

});

/* ******************************************************** */
/*   Store exposer -- run protocolListenHTTP for every      */
/*                    store marked as `hotExpose`
/* ******************************************************** */
hotplate.hotEvents.onCollect( 'setRoutes', function( app, done ){

  exports.getAllStores( function( err, allStores ){

    Object.keys( allStores ).forEach( function( storeName ){

      var store = allStores[ storeName ];

      // The store has a public URL: add it to the list of stores to expose
      // Note that I pass the modified URL to setAllRoutes
      if( store.hotExpose ){
        store.publicURLPrefix = hotplate.config.get( 'hotCoreStore.storesUrlsPrefix' );
        store.protocolListenHTTP( { app: app } );
      }
    });

    done( null );
  });
});

/* ******************************************************** */
/*   Store index creator                                    */
/* ******************************************************** */

exports.regenerateAllIndexes = function( done ){

  exports.getAllStores( function( err, allStores ){

    Object.keys( allStores ).forEach( function( storeName ){

      var store = allStores[ storeName ];

      if( ! store.dbLayer ) return; // Like saying "continue"

      store.dbLayer.dropAllIndexes( function( e ){
        store.dbLayer.generateSchemaIndexes( { background: true }, function(){}  );
      });
    });

    done( null );
  });
}

hotplate.hotEvents.onCollect( 'run', function( done ){
  if( ! hotplate.config.get( 'hotCoreStore.zapIndexes' ) ) return done( null );

  exports.regenerateAllIndexes( done );
});
<commit_msg>Important sane renaming in permission mixins<commit_after>"use strict";

var dummy
  , hotplate =  require('hotplate')
  , declare = require( 'simpledeclare' )
  , SimpleDbLayer = require( 'simpledblayer' )
  , SimpleSchema = require( 'simpleschema' )
  , JsonRestStores = require( 'jsonreststores' )
  , async = require( 'async')
;

var registry = exports.registry = {};

hotplate.config.set( 'hotCoreStore.storesUrlsPrefix', "/stores" );
hotplate.config.set( 'hotCoreStore.zapIndexes', false );

/* ******************************************************** */
/* The basic stores, ready-to-use with the selected DB etc. */
/* ******************************************************** */

exports.get = hotplate.cacheable( function( done ){

  // Simple schema
  var BasicSchema =  declare( [ SimpleSchema, hotplate.config.get( 'hotplate.SchemaMixin') ] );

  // Enhanced schema (legacy)
  var HotSchema = BasicSchema;

  // Sets the DB Layer
  var DbLayer = declare([ SimpleDbLayer, hotplate.config.get('hotplate.DbLayerMixin') ], {
    db: hotplate.config.get( 'hotplate.db' )
  });

    // Creates a basic DB store based on that layer
  var BasicDbStore = declare( [ JsonRestStores, JsonRestStores.SimpleDbLayerMixin, JsonRestStores.HTTPMixin ], {
    DbLayer: DbLayer,
    chainErrors: 'all'
  });

  // Creates a basic DB store based on that layer
  var HotStore = declare( [ BasicDbStore ], { enableComet: true } );

  done( null, { BasicSchema: BasicSchema, HotSchema: HotSchema, BasicDbStore: BasicDbStore, HotStore: HotStore } );

} );

/* ******************************************************** */
/*                  Permission mixins                       */
/* ******************************************************** */

var _onlyUserId = function( request, where, cb ){
  var self = this;

  // User is not logged in: fail
  if( ! request.session.userId || ! request.session.loggedIn) return cb( new self.UnauthorizedError() );

  // The request doesn't include a userId: pass it through (nothing to compare against)
  if( ! request[ where ].userId ){
    return cb( new Error( "This permission needs to be used on a store with userId defined. Store: " + this.storeName ) );
  }

  // userId is different to session's: fail
  if( request[ where ].userId.toString() !== request.session.userId.toString() ){
    return cb( null, false );
  } else {
    cb( null, true );
  }
};

/* To WRITE (put, post, delete), userId needs to match logged in user */
// Was: BasicPermissionsMixin
exports.OnlyUserIdCanWrite = declare( Object, {

  _onlyUserId: _onlyUserId,

  checkPermissions: function f( request, method, cb ){
    var self = this;

    self.inheritedAsync( f, arguments, function( err, res ){
      if( err ) return cb( err );
      if( ! res ) return cb( null, false );

      // Only putXXX methods are handled
      if( method != 'put' && method != 'post' && method != 'delete' ) return cb( null, true );

      self._onlyUserId( request, 'body', cb );
    });
  },

});
exports.BasicPermissionsMixin = exports.OnlyUserIdCanWrite;

/* To READ (get, getQuery), userId needs to match logged in user */
// Was: PrivateUserDataPermissionsMixin
exports.OnlyUserIdCanRead = declare( Object, {

  _onlyUserId: _onlyUserId,

  checkPermissions: function f( request, method, cb ){
    var self = this;

    this.inheritedAsync( f, arguments, function( err, res ){
      if( err ) return cb( err );
      if( ! res ) return cb( null, false );

      // Only getXXX methods are handled
      if( method !== 'get' && method !== 'getQuery' ) return cb( null, true );

      self._onlyUserId( request, 'params', cb );

    });
  },

});
exports.PrivateUserDataPermissionsMixin = exports.OnlyUserIdCanRead;

/* ******************************************************** */
/*                  Registry                                */
/* ******************************************************** */

exports.getAllStores = hotplate.cacheable( function( done ){

  hotplate.hotEvents.emitCollect( 'stores', function( err, results){

    results.forEach( function( element ) {

      Object.keys( element.result ).forEach( function( k ){

       var store = element.result[ k ];

       // Add the module to the store registry
       registry[ store.storeName ] = store;

      });

    });
    done( null, registry );
  });

});

/* ******************************************************** */
/*   Store exposer -- run protocolListenHTTP for every      */
/*                    store marked as `hotExpose`
/* ******************************************************** */
hotplate.hotEvents.onCollect( 'setRoutes', function( app, done ){

  exports.getAllStores( function( err, allStores ){

    Object.keys( allStores ).forEach( function( storeName ){

      var store = allStores[ storeName ];

      // The store has a public URL: add it to the list of stores to expose
      // Note that I pass the modified URL to setAllRoutes
      if( store.hotExpose ){
        store.publicURLPrefix = hotplate.config.get( 'hotCoreStore.storesUrlsPrefix' );
        store.protocolListenHTTP( { app: app } );
      }
    });

    done( null );
  });
});

/* ******************************************************** */
/*   Store index creator                                    */
/* ******************************************************** */

exports.regenerateAllIndexes = function( done ){

  exports.getAllStores( function( err, allStores ){

    Object.keys( allStores ).forEach( function( storeName ){

      var store = allStores[ storeName ];

      if( ! store.dbLayer ) return; // Like saying "continue"

      store.dbLayer.dropAllIndexes( function( e ){
        store.dbLayer.generateSchemaIndexes( { background: true }, function(){}  );
      });
    });

    done( null );
  });
}

hotplate.hotEvents.onCollect( 'run', function( done ){
  if( ! hotplate.config.get( 'hotCoreStore.zapIndexes' ) ) return done( null );

  exports.regenerateAllIndexes( done );
});
<|endoftext|>


<commit_before>var CFDocs = {};
Elemental.addNamespace(CFDocs);

$(document).ready(function() {
    Elemental.load(document);
});

CFDocs.normalizeUrl = function(url) {
    var match;
    if (match = url.match("^(.*)index.html$")) {
        return match[1];
    } else {
        return url;
    }
}

$(function () {

    var normalizedCurrentUrl = CFDocs.normalizeUrl(window.location.pathname);

    function isCurrentPage(link) {
        var originalLinkHref = link.attr('href').toString();
        var normalizedLinkHref = normalizeUrl(originalLinkHref);

        var currentLinkIsHome = link.attr('id') == "home-nav-link";
        var windowLocationIsExactMatch = normalizedCurrentUrl == normalizedLinkHref;

        if (currentLinkIsHome) {
            if (windowLocationIsExactMatch) return true;
        } else {
            if (normalizedCurrentUrl.match("^" + normalizedLinkHref)) return true;
        }
        return false;
    }

	if (document.location.pathname.indexOf('/pivotalax/') > -1 ||
        document.location.pathname.indexOf('/chorus/') > -1) {
		document.location.href = "https://alpine.atlassian.net/wiki/display/DOC/Alpine+Overview";
	}

    // For main search
    $('#click-to-search').click(function () {
        $('#search-dropdown-box').show();
        $('html,body').scrollTop(0);
    });

    $('.search-dropdown--container .close-menu-large').click(function() {
        $('#search-dropdown-box').hide();
    });

  $('.js-deep-nav .hasSubMenuClosed').siblings('ul').hide();
  $('.js-deep-nav .hasSubMenuClosed').click(function() {
    $(this).toggleClass('hasSubMenuOpened');
    $(this).siblings('ul').slideToggle();
  });

});

// Accordion
(function() {
    $('#accordion-1').dcAccordion({
      eventType: 'click',
      autoClose: true,
      saveState: true,
      disableLink: false,
      speed: 'fast',
      classActive: 'test',
      showCount: false
    });
});

//Global Google Search
(function() {
    var cx = '005804290371689664731:n1ix15a_ysy';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
        '//www.google.com/cse/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
})();

$(function () {
  window.addEventListener("orientationchange", function() {
    var deviceHeight = jQuery(window).height();
    var openDrawer = jQuery(".js-open-nav-drawer.js-slide-right");
    if (!openDrawer.length) {
      return;
    } else {
      jQuery(".viewport").height(deviceHeight).addClass("constrained");
    }
  }, false);

  $(".js-open-nav-drawer").click(function() {
    $(".navigation-drawer--container").addClass("js-open");
    $(".mobile-nav, .body--container, .homepage--body").addClass("js-slide-right");

    var deviceHeight = jQuery(window).height();
    $(".viewport").height(deviceHeight).addClass("constrained");
    $("#scrim").addClass("js-show js-open-mobile-nav");
    $("#scrim").click(function() {
      $(".navigation-drawer--container").removeClass("js-open");
      $(".mobile-nav, .body--container, .homepage--body").removeClass("js-slide-right");
      $(".viewport").removeClass("constrained");
    });
  });
});

// NAVIGATION
$(function() {
    var headerHeight = 45;
    // Smooth scrolling for all jump links
    $('a[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
            if (target.length) {
                $('html,body').animate({
                    scrollTop: target.offset().top - headerHeight
                }, 600);
            // return false;
            }
        }
    });

    var currentUrl = window.location.pathname;
    var $activeNavLink = $(".js-sidenav a[href='" + currentUrl + "']");

    if ($activeNavLink.length) {
        // Highlight side navigation link that matches current url path
        $activeNavLink.attr('class', "active");
        $activeParent = $activeNavLink.parents('.js-menu-item');

        $activeParent.addClass('is-clicked');

        $activeNavLink.parents('.js-menu-content').slideDown(function() {
            // Scroll to active side navigation link
            $('.js-sidenav').animate({
            scrollTop: $activeNavLink.offset().top - (headerHeight * 2)
            }, 100);
        });
    }

    // Show and hide back to top
    if(jQuery().waypoint) {
        $('#js-to-top').waypoint('sticky', {
          wrapper: '
',
          stuckClass: 'sticky',
          offset: 100
        });
    }
});

// Collapse and expand menu content
// @requires class="collapsible" data-behavior="Collapsible"
CFDocs.Collapsible = function(element) {
    var $el = $(element);
    var $clickableTitle = $el.find('.js-menu-title');

    $clickableTitle.click(function() {
        var $content = $(this).siblings('.js-menu-content');
        var $parent = $(this).parents('.js-menu-item');

        $content.slideToggle();
        $parent.toggleClass('is-clicked');
    });
}

// Show and hide search form
CFDocs.Search = function(element) {
    var $el = $(element);
    $el.click(function() {
        $('.js-searchbar').toggleClass('active');
    });
}

// Show and hide main navigation mobile menu
CFDocs.MenuMobile = function(element) {
    var $el = $(element);
    $el.click(function() {
        $('.js-bar-links').toggleClass('menu-active');
    });
}

// Show and hide side navigation mobile menu
CFDocs.SubMenuMobile = function(element) {
    var $el = $(element);
    $el.click(function() {
        $('.js-sidenav').toggleClass('active');
    });
}

<commit_msg>Updating search id<commit_after>var CFDocs = {};
Elemental.addNamespace(CFDocs);

$(document).ready(function() {
    Elemental.load(document);
});

CFDocs.normalizeUrl = function(url) {
    var match;
    if (match = url.match("^(.*)index.html$")) {
        return match[1];
    } else {
        return url;
    }
}

$(function () {

    var normalizedCurrentUrl = CFDocs.normalizeUrl(window.location.pathname);

    function isCurrentPage(link) {
        var originalLinkHref = link.attr('href').toString();
        var normalizedLinkHref = normalizeUrl(originalLinkHref);

        var currentLinkIsHome = link.attr('id') == "home-nav-link";
        var windowLocationIsExactMatch = normalizedCurrentUrl == normalizedLinkHref;

        if (currentLinkIsHome) {
            if (windowLocationIsExactMatch) return true;
        } else {
            if (normalizedCurrentUrl.match("^" + normalizedLinkHref)) return true;
        }
        return false;
    }

	if (document.location.pathname.indexOf('/pivotalax/') > -1 ||
        document.location.pathname.indexOf('/chorus/') > -1) {
		document.location.href = "https://alpine.atlassian.net/wiki/display/DOC/Alpine+Overview";
	}

    // For main search
    $('#click-to-search').click(function () {
        $('#search-dropdown-box').show();
        $('html,body').scrollTop(0);
    });

    $('.search-dropdown--container .close-menu-large').click(function() {
        $('#search-dropdown-box').hide();
    });

  $('.js-deep-nav .hasSubMenuClosed').siblings('ul').hide();
  $('.js-deep-nav .hasSubMenuClosed').click(function() {
    $(this).toggleClass('hasSubMenuOpened');
    $(this).siblings('ul').slideToggle();
  });

});

// Accordion
(function() {
    $('#accordion-1').dcAccordion({
      eventType: 'click',
      autoClose: true,
      saveState: true,
      disableLink: false,
      speed: 'fast',
      classActive: 'test',
      showCount: false
    });
});

//Global Google Search
(function() {
    var cx = '005804290371689664731:9jhxguhn8dy';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
        '//www.google.com/cse/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
})();

$(function () {
  window.addEventListener("orientationchange", function() {
    var deviceHeight = jQuery(window).height();
    var openDrawer = jQuery(".js-open-nav-drawer.js-slide-right");
    if (!openDrawer.length) {
      return;
    } else {
      jQuery(".viewport").height(deviceHeight).addClass("constrained");
    }
  }, false);

  $(".js-open-nav-drawer").click(function() {
    $(".navigation-drawer--container").addClass("js-open");
    $(".mobile-nav, .body--container, .homepage--body").addClass("js-slide-right");

    var deviceHeight = jQuery(window).height();
    $(".viewport").height(deviceHeight).addClass("constrained");
    $("#scrim").addClass("js-show js-open-mobile-nav");
    $("#scrim").click(function() {
      $(".navigation-drawer--container").removeClass("js-open");
      $(".mobile-nav, .body--container, .homepage--body").removeClass("js-slide-right");
      $(".viewport").removeClass("constrained");
    });
  });
});

// NAVIGATION
$(function() {
    var headerHeight = 45;
    // Smooth scrolling for all jump links
    $('a[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
            if (target.length) {
                $('html,body').animate({
                    scrollTop: target.offset().top - headerHeight
                }, 600);
            // return false;
            }
        }
    });

    var currentUrl = window.location.pathname;
    var $activeNavLink = $(".js-sidenav a[href='" + currentUrl + "']");

    if ($activeNavLink.length) {
        // Highlight side navigation link that matches current url path
        $activeNavLink.attr('class', "active");
        $activeParent = $activeNavLink.parents('.js-menu-item');

        $activeParent.addClass('is-clicked');

        $activeNavLink.parents('.js-menu-content').slideDown(function() {
            // Scroll to active side navigation link
            $('.js-sidenav').animate({
            scrollTop: $activeNavLink.offset().top - (headerHeight * 2)
            }, 100);
        });
    }

    // Show and hide back to top
    if(jQuery().waypoint) {
        $('#js-to-top').waypoint('sticky', {
          wrapper: '
',
          stuckClass: 'sticky',
          offset: 100
        });
    }
});

// Collapse and expand menu content
// @requires class="collapsible" data-behavior="Collapsible"
CFDocs.Collapsible = function(element) {
    var $el = $(element);
    var $clickableTitle = $el.find('.js-menu-title');

    $clickableTitle.click(function() {
        var $content = $(this).siblings('.js-menu-content');
        var $parent = $(this).parents('.js-menu-item');

        $content.slideToggle();
        $parent.toggleClass('is-clicked');
    });
}

// Show and hide search form
CFDocs.Search = function(element) {
    var $el = $(element);
    $el.click(function() {
        $('.js-searchbar').toggleClass('active');
    });
}

// Show and hide main navigation mobile menu
CFDocs.MenuMobile = function(element) {
    var $el = $(element);
    $el.click(function() {
        $('.js-bar-links').toggleClass('menu-active');
    });
}

// Show and hide side navigation mobile menu
CFDocs.SubMenuMobile = function(element) {
    var $el = $(element);
    $el.click(function() {
        $('.js-sidenav').toggleClass('active');
    });
}

<|endoftext|>


<commit_before>var Youtube = require("youtube-api");
var GLOBAL_CONFIG = require("../../global-config.js");

module.exports = function(Search) {
  Search.afterCreate = function(next) {
    Youtube.authenticate({
      type: "key",
      key: GLOBAL_CONFIG.youtubeApiKey
    });

    Youtube.search.list({q:this.keyword, part:"snippet", maxResults:5}, function(err, data) {
      data.items.forEach(function(item) {
        console.log(item.id.videoId);
        console.log(item.snippet.title);
        console.log("-----");
      });

      next();
    });
  };
};
<commit_msg>検索結果に得られるのはYoutubeのvideoのみに修正<commit_after>var Youtube = require("youtube-api");
var GLOBAL_CONFIG = require("../../global-config.js");

module.exports = function(Search) {
  Search.afterCreate = function(next) {
    Youtube.authenticate({
      type: "key",
      key: GLOBAL_CONFIG.youtubeApiKey
    });

    Youtube.search.list({q:this.keyword, part:"snippet", maxResults:5, type:"video"}, function(err, data) {
      data.items.forEach(function(item) {
        console.log(item.id.videoId);
        console.log(item.snippet.title);
        console.log("-----");
      });

      next();
    });
  };
};
<|endoftext|>


<commit_before>'use strict';
var t = require('tape');
var validate = require('../lib/validate').v3;

// Cover render_fill well as an instance of render_*.
t('v3 render_fill', function(t) {
    t.equal(validate.render_fill('foobar', '')[0].message, 'render_fill property unrecognized: foobar');
    t.equal(validate.render_fill('type', 'line')[0].message, 'type: expected one of [fill], line found');
    t.equal(validate.render_fill('type', 'fill').length, 0);
    t.equal(validate.render_fill('fill-antialias', 1)[0].message, 'fill-antialias: boolean expected, number found');
    t.equal(validate.render_fill('fill-antialias', true).length, 0);

    t.end();
});

// Cover class_fill well as an instance of class_*.
t('v3 class_fill', function(t) {
    t.equal(validate.class_fill('foobar', '')[0].message, 'class_fill property unrecognized: foobar');
    t.equal(validate.class_fill('fill-enabled', 1)[0].message, 'fill-enabled: boolean expected, number found');
    t.equal(validate.class_fill('fill-enabled', true).length, 0);
    t.equal(validate.class_fill('fill-opacity', 'foo')[0].message, 'fill-opacity: number expected, string found');
    t.equal(validate.class_fill('fill-opacity', 1).length, 0);
    t.equal(validate.class_fill('fill-color', 5)[0].message, 'fill-color: color expected, number found');
    t.equal(validate.class_fill('fill-color', [0,0])[0].message, 'fill-color: color expected, 0,0 found');
    t.equal(validate.class_fill('fill-color', [0,0,0]).length, 0);
    t.equal(validate.class_fill('fill-color', [0,0,0,0]).length, 0);
    t.equal(validate.class_fill('fill-color', 'rgb(0,0,0)').length, 0);
    t.equal(validate.class_fill('fill-color', 'rgba(0,0,0,1)').length, 0);
    t.equal(validate.class_fill('fill-color', '#ff00ff').length, 0);
    t.equal(validate.class_fill('fill-color', 'red').length, 0);
    t.equal(validate.class_fill('fill-translate', 1)[0].message, 'fill-translate: array expected, number found');
    t.equal(validate.class_fill('fill-translate', [0,1,2])[0].message, 'fill-translate: array length 2 expected, length 3 found');
    t.equal(validate.class_fill('fill-translate', ['a','b'])[0].message, 'fill-translate[0]: number expected, string found');
    t.equal(validate.class_fill('fill-translate', [0,1]).length, 0);
    t.equal(validate.class_fill('fill-translate-anchor', 1)[0].message, 'fill-translate-anchor: expected one of [map, viewport], 1 found');
    t.equal(validate.class_fill('fill-translate-anchor', 'map').length, 0);

    t.end();
});

t('v3 transition', function(t) {
    t.equal(validate.transition('foobar', '')[0].message, 'transition property unrecognized: foobar');

    // duration in the context of class_fill
    t.equal(validate.class_fill('transition-fill-opacity', {
        foobar: ''
    })[0].message, 'transition property unrecognized: foobar');
    t.equal(validate.class_fill('transition-fill-opacity', {
        duration: ''
    })[0].message, 'transition-fill-opacity.duration: number expected, string found');
    t.equal(validate.class_fill('transition-fill-opacity', {
        delay: ''
    })[0].message, 'transition-fill-opacity.delay: number expected, string found');
    t.equal(validate.class_fill('transition-fill-opacity', {
        duration: 10,
        delay: 10
    }).length, 0);

    t.end();
});

t('v3 function', function(t) {
    t.equal(validate.function('foobar', '')[0].message, 'function property unrecognized: foobar');

    // stops function in the context of class_fill
    t.equal(validate.class_fill('fill-opacity', {
        fn: 'stops'
    })[0].message, 'function property values required');
    t.equal(validate.class_fill('fill-opacity', {
        fn: 'stops',
        values: ''
    })[0].message, 'fill-opacity.values: array expected, string found');
    t.equal(validate.class_fill('fill-opacity', {
        fn: 'stops',
        values: ['a']
    })[0].message, 'fill-opacity.values[0]: array expected, string found');
    t.equal(validate.class_fill('fill-opacity', {
        fn: 'stops',
        values: [[0]]
    })[0].message, 'fill-opacity.values[0]: array length 2 expected, length 1 found');
    t.equal(validate.class_fill('fill-opacity', {
        fn: 'stops',
        values: [[0,1]]
    }).length, 0);

    // linear function in the context of class_fill
    t.equal(validate.class_fill('fill-opacity', {
        fn: 'linear'
    })[2].message, 'function property z required');
    t.equal(validate.class_fill('fill-opacity', {
        fn: 'linear',
        z: 5,
        value: 'boolean'
    }).length, 0);

    // unknown function
    t.equal(validate.class_fill('fill-opacity', {
        fn: 'expinential'
    })[0].message, 'fill-opacity.fn: expected one of [stops], expinential found');

    t.end();
});

t('v3 layer', function(t) {
    t.equal(validate.layer('foobar', '')[0].message, 'layer property unrecognized: foobar');
    t.end();
});

t('v3 source', function(t) {
    t.equal(validate.source('foobar', '')[0].message, 'source property unrecognized: foobar');
    t.end();
});

t('v3 filter', function(t) {
    t.equal(validate.filter('foobar', '')[0].message, 'filter property unrecognized: foobar');
    t.end();
});

<commit_msg>Update v3 tests for values => stops rename.<commit_after>'use strict';
var t = require('tape');
var validate = require('../lib/validate').v3;

// Cover render_fill well as an instance of render_*.
t('v3 render_fill', function(t) {
    t.equal(validate.render_fill('foobar', '')[0].message, 'render_fill property unrecognized: foobar');
    t.equal(validate.render_fill('type', 'line')[0].message, 'type: expected one of [fill], line found');
    t.equal(validate.render_fill('type', 'fill').length, 0);
    t.equal(validate.render_fill('fill-antialias', 1)[0].message, 'fill-antialias: boolean expected, number found');
    t.equal(validate.render_fill('fill-antialias', true).length, 0);

    t.end();
});

// Cover class_fill well as an instance of class_*.
t('v3 class_fill', function(t) {
    t.equal(validate.class_fill('foobar', '')[0].message, 'class_fill property unrecognized: foobar');
    t.equal(validate.class_fill('fill-enabled', 1)[0].message, 'fill-enabled: boolean expected, number found');
    t.equal(validate.class_fill('fill-enabled', true).length, 0);
    t.equal(validate.class_fill('fill-opacity', 'foo')[0].message, 'fill-opacity: number expected, string found');
    t.equal(validate.class_fill('fill-opacity', 1).length, 0);
    t.equal(validate.class_fill('fill-color', 5)[0].message, 'fill-color: color expected, number found');
    t.equal(validate.class_fill('fill-color', [0,0])[0].message, 'fill-color: color expected, 0,0 found');
    t.equal(validate.class_fill('fill-color', [0,0,0]).length, 0);
    t.equal(validate.class_fill('fill-color', [0,0,0,0]).length, 0);
    t.equal(validate.class_fill('fill-color', 'rgb(0,0,0)').length, 0);
    t.equal(validate.class_fill('fill-color', 'rgba(0,0,0,1)').length, 0);
    t.equal(validate.class_fill('fill-color', '#ff00ff').length, 0);
    t.equal(validate.class_fill('fill-color', 'red').length, 0);
    t.equal(validate.class_fill('fill-translate', 1)[0].message, 'fill-translate: array expected, number found');
    t.equal(validate.class_fill('fill-translate', [0,1,2])[0].message, 'fill-translate: array length 2 expected, length 3 found');
    t.equal(validate.class_fill('fill-translate', ['a','b'])[0].message, 'fill-translate[0]: number expected, string found');
    t.equal(validate.class_fill('fill-translate', [0,1]).length, 0);
    t.equal(validate.class_fill('fill-translate-anchor', 1)[0].message, 'fill-translate-anchor: expected one of [map, viewport], 1 found');
    t.equal(validate.class_fill('fill-translate-anchor', 'map').length, 0);

    t.end();
});

t('v3 transition', function(t) {
    t.equal(validate.transition('foobar', '')[0].message, 'transition property unrecognized: foobar');

    // duration in the context of class_fill
    t.equal(validate.class_fill('transition-fill-opacity', {
        foobar: ''
    })[0].message, 'transition property unrecognized: foobar');
    t.equal(validate.class_fill('transition-fill-opacity', {
        duration: ''
    })[0].message, 'transition-fill-opacity.duration: number expected, string found');
    t.equal(validate.class_fill('transition-fill-opacity', {
        delay: ''
    })[0].message, 'transition-fill-opacity.delay: number expected, string found');
    t.equal(validate.class_fill('transition-fill-opacity', {
        duration: 10,
        delay: 10
    }).length, 0);

    t.end();
});

t('v3 function', function(t) {
    t.equal(validate.function('foobar', '')[0].message, 'function property unrecognized: foobar');

    // stops function in the context of class_fill
    t.equal(validate.class_fill('fill-opacity', {
        fn: 'stops'
    })[0].message, 'function property stops required');
    t.equal(validate.class_fill('fill-opacity', {
        fn: 'stops',
        stops: ''
    })[0].message, 'fill-opacity.stops: array expected, string found');
    t.equal(validate.class_fill('fill-opacity', {
        fn: 'stops',
        stops: ['a']
    })[0].message, 'fill-opacity.stops[0]: array expected, string found');
    t.equal(validate.class_fill('fill-opacity', {
        fn: 'stops',
        stops: [[0]]
    })[0].message, 'fill-opacity.stops[0]: array length 2 expected, length 1 found');
    t.equal(validate.class_fill('fill-opacity', {
        fn: 'stops',
        stops: [[0,1]]
    }).length, 0);

    // linear function in the context of class_fill
    t.equal(validate.class_fill('fill-opacity', {
        fn: 'linear'
    })[2].message, 'function property z required');
    t.equal(validate.class_fill('fill-opacity', {
        fn: 'linear',
        z: 5,
        value: 'boolean'
    }).length, 0);

    // unknown function
    t.equal(validate.class_fill('fill-opacity', {
        fn: 'expinential'
    })[0].message, 'fill-opacity.fn: expected one of [stops], expinential found');

    t.end();
});

t('v3 layer', function(t) {
    t.equal(validate.layer('foobar', '')[0].message, 'layer property unrecognized: foobar');
    t.end();
});

t('v3 source', function(t) {
    t.equal(validate.source('foobar', '')[0].message, 'source property unrecognized: foobar');
    t.end();
});

t('v3 filter', function(t) {
    t.equal(validate.filter('foobar', '')[0].message, 'filter property unrecognized: foobar');
    t.end();
});

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { StyleSheet, Text, View, Animated, TouchableOpacity, Dimensions } from 'react-native';
const { width } = Dimensions.get('window');

const alignItemsMap = {
  center: "center",
  left: "flex-start",
  right: "flex-end"
}

let actionBtnWidth = 0;

export default class ActionButtonItem extends Component {

  constructor(props) {
    super(props);
    this.state = {
      spaceBetween: 15,
      alignItems: alignItemsMap[this.props.position]
    };

    if (!props.children || Array.isArray(props.children)) {
      throw new Error("ActionButtonItem must have a Child component.");
    }

    if(props.size > 0) {
      actionBtnWidth = this.props.size;
    }
  }

  render() {
    return (
      <Animated.View
        style={[styles.actionButtonWrap, {
          alignItems: this.state.alignItems,
          marginBottom: this.props.spacing,
          opacity: this.props.anim,
          transform: [{
            translateY: this.props.anim.interpolate({
              inputRange: [0, 1],
              outputRange: [40, 0]
            }),
           }],
          }
        ]}
      >
        <TouchableOpacity style={{flex:1}} activeOpacity={this.props.activeOpacity || 0.85} onPress={this.props.onPress}>
          <View
            style={[styles.actionButton, this.props.style, {
              width: actionBtnWidth,
              height: actionBtnWidth,
              borderRadius: actionBtnWidth / 2,
              backgroundColor: this.props.buttonColor || this.props.btnColor
            }]}
          >
            {this.props.children}
          </View>
        </TouchableOpacity>
        {
          !!this.props.title && (
              <TouchableOpacity style={this.getTextStyles()} activeOpacity={this.props.activeOpacity || 0.85} onPress={this.props.onPress}>
                <Text style={styles.actionText}>{this.props.title}</Text>
              </TouchableOpacity>
            )
        }
      </Animated.View>
    );
  }

  getTextStyles() {
    // to align the center of the label with the center of the button,
    // offset = (half the size of the btn) - (half the size of the label)
    let offsetTop = actionBtnWidth >= 28 ? (actionBtnWidth / 2) - 14 : 0;

    let positionStyles = {
      right: actionBtnWidth + this.state.spaceBetween,
      top: offsetTop
    }

    let bgStyle = { backgroundColor : 'white' };

    if (this.props.titleBgColor) bgStyle = {
      backgroundColor:this.props.titleBgColor
    }

    if (this.props.position == 'left') positionStyles = {
      left: actionBtnWidth + this.state.spaceBetween,
      top: offsetTop
    }

    if (this.props.position == 'center') positionStyles = {
      right: actionBtnWidth/2 + width/2 + this.state.spaceBetween,
      top: offsetTop
    }

    return [styles.actionTextView, positionStyles, bgStyle];
  }
}

const styles = StyleSheet.create({
  actionButtonWrap: {
    width
  },
  actionButton: {
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
    paddingTop: 2,
    shadowOpacity: 0.3,
    shadowOffset: {
      width: 0, height: 1,
    },
    shadowColor: '#444',
    shadowRadius: 1,
  },
  actionTextView: {
    position: 'absolute',
    paddingVertical: 4,
    paddingHorizontal: 10,
    borderRadius: 3,
    shadowOpacity: 0.3,
    shadowOffset: {
      width: 0, height: 1,
    },
    shadowColor: '#444',
    shadowRadius: 1,
  },
  actionText: {
    flex: 1,
    color: '#444',
    fontSize: 14,
  }
});
<commit_msg>Added titleColor prop for action button item<commit_after>import React, { Component } from 'react';
import { StyleSheet, Text, View, Animated, TouchableOpacity, Dimensions } from 'react-native';
const { width } = Dimensions.get('window');

const alignItemsMap = {
  center: "center",
  left: "flex-start",
  right: "flex-end"
}

let actionBtnWidth = 0;

export default class ActionButtonItem extends Component {

  constructor(props) {
    super(props);
    this.state = {
      spaceBetween: 15,
      alignItems: alignItemsMap[this.props.position]
    };

    if (!props.children || Array.isArray(props.children)) {
      throw new Error("ActionButtonItem must have a Child component.");
    }

    if(props.size > 0) {
      actionBtnWidth = this.props.size;
    }
  }

  render() {
    return (
      <Animated.View
        style={[styles.actionButtonWrap, {
          alignItems: this.state.alignItems,
          marginBottom: this.props.spacing,
          opacity: this.props.anim,
          transform: [{
            translateY: this.props.anim.interpolate({
              inputRange: [0, 1],
              outputRange: [40, 0]
            }),
           }],
          }
        ]}
      >
        <TouchableOpacity style={{flex:1}} activeOpacity={this.props.activeOpacity || 0.85} onPress={this.props.onPress}>
          <View
            style={[styles.actionButton, this.props.style, {
              width: actionBtnWidth,
              height: actionBtnWidth,
              borderRadius: actionBtnWidth / 2,
              backgroundColor: this.props.buttonColor || this.props.btnColor
            }]}
          >
            {this.props.children}
          </View>
        </TouchableOpacity>
        {
          !!this.props.title && (
              <TouchableOpacity style={this.getTextStyles()} activeOpacity={this.props.activeOpacity || 0.85} onPress={this.props.onPress}>
                <Text style={[styles.actionText, { color: this.props.titleColor || '#444' }]}>
                  {this.props.title}
                </Text>
              </TouchableOpacity>
            )
        }
      </Animated.View>
    );
  }

  getTextStyles() {
    // to align the center of the label with the center of the button,
    // offset = (half the size of the btn) - (half the size of the label)
    let offsetTop = actionBtnWidth >= 28 ? (actionBtnWidth / 2) - 14 : 0;

    let positionStyles = {
      right: actionBtnWidth + this.state.spaceBetween,
      top: offsetTop
    }

    let bgStyle = { backgroundColor : 'white' };

    if (this.props.titleBgColor) bgStyle = {
      backgroundColor:this.props.titleBgColor
    }

    if (this.props.position == 'left') positionStyles = {
      left: actionBtnWidth + this.state.spaceBetween,
      top: offsetTop
    }

    if (this.props.position == 'center') positionStyles = {
      right: actionBtnWidth/2 + width/2 + this.state.spaceBetween,
      top: offsetTop
    }

    return [styles.actionTextView, positionStyles, bgStyle];
  }
}

const styles = StyleSheet.create({
  actionButtonWrap: {
    width
  },
  actionButton: {
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
    paddingTop: 2,
    shadowOpacity: 0.3,
    shadowOffset: {
      width: 0, height: 1,
    },
    shadowColor: '#444',
    shadowRadius: 1,
  },
  actionTextView: {
    position: 'absolute',
    paddingVertical: 4,
    paddingHorizontal: 10,
    borderRadius: 3,
    shadowOpacity: 0.3,
    shadowOffset: {
      width: 0, height: 1,
    },
    shadowColor: '#444',
    shadowRadius: 1,
  },
  actionText: {
    flex: 1,
    fontSize: 14,
  }
});
<|endoftext|>


<commit_before>import React from "react";
import { connect } from "react-redux";
import { push } from "redux-router";

import CircularProgress from 'material-ui/CircularProgress';

import { Actions as AppActions } from "../App/redux/actions";
import { Actions as DashboardActions, ActionKeyStore as DashboardActionKeyStore } from "../../utils/dashboards/redux/actions"

class DashboardView extends React.Component {

    componentWillMount() {
        this.props.setPageTitle("Dashboard");
        this.props.fetchDashboardConfiguration(this.props.params.dashboardID);
    };

    render() {
        return (

                    This dashboard component is loading the configuration file...

                {(() => {
                    if (this.props.error){
                        return
{this.props.error}

                    }

                    if (this.props.configuration) {
                        let configuration = this.props.configuration.toJS();
                        return
#{configuration.id} - {configuration.title}

                    }

                    return <CircularProgress color="#eeeeee"/>
                })()}

        );
    }
}

const mapStateToProps = (state, ownProps) => ({

    configuration: state.dashboards.getIn([
        DashboardActionKeyStore.KEY_STORE_DASHBOARDS,
        ownProps.params.dashboardID,
        DashboardActionKeyStore.KEY_STORE_DATA
    ]),

    fetching: state.dashboards.getIn([
        DashboardActionKeyStore.KEY_STORE_DASHBOARDS,
        ownProps.params.dashboardID,
        DashboardActionKeyStore.KEY_STORE_IS_FETCHING
    ]),

    error: state.dashboards.getIn([
        DashboardActionKeyStore.KEY_STORE_DASHBOARDS,
        ownProps.params.dashboardID,
        DashboardActionKeyStore.KEY_STORE_ERROR
    ])
});

const actionCreators = (dispatch) => ({
    setPageTitle: function(aTitle) {
        dispatch(AppActions.updateTitle(aTitle));
    },
    fetchDashboardConfiguration: function(dashboardID) {
        dispatch(DashboardActions.fetch(dashboardID));
    }
 });

export default connect(mapStateToProps, actionCreators)(DashboardView);
<commit_msg>Refactor dashboard index<commit_after>import React from "react";
import { connect } from "react-redux";
import { push } from "redux-router";

import CircularProgress from 'material-ui/CircularProgress';

import { Actions as AppActions } from "../App/redux/actions";
import { Actions as DashboardActions, ActionKeyStore as DashboardActionKeyStore } from "../../utils/dashboards/redux/actions"

class DashboardView extends React.Component {

    componentWillMount() {
        this.props.setPageTitle("Dashboard");
        this.props.fetchDashboardConfiguration(this.props.params.dashboardID);
    };

    render() {
        return (

                {(() => {
                    if (this.props.fetching)
                        return

                            <CircularProgress color="#eeeeee"/>
                            This dashboard component is loading the configuration file...

                    if (this.props.error)
                        return
{this.props.error}

                    if (this.props.configuration) {
                        let configuration = this.props.configuration.toJS();
                        return
#{configuration.id} - {configuration.title}

                    }
                })()}

        );
    }
}

const mapStateToProps = (state, ownProps) => ({

    configuration: state.dashboards.getIn([
        DashboardActionKeyStore.KEY_STORE_DASHBOARDS,
        ownProps.params.dashboardID,
        DashboardActionKeyStore.KEY_STORE_DATA
    ]),

    fetching: state.dashboards.getIn([
        DashboardActionKeyStore.KEY_STORE_DASHBOARDS,
        ownProps.params.dashboardID,
        DashboardActionKeyStore.KEY_STORE_IS_FETCHING
    ]),

    error: state.dashboards.getIn([
        DashboardActionKeyStore.KEY_STORE_DASHBOARDS,
        ownProps.params.dashboardID,
        DashboardActionKeyStore.KEY_STORE_ERROR
    ])
});

const actionCreators = (dispatch) => ({
    setPageTitle: function(aTitle) {
        dispatch(AppActions.updateTitle(aTitle));
    },
    fetchDashboardConfiguration: function(dashboardID) {
        dispatch(DashboardActions.fetch(dashboardID));
    }
 });

export default connect(mapStateToProps, actionCreators)(DashboardView);
<|endoftext|>


<commit_before>const path = require('path')
const os = require('os')
const fs = require('fs')
const babel = require('@babel/core')
const PQueue = require('p-queue').default

const { getSources } = require('./utils')

let babelrc

try {
  babelrc = require(path.join(process.cwd(), '.babelrc'))
} catch (e) {
  babelrc = require('../.babelrc')
}

const babelOptions = {
  ignore: babelrc.ignore,
  babelrc: false,
  sourceMaps: true,
  presets: [
    [require('@babel/preset-typescript'), {
      allExtensions: true,
      isTSX: true,
    }],
  ],
  plugins: [
    require('@babel/plugin-proposal-class-properties'),
    require('babel-plugin-transform-inline-environment-variables'),
    [require('babel-plugin-bare-import-rewrite'), {
      resolveDirectories: ['.'],
    }],
  ],
}

const queue = new PQueue({ concurrency: os.cpus().length })

module.exports = async sources => {
  sources = sources || await getSources()

  queue.clear()

  // touch the .js files so they can be resolved successfully
  await Promise.all(sources.map(sourceFile => {
    const jsName = getJsName(sourceFile)
    return fs.promises.writeFile(jsName, '')
  }))

  await sources.map(sourceFile => queue.add(async () => {
    const jsName = getJsName(sourceFile)
    const mapName = `${jsName}.map`

    const { code, map } = await babel.transformFileAsync(sourceFile, babelOptions)

    const jsStream = fs.createWriteStream(jsName)
    jsStream.write(code)
    jsStream.end(`\n//# sourceMappingURL=${path.basename(mapName)}`)

    const mapStream = fs.createWriteStream(mapName)
    mapStream.end(JSON.stringify(map, null, '\t'))

    return Promise.all([
      new Promise(resolve => jsStream.on('close', resolve)),
      new Promise(resolve => mapStream.on('close', resolve)),
    ])
  }))
}

module.exports.babelOptions = babelOptions

function getJsName (tsName) {
  return tsName.replace(/\.[jt]sx?$/, '.js')
}
<commit_msg>fix: correct esnext script promise<commit_after>const path = require('path')
const os = require('os')
const fs = require('fs')
const babel = require('@babel/core')
const PQueue = require('p-queue').default

const { getSources } = require('./utils')

let babelrc

try {
  babelrc = require(path.join(process.cwd(), '.babelrc'))
} catch (e) {
  babelrc = require('../.babelrc')
}

const babelOptions = {
  ignore: babelrc.ignore,
  babelrc: false,
  sourceMaps: true,
  presets: [
    [require('@babel/preset-typescript'), {
      allExtensions: true,
      isTSX: true,
    }],
  ],
  plugins: [
    require('@babel/plugin-proposal-class-properties'),
    require('babel-plugin-transform-inline-environment-variables'),
    [require('babel-plugin-bare-import-rewrite'), {
      resolveDirectories: ['.'],
    }],
  ],
}

const queue = new PQueue({ concurrency: os.cpus().length })

module.exports = async sources => {
  sources = sources || await getSources()

  queue.clear()

  // touch the .js files so they can be resolved successfully
  await Promise.all(sources.map(sourceFile => {
    const jsName = getJsName(sourceFile)
    return fs.promises.writeFile(jsName, '')
  }))

  await Promise.all(sources.map(sourceFile => queue.add(async () => {
    const jsName = getJsName(sourceFile)
    const mapName = `${jsName}.map`

    const { code, map } = await babel.transformFileAsync(sourceFile, babelOptions)

    const jsStream = fs.createWriteStream(jsName)
    jsStream.write(code)
    jsStream.end(`\n//# sourceMappingURL=${path.basename(mapName)}`)

    const mapStream = fs.createWriteStream(mapName)
    mapStream.end(JSON.stringify(map, null, '\t'))

    return Promise.all([
      new Promise(resolve => jsStream.on('close', resolve)),
      new Promise(resolve => mapStream.on('close', resolve)),
    ])
  })))
}

module.exports.babelOptions = babelOptions

function getJsName (tsName) {
  return tsName.replace(/\.[jt]sx?$/, '.js')
}
<|endoftext|>