<commit_before>
md.webrequest = ({storage: {state}, detect}) => {

  var permissions = ['webRequest', 'webRequestBlocking']

  var filter = {
    urls: ['<all_urls>'],
    types: ['main_frame', 'sub_frame']
  }

  var options = ['blocking', 'responseHeaders']

  var onHeadersReceived = ({method, url, responseHeaders}) => {
    if (method !== 'GET') {
      return {responseHeaders}
    }

    var header = responseHeaders.find(({name}) => /^content-type/i.test(name)) || {}
    var origin = detect.match(url)

    if (!detect.header(header.value) && !origin) {
      return {responseHeaders}
    }

    if (origin.csp) {
      responseHeaders = responseHeaders
        .filter(({name}) => !/content-security-policy/i.test(name))
    }

    // ff: markdown `content-type` is not allowed
    if (/Firefox/.test(navigator.userAgent) && detect.header(header.value)) {
      header.value = 'text/plain'
    }

    if (origin.encoding && header.name) {
      var [media] = header.value.split(';')
      header.value = `${media}; charset=${origin.encoding}`
    }

    return {responseHeaders}
  }

  var onCompleted = ({ip, tabId}) => {
    if (ip && ip !== '127.0.0.1' && ip !== '::1') {
      setTimeout(() => {
        chrome.tabs.sendMessage(tabId, {message: 'autoreload'})
      }, 500)
    }
  }

  var events = () => {
    var headers = false
    for (var key in state.origins) {
      if (state.origins[key].csp || state.origins[key].encoding) {
        headers = true
        break
      }
    }

    // ff: webRequest is required permission
    if (/Firefox/.test(navigator.userAgent)) {
      headers = true
    }

    var completed = false
    if (state.content.autoreload) {
      completed = true
    }

    return {headers, completed}
  }

  var perm = (headers, completed, done) => {
    // ff: webRequest is required permission
    if (/Firefox/.test(navigator.userAgent)) {
      done()
    }
    // request permissions
    else if ((headers || completed) && !chrome.webRequest) {
      chrome.permissions.request({permissions}, done)
    }
    // remove permissions
    else if (!headers && !completed && chrome.webRequest) {
      chrome.permissions.remove({permissions}, () => {
        chrome.webRequest = null
        done()
      })
    }
    else {
      done()
    }
  }

  return () => {

    var {headers, completed} = events()

    // remove listeners
    if (chrome.webRequest) {
      if (!headers && !/Firefox/.test(navigator.userAgent)) {
        chrome.webRequest.onHeadersReceived.removeListener(onHeadersReceived)
      }
      if (!completed) {
        chrome.webRequest.onCompleted.removeListener(onCompleted)
      }
    }

    perm(headers, completed, () => {
      // add listeners
      if (headers && !chrome.webRequest.onHeadersReceived.hasListener(onHeadersReceived)) {
        chrome.webRequest.onHeadersReceived.addListener(onHeadersReceived, filter, options)
      }
      if (completed && !chrome.webRequest.onCompleted.hasListener(onCompleted)) {
        chrome.webRequest.onCompleted.addListener(onCompleted, filter)
      }
    })
  }
}
<commit_msg>Refactor webrequest headers handler<commit_after>
md.webrequest = ({storage: {state}, detect}) => {

  var permissions = ['webRequest', 'webRequestBlocking']

  var filter = {
    urls: ['<all_urls>'],
    types: ['main_frame', 'sub_frame']
  }

  var options = ['blocking', 'responseHeaders']

  var onHeadersReceived = ({method, url, responseHeaders}) => {
    if (method !== 'GET') {
      return {responseHeaders}
    }

    var header = responseHeaders.find(({name}) => /^content-type/i.test(name))

    // ff: markdown `content-type` is not allowed
    if (header && detect.header(header.value) && /Firefox/.test(navigator.userAgent)) {
      header.value = 'text/plain'
    }

    var origin = detect.match(url)

    if (!origin) {
      return {responseHeaders}
    }

    if (origin.csp) {
      responseHeaders = responseHeaders
        .filter(({name}) => !/content-security-policy/i.test(name))
    }

    if (origin.encoding && header && /charset/.test(header.value)) {
      var [media] = header.value.split(';')
      header.value = `${media}; charset=${origin.encoding}`
    }

    return {responseHeaders}
  }

  var onCompleted = ({ip, tabId}) => {
    if (ip && ip !== '127.0.0.1' && ip !== '::1') {
      setTimeout(() => {
        chrome.tabs.sendMessage(tabId, {message: 'autoreload'})
      }, 500)
    }
  }

  var events = () => {
    var headers = false
    for (var key in state.origins) {
      if (state.origins[key].csp || state.origins[key].encoding) {
        headers = true
        break
      }
    }

    // ff: webRequest is required permission
    if (/Firefox/.test(navigator.userAgent)) {
      headers = true
    }

    var completed = false
    if (state.content.autoreload) {
      completed = true
    }

    return {headers, completed}
  }

  var perm = (headers, completed, done) => {
    // ff: webRequest is required permission
    if (/Firefox/.test(navigator.userAgent)) {
      done()
    }
    // request permissions
    else if ((headers || completed) && !chrome.webRequest) {
      chrome.permissions.request({permissions}, done)
    }
    // remove permissions
    else if (!headers && !completed && chrome.webRequest) {
      chrome.permissions.remove({permissions}, () => {
        chrome.webRequest = null
        done()
      })
    }
    else {
      done()
    }
  }

  return () => {

    var {headers, completed} = events()

    // remove listeners
    if (chrome.webRequest) {
      if (!headers && !/Firefox/.test(navigator.userAgent)) {
        chrome.webRequest.onHeadersReceived.removeListener(onHeadersReceived)
      }
      if (!completed) {
        chrome.webRequest.onCompleted.removeListener(onCompleted)
      }
    }

    perm(headers, completed, () => {
      // add listeners
      if (headers && !chrome.webRequest.onHeadersReceived.hasListener(onHeadersReceived)) {
        chrome.webRequest.onHeadersReceived.addListener(onHeadersReceived, filter, options)
      }
      if (completed && !chrome.webRequest.onCompleted.hasListener(onCompleted)) {
        chrome.webRequest.onCompleted.addListener(onCompleted, filter)
      }
    })
  }
}
<|endoftext|>


<commit_before>import Vue from 'vue'
import Router from 'vue-router'

// 公司信息管理
import informationDetail from '@/views/information/detail'
import informationEdit from '@/views/information/edit'
import informationShow from '@/views/information/show'

// 员工管理
import userList from '@/views/user/list'
import userCreate from '@/views/user/create'
import userEdit from '@/views/user/edit'
import userLog from '@/views/user/log'

// 课程管理
import courseCategoryList from '@/views/course/category/list'
import courseCategoryCreate from '@/views/course/category/create'
import courseCategoryEdit from '@/views/course/category/edit'

import courseList from '@/views/course/list'
// import courseDetail from '@/views/course/detail'
import courseEdit from '@/views/course/edit'
import courseComment from '@/views/course/comment'
import learningList from '@/views/course/learningList'

// 报名管理
import registrationEnrollmentRecord from '@/views/registration/enrollmentRecord'
import registrationTrainlist from '@/views/registration/trainlist'
import registrationEdit from '@/views/registration/edit'
import registrationRecord from '@/views/registration/record'
import registrationComment from '@/views/registration/comment'

// 约课管理
import bookingList from '@/views/booking/list'
import bookingDetail from '@/views/booking/detail'

// 修改密码
import adminList from '@/views/admin/list'
import adminChangePWD from '@/views/admin/changePWD'

// 考试管理
import examList from '@/views/exam/list'
import examQuestionList from '@/views/exam/questionList'
import examUserList from '@/views/exam/userList'

Vue.use(Router)
var requiresAuth = false

export default new Router({
  mode: 'history',
  routes: [
    // 公司信息管理
    {
      path: '/',
      name: 'informationDetail',
      component: informationDetail,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/information/edit',
      name: 'informationEdit',
      component: informationEdit,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/information/show',
      name: 'informationShow',
      component: informationShow,
      meta: {requiresAuth: requiresAuth}
    },
    // 员工管理
    {
      path: '/user/list',
      name: 'userList',
      component: userList,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/user/create',
      name: 'userCreate',
      component: userCreate,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/user/edit',
      name: 'userEdit',
      component: userEdit,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/user/log',
      name: 'userLog',
      component: userLog,
      meta: {requiresAuth: requiresAuth}
    },
    // 课程管理
    {
      path: '/course/category/list',
      name: 'courseCategoryList',
      component: courseCategoryList,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/course/category/create',
      name: 'courseCategoryCreate',
      component: courseCategoryCreate,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/course/category/edit',
      name: 'courseCategoryEdit',
      component: courseCategoryEdit,
      meta: { requiresAuth: requiresAuth }
    },
    // {
    //   path: '/course/detail',
    //   name: 'courseDetail',
    //   component: courseDetail,
    //   meta: {requiresAuth: requiresAuth}
    // },
    {
      path: '/course/edit',
      name: 'courseEdit',
      component: courseEdit,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/course/comment',
      name: 'courseComment',
      component: courseComment,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/course/list',
      name: 'courseList',
      component: courseList,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/course/learningList',
      name: 'learningList',
      component: learningList,
      meta: {requiresAuth: requiresAuth}
    },
    // 报名管理
    {
      path: '/registration/EnrollmentRecord',
      name: 'registrationEnrollmentRecord',
      component: registrationEnrollmentRecord,
      meta: {requiresAuth: requiresAuth}
    }, {
      path: '/registration/trainList',
      name: 'registrationTrainlist',
      component: registrationTrainlist,
      meta: {requiresAuth: requiresAuth}
    }, {
      path: '/registration/edit',
      name: 'registrationEdit',
      component: registrationEdit,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/registration/record',
      name: 'registrationRecord',
      component: registrationRecord,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/registration/comment',
      name: 'registrationComment',
      component: registrationComment,
      meta: {requiresAuth: requiresAuth}
    },
    // 约课
    {
      path: '/booking/list',
      name: 'bookingList',
      component: bookingList,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/booking/detail',
      name: 'bookingDetail',
      component: bookingDetail,
      meta: {requiresAuth: requiresAuth}
    },
    // 系统管理
    {
      path: '/admin/changePWD',
      name: 'adminChangePWD',
      component: adminChangePWD,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/admin/list',
      name: 'adminList',
      component: adminList,
      meta: {requiresAuth: requiresAuth}
    },
// 考试管理
    {
      path: '/exam/list',
      name: 'examList',
      component: examList,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/exam/questionList',
      name: 'examQuestionList',
      component: examQuestionList,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/exam/userList',
      name: 'examUserList',
      component: examUserList,
      meta: {requiresAuth: requiresAuth}
    }
  ]
})
<commit_msg>static<commit_after>import Vue from 'vue'
import Router from 'vue-router'

// 公司信息管理
import informationDetail from '@/views/information/detail'
import informationEdit from '@/views/information/edit'
import informationShow from '@/views/information/show'

// 员工管理
import userList from '@/views/user/list'
import userCreate from '@/views/user/create'
import userEdit from '@/views/user/edit'
import userLog from '@/views/user/log'

// 课程管理
import courseCategoryList from '@/views/course/category/list'
import courseCategoryCreate from '@/views/course/category/create'
import courseCategoryEdit from '@/views/course/category/edit'

import courseList from '@/views/course/list'
// import courseDetail from '@/views/course/detail'
import courseEdit from '@/views/course/edit'
import courseComment from '@/views/course/comment'
import learningList from '@/views/course/learningList'

// 报名管理
import registrationEnrollmentRecord from '@/views/registration/enrollmentRecord'
import registrationTrainlist from '@/views/registration/trainList'
import registrationEdit from '@/views/registration/edit'
import registrationRecord from '@/views/registration/record'
import registrationComment from '@/views/registration/comment'

// 约课管理
import bookingList from '@/views/booking/list'
import bookingDetail from '@/views/booking/detail'

// 修改密码
import adminList from '@/views/admin/list'
import adminChangePWD from '@/views/admin/changePWD'

// 考试管理
import examList from '@/views/exam/list'
import examQuestionList from '@/views/exam/questionList'
import examUserList from '@/views/exam/userList'

Vue.use(Router)
var requiresAuth = false

export default new Router({
  mode: 'history',
  routes: [
    // 公司信息管理
    {
      path: '/',
      name: 'informationDetail',
      component: informationDetail,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/information/edit',
      name: 'informationEdit',
      component: informationEdit,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/information/show',
      name: 'informationShow',
      component: informationShow,
      meta: {requiresAuth: requiresAuth}
    },
    // 员工管理
    {
      path: '/user/list',
      name: 'userList',
      component: userList,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/user/create',
      name: 'userCreate',
      component: userCreate,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/user/edit',
      name: 'userEdit',
      component: userEdit,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/user/log',
      name: 'userLog',
      component: userLog,
      meta: {requiresAuth: requiresAuth}
    },
    // 课程管理
    {
      path: '/course/category/list',
      name: 'courseCategoryList',
      component: courseCategoryList,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/course/category/create',
      name: 'courseCategoryCreate',
      component: courseCategoryCreate,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/course/category/edit',
      name: 'courseCategoryEdit',
      component: courseCategoryEdit,
      meta: { requiresAuth: requiresAuth }
    },
    // {
    //   path: '/course/detail',
    //   name: 'courseDetail',
    //   component: courseDetail,
    //   meta: {requiresAuth: requiresAuth}
    // },
    {
      path: '/course/edit',
      name: 'courseEdit',
      component: courseEdit,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/course/comment',
      name: 'courseComment',
      component: courseComment,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/course/list',
      name: 'courseList',
      component: courseList,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/course/learningList',
      name: 'learningList',
      component: learningList,
      meta: {requiresAuth: requiresAuth}
    },
    // 报名管理
    {
      path: '/registration/EnrollmentRecord',
      name: 'registrationEnrollmentRecord',
      component: registrationEnrollmentRecord,
      meta: {requiresAuth: requiresAuth}
    }, {
      path: '/registration/trainList',
      name: 'registrationTrainlist',
      component: registrationTrainlist,
      meta: {requiresAuth: requiresAuth}
    }, {
      path: '/registration/edit',
      name: 'registrationEdit',
      component: registrationEdit,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/registration/record',
      name: 'registrationRecord',
      component: registrationRecord,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/registration/comment',
      name: 'registrationComment',
      component: registrationComment,
      meta: {requiresAuth: requiresAuth}
    },
    // 约课
    {
      path: '/booking/list',
      name: 'bookingList',
      component: bookingList,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/booking/detail',
      name: 'bookingDetail',
      component: bookingDetail,
      meta: {requiresAuth: requiresAuth}
    },
    // 系统管理
    {
      path: '/admin/changePWD',
      name: 'adminChangePWD',
      component: adminChangePWD,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/admin/list',
      name: 'adminList',
      component: adminList,
      meta: {requiresAuth: requiresAuth}
    },
// 考试管理
    {
      path: '/exam/list',
      name: 'examList',
      component: examList,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/exam/questionList',
      name: 'examQuestionList',
      component: examQuestionList,
      meta: {requiresAuth: requiresAuth}
    },
    {
      path: '/exam/userList',
      name: 'examUserList',
      component: examUserList,
      meta: {requiresAuth: requiresAuth}
    }
  ]
})
<|endoftext|>


<commit_before>function Recorder(api) {
  var calls = []
  var recorder = {}
  for (key in api) {
    var f = api[key]
    if (typeof f == "function") {
      recorder[key] = proxyMethod(key, f)
    }
  }
  recorder._recorder = {
    calls: function() {
      return calls
    },
    reset: function() {
      calls = []
    }
  }
  return recorder

  function proxyMethod(key, f) {
      return function() {
        calls.push([key, Array.prototype.slice.call(arguments)])
        return f.apply(api, arguments)
      }
  }
}
<commit_msg>added recorder.export<commit_after>function Recorder(api) {
  var calls = []
  var recorder = {}
  for (key in api) {
    var f = api[key]
    if (typeof f == "function") {
      recorder[key] = proxyMethod(key, f)
    }
  }
  recorder._recorder = {
    calls: function() {
      return calls
    },
    reset: function() {
      calls = []
    },
    export: function() {
      return JSON.stringify(calls)
    }
  }
  return recorder

  function proxyMethod(key, f) {
      return function() {
        calls.push([key, Array.prototype.slice.call(arguments)])
        return f.apply(api, arguments)
      }
  }
}
<|endoftext|>


<commit_before>describe('perform mapping', function () {

    var Pouch, RawQuery, RestAPI, RestError, RelationshipType, RelatedObjectProxy, RestObject, $rootScope;
    var api, carMapping;

    beforeEach(function () {
        module('restkit.mapping', function ($provide) {
            $provide.value('$log', console);
            $provide.value('$q', Q);
        });
        module('restkit.relationship', function ($provide) {
            $provide.value('$log', console);
            $provide.value('$q', Q);
        });

        inject(function (_Index_, _Pouch_, _Indexes_, _RawQuery_, _RestObject_, _Mapping_, _RestAPI_, _RestError_, _RelationshipType_, _RelatedObjectProxy_, _$rootScope_) {
            Pouch = _Pouch_;
            RawQuery = _RawQuery_;
            RestAPI = _RestAPI_;
            RelationshipType = _RelationshipType_;
            RelatedObjectProxy = _RelatedObjectProxy_;
            RestObject = _RestObject_;
            $rootScope = _$rootScope_;
        });

        Pouch.reset();

    });

    describe('no relationships', function () {
        var obj;

        beforeEach(function (done) {
            api = new RestAPI('myApi', function (err, version) {
                if (err) done(err);
                carMapping = api.registerMapping('Car', {
                    id: 'id',
                    attributes: ['colour', 'name']
                });
            }, function (err) {
                if (err) done(err);
                carMapping.map({colour: 'red', name: 'Aston Martin', id: 'dfadf'}, function (err, _obj) {
                    obj = _obj;
                    done(err);
                });
            });
        });

        describe('new', function () {

            it('returns a restobject', function () {
                assert.instanceOf(obj, RestObject);
            });

            it('has the right fields', function () {
                assert.equal(obj.colour, 'red');
                assert.equal(obj.name, 'Aston Martin');
                assert.equal(obj.id, 'dfadf');
                assert.ok(obj._id);
            });

            it('is placed down to pouch', function (done) {
                var pouchId = obj._id;
                Pouch.getPouch().get(pouchId, function (err, resp) {
                    if (err) done(err);
                    assert.ok(resp);
                    done();
                });
            });
        });

        describe('existing', function () {

            describe('via id', function () {
                var newObj;
                beforeEach(function (done) {
                    carMapping.map({colour: 'blue', id: 'dfadf'}, function (err, obj) {
                        if (err) done(err);
                        newObj = obj;
                        done();
                    });
                });

                it('should be mapped onto the old object', function () {
                    assert.equal(newObj, obj);
                });

                it('should have the new colour', function () {
                    assert.equal(newObj.colour, 'blue');
                });
            });

            describe('via _id', function () {
                var newObj;
                beforeEach(function (done) {
                    carMapping.map({colour: 'blue', _id: obj._id}, function (err, obj) {
                        if (err) done(err);
                        newObj = obj;
                        done();
                    });
                });

                it('should be mapped onto the old object', function () {
                    assert.equal(newObj, obj);
                });

                it('should have the new colour', function () {
                    assert.equal(newObj.colour, 'blue');
                });
            });
        })

    });

    describe('with relationship', function () {

        describe('foreign key', function () {
            var personMapping;
            beforeEach(function (done) {
                api = new RestAPI('myApi', function (err, version) {
                    if (err) done(err);
                    personMapping = api.registerMapping('Person', {
                        id: 'id',
                        attributes: ['name', 'age']
                    });
                    carMapping = api.registerMapping('Car', {
                        id: 'id',
                        attributes: ['colour', 'name'],
                        relationships: {
                            owner: {
                                mapping: 'Person',
                                type: RelationshipType.ForeignKey,
                                reverse: 'cars'
                            }
                        }
                    });
                }, function (err) {
                    if (err) done(err);
                    done();
                });
            });

            describe('remote id', function () {

                describe('forward', function () {
                    describe('object that already exists', function () {
                        var person, car;
                        beforeEach(function (done) {
                            personMapping.map({name: 'Michael Ford', age: 23, id: 'personRemoteId'}, function (err, _person) {
                                if (err) done(err);
                                person = _person;
                                carMapping.map({name: 'Bentley', colour: 'black', owner: 'personRemoteId', id: 'carRemoteId'}, function (err, _car) {
                                    if (err) done(err);
                                    car = _car;
                                    done();
                                });
                            });
                        });
                        it('owner of car should be michael', function (done) {
                            $rootScope.$digest(); // Ensure cache gets updated.
                            car.owner.get(function (err, owner) {
                                if (err) done(err);
                                assert.equal(owner, person);
                                done();
                            })
                        });
                        it('michael should the car', function (done) {
                            $rootScope.$digest(); // Ensure cache gets updated.
                            person.cars.get(function (err, cars) {
                                if (err) done(err);
                                assert.include(cars, car);
                                done();
                            });
                        });
                    });

                    describe('remote id of an object that doesnt exist', function () {
                        var car;
                        beforeEach(function (done) {
                            carMapping.map({name: 'Bentley', colour: 'black', owner: 'personRemoteId', id: 'carRemoteId'}, function (err, _car) {
                                console.error('done!!!!!!');
                                if (err) done(err);
                                car = _car;
                                done();
                            });
                        });
                        it('car should have a new owner and new owner should have a car', function (done) {
                            $rootScope.$digest(); // Ensure cache gets updated.
                            car.owner.get(function (err, person) {
                                if (err) done(err);
                                assert.equal(person.id, 'personRemoteId');
                                person.cars.get(function (err, cars) {
                                    if (err) done(err);
                                    assert.equal(cars.length, 1);
                                    assert.include(cars, car);
                                    done();
                                });
                            });
                        })

                    })
                });

                describe('reverse', function () {
                    describe('remoteids of objects that already exist', function () {
                        var person, cars;
                        beforeEach(function (done) {
                            var raw = [
                                {colour: 'red', name: 'Aston Martin', id: 'remoteId1'},
                                {colour: 'blue', name: 'Lambo', id: "remoteId2"},
                                {colour: 'green', name: 'Ford', id: "remoteId3"}
                            ];
                            carMapping._mapBulk(raw, function (err, objs, res) {
                                if (err) done(err);
                                cars = objs;
                                personMapping.map({
                                    name: 'Michael Ford',
                                    age: 23,
                                    id: 'personRemoteId',
                                    cars: ['remoteId1', 'remoteId2', 'remoteId3']
                                }, function (err, _person) {
                                    if (err) done(err);
                                    person = _person;
                                    done();
                                });
                            });
                        });

                        it('cars should have person as their owner', function () {
                            _.each(cars, function (car) {
                                assert.equal(car.owner._id, person._id);
                            })
                        });

                        it('person should have car objects', function () {
                            dump(person.cars);
                            _.each(cars, function (car) {
                                assert.include(person.cars._id, car._id);
                                assert.include(person.cars.relatedObject, car);
                            })
                        });
                    });

                    describe('remoteids of objects that dont exist', function () {
                        var person;
                        beforeEach(function (done) {
                            personMapping.map({
                                name: 'Michael Ford',
                                age: 23,
                                id: 'personRemoteId',
                                cars: ['remoteId1', 'remoteId2', 'remoteId3']
                            }, function (err, _person) {
                                if (err) done(err);
                                person = _person;
                                done();
                            });
                        });

                        it('person has 3 new cars, and those cars are owned by the person', function (done) {
                            person.cars.get(function (err, cars) {
                                done(err);
                                assert.equal(cars.length, 3);
                                _.each(cars, function (car) {
                                    assert.equal(car.owner._id, person._id);
                                })
                            });
                        })
                    });

                    describe('mixture', function () {
                        var person, cars;
                        beforeEach(function (done) {
                            var raw = [
                                {colour: 'red', name: 'Aston Martin', id: 'remoteId1'},
                                {colour: 'green', name: 'Ford', id: "remoteId3"}
                            ];
                            carMapping._mapBulk(raw, function (err, objs, res) {
                                if (err) done(err);
                                cars = objs;
                                personMapping.map({
                                    name: 'Michael Ford',
                                    age: 23,
                                    id: 'personRemoteId',
                                    cars: ['remoteId1', 'remoteId2', 'remoteId3']
                                }, function (err, _person) {
                                    if (err) done(err);
                                    person = _person;
                                    done();
                                });
                            });
                        });

                        it('cars should have person as their owner', function () {
                            _.each(cars, function (car) {
                                assert.equal(car.owner._id, person._id);
                            })
                        });

                        it('person should have car objects', function () {
                            dump(person.cars);
                            _.each(cars, function (car) {
                                assert.include(person.cars._id, car._id);
                                assert.include(person.cars.relatedObject, car);
                            })
                        });

                        it('person has 3 new cars, and those cars are owned by the person', function (done) {
                            person.cars.get(function (err, cars) {
                                done(err);
                                assert.equal(cars.length, 3);
                                _.each(cars, function (car) {
                                    assert.equal(car.owner._id, person._id);
                                })
                            });
                        })

                    })
                })

            });

            // TODO
            describe('_id', function () {
                describe('forward', function () {
                    describe('object already exists', function () {
                        // TODO
                    });
                    describe('object doesnt exist', function () {
                        // TODO
                    });
                });
                describe('reverse', function () {
                    describe('all objects already exist', function () {
                        // TODO
                    });
                    describe('no objects exist', function () {
                        // TODO
                    });
                    describe('mixed', function () {
                        // TODO
                    });
                });
            });

            // TODO
            describe('object', function () {
                describe('forward', function () {
                    describe('object already exists', function () {
                        // TODO
                    });
                    describe('object doesnt exist', function () {
                        // TODO
                    });
                });
                describe('reverse', function () {
                    describe('all objects already exist', function () {
                        // TODO
                    });
                    describe('no objects exist', function () {
                        // TODO
                    });
                    describe('mixed', function () {
                        // TODO
                    });
                });
            });

        });

    });

    describe('bulk', function () {

        it('should redirect arrays to _mapBulk when passed to map', function (done) {
            var raw = [
                {colour: 'red', name: 'Aston Martin', id: 'remoteId1'},
                {colour: 'blue', name: 'Lambo', id: "remoteId2"},
                {colour: 'green', name: 'Ford', id: "remoteId3"}
            ];
            sinon.stub(carMapping, '_mapBulk', function (_, callback) {
                callback();
            });
            carMapping.map(raw, function () {
                sinon.assert.calledWith(carMapping._mapBulk, raw);
                done();
            })
        });

        describe('new', function () {

            beforeEach(function (done) {
                api = new RestAPI('myApi', function (err, version) {
                    if (err) done(err);
                    carMapping = api.registerMapping('Car', {
                        id: 'id',
                        attributes: ['colour', 'name']
                    });
                }, function (err) {
                    done(err);
                });
            });

            it('all valid', function (done) {
                var raw = [
                    {colour: 'red', name: 'Aston Martin', id: 'remoteId1'},
                    {colour: 'blue', name: 'Lambo', id: "remoteId2"},
                    {colour: 'green', name: 'Ford', id: "remoteId3"}
                ];
                carMapping._mapBulk(raw, function (err, objs, res) {
                    assert.notOk(err);
                    assert.equal(objs.length, raw.length);
                    assert.equal(res.length, raw.length);
                    _.each(res, function (r) {
                        assert.notOk(r.err);
                        assert.ok(r.obj);
                    });
                    _.each(objs, function (o) {
                        assert.include(_.pluck(res, 'obj'), o);
                    });
                    _.each(raw, function (r) {
                        assert.include(_.pluck(res, 'raw'), r);
                    });
                    done();
                })
            });

            it('one err', function (done) {
                var raw = [
                    {colour: 'red', name: 'Aston Martin', id: 'remoteId1'},
                    {colour: 'blue', name: 'Lambo'},
                    {colour: 'green', name: 'Ford', id: "remoteId3"}
                ];
                carMapping._mapBulk(raw, function (err, objs, res) {
                    assert.equal(err.length, 1);
                    assert.equal(objs.length, raw.length - 1);
                    assert.equal(res.length, raw.length);
                    assert.include(_.pluck(res, 'err'), err[0]);
                    done();
                })
            });

        })

    });

});
<commit_msg>skeleton for testing the other ways to map objects<commit_after>describe('perform mapping', function () {

    var Pouch, RawQuery, RestAPI, RestError, RelationshipType, RelatedObjectProxy, RestObject, $rootScope;
    var api, carMapping;

    beforeEach(function () {
        module('restkit.mapping', function ($provide) {
            $provide.value('$log', console);
            $provide.value('$q', Q);
        });
        module('restkit.relationship', function ($provide) {
            $provide.value('$log', console);
            $provide.value('$q', Q);
        });

        inject(function (_Index_, _Pouch_, _Indexes_, _RawQuery_, _RestObject_, _Mapping_, _RestAPI_, _RestError_, _RelationshipType_, _RelatedObjectProxy_, _$rootScope_) {
            Pouch = _Pouch_;
            RawQuery = _RawQuery_;
            RestAPI = _RestAPI_;
            RelationshipType = _RelationshipType_;
            RelatedObjectProxy = _RelatedObjectProxy_;
            RestObject = _RestObject_;
            $rootScope = _$rootScope_;
        });

        Pouch.reset();

    });

    describe('no relationships', function () {
        var obj;

        beforeEach(function (done) {
            api = new RestAPI('myApi', function (err, version) {
                if (err) done(err);
                carMapping = api.registerMapping('Car', {
                    id: 'id',
                    attributes: ['colour', 'name']
                });
            }, function (err) {
                if (err) done(err);
                carMapping.map({colour: 'red', name: 'Aston Martin', id: 'dfadf'}, function (err, _obj) {
                    obj = _obj;
                    done(err);
                });
            });
        });

        describe('new', function () {

            it('returns a restobject', function () {
                assert.instanceOf(obj, RestObject);
            });

            it('has the right fields', function () {
                assert.equal(obj.colour, 'red');
                assert.equal(obj.name, 'Aston Martin');
                assert.equal(obj.id, 'dfadf');
                assert.ok(obj._id);
            });

            it('is placed down to pouch', function (done) {
                var pouchId = obj._id;
                Pouch.getPouch().get(pouchId, function (err, resp) {
                    if (err) done(err);
                    assert.ok(resp);
                    done();
                });
            });
        });

        describe('existing', function () {

            describe('via id', function () {
                var newObj;
                beforeEach(function (done) {
                    carMapping.map({colour: 'blue', id: 'dfadf'}, function (err, obj) {
                        if (err) done(err);
                        newObj = obj;
                        done();
                    });
                });

                it('should be mapped onto the old object', function () {
                    assert.equal(newObj, obj);
                });

                it('should have the new colour', function () {
                    assert.equal(newObj.colour, 'blue');
                });
            });

            describe('via _id', function () {
                var newObj;
                beforeEach(function (done) {
                    carMapping.map({colour: 'blue', _id: obj._id}, function (err, obj) {
                        if (err) done(err);
                        newObj = obj;
                        done();
                    });
                });

                it('should be mapped onto the old object', function () {
                    assert.equal(newObj, obj);
                });

                it('should have the new colour', function () {
                    assert.equal(newObj.colour, 'blue');
                });
            });
        })

    });

    describe('with relationship', function () {

        describe.only('foreign key', function () {
            var personMapping;
            beforeEach(function (done) {
                api = new RestAPI('myApi', function (err, version) {
                    if (err) done(err);
                    personMapping = api.registerMapping('Person', {
                        id: 'id',
                        attributes: ['name', 'age']
                    });
                    carMapping = api.registerMapping('Car', {
                        id: 'id',
                        attributes: ['colour', 'name'],
                        relationships: {
                            owner: {
                                mapping: 'Person',
                                type: RelationshipType.ForeignKey,
                                reverse: 'cars'
                            }
                        }
                    });
                }, function (err) {
                    if (err) done(err);
                    done();
                });
            });

            describe('remote id', function () {

                describe('forward', function () {
                    describe('object that already exists', function () {
                        var person, car;
                        beforeEach(function (done) {
                            personMapping.map({name: 'Michael Ford', age: 23, id: 'personRemoteId'}, function (err, _person) {
                                if (err) done(err);
                                person = _person;
                                carMapping.map({name: 'Bentley', colour: 'black', owner: 'personRemoteId', id: 'carRemoteId'}, function (err, _car) {
                                    if (err) done(err);
                                    car = _car;
                                    done();
                                });
                            });
                        });
                        it('owner of car should be michael', function (done) {
                            $rootScope.$digest(); // Ensure cache gets updated.
                            car.owner.get(function (err, owner) {
                                if (err) done(err);
                                assert.equal(owner, person);
                                done();
                            })
                        });
                        it('michael should the car', function (done) {
                            $rootScope.$digest(); // Ensure cache gets updated.
                            person.cars.get(function (err, cars) {
                                if (err) done(err);
                                assert.include(cars, car);
                                done();
                            });
                        });
                    });

                    describe('remote id of an object that doesnt exist', function () {
                        var car;
                        beforeEach(function (done) {
                            carMapping.map({name: 'Bentley', colour: 'black', owner: 'personRemoteId', id: 'carRemoteId'}, function (err, _car) {
                                console.error('done!!!!!!');
                                if (err) done(err);
                                car = _car;
                                done();
                            });
                        });
                        it('car should have a new owner and new owner should have a car', function (done) {
                            $rootScope.$digest(); // Ensure cache gets updated.
                            car.owner.get(function (err, person) {
                                if (err) done(err);
                                assert.equal(person.id, 'personRemoteId');
                                person.cars.get(function (err, cars) {
                                    if (err) done(err);
                                    assert.equal(cars.length, 1);
                                    assert.include(cars, car);
                                    done();
                                });
                            });
                        })

                    })
                });

                describe('reverse', function () {
                    describe('remoteids of objects that already exist', function () {
                        var person, cars;
                        beforeEach(function (done) {
                            var raw = [
                                {colour: 'red', name: 'Aston Martin', id: 'remoteId1'},
                                {colour: 'blue', name: 'Lambo', id: "remoteId2"},
                                {colour: 'green', name: 'Ford', id: "remoteId3"}
                            ];
                            carMapping._mapBulk(raw, function (err, objs, res) {
                                if (err) done(err);
                                cars = objs;
                                personMapping.map({
                                    name: 'Michael Ford',
                                    age: 23,
                                    id: 'personRemoteId',
                                    cars: ['remoteId1', 'remoteId2', 'remoteId3']
                                }, function (err, _person) {
                                    if (err) done(err);
                                    person = _person;
                                    done();
                                });
                            });
                        });

                        it('cars should have person as their owner', function () {
                            _.each(cars, function (car) {
                                assert.equal(car.owner._id, person._id);
                            })
                        });

                        it('person should have car objects', function () {
                            dump(person.cars);
                            _.each(cars, function (car) {
                                assert.include(person.cars._id, car._id);
                                assert.include(person.cars.relatedObject, car);
                            })
                        });
                    });

                    describe('remoteids of objects that dont exist', function () {
                        var person;
                        beforeEach(function (done) {
                            personMapping.map({
                                name: 'Michael Ford',
                                age: 23,
                                id: 'personRemoteId',
                                cars: ['remoteId1', 'remoteId2', 'remoteId3']
                            }, function (err, _person) {
                                if (err) done(err);
                                person = _person;
                                done();
                            });
                        });

                        it('person has 3 new cars, and those cars are owned by the person', function (done) {
                            person.cars.get(function (err, cars) {
                                done(err);
                                assert.equal(cars.length, 3);
                                _.each(cars, function (car) {
                                    assert.equal(car.owner._id, person._id);
                                })
                            });
                        })
                    });

                    describe('mixture', function () {
                        var person, cars;
                        beforeEach(function (done) {
                            var raw = [
                                {colour: 'red', name: 'Aston Martin', id: 'remoteId1'},
                                {colour: 'green', name: 'Ford', id: "remoteId3"}
                            ];
                            carMapping._mapBulk(raw, function (err, objs, res) {
                                if (err) done(err);
                                cars = objs;
                                personMapping.map({
                                    name: 'Michael Ford',
                                    age: 23,
                                    id: 'personRemoteId',
                                    cars: ['remoteId1', 'remoteId2', 'remoteId3']
                                }, function (err, _person) {
                                    if (err) done(err);
                                    person = _person;
                                    done();
                                });
                            });
                        });

                        it('cars should have person as their owner', function () {
                            _.each(cars, function (car) {
                                assert.equal(car.owner._id, person._id);
                            })
                        });

                        it('person should have car objects', function () {
                            dump(person.cars);
                            _.each(cars, function (car) {
                                assert.include(person.cars._id, car._id);
                                assert.include(person.cars.relatedObject, car);
                            })
                        });

                        it('person has 3 new cars, and those cars are owned by the person', function (done) {
                            person.cars.get(function (err, cars) {
                                done(err);
                                assert.equal(cars.length, 3);
                                _.each(cars, function (car) {
                                    assert.equal(car.owner._id, person._id);
                                })
                            });
                        })

                    })
                })

            });

            // TODO
            describe('_id', function () {
                describe('forward', function () {
                    describe('object already exists', function () {
                        // TODO
                    });
                    describe('object doesnt exist', function () {
                        // TODO
                    });
                });
                describe('reverse', function () {
                    describe('all objects already exist', function () {
                        // TODO
                    });
                    describe('no objects exist', function () {
                        // TODO
                    });
                    describe('mixed', function () {
                        // TODO
                    });
                });
            });

        });

    });

    describe('bulk', function () {

        it('should redirect arrays to _mapBulk when passed to map', function (done) {
            var raw = [
                {colour: 'red', name: 'Aston Martin', id: 'remoteId1'},
                {colour: 'blue', name: 'Lambo', id: "remoteId2"},
                {colour: 'green', name: 'Ford', id: "remoteId3"}
            ];
            sinon.stub(carMapping, '_mapBulk', function (_, callback) {
                callback();
            });
            carMapping.map(raw, function () {
                sinon.assert.calledWith(carMapping._mapBulk, raw);
                done();
            })
        });

        describe('new', function () {

            beforeEach(function (done) {
                api = new RestAPI('myApi', function (err, version) {
                    if (err) done(err);
                    carMapping = api.registerMapping('Car', {
                        id: 'id',
                        attributes: ['colour', 'name']
                    });
                }, function (err) {
                    done(err);
                });
            });

            it('all valid', function (done) {
                var raw = [
                    {colour: 'red', name: 'Aston Martin', id: 'remoteId1'},
                    {colour: 'blue', name: 'Lambo', id: "remoteId2"},
                    {colour: 'green', name: 'Ford', id: "remoteId3"}
                ];
                carMapping._mapBulk(raw, function (err, objs, res) {
                    assert.notOk(err);
                    assert.equal(objs.length, raw.length);
                    assert.equal(res.length, raw.length);
                    _.each(res, function (r) {
                        assert.notOk(r.err);
                        assert.ok(r.obj);
                    });
                    _.each(objs, function (o) {
                        assert.include(_.pluck(res, 'obj'), o);
                    });
                    _.each(raw, function (r) {
                        assert.include(_.pluck(res, 'raw'), r);
                    });
                    done();
                })
            });

            it('one err', function (done) {
                var raw = [
                    {colour: 'red', name: 'Aston Martin', id: 'remoteId1'},
                    {colour: 'blue', name: 'Lambo'},
                    {colour: 'green', name: 'Ford', id: "remoteId3"}
                ];
                carMapping._mapBulk(raw, function (err, objs, res) {
                    assert.equal(err.length, 1);
                    assert.equal(objs.length, raw.length - 1);
                    assert.equal(res.length, raw.length);
                    assert.include(_.pluck(res, 'err'), err[0]);
                    done();
                })
            });

        })

    });

});
<|endoftext|>


<commit_before>function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

/* This function is used to change the style class of an element */
function swapClass(obj, newStyle) {
    obj.className = newStyle;
}

function isUndefined(value) {
    var undef;
    return value == undef;
}

/* Function for showing and hiding elements that use 'display:none' to hide
function toggleDisplay(targetId)
{
    if (document.getElementById) {
        target = document.getElementById(targetId);
    	if (target.style.display == "none"){
    		target.style.display = "";
    	} else {
    		target.style.display = "none";
    	}
    }
}

function toggleVisibility(targetId) {
    if (document.getElementById) {
        target = document.getElementById(targetId);
    	if (target.style.visibility == "hidden"){
    		target.style.visibility = "visible";
    	} else {
    		target.style.visibility = "hidden";
    	}
    }
}
 */

function checkAll(theForm) { // check all the checkboxes in the list
  for (var i=0;i<theForm.elements.length;i++) {
    var e = theForm.elements[i];
		var eName = e.name;
    	if (eName != 'allbox' &&
            (e.type.indexOf("checkbox") == 0)) {
        	e.checked = theForm.allbox.checked;
		}
	}
}

/* Function to clear a form of all it's values */
function clearForm(frmObj) {
	for (var i = 0; i < frmObj.length; i++) {
        var element = frmObj.elements[i];
		if(element.type.indexOf("text") == 0 ||
				element.type.indexOf("password") == 0) {
					element.value="";
		} else if (element.type.indexOf("radio") == 0) {
			element.checked=false;
		} else if (element.type.indexOf("checkbox") == 0) {
			element.checked = false;
		} else if (element.type.indexOf("select") == 0) {
			for(var j = 0; j < element.length ; j++) {
				element.options[j].selected=false;
			}
            element.options[0].selected=true;
		}
	}
}

/* Function to get a form's values in a string */
function getFormAsString(frmObj) {
    var query = "";
	for (var i = 0; i < frmObj.length; i++) {
        var element = frmObj.elements[i];
        if (element.type.indexOf("checkbox") == 0 ||
            element.type.indexOf("radio") == 0) {
            if (element.checked) {
                query += element.name + '=' + escape(element.value) + "&";
            }
		} else if (element.type.indexOf("select") == 0) {
			for (var j = 0; j < element.length ; j++) {
				if (element.options[j].selected) {
                    query += element.name + '=' + escape(element.value) + "&";
                }
			}
        } else {
            query += element.name + '='
                  + escape(element.value) + "&";
        }
    }
    return query;
}

/* Function to hide form elements that show through
   the search form when it is visible */
function toggleForm(frmObj, iState) // 1 visible, 0 hidden
{
	for(var i = 0; i < frmObj.length; i++) {
		if (frmObj.elements[i].type.indexOf("select") == 0 || frmObj.elements[i].type.indexOf("checkbox") == 0) {
            frmObj.elements[i].style.visibility = iState ? "visible" : "hidden";
		}
	}
}

/* Helper function for re-ordering options in a select */
function opt(txt,val,sel) {
    this.txt=txt;
    this.val=val;
    this.sel=sel;
}

/* Function for re-ordering <option>'s in a <select> */
function move(list,to) {
    var total=list.options.length;
    index = list.selectedIndex;
    if (index == -1) return false;
    if (to == +1 && index == total-1) return false;
    if (to == -1 && index == 0) return false;
    to = index+to;
    var opts = new Array();
    for (i=0; i<total; i++) {
        opts[i]=new opt(list.options[i].text,list.options[i].value,list.options[i].selected);
    }
    tempOpt = opts[to];
    opts[to] = opts[index];
    opts[index] = tempOpt
    list.options.length=0; // clear

    for (i=0;i<opts.length;i++) {
        list.options[i] = new Option(opts[i].txt,opts[i].val);
        list.options[i].selected = opts[i].sel;
    }

    list.focus();
}

/*  This function is to select all options in a multi-valued <select> */
function selectAll(elementId) {
    var element = document.getElementById(elementId);
	len = element.length;
	if (len != 0) {
		for (i = 0; i < len; i++) {
			element.options[i].selected = true;
		}
	}
}

/* This function is used to select a checkbox by passing
 * in the checkbox id
 */
function toggleChoice(elementId) {
    var element = document.getElementById(elementId);
    if (element.checked) {
        element.checked = false;
    } else {
        element.checked = true;
    }
}

/* This function is used to select a radio button by passing
 * in the radio button id and index you want to select
 */
function toggleRadio(elementId, index) {
    var element = document.getElementsByName(elementId)[index];
    element.checked = true;
}

/* This function is used to open a pop-up window */
function openWindow(url, winTitle, winParams) {
	winName = window.open(url, winTitle, winParams);
    winName.focus();
}

/* This function is to open search results in a pop-up window */
function openSearch(url, winTitle) {
    var screenWidth = parseInt(screen.availWidth);
    var screenHeight = parseInt(screen.availHeight);

    var winParams = "width=" + screenWidth + ",height=" + screenHeight;
        winParams += ",left=0,top=0,toolbar,scrollbars,resizable,status=yes";

    openWindow(url, winTitle, winParams);
}

/* This function is used to set cookies */
function setCookie(name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
}

/* This function is used to get cookies */
function getCookie(name) {
	var prefix = name + "="
	var start = document.cookie.indexOf(prefix)

	if (start==-1) {
		return null;
	}

	var end = document.cookie.indexOf(";", start+prefix.length)
	if (end==-1) {
		end=document.cookie.length;
	}

	var value=document.cookie.substring(start+prefix.length, end)
	return unescape(value);
}

/* This function is used to delete cookies */
function deleteCookie(name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

// This function is for stripping leading and trailing spaces
function trim(str) {
    if (str != null) {
        var i;
        for (i=0; i<str.length; i++) {
            if (str.charAt(i)!=" ") {
                str=str.substring(i,str.length);
                break;
            }
        }

        for (i=str.length-1; i>=0; i--) {
            if (str.charAt(i)!=" ") {
                str=str.substring(0,i+1);
                break;
            }
        }

        if (str.charAt(0)==" ") {
            return "";
        } else {
            return str;
        }
    }
}

/*
* This method is used for client-side validation in the commons-validation framework. The original version used an 'alert'. We changed this to update style of the invalid field.
*/
function validateRequired(form) {
    var bValid = true;
    var focusField = null;
    var i = 0;
    var fields = new Array();
    oRequired = new required();

    for (x in oRequired) {
	    formid = oRequired[x][0] + ".label" ;
        labelel = document.getElementById(formid);
        if ((form[oRequired[x][0]].type == 'select-multiple' | form[oRequired[x][0]].type == 'file' || form[oRequired[x][0]].type == 'text' || form[oRequired[x][0]].type == 'textarea' || form[oRequired[x][0]].type == 'select-one' || form[oRequired[x][0]].type == 'radio' || form[oRequired[x][0]].type == 'password') && form[oRequired[x][0]].value == '') {
           if (i == 0)
              focusField = form[oRequired[x][0]];

           fields[i++] = oRequired[x][1];
           labelel.setAttribute("class", "error");
           labelel.setAttribute("title", oRequired[x][1]);

           bValid = false;
        } else {
        	labelel.setAttribute("class", "");
        }
    }

    if (fields.length > 0) {
       focusField.focus();
    //   alert(fields.join('\n'));
    }

    return bValid;
}

// This function is a generic function to create form elements
function createFormElement(element, type, name, id, value, parent) {
    var e = document.createElement(element);
    e.setAttribute("name", name);
    e.setAttribute("type", type);
    e.setAttribute("id", id);
    e.setAttribute("value", value);
    parent.appendChild(e);
}

function confirmDelete(obj) {
    var msg = "Are you sure you want to delete this " + obj + "?";
    ans = confirm(msg);
    if (ans) {
        return true;
    } else {
        return false;
    }
}

function highlightTableRows(tableId) {
    var previousClass = null;
    var table = document.getElementById(tableId);
    var tbody = table.getElementsByTagName("tbody")[0];
    if (tbody == null) {
        var rows = table.getElementsByTagName("tr");
    } else {
        var rows = tbody.getElementsByTagName("tr");
    }
    // add event handlers so rows light up and are clickable
    for (i=0; i < rows.length; i++) {
        rows[i].onmouseover = function() { previousClass=this.className;this.className+=' over' };
        rows[i].onmouseout = function() { this.className=previousClass };
        rows[i].onclick = function() {
            var cell = this.getElementsByTagName("td")[0];
            var link = cell.getElementsByTagName("a")[0];
            location.href = link.getAttribute("href");
            this.style.cursor="wait";
        }
    }
}

//function highlightFormElements() {
//    // add input box highlighting
//    addFocusHandlers(document.getElementsByTagName("input"));
//    addFocusHandlers(document.getElementsByTagName("textarea"));
//}

//function addFocusHandlers(elements) {
//    for (i=0; i < elements.length; i++) {
//        if (elements[i].type != "button" && elements[i].type != "submit" &&
//            elements[i].type != "reset" && elements[i].type != "checkbox" && elements[i].type != "radio") {
//            if (elements[i].getAttribute('readonly') != "readonly" && elements[i].getAttribute('readonly') != "disabled") {
//                elements[i].onfocus=function() {this.className='focus';this.select()};
//                elements[i].onblur=function() {this.className=''};
//            }
//        }
//    }
//}

//function radio(clicked){
//    var form = clicked.form;
//    var checkboxes = form.elements[clicked.name];
//    if (!clicked.checked || !checkboxes.length) {
//        clicked.parentNode.parentNode.className="";
//        return false;
//    }
//
//    for (i=0; i<checkboxes.length; i++) {
//        if (checkboxes[i] != clicked) {
//            checkboxes[i].checked=false;
//            checkboxes[i].parentNode.parentNode.className="";
//        }
//    }
//
//    // highlight the row
//    clicked.parentNode.parentNode.className="over";
//}
//
//window.onload = function() {
//    highlightFormElements();
//    if ($('successMessages')) {
//        new Effect.Highlight('successMessages');
//        // causes webtest exception on OS X : http://lists.canoo.com/pipermail/webtest/2006q1/005214.html
//        // window.setTimeout("Effect.DropOut('successMessages')", 3000);
//    }
//    if ($('errorMessages')) {
//        new Effect.Highlight('errorMessages');
//    }
//}

// Show the document's title on the status bar
window.defaultStatus=document.title;

<commit_msg>formatting; mark as deprecated<commit_after>/**
 * @deprecated
 */

function MM_preloadImages() { // v3.0
	var d = document;
	if (d.images) {
		if (!d.MM_p)
			d.MM_p = new Array();
		var i, j = d.MM_p.length, a = MM_preloadImages.arguments;
		for (i = 0; i < a.length; i++)
			if (a[i].indexOf("#") != 0) {
				d.MM_p[j] = new Image;
				d.MM_p[j++].src = a[i];
			}
	}
}

function MM_swapImgRestore() { // v3.0
	var i, x, a = document.MM_sr;
	for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++)
		x.src = x.oSrc;
}

function MM_findObj(n, d) { // v4.01
	var p, i, x;
	if (!d)
		d = document;
	if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
		d = parent.frames[n.substring(p + 1)].document;
		n = n.substring(0, p);
	}
	if (!(x = d[n]) && d.all)
		x = d.all[n];
	for (i = 0; !x && i < d.forms.length; i++)
		x = d.forms[i][n];
	for (i = 0; !x && d.layers && i < d.layers.length; i++)
		x = MM_findObj(n, d.layers[i].document);
	if (!x && d.getElementById)
		x = d.getElementById(n);
	return x;
}

function MM_swapImage() { // v3.0
	var i, j = 0, x, a = MM_swapImage.arguments;
	document.MM_sr = new Array;
	for (i = 0; i < (a.length - 2); i += 3)
		if ((x = MM_findObj(a[i])) != null) {
			document.MM_sr[j++] = x;
			if (!x.oSrc)
				x.oSrc = x.src;
			x.src = a[i + 2];
		}
}

/* This function is used to change the style class of an element */
function swapClass(obj, newStyle) {
	obj.className = newStyle;
}

function isUndefined(value) {
	var undef;
	return value == undef;
}

function checkAll(theForm) { // check all the checkboxes in the list
	for (var i = 0; i < theForm.elements.length; i++) {
		var e = theForm.elements[i];
		var eName = e.name;
		if (eName != 'allbox' && (e.type.indexOf("checkbox") == 0)) {
			e.checked = theForm.allbox.checked;
		}
	}
}

/* Function to clear a form of all it's values */
function clearForm(frmObj) {
	for (var i = 0; i < frmObj.length; i++) {
		var element = frmObj.elements[i];
		if (element.type.indexOf("text") == 0
				|| element.type.indexOf("password") == 0) {
			element.value = "";
		} else if (element.type.indexOf("radio") == 0) {
			element.checked = false;
		} else if (element.type.indexOf("checkbox") == 0) {
			element.checked = false;
		} else if (element.type.indexOf("select") == 0) {
			for (var j = 0; j < element.length; j++) {
				element.options[j].selected = false;
			}
			element.options[0].selected = true;
		}
	}
}

/* Function to get a form's values in a string */
function getFormAsString(frmObj) {
	var query = "";
	for (var i = 0; i < frmObj.length; i++) {
		var element = frmObj.elements[i];
		if (element.type.indexOf("checkbox") == 0
				|| element.type.indexOf("radio") == 0) {
			if (element.checked) {
				query += element.name + '=' + escape(element.value) + "&";
			}
		} else if (element.type.indexOf("select") == 0) {
			for (var j = 0; j < element.length; j++) {
				if (element.options[j].selected) {
					query += element.name + '=' + escape(element.value) + "&";
				}
			}
		} else {
			query += element.name + '=' + escape(element.value) + "&";
		}
	}
	return query;
}

/*
 * Function to hide form elements that show through the search form when it is
 * visible
 */
function toggleForm(frmObj, iState) // 1 visible, 0 hidden
{
	for (var i = 0; i < frmObj.length; i++) {
		if (frmObj.elements[i].type.indexOf("select") == 0
				|| frmObj.elements[i].type.indexOf("checkbox") == 0) {
			frmObj.elements[i].style.visibility = iState ? "visible" : "hidden";
		}
	}
}

/* Helper function for re-ordering options in a select */
function opt(txt, val, sel) {
	this.txt = txt;
	this.val = val;
	this.sel = sel;
}

/* Function for re-ordering <option>'s in a <select> */
function move(list, to) {
	var total = list.options.length;
	index = list.selectedIndex;
	if (index == -1)
		return false;
	if (to == +1 && index == total - 1)
		return false;
	if (to == -1 && index == 0)
		return false;
	to = index + to;
	var opts = new Array();
	for (i = 0; i < total; i++) {
		opts[i] = new opt(list.options[i].text, list.options[i].value,
				list.options[i].selected);
	}
	tempOpt = opts[to];
	opts[to] = opts[index];
	opts[index] = tempOpt
	list.options.length = 0; // clear

	for (i = 0; i < opts.length; i++) {
		list.options[i] = new Option(opts[i].txt, opts[i].val);
		list.options[i].selected = opts[i].sel;
	}

	list.focus();
}

/* This function is to select all options in a multi-valued <select> */
function selectAll(elementId) {
	var element = document.getElementById(elementId);
	len = element.length;
	if (len != 0) {
		for (i = 0; i < len; i++) {
			element.options[i].selected = true;
		}
	}
}

/*
 * This function is used to select a checkbox by passing in the checkbox id
 */
function toggleChoice(elementId) {
	var element = document.getElementById(elementId);
	if (element.checked) {
		element.checked = false;
	} else {
		element.checked = true;
	}
}

/*
 * This function is used to select a radio button by passing in the radio button
 * id and index you want to select
 */
function toggleRadio(elementId, index) {
	var element = document.getElementsByName(elementId)[index];
	element.checked = true;
}

/* This function is used to open a pop-up window */
function openWindow(url, winTitle, winParams) {
	winName = window.open(url, winTitle, winParams);
	winName.focus();
}

/* This function is to open search results in a pop-up window */
function openSearch(url, winTitle) {
	var screenWidth = parseInt(screen.availWidth);
	var screenHeight = parseInt(screen.availHeight);

	var winParams = "width=" + screenWidth + ",height=" + screenHeight;
	winParams += ",left=0,top=0,toolbar,scrollbars,resizable,status=yes";

	openWindow(url, winTitle, winParams);
}

/* This function is used to set cookies */
function setCookie(name, value, expires, path, domain, secure) {
	document.cookie = name + "=" + escape(value)
			+ ((expires) ? "; expires=" + expires.toGMTString() : "")
			+ ((path) ? "; path=" + path : "")
			+ ((domain) ? "; domain=" + domain : "")
			+ ((secure) ? "; secure" : "");
}

/* This function is used to get cookies */
function getCookie(name) {
	var prefix = name + "="
	var start = document.cookie.indexOf(prefix)

	if (start == -1) {
		return null;
	}

	var end = document.cookie.indexOf(";", start + prefix.length)
	if (end == -1) {
		end = document.cookie.length;
	}

	var value = document.cookie.substring(start + prefix.length, end)
	return unescape(value);
}

/* This function is used to delete cookies */
function deleteCookie(name, path, domain) {
	if (getCookie(name)) {
		document.cookie = name + "=" + ((path) ? "; path=" + path : "")
				+ ((domain) ? "; domain=" + domain : "")
				+ "; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}

// This function is for stripping leading and trailing spaces
function trim(str) {
	if (str != null) {
		var i;
		for (i = 0; i < str.length; i++) {
			if (str.charAt(i) != " ") {
				str = str.substring(i, str.length);
				break;
			}
		}

		for (i = str.length - 1; i >= 0; i--) {
			if (str.charAt(i) != " ") {
				str = str.substring(0, i + 1);
				break;
			}
		}

		if (str.charAt(0) == " ") {
			return "";
		} else {
			return str;
		}
	}
}

/*
 * This method is used for client-side validation in the commons-validation
 * framework. The original version used an 'alert'. We changed this to update
 * style of the invalid field. FIXME replace with Ext form validation.
 */
function validateRequired(form) {
	var bValid = true;
	var focusField = null;
	var i = 0;
	var fields = new Array();
	oRequired = new required();

	for (x in oRequired) {
		formid = oRequired[x][0] + ".label";
		labelel = document.getElementById(formid);
		if (!labelel) {
			continue;
		}
		if ((form[oRequired[x][0]].type == 'select-multiple'
				| form[oRequired[x][0]].type == 'file'
				|| form[oRequired[x][0]].type == 'text'
				|| form[oRequired[x][0]].type == 'textarea'
				|| form[oRequired[x][0]].type == 'select-one'
				|| form[oRequired[x][0]].type == 'radio' || form[oRequired[x][0]].type == 'password')
				&& form[oRequired[x][0]].value == '') {
			if (i == 0)
				focusField = form[oRequired[x][0]];

			fields[i++] = oRequired[x][1];
			labelel.setAttribute("class", "error");
			labelel.setAttribute("title", oRequired[x][1]);

			bValid = false;
		} else {
			labelel.setAttribute("class", "");
		}
	}

	if (fields.length > 0) {
		focusField.focus();
		// alert(fields.join('\n'));
	}

	return bValid;
}

// This function is a generic function to create form elements
function createFormElement(element, type, name, id, value, parent) {
	var e = document.createElement(element);
	e.setAttribute("name", name);
	e.setAttribute("type", type);
	e.setAttribute("id", id);
	e.setAttribute("value", value);
	parent.appendChild(e);
}

function confirmDelete(obj) {
	var msg = "Are you sure you want to delete this " + obj + "?";
	ans = confirm(msg);
	if (ans) {
		return true;
	} else {
		return false;
	}
}

function highlightTableRows(tableId) {
	var previousClass = null;
	var table = document.getElementById(tableId);
	var tbody = table.getElementsByTagName("tbody")[0];
	if (tbody == null) {
		var rows = table.getElementsByTagName("tr");
	} else {
		var rows = tbody.getElementsByTagName("tr");
	}
	// add event handlers so rows light up and are clickable
	for (i = 0; i < rows.length; i++) {
		rows[i].onmouseover = function() {
			previousClass = this.className;
			this.className += ' over'
		};
		rows[i].onmouseout = function() {
			this.className = previousClass
		};
		rows[i].onclick = function() {
			var cell = this.getElementsByTagName("td")[0];
			var link = cell.getElementsByTagName("a")[0];
			location.href = link.getAttribute("href");
			this.style.cursor = "wait";
		}
	}
}

window.defaultStatus = document.title;
<|endoftext|>


<commit_before>'use strict';
// gulp
var gulp = require('gulp');
var paths = gulp.paths;
var options = gulp.options;
// plugins
var $ = require('gulp-load-plugins')();
// modules
var wiredep = require('wiredep');
var mainBowerFiles = require('main-bower-files');

// inject app/**/*.js, bower components, css into index.html
// inject environment variables into config.js constant
gulp.task('inject-all', ['styles', 'wiredep', 'bower-fonts', 'environment', 'build-vars'], function () {

  return gulp.src('app/index.html')
    .pipe(
      $.inject( // app/**/*.js files
        gulp.src(paths.jsFiles)
          .pipe($.plumber()) // use plumber so watch can start despite js errors
          .pipe($.naturalSort())
          .pipe($.angularFilesort()),
        {relative: true}))
    .pipe(
      $.inject( // inject compiled css
        gulp.src('.tmp/*/styles/*.css', {read: false}),
        {
          ignorePath: '../.tmp',
          relative: true,
        }))
    .pipe(gulp.dest('app'));
});

// build styles to tmp
gulp.task('styles', ['clean'], function () {

  // compile css starting from each module's scss
  return gulp.src('app/*/styles/!(_)*.scss')
    .pipe($.plumber())
    .pipe($.sourcemaps.init())
    .pipe($.sass.sync().on('error', $.sass.logError))
    .pipe($.autoprefixer({ browsers: ['last 2 versions'], remove: false}))
    .pipe($.sourcemaps.write('.'))
    .pipe(gulp.dest('.tmp/'));
});

// inject bower components into index.html
gulp.task('wiredep', function () {

  return gulp.src('app/index.html')
<% if (answers.ionicCss) { -%>
    // we're not excluding the ionic css here
    .pipe(wiredep.stream())
<% } else { -%>
    // exclude ionic scss since we're using ionic sass
    .pipe(wiredep.stream({exclude: ['bower_components/ionic/release/css']}))
<% } -%>
    .pipe(gulp.dest('app/'));
});

// copy bower fonts
<% if (answers.ionicCss) { -%>
gulp.task('bower-fonts', ['clean'], function () {
  // to do www/fonts (ionic css requires it to be in this folder)
  var DEST = 'www/fonts';
  var fontFiles = mainBowerFiles({filter: /\.(eot|svg|ttf|woff)$/i});
<% } else { -%>
gulp.task('bower-fonts', function () {
  // to app/main/assets/fonts (path can be set in app/main/styles/<module>.scss)
  var DEST = 'app/main/assets/fonts';
  var fontFiles = mainBowerFiles({filter: /\.(eot|svg|ttf|woff)$/i})
    .concat('app/main/assets/fonts/**/*');
<% } -%>

  return gulp.src(fontFiles)
    .pipe($.changed(DEST))
    .pipe(gulp.dest(DEST));
});

/**
 * transforms object into a string format that is ready for injection at indentation 4
 * @param  {Object} obj Object with values to inject
 * @return {String}     properly formatted string
 */
var injectFormat = function (obj) {
  // indentation of 2
  obj = JSON.stringify(obj, null, 2);
  // replace all doublequotes with singlequotes
  obj = obj.replace(/\"/g, '\'');
  // remove first and last line curly braces
  obj = obj.replace(/^\{\n/, '').replace(/\n\}$/, '');
  // remove indentation of first line
  obj = obj.replace(/^( ){2}/, '');
  // insert padding for all remaining lines
  obj = obj.replace(/\n( ){2}/g, '\n    ');

  return obj;
};

gulp.task('environment', function () {
  return gulp.src('app/*/constants/*config-const.js')
    .pipe(
      $.inject(
        gulp.src('app/main/constants/env-' + options.env + '.json'),
        {
          starttag: '/*inject-env*/',
          endtag: '/*endinject*/',
          transform: function (filePath, file) {
            var json;
            try {
              json = JSON.parse(file.contents.toString('utf8'));
            }
            catch (e) {
              console.log(e);
            }

            if (json) {
              json = injectFormat(json);
            }
            return json;
          }
        }))
    .pipe(gulp.dest('app/'));
});

gulp.task('build-vars', ['environment'], function () {
  return gulp.src('app/*/constants/*config-const.js')
    .pipe(
      $.inject(
        gulp.src(''),
        {
          starttag: '/*inject-build*/',
          endtag: '/*endinject*/',
          transform: function () {
            var obj = {};
            var buildVars = options.buildVars;

            if (buildVars) {
              // loop over build variables
              var variables = buildVars.split(',');
              for (var i = 0, variable; ((variable = variables[i])); i++) {
                var splits = variable.split(':');
                // add key and value to object
                obj[splits[0]] = splits[1];
              }
              return injectFormat(obj);
            }
            else {
              return;
            }
          }
        }))
    .pipe(gulp.dest('app/'));
});
<commit_msg>fixes #256: inconsistent injection order of css files<commit_after>'use strict';
// gulp
var gulp = require('gulp');
var paths = gulp.paths;
var options = gulp.options;
// plugins
var $ = require('gulp-load-plugins')();
// modules
var wiredep = require('wiredep');
var mainBowerFiles = require('main-bower-files');

// inject app/**/*.js, bower components, css into index.html
// inject environment variables into config.js constant
gulp.task('inject-all', ['styles', 'wiredep', 'bower-fonts', 'environment', 'build-vars'], function () {

  return gulp.src('app/index.html')
    .pipe(
      $.inject( // app/**/*.js files
        gulp.src(paths.jsFiles)
          .pipe($.plumber()) // use plumber so watch can start despite js errors
          .pipe($.naturalSort())
          .pipe($.angularFilesort()),
        {relative: true}))
    .pipe(
      $.inject( // inject compiled css
        gulp.src('.tmp/*/styles/*.css', {read: false})
          .pipe($.naturalSort()),
        {
          ignorePath: '../.tmp',
          relative: true,
        }))
    .pipe(gulp.dest('app'));
});

// build styles to tmp
gulp.task('styles', ['clean'], function () {

  // compile css starting from each module's scss
  return gulp.src('app/*/styles/!(_)*.scss')
    .pipe($.plumber())
    .pipe($.sourcemaps.init())
    .pipe($.sass.sync().on('error', $.sass.logError))
    .pipe($.autoprefixer({ browsers: ['last 2 versions'], remove: false}))
    .pipe($.sourcemaps.write('.'))
    .pipe(gulp.dest('.tmp/'));
});

// inject bower components into index.html
gulp.task('wiredep', function () {

  return gulp.src('app/index.html')
<% if (answers.ionicCss) { -%>
    // we're not excluding the ionic css here
    .pipe(wiredep.stream())
<% } else { -%>
    // exclude ionic scss since we're using ionic sass
    .pipe(wiredep.stream({exclude: ['bower_components/ionic/release/css']}))
<% } -%>
    .pipe(gulp.dest('app/'));
});

// copy bower fonts
<% if (answers.ionicCss) { -%>
gulp.task('bower-fonts', ['clean'], function () {
  // to do www/fonts (ionic css requires it to be in this folder)
  var DEST = 'www/fonts';
  var fontFiles = mainBowerFiles({filter: /\.(eot|svg|ttf|woff)$/i});
<% } else { -%>
gulp.task('bower-fonts', function () {
  // to app/main/assets/fonts (path can be set in app/main/styles/<module>.scss)
  var DEST = 'app/main/assets/fonts';
  var fontFiles = mainBowerFiles({filter: /\.(eot|svg|ttf|woff)$/i})
    .concat('app/main/assets/fonts/**/*');
<% } -%>

  return gulp.src(fontFiles)
    .pipe($.changed(DEST))
    .pipe(gulp.dest(DEST));
});

/**
 * transforms object into a string format that is ready for injection at indentation 4
 * @param  {Object} obj Object with values to inject
 * @return {String}     properly formatted string
 */
var injectFormat = function (obj) {
  // indentation of 2
  obj = JSON.stringify(obj, null, 2);
  // replace all doublequotes with singlequotes
  obj = obj.replace(/\"/g, '\'');
  // remove first and last line curly braces
  obj = obj.replace(/^\{\n/, '').replace(/\n\}$/, '');
  // remove indentation of first line
  obj = obj.replace(/^( ){2}/, '');
  // insert padding for all remaining lines
  obj = obj.replace(/\n( ){2}/g, '\n    ');

  return obj;
};

gulp.task('environment', function () {
  return gulp.src('app/*/constants/*config-const.js')
    .pipe(
      $.inject(
        gulp.src('app/main/constants/env-' + options.env + '.json'),
        {
          starttag: '/*inject-env*/',
          endtag: '/*endinject*/',
          transform: function (filePath, file) {
            var json;
            try {
              json = JSON.parse(file.contents.toString('utf8'));
            }
            catch (e) {
              console.log(e);
            }

            if (json) {
              json = injectFormat(json);
            }
            return json;
          }
        }))
    .pipe(gulp.dest('app/'));
});

gulp.task('build-vars', ['environment'], function () {
  return gulp.src('app/*/constants/*config-const.js')
    .pipe(
      $.inject(
        gulp.src(''),
        {
          starttag: '/*inject-build*/',
          endtag: '/*endinject*/',
          transform: function () {
            var obj = {};
            var buildVars = options.buildVars;

            if (buildVars) {
              // loop over build variables
              var variables = buildVars.split(',');
              for (var i = 0, variable; ((variable = variables[i])); i++) {
                var splits = variable.split(':');
                // add key and value to object
                obj[splits[0]] = splits[1];
              }
              return injectFormat(obj);
            }
            else {
              return;
            }
          }
        }))
    .pipe(gulp.dest('app/'));
});
<|endoftext|>