<commit_before>'use strict';

/*jshint expr: true*/

const expect = require( 'chai' ).expect;

const jwtBuilder = require( 'jwt-builder' );

const token = require( '../../../lib/jwt/token' );

describe( 'lib/jwt/jwt', function() {

    describe( '.decode', function() {

        it( 'valid token', function() {

            const jwtToken = jwtBuilder( { algorithm: 'HS256', secret: 'super-secret', user: 'fred', iat: true, exp: 100 } );

            let decoded = token.decode( jwtToken, 'HS256', 'super-secret' );

            expect( decoded.iat ).to.exist;
            expect( decoded.exp ).to.exist;
            expect( decoded.user ).to.equal( 'fred' );
        });

        it( 'fail when invalid algorithm is used', function() {

            const jwtToken = jwtBuilder( { algorithm: 'HS256', secret: 'super-secret', user: 'fred', iat: true, exp: 100 } );

            expect( token.decode.bind( null, jwtToken, 'HS384', 'super-secret' ) ).to.throw( 'authentication error: Signature verification failed' );
        });

        it( 'fail when invalid key is used', function() {

            const jwtToken = jwtBuilder( { algorithm: 'HS256', secret: 'super-secret', user: 'fred', iat: true, exp: 100 } );

            expect( token.decode.bind( null, jwtToken, 'HS256', 'other-super-secret' ) ).to.throw( 'authentication error: Signature verification failed' );
        });

        it( 'fail when token is expired', function( done ) {

            const jwtToken = jwtBuilder( { algorithm: 'HS256', secret: 'super-secret', user: 'fred', iat: true, exp: 1 } );

            setTimeout( () => {

                try {

                    expect( token.decode.bind( null, jwtToken, 'HS256', 'super-secret' ) ).to.throw( 'authentication error: Token expired' );

                    done();
                }
                catch( err ) {

                    done( err );
                }
            }, 1001 );
        });

        it( 'fail when token issued at date is after current time', function() {

            const jwtToken = jwtBuilder( { algorithm: 'HS256', secret: 'super-secret', user: 'fred', iat: 100, exp: 100 } );

            expect( token.decode.bind( null, jwtToken, 'HS256', 'super-secret' ) ).to.throw( 'authentication error: token used before issue date' );
        });
    });
});
<commit_msg>improved test coverage<commit_after>'use strict';

/*jshint expr: true*/

const expect = require( 'chai' ).expect;

const jwtBuilder = require( 'jwt-builder' );

const token = require( '../../../lib/jwt/token' );

describe( 'lib/jwt/jwt', function() {

    describe( '.decode', function() {

        it( 'valid token', function() {

            const jwtToken = jwtBuilder( { algorithm: 'HS256', secret: 'super-secret', user: 'fred', iat: true, exp: 100 } );

            let decoded = token.decode( jwtToken, 'HS256', 'super-secret' );

            expect( decoded.iat ).to.exist;
            expect( decoded.exp ).to.exist;
            expect( decoded.user ).to.equal( 'fred' );
        });

        it( 'valid token, no iat', function() {

            const jwtToken = jwtBuilder( { algorithm: 'HS256', secret: 'super-secret', user: 'fred', iat: false, exp: 100 } );

            let decoded = token.decode( jwtToken, 'HS256', 'super-secret' );

            expect( decoded.iat ).to.not.exist;
            expect( decoded.exp ).to.exist;
            expect( decoded.user ).to.equal( 'fred' );
        });

        it( 'fail when invalid algorithm is used', function() {

            const jwtToken = jwtBuilder( { algorithm: 'HS256', secret: 'super-secret', user: 'fred', iat: true, exp: 100 } );

            expect( token.decode.bind( null, jwtToken, 'HS384', 'super-secret' ) ).to.throw( 'authentication error: Signature verification failed' );
        });

        it( 'fail when invalid key is used', function() {

            const jwtToken = jwtBuilder( { algorithm: 'HS256', secret: 'super-secret', user: 'fred', iat: true, exp: 100 } );

            expect( token.decode.bind( null, jwtToken, 'HS256', 'other-super-secret' ) ).to.throw( 'authentication error: Signature verification failed' );
        });

        it( 'fail when token is expired', function( done ) {

            const jwtToken = jwtBuilder( { algorithm: 'HS256', secret: 'super-secret', user: 'fred', iat: true, exp: 1 } );

            setTimeout( () => {

                try {

                    expect( token.decode.bind( null, jwtToken, 'HS256', 'super-secret' ) ).to.throw( 'authentication error: Token expired' );

                    done();
                }
                catch( err ) {

                    done( err );
                }
            }, 1001 );
        });

        it( 'fail when token issued at date is after current time', function() {

            const jwtToken = jwtBuilder( { algorithm: 'HS256', secret: 'super-secret', user: 'fred', iat: 100, exp: 100 } );

            expect( token.decode.bind( null, jwtToken, 'HS256', 'super-secret' ) ).to.throw( 'authentication error: token used before issue date' );
        });
    });

    describe( '.validateXSRF', function() {

        it( 'valid token', function() {

            let xsrfToken = "xsrf-" + Date.now().toString();

            let decoded = {

                stuff: 'whatever',
                nonce: xsrfToken
            };

            token.validateXSRF( decoded, xsrfToken, [ 'nonce' ] );
        });

        it( 'fail: missing token', function() {

            let decoded = {

                stuff: 'whatever',
                nonce: 'token-here'
            };

            expect( token.validateXSRF.bind( null, decoded, null, [ 'nonce' ] ) ).to.throw( 'authentication error: missing xsrf token' );
        });

        it( 'fail: missing token', function() {

            let xsrfToken = "xsrf-" + Date.now().toString();

            let decoded = {

                stuff: 'whatever'
            };

            expect( token.validateXSRF.bind( null, decoded, xsrfToken, [ 'nonce' ] ) ).to.throw( 'authentication error: xsrf claim missing' );
        });

        it( 'fail: missing token', function() {

            let xsrfToken = "xsrf-" + Date.now().toString();

            let decoded = {

                stuff: 'whatever',
                nonce: xsrfToken + 'x'
            };

            expect( token.validateXSRF.bind( null, decoded, xsrfToken, [ 'nonce' ] ) ).to.throw( 'authentication error: xsrf token mismatch' );
        });
    });
});
<|endoftext|>


<commit_before>var dataForm = require('../../../lib/utils/xep-0004')
  , should   = require('should')
  , helper   = require('../../helper')
  , ltx      = require('ltx')

describe('XEP-0004', function() {

    it('Should export the data form namespace', function() {
        dataForm.NS.should.equal('jabber:x:data')
    })

    describe('Add a data form to a stanza', function() {

        var stanza

        beforeEach(function() {
            stanza = new ltx.Element('iq')
        })

        it('Can add an empty data form', function() {
            dataForm.addForm(stanza, [], 'some-data-form')
            var x = stanza.getChild('x', dataForm.NS)
            x.attrs.type.should.equal('submit')
            var field = x.getChild('field')
            field.attrs.var.should.equal('FORM_TYPE')
            field.attrs.type.should.equal('hidden')
            field.getChild('value').getText().should.equal('some-data-form')
            x.getChildren('field').length.should.equal(1)
        })

        it('Can add field with boolean value', function() {
            dataForm.addForm(stanza, [{ var: 'field1', value: true }], 'df')
            var field = stanza.getChild('x').getChildren('field')[1]
            field.attrs.var.should.equal('field1')
            field.getChild('value').getText().should.equal('true')
        })

        it('Can add a string value', function() {
            dataForm.addForm(stanza, [{ var: 'field2', value: 'hello' }], 'df')
            var field = stanza.getChild('x').getChildren('field')[1]
            field.attrs.var.should.equal('field2')
            field.getChild('value').getText().should.equal('hello')
        })

        it('Can add a number value', function() {
            dataForm.addForm(stanza, [{ var: 'field3', value: 222 }], 'df')
            var field = stanza.getChild('x').getChildren('field')[1]
            field.attrs.var.should.equal('field3')
            field.getChild('value').getText().should.equal('222')
        })

        it('Can add an array of values', function() {
            dataForm.addForm(
                stanza,
                [{ var: 'field4', value: [ 'hello', 'world' ] }],
                'df'
            )
            var field = stanza.getChild('x').getChildren('field')[1]
            field.attrs.var.should.equal('field4')
            field.getChildren('value').length.should.equal(2)
            var values = field.getChildren('value')
            values[0].getText().should.equal('hello')
            values[1].getText().should.equal('world')
        })
    })

    describe('Can parse data form from details', function() {

        var stanza

        beforeEach(function() {
            stanza = helper.getStanza('xep-0004/empty-form')
        })

        it('Can parse empty data form', function() {
            var form = dataForm.parseFields(stanza)
            form.title.should.equal('form-title')
            form.instructions.should.equal('form-instructions')
            should.exist(form.fields)
        })

        it('Does not add \'FORM_TYPE\' fields', function() {
            stanza.c('field', { type:'FORM_TYPE' })
            var form = dataForm.parseFields(stanza)
            form.fields.length.should.equal(0)
        })

        it('Can parse a very basic form field', function() {
            stanza.c('field', { type: 'text-single', var: 'field1' })
            var form = dataForm.parseFields(stanza)
            form.fields.length.should.equal(1)
            form.fields[0].var.should.equal('field1')
            form.fields[0].type.should.equal('text-single')
            form.fields[0].required.should.equal.false
        })

        it('Can parse basic form field', function() {
            var stanza = helper.getStanza('xep-0004/single-basic-field')
            var form = dataForm.parseFields(stanza)
            form.fields.length.should.equal(1)
            form.fields[0].var.should.equal('field1')
            form.fields[0].type.should.equal('text-single')
            form.fields[0].required.should.equal.true
            form.fields[0].description.should.equal('field1-description')
            form.fields[0].value.should.equal('value1')
            form.fields[0].label.should.equal('label1')
        })

        it('Can parse multi-select field', function() {
            var stanza = helper.getStanza('xep-0004/multi-select-field')
            var form = dataForm.parseFields(stanza)
            form.fields.length.should.equal(1)
            form.fields[0].var.should.equal('field1')
            form.fields[0].type.should.equal('list-multi')
            form.fields[0].required.should.equal.true
            form.fields[0].description.should.equal('field1-description')
            form.fields[0].label.should.equal('label1')
            form.fields[0].options.length.should.equal(3)
            form.fields[0].options[0].should.eql(
               { label: 'label3', value: 'value3' }
            )
            form.fields[0].value.length.should.equal(2)
            form.fields[0].value[0].should.equal('value1')
            form.fields[0].value[1].should.equal('value2')
        })

    })
})
<commit_msg>Fixing bad test<commit_after>var dataForm = require('../../../lib/utils/xep-0004')
  , should   = require('should')
  , helper   = require('../../helper')
  , ltx      = require('ltx')

