<commit_before>import React from 'react'
import Formsy from 'formsy-react'
import Modal from 'react-modal';
import MyInput from '../components/my-input'
import MySelect from '../components/my-select'
import MyTextarea from '../components/my-textarea'
import SectionTitle from '../components/section-title'
import HttpHelpers from '../utils/http-helpers'
var _ = require('lodash');

const redirectUrl = (window.location.href.split("/\?", 2)[0] + '/step2').replace("//step2", "/step2");
const randomEmail = Math.random().toString(36).substr(2,10);

const FormContainer = React.createClass({
  getInitialState() {
    return {
      canSubmit: false,
      isLoading: false,
      validationErrors: {},
      serverErrorMsg: false,
      serverSuccessMsg: false,
      showSubmissionModal: false,
      loading: {
        'street': false,
        'suburb': false,
      },
      suburbs: ['Enter Postcode...'],
      streets: ['Choose Suburb...'],
      postcode: '0000',
      country: 'au',
    };
  },
  submit(data) {
    if (data.mnames === undefined) { data.mnames = ""}
    if (data.referred_by === undefined) { data.referred_by = ""}
    if (data.member_comment === undefined) { data.member_comment = ""}
    data.dob = data.dobYear + '-' + data.dobMonth + '-' + data.dobDay + 'T12:00:00';
    data.address = _.join([data.addr_street_no, data.addr_street, data.addr_suburb, data.addr_postcode], "; ");
    data.name = _.join([data.fname, data.mnames, data.lname], ", ");

    this.setState({isLoading: true, showSubmissionModal: true});
    HttpHelpers.sendForm(data, function(response){

      if (__DEV__) {
        console.log(response);
        console.log(data);
      }

      if (response.ok && response.status === 200 && response.body.success === true) {
        this.setState({
          isLoading: false,
          serverSuccessMsg: "Success"
        });
        setTimeout(function() {
          window.location.assign(redirectUrl)
        }, 1500);

        ga('send', {hitType: 'event', eventCategory: 'Membership Form', eventAction: 'Submission'});
        fbq('track', 'Complete Registration');
        fbq('track', 'NewMember');  // a different pixel thing to the above, keep both.

      } else if (response.status === 409) {
        console.log('Duplicate email detected');
        this.setState({
          isLoading: false,
          serverErrorMsg: "Error. Email already exists. Please update details instead of re-registering."
        });
      } else {
        this.setState({
          isLoading: false,
          serverErrorMsg: "Server error, " + response.statusText ? response.statusText : null
        });
      }
    }.bind(this))
  },
  enableButton() {
    this.setState({ canSubmit: true });
  },
  disableButton() {
    this.setState({ canSubmit: false });
  },
  closeModal() {
    this.setState({ showSubmissionModal: false });
  },

  checkPC(evt) {
    const pcTest = /\d{4}/;
    const pc = evt.currentTarget.value;
    console.log(pc);
    if (pcTest.test(pc)) {
      this.updateSuburbs(pc);
    }
  },

  checkSuburb(evt) {
    const suburb = evt.currentTarget.value;
    this.updateStreets(suburb);
  },

  updateSuburbs(pc){
    this.setState({loading: { suburb: true }, suburbs: ['Loading...'], postcode: pc});
    const outer = this;
    const setStateUnk = function() { outer.setState({suburbs: ["Unknown Postcode"]}); };
    HttpHelpers.getSuburbs(pc, function(err, resp){
      if (err) {
        console.log(err);
        setStateUnk();
      } else {
        console.log(resp);
        if (resp.body.suburbs.length == 0)
          setStateUnk();
        else {
          outer.setState({suburbs: _.concat(["Choose Suburb..."], resp.body.suburbs)});
          outer.updateStreets(resp.body.suburbs[0]);
        }
      }
    });
  },

  updateStreets(suburb){
    const outer = this;
    this.setState({loading: { street: true }, streets:["Loading..."], suburb: suburb});
    HttpHelpers.getStreets(this.state.postcode, suburb, function(err, resp){
      if(err){
        console.log(err);
        outer.setState({streets:["Unknown Suburb"]});
      } else {
        console.log(resp);
        outer.setState({streets: _.concat(["Choose Street..."], resp.body.streets)});
      }
    })
  },

  writeToState(_key){
    return function(evt){
      let newState = {};
      newState[_key] = evt.currentTarget.value;
      this.setState(newState);
    }
  },

  render() {
    return (
      <Formsy.Form
        onSubmit={this.submit}
        onValid={this.enableButton}
        onInvalid={this.disableButton}
        onChange={this.validateForm}>

Sign up below, it's quick and easy

              Please make sure your details exactly match those on the electoral roll. You can confirm them on the
               AEC website.

          <MyInput
            inputClass="checkbox"
            type="checkbox"
            name="onAECRoll"
            title="I am on the Australian Electoral Roll."
            validationError="First name is required"
            value={false} />

          <SectionTitle text="1. Name"/>

          <MyInput
            inputClass="input"
            name="fname"
            title="Legal first name"
            autocomplete="given-name"
            value={__DEV__ ? "asdf" : ""}
            validationErrors={{
              isRequired: 'First name is required'
            }}
            required />

            <MyInput
              inputClass="input"
              name="mnames"
              autocomplete="false"
              title="Legal middle name"
              value={__DEV__ ? "asdf" : ""}
              validationErrors={{
                isSpecialWords: 'Only letters please'
              }}
              formNoValidate />

          <MyInput
            inputClass="input"
            name="lname"
            autocomplete="family-name"
            title="Legal last name"
            value={__DEV__ ? "asdf" : ""}
            validationErrors={{
              isRequired: 'First name is required'
            }}
            required />

          <SectionTitle text="2. Address"/>

          <MySelect
            inputClass="input"
            name="addr_country"
            title="Country"
            validationError="Country Required"
            options={[{title: 'Australia', value: 'au'}]}
            onChange={this.writeToState('country')}
            />

          <MyInput
            inputClass="input"
            name="addr_postcode"
            title="Postcode"
            validations={_.includes(['au'], this.state.country) ? "isNumeric,isLength:4" : null}
            pattern={_.includes(['au'], this.state.country) ? "\\d*" : ""}
            value={__DEV__ ? "2000" : ""}
            validationErrors={{
              isRequired: 'Postcode required',
              isNumeric: 'Only numbers allowed',
              isLength: 'Length needs to be 4 digits'
            }}
            onChange={this.checkPC}
            required />

          <MySelect
            inputClass="input"
            name="addr_suburb"
            title="Suburb"
            validationError="Suburb required"
            options={this.state.suburbs}
            value={__DEV__ ? "HAYMARKET (NSW)" : ""}
            disabled={this.state.suburbs[0] == 'Loading...'}
            onChange={this.checkSuburb}
            validations={{
              notDefault: function(values, value){
                return !_.includes(value, '...') ? true : "Must choose a suburb";
              }
            }}
            required />

            <MyInput
              inputClass="input"
              className="col-4 inline-block px1 relative"
              name="addr_street_no"
              title="Unit / Street No."
              validationError="Unit and Street Number required"
              placeholder="eg: u32 / 117"
              value={__DEV__ ? "13 / 37" : ""}
              required
              />

            <MySelect
              className="col-8 mx-auto inline-block px1 relative"
              inputClass="input"
              name="addr_street"
              title="Street"
              validationError="Street address is required"
              value={__DEV__ ? "asdf" : ""}
              disabled={this.state.streets[0] == 'Loading...'}
              validationErrors={{
                isRequired: 'Street address required'
              }}
              options={this.state.streets}
              required />

          <SectionTitle text="3. Date of Birth" infoText="(Required by AEC)"/>

              <MyInput
                inputClass="input"
                name="dobDay"
                title="Day"
                placeholder="DD"
                pattern="\d*"
                value={__DEV__ ? "01" : ""}
                validations={{
                  isNumeric: true,
                  isLength: 2,
                  matchRegexp: /(0[1-9]|[12]\d|3[01])/
                }}
                validationErrors={{
                  isRequired: 'Day required',
                  isNumeric: 'Only numbers allowed',
                  isLength: 'Length must be 2 digits',
                  matchRegexp: 'Invalid date range'
                }}
                required />

              <MyInput
                inputClass="input"
                name="dobMonth"
                title="Month"
                placeholder="MM"
                pattern="\d*"
                value={__DEV__ ? "01" : ""}
                validations={{
                  isNumeric: true,
                  isLength: 2,
                  matchRegexp: /^(0[1-9]|1[0-2])$/
                }}
                validationErrors={{
                  isRequired: 'Month required',
                  isNumeric: 'Only numbers allowed',
                  isLength: 'Month must be 2 digits',
                  matchRegexp: 'Invalid date range'
                }}
                required />

              <MyInput
                inputClass="input"
                name="dobYear"
                title="Year"
                placeholder="YYYY"
                pattern="\d*"
                value={__DEV__ ? "2000" : ""}
                validations={{
                  isNumeric: true,
                  isLength: 4,
                  matchRegexp: /^(190[0-9]|19[1-9]\d|200\d|201[0-6])$/
                }}
                validationErrors={{
                  isRequired: 'Year required',
                  isNumeric: 'Only numbers allowed',
                  isLength: 'Year must be 4 digits',
                  matchRegexp: 'Invalid date range'
                }}
                required />

          <SectionTitle text="4. Contact details"/>
          <MyInput
            inputClass="input"
            type="tel"
            name="contact_number"
            pattern="\d*"
            title="Phone"
            value={__DEV__ ? "1234567890" : ""}
            validations={{
              minLength: 8
            }}
            validationErrors={{
              isRequired: 'Phone number is required',
              minLength: 'Needs to be at least 8 digits.'
            }}
            required />

          <MyInput
            inputClass="input"
            name="email"
            title="Email"
            type="email"
            pattern="[^ @]*@[^ @]*"
            value={__DEV__ ? randomEmail + "@xk.io" : ""}
            validations="isEmail"
            validationError="This is not a valid email"
            autocomplete="email"
            required />

          <SectionTitle text="5. Get Involved"/>

          { this.props.onReferrer
            ?
            <MyInput
              inputClass="input hide"
              name="referred_by"
              value={this.props.onReferrer} />
             :

                <MyInput
                  inputClass="input"
                  name="referred_by"
                  title="How did you hear about Flux?"
                  subtext="(optional)" />

}

          {/*<MyInput
            inputClass="input"
            type="checkbox"
            name="mailing-list"
            title="Send me Flux news and important updates."
            value={true}
             />*/}

         <MyTextarea
             rows="3"
             inputClass="input"
             name="member_comment"
             title="Comments / Notes"
             value={__DEV__ ? "DEV SUBMISSION - PLEASE DELETE" : ""}
             subtext="(Optional, Anything you'd like to add, about yourself, us, or anything, really.)" />

           <MyInput
             inputClass="input"
             type="checkbox"
             name="volunteer"
             title="I'm interested in volunteering"
             value={false}
              />

              <button type="submit" className="h3 btn btn-primary" disabled={!this.state.canSubmit}>Submit chevron_right</button>

            {!this.state.canSubmit
              &&

                *

You can't submit until you fill out all required fields

}

             <Modal
              isOpen={this.state.showSubmissionModal}
              contentLabel="Processing Registration"
              onRequestClose={this.closeModal}
              style={{
                overlay: {
                  backgroundColor: "rgba(20, 20, 20, 0.5)",
                },
                content: {

                }
              }}
             >
               {this.state.isLoading
                ?

Registering...

                : this.state.serverSuccessMsg
                ?

{this.state.serverSuccessMsg}

                    Redirecting...

                : this.state.serverErrorMsg
                ?

{this.state.serverErrorMsg}

                    <button className="btn btn-primary mx-auto h1" onClick={this.closeModal}>Close</button>

                : null}
             </Modal>

            lock
            Your details will be kept absolutely confidential and will only be used for party business.

      </Formsy.Form>
    );
  }
});

export default FormContainer;
<commit_msg>Fix street alignment on phones<commit_after>import React from 'react'
import Formsy from 'formsy-react'
import Modal from 'react-modal';
import MyInput from '../components/my-input'
import MySelect from '../components/my-select'
import MyTextarea from '../components/my-textarea'
import SectionTitle from '../components/section-title'
import HttpHelpers from '../utils/http-helpers'
var _ = require('lodash');

const redirectUrl = (window.location.href.split("/\?", 2)[0] + '/step2').replace("//step2", "/step2");
const randomEmail = Math.random().toString(36).substr(2,10);

const FormContainer = React.createClass({
  getInitialState() {
    return {
      canSubmit: false,
      isLoading: false,
      validationErrors: {},
      serverErrorMsg: false,
      serverSuccessMsg: false,
      showSubmissionModal: false,
      loading: {
        'street': false,
        'suburb': false,
      },
      suburbs: ['Enter Postcode...'],
      streets: ['Choose Suburb...'],
      postcode: '0000',
      country: 'au',
    };
  },
  submit(data) {
    if (data.mnames === undefined) { data.mnames = ""}
    if (data.referred_by === undefined) { data.referred_by = ""}
    if (data.member_comment === undefined) { data.member_comment = ""}
    data.dob = data.dobYear + '-' + data.dobMonth + '-' + data.dobDay + 'T12:00:00';
    data.address = _.join([data.addr_street_no, data.addr_street, data.addr_suburb, data.addr_postcode], "; ");
    data.name = _.join([data.fname, data.mnames, data.lname], ", ");

    this.setState({isLoading: true, showSubmissionModal: true});
    HttpHelpers.sendForm(data, function(response){

      if (__DEV__) {
        console.log(response);
        console.log(data);
      }

      if (response.ok && response.status === 200 && response.body.success === true) {
        this.setState({
          isLoading: false,
          serverSuccessMsg: "Success"
        });
        setTimeout(function() {
          window.location.assign(redirectUrl)
        }, 1500);

        ga('send', {hitType: 'event', eventCategory: 'Membership Form', eventAction: 'Submission'});
        fbq('track', 'Complete Registration');
        fbq('track', 'NewMember');  // a different pixel thing to the above, keep both.

      } else if (response.status === 409) {
        console.log('Duplicate email detected');
        this.setState({
          isLoading: false,
          serverErrorMsg: "Error. Email already exists. Please update details instead of re-registering."
        });
      } else {
        this.setState({
          isLoading: false,
          serverErrorMsg: "Server error, " + response.statusText ? response.statusText : null
        });
      }
    }.bind(this))
  },
  enableButton() {
    this.setState({ canSubmit: true });
  },
  disableButton() {
    this.setState({ canSubmit: false });
  },
  closeModal() {
    this.setState({ showSubmissionModal: false });
  },

  checkPC(evt) {
    const pcTest = /\d{4}/;
    const pc = evt.currentTarget.value;
    console.log(pc);
    if (pcTest.test(pc)) {
      this.updateSuburbs(pc);
    }
  },

  checkSuburb(evt) {
    const suburb = evt.currentTarget.value;
    this.updateStreets(suburb);
  },

  updateSuburbs(pc){
    this.setState({loading: { suburb: true }, suburbs: ['Loading...'], postcode: pc});
    const outer = this;
    const setStateUnk = function() { outer.setState({suburbs: ["Unknown Postcode"]}); };
    HttpHelpers.getSuburbs(pc, function(err, resp){
      if (err) {
        console.log(err);
        setStateUnk();
      } else {
        console.log(resp);
        if (resp.body.suburbs.length == 0)
          setStateUnk();
        else {
          outer.setState({suburbs: _.concat(["Choose Suburb..."], resp.body.suburbs)});
          outer.updateStreets(resp.body.suburbs[0]);
        }
      }
    });
  },

  updateStreets(suburb){
    const outer = this;
    this.setState({loading: { street: true }, streets:["Loading..."], suburb: suburb});
    HttpHelpers.getStreets(this.state.postcode, suburb, function(err, resp){
      if(err){
        console.log(err);
        outer.setState({streets:["Unknown Suburb"]});
      } else {
        console.log(resp);
        outer.setState({streets: _.concat(["Choose Street..."], resp.body.streets)});
      }
    })
  },

  writeToState(_key){
    return function(evt){
      let newState = {};
      newState[_key] = evt.currentTarget.value;
      this.setState(newState);
    }
  },

  render() {
    return (
      <Formsy.Form
        onSubmit={this.submit}
        onValid={this.enableButton}
        onInvalid={this.disableButton}
        onChange={this.validateForm}>

Sign up below, it's quick and easy

              Please make sure your details exactly match those on the electoral roll. You can confirm them on the
               AEC website.

          <MyInput
            inputClass="checkbox"
            type="checkbox"
            name="onAECRoll"
            title="I am on the Australian Electoral Roll."
            validationError="First name is required"
            value={false} />

          <SectionTitle text="1. Name"/>

          <MyInput
            inputClass="input"
            name="fname"
            title="Legal first name"
            autocomplete="given-name"
            value={__DEV__ ? "asdf" : ""}
            validationErrors={{
              isRequired: 'First name is required'
            }}
            required />

            <MyInput
              inputClass="input"
              name="mnames"
              autocomplete="false"
              title="Legal middle name"
              value={__DEV__ ? "asdf" : ""}
              validationErrors={{
                isSpecialWords: 'Only letters please'
              }}
              formNoValidate />

          <MyInput
            inputClass="input"
            name="lname"
            autocomplete="family-name"
            title="Legal last name"
            value={__DEV__ ? "asdf" : ""}
            validationErrors={{
              isRequired: 'First name is required'
            }}
            required />

          <SectionTitle text="2. Address"/>

          <MySelect
            inputClass="input"
            name="addr_country"
            title="Country"
            validationError="Country Required"
            options={[{title: 'Australia', value: 'au'}]}
            onChange={this.writeToState('country')}
            />

          <MyInput
            inputClass="input"
            name="addr_postcode"
            title="Postcode"
            validations={_.includes(['au'], this.state.country) ? "isNumeric,isLength:4" : null}
            pattern={_.includes(['au'], this.state.country) ? "\\d*" : ""}
            value={__DEV__ ? "2000" : ""}
            validationErrors={{
              isRequired: 'Postcode required',
              isNumeric: 'Only numbers allowed',
              isLength: 'Length needs to be 4 digits'
            }}
            onChange={this.checkPC}
            required />

          <MySelect
            inputClass="input"
            name="addr_suburb"
            title="Suburb"
            validationError="Suburb required"
            options={this.state.suburbs}
            value={__DEV__ ? "HAYMARKET (NSW)" : ""}
            disabled={this.state.suburbs[0] == 'Loading...'}
            onChange={this.checkSuburb}
            validations={{
              notDefault: function(values, value){
                return !_.includes(value, '...') ? true : "Must choose a suburb";
              }
            }}
            required />

            <MyInput
              inputClass="input"
              className="col-4 inline-block px1"
              name="addr_street_no"
              title="Unit / Street No."
              validationError="Unit and Street Number required"
              placeholder="eg: u32 / 117"
              value={__DEV__ ? "13 / 37" : ""}
              required
              />

            <MySelect
              className="col-8 mx-auto inline-block px1 absolute bottom-0 right-0 pb1"
              inputClass="input"
              name="addr_street"
              title="Street"
              validationError="Street address is required"
              value={__DEV__ ? "asdf" : ""}
              disabled={this.state.streets[0] == 'Loading...'}
              validationErrors={{
                isRequired: 'Street address required'
              }}
              options={this.state.streets}
              required />

          <SectionTitle text="3. Date of Birth" infoText="(Required by AEC)"/>

              <MyInput
                inputClass="input"
                name="dobDay"
                title="Day"
                placeholder="DD"
                pattern="\d*"
                value={__DEV__ ? "01" : ""}
                validations={{
                  isNumeric: true,
                  isLength: 2,
                  matchRegexp: /(0[1-9]|[12]\d|3[01])/
                }}
                validationErrors={{
                  isRequired: 'Day required',
                  isNumeric: 'Only numbers allowed',
                  isLength: 'Length must be 2 digits',
                  matchRegexp: 'Invalid date range'
                }}
                required />

              <MyInput
                inputClass="input"
                name="dobMonth"
                title="Month"
                placeholder="MM"
                pattern="\d*"
                value={__DEV__ ? "01" : ""}
                validations={{
                  isNumeric: true,
                  isLength: 2,
                  matchRegexp: /^(0[1-9]|1[0-2])$/
                }}
                validationErrors={{
                  isRequired: 'Month required',
                  isNumeric: 'Only numbers allowed',
                  isLength: 'Month must be 2 digits',
                  matchRegexp: 'Invalid date range'
                }}
                required />

              <MyInput
                inputClass="input"
                name="dobYear"
                title="Year"
                placeholder="YYYY"
                pattern="\d*"
                value={__DEV__ ? "2000" : ""}
                validations={{
                  isNumeric: true,
                  isLength: 4,
                  matchRegexp: /^(190[0-9]|19[1-9]\d|200\d|201[0-6])$/
                }}
                validationErrors={{
                  isRequired: 'Year required',
                  isNumeric: 'Only numbers allowed',
                  isLength: 'Year must be 4 digits',
                  matchRegexp: 'Invalid date range'
                }}
                required />

          <SectionTitle text="4. Contact details"/>
          <MyInput
            inputClass="input"
            type="tel"
            name="contact_number"
            pattern="\d*"
            title="Phone"
            value={__DEV__ ? "1234567890" : ""}
            validations={{
              minLength: 8
            }}
            validationErrors={{
              isRequired: 'Phone number is required',
              minLength: 'Needs to be at least 8 digits.'
            }}
            required />

          <MyInput
            inputClass="input"
            name="email"
            title="Email"
            type="email"
            pattern="[^ @]*@[^ @]*"
            value={__DEV__ ? randomEmail + "@xk.io" : ""}
            validations="isEmail"
            validationError="This is not a valid email"
            autocomplete="email"
            required />

          <SectionTitle text="5. Get Involved"/>

          { this.props.onReferrer
            ?
            <MyInput
              inputClass="input hide"
              name="referred_by"
              value={this.props.onReferrer} />
             :

                <MyInput
                  inputClass="input"
                  name="referred_by"
                  title="How did you hear about Flux?"
                  subtext="(optional)" />

}

          {/*<MyInput
            inputClass="input"
            type="checkbox"
            name="mailing-list"
            title="Send me Flux news and important updates."
            value={true}
             />*/}

         <MyTextarea
             rows="3"
             inputClass="input"
             name="member_comment"
             title="Comments / Notes"
             value={__DEV__ ? "DEV SUBMISSION - PLEASE DELETE" : ""}
             subtext="(Optional, Anything you'd like to add, about yourself, us, or anything, really.)" />

           <MyInput
             inputClass="input"
             type="checkbox"
             name="volunteer"
             title="I'm interested in volunteering"
             value={false}
              />

              <button type="submit" className="h3 btn btn-primary" disabled={!this.state.canSubmit}>Submit chevron_right</button>

            {!this.state.canSubmit
              &&

                *

You can't submit until you fill out all required fields

}

             <Modal
              isOpen={this.state.showSubmissionModal}
              contentLabel="Processing Registration"
              onRequestClose={this.closeModal}
              style={{
                overlay: {
                  backgroundColor: "rgba(20, 20, 20, 0.5)",
                },
                content: {

                }
              }}
             >
               {this.state.isLoading
                ?

Registering...

                : this.state.serverSuccessMsg
                ?

{this.state.serverSuccessMsg}

                    Redirecting...

                : this.state.serverErrorMsg
                ?

{this.state.serverErrorMsg}

                    <button className="btn btn-primary mx-auto h1" onClick={this.closeModal}>Close</button>

                : null}
             </Modal>

            lock
            Your details will be kept absolutely confidential and will only be used for party business.

      </Formsy.Form>
    );
  }
});

export default FormContainer;
<|endoftext|>


<commit_before>Frog.Uploader = new Class({
    Implements: Events,
    initialize: function(id) {
        var self = this;
        this.id = id;
        this.element = new Element('div', {'id': 'frog_upload'}).inject(document.body, 'top');
        var list = new Element('div', {'id': 'frog_upload_files'}).inject(this.element);
        var uploader = new plupload.Uploader({
            runtimes: 'html5',
            browse_button: 'frogBrowseButton',
            drop_element: 'frog_upload',
            container: 'frog_upload',
            max_file_size: '500mb',
            url: '/frog/',
            headers: {"X-CSRFToken": Cookie.read('csrftoken')},
            multipart_params: {
                'galleries': this.id.toString()
            },
            filters: [
                {title: "Image files", extensions: "jpg,png"},
                {title: "Video files", extensions: "mp4,avi,mov"}
            ]
        });

        uploader.init();

        uploader.bind('FilesAdded', function(up, files) {
            if (!self.element.isVisible()) {
                self.element.show();
                self.setupUI();
                self.uploaderList.show();
            }
            files.each(function(f) {
                new Request.JSON({
                    url: '/frog/isunique',
                    onSuccess: function(res) {
                        obj = {
                            id: f.id,
                            file: f.name,
                            size: f.size,
                            percent: 0,
                            unique: res.value === true
                        }
                        if (obj.isUnique) {
                            obj.date = new Date(Date.now());
                        }
                        else {
                            obj.date = new Date(res.value.created);
                        }
                        var item = self.uploaderList.store.add(obj);
                    }
                }).GET({path:f.name})
            });
        });

        uploader.bind('UploadProgress', function(up, file) {
            self.uploaderList.store.getById(file.id).set('percent', file.percent);
        });

        uploader.bind('UploadComplete', function(up, files) {
            self.element.hide();
            self.uploaderList.store.removeAll();
            self.uploaderList.hide();
            self.fireEvent('onComplete', [this]);
        });

        this.uploader = uploader;

        document.body.addEventListener('dragenter', function() {
            self.element.show();
            self.setupUI();
            self.uploaderList.show();
        }, false);
    },
    toElement: function() {
        return this.element;
    },
    setupUI: function() {
        var self = this;
        if (this.uploaderList) {
            return this.uploaderList;
        }

        Ext.require(['*']);
        var store = Ext.create('Ext.data.ArrayStore', {
            fields: [
                {name: 'id'},
                {name: 'file'},
                {name: 'size', type: 'int'},
                {name: 'percent', type: 'int'},
                {name: 'unique', type: 'bool'},
                {name: 'date', type: 'date'}
            ]
        });
        var grid = Ext.create('Ext.grid.Panel', {
            store: store,
            columns: [
                {
                    text     : 'File',
                    flex     : 6,
                    sortable : false,
                    dataIndex: 'file'
                },
                {
                    text     : 'Size',
                    flex     : 1,
                    sortable : false,
                    dataIndex: 'size'
                },
                {
                    text: 'Created',
                    flex: 2,
                    sortable: false,
                    dataIndex: 'date',
                    xtype: 'datecolumn',
                    format:'Y-m-d'
                },
                {
                    text     : '%',
                    flex     : 1,
                    sortable : false,
                    dataIndex: 'percent'
                },
                {
                    xtype: 'actioncolumn',
                    flex: 1,
                    sortable: false,
                    items: [
                        {
                            text: 'remove',
                            icon: '/static/frog/i/delete.png',
                            handler: function(grid, rowIndex, colIndex) {
                                var rec = store.getAt(rowIndex);
                                var file = self.uploader.getFile(rec.get('id'));
                                self.uploader.removeFile(file);
                                store.remove([rec]);
                            }
                        }
                    ]
                }
            ],
            height: 350,
            width: '100%',
            title: 'Files to Upload',
            renderTo: 'frog_upload_files',
            viewConfig: {
                stripeRows: true,
                getRowClass: function(record) {
                    var c = record.get('unique');
                    return (c) ? '' : 'red';
                }
            }
        });

        var uploadButton = Ext.create('Ext.Button', {
            text: 'Upload Files',
            renderTo: 'frog_upload_files',
            scale: 'large',
            handler: function() {
                self.uploader.start();
            }
        });
        var uploadButton = Ext.create('Ext.Button', {
            text: 'Cancel',
            renderTo: 'frog_upload_files',
            scale: 'large',
            handler: function() {
                self.element.hide();
                self.uploaderList.store.removeAll();
                self.uploaderList.hide();
            }
        });

        this.uploaderList = grid;
    },
})<commit_msg>Items will now be removed from the uploader as they are completed<commit_after>Frog.Uploader = new Class({
    Implements: Events,
    initialize: function(id) {
        var self = this;
        this.id = id;
        this.element = new Element('div', {'id': 'frog_upload'}).inject(document.body, 'top');
        var list = new Element('div', {'id': 'frog_upload_files'}).inject(this.element);
        var uploader = new plupload.Uploader({
            runtimes: 'html5',
            browse_button: 'frogBrowseButton',
            drop_element: 'frog_upload',
            container: 'frog_upload',
            max_file_size: '500mb',
            url: '/frog/',
            headers: {"X-CSRFToken": Cookie.read('csrftoken')},
            multipart_params: {
                'galleries': this.id.toString()
            },
            filters: [
                {title: "Image files", extensions: "jpg,png"},
                {title: "Video files", extensions: "mp4,avi,mov"}
            ]
        });

        uploader.init();

        uploader.bind('FilesAdded', function(up, files) {
            if (!self.element.isVisible()) {
                self.element.show();
                self.setupUI();
                self.uploaderList.show();
            }
            files.each(function(f) {
                new Request.JSON({
                    url: '/frog/isunique',
                    onSuccess: function(res) {
                        obj = {
                            id: f.id,
                            file: f.name,
                            size: f.size,
                            percent: 0,
                            unique: res.value === true
                        }
                        if (obj.isUnique) {
                            obj.date = new Date();
                        }
                        else {
                            obj.date = new Date(res.value.created);
                        }
                        var item = self.uploaderList.store.add(obj);
                    }
                }).GET({path:f.name})
            });
        });

        uploader.bind('UploadProgress', function(up, file) {
            self.uploaderList.store.getById(file.id).set('percent', file.percent);
        });

        uploader.bind('FileUploaded', function(up, file, res) {
            var index = self.uploaderList.store.getById(file.id)
            self.uploaderList.store.remove(index);
        });

        uploader.bind('UploadComplete', function(up, files) {
            self.element.hide();
            self.uploaderList.store.removeAll();
            self.uploaderList.hide();
            self.fireEvent('onComplete', [this]);
        });

        this.uploader = uploader;

        document.body.addEventListener('dragenter', function() {
            self.element.show();
            self.setupUI();
            self.uploaderList.show();
        }, false);
    },
    toElement: function() {
        return this.element;
    },
    setupUI: function() {
        var self = this;
        if (this.uploaderList) {
            return this.uploaderList;
        }

        Ext.require(['*']);
        var store = Ext.create('Ext.data.ArrayStore', {
            fields: [
                {name: 'id'},
                {name: 'file'},
                {name: 'size', type: 'int'},
                {name: 'percent', type: 'int'},
                {name: 'unique', type: 'bool'},
                {name: 'date', type: 'date'}
            ]
        });
        var grid = Ext.create('Ext.grid.Panel', {
            store: store,
            columns: [
                {
                    text     : 'File',
                    flex     : 6,
                    sortable : false,
                    dataIndex: 'file'
                },
                {
                    text     : 'Size',
                    flex     : 1,
                    sortable : false,
                    dataIndex: 'size'
                },
                {
                    text: 'Created',
                    flex: 2,
                    sortable: false,
                    dataIndex: 'date',
                    xtype: 'datecolumn',
                    format:'Y-m-d'
                },
                {
                    text     : '%',
                    flex     : 1,
                    sortable : false,
                    dataIndex: 'percent'
                },
                {
                    xtype: 'actioncolumn',
                    flex: 1,
                    sortable: false,
                    items: [
                        {
                            text: 'remove',
                            icon: '/static/frog/i/delete.png',
                            handler: function(grid, rowIndex, colIndex) {
                                var rec = store.getAt(rowIndex);
                                var file = self.uploader.getFile(rec.get('id'));
                                self.uploader.removeFile(file);
                                store.remove([rec]);
                            }
                        }
                    ]
                }
            ],
            height: 350,
            width: '100%',
            title: 'Files to Upload',
            renderTo: 'frog_upload_files',
            viewConfig: {
                stripeRows: true,
                getRowClass: function(record) {
                    var c = record.get('unique');
                    return (c) ? '' : 'red';
                }
            }
        });

        var uploadButton = Ext.create('Ext.Button', {
            text: 'Upload Files',
            renderTo: 'frog_upload_files',
            scale: 'large',
            handler: function() {
                self.uploader.start();
            }
        });
        var uploadButton = Ext.create('Ext.Button', {
            text: 'Cancel',
            renderTo: 'frog_upload_files',
            scale: 'large',
            handler: function() {
                self.element.hide();
                self.uploaderList.store.removeAll();
                self.uploaderList.hide();
            }
        });

        this.uploaderList = grid;
    },
})<|endoftext|>


<commit_before>import FBSDK, { LoginManager } from 'react-native-fbsdk';
const { LoginButton, AccessToken, ShareDialog } = FBSDK;

export default facebookActions = {

    facebookAction: () => {
      return {
        type: 'IS_AUTHENTICATED',
        payload: AccessToken.getCurrentAccessToken()
        .then((data) => {
          console.log('facebook data change to became payload', data)
          return data
        })
        .catch((err) => {
          console.log(err);
        })
      }
    }
}
<commit_msg>facebook action for log in<commit_after>import FBSDK, { LoginManager } from 'react-native-fbsdk';
const { LoginButton, AccessToken, ShareDialog } = FBSDK;

export default facebookActions = {

    facebookAction: () => {
      return function(dispatch) {
        AccessToken.getCurrentAccessToken()
          .then((data) => {
            console.log('facebook data change to became payload', data)
            dispatch({type: 'IS_AUTHENTICATED', payload: data});
          })
          .catch((err) => {
            console.log('Error: ', err);
          })
      }
    }
}
<|endoftext|>


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

  var $ = require('jquery'),
      network = require('network'),
      latenza = require('latenza'),
      hogan = require('hogan'),
      requests = {},
      nodeinfo = {};

  requests.submission = require('./requests/submission');
  requests.node = require('./requests/node');

  // Return a function that can be called to do the DOM binding given a
  // jQuery DOM object to use as the parent container.
  return function uiSubmission(parentDom) {

    // Use the body element if no parentDom provided
    parentDom = parentDom || $('body');

    function debugDeck() {
        var debug = require('./debug'),
            dummy_requests = require('./dummy/requests'),
            submissionID = null;

        $("#node_button").click(function() {
          latenza.ajax({'url': '/node',
                        'type': 'GET'
          }).done(function(data) {
            debug.write(data, 'GET /node');
          });
        });

        $("#create_new").click(function() {
          requests.submission.root().done(function(data) {
                  submissionID = data['submission_id'];
                  debug.write(data, 'GET /submission');
          });
        });

        $("#send_fields").click(function() {
          if (submissionID) {
            var fields = {"FieldA": "hello", "FieldB": "world!"};
            var path = '/submission/'+submissionID+'/status';
            requests.submission.status_post(submissionID, {'fields': fields}).done(function(data){
              debug.write(data, 'POST '+path);
            });

          } else {
            alert("Run create new first!");
          }
        });

        $("#select_context").click(function() {
          if (submissionID) {
            var path = '/submission/'+submissionID+'/status';
            requests.submission.status_post(submissionID, {'context_selected':
                            nodeinfo.selected_context}).done(function(data){
              debug.write(data, 'POST '+path);
            });

          } else {
            alert("Run create new first!");
          }
        });

        $("#status").click(function() {
          var request = dummy_requests.submissionStatusPost;
          if (submissionID) {
            var path = '/submission/'+submissionID+'/status';
            requests.submission.status_get(submissionID).done(function(data){
              debug.write(data, 'GET '+path);
            });

          } else {
            alert("Run create new first!");
          }
        });

        $("#finalize_button").click(function() {
          if (submissionID) {
            var request = {'proposed_receipt': 'igotnicereceipt',
                           'folder_name': 'My Documents',
                           'folder_description': 'I have lots of warez!'};
            var path = '/submission/'+submissionID+'/finalize';
            latenza.ajax({'url': path,
                          'data': JSON.stringify(request),
                          'type': 'POST'
            }).done(function(data){
              debug.write(data, 'POST '+path);
            });

          } else {
            alert("Run create new first!");
          }
        });
    };

    function renderTemplate(template, data) {
        if (data.help) {
            template += '{{help}}'
        }
        var cTemplate = hogan.compile(template);
        var rendered = cTemplate.render(data);
        // console.log(rendered);
        return rendered;
    };

    var process = {
        string: function(data) {
            var template;
            template = '{{label}}\n';

            template += '<input type="text" name="{{name}}"';
            template +=        'value="{{default}}" placeholder="{{hint}}"';
            template +=        'required="{{required}}"/>';

            return renderTemplate(template, data);
        },

        text: function(data) {
            var template;
            template = '{{label}}\n';
            template += '<textarea name="{{name}}" required={{required}}>{{default}}</textarea>\n';
            return renderTemplate(template, data);
        },

        checkbox: function(data) {
            var template;
            template = '\n';
            template += '<input type="checkbox" name="{{name}}" required={{required}}>{{label}}\n';
            template += '';
            return renderTemplate(template, data);
        },

        radio: function(data) {
            var x,
                template = '',
                parsed_data = data;

            for (x in data.options) {
                parsed_data['label'+x] = data.options[x].label;
                parsed_data['value'+x] = data.options[x].value;
                template += '\n';
                template += '<input type="radio" name="{{name}}" value="{{value'+x+'}}" required={{required}}>\n';
                template += '{{label'+x+'}}\n';
                template += '';
            }
            return renderTemplate(template, parsed_data);
        }
    };

    function incompleteForm() {
    };

    function submitForm(data) {
        // console.log(data);
        var x,
            form = $(data.target.parentElement);

        var inputs = form.find('input');

        for (x in inputs) {
            // console.log(inputs[x]);
        };
        return false;
    };

    function processFields(data) {
        console.log(dummy_requests);
        for (field in data) {
            console.log(data[field]);
        }
        return JSON.stringify(dummy_requests.submissionStatusPost);
    };

    function processForm(form) {
        $('.submissionFormLeft')[0].innerHTML = "";
        $('.submissionFormRight')[0].innerHTML = "";
        $('.submissionForm button').remove();

        var x, target,
            allowed_types = ['string', 'text','checkbox', 'radio'];
        for (x in form) {
          // console.log(form[x].type);
          if (allowed_types.indexOf(form[x].type) != -1) {
            if ((x % 2) == 0) {
              target = $('.submissionFormLeft');
            } else {
              target = $('.submissionFormRight');
            }
            target.append(process[form[x].type](form[x]));
          }
        };
        $('.submissionForm').append('<button id="submit_button">Submit</button>');

        $('#submit_button').click(function(){
          latenza.ajax({'url': '/submission/foobar/status',
                        'data': processFields($(this).serializeArray()),
                        'type': 'POST'
                      }).done(function(data) {
                        var form = $('form');
                        form.hide();
                        var parsed = JSON.parse(data);
                        form.after('
Receipt: '+parsed.receipt+'
');
                            // console.log(data);
                      });
          return false;
        });
    };

    function getContextFields(context_id) {
      for (var name in nodeinfo.contexts) {
        var context = nodeinfo.contexts[name];
        if (context.id == context_id) {
          return context.fields;
        }
      }
    };

    function processContexts(contexts) {
      var context_selector = $("#context_selector"),
          context_id, fields;
      context_selector.change(function(){
        context_id = $('#context_selector option:selected')[0].value;
        nodeinfo.selected_context = contexts[0].id;
        fields = getContextFields(context_id);
        processForm(fields);
      });
      for (var i in contexts) {
        // XXX do validation here.
        var context_option = "<option value=" + contexts[i].id + ">" + contexts[i].name + "</option>";
        context_selector.append(context_option);
      };
      return contexts;
    };

    requests.node.root().done(function(data) {
        var contexts;
        nodeinfo = data;
        nodeinfo.contexts = processContexts(nodeinfo.contexts);
        nodeinfo.selected_context = nodeinfo.contexts[0].id;
        processForm(nodeinfo.contexts[0].fields);
        debugDeck();
    });

  };
});
<commit_msg>Implement submission UI side up until the creation of the receipt<commit_after>define(function (require) {
  'use strict';

  var $ = require('jquery'),
      network = require('network'),
      latenza = require('latenza'),
      hogan = require('hogan'),
      requests = {},
      nodeinfo = {};

  requests.submission = require('./requests/submission');
  requests.node = require('./requests/node');

  // Return a function that can be called to do the DOM binding given a
  // jQuery DOM object to use as the parent container.
  return function uiSubmission(parentDom) {

    // Use the body element if no parentDom provided
    parentDom = parentDom || $('body');

    function debugDeck() {
        var debug = require('./debug'),
            dummy_requests = require('./dummy/requests'),
            submissionID = null;

        $("#node_button").click(function() {
          latenza.ajax({'url': '/node',
                        'type': 'GET'
          }).done(function(data) {
            debug.write(data, 'GET /node');
          });
        });

        $("#create_new").click(function() {
          requests.submission.root().done(function(data) {
                  submissionID = data['submission_id'];
                  debug.write(data, 'GET /submission');
          });
        });

        $("#send_fields").click(function() {
          if (submissionID) {
            var fields = {"FieldA": "hello", "FieldB": "world!"};
            var path = '/submission/'+submissionID+'/status';
            requests.submission.status_post(submissionID, {'fields': fields}).done(function(data){
              debug.write(data, 'POST '+path);
            });

          } else {
            alert("Run create new first!");
          }
        });

        $("#select_context").click(function() {
          if (submissionID) {
            var path = '/submission/'+submissionID+'/status';
            requests.submission.status_post(submissionID, {'context_selected':
                            nodeinfo.context_selected}).done(function(data){
              debug.write(data, 'POST '+path);
            });

          } else {
            alert("Run create new first!");
          }
        });

        $("#status").click(function() {
          var request = dummy_requests.submissionStatusPost;
          if (submissionID) {
            var path = '/submission/'+submissionID+'/status';
            requests.submission.status_get(submissionID).done(function(data){
              debug.write(data, 'GET '+path);
            });

          } else {
            alert("Run create new first!");
          }
        });

        $("#finalize_button").click(function() {
          if (submissionID) {
            var request = {'proposed_receipt': 'igotnicereceipt',
                           'folder_name': 'My Documents',
                           'folder_description': 'I have lots of warez!'};
            var path = '/submission/'+submissionID+'/finalize';
            latenza.ajax({'url': path,
                          'data': JSON.stringify(request),
                          'type': 'POST'
            }).done(function(data){
              debug.write(data, 'POST '+path);
            });

          } else {
            alert("Run create new first!");
          }
        });
    };

    function renderTemplate(template, data) {
        if (data.help) {
            template += '{{help}}'
        }
        var cTemplate = hogan.compile(template);
        var rendered = cTemplate.render(data);
        // console.log(rendered);
        return rendered;
    };

    var process = {
        string: function(data) {
            var template;
            template = '{{label}}\n';

            template += '<input type="text" name="{{name}}"';
            template +=        'value="{{default}}" placeholder="{{hint}}"';
            template +=        'required="{{required}}"/>';

            return renderTemplate(template, data);
        },

        text: function(data) {
            var template;
            template = '{{label}}\n';
            template += '<textarea name="{{name}}" required={{required}}>{{default}}</textarea>\n';
            return renderTemplate(template, data);
        },

        checkbox: function(data) {
            var template;
            template = '\n';
            template += '<input type="checkbox" name="{{name}}" required={{required}}>{{label}}\n';
            template += '';
            return renderTemplate(template, data);
        },

        radio: function(data) {
            var x,
                template = '',
                parsed_data = data;

            for (x in data.options) {
                parsed_data['label'+x] = data.options[x].label;
                parsed_data['value'+x] = data.options[x].value;
                template += '\n';
                template += '<input type="radio" name="{{name}}" value="{{value'+x+'}}" required={{required}}>\n';
                template += '{{label'+x+'}}\n';
                template += '';
            }
            return renderTemplate(template, parsed_data);
        }
    };

    function incompleteForm() {
    };

    function submitForm(data) {
        // console.log(data);
        var x,
            form = $(data.target.parentElement);

        var inputs = form.find('input');

        for (x in inputs) {
            // console.log(inputs[x]);
        };
        return false;
    };

    function processFields(form) {
      var data = form.serializeArray(),
          fields = {};
      for (var field in data) {
        fields[data[field].name] = data[field].value;
      }
      return fields;
    };

    function showReceipt(receipt_id) {
      $('.submissionForm').hide();
      $('.submissionContainer').append("
Here is your receipt
");
      $('.submissionContainer').append("
"+receipt_id+"
");
      $('.submissionContainer').append("debug link");
    };

    function processForm(form) {
        $('.submissionFormLeft')[0].innerHTML = "";
        $('.submissionFormRight')[0].innerHTML = "";
        $('.submissionForm button').remove();

        var x, target,
            allowed_types = ['string', 'text','checkbox', 'radio'];
        for (x in form) {
          // console.log(form[x].type);
          if (allowed_types.indexOf(form[x].type) != -1) {
            if ((x % 2) == 0) {
              target = $('.submissionFormLeft');
            } else {
              target = $('.submissionFormRight');
            }
            target.append(process[form[x].type](form[x]));
          }
        };
        $('.submissionForm').append('<button id="submit_button">Submit</button>');

        // XXX refactor this to remove this nesting insanity!
        $('#submit_button').click(function(){
          requests.submission.root().done(function(data) {
            var fields = processFields($('.submissionForm'));
            requests.submission.status_post(data['submission_id'],
                  {'fields': fields,
                   'context_selected': nodeinfo.context_selected}).done(function(args){
                     var proposed_receipt = "ididntchangeit",
                         folder_name = "foldername",
                         folder_description = "folderdesc";
                     requests.submission.finalize_post(data['submission_id'], proposed_receipt,
                                    folder_name, folder_description).done(function(data){
                                      showReceipt(data.receipt);
                                    });
            });
          });
          return false;
        });
    };

    function getContextFields(context_id) {
      for (var name in nodeinfo.contexts) {
        var context = nodeinfo.contexts[name];
        if (context.id == context_id) {
          return context.fields;
        }
      }
    };

    function processContexts(contexts) {
      var context_selector = $("#context_selector"),
          context_id, fields;
      context_selector.change(function(){
        context_id = $('#context_selector option:selected')[0].value;
        nodeinfo.context_selected = contexts[0].id;
        fields = getContextFields(context_id);
        processForm(fields);
      });
      for (var i in contexts) {
        // XXX do validation here.
        var context_option = "<option value=" + contexts[i].id + ">" + contexts[i].name + "</option>";
        context_selector.append(context_option);
      };
      return contexts;
    };

    requests.node.root().done(function(data) {
        var contexts;
        nodeinfo = data;
        nodeinfo.contexts = processContexts(nodeinfo.contexts);
        nodeinfo.context_selected = nodeinfo.contexts[0].id;
        processForm(nodeinfo.contexts[0].fields);
        debugDeck();
    });

  };
});
<|endoftext|>


<commit_before>const path = require('path');
require('dotenv').load({path: path.join(__dirname, '.env.test')});
//start db, store connection
const connection = require('../../lib/mongoose-setup');

//drop db before starting
before( done => {
  console.log('before all tests');
  const drop = () => connection.db.dropDatabase(done);
  if (connection.readyState === 1) drop();
  else connection.on('open', drop);
});

//close connection after all tests run
after(() => {
  console.log('after all tests');
  connection.close();
});
<commit_msg>travis fixes<commit_after>const path = require('path');
require('dotenv').load({path: path.join(__dirname, '../.env.test')});
//start db, store connection
const connection = require('../../lib/mongoose-setup');

//drop db before starting
before( done => {
  console.log('before all tests');
  const drop = () => connection.db.dropDatabase(done);
  if (connection.readyState === 1) drop();
  else connection.on('open', drop);
});

//close connection after all tests run
after(() => {
  console.log('after all tests');
  connection.close();
});
<|endoftext|>


<commit_before>var keystone = require('keystone'),
    Post = keystone.list('Post')

module.exports.default = {
    /*
        A comma delimited list of allowed http methods for this list.
        Defaults to empty list.
     */
    "httpMethods": "get",

    /*
     A comma delimited list of allowed http methods for this list that act on a group.
     Set true to inherit from httpMethods.
     WARNING: It is recommended to set this value explicitly (e.g: don`t set true) to prevent catastrophic results.
     For protection, setting httpGroupMethods: TRUE will not drill down to inheriting profiles, the inherited value will be the
     actual httpMethods value of the parent profile and not a reflection of httpMethods of the child profile.

     Defaults to empty list.
     */
    "httpGroupMethods": "get",

    /*
        defaultKey: The column used to search a single list instance with. (e.g: hello-world in www.site.com/api/post/hello-world)
        If not set defaults to the value of list.autokey.path, if list does`nt contain an autokey then _id is taken.
        To disable single item access, set to false.
     */
    "defaultKey": "slug",

    /*
        A filter that acts as a safe-guard to all user queries, except direct id queries (using defaultKey).
        This filter is added to each query. If keys in permanentFilter exist in a query, permanentFilter will override them.
        Example: To return only 'published' posts for GET requests set:  'state:published'
        The filter is declared using KeystoneJS 'queryfilter' library/ see: https://github.com/keystonejs/queryfilter

        Defaults to undefined
     */
    "permanentFilter": "state:published",

    "columns": {
        "visible": [
            "title",
            "publishedDate",
            "slug",
            "author",
            "content.brief",
            "content.extended",
            "categories",
            "tags"
        ],
        "no_filter": [
            "state",
            "slug",
            "_id"
        ]
    }
}

module.exports.isAdmin = {
    "__extends__": "default",

    "httpMethods": "get,post,put,delete",
    httpGroupMethods: "get,post,put,delete",
    "permanentFilter": undefined
}<commit_msg>fixed example.<commit_after>var keystone = require('keystone'),
    Post = keystone.list('Post')

module.exports.default = {
    /*
        A comma delimited list of allowed http methods for this list.
        Defaults to empty list.
     */
    "httpMethods": "get",

    /*
     A comma delimited list of allowed http methods for this list that acts on a group.
     A group is an action taken on a list of List (e.g: not accessing a direct instance via defaultKey)
     Set true to inherit from httpMethods.
     WARNING: It is recommended to set this value explicitly (e.g: don`t set true) to prevent catastrophic results.
     For protection, setting httpGroupMethods: TRUE will not drill down to inheriting profiles, the inherited value will be the
     actual httpMethods value of the parent profile and not a reflection of httpMethods of the child profile.

     Defaults to empty list.
     */
    "httpGroupMethods": "get",

    /*
        defaultKey: The column used to search a single list instance with. (e.g: hello-world in www.site.com/api/post/hello-world)
        If not set defaults to the value of list.autokey.path, if list does`nt contain an autokey then _id is taken.
        To disable single item access, set to false.
     */
    "defaultKey": "slug",

    /*
        A filter that acts as a safe-guard to all user queries, except direct id queries (using defaultKey).
        This filter is added to each query. If keys in permanentFilter exist in a query, permanentFilter will override them.
        Example: To return only 'published' posts for GET requests set:  'state:published'
        The filter is declared using KeystoneJS 'queryfilter' library/ see: https://github.com/keystonejs/queryfilter

        Defaults to undefined
     */
    "permanentFilter": "state:published",

    "columns": {
        "visible": [
            "title",
            "publishedDate",
            "slug",
            "author",
            "content.brief",
            "content.extended",
            "categories",
            "tags"
        ],
        "no_filter": [
            "state",
            "slug",
            "_id"
        ]
    }
}

module.exports.isAdmin = {
    "__extends__": "default",

    "httpMethods": "get,post,put,delete",
    httpGroupMethods: "get,post,put,delete",
    "permanentFilter": undefined
}<|endoftext|>


<commit_before>define(
[
    'models',
    'views/common',
    'views/dialogs',
    'text!templates/cluster/network_tab.html',
    'text!templates/cluster/network_tab_view.html',
    'text!templates/cluster/verify_network_control.html'
],
function(models, commonViews, dialogViews, networkTabTemplate, networkTabViewModeTemplate, networkTabVerificationControlTemplate) {
    'use strict';
    var NetworkTab, NetworkTabVerificationControl;

    NetworkTab = commonViews.Tab.extend({
        template: _.template(networkTabTemplate),
        viewModeTemplate: _.template(networkTabViewModeTemplate),
        updateInterval: 3000,
        hasChanges: false,
        events: {
            'keyup .row input': 'makeChanges',
            'change .row select': 'makeChanges',
            'click .apply-btn:not([disabled])': 'applyChanges',
            'click .verify-networks-btn:not([disabled])': 'verifyNetworks',
            'click .btn-revert-changes:not([disabled])': 'revertChanges',
            'click .net-manager input:not([checked])': 'changeManager',
            'keyup .range': 'displayRange'
        },
        defaultButtonsState: function(buttonState) {
            this.$('.btn:not(.verify-networks-btn)').attr('disabled', buttonState);
        },
        disableControls: function() {
            this.$('.btn, input, select').attr('disabled', true);
        },
        checkForChanges: function() {
            this.setValues();
            var noChanges = _.isEqual(this.model.get('networks').toJSON(), this.model.get('networksDbState').settings) && this.model.get('net_manager') == this.model.get('networksDbState').manager;
            this.defaultButtonsState(noChanges);
            this.hasChanges = !noChanges;
        },
        makeChanges: function(e) {
            var row = e ? this.$(e.target).parents('.control-group') : this.$('.control-group[data-network-name=fixed]');
            this.$('.control-group .error').removeClass('error');
            row.removeClass('error').find('.help-inline').text('');
            this.model.get('networks').get(row.data('network-id')).on('error', function(model, errors) {
                row.addClass('error').find('.help-inline').text(errors.cidr || errors.vlan_start || errors.amount);
            }, this);
            this.model.get('networks').get(row.data('network-id')).set({
                cidr: $('.cidr input', row).val(),
                vlan_start: $('.vlan_start input:first', row).val(),
                amount: this.model.get('net_manager') == 'FlatDHCPManager' ? 1 : $('.amount input', row).val(),
                network_size: parseInt($('.network_size select', row).val(), 10)
            });
            this.checkForChanges();
            app.page.removeVerificationTask();
        },
        calculateVlanEnd: function() {
            if (this.model.get('net_manager') == 'VlanManager') {
                var amount = parseInt(this.$('.fixed-row .amount input').val(), 10);
                var vlanStart = parseInt(this.$('.fixed-row .vlan_start input:first').val(), 10);
                var vlanEnd =  vlanStart + amount - 1;
                if (vlanEnd > 4094) {
                    vlanEnd = 4094;
                }
                this.$('input.vlan-end').val(vlanEnd);
            }
        },
        displayRange: function() {
            if (this.model.get('net_manager') == 'VlanManager' && parseInt(this.$('.fixed-row .amount input').val(), 10) > 1 && parseInt(this.$('.fixed-row .vlan_start input:first').val(), 10)) {
                this.$('.fixed-header .vlan').text('VLAN ID range');
                this.$('.fixed-row .vlan_start input:first').addClass('range');
                this.calculateVlanEnd();
                this.$('.vlan-end').removeClass('hide').show();
            } else {
                this.$('.fixed-header .vlan').text('VLAN ID');
                this.$('.vlan-end').hide();
            }
        },
        changeManager: function(e) {
            this.$('.net-manager input').attr('checked', false);
            this.$(e.target).attr('checked', true);
            this.model.set({net_manager: this.$(e.target).val()}, {silent: true});
            this.$('.control-group .error').removeClass('error');
            this.checkForChanges();
            this.$('.fixed-row .amount, .fixed-header .amount, .fixed-row .network_size, .fixed-header .size').toggle().removeClass('hide');
            this.displayRange();
            app.page.removeVerificationTask();
        },
        setValues: function() {
            var valid = true;
            this.model.get('networks').each(function(network) {
                var row = this.$('.control-group[data-network-name=' + network.get('name') + ']');
                network.on('error', function(model, errors) {
                    valid = false;
                }, this);
                network.set({
                    cidr: $('.cidr input', row).val(),
                    vlan_start: parseInt($('.vlan_start input:first', row).val(), 10),
                    amount: this.model.get('net_manager') == 'FlatDHCPManager' ? 1 : parseInt($('.amount input', row).val(), 10),
                    network_size: parseInt($('.network_size select', row).val(), 10)
                });
            }, this);
            return valid;
        },
        applyChanges: function() {
            if (this.setValues()) {
                this.disableControls();
                this.model.update({net_manager: this.$('.net-manager input[checked]').val()});
                Backbone.sync('update', this.model.get('networks'), {
                    url: '/api/clusters/' + this.model.id + '/save/networks',
                    error: _.bind(function() {
                        this.defaultButtonsState(false);
                        var dialog = new dialogViews.SimpleMessage({error: true, title: 'Networks'});
                        this.registerSubView(dialog);
                        dialog.render();
                    }, this),
                    success: _.bind(function(task) {
                        if (task && task.status == 'error') {
                            this.defaultButtonsState(false);
                        } else {
                            this.hasChanges = false;
                            this.model.get('networksDbState').settings = this.model.get('networks').toJSON();
                            this.model.get('networksDbState').manager = this.model.get('net_manager');
                        }
                    }, this),
                    complete: _.bind(function() {
                        this.model.fetch().done(_.bind(this.render, this));
                    }, this)
                });
            }
        },
        scheduleUpdate: function() {
            if (this.model.task('verify_networks', 'running')) {
                this.registerDeferred($.timeout(this.updateInterval).done(_.bind(this.update, this)));
            }
        },
        update: function(force) {
            var task = this.model.task('verify_networks', 'running');
            if (task && (force || app.page.$el.find(this.el).length)) {
                this.registerDeferred(task.fetch({complete: _.bind(this.scheduleUpdate, this)}));
            }
        },
        startVerification: function() {
            var task = new models.Task();
            task.save({}, {
                type: 'PUT',
                url: '/api/clusters/' + this.model.id + '/verify/networks',
                data: JSON.stringify(this.model.get('networks')),
                error:  _.bind(function() {
                        this.$('.verify-networks-btn').attr('disabled', false);
                        var dialog = new dialogViews.SimpleMessage({error: true, title: 'Network verification'});
                        this.registerSubView(dialog);
                        dialog.render();
                    }, this),
                complete: _.bind(function() {
                    var request = this.model.get('tasks').fetch({data: {cluster_id: this.model.id}});
                    request.done(_.bind(this.scheduleUpdate, this));
                    this.registerDeferred(request);
                }, this)
            });
        },
        verifyNetworks: function() {
            if (this.setValues()) {
                this.$('.verify-networks-btn').attr('disabled', true);
                app.page.removeVerificationTask().done(_.bind(this.startVerification, this));
            }
        },
        bindTaskEvents: function() {
            var task = this.model.task('verify_networks') || this.model.task('check_networks', 'error') || this.model.task('deploy', 'running');
            if (task) {
                task.bind('change:status', this.render, this);
                if (this.model.get('networks')) {
                    this.render();
                }
            }
        },
        bindEvents: function() {
            this.model.get('tasks').bind('remove', this.renderVerificationControl, this);
            this.model.get('tasks').bind('reset', this.bindTaskEvents, this);
            this.bindTaskEvents();
        },
        revertChanges: function() {
            this.hasChanges = false;
            this.model.set({
                net_manager: this.model.get('networksDbState').manager,
                networks: new models.Networks(this.model.get('networksDbState').settings)
            }, {silent: true});
            this.model.get('networks').deferred = new $.Deferred();
            this.model.get('networks').deferred.resolve();
            app.page.removeVerificationTask().done(_.bind(this.render, this));
        },
        initialize: function(options) {
            _.defaults(this, options);
            this.model.bind('change:tasks', this.bindEvents, this);
            this.bindEvents();
            if (!this.model.get('networks')) {
                this.model.set({'networks': new models.Networks()}, {silent: true});
                this.model.get('networks').deferred = this.model.get('networks').fetch({data: {cluster_id: this.model.id}});
                this.model.get('networks').deferred.done(_.bind(function() {
                    var networksDbState = {
                        settings: this.model.get('networks').toJSON(),
                        manager: this.model.get('net_manager')
                    };
                    this.model.set({'networksDbState': networksDbState}, {silent: true});
                    this.render();
                }, this));
            } else {
                this.revertChanges();
            }
        },
        showVerificationErrors: function() {
            var task = this.model.task('verify_networks', 'error') || this.model.task('check_networks', 'error');
            if (task && task.get('result').length) {
                var verificationResult = task.get('result');
                _.each(verificationResult, function(failedNetwork) {
                    _.each(failedNetwork.errors, function(field) {
                        this.$('.control-group[data-network-id=' + failedNetwork.id + ']').find('.' + field).children().addClass('error');
                    }, this);
                }, this);
            }
        },
        renderVerificationControl: function() {
            var verificationView = new NetworkTabVerificationControl({model: this.model, networks: this.model.get('networks')});
            this.registerSubView(verificationView);
            this.$('.verification-control').html(verificationView.render().el);
            this.showVerificationErrors();
        },
        render: function() {
            this.$el.html(this.template({cluster: this.model, networks: this.model.get('networks'), hasChanges: this.hasChanges}));
            this.renderVerificationControl();
            return this;
        }
    });

    NetworkTabVerificationControl = Backbone.View.extend({
        template: _.template(networkTabVerificationControlTemplate),
        initialize: function(options) {
            _.defaults(this, options);
        },
        render: function() {
            this.$el.html(this.template({cluster: this.model, networks: this.networks}));
            return this;
        }
    });

    return NetworkTab;
});
<commit_msg>PRD-615 fix<commit_after>define(
[
    'models',
    'views/common',
    'views/dialogs',
    'text!templates/cluster/network_tab.html',
    'text!templates/cluster/network_tab_view.html',
    'text!templates/cluster/verify_network_control.html'
],
function(models, commonViews, dialogViews, networkTabTemplate, networkTabViewModeTemplate, networkTabVerificationControlTemplate) {
    'use strict';
    var NetworkTab, NetworkTabVerificationControl;

    NetworkTab = commonViews.Tab.extend({
        template: _.template(networkTabTemplate),
        viewModeTemplate: _.template(networkTabViewModeTemplate),
        updateInterval: 3000,
        hasChanges: false,
        fixedAmount: 1,
        events: {
            'keyup .row input': 'makeChanges',
            'change .row select': 'makeChanges',
            'click .apply-btn:not([disabled])': 'applyChanges',
            'click .verify-networks-btn:not([disabled])': 'verifyNetworks',
            'click .btn-revert-changes:not([disabled])': 'revertChanges',
            'click .net-manager input:not([checked])': 'changeManager',
            'keyup .range': 'displayRange',
            'keyup input[name=fixed-amount]': 'setFixedAmount'
        },
        defaultButtonsState: function(buttonState) {
            this.$('.btn:not(.verify-networks-btn)').attr('disabled', buttonState);
        },
        disableControls: function() {
            this.$('.btn, input, select').attr('disabled', true);
        },
        checkForChanges: function() {
            this.setValues();
            var noChanges = _.isEqual(this.model.get('networks').toJSON(), this.model.get('networksDbState').settings) && this.model.get('net_manager') == this.model.get('networksDbState').manager;
            this.defaultButtonsState(noChanges);
            this.hasChanges = !noChanges;
        },
        makeChanges: function(e) {
            var row = e ? this.$(e.target).parents('.control-group') : this.$('.control-group[data-network-name=fixed]');
            this.$('.control-group .error').removeClass('error');
            row.removeClass('error').find('.help-inline').text('');
            this.model.get('networks').get(row.data('network-id')).on('error', function(model, errors) {
                row.addClass('error').find('.help-inline').text(errors.cidr || errors.vlan_start || errors.amount);
            }, this);
            this.model.get('networks').get(row.data('network-id')).set({
                cidr: $('.cidr input', row).val(),
                vlan_start: $('.vlan_start input:first', row).val(),
                amount: this.model.get('net_manager') == 'FlatDHCPManager' ? 1 : $('.amount input', row).val(),
                network_size: parseInt($('.network_size select', row).val(), 10)
            });
            this.checkForChanges();
            app.page.removeVerificationTask();
        },
        calculateVlanEnd: function() {
            if (this.model.get('net_manager') == 'VlanManager') {
                var amount = parseInt(this.$('.fixed-row .amount input').val(), 10);
                var vlanStart = parseInt(this.$('.fixed-row .vlan_start input:first').val(), 10);
                var vlanEnd =  vlanStart + amount - 1;
                if (vlanEnd > 4094) {
                    vlanEnd = 4094;
                }
                this.$('input.vlan-end').val(vlanEnd);
            }
        },
        displayRange: function() {
            if (this.model.get('net_manager') == 'VlanManager' && parseInt(this.$('.fixed-row .amount input').val(), 10) > 1 && parseInt(this.$('.fixed-row .vlan_start input:first').val(), 10)) {
                this.$('.fixed-header .vlan').text('VLAN ID range');
                this.$('.fixed-row .vlan_start input:first').addClass('range');
                this.calculateVlanEnd();
                this.$('.vlan-end').removeClass('hide').show();
            } else {
                this.$('.fixed-header .vlan').text('VLAN ID');
                this.$('.vlan-end').hide();
            }
        },
        changeManager: function(e) {
            this.$('.net-manager input').attr('checked', false);
            this.$(e.target).attr('checked', true);
            this.model.set({net_manager: this.$(e.target).val()}, {silent: true});
            this.$('.control-group .error').removeClass('error');
            this.checkForChanges();
            this.$('.fixed-row .amount, .fixed-header .amount, .fixed-row .network_size, .fixed-header .size').toggle().removeClass('hide');
            if (this.model.get('net_manager') == 'VlanManager') {
                this.$('input[name=fixed-amount]').val(this.fixedAmount);
            } else {
                this.$('input[name=fixed-amount]').val(1);
            }
            this.displayRange();
            app.page.removeVerificationTask();
        },
        setFixedAmount: function() {
            this.fixedAmount = parseInt(this.$('input[name=fixed-amount]').val(), 10);
        },
        setValues: function() {
            var valid = true;
            this.model.get('networks').each(function(network) {
                var row = this.$('.control-group[data-network-name=' + network.get('name') + ']');
                network.on('error', function(model, errors) {
                    valid = false;
                }, this);
                network.set({
                    cidr: $('.cidr input', row).val(),
                    vlan_start: parseInt($('.vlan_start input:first', row).val(), 10),
                    amount: this.model.get('net_manager') == 'FlatDHCPManager' || network.get('name') != 'fixed' ? 1 : this.fixedAmount,
                    network_size: parseInt($('.network_size select', row).val(), 10)
                });
            }, this);
            return valid;
        },
        applyChanges: function() {
            if (this.setValues()) {
                this.disableControls();
                this.model.update({net_manager: this.$('.net-manager input[checked]').val()});
                Backbone.sync('update', this.model.get('networks'), {
                    url: '/api/clusters/' + this.model.id + '/save/networks',
                    error: _.bind(function() {
                        this.defaultButtonsState(false);
                        var dialog = new dialogViews.SimpleMessage({error: true, title: 'Networks'});
                        this.registerSubView(dialog);
                        dialog.render();
                    }, this),
                    success: _.bind(function(task) {
                        if (task && task.status == 'error') {
                            this.defaultButtonsState(false);
                        } else {
                            this.hasChanges = false;
                            this.model.get('networksDbState').settings = this.model.get('networks').toJSON();
                            this.model.get('networksDbState').manager = this.model.get('net_manager');
                        }
                    }, this),
                    complete: _.bind(function() {
                        this.model.fetch().done(_.bind(this.render, this));
                    }, this)
                });
            }
        },
        scheduleUpdate: function() {
            if (this.model.task('verify_networks', 'running')) {
                this.registerDeferred($.timeout(this.updateInterval).done(_.bind(this.update, this)));
            }
        },
        update: function(force) {
            var task = this.model.task('verify_networks', 'running');
            if (task && (force || app.page.$el.find(this.el).length)) {
                this.registerDeferred(task.fetch({complete: _.bind(this.scheduleUpdate, this)}));
            }
        },
        startVerification: function() {
            var task = new models.Task();
            task.save({}, {
                type: 'PUT',
                url: '/api/clusters/' + this.model.id + '/verify/networks',
                data: JSON.stringify(this.model.get('networks')),
                error:  _.bind(function() {
                        this.$('.verify-networks-btn').attr('disabled', false);
                        var dialog = new dialogViews.SimpleMessage({error: true, title: 'Network verification'});
                        this.registerSubView(dialog);
                        dialog.render();
                    }, this),
                complete: _.bind(function() {
                    var request = this.model.get('tasks').fetch({data: {cluster_id: this.model.id}});
                    request.done(_.bind(this.scheduleUpdate, this));
                    this.registerDeferred(request);
                }, this)
            });
        },
        verifyNetworks: function() {
            if (this.setValues()) {
                this.$('.verify-networks-btn').attr('disabled', true);
                app.page.removeVerificationTask().done(_.bind(this.startVerification, this));
            }
        },
        bindTaskEvents: function() {
            var task = this.model.task('verify_networks') || this.model.task('check_networks', 'error') || this.model.task('deploy', 'running');
            if (task) {
                task.bind('change:status', this.render, this);
                if (this.model.get('networks')) {
                    this.render();
                }
            }
        },
        bindEvents: function() {
            this.model.get('tasks').bind('remove', this.renderVerificationControl, this);
            this.model.get('tasks').bind('reset', this.bindTaskEvents, this);
            this.bindTaskEvents();
        },
        revertChanges: function() {
            this.hasChanges = false;
            this.model.set({
                net_manager: this.model.get('networksDbState').manager,
                networks: new models.Networks(this.model.get('networksDbState').settings)
            }, {silent: true});
            this.model.get('networks').deferred = new $.Deferred();
            this.model.get('networks').deferred.resolve();
            app.page.removeVerificationTask().done(_.bind(this.render, this));
        },
        initialize: function(options) {
            _.defaults(this, options);
            this.model.bind('change:tasks', this.bindEvents, this);
            this.bindEvents();
            if (!this.model.get('networks')) {
                this.model.set({'networks': new models.Networks()}, {silent: true});
                this.model.get('networks').deferred = this.model.get('networks').fetch({data: {cluster_id: this.model.id}});
                this.model.get('networks').deferred.done(_.bind(function() {
                    var networksDbState = {
                        settings: this.model.get('networks').toJSON(),
                        manager: this.model.get('net_manager')
                    };
                    this.model.set({'networksDbState': networksDbState}, {silent: true});
                    this.render();
                }, this));
            } else {
                this.revertChanges();
            }
        },
        showVerificationErrors: function() {
            var task = this.model.task('verify_networks', 'error') || this.model.task('check_networks', 'error');
            if (task && task.get('result').length) {
                var verificationResult = task.get('result');
                _.each(verificationResult, function(failedNetwork) {
                    _.each(failedNetwork.errors, function(field) {
                        this.$('.control-group[data-network-id=' + failedNetwork.id + ']').find('.' + field).children().addClass('error');
                    }, this);
                }, this);
            }
        },
        renderVerificationControl: function() {
            var verificationView = new NetworkTabVerificationControl({model: this.model, networks: this.model.get('networks')});
            this.registerSubView(verificationView);
            this.$('.verification-control').html(verificationView.render().el);
            this.showVerificationErrors();
        },
        render: function() {
            this.$el.html(this.template({cluster: this.model, networks: this.model.get('networks'), hasChanges: this.hasChanges}));
            this.renderVerificationControl();
            return this;
        }
    });

    NetworkTabVerificationControl = Backbone.View.extend({
        template: _.template(networkTabVerificationControlTemplate),
        initialize: function(options) {
            _.defaults(this, options);
        },
        render: function() {
            this.$el.html(this.template({cluster: this.model, networks: this.networks}));
            return this;
        }
    });

    return NetworkTab;
});
<|endoftext|>


<commit_before>/**
 * History.js Native Adapter
 * @author Benjamin Arthur Lupton <contact@balupton.com>
 * @copyright 2010-2011 Benjamin Arthur Lupton <contact@balupton.com>
 * @license New BSD License <http://creativecommons.org/licenses/BSD/>
 */

// Closure
(function(window,undefined){
	"use strict";

	// Localise Globals
	var History = window.History = window.History||{};

	// Check Existence
	if ( typeof History.Adapter !== 'undefined' ) {
		throw new Error('History.js Adapter has already been loaded...');
	}

	// Add the Adapter
	History.Adapter = {
		/**
		 * History.Adapter.handlers[uid][eventName] = Array
		 */
		handlers: {},

		/**
		 * History.Adapter._uid
		 * The current element unique identifier
		 */
		_uid: 1,

		/**
		 * History.Adapter.uid(element)
		 * @param {Element} element
		 * @return {String} uid
		 */
		 uid: function(element){
			return element._uid || (element._uid = History.Adapter._uid++);
		 },

		/**
		 * History.Adapter.bind(el,event,callback)
		 * @param {Element} element
		 * @param {String} eventName - custom and standard events
		 * @param {Function} callback
		 * @return
		 */
		bind: function(element,eventName,callback){
			// Prepare
			var uid = History.Adapter.uid(element);

			// Apply Listener
			History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
			History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];
			History.Adapter.handlers[uid][eventName].push(callback);

			// Bind Global Listener
			element['on'+eventName] = (function(element,eventName){
				return function(event){
					History.Adapter.trigger(element,eventName,event);
				};
			})(element,eventName);
		},

		/**
		 * History.Adapter.trigger(el,event)
		 * @param {Element} element
		 * @param {String} eventName - custom and standard events
		 * @param {Object} event - a object of event data
		 * @return
		 */
		trigger: function(element,eventName,event){
			// Prepare
			event = event || {};
			var uid = History.Adapter.uid(element),
				i,n;

			// Apply Listener
			History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
			History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];

			// Fire Listeners
			for ( i=0,n=History.Adapter.handlers[uid][eventName].length; i<n; ++i ) {
				History.Adapter.handlers[uid][eventName][i].apply(this,[event]);
			}
		},

		/**
		 * History.Adapter.extractEventData(key,event,extra)
		 * @param {String} key - key for the event data to extract
		 * @param {String} event - custom and standard events
		 * @return {mixed}
		 */
		extractEventData: function(key,event){
			var result = (event && event[key]) || undefined;
			return result;
		},

		/**
		 * History.Adapter.onDomLoad(callback)
		 * @param {Function} callback
		 * @return
		 */
		onDomLoad: function(callback) {
			var timeout = window.setTimeout(function(){
				callback();
			},2000);
			window.onload = function(){
				clearTimeout(timeout);
				callback();
			};
		}
	};

	// Try and Initialise History
	if ( typeof History.init !== 'undefined' ) {
		History.init();
	}

})(window);
<commit_msg>Removes stray spaces so that the build script can run.<commit_after>/**
 * History.js Native Adapter
 * @author Benjamin Arthur Lupton <contact@balupton.com>
 * @copyright 2010-2011 Benjamin Arthur Lupton <contact@balupton.com>
 * @license New BSD License <http://creativecommons.org/licenses/BSD/>
 */

// Closure
(function(window,undefined){
	"use strict";

	// Localise Globals
	var History = window.History = window.History||{};

	// Check Existence
	if ( typeof History.Adapter !== 'undefined' ) {
		throw new Error('History.js Adapter has already been loaded...');
	}

	// Add the Adapter
	History.Adapter = {
		/**
		 * History.Adapter.handlers[uid][eventName] = Array
		 */
		handlers: {},

		/**
		 * History.Adapter._uid
		 * The current element unique identifier
		 */
		_uid: 1,

		/**
		 * History.Adapter.uid(element)
		 * @param {Element} element
		 * @return {String} uid
		 */
		uid: function(element){
			return element._uid || (element._uid = History.Adapter._uid++);
		},

		/**
		 * History.Adapter.bind(el,event,callback)
		 * @param {Element} element
		 * @param {String} eventName - custom and standard events
		 * @param {Function} callback
		 * @return
		 */
		bind: function(element,eventName,callback){
			// Prepare
			var uid = History.Adapter.uid(element);

			// Apply Listener
			History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
			History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];
			History.Adapter.handlers[uid][eventName].push(callback);

			// Bind Global Listener
			element['on'+eventName] = (function(element,eventName){
				return function(event){
					History.Adapter.trigger(element,eventName,event);
				};
			})(element,eventName);
		},

		/**
		 * History.Adapter.trigger(el,event)
		 * @param {Element} element
		 * @param {String} eventName - custom and standard events
		 * @param {Object} event - a object of event data
		 * @return
		 */
		trigger: function(element,eventName,event){
			// Prepare
			event = event || {};
			var uid = History.Adapter.uid(element),
				i,n;

			// Apply Listener
			History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
			History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];

			// Fire Listeners
			for ( i=0,n=History.Adapter.handlers[uid][eventName].length; i<n; ++i ) {
				History.Adapter.handlers[uid][eventName][i].apply(this,[event]);
			}
		},

		/**
		 * History.Adapter.extractEventData(key,event,extra)
		 * @param {String} key - key for the event data to extract
		 * @param {String} event - custom and standard events
		 * @return {mixed}
		 */
		extractEventData: function(key,event){
			var result = (event && event[key]) || undefined;
			return result;
		},

		/**
		 * History.Adapter.onDomLoad(callback)
		 * @param {Function} callback
		 * @return
		 */
		onDomLoad: function(callback) {
			var timeout = window.setTimeout(function(){
				callback();
			},2000);
			window.onload = function(){
				clearTimeout(timeout);
				callback();
			};
		}
	};

	// Try and Initialise History
	if ( typeof History.init !== 'undefined' ) {
		History.init();
	}

})(window);
<|endoftext|>