describe('XEP-0004', function() {

    it('Should export the data form namespace', function() {
        dataForm.NS.should.equal('jabber:x:data')
    })

    describe('Add a data form to a stanza', function() {

        var stanza

        beforeEach(function() {
            stanza = new ltx.Element('iq')
        })

        it('Can add an empty data form', function() {
            dataForm.addForm(stanza, [], 'some-data-form')
            var x = stanza.getChild('x', dataForm.NS)
            x.attrs.type.should.equal('submit')
            var field = x.getChild('field')
            field.attrs.var.should.equal('FORM_TYPE')
            field.attrs.type.should.equal('hidden')
            field.getChild('value').getText().should.equal('some-data-form')
            x.getChildren('field').length.should.equal(1)
        })

        it('Can add field with boolean value', function() {
            dataForm.addForm(stanza, [{ var: 'field1', value: true }], 'df')
            var field = stanza.getChild('x').getChildren('field')[1]
            field.attrs.var.should.equal('field1')
            field.getChild('value').getText().should.equal('true')
        })

        it('Can add a string value', function() {
            dataForm.addForm(stanza, [{ var: 'field2', value: 'hello' }], 'df')
            var field = stanza.getChild('x').getChildren('field')[1]
            field.attrs.var.should.equal('field2')
            field.getChild('value').getText().should.equal('hello')
        })

        it('Can add a number value', function() {
            dataForm.addForm(stanza, [{ var: 'field3', value: 222 }], 'df')
            var field = stanza.getChild('x').getChildren('field')[1]
            field.attrs.var.should.equal('field3')
            field.getChild('value').getText().should.equal('222')
        })

        it('Can add an array of values', function() {
            dataForm.addForm(
                stanza,
                [{ var: 'field4', value: [ 'hello', 'world' ] }],
                'df'
            )
            var field = stanza.getChild('x').getChildren('field')[1]
            field.attrs.var.should.equal('field4')
            field.getChildren('value').length.should.equal(2)
            var values = field.getChildren('value')
            values[0].getText().should.equal('hello')
            values[1].getText().should.equal('world')
        })
    })

    describe('Can parse data form from details', function() {

        var stanza

        beforeEach(function() {
            stanza = helper.getStanza('xep-0004/empty-form')
        })

        it('Can parse empty data form', function() {
            var form = dataForm.parseFields(stanza)
            form.title.should.equal('form-title')
            form.instructions.should.equal('form-instructions')
            should.exist(form.fields)
        })

        it('Does not add \'FORM_TYPE\' fields', function() {
            stanza.c('field', { var:'FORM_TYPE' })
            var form = dataForm.parseFields(stanza)
            form.fields.length.should.equal(0)
        })

        it('Can parse a very basic form field', function() {
            stanza.c('field', { type: 'text-single', var: 'field1' })
            var form = dataForm.parseFields(stanza)
            form.fields.length.should.equal(1)
            form.fields[0].var.should.equal('field1')
            form.fields[0].type.should.equal('text-single')
            form.fields[0].required.should.equal.false
        })

        it('Can parse basic form field', function() {
            var stanza = helper.getStanza('xep-0004/single-basic-field')
            var form = dataForm.parseFields(stanza)
            form.fields.length.should.equal(1)
            form.fields[0].var.should.equal('field1')
            form.fields[0].type.should.equal('text-single')
            form.fields[0].required.should.equal.true
            form.fields[0].description.should.equal('field1-description')
            form.fields[0].value.should.equal('value1')
            form.fields[0].label.should.equal('label1')
        })

        it('Can parse multi-select field', function() {
            var stanza = helper.getStanza('xep-0004/multi-select-field')
            var form = dataForm.parseFields(stanza)
            form.fields.length.should.equal(1)
            form.fields[0].var.should.equal('field1')
            form.fields[0].type.should.equal('list-multi')
            form.fields[0].required.should.equal.true
            form.fields[0].description.should.equal('field1-description')
            form.fields[0].label.should.equal('label1')
            form.fields[0].options.length.should.equal(3)
            form.fields[0].options[0].should.eql(
               { label: 'label3', value: 'value3' }
            )
            form.fields[0].value.length.should.equal(2)
            form.fields[0].value[0].should.equal('value1')
            form.fields[0].value[1].should.equal('value2')
        })

    })
})
<|endoftext|>


<commit_before>angular.module('travel.ratings', ['ui.bootstrap', 'ngAnimate'])

.controller('RatingsController', function ($scope, $window, $rootScope, $state, $uibModal, CurrentInfo, Venues, Groups, Util) {
  $scope.filteredUserRatings = [];
  $scope.filteredGroupRatings  = [];
  $scope.city = $rootScope.destination;
  $scope.heading = null;
  $scope.allVenuesRatings = [];
  $scope.groups = [];

  ////////////////// GET ALL THE GROUPS OF A USER //////////////////////

  $scope.getUserGroups = function() {
    Groups.getUserGroups($rootScope.currentUser._id)
      .then(function(groupsInfo){
        $scope.groups = groupsInfo;
      });
  };

  ////////////////// SELECTING A GROUP WILL REROUTE TO RATINGS //////////////////////

  $scope.selectGroup = Groups.selectGroup(function () {
    $state.go('ratings');
  });

  ////////////////// FILTER FOR RESTAURANTS/ATTRACTIONS/HOTELS //////////////////////

  $scope.filterRatings = function (filterType) {
    if (!$scope.allVenuesRatings.length) return;

    var venues = [];
    var groupRatings = [];
    var userRatings = [];
    var userId = $rootScope.currentUser._id;

    // set heading to appropriate value
    if (filterType === 1) {
      $scope.heading = 'Hotels';
    } else if (filterType === 2) {
      $scope.heading = 'Restaurants';
    } else if (filterType === 3) {
      $scope.heading = 'Attractions';
    }

    // populate venues with appropriate results
    // not working with groups removed this code...
    // if (favorite.userInfo === $rootScope.currentUser) {
    //   console.log(favorite.venue);
    // } else {
    //   GroupRatings.push(favorite);
    // }

    $scope.allVenuesRatings.forEach(function(ven) {
      if (ven.venue.venue_type_id === filterType) {
        venues.push(ven);
      }
    });
    venues.forEach(function(ven) {
      $scope.addAvg(ven);
      ven.allRatings.forEach(function(rating) {
        if (rating.user === userId) {
          ven.currentRating = rating.userRating;
          userRatings.push(ven);
        }
      });
    });
    $scope.filteredGroupRatings = groupRatings;
    $scope.filteredUserRatings  = userRatings;
    console.log(userRatings);
  };

  ////////////////// ADD AVERAGES FOR A VENUE //////////////////////

  $scope.addAvg = function (venue) {
    var total = 0;
    var numberofRatings = 0;
    venue.allRatings.forEach(function(rating){
      if (rating.userRating !== 0) {
        total += rating.userRating;
        numberofRatings ++;
      }
    });
    console.log(total);
    console.log(numberofRatings);
    venue.avgRating = (total / numberofRatings) || 0;
  };

  ////////////////// GET ALL RATINGS OF THE GROUP //////////////////////

  $scope.getRatings = function() {
    var userId = $rootScope.currentUser._id;
    var groupId = $rootScope.currentGroup._id;
    var query = {
      userId : userId,
      groupId : groupId
    };
    Venues.getRatings(query)
      .then(function(venuesInfo){
        console.log(venuesInfo);
        $scope.allVenuesRatings = venuesInfo;
        $scope.filterRatings(1);
      });
  };

  // $scope.fetchUserFavorites = function () {
  //   var userId = $rootScope.currentUser._id;
  //   Venues.getUserFavorites(userId)
  //   .then(function(favorites) {
  //     $scope.allVenuesRatings = favorites;
  //     console.log('favorites', $scope.allVenuesRatings);
  //     $scope.filterRatings(1);
  //   });
  // };

  ////////////////// USER ADD RATING //////////////////////

  $scope.ratings = {};
  $scope.max = 10;
  $scope.isReadonly = false;
  $scope.showRatings = {};
  $scope.hoveringOver = function(value,id) {
    $scope.showRatings[id] = value;
  };

  $scope.addRating = function(venueData, rating) {
    var userId = $rootScope.currentUser._id;
    venueData.allRatings.forEach(function(rate) {
      if (rate.user = userId) {
        rate.userRating = rating;
      };
    });
    venueData.currentRating = rating;
    console.log(venueData);
    $scope.addAvg(venueData);
    var data = {
      venue : venueData.venue,
      userId : userId,
      groupId : $rootScope.currentGroup._id,
      rating : rating
    };
    Venues.addRating(data);
  };

  ////////////////// GET DETAILED INFO OF A VENUE //////////////////////

  // Sets image carousel interval
  $scope.myInterval = 5000;
  $scope.noWrapSlides = false;
  $scope.moreInfo = $rootScope.moreInfo;
  $scope.phoneHide = $rootScope.phoneHide;

  $scope.getDetailedVenueInfo = function(venue) {
    if (venue.venue.telephone === null) {
      $rootScope.phoneHide = true;
    } else {
      $rootScope.phoneHide = false;
    }
    $rootScope.moreInfo = venue;
    $scope.moreInfo = venue;
    $scope.openModal();
  };
  $scope.exit = function(){
    $uibModalInstance.close();
  };
  $scope.openModal = function() {
    var modalInstance = $uibModal.open({
      animation: $scope.animationsEnabled,
      templateUrl: 'app/ratings/moreInfo.html',
      controller: 'RatingsController',
    });
  };

  ////////////////// ADMIN ONLY //////////////////////

  $scope.addtoItin = function(venueData) {
    var data = {
      venue : venueData,
      userId : $rootScope.currentUser._id,
      groupId : $rootScope.currentGroup._id,
      startDate : null,
      endDate : null
    };
    Venues.addtoItinerary(data);
  };

  ////////////////// INIT STATE //////////////////////

  $scope.getRatings();

});<commit_msg>fixed jshint issues<commit_after>angular.module('travel.ratings', ['ui.bootstrap', 'ngAnimate'])

.controller('RatingsController', function ($scope, $window, $rootScope, $state, $uibModal, CurrentInfo, Venues, Groups, Util) {
  $scope.filteredUserRatings = [];
  $scope.filteredGroupRatings  = [];
  $scope.city = $rootScope.destination;
  $scope.heading = null;
  $scope.allVenuesRatings = [];
  $scope.groups = [];

  ////////////////// GET ALL THE GROUPS OF A USER //////////////////////

  $scope.getUserGroups = function() {
    Groups.getUserGroups($rootScope.currentUser._id)
      .then(function(groupsInfo){
        $scope.groups = groupsInfo;
      });
  };

  ////////////////// SELECTING A GROUP WILL REROUTE TO RATINGS //////////////////////

  $scope.selectGroup = Groups.selectGroup(function () {
    $state.go('ratings');
  });

  ////////////////// FILTER FOR RESTAURANTS/ATTRACTIONS/HOTELS //////////////////////

  $scope.filterRatings = function (filterType) {
    if (!$scope.allVenuesRatings.length) return;

    var venues = [];
    var groupRatings = [];
    var userRatings = [];
    var userId = $rootScope.currentUser._id;

    // set heading to appropriate value
    if (filterType === 1) {
      $scope.heading = 'Hotels';
    } else if (filterType === 2) {
      $scope.heading = 'Restaurants';
    } else if (filterType === 3) {
      $scope.heading = 'Attractions';
    }

    // populate venues with appropriate results
    // not working with groups removed this code...
    // if (favorite.userInfo === $rootScope.currentUser) {
    //   console.log(favorite.venue);
    // } else {
    //   GroupRatings.push(favorite);
    // }

    $scope.allVenuesRatings.forEach(function(ven) {
      if (ven.venue.venue_type_id === filterType) {
        venues.push(ven);
      }
    });
    venues.forEach(function(ven) {
      $scope.addAvg(ven);
      ven.allRatings.forEach(function(rating) {
        if (rating.user === userId) {
          ven.currentRating = rating.userRating;
          userRatings.push(ven);
        }
      });
    });
    $scope.filteredGroupRatings = groupRatings;
    $scope.filteredUserRatings  = userRatings;
    console.log(userRatings);
  };

  ////////////////// ADD AVERAGES FOR A VENUE //////////////////////

  $scope.addAvg = function (venue) {
    var total = 0;
    var numberofRatings = 0;
    venue.allRatings.forEach(function(rating){
      if (rating.userRating !== 0) {
        total += rating.userRating;
        numberofRatings ++;
      }
    });
    console.log(total);
    console.log(numberofRatings);
    venue.avgRating = (total / numberofRatings) || 0;
  };

  ////////////////// GET ALL RATINGS OF THE GROUP //////////////////////

  $scope.getRatings = function() {
    var userId = $rootScope.currentUser._id;
    var groupId = $rootScope.currentGroup._id;
    var query = {
      userId : userId,
      groupId : groupId
    };
    Venues.getRatings(query)
      .then(function(venuesInfo){
        console.log(venuesInfo);
        $scope.allVenuesRatings = venuesInfo;
        $scope.filterRatings(1);
      });
  };

  // $scope.fetchUserFavorites = function () {
  //   var userId = $rootScope.currentUser._id;
  //   Venues.getUserFavorites(userId)
  //   .then(function(favorites) {
  //     $scope.allVenuesRatings = favorites;
  //     console.log('favorites', $scope.allVenuesRatings);
  //     $scope.filterRatings(1);
  //   });
  // };

  ////////////////// USER ADD RATING //////////////////////

  $scope.ratings = {};
  $scope.max = 10;
  $scope.isReadonly = false;
  $scope.showRatings = {};
  $scope.hoveringOver = function(value,id) {
    $scope.showRatings[id] = value;
  };

  $scope.addRating = function(venueData, rating) {
    var userId = $rootScope.currentUser._id;
    venueData.allRatings.forEach(function(rate) {
      if (rate.user === userId) {
        rate.userRating = rating;
      }
    });
    venueData.currentRating = rating;
    console.log(venueData);
    $scope.addAvg(venueData);
    var data = {
      venue : venueData.venue,
      userId : userId,
      groupId : $rootScope.currentGroup._id,
      rating : rating
    };
    Venues.addRating(data);
  };

  ////////////////// GET DETAILED INFO OF A VENUE //////////////////////

  // Sets image carousel interval
  $scope.myInterval = 5000;
  $scope.noWrapSlides = false;
  $scope.moreInfo = $rootScope.moreInfo;
  $scope.phoneHide = $rootScope.phoneHide;

  $scope.getDetailedVenueInfo = function(venue) {
    if (venue.venue.telephone === null) {
      $rootScope.phoneHide = true;
    } else {
      $rootScope.phoneHide = false;
    }
    $rootScope.moreInfo = venue;
    $scope.moreInfo = venue;
    $scope.openModal();
  };
  $scope.exit = function(){
    $uibModalInstance.close();
  };
  $scope.openModal = function() {
    var modalInstance = $uibModal.open({
      animation: $scope.animationsEnabled,
      templateUrl: 'app/ratings/moreInfo.html',
      controller: 'RatingsController',
    });
  };

  ////////////////// ADMIN ONLY //////////////////////

  $scope.addtoItin = function(venueData) {
    var data = {
      venue : venueData,
      userId : $rootScope.currentUser._id,
      groupId : $rootScope.currentGroup._id,
      startDate : null,
      endDate : null
    };
    Venues.addtoItinerary(data);
  };

  ////////////////// INIT STATE //////////////////////

  $scope.getRatings();

});<|endoftext|>


<commit_before>// @flow
import React from 'react';
import Uploader from './Uploader';
import CanvasComponent from './Canvas';
import TitleBar from 'react-window-titlebar';
import ActionBar from './ActionBar';
import {bindActionCreators} from 'redux';
import {updateCanvasImage, updateTitle} from '../actions/canvas';
import {connect} from 'react-redux';
import {remote} from 'electron';
import Icon from './Icon';
import {saveImage, saveDialog} from '../utils';

class Editor extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			stage: null
		}
	}

	onImage = (files) => {
		this.props.updateCanvasImage(files[0].path);
		this.props.updateTitle(files[0].name);
		this.setState({
			filename: files[0].path // extract filename from image
		})
	}

	showUploader = () => {
		return <Uploader onDrop={this.onImage} className="uploader" activeClassName="active">

Drop image here & start editing

				</Uploader>
	}

	onDowload = () => {
		const {stage, filename} = this.state;
		let newImage = stage.getStage().toDataURL().replace(/^data:image\/png;base64,/, ""); // get canvas dataurl data and strip data meta ( we don't need it to save file to disk )
		saveDialog(filename, (name) => saveImage(name, newImage));
	}

	render () {
		const {image, width, height, rotation, title} = this.props.canvas;
		return (

				<TitleBar remote={remote} title={title} theme="light"/>
				{ image ?

					<CanvasComponent getStage={(stage) => this.setState({stage})} rotation={rotation} bgImage={image} width={width} height={height} />
					<ActionBar>
						<button className="btn btn-default">
							<Icon name="sliders" />
						</button>
						<button onClick={this.onDowload} className="btn btn-default">
							<Icon name="download" />
						</button>
					</ActionBar>

 : this.showUploader()}

		)
	}
}

export default connect((state) => ({
	canvas: state.canvas
}), (dispatch) => bindActionCreators({updateCanvasImage, updateTitle}, dispatch)
)(Editor);<commit_msg>removed effects button<commit_after>// @flow
import React from 'react';
import Uploader from './Uploader';
import CanvasComponent from './Canvas';
import TitleBar from 'react-window-titlebar';
import ActionBar from './ActionBar';
import {bindActionCreators} from 'redux';
import {updateCanvasImage, updateTitle} from '../actions/canvas';
import {connect} from 'react-redux';
import {remote} from 'electron';
import Icon from './Icon';
import {saveImage, saveDialog} from '../utils';

class Editor extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			stage: null
		}
	}

	onImage = (files) => {
		this.props.updateCanvasImage(files[0].path);
		this.props.updateTitle(files[0].name);
		this.setState({
			filename: files[0].path // extract filename from image
		})
	}

	showUploader = () => {
		return <Uploader onDrop={this.onImage} className="uploader" activeClassName="active">

Drop image here & start editing

				</Uploader>
	}

	onDowload = () => {
		const {stage, filename} = this.state;
		let newImage = stage.getStage().toDataURL().replace(/^data:image\/png;base64,/, ""); // get canvas dataurl data and strip data meta ( we don't need it to save file to disk )
		saveDialog(filename, (name) => saveImage(name, newImage));
	}

	render () {
		const {image, width, height, rotation, title} = this.props.canvas;
		return (

				<TitleBar remote={remote} title={title} theme="light"/>
				{ image ?

					<CanvasComponent getStage={(stage) => this.setState({stage})} rotation={rotation} bgImage={image} width={width} height={height} />
					<ActionBar>
						<button onClick={this.onDowload} className="btn btn-default">
							<Icon name="download" />
						</button>
					</ActionBar>

 : this.showUploader()}

		)
	}
}

export default connect((state) => ({
	canvas: state.canvas
}), (dispatch) => bindActionCreators({updateCanvasImage, updateTitle}, dispatch)
)(Editor);<|endoftext|>


<commit_before><commit_msg>Add test for favicon middleware<commit_after>require('../helper')

describe('Favicon middleware', function(){
  var app
  beforeEach(function() {
    app = starweb()
    app.on('error', function(err) {
      console.log(err.stack)
    })
  })

  it('serves default favicon', function(done) {
    app.use(app.favicon())
    request(app.run())
      .get('/favicon.ico')
      .expect(200)
      .expect('Content-Type', 'image/x-icon')
      .end(done)
  })

  it('ignores non-favicon request', function(done) {
    app.use(app.favicon())
    app.use(function *(next) {
      this.body = 'whatever'
      yield next
    })
    request(app.run())
      .get('/notfavicon')
      .expect(200, 'whatever')
      .expect('Content-Type', 'text/plain')
      .end(done)
  })

  it('serves custom favicon', function(done) {
    app.use(app.favicon('notexist'))
    request(app.run())
      .get('/favicon.ico')
      .expect(404)
      .end(done)
  })
})<|endoftext|>


<commit_before>'use strict';

/* js wirte for teain
 * design and code by Yuzo
 */

/* App Module */

var teaApp = angular.module('tea', [
    'ngRoute',
    'ngAnimate',
    'ngCookies',
    'teaControllers'
]);

teaApp.config(['$routeProvider',
    function($routeProvider) {
        $routeProvider.
        when('/', {
            templateUrl: '/static/tea/partials/tea-index.html',
            controller: 'indexController'
        }).
        when('/item/:itemID', {
            templateUrl: '/static/tea/partials/tea-item.html',
            controller: 'detailController'
        }).
        when('/register', {
            templateUrl: '/static/tea/partials/tea-register.html',
            controller: 'registerController'
        }).
        when('/login', {
            templateUrl: '/static/tea/partials/tea-login.html',
            controller: 'loginController'
        }).
        when('/flow', {
            templateUrl: '/static/tea/partials/tea-flow.html',
            controller: 'flowController'
        }).
        when('/raise', {
            templateUrl: '/static/tea/partials/tea-raise.html',
            controller: 'raiseController'
        }).
        when('/ucenter', {
            templateUrl: '/static/tea/partials/tea-ucenter.html',
            controller: 'ucenterController'
        }).
        when('/weibo', {
            templateUrl: '/static/tea/partials/tea-weibo.html',
            controller: 'weiboController'
        }).
        otherwise({
            redirectTo: '/'
        });
    }
]);

teaApp.run(function($rootScope, $cookies) {
    //app range initalize
    window.baseurl = '';
    //stoke update
    $rootScope.$on('$routeChangeSuccess', function(event, current) {
        //console.log(event, current);
        var total = document.querySelectorAll('.entry');
        angular.element(total).removeClass('selected');
    });
    //addPrefix function
    window.addPrefix = function addPrefix(data) {
        for (var i = data.length - 1; i >= 0; i--) {
            data[i].fields.img_src = baseurl + '/media/' + data[i].fields.img_src;
        };
        return data;
    }
    //myAlert function
    window.myAlert = function myAlert(text) {
        var target = document.querySelector('#myAlert');
        angular.element(target).html(text);

        angular.element(target).css('display', 'block');
        setTimeout(function() {
            angular.element(target).css('opacity', '0.9');
        }, 50);

        function fadeOut() {
            angular.element(target).css('opacity', '0');
            setTimeout(function() {
                angular.element(target).css('display', 'none');
            }, 800);
        };

        setTimeout(function() {
            fadeOut();
        }, 3000);
        target.addEventListener('click', function() {
            fadeOut();
        });
    }
    //change text of the login button
    if ($cookies.username) {
        var target = document.querySelector('#toRegister');
        angular.element(target).text($cookies.username);
    }
    //toRegister function
    window.toRegister = function toRegister() {
        //console.log($cookies);
        if ($cookies.username) {
            if (confirm("退出当前账户？")) {
                //buggy?
                //$cookies.username = "";
                document.cookie = 'username=';
                window.location.reload();
            };
        } else {
            window.location.href = '#/register';
        }
    }
});

/* Controllers */

var teaControllers = angular.module('teaControllers', []);

teaControllers.controller('indexController', ['$scope', '$http', '$cookies',
    function($scope, $http, $cookies) {
        var path = baseurl + '/api/get_cloth_list/1/6/';
        //console.log(path);
        $http.get(path).success(function(data) {
            $scope.clothes = addPrefix(data);
            //control welcome banner
            if (!$cookies.username) {
                var target = document.querySelector('#welcome')
                angular.element(target).css('display', 'block');
            }
        });
    }
]);

teaControllers.controller('detailController', ['$scope', '$routeParams', '$http', '$cookies',
    function($scope, $routeParams, $http, $cookies) {
        //init functions
        var path = baseurl + '/api/get_cloth/' + $routeParams.itemID + '/';
        //console.log(path);
        $http.get(path).success(function(data) {
            $scope.cloth = addPrefix(data)[0];
        });

        var path = baseurl + '/api/get_cloth_sizes/' + $routeParams.itemID + '/';
        $http.get(path).success(function(data) {
            $scope.sizes = data;
        });

        var path = baseurl + '/api/get_cloth_imgs/' + $routeParams.itemID + '/';
        $http.get(path).success(function(data) {
            $scope.imgs = addPrefix(data);
            angular.element(document).ready(function() {
                var clickEvent = document.createEvent("MouseEvents");
                clickEvent.initEvent("click", true, true);
                document.querySelector('.imgs img').dispatchEvent(clickEvent);
            });
        });

        var path = baseurl + '/api/get_cloth_descs/' + $routeParams.itemID + '/';
        $http.get(path).success(function(data) {
            $scope.descs = addPrefix(data);
        });

        //interact functions
        $scope.changeImg = function(img, $event) {
            var imgNodes = document.querySelectorAll('.imgs img')
            angular.element(imgNodes).removeClass('selected');
            angular.element($event.target).addClass('selected');
            //$event.target.className = 'selected';
            for (var i = $scope.imgs.length - 1; i >= 0; i--) {
                if ($scope.imgs[i].pk === img.pk) {
                    $scope.cloth.fields.img_src = $scope.imgs[i].fields.img_src;
                    break;
                }
            };
        }
        $scope.changeSize = function(size, $event) {
            var sizeNodes = document.querySelectorAll('.sizes li');
            //console.log(sizeNodes);
            angular.element(sizeNodes).removeClass('selected');
            angular.element($event.target).addClass('selected');
        }

        //purchase functions
        $scope.num = 1;
        //get csrf
        var path = baseurl + '/api/make_order/';
        $http.get(path);
        //buyButton
        $scope.buy = function buy(clothID, num) {
            var postData = {
                user_id: $cookies.userID,
                cloth_id: clothID,
                num: num,
                csrfmiddlewaretoken: $cookies.csrftoken
            }

            var config = {
                method: 'POST',
                url: path,
                data: postData,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                transformRequest: function(obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
                    }
                    return str.join('&');
                }
            }

            $http(config).success(function(data) {
                if (data == 'ok') {
                    myAlert(' 购买成功');
                } else {
                    myAlert(' 购买失败');
                }
            });
        }
    }
]);

teaControllers.controller('registerController', ['$scope', '$http', '$cookies',
    function($scope, $http, $cookies) {
        var current = document.querySelector('#toRegister');
        angular.element(current).addClass('selected');

        //get csrf
        var path = baseurl + '/accounts/register/';
        $http.get(path);

        $scope.checkMust = function checkMust($event) {
            //console.log($event.target);
            var target = angular.element($event.target);
            if (target.val()) {
                target.removeClass('invalid');
                target.addClass('valid');
            } else {
                target.removeClass('valid');
                target.addClass('invalid');
            }
        }

        $scope.register = function register() {
            $scope.info.csrfmiddlewaretoken = $cookies.csrftoken;

            var config = {
                method: 'POST',
                url: path,
                data: $scope.info,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                transformRequest: function(obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
                    }
                    return str.join('&');
                }
            }

            $http(config).success(function(data) {
                if (data == 'ok') {
                    myAlert(' 注册成功');
                    var path = baseurl + '/accounts/userinfo/';
                    $http.get(path).success(function(data) {
                        //console.log(data);
                        $cookies.username = data[0].fields.username;
                        $cookies.userID = data[0].pk;
                        setTimeout(function() {
                            window.location.href = '/';
                        }, 1000)
                    })
                } else {
                    myAlert(' 注册失败');
                }
            });
        }
    }
]);

teaControllers.controller('loginController', ['$scope', '$http', '$cookies',
    function($scope, $http, $cookies) {
        var current = document.querySelector('#toRegister');
        angular.element(current).addClass('selected');

        //get csrf
        var path = baseurl + '/accounts/login/';
        $http.get(path);

        $scope.checkMust = function checkMust($event) {
            //console.log($event.target);
            var target = angular.element($event.target);
            if (target.val()) {
                target.removeClass('invalid');
                target.addClass('valid');
            } else {
                target.removeClass('valid');
                target.addClass('invalid');
            }
        }

        $scope.login = function login() {
            $scope.info.csrfmiddlewaretoken = $cookies.csrftoken;

            var config = {
                method: 'POST',
                url: path,
                data: $scope.info,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                transformRequest: function(obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
                    }
                    return str.join('&');
                }
            }

            $http(config).success(function(data) {
                if (data == 'ok') {
                    myAlert(' 登录成功');
                    var path = baseurl + '/accounts/userinfo/';
                    $http.get(path).success(function(data) {
                        //console.log(data);
                        $cookies.username = data[0].fields.username;
                        $cookies.userID = data[0].pk;
                        setTimeout(function() {
                            window.location.href = '/';
                        }, 1000)
                    })
                } else {
                    myAlert(' 登录失败');
                }
            });
        }
    }
]);

teaControllers.controller('flowController', ['$scope', '$http',
    function($scope, $http) {
        var current = document.querySelector('#entry');
        angular.element(current).addClass('selected');

        $scope.orderProp = 'fields.end_date';
        $scope.reverse = 1;

        $scope.quantity = 6;
        //$scope.$watch('quantity');

        var path = baseurl + '/api/get_cloth_list/1/100/';

        $http.get(path).success(function(data) {
            $scope.clothes = addPrefix(data);
        });

        var pageID = 1;
        window.onscroll = function(event) {
            //console.log(pageID * window.innerHeight - window.scrollY);
            if ((pageID * window.innerHeight + pageID * 25 - window.scrollY) < 25) {
                $scope.quantity = (++pageID) * 6;
                //force refresh data!!
                $scope.$digest();
            }
        }

        //interact functions
        $scope.changeStroke = function($event) {
            var orderNodes = document.querySelectorAll('.order-selector');
            angular.element(orderNodes).removeClass('selected');
            angular.element($event.target).addClass('selected');
        }
        $scope.changeFlag = function($event) {
            var flagNodes = document.querySelectorAll('.reverse-flag');
            angular.element(flagNodes).removeClass('selected');
            angular.element($event.target).addClass('selected');
        }
    }
]);

teaControllers.controller('raiseController', ['$scope', '$http',
    function($scope, $http) {
        var current = document.querySelector('#raise');
        angular.element(current).addClass('selected');

        //bind click
        var img = document.querySelector('#preview');
        angular.element(img).on('click', function(event) {
            //console.log(event);
            var clickEvent = document.createEvent("MouseEvents");
            clickEvent.initEvent("click", true, true);
            document.querySelector('#raiseFile').dispatchEvent(clickEvent);
        });

        //preview function
        window.previewImage = function previewImage(file) {
            //console.log(file.files.item(0));
            if (file.files.item(0).size > 10485760) {
                alert('这个图有点大。。。');
                return false;
            }
            switch (file.files.item(0).type) {
                case 'image/pjpeg':
                    ;
                case 'image/jpeg':
                    ;
                case 'image/png':
                    ;
                case 'image/x-png':
                    ;
                case 'image/gif':
                    break;
                default:
                    alert('这个是图吗。。。');
                    return false;
            }
            var MAXWIDTH = 128;
            var MAXHEIGHT = 128;
            var div = document.querySelector('#preview');

            div.innerHTML = '';
            var img = document.querySelector('#imghead');
            img.onload = function() {
                var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
                img.width = rect.width;
                img.height = rect.height;
                //img.style.marginLeft = rect.left+'px';
                img.style.marginTop = rect.top + 'px';
            }
            var reader = new FileReader();
            reader.onload = function(evt) {
                img.src = evt.target.result;
            }
            reader.readAsDataURL(file.files[0]);
        }

        function clacImgZoomParam(maxWidth, maxHeight, width, height) {
            var param = {
                top: 0,
                left: 0,
                width: width,
                height: height
            };
            var rateWidth, rateHeight;

            if (width > maxWidth || height > maxHeight) {
                rateWidth = width / maxWidth;
                rateHeight = height / maxHeight;

                if (rateWidth > rateHeight) {
                    param.width = maxWidth;
                    param.height = Math.round(height / rateWidth);
                } else {
                    param.width = Math.round(width / rateHeight);
                    param.height = maxHeight;
                }
            }

            param.left = Math.round((maxWidth - param.width) / 2);
            param.top = Math.round((maxHeight - param.height) / 2);
            return param;
        }
    }
]);

teaControllers.controller('ucenterController', ['$scope', '$http',
    function($scope, $http) {
        var current = document.querySelector('#ucenter');
        angular.element(current).addClass('selected');

        var path = '/api/get_user_orders/';

        $http.get(path).success(function(data) {
            $scope.orders = data;
        });
    }
]);

teaControllers.controller('weiboController', ['$scope', '$http',
    function($scope, $http) {
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.async = false;
        s.src = 'http://tjs.sjs.sinajs.cn/open/api/js/wb.js?appkey=2037499622';
        var x = document.getElementsByTagName('script')[0];
        x.parentNode.insertBefore(s, x);

        angular.element(document).ready(function() {
            WB2.anyWhere(function(W) {
                W.widget.connectButton({
                    id: "wb_connect_btn",
                    type: '3,2',
                    callback: {
                        login: function(o) {
                            alert(o.screen_name)
                        },
                        logout: function() {
                            alert('logout');
                        }
                    }
                });
            });
        });
    }
]);<commit_msg>add console.log(o)<commit_after>'use strict';

/* js wirte for teain
 * design and code by Yuzo
 */

/* App Module */

var teaApp = angular.module('tea', [
    'ngRoute',
    'ngAnimate',
    'ngCookies',
    'teaControllers'
]);

teaApp.config(['$routeProvider',
    function($routeProvider) {
        $routeProvider.
        when('/', {
            templateUrl: '/static/tea/partials/tea-index.html',
            controller: 'indexController'
        }).
        when('/item/:itemID', {
            templateUrl: '/static/tea/partials/tea-item.html',
            controller: 'detailController'
        }).
        when('/register', {
            templateUrl: '/static/tea/partials/tea-register.html',
            controller: 'registerController'
        }).
        when('/login', {
            templateUrl: '/static/tea/partials/tea-login.html',
            controller: 'loginController'
        }).
        when('/flow', {
            templateUrl: '/static/tea/partials/tea-flow.html',
            controller: 'flowController'
        }).
        when('/raise', {
            templateUrl: '/static/tea/partials/tea-raise.html',
            controller: 'raiseController'
        }).
        when('/ucenter', {
            templateUrl: '/static/tea/partials/tea-ucenter.html',
            controller: 'ucenterController'
        }).
        when('/weibo', {
            templateUrl: '/static/tea/partials/tea-weibo.html',
            controller: 'weiboController'
        }).
        otherwise({
            redirectTo: '/'
        });
    }
]);

teaApp.run(function($rootScope, $cookies) {
    //app range initalize
    window.baseurl = '';
    //stoke update
    $rootScope.$on('$routeChangeSuccess', function(event, current) {
        //console.log(event, current);
        var total = document.querySelectorAll('.entry');
        angular.element(total).removeClass('selected');
    });
    //addPrefix function
    window.addPrefix = function addPrefix(data) {
        for (var i = data.length - 1; i >= 0; i--) {
            data[i].fields.img_src = baseurl + '/media/' + data[i].fields.img_src;
        };
        return data;
    }
    //myAlert function
    window.myAlert = function myAlert(text) {
        var target = document.querySelector('#myAlert');
        angular.element(target).html(text);

        angular.element(target).css('display', 'block');
        setTimeout(function() {
            angular.element(target).css('opacity', '0.9');
        }, 50);

        function fadeOut() {
            angular.element(target).css('opacity', '0');
            setTimeout(function() {
                angular.element(target).css('display', 'none');
            }, 800);
        };

        setTimeout(function() {
            fadeOut();
        }, 3000);
        target.addEventListener('click', function() {
            fadeOut();
        });
    }
    //change text of the login button
    if ($cookies.username) {
        var target = document.querySelector('#toRegister');
        angular.element(target).text($cookies.username);
    }
    //toRegister function
    window.toRegister = function toRegister() {
        //console.log($cookies);
        if ($cookies.username) {
            if (confirm("退出当前账户？")) {
                //buggy?
                //$cookies.username = "";
                document.cookie = 'username=';
                window.location.reload();
            };
        } else {
            window.location.href = '#/register';
        }
    }
});

/* Controllers */

var teaControllers = angular.module('teaControllers', []);

teaControllers.controller('indexController', ['$scope', '$http', '$cookies',
    function($scope, $http, $cookies) {
        var path = baseurl + '/api/get_cloth_list/1/6/';
        //console.log(path);
        $http.get(path).success(function(data) {
            $scope.clothes = addPrefix(data);
            //control welcome banner
            if (!$cookies.username) {
                var target = document.querySelector('#welcome')
                angular.element(target).css('display', 'block');
            }
        });
    }
]);

teaControllers.controller('detailController', ['$scope', '$routeParams', '$http', '$cookies',
    function($scope, $routeParams, $http, $cookies) {
        //init functions
        var path = baseurl + '/api/get_cloth/' + $routeParams.itemID + '/';
        //console.log(path);
        $http.get(path).success(function(data) {
            $scope.cloth = addPrefix(data)[0];
        });

        var path = baseurl + '/api/get_cloth_sizes/' + $routeParams.itemID + '/';
        $http.get(path).success(function(data) {
            $scope.sizes = data;
        });

        var path = baseurl + '/api/get_cloth_imgs/' + $routeParams.itemID + '/';
        $http.get(path).success(function(data) {
            $scope.imgs = addPrefix(data);
            angular.element(document).ready(function() {
                var clickEvent = document.createEvent("MouseEvents");
                clickEvent.initEvent("click", true, true);
                document.querySelector('.imgs img').dispatchEvent(clickEvent);
            });
        });

        var path = baseurl + '/api/get_cloth_descs/' + $routeParams.itemID + '/';
        $http.get(path).success(function(data) {
            $scope.descs = addPrefix(data);
        });

        //interact functions
        $scope.changeImg = function(img, $event) {
            var imgNodes = document.querySelectorAll('.imgs img')
            angular.element(imgNodes).removeClass('selected');
            angular.element($event.target).addClass('selected');
            //$event.target.className = 'selected';
            for (var i = $scope.imgs.length - 1; i >= 0; i--) {
                if ($scope.imgs[i].pk === img.pk) {
                    $scope.cloth.fields.img_src = $scope.imgs[i].fields.img_src;
                    break;
                }
            };
        }
        $scope.changeSize = function(size, $event) {
            var sizeNodes = document.querySelectorAll('.sizes li');
            //console.log(sizeNodes);
            angular.element(sizeNodes).removeClass('selected');
            angular.element($event.target).addClass('selected');
        }

        //purchase functions
        $scope.num = 1;
        //get csrf
        var path = baseurl + '/api/make_order/';
        $http.get(path);
        //buyButton
        $scope.buy = function buy(clothID, num) {
            var postData = {
                user_id: $cookies.userID,
                cloth_id: clothID,
                num: num,
                csrfmiddlewaretoken: $cookies.csrftoken
            }

            var config = {
                method: 'POST',
                url: path,
                data: postData,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                transformRequest: function(obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
                    }
                    return str.join('&');
                }
            }

            $http(config).success(function(data) {
                if (data == 'ok') {
                    myAlert(' 购买成功');
                } else {
                    myAlert(' 购买失败');
                }
            });
        }
    }
]);

teaControllers.controller('registerController', ['$scope', '$http', '$cookies',
    function($scope, $http, $cookies) {
        var current = document.querySelector('#toRegister');
        angular.element(current).addClass('selected');

        //get csrf
        var path = baseurl + '/accounts/register/';
        $http.get(path);

        $scope.checkMust = function checkMust($event) {
            //console.log($event.target);
            var target = angular.element($event.target);
            if (target.val()) {
                target.removeClass('invalid');
                target.addClass('valid');
            } else {
                target.removeClass('valid');
                target.addClass('invalid');
            }
        }

        $scope.register = function register() {
            $scope.info.csrfmiddlewaretoken = $cookies.csrftoken;

            var config = {
                method: 'POST',
                url: path,
                data: $scope.info,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                transformRequest: function(obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
                    }
                    return str.join('&');
                }
            }

            $http(config).success(function(data) {
                if (data == 'ok') {
                    myAlert(' 注册成功');
                    var path = baseurl + '/accounts/userinfo/';
                    $http.get(path).success(function(data) {
                        //console.log(data);
                        $cookies.username = data[0].fields.username;
                        $cookies.userID = data[0].pk;
                        setTimeout(function() {
                            window.location.href = '/';
                        }, 1000)
                    })
                } else {
                    myAlert(' 注册失败');
                }
            });
        }
    }
]);

teaControllers.controller('loginController', ['$scope', '$http', '$cookies',
    function($scope, $http, $cookies) {
        var current = document.querySelector('#toRegister');
        angular.element(current).addClass('selected');

        //get csrf
        var path = baseurl + '/accounts/login/';
        $http.get(path);

        $scope.checkMust = function checkMust($event) {
            //console.log($event.target);
            var target = angular.element($event.target);
            if (target.val()) {
                target.removeClass('invalid');
                target.addClass('valid');
            } else {
                target.removeClass('valid');
                target.addClass('invalid');
            }
        }

        $scope.login = function login() {
            $scope.info.csrfmiddlewaretoken = $cookies.csrftoken;

            var config = {
                method: 'POST',
                url: path,
                data: $scope.info,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                transformRequest: function(obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
                    }
                    return str.join('&');
                }
            }

            $http(config).success(function(data) {
                if (data == 'ok') {
                    myAlert(' 登录成功');
                    var path = baseurl + '/accounts/userinfo/';
                    $http.get(path).success(function(data) {
                        //console.log(data);
                        $cookies.username = data[0].fields.username;
                        $cookies.userID = data[0].pk;
                        setTimeout(function() {
                            window.location.href = '/';
                        }, 1000)
                    })
                } else {
                    myAlert(' 登录失败');
                }
            });
        }
    }
]);

teaControllers.controller('flowController', ['$scope', '$http',
    function($scope, $http) {
        var current = document.querySelector('#entry');
        angular.element(current).addClass('selected');

        $scope.orderProp = 'fields.end_date';
        $scope.reverse = 1;

        $scope.quantity = 6;
        //$scope.$watch('quantity');

        var path = baseurl + '/api/get_cloth_list/1/100/';

        $http.get(path).success(function(data) {
            $scope.clothes = addPrefix(data);
        });

        var pageID = 1;
        window.onscroll = function(event) {
            //console.log(pageID * window.innerHeight - window.scrollY);
            if ((pageID * window.innerHeight + pageID * 25 - window.scrollY) < 25) {
                $scope.quantity = (++pageID) * 6;
                //force refresh data!!
                $scope.$digest();
            }
        }

        //interact functions
        $scope.changeStroke = function($event) {
            var orderNodes = document.querySelectorAll('.order-selector');
            angular.element(orderNodes).removeClass('selected');
            angular.element($event.target).addClass('selected');
        }
        $scope.changeFlag = function($event) {
            var flagNodes = document.querySelectorAll('.reverse-flag');
            angular.element(flagNodes).removeClass('selected');
            angular.element($event.target).addClass('selected');
        }
    }
]);

teaControllers.controller('raiseController', ['$scope', '$http',
    function($scope, $http) {
        var current = document.querySelector('#raise');
        angular.element(current).addClass('selected');

        //bind click
        var img = document.querySelector('#preview');
        angular.element(img).on('click', function(event) {
            //console.log(event);
            var clickEvent = document.createEvent("MouseEvents");
            clickEvent.initEvent("click", true, true);
            document.querySelector('#raiseFile').dispatchEvent(clickEvent);
        });

        //preview function
        window.previewImage = function previewImage(file) {
            //console.log(file.files.item(0));
            if (file.files.item(0).size > 10485760) {
                alert('这个图有点大。。。');
                return false;
            }
            switch (file.files.item(0).type) {
                case 'image/pjpeg':
                    ;
                case 'image/jpeg':
                    ;
                case 'image/png':
                    ;
                case 'image/x-png':
                    ;
                case 'image/gif':
                    break;
                default:
                    alert('这个是图吗。。。');
                    return false;
            }
            var MAXWIDTH = 128;
            var MAXHEIGHT = 128;
            var div = document.querySelector('#preview');

            div.innerHTML = '';
            var img = document.querySelector('#imghead');
            img.onload = function() {
                var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
                img.width = rect.width;
                img.height = rect.height;
                //img.style.marginLeft = rect.left+'px';
                img.style.marginTop = rect.top + 'px';
            }
            var reader = new FileReader();
            reader.onload = function(evt) {
                img.src = evt.target.result;
            }
            reader.readAsDataURL(file.files[0]);
        }

        function clacImgZoomParam(maxWidth, maxHeight, width, height) {
            var param = {
                top: 0,
                left: 0,
                width: width,
                height: height
            };
            var rateWidth, rateHeight;

            if (width > maxWidth || height > maxHeight) {
                rateWidth = width / maxWidth;
                rateHeight = height / maxHeight;

                if (rateWidth > rateHeight) {
                    param.width = maxWidth;
                    param.height = Math.round(height / rateWidth);
                } else {
                    param.width = Math.round(width / rateHeight);
                    param.height = maxHeight;
                }
            }

            param.left = Math.round((maxWidth - param.width) / 2);
            param.top = Math.round((maxHeight - param.height) / 2);
            return param;
        }
    }
]);

teaControllers.controller('ucenterController', ['$scope', '$http',
    function($scope, $http) {
        var current = document.querySelector('#ucenter');
        angular.element(current).addClass('selected');

        var path = '/api/get_user_orders/';

        $http.get(path).success(function(data) {
            $scope.orders = data;
        });
    }
]);

teaControllers.controller('weiboController', ['$scope', '$http',
    function($scope, $http) {
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.async = false;
        s.src = 'http://tjs.sjs.sinajs.cn/open/api/js/wb.js?appkey=2037499622';
        var x = document.getElementsByTagName('script')[0];
        x.parentNode.insertBefore(s, x);

        angular.element(document).ready(function() {
            WB2.anyWhere(function(W) {
                W.widget.connectButton({
                    id: "wb_connect_btn",
                    type: '3,2',
                    callback: {
                        login: function(o) {
                            alert(o.screen_name)
                            console.log(o);
                        },
                        logout: function() {
                            alert('logout');
                        }
                    }
                });
            });
        });
    }
]);<|endoftext|>


<commit_before>'use script';
angular
    .module('myApp')
    .component('areaChart', {
        bindings: {
            data: '<'
        },
        controller: Controller,
        template: `<div google-chart chart='$ctrl.chart' style='$ctrl.chart.cssStyle'></div>`
    });

Controller.$inject = ['$q']

function Controller($q) {
    const vm = this;
    const warnOnDaysClose = 30;
    const chartStates = [
        { name: 'actual-planned', color: 'green', line: 'continuos' },
        { name: 'actual-passed', color: 'red', line: 'continuos' },
        { name: 'prognos-planned', color: 'lightgreen', line: 'intermitent' },
        { name: 'prognos-passed', color: 'pink', line: 'intermitent' },
        { name: 'closeToendDate', color: 'orange', line: 'intermitent' },
        { name: 'contractedMileageLine', color: 'red', line: 'intermitent' }];

    const userData =
        {
            assumedMileage: 475,
            assumedDate: '20170315',
            contractStart: '20170207',
            contractEnd: '20170421',
            mileage: 450,
            contractMileage: 400
        };

    let actualValues = [];
    let assumedData = false;

    var chartData = {
        type: 'ComboChart',
        cssStyle: 'height:200px; width:300px;',
        data: {
            'cols': [
                { id: 'month', label: 'Month', type: 'string' },
                { id: 'line1-id', label: '', type: 'number' },
                { id: 'line2-id', label: '', type: 'number' },
                { id: 'line3-id', label: '', type: 'number' },
                { id: 'line4-id', label: '', type: 'number' },
                { id: 'line5-id', label: '', type: 'number' }

            ], 'rows': []
        },
        options: {
            title: 'Mileage contract',
            type: 'area',
            colors: [],
            legend: 'none',
            displayExactValues: true,
            crosshair: { trigger: 'both', orientation: 'vertical' },
            vAxis: {
                ticks: [0, 100, 200, 300, 400, 500]
            },
            hAxis: {
            },
            series: {
                2: {
                    areaOpacity: 0,
                    visibleInLegend: false
                }
            }
        }
    };

    Init();

    function Init() {
        $q.resolve(chartData)
            .then(setDates)
            .then(setLineColors)
            .then(setRowsActualData)
            .catch(error => console.info(error));
    }

    function getAssumedMileage(index) {
        switch (index) {
            case 1:
                return userData['mileage'];
                break;
            case 2:
                return userData['assumedMileage'];
                break;
            case 3:
                return null;
                return userData['assumedMileage'];
                break
        }
    }

    function getActualMileage(index) {
        let startDate = moment(userData['contractStart']).format('MMM');
        let todayDate = moment(Date.Now).format('MMM');

        switch (index) {
            case 0:
                return (startDate === todayDate) ? userData['mileage'] : 0;
                break;
            case 1:
                return userData['mileage'];
                break;
            case 3:
                return null;
                break;
        }
    }

    function setLineColors(chart) {
        chart.options.colors = [
            getChartState('actual', userData['mileage']).color,
            getChartState('prognos', userData['assumedMileage']).color,
            chartStates.find(x => x.name === 'contractedMileageLine').color,
            chartStates.find(x => x.name === 'closeToendDate').color];
        return $q.resolve(chart);
    }

    function setDates(chart) {
        const startDate = moment(userData['contractStart']);
        const endDate = moment(userData['contractEnd']);
        const todaysDate = moment();
        const assumedDate = moment(userData['assumedDate']);

        if (todaysDate.diff(endDate) > 0) {
            assumedData = false;
            actualValues = [startDate.format('LL'), endDate.format('LL'), todaysDate.format('LL')]
        } else if (assumedDate > endDate)  {
            assumedData = true;
            actualValues = [startDate.format('LL'), todaysDate.format('MMM'), endDate.format('LL'), assumedDate.format('LL')]
        } else if (endDate.diff(todaysDate, 'days') <= warnOnDaysClose)  {
            assumedData = true;
            actualValues = [startDate.format('LL'), todaysDate.format('MMM'), endDate.format('LL'), assumedDate.format('LL')]
        } else {
            assumedData = true;
            actualValues = [startDate.format('LL'), todaysDate.format('MMM'), assumedDate.format('LL'), endDate.format('LL')];
        }
        return $q.resolve(chart);
    }

    function getChartState(state = 'prognos', mileageRef) {
        const roofMileage = userData['contractMileage'];
        const param = mileageRef < roofMileage ? `${state}-planned` : `${state}-passed`;
        const resultState = chartStates.find(x => x.name === param);
        return resultState;
    }

    function checkAssumedDataIsNeeded(index) {
        if (assumedData) {
            return ((index === 3) || (index === 2)) ? userData['assumedMileage'] : null
        }
        return null;
    }

    function setRowsActualData(chart) {
        chart.data.rows = actualValues.map(function (date, index) {
            return {
                c: [
                    { v: date },
                    { v: getActualMileage(index) },
                    { v: getAssumedMileage(index) },
                    { v: userData['contractMileage'] },
                    { v: checkAssumedDataIsNeeded(index) }
                ]
            }
        });
        console.log('chart: ', chart);
        return $q.resolve(chart);
    }

    vm.chart = chartData;
}<commit_msg>[] Changes at work. Some refactor<commit_after>'use script';
angular
    .module('myApp')
    .component('areaChart', {
        bindings: {
            data: '<'
        },
        controller: Controller,
        template: `<div google-chart chart='$ctrl.chart' style='$ctrl.chart.cssStyle'></div>`
    });

Controller.$inject = ['$q']

function Controller($q) {
    const vm = this;
    const warnOnDaysClose = 30;
    const dashedLineStyle = ['4', '4'];
    const chartStates = [
        { name: 'actual-planned', color: '#94c333', line: 'continuos' },
        { name: 'actual-passed', color: '#fa0032', line: 'continuos' },
        { name: 'prognos-planned', color: '#94c333', line: 'intermitent' },
        { name: 'prognos-passed', color: '#fa0032', line: 'intermitent' },
        { name: 'closeToendDate', color: '#fcb60b', line: 'intermitent' },
        { name: 'contractedMileageLine', color: '#94c333', line: 'intermitent' }];

    const userData =
        {
            assumedMileage: 375,
            assumedDate: '20170315',
            contractStart: '20170301',
            contractEnd: '20170321',
            overrideDate: '20170318',
            mileage: 350,
            contractMileage: 400
        };

    const startDate = moment(userData['contractStart']);
    const endDate = moment(userData['contractEnd']);
    const todaysDate = moment();
    const assumedDate = moment(userData['assumedDate']);
    const overrideDate = moment(userData['overrideDate']);

    let actualValues = [];

    let assumedData = false;

    var chartData = {
        type: 'ComboChart',
        cssStyle: 'height:200px; width:300px;',
        data: {
            'cols': [
                { id: 'month', label: 'Month', type: 'string' },
                { id: 'line1-id', label: '', type: 'number' },
                { id: 'line2-id', label: '', type: 'number' },
                { id: 'line3-id', label: '', type: 'number' },
                { id: 'line4-id', label: '', type: 'number' },
                { id: 'line5-id', label: '', type: 'number' }

            ], 'rows': []
        },
        options: {
            title: 'Mileage contract',
            type: 'area',
            legend: 'none',
            displayExactValues: true,
            vAxis: {
                ticks: [0, 100, 200, 300, 400, 500]
            },
            hAxis: {
            },
            series: {
                0: {},
                1: {},
                2: {},
                3: {
                    areaOpacity: 0,
                    visibleInLegend: true
                },
                4: {},

            }
        }
    };

    Init();

    function Init() {
        $q.resolve(chartData)
            .then(setLinesProperties)
            .then(prepareChartData)
            .then(setRowsActualData)
            .catch(error => console.info(error));
    }

    function prepareChartData(chart) {

        actualValues = [
            { date: startDate.format('LL'), mileage: 0 },
            { date: todaysDate.format('LL'), mileage: userData['mileage'] },
            { date: assumedDate.format('LL'), mileage: userData['assumedMileage'] },
            { date: endDate.format('LL'), mileage: userData['assumedMileage'] }];

        return $q.resolve(chart);
    }

    function setLinesProperties(chart) {
        let actualLine = getChartState('actual', userData['mileage']);
        let prognosLine = getChartState('prognos', userData['assumedMileage']);
        if (prognosLine.name === 'prognos-planned') {
            angular.extend(chart.options.series['1'], { lineDashStyle: dashedLineStyle });
             angular.extend(chart.options.series['1'], { lineDashStyle: dashedLineStyle });
        }
        chart.options.colors = [
            actualLine.color,
            prognosLine.color,
            chartStates.find(x => x.name === 'contractedMileageLine').color,
            'green',
            chartStates.find(x => x.name === 'closeToendDate').color];
        return $q.resolve(chart);
    }

    function getOverridedDistance() {
        return userData['mileage'] - userData['contractMileage'];
    }

    function getChartState(state = 'prognos', mileageRef) {
        const roofMileage = userData['contractMileage'];
        const param = mileageRef < roofMileage ? `${state}-planned` : `${state}-passed`;

        const resultState = chartStates.find(x => x.name === param);
        return resultState;
    }

    function setRowsActualData(chart) {
        chart.data.rows = actualValues.map((data, index) => {
            return {
                c: [
                    getRowsDates(data, index),
                    { v: getActualRowData(data, index) },
                    { v: getPrognosRowData(data, index) },
                    { v: getOverridedRowData(data, index) },
                    { v: userData['contractMileage'] }
                ]
            }
        })
        console.log("chart: ", chart);
        return $q.resolve(chart);
    }

    function getRowsDates(data) {

            return { v: data['date'], f: data['date'] }

    }

    function getActualRowData(dat, index) {
        if (index < 2) {
            return dat['mileage']
        }
        return null
    }

    function getPrognosRowData(dat, index) {
        if ((index > 0) && (index < 3)) {
            return dat['mileage'];
        }
        return null;
    }

    function checkOverrideContractMileage(data) {
        return data['mileage'] > userData['contractMileage'];
    }

    function getOverridedRowData(data, index) {
        if (index >= 2) {
            return data['mileage'];
        }
        return null;
    }

    vm.chart = chartData;
}
<|endoftext|>


<commit_before>/*
 *
 * Dashboard
 *
 */

 import React from 'react';
 import Helmet from 'react-helmet';
 import Responsive from 'react-responsive';
 import {Link} from "react-router";
 import FlatButton from "material-ui/FlatButton";
 import NavBar2 from 'components/NavBar2';
 import FooterNav2 from 'components/FooterNav2';

export default class Dashboard extends React.PureComponent {
  constructor(props){
  super(props);
  this.state={
    title:"",
    body:"",
    image:"",
    preview:"",
    token:sessionStorage.getItem("token")
  }
}
handleTitle = (event) => {
  this.setState({
    title: event.target.value
  })
}
handleBody = (event) => {
  this.setState({
    body:event.target.value
  })
}
handleImage = (event) => {
  event.preventDefault();
  let reader = new FileReader();
  let file = event.target.files[0];
  reader.onloadend = () => {
    this.setState({
      image: file,
      preview: reader.result
    })
  }
  reader.readAsDataURL(file);
}

 storeArticle = () => {

   var data = new FormData ();
   data.append("title", this.state.title);
   data.append("body", this.state.body);
   data.append("image", this.state.image);

 fetch("http://localhost:8000/api/storeArticle?token="+this.state.token,{
   method:"post",
   body:data
 })
 .then(function(response){
   return response.json();
 })
 .then(function(json){
   if(json.success){
     this.setState({
       title:"",
       body:"",
       image:"",
       preview:"",
     })
     alert("Success! You did it!");
   }
   else if (json.error){
     alert("You need to fill out all fields.");
   }
 }.bind(this))
}
  render() {
    const divStyle={
      textAlign:"center",
    }
    const titleStyle={
      color:"#eeeeee",
      fontSize:"6em",
      fontFamily:"Quicksand",
      fontWeight:"300",
      textTransform:"uppercase",
      letterSpacing:"6px",
      textAlign:"center",
      marginTop:"280px"
    }
    const titleStyleMobile={
      color:"#eeeeee",
      fontSize:"4em",
      fontFamily:"Quicksand",
      fontWeight:"400",
      textTransform:"uppercase",
      letterSpacing:"6px",
      textAlign:"center",
      marginTop:"225px"
    }
    const divStyleParallax={
      width:"100%",
      height:"600px",
      background:"url(http://h4z.it/Image/73803a_SC_0785bwrev.jpg)",
      backgroundSize:"cover",
      backgroundAttachment:"fixed",
      backgroundPosition:"center",
      backgroundRepeat:"no-repeat",
    }
      const divStyleMobileParallax={
        width:"100%",
        height:"500px",
        background:"url(http://h4z.it/Image/73803a_SC_0785bwrev.jpg)",
        backgroundSize:"cover",
        backgroundAttachment:"fixed",
        backgroundPosition:"center",
        backgroundRepeat:"no-repeat",
    }
    const box={
        top:"600px",
        margin:"auto",
        color:"#eeeeee",
        fontSize:"6em",
        fontFamily:"Quicksand",
        fontWeight:"300",
        textTransform:"uppercase",
        letterSpacing:"6px",
        textAlign:"center",
        height:"300px",
        width:"100%",
    }
    const divStyle2={
      width:"100%",
      height:"1500px",
      background:"rgba(0, 0, 0, 1.00)"

    }
    const bodyStyle={
      color:"#ffffff",
      fontSize:"1em",
      fontFamily:"Open Sans",
      fontWeight:"400",
      textAlign:"left",
      display:"flex",
      flexDirection:"column",
    }
    const divStyle3={
      width:"100%",
      height:"650px",
      background:"rgba(0, 0, 0, 1.00)"
    }
    const box2={
      width:"1500px",
      height:"800px",
      border:"2px solid #ffffff",
      margin:"0 auto",
      display:"flex",
      flexDirection:"row",
      justifyContent:"space-around",

    }
    const inputBox={
      color:"#191919",
      fontSize:"1em",
      fontFamily:"Open Sans",
      fontWeight:"400",
      textAlign:"left",
      width:"300px",
      height:"50px",
      marginTop:"10px",
      marginBottom:"30px",
      marginRight:"30px",
      background:"#ffffff"
    }
    const inputBoxMobile={
      color:"#191919",
      fontSize:"1em",
      fontFamily:"Open Sans",
      fontWeight:"400",
      textAlign:"left",
      width:"285px",
      height:"40px",
      marginTop:"10px",
      marginBottom:"30px",
      marginRight:"30px",
      background:"#ffffff"

    }
    const inputBox2={
      color:"#191919",
      fontSize:"1em",
      fontFamily:"Open Sans",
      fontWeight:"400",
      textAlign:"left",
      width:"692px",
      height:"200px",
      marginTop:"10px",
      marginBottom:"100px",
      marginRight:"30px",
      background:"#ffffff"
    }
    const inputBox2Mobile={
      color:"#191919",
      fontSize:"1em",
      fontFamily:"Open Sans",
      fontWeight:"400",
      textAlign:"left",
      width:"285px",
      height:"285px",
      marginTop:"10px",
      marginBottom:"30px",
      marginRight:"30px",
      background:"#ffffff"
    }
    const inputBox3={
      color:"#ffffff",
      fontSize:"1em",
      fontFamily:"Open Sans",
      fontWeight:"400",
      textAlign:"center",
      width:"100px",
      height:"50px",
      marginTop:"50px",
      marginBottom:"125px",
      background:"rgba(0, 0, 0, 1.00)",
      border:"1px solid #ffffff",
    }
    const inputBox3Mobile={
      color:"#ffffff",
      fontSize:"1em",
      fontFamily:"Open Sans",
      fontWeight:"400",
      textAlign:"center",
      width:"100px",
      height:"50px",
      marginTop:"50px",
      marginBottom:"20px",
      background:"rgba(0, 0, 0, 1.00)",
      border:"1px solid #ffffff",
    }
    const divStyle4={
      width:"100%",
      height:"auto",
      background:"rgba(0, 0, 0, 1.00)",
      color:"#ffffff"

    }
    const divStyle5={
      width:"100%",
      height:"150px",
      marginTop:"75px",
      background:"rgba(0, 0, 0, 1.00)",
      color:"#ffffff"
    }
    const divStyle5Mobile={
      width:"100%",
      height:"75px",
      marginTop:"37px",
      background:"rgba(0, 0, 0, 1.00)",
      color:"#ffffff"
    }
    const contactLeft={
      width:"30%",
      display:"flex",
      flexDirection:"column",
      paddingLeft:"1%",
      paddingTop:"4%"
    }
    const contactLeftMobile={
      display:"flex",
      flexDirection:"column",
      paddingLeft:"5%",
      paddingTop:"8%"
    }
    const contactRight={
      width:"70%",
      display:"flex",
      flexDirection:"column",
      paddingLeft:"1%",
      paddingTop:"5%"

    }
    const contactRow={
      display:"flex",
      flexDirection:"row",
      justifyContent:"space-around",
      padding:"50px 150px 0px 0px"
    }
    const contactRowMobile={
      display:"flex",
      flexDirection:"row",
      justifyContent:"space-around",
      paddingTop:"5px",
      margin:"0 auto",
    }
    const headerStyle={
      color:"#ffffff",
      fontSize:"1.20em",
      fontFamily:"Open Sans",
      fontWeight:"600",
      textTransform:"uppercase",
  }
  const mainStyle={
    display:"flex",
    flexDirection:"column",
    background:"rgba(0, 0, 0, 1.00)",
    }
    const mainStyleMobile={
      display:"flex",
      flexDirection:"column",
      color:"#191919",

    }
    const footerStyleMobile={
      display:"flex",
      flexDirection:"column",
      textDecoration:"none",
      color:"#000000",
      fontSize:"1em",
      fontFamily:"Josefin Sans",
      fontStyle:"light",
      fontWeight:"500",
      textAlign:"center",
      textTransform:"uppercase",
      letterSpacing:"2px",
    }
    const headStyleMobile={
      display:"flex",
      marginTop:"20px",
      flexDirection:"column",
      alignItems:"center",
    }
    const linkStyle={
      display:"flex",
      flexDirection:"column",
      textDecoration:"none",
      color:"#000000",
      fontSize:".75em",
      fontFamily:"Josefin Sans",
      fontStyle:"light",
      fontWeight:"400",
      textAlign:"center",
      textTransform:"uppercase",
      letterSpacing:"2px",
    }
    const mottoStyle={
      color:"ffffff",
      fontSize:"1.20em",
      fontFamily:"Open Sans",
      fontWeight:"700",
      textAlign:"center",
      textTransform:"uppercase",
      letterSpacing:"2px",
      background:"rgba(0, 0, 0, 1.00)",
    }
    const mottoStyleMobile={
        color:"#ffffff",
        fontSize:".90em",
        fontFamily:"Open Sans",
        fontWeight:"700",
        textAlign:"center",
        textTransform:"uppercase",
        marginTop:"30px",
        letterSpacing:"2px",
        background:"rgba(0, 0, 0, 1.00)",
     }
     const pageLinks = [];

     const preview = {};

    return (

        <Helmet title="Dashboard" meta={[ { name: 'description', content: 'Description of Dashboard' }]}/>

                <NavBar2/>

            <Responsive minDeviceWidth={1024}>

 Dashboard

            </Responsive>

            <Responsive maxDeviceWidth={1023}>

 Dash
board

            </Responsive>

        <Responsive minDeviceWidth={1024}>

               Title <input onChange = {this.handleTitle} type="text" style={inputBox} value={this.state.title}/>

               Body <textarea onChange = {this.handleBody} style={inputBox2}>{this.state.body}</textarea>

            <input type="file" onChange={this.handleImage} style={bodyStyle}/>

            <input onTouchTap = {this.storeArticle} type="submit" placeholder="Send Message" style={inputBox3}/>

        </Responsive>

        <Responsive maxDeviceWidth={1023}>

               Title <input onChange = {this.handleTitle} type="text" style={inputBoxMobile} value={this.state.title}/>

               Body <textarea onChange = {this.handleBody} type="text" style={inputBox2Mobile}>{this.state.body}</textarea>

              <input type="file" onChange={this.handleImage} style={bodyStyle}/>

              <input onTouchTap = {this.storeArticle} type="submit" placeholder="Send Message" style={inputBox3Mobile}/>

        </Responsive>

        <Responsive minDeviceWidth={1024}>

 Design good.

        </Responsive>

        <Responsive maxDeviceWidth={1023}>

 Design good.

        </Responsive>

          <FooterNav2/>

          );
        }
      }
<commit_msg>blog comments container added<commit_after>/*
 *
 * Dashboard
 *
 */

 import React from 'react';
 import Helmet from 'react-helmet';
 import Responsive from 'react-responsive';
 import {Link} from "react-router";
 import FlatButton from "material-ui/FlatButton";
 import NavBar2 from 'components/NavBar2';
 import FooterNav2 from 'components/FooterNav2';

export default class Dashboard extends React.PureComponent {
  constructor(props){
  super(props);
  this.state={
    title:"",
    body:"",
    image:"",
    preview:"",
    token:sessionStorage.getItem("token")
  }
}
handleTitle = (event) => {
  this.setState({
    title:event.target.value
  })
}
handleBody = (event) => {
  this.setState({
    body:event.target.value
  })
}
handleImage = (event) => {
  event.preventDefault();
  let reader = new FileReader();
  let file = event.target.files[0];
  reader.onloadend = () => {
    this.setState({
      image: file,
      preview: reader.result
    })
  }
  reader.readAsDataURL(file);
}

 storeArticle = () => {

   var data = new FormData ();
   data.append("title", this.state.title);
   data.append("body", this.state.body);
   data.append("image", this.state.image);

 fetch("http://localhost:8000/api/storeArticle?token="+this.state.token,{
   method:"post",
   body:data
 })
 .then(function(response){
   return response.json();
 })
 .then(function(json){
   if(json.success){
     this.setState({
       title:"",
       body:"",
       image:"",
       preview:"",
     })
     alert("Success! You did it!");
   }
   else if (json.error){
     alert("You need to fill out all fields.");
   }
 }.bind(this))
}
  render() {
    const divStyle={
      textAlign:"center",
    }
    const titleStyle={
      color:"#eeeeee",
      fontSize:"6em",
      fontFamily:"Quicksand",
      fontWeight:"300",
      textTransform:"uppercase",
      letterSpacing:"6px",
      textAlign:"center",
      marginTop:"280px"
    }
    const titleStyleMobile={
      color:"#eeeeee",
      fontSize:"4em",
      fontFamily:"Quicksand",
      fontWeight:"400",
      textTransform:"uppercase",
      letterSpacing:"6px",
      textAlign:"center",
      marginTop:"225px"
    }
    const divStyleParallax={
      width:"100%",
      height:"600px",
      background:"url(http://h4z.it/Image/73803a_SC_0785bwrev.jpg)",
      backgroundSize:"cover",
      backgroundAttachment:"fixed",
      backgroundPosition:"center",
      backgroundRepeat:"no-repeat",
    }
      const divStyleMobileParallax={
        width:"100%",
        height:"500px",
        background:"url(http://h4z.it/Image/73803a_SC_0785bwrev.jpg)",
        backgroundSize:"cover",
        backgroundAttachment:"fixed",
        backgroundPosition:"center",
        backgroundRepeat:"no-repeat",
    }
    const box={
        top:"600px",
        margin:"auto",
        color:"#eeeeee",
        fontSize:"6em",
        fontFamily:"Quicksand",
        fontWeight:"300",
        textTransform:"uppercase",
        letterSpacing:"6px",
        textAlign:"center",
        height:"300px",
        width:"100%",
    }
    const divStyle2={
      width:"100%",
      height:"1500px",
      background:"rgba(0, 0, 0, 1.00)"

    }
    const bodyStyle={
      color:"#ffffff",
      fontSize:"1em",
      fontFamily:"Open Sans",
      fontWeight:"400",
      textAlign:"left",
      display:"flex",
      flexDirection:"column",
    }
    const divStyle3={
      width:"100%",
      height:"650px",
      background:"rgba(0, 0, 0, 1.00)"
    }
    const box2={
      width:"1500px",
      height:"800px",
      border:"2px solid #ffffff",
      margin:"0 auto",
      display:"flex",
      flexDirection:"row",
      justifyContent:"space-around",

    }
    const inputBox={
      color:"#191919",
      fontSize:"1em",
      fontFamily:"Open Sans",
      fontWeight:"400",
      textAlign:"left",
      width:"300px",
      height:"50px",
      marginTop:"10px",
      marginBottom:"30px",
      marginRight:"30px",
      background:"#ffffff"
    }
    const inputBoxMobile={
      color:"#191919",
      fontSize:"1em",
      fontFamily:"Open Sans",
      fontWeight:"400",
      textAlign:"left",
      width:"285px",
      height:"40px",
      marginTop:"10px",
      marginBottom:"30px",
      marginRight:"30px",
      background:"#ffffff"

    }
    const inputBox2={
      color:"#191919",
      fontSize:"1em",
      fontFamily:"Open Sans",
      fontWeight:"400",
      textAlign:"left",
      width:"692px",
      height:"200px",
      marginTop:"10px",
      marginBottom:"100px",
      marginRight:"30px",
      background:"#ffffff"
    }
    const inputBox2Mobile={
      color:"#191919",
      fontSize:"1em",
      fontFamily:"Open Sans",
      fontWeight:"400",
      textAlign:"left",
      width:"285px",
      height:"285px",
      marginTop:"10px",
      marginBottom:"30px",
      marginRight:"30px",
      background:"#ffffff"
    }
    const inputBox3={
      color:"#ffffff",
      fontSize:"1em",
      fontFamily:"Open Sans",
      fontWeight:"400",
      textAlign:"center",
      width:"100px",
      height:"50px",
      marginTop:"50px",
      marginBottom:"125px",
      background:"rgba(0, 0, 0, 1.00)",
      border:"1px solid #ffffff",
    }
    const inputBox3Mobile={
      color:"#ffffff",
      fontSize:"1em",
      fontFamily:"Open Sans",
      fontWeight:"400",
      textAlign:"center",
      width:"100px",
      height:"50px",
      marginTop:"50px",
      marginBottom:"20px",
      background:"rgba(0, 0, 0, 1.00)",
      border:"1px solid #ffffff",
    }
    const divStyle4={
      width:"100%",
      height:"auto",
      background:"rgba(0, 0, 0, 1.00)",
      color:"#ffffff"

    }
    const divStyle5={
      width:"100%",
      height:"150px",
      marginTop:"75px",
      background:"rgba(0, 0, 0, 1.00)",
      color:"#ffffff"
    }
    const divStyle5Mobile={
      width:"100%",
      height:"75px",
      marginTop:"37px",
      background:"rgba(0, 0, 0, 1.00)",
      color:"#ffffff"
    }
    const contactLeft={
      width:"30%",
      display:"flex",
      flexDirection:"column",
      paddingLeft:"1%",
      paddingTop:"4%"
    }
    const contactLeftMobile={
      display:"flex",
      flexDirection:"column",
      paddingLeft:"5%",
      paddingTop:"8%"
    }
    const contactRight={
      width:"70%",
      display:"flex",
      flexDirection:"column",
      paddingLeft:"1%",
      paddingTop:"5%"

    }
    const contactRow={
      display:"flex",
      flexDirection:"row",
      justifyContent:"space-around",
      padding:"50px 150px 0px 0px"
    }
    const contactRowMobile={
      display:"flex",
      flexDirection:"row",
      justifyContent:"space-around",
      paddingTop:"5px",
      margin:"0 auto",
    }
    const headerStyle={
      color:"#ffffff",
      fontSize:"1.20em",
      fontFamily:"Open Sans",
      fontWeight:"600",
      textTransform:"uppercase",
  }
  const mainStyle={
    display:"flex",
    flexDirection:"column",
    background:"rgba(0, 0, 0, 1.00)",
    }
    const mainStyleMobile={
      display:"flex",
      flexDirection:"column",
      color:"#191919",

    }
    const footerStyleMobile={
      display:"flex",
      flexDirection:"column",
      textDecoration:"none",
      color:"#000000",
      fontSize:"1em",
      fontFamily:"Josefin Sans",
      fontStyle:"light",
      fontWeight:"500",
      textAlign:"center",
      textTransform:"uppercase",
      letterSpacing:"2px",
    }
    const headStyleMobile={
      display:"flex",
      marginTop:"20px",
      flexDirection:"column",
      alignItems:"center",
    }
    const linkStyle={
      display:"flex",
      flexDirection:"column",
      textDecoration:"none",
      color:"#000000",
      fontSize:".75em",
      fontFamily:"Josefin Sans",
      fontStyle:"light",
      fontWeight:"400",
      textAlign:"center",
      textTransform:"uppercase",
      letterSpacing:"2px",
    }
    const mottoStyle={
      color:"ffffff",
      fontSize:"1.20em",
      fontFamily:"Open Sans",
      fontWeight:"700",
      textAlign:"center",
      textTransform:"uppercase",
      letterSpacing:"2px",
      background:"rgba(0, 0, 0, 1.00)",
    }
    const mottoStyleMobile={
        color:"#ffffff",
        fontSize:".90em",
        fontFamily:"Open Sans",
        fontWeight:"700",
        textAlign:"center",
        textTransform:"uppercase",
        marginTop:"30px",
        letterSpacing:"2px",
        background:"rgba(0, 0, 0, 1.00)",
     }
     const pageLinks = [];

     const preview = {};

    return (

        <Helmet title="Dashboard" meta={[ { name: 'description', content: 'Description of Dashboard' }]}/>

                <NavBar2/>

            <Responsive minDeviceWidth={1024}>

 Dashboard

            </Responsive>

            <Responsive maxDeviceWidth={1023}>

 Dash
board

            </Responsive>

        <Responsive minDeviceWidth={1024}>

               Title <input onChange = {this.handleTitle} type="text" style={inputBox} value={this.state.title}/>

               Body <textarea onChange = {this.handleBody} style={inputBox2}>{this.state.body}</textarea>

            <input type="file" onChange={this.handleImage} style={bodyStyle}/>

            <input onTouchTap = {this.storeArticle} type="submit" placeholder="Send Message" style={inputBox3}/>

        </Responsive>

        <Responsive maxDeviceWidth={1023}>

               Title <input onChange = {this.handleTitle} type="text" style={inputBoxMobile} value={this.state.title}/>

               Body <textarea onChange = {this.handleBody} type="text" style={inputBox2Mobile}>{this.state.body}</textarea>

              <input type="file" onChange={this.handleImage} style={bodyStyle}/>

              <input onTouchTap = {this.storeArticle} type="submit" placeholder="Send Message" style={inputBox3Mobile}/>

        </Responsive>

        <Responsive minDeviceWidth={1024}>

 Design good.

        </Responsive>

        <Responsive maxDeviceWidth={1023}>

 Design good.

        </Responsive>

          <FooterNav2/>

          );
        }
      }
<|endoftext|>