<commit_before>
define(['jquery', 'underscore', 'backbone', 'text!templates/lot/lot.html', 'text!templates/lot/lotViewEmpty.html',
        'routing/router', 'collections/lots', 'collections/spots', 'collections/users',
        'views/spot/spotList', 'views/spot/editSpot', 'models/user'],
  function($, _, Backbone, Template, LotViewEmptyTemplate, Router, LotsCollection,
           SpotsCollection, UsersCollection, SpotListView, EditSpotView, User) {

  var LotView = Backbone.View.extend({
    tagName: 'div',
    className: 'lot-view',
    template: _.template( Template ),

    events: {
      'click #spot-list-add-spot-button': 'createNewSpot',
      'click .spot-list-item': 'toggleEditSpotModal'
    },

    initialize: function(options) {
      this.user = options.user;
      if(this.model){
        this.spotsCollection = new SpotsCollection([], {lot: this.model});
        this.listenTo(this.model, 'change', this.render);
        this.listenTo(this.model, 'destroy', this.remove);
      }
    },

    render: function() {
      if(this.model){
        //set the image
        var theLat = this.model.get('lat');
        var theLon = this.model.get('lon');
        console.log(theLat);
        theLat = theLat.toFixed(5);
        theLon = theLon.toFixed(5);
        console.log(theLat);
        var attr = "http://maps.googleapis.com/maps/api/streetview?size=850x300&location="+theLat+","+theLon+"&sensor=false";
        this.$el.html( this.template( this.model.toJSON() ) );
        this.$el.find('.lot-page-main-image').attr('src',attr);
        console.log(this.$el);
        this.renderSpots();
      } else {
        this.$el.html( LotViewEmptyTemplate );
      }
      return this;
    },

    renderSpots: function() {
      if(this.model.get('_id')){
        var thisGuy = this;
        this.spotsCollection.fetch({success: function(res){
          thisGuy.spotListView = new SpotListView( {collection: res, user: thisGuy.user} );
          thisGuy.$el.find('#spot-view-div').html( thisGuy.spotListView.render().el );
        }});
      }
    },

    renderEditSpotView: function(element, model, lot, user, isParent){
      this.editSpotView = new EditSpotView( {model: model, lot: lot, user: user} );
      if(isParent){
        var editEl = this.editSpotView.render().$el;
        editEl.find('#edit-spot-options').attr('id','create-first-spot');
        console.log(editEl);

        element.append( editEl );
      } else{
        element.after( this.editSpotView.render().el );
      }
    },

    deleteLot: function() {
      this.model.destroy({wait: true})
        .done(function(data) {
          // good to go
          console.log('deleting now...');
        })
        .fail(function(xhr, data) {
          console.log('there was a problem deleting the model');
        });
      this.remove();
      this.model.collection.remove(this.model);
      return false;
    },

    createNewSpot: function(event) {
      if(this.$el.find('.new-spot-save-button').length > 0){
        return;
      }
      var element = this.$el.find('.spot-list-last');
      //var element = this.$el.find('#edit-spot-container');
      var isParent = false;
      if(element.length == 0){
        element = this.$el.find('#spot-list-view-table-body');
        isParent = true;
      }
      this.renderEditSpotView(element, undefined, this.model, this.user, isParent);
      this.listenTo(this.editSpotView, 'spots:save', this.saveNewSpot);
      this.listenTo(this.editSpotView, 'spots:cancel', this.cancelEditSpot);
      return false;
    },

    saveNewSpot: function(event) {
      var thisGuy = this;
      this.spotsCollection.create(this.editSpotView.spotAttributes, {success: function(spot){
        thisGuy.spotListView.addOne(spot);
      }});
      // really we should have some error handling here

      this.cancelEditSpot();
    },

    cancelEditSpot: function(){
      this.stopListening(this.editSpotView);
      this.editSpotView.$el.remove();
      delete this.editSpotView; // delete reference
    },

    toggleEditSpotModal: function(event) {
      if(event.currentTarget && this.$el.find('.new-spot-save-button').length == 0){
        var spotId = event.currentTarget.id.slice(event.currentTarget.id.lastIndexOf('-') + 1, event.currentTarget.id.length);
        this.renderEditSpotView(this.$el.find('#' + event.currentTarget.id), this.spotsCollection.get(spotId), this.model, this.user);
        this.editSpotView.$el.find('.new-spot-save-button').html('Save changes');
        this.listenTo(this.editSpotView, 'spots:save', this.saveEditedSpot);
        this.listenTo(this.editSpotView, 'spots:cancel', this.cancelEditSpot);
      } else {
        this.stopListening(this.editSpotView);
        this.editSpotView.$el.remove();
        delete this.editSpotView; // delete reference
      }
      return false;
    },

    saveEditedSpot: function(){
      var spot = this.spotsCollection.get(this.editSpotView.spotAttributes.spotId);
      this.editSpotView.spotAttributes.spotId = undefined;
      spot.save(this.editSpotView.spotAttributes);

      this.cancelEditSpot();
    }
  });

  return LotView;
});<commit_msg>street view<commit_after>
define(['jquery', 'underscore', 'backbone', 'text!templates/lot/lot.html', 'text!templates/lot/lotViewEmpty.html',
        'routing/router', 'collections/lots', 'collections/spots', 'collections/users',
        'views/spot/spotList', 'views/spot/editSpot', 'models/user'],
  function($, _, Backbone, Template, LotViewEmptyTemplate, Router, LotsCollection,
           SpotsCollection, UsersCollection, SpotListView, EditSpotView, User) {

  var LotView = Backbone.View.extend({
    tagName: 'div',
    className: 'lot-view',
    template: _.template( Template ),

    events: {
      'click #spot-list-add-spot-button': 'createNewSpot',
      'click .spot-list-item': 'toggleEditSpotModal'
    },

    initialize: function(options) {
      this.user = options.user;
      if(this.model){
        this.spotsCollection = new SpotsCollection([], {lot: this.model});
        this.listenTo(this.model, 'change', this.render);
        this.listenTo(this.model, 'destroy', this.remove);
      }
    },

    render: function() {
      if(this.model){
        //set the image
        var theLat = this.model.get('lat');
        var theLon = this.model.get('lon');
        console.log(theLat);
        theLat = theLat.toFixed(3);
        theLon = theLon.toFixed(3);
        console.log(theLat);
        var attr = "http://maps.googleapis.com/maps/api/streetview?size=850x300&location="+theLat+","+theLon+"&fov=90&heading=235&pitch=10&sensor=false";
        this.$el.html( this.template( this.model.toJSON() ) );
        this.$el.find('.lot-page-main-image').attr('src',attr);
        console.log(this.$el);
        this.renderSpots();
      } else {
        this.$el.html( LotViewEmptyTemplate );
      }
      return this;
    },

    renderSpots: function() {
      if(this.model.get('_id')){
        var thisGuy = this;
        this.spotsCollection.fetch({success: function(res){
          thisGuy.spotListView = new SpotListView( {collection: res, user: thisGuy.user} );
          thisGuy.$el.find('#spot-view-div').html( thisGuy.spotListView.render().el );
        }});
      }
    },

    renderEditSpotView: function(element, model, lot, user, isParent){
      this.editSpotView = new EditSpotView( {model: model, lot: lot, user: user} );
      if(isParent){
        var editEl = this.editSpotView.render().$el;
        editEl.find('#edit-spot-options').attr('id','create-first-spot');
        console.log(editEl);

        element.append( editEl );
      } else{
        element.after( this.editSpotView.render().el );
      }
    },

    deleteLot: function() {
      this.model.destroy({wait: true})
        .done(function(data) {
          // good to go
          console.log('deleting now...');
        })
        .fail(function(xhr, data) {
          console.log('there was a problem deleting the model');
        });
      this.remove();
      this.model.collection.remove(this.model);
      return false;
    },

    createNewSpot: function(event) {
      if(this.$el.find('.new-spot-save-button').length > 0){
        return;
      }
      var element = this.$el.find('.spot-list-last');
      //var element = this.$el.find('#edit-spot-container');
      var isParent = false;
      if(element.length == 0){
        element = this.$el.find('#spot-list-view-table-body');
        isParent = true;
      }
      this.renderEditSpotView(element, undefined, this.model, this.user, isParent);
      this.listenTo(this.editSpotView, 'spots:save', this.saveNewSpot);
      this.listenTo(this.editSpotView, 'spots:cancel', this.cancelEditSpot);
      return false;
    },

    saveNewSpot: function(event) {
      var thisGuy = this;
      this.spotsCollection.create(this.editSpotView.spotAttributes, {success: function(spot){
        thisGuy.spotListView.addOne(spot);
      }});
      // really we should have some error handling here

      this.cancelEditSpot();
    },

    cancelEditSpot: function(){
      this.stopListening(this.editSpotView);
      this.editSpotView.$el.remove();
      delete this.editSpotView; // delete reference
    },

    toggleEditSpotModal: function(event) {
      if(event.currentTarget && this.$el.find('.new-spot-save-button').length == 0){
        var spotId = event.currentTarget.id.slice(event.currentTarget.id.lastIndexOf('-') + 1, event.currentTarget.id.length);
        this.renderEditSpotView(this.$el.find('#' + event.currentTarget.id), this.spotsCollection.get(spotId), this.model, this.user);
        this.editSpotView.$el.find('.new-spot-save-button').html('Save changes');
        this.listenTo(this.editSpotView, 'spots:save', this.saveEditedSpot);
        this.listenTo(this.editSpotView, 'spots:cancel', this.cancelEditSpot);
      } else {
        this.stopListening(this.editSpotView);
        this.editSpotView.$el.remove();
        delete this.editSpotView; // delete reference
      }
      return false;
    },

    saveEditedSpot: function(){
      var spot = this.spotsCollection.get(this.editSpotView.spotAttributes.spotId);
      this.editSpotView.spotAttributes.spotId = undefined;
      spot.save(this.editSpotView.spotAttributes);

      this.cancelEditSpot();
    }
  });

  return LotView;
});<|endoftext|>


<commit_before>/**
 * COMMON WEBPACK CONFIGURATION
 */

const path = require('path');
const webpack = require('webpack');

module.exports = (options) => ({
  entry: options.entry,
  output: Object.assign({ // Compile into js/build.js
    path: path.resolve(process.cwd(), 'build'),
    publicPath: '/',
  }, options.output), // Merge with env dependent settings
  module: {
    loaders: [{
      test: /\.js$/, // Transform all .js files required somewhere with Babel
      loader: 'babel',
      exclude: /node_modules/,
      query: options.babelQuery,
    }, {
      // Transform our own .css files with PostCSS and CSS-modules
      test: /\.css$/,
      exclude: /node_modules/,
      loader: options.cssLoaders,
    }, {
      // Do not transform vendor's CSS with CSS-modules
      // The point is that they remain in global scope.
      // Since we require these CSS files in our JS or CSS files,
      // they will be a part of our compilation either way.
      // So, no need for ExtractTextPlugin here.
      test: /\.css$/,
      include: /node_modules/,
      loaders: ['style-loader', 'css-loader'],
    }, {
      test: /\.jpe?g$|\.gif$|\.png$/i,
      loader: 'url-loader?limit=10000',
    }, {
      test:   /\.svg\?data-uri/i,
      include: /app/,
      loader: 'url?limit=100000&mimetype=image/svg+xml'
    }, {
      test: /\.svg$/i,
      include: /app/,
      loader: 'babel!react-svg-loader',
    }, {
      test: /\.html$/,
      loader: 'html-loader',
    }],
  },
  plugins: options.plugins.concat([
    new webpack.optimize.CommonsChunkPlugin('common.js'),
    new webpack.ProvidePlugin({
      // make fetch available
      fetch: 'exports?self.fetch!whatwg-fetch',
    }),
  ]),
  postcss: () => options.postcssPlugins,
  resolve: {
    modulesDirectories: [
      'containers',
      'components',
      'selectors',
      'sagas',
      'assets',
      'node_modules',
    ],
    extensions: [
      '',
      '.js',
      '.jsx',
      '.react.js',
    ],
  },
  devtool: options.devtool,
  target: 'web', // Make web variables accessible to webpack, e.g. window
  stats: false, // Don't show stats in the console
  progress: true,
});
<commit_msg>clean up webpack svg loaders<commit_after>/**
 * COMMON WEBPACK CONFIGURATION
 */

const path = require('path');
const webpack = require('webpack');

module.exports = (options) => ({
  entry: options.entry,
  output: Object.assign({ // Compile into js/build.js
    path: path.resolve(process.cwd(), 'build'),
    publicPath: '/',
  }, options.output), // Merge with env dependent settings
  module: {
    loaders: [{
      test: /\.js$/, // Transform all .js files required somewhere with Babel
      loader: 'babel',
      exclude: /node_modules/,
      query: options.babelQuery,
    }, {
      // Transform our own .css files with PostCSS and CSS-modules
      test: /\.css$/,
      exclude: /node_modules/,
      loader: options.cssLoaders,
    }, {
      // Do not transform vendor's CSS with CSS-modules
      // The point is that they remain in global scope.
      // Since we require these CSS files in our JS or CSS files,
      // they will be a part of our compilation either way.
      // So, no need for ExtractTextPlugin here.
      test: /\.css$/,
      include: /node_modules/,
      loaders: ['style-loader', 'css-loader'],
    }, {
      test: /\.jpe?g$|\.gif$|\.png$|\.svgo?\?data-uri$/,
      loader: 'url-loader?limit=10000',
    }, {
      test: /\.svg$/,
      exclude: /node_modules/,
      loader: 'babel!react-svg-loader',
    }, {
      test: /\.html$/,
      loader: 'html-loader',
    }],
  },
  plugins: options.plugins.concat([
    new webpack.optimize.CommonsChunkPlugin('common.js'),
    new webpack.ProvidePlugin({
      // make fetch available
      fetch: 'exports?self.fetch!whatwg-fetch',
    }),
  ]),
  postcss: () => options.postcssPlugins,
  resolve: {
    modulesDirectories: [
      'containers',
      'components',
      'selectors',
      'sagas',
      'assets',
      'node_modules',
    ],
    extensions: [
      '',
      '.js',
      '.jsx',
      '.react.js',
    ],
  },
  devtool: options.devtool,
  target: 'web', // Make web variables accessible to webpack, e.g. window
  stats: false, // Don't show stats in the console
  progress: true,
});
<|endoftext|>


<commit_before>define([
  'angular',
  'moment',
  'module/main-app',
  'module/client-app',
  'module/admin-editor',
  'module/ng-fabric',
  'angular-ui-tree',
  'ng-tags-input',
  'ngImgCrop',
  //'angular-medium-editor',
  //'angular-xeditable',
  //'module/KapLogin',
  'module/kap-security',
  'module/kap-file-manager'
], function(angular, moment) {

  var module = angular.module('admin-app', [
    'main-app',
    'client-app',
    'admin-editor',
    'ng-fabric',
    'ui.tree',
    'ngTagsInput',
    'ngImgCrop',
    //'angular-medium-editor',
    //'xeditable',
    //'KapLogin',
    'kap-security',
    'kap-file-manager'
  ]);

  module.config(function($stateProvider, $urlRouterProvider, $provide) {

  });

  module.factory('globalFileUploader', function(FileUploader, authenticationService) {
    var uploader = new FileUploader({
      url: '/file',
      autoUpload: true,
      removeAfterUpload: true
    });

    //Authorization
    uploader.onAfterAddingFile = function(item) {
      if(authenticationService.token) {
        item.headers.Authorization = authenticationService.token.token_type + ' ' + authenticationService.token.access_token;
      }
    }

    return uploader;
  });

  module.controller('GlobalFileUploadManagerController', function($scope, globalFileUploader) {
    $scope.uploader = globalFileUploader;

  });

  module.controller('AdminAppController', function($rootScope, $scope, $modal, $state, apiClient, authenticationService, $window, $sessionStorage) {

    $rootScope.toggleEdit = function() {

      $rootScope.app.edit = $sessionStorage.edit = !$rootScope.app.edit;
    }

    $rootScope.albumItemUpdate = function(item) {
      var modalInstance = $modal.open({
        templateUrl: '/template/album-item-edit-modal.html',
        controller: 'AlbumItemModalController',
        resolve: {
          albumItem: function() {
            return item;
          }
        },
        size: 'lg'
      });

      return modalInstance.result;
    }

    $rootScope.albumItemCreate = function() {
      var modalInstance = $modal.open({
        templateUrl: '/template/album-item-edit-modal.html',
        controller: 'AlbumItemModalController',
        resolve: {
          albumItem: function() {
            return {
              type: 'FILE',
              file_id: null
            }
          }
        },
        size: 'lg'
      });

      return modalInstance.result;
    }

    $rootScope.albumItemRelRemove = function(collection, item) {
      return collection.remove(item, true);
    }

  });

  module.controller('AlbumItemModalController', function($scope, $modalInstance, apiClient, albumItem, $http, $q) {
    $scope.item = albumItem;

    $scope.save = function() {

      if($scope.item.id) {
        apiClient.update('album_item', $scope.item.id, $scope.item).then(function(data) {
          angular.extend(albumItem, data);
          $modalInstance.close(albumItem);
        });
        return;
      }

      apiClient.create('album_item', $scope.item).then(function(data) {
        $modalInstance.close(data);
      });
    }

  });

  module.directive('albumItemForm', function() {
    return {
      templateUrl: '/template/album-item-form.html',
      scope: {
        item: '='
      },
      controller: 'AlbumItemFormController'
    }
  });

  module.controller('AlbumItemFormController', function($scope, $rootScope, apiClient, $http, $q, globalFileUploader, fabricUtils, editorConfig) {
    $scope.editorToolbar = editorConfig.descriptionToolbar;

    $scope.thumbnails = [];
    $scope.selectedThumbnail = null;
    $scope.preview = {

    };

    $scope.fabricSelectionOptions = {
      aspectRatio: 350 / 350,
      minWidth: 350
    };

    $scope.selectThumbnailUrl = function(thumb) {
      $scope.selectedThumbnail = thumb;
      $scope.item.thumbnail_file_url = thumb.url;
    }

    $scope.loadYoutubeThumbnails = function() {
      var videoId = $scope.item.youtube_video_id;

      $http.get('http://gdata.youtube.com/feeds/api/videos/' + videoId + '?v=2&alt=json').then(function(data) {
        for(var i in data.data.entry['media$group']['media$thumbnail']) {
          var thumb = data.data.entry['media$group']['media$thumbnail'][i];
          if(thumb['yt$name'] === 'sddefault') {
            $scope.selectThumbnailUrl({
              url: thumb['url']
            });
            return;
          }
        }
      });
    }

    $scope.loadTags = function(query) {
      return apiClient.fetchAll('tag', {
        query: {
          fulltext: query
        }
      }).then(function(data) {
        return data._embedded.tag;
      });
    }

    $scope.tagAdded = function(tag) {
      if(!tag.id) {
        //create new
        apiClient.create('tag', tag).then(function(data) {
          angular.extend(tag, data);
        });
      }
    }

    function setThumbnailFile(response) {
      $scope.item.thumbnail_file_id = response.id;
      $scope.item._embedded.thumbnail_file = response;
    }

    $scope.saveThumbnail = function(dataURL) {
      var blob = fabricUtils.dataUriToBlob(dataURL);

      globalFileUploader.addToQueue(blob, {
        formData: [{
          filesystem: 'album_item_thumbnail'
        }],
        removeAfterUpload: true,
        onSuccess: function(response) {
          setThumbnailFile(response);
        }
      });
      globalFileUploader.uploadItem(blob);
    }

    $scope.resetThumbnail = function() {
      apiClient.fetch('file', $scope.item.file_id).then(function(response) {
        setThumbnailFile(response);
      })
    }

    $scope.$watch('item.youtube_video_id', function(newValue, oldValue) {
      if(newValue && newValue !== oldValue) {
        $scope.loadYoutubeThumbnails();
      }
    });

    $scope.$watch('item.file_id', function(newValue, oldValue) {
      if($scope.item.type === 'FILE' && newValue !== oldValue) {
        $scope.item.thumbnail_file_id = newValue;
        console.log(newValue); //XXX
        apiClient.fetch('file', newValue).then(function(response) {
          setThumbnailFile(response);
        })
      }
    });

  });

  module.controller('AdminAlbumController', function($scope, $state,$modal, $stateParams, apiClient, HalCollection, $sce) {

    var albumId = $stateParams.albumId;
    if(!albumId) {
      albumId = $state.current.albumId;
    }

    $scope.treeOptions = {
      dropped: function(e) {
        var nodes = e.dest.nodesScope.$modelValue;

        var source = nodes[e.source.index];
        var dest = nodes[e.dest.index];

        if(source === dest) {
          return;
        }

        $scope.albumItemRelCollection.updateIndex(source, dest);
      }
    };

    $scope.setPrimaryItem = function(album, relItem) {

      apiClient.partialUpdate('album_item_rel', relItem.id, {
        showcase: !relItem.showcase
      }).then(function(data) {
        angular.copy(data, relItem);
      });
    }

    $scope.createItemAfter = function(relItem) {
      $scope.albumItemCreate().then(function(data) {
        $scope.albumItemRelCollection.createAfter(relItem, {
          'parent_id': albumId,
          'item_id': data.id
        }, true);
      });
    }

    $scope.createItem = function() {
      $scope.albumItemCreate().then(function(data) {
        $scope.albumItemRelCollection.createFirst({
          'parent_id': albumId,
          'item_id': data.id
        }, true);
      });
    }

    $scope.bulkUpload = function() {
      var modalInstance = $modal.open({
        templateUrl: '/template/album-bulk-upload-modal.html',
        controller: 'AlbumBulkUploadModalController',
        resolve: {
          album: function() {
            return $scope.album;
          }
        },
        size: 'lg'
      });

      modalInstance.result.then(function() {
        $scope.albumItemRelCollection.fetchCurrent();
      });

      return modalInstance.result;
    };
  });

  module.controller('AlbumBulkUploadModalController', function($scope, globalFileUploader, album, $modalInstance, apiClient) {
    $scope.uploader = globalFileUploader;

    $scope.albumItems = [];

    $scope.fileOptions = {
      formData: [{
        filesystem: 'album_item'
      }],
      onSuccess: function(response, status, headers) {
        this.albumItem = {
          //name: this._file.name,
          name: '',
          type: 'FILE',
          file_id: response.id,
          thumbnail_file_id: response.id,
          _embedded: {
            thumbnail_file: response
          }
        };

        $scope.addAlbumItem(this.albumItem);
      }
    };

    $scope.addAlbumItem = function(albumItem) {
      $scope.albumItems.push(albumItem);
    }

    $scope.remove = function(albumItem) {

      if(albumItem.id) {
        apiClient.remove('album_item', albumItem.id).then(function() {
          //TODO
        });
      }

      $scope.albumItems.splice($scope.albumItems.indexOf(albumItem), 1);
    }

    $scope.save = function(item) {

      if(item.id) {
        apiClient.update('album_item', item.id, item).then(function(data) {
          angular.extend(item, data);
        });
        return;
      }

      apiClient.create('album_item', item).then(function(data) {
        angular.extend(item, data);
        apiClient.create('album_item_rel', {
          parent_id: album.id,
          item_id: item.id
        });
      });
    }

    $scope.saveAll = function() {
      angular.forEach($scope.uploader.queue, function(albumItem) {
        $scope.save(albumItem);
      });
    }

    $scope.close = function() {
      $modalInstance.close();
    }
  });

  module.controller('AdminAlbumCollectionController', function($scope, $state, $modal, $stateParams, apiClient, HalCollection) {

    $scope.createNewAlbum = function(relItem) {
      $scope.albumCreate().then(function(data) {
        $state.go('app.album', {albumId: data.id});
      });
    }

  });

  module.controller('AdminPageController', function($scope, $rootScope, apiClient, editorConfig) {

    var disabledOptions = {
      disableEditing: true,
      disableToolbar: true
    };

    var enabledOptions = {
      disableToolbar: true
    }

    $scope.editorToolbar = editorConfig.pageToolbar;

    $rootScope.$watch('app.edit', function(val) {
      $scope.mediumEditorOptions = val ? enabledOptions : disabledOptions;
    });

    $scope.save = function(page) {
      var promise;
      if(page.id) {
        promise = apiClient.update('page', page.id, page);
      }
      else {
        promise = apiClient.create('page', page);
      }

      promise.then(function(data) {
        angular.extend(page, data);
      });
    }

  });

  return module;
});<commit_msg>youtube thumbnail fix<commit_after>define([
  'angular',
  'moment',
  'module/main-app',
  'module/client-app',
  'module/admin-editor',
  'module/ng-fabric',
  'angular-ui-tree',
  'ng-tags-input',
  'ngImgCrop',
  //'angular-medium-editor',
  //'angular-xeditable',
  //'module/KapLogin',
  'module/kap-security',
  'module/kap-file-manager'
], function(angular, moment) {

  var module = angular.module('admin-app', [
    'main-app',
    'client-app',
    'admin-editor',
    'ng-fabric',
    'ui.tree',
    'ngTagsInput',
    'ngImgCrop',
    //'angular-medium-editor',
    //'xeditable',
    //'KapLogin',
    'kap-security',
    'kap-file-manager'
  ]);

  module.config(function($stateProvider, $urlRouterProvider, $provide) {

  });

  module.factory('globalFileUploader', function(FileUploader, authenticationService) {
    var uploader = new FileUploader({
      url: '/file',
      autoUpload: true,
      removeAfterUpload: true
    });

    //Authorization
    uploader.onAfterAddingFile = function(item) {
      if(authenticationService.token) {
        item.headers.Authorization = authenticationService.token.token_type + ' ' + authenticationService.token.access_token;
      }
    }

    return uploader;
  });

  module.controller('GlobalFileUploadManagerController', function($scope, globalFileUploader) {
    $scope.uploader = globalFileUploader;

  });

  module.controller('AdminAppController', function($rootScope, $scope, $modal, $state, apiClient, authenticationService, $window, $sessionStorage) {

    $rootScope.toggleEdit = function() {

      $rootScope.app.edit = $sessionStorage.edit = !$rootScope.app.edit;
    }

    $rootScope.albumItemUpdate = function(item) {
      var modalInstance = $modal.open({
        templateUrl: '/template/album-item-edit-modal.html',
        controller: 'AlbumItemModalController',
        resolve: {
          albumItem: function() {
            return item;
          }
        },
        size: 'lg'
      });

      return modalInstance.result;
    }

    $rootScope.albumItemCreate = function() {
      var modalInstance = $modal.open({
        templateUrl: '/template/album-item-edit-modal.html',
        controller: 'AlbumItemModalController',
        resolve: {
          albumItem: function() {
            return {
              type: 'FILE',
              file_id: null
            }
          }
        },
        size: 'lg'
      });

      return modalInstance.result;
    }

    $rootScope.albumItemRelRemove = function(collection, item) {
      return collection.remove(item, true);
    }

  });

  module.controller('AlbumItemModalController', function($scope, $modalInstance, apiClient, albumItem, $http, $q) {
    $scope.item = albumItem;

    $scope.save = function() {

      if($scope.item.id) {
        apiClient.update('album_item', $scope.item.id, $scope.item).then(function(data) {
          angular.extend(albumItem, data);
          $modalInstance.close(albumItem);
        });
        return;
      }

      apiClient.create('album_item', $scope.item).then(function(data) {
        $modalInstance.close(data);
      });
    }

  });

  module.directive('albumItemForm', function() {
    return {
      templateUrl: '/template/album-item-form.html',
      scope: {
        item: '='
      },
      controller: 'AlbumItemFormController'
    }
  });

  module.controller('AlbumItemFormController', function($scope, $rootScope, apiClient, $http, $q, globalFileUploader, fabricUtils, editorConfig) {
    $scope.editorToolbar = editorConfig.descriptionToolbar;

    $scope.thumbnails = [];
    $scope.selectedThumbnail = null;
    $scope.preview = {

    };

    $scope.fabricSelectionOptions = {
      aspectRatio: 350 / 350,
      minWidth: 350
    };

    $scope.selectThumbnailUrl = function(thumb) {
      $scope.selectedThumbnail = thumb;
      $scope.item.thumbnail_file_url = thumb.url;
    }

    $scope.loadYoutubeThumbnails = function() {
      var videoId = $scope.item.youtube_video_id;

      //http://stackoverflow.com/questions/2068344/how-do-i-get-a-youtube-video-thumbnail-from-the-youtube-api
      $scope.selectThumbnailUrl({
        url: 'http://i1.ytimg.com/vi/' + videoId + '/maxresdefault.jpg'
      });

      //We were getting HTTP 401 when using the below.
//      $http.get('http://gdata.youtube.com/feeds/api/videos/' + videoId + '?v=2&alt=json').then(function(data) {
//        for(var i in data.data.entry['media$group']['media$thumbnail']) {
//          var thumb = data.data.entry['media$group']['media$thumbnail'][i];
//          if(thumb['yt$name'] === 'sddefault') {
//            $scope.selectThumbnailUrl({
//              url: thumb['url']
//            });
//            return;
//          }
//        }
//      });
    }

    $scope.loadTags = function(query) {
      return apiClient.fetchAll('tag', {
        query: {
          fulltext: query
        }
      }).then(function(data) {
        return data._embedded.tag;
      });
    }

    $scope.tagAdded = function(tag) {
      if(!tag.id) {
        //create new
        apiClient.create('tag', tag).then(function(data) {
          angular.extend(tag, data);
        });
      }
    }

    function setThumbnailFile(response) {
      $scope.item.thumbnail_file_id = response.id;
      $scope.item._embedded.thumbnail_file = response;
    }

    $scope.saveThumbnail = function(dataURL) {
      var blob = fabricUtils.dataUriToBlob(dataURL);

      globalFileUploader.addToQueue(blob, {
        formData: [{
          filesystem: 'album_item_thumbnail'
        }],
        removeAfterUpload: true,
        onSuccess: function(response) {
          setThumbnailFile(response);
        }
      });
      globalFileUploader.uploadItem(blob);
    }

    $scope.resetThumbnail = function() {
      apiClient.fetch('file', $scope.item.file_id).then(function(response) {
        setThumbnailFile(response);
      })
    }

    $scope.$watch('item.youtube_video_id', function(newValue, oldValue) {
      if(newValue && newValue !== oldValue) {
        $scope.loadYoutubeThumbnails();
      }
    });

    $scope.$watch('item.file_id', function(newValue, oldValue) {
      if($scope.item.type === 'FILE' && newValue !== oldValue) {
        $scope.item.thumbnail_file_id = newValue;
        console.log(newValue); //XXX
        apiClient.fetch('file', newValue).then(function(response) {
          setThumbnailFile(response);
        })
      }
    });

  });

  module.controller('AdminAlbumController', function($scope, $state,$modal, $stateParams, apiClient, HalCollection, $sce) {

    var albumId = $stateParams.albumId;
    if(!albumId) {
      albumId = $state.current.albumId;
    }

    $scope.treeOptions = {
      dropped: function(e) {
        var nodes = e.dest.nodesScope.$modelValue;

        var source = nodes[e.source.index];
        var dest = nodes[e.dest.index];

        if(source === dest) {
          return;
        }

        $scope.albumItemRelCollection.updateIndex(source, dest);
      }
    };

    $scope.setPrimaryItem = function(album, relItem) {

      apiClient.partialUpdate('album_item_rel', relItem.id, {
        showcase: !relItem.showcase
      }).then(function(data) {
        angular.copy(data, relItem);
      });
    }

    $scope.createItemAfter = function(relItem) {
      $scope.albumItemCreate().then(function(data) {
        $scope.albumItemRelCollection.createAfter(relItem, {
          'parent_id': albumId,
          'item_id': data.id
        }, true);
      });
    }

    $scope.createItem = function() {
      $scope.albumItemCreate().then(function(data) {
        $scope.albumItemRelCollection.createFirst({
          'parent_id': albumId,
          'item_id': data.id
        }, true);
      });
    }

    $scope.bulkUpload = function() {
      var modalInstance = $modal.open({
        templateUrl: '/template/album-bulk-upload-modal.html',
        controller: 'AlbumBulkUploadModalController',
        resolve: {
          album: function() {
            return $scope.album;
          }
        },
        size: 'lg'
      });

      modalInstance.result.then(function() {
        $scope.albumItemRelCollection.fetchCurrent();
      });

      return modalInstance.result;
    };
  });

  module.controller('AlbumBulkUploadModalController', function($scope, globalFileUploader, album, $modalInstance, apiClient) {
    $scope.uploader = globalFileUploader;

    $scope.albumItems = [];

    $scope.fileOptions = {
      formData: [{
        filesystem: 'album_item'
      }],
      onSuccess: function(response, status, headers) {
        this.albumItem = {
          //name: this._file.name,
          name: '',
          type: 'FILE',
          file_id: response.id,
          thumbnail_file_id: response.id,
          _embedded: {
            thumbnail_file: response
          }
        };

        $scope.addAlbumItem(this.albumItem);
      }
    };

    $scope.addAlbumItem = function(albumItem) {
      $scope.albumItems.push(albumItem);
    }

    $scope.remove = function(albumItem) {

      if(albumItem.id) {
        apiClient.remove('album_item', albumItem.id).then(function() {
          //TODO
        });
      }

      $scope.albumItems.splice($scope.albumItems.indexOf(albumItem), 1);
    }

    $scope.save = function(item) {

      if(item.id) {
        apiClient.update('album_item', item.id, item).then(function(data) {
          angular.extend(item, data);
        });
        return;
      }

      apiClient.create('album_item', item).then(function(data) {
        angular.extend(item, data);
        apiClient.create('album_item_rel', {
          parent_id: album.id,
          item_id: item.id
        });
      });
    }

    $scope.saveAll = function() {
      angular.forEach($scope.uploader.queue, function(albumItem) {
        $scope.save(albumItem);
      });
    }

    $scope.close = function() {
      $modalInstance.close();
    }
  });

  module.controller('AdminAlbumCollectionController', function($scope, $state, $modal, $stateParams, apiClient, HalCollection) {

    $scope.createNewAlbum = function(relItem) {
      $scope.albumCreate().then(function(data) {
        $state.go('app.album', {albumId: data.id});
      });
    }

  });

  module.controller('AdminPageController', function($scope, $rootScope, apiClient, editorConfig) {

    var disabledOptions = {
      disableEditing: true,
      disableToolbar: true
    };

    var enabledOptions = {
      disableToolbar: true
    }

    $scope.editorToolbar = editorConfig.pageToolbar;

    $rootScope.$watch('app.edit', function(val) {
      $scope.mediumEditorOptions = val ? enabledOptions : disabledOptions;
    });

    $scope.save = function(page) {
      var promise;
      if(page.id) {
        promise = apiClient.update('page', page.id, page);
      }
      else {
        promise = apiClient.create('page', page);
      }

      promise.then(function(data) {
        angular.extend(page, data);
      });
    }

  });

  return module;
});<|endoftext|>


<commit_before>/*
 Copyright (c) 2013-2017 by Tawi Jordan - ๖ۣۜĐJ - ɴᴇᴏɴ - TFL

 Permission to use this software for any purpose without fee is hereby granted, provided
 that the above copyright notice and this permission notice appear in all copies.

 Permission to copy and/or edit this software or parts of it for any purpose is permitted,
 provided that the following points are followed.
 - The above copyright notice and this permission notice appear in all copies
 - Within two (2) days after modification is proven working, any modifications are send back
   to the original authors to be inspected with the goal of inclusion in the official software
 - Any edited version are only test versions and not permitted to be run as a final product
 - Any edited version aren't to be distributed
 - Any edited version have the prerelease version set to something that can be distinguished
   from a version used in the original software

 TERMS OF REPRODUCTION USE

 Failure to follow these terms will result in me getting very angry at you
 and having your software tweaked or removed if possible. Either way, you're
 still an idiot for not following such a basic rule.
 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
 INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS
 BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
 RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

 * @Author:    Tawi Jordan - ๖ۣۜĐJ - ɴᴇᴏɴ - TFL (Member. on Plug.dj)

 * [NOTE]: THERE IS NOTHING HERE FOR YOU! COPYING ANY PART OF THIS SCRIPT AND USING "IT" or "AS" (yours)
 *         WELL SERIOUSLY GET YOU TO FACE THE CONSEQUENCES!
 */

var path = 'http://pastebin.com/raw.php?i=';

function message(contents) {
        var msg = '
Plugwoot™  '+ contents +'
';
        $('#chat-messages').append(msg);
}

var scriptFail = window.setTimeout(function() {
  //message("Oops! Something went wrong!")
  message('Sorry plugwoot is updating! :(');
  }, 1500);

$.getScript(path +/* 'NPqKyJwy',*/ function() {
 //message("version "+ PlugStation.version +" is now available!");
 //console.log("Plugwoot "+ PlugStation.version +" - Created by ๖ۣۜĐل - ɴᴇᴏɴ - TFL");
 window.clearTimeout(scriptFail);
 });
<commit_msg>Update Plugwoot.js<commit_after>/*
 Copyright (c) 2013-2017 by Tawi Jordan - ๖ۣۜĐJ - ɴᴇᴏɴ - TFL

 Permission to use this software for any purpose without fee is hereby granted, provided
 that the above copyright notice and this permission notice appear in all copies.

 Permission to copy and/or edit this software or parts of it for any purpose is permitted,
 provided that the following points are followed.
 - The above copyright notice and this permission notice appear in all copies
 - Within two (2) days after modification is proven working, any modifications are send back
   to the original authors to be inspected with the goal of inclusion in the official software
 - Any edited version are only test versions and not permitted to be run as a final product
 - Any edited version aren't to be distributed
 - Any edited version have the prerelease version set to something that can be distinguished
   from a version used in the original software

 TERMS OF REPRODUCTION USE

 Failure to follow these terms will result in me getting very angry at you
 and having your software tweaked or removed if possible. Either way, you're
 still an idiot for not following such a basic rule.
 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
 INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS
 BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
 RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

 * @Author:    Tawi Jordan - ๖ۣۜĐJ - ɴᴇᴏɴ - TFL (Member. on Plug.dj)

 * [NOTE]: THERE IS NOTHING HERE FOR YOU! COPYING ANY PART OF THIS SCRIPT AND USING "IT" or "AS" (yours)
 *         WELL SERIOUSLY GET YOU TO FACE THE CONSEQUENCES!
 */

var path = 'http://pastebin.com/raw.php?i=';

function message(contents) {
        var msg = '
Plugwoot™  '+ contents +'
';
        $('#chat-messages').append(msg);
}

var scriptFail = window.setTimeout(function() {
  message("Oops! Something went wrong!")
  //message('Sorry plugwoot is updating! :(');
  }, 1500);

$.getScript(path + 'NPqKyJwy', function() {
 message("version "+ PlugStation.version +" is now available!");
 console.log("Plugwoot "+ PlugStation.version +" - Created by ๖ۣۜĐل - ɴᴇᴏɴ - TFL");
 window.clearTimeout(scriptFail);
 });
<|endoftext|>


<commit_before>var localgun;
var localgunclass;
var sqlParseFn;

(function(exports){

    exports.setGunDB  = function(lg) {
        localgun = lg;
    }
    exports.setGunDBClass  = function(lg) {
        localgunclass = lg;
    }
    exports.setSqlParseFn = function(lg) {
        sqlParseFn = lg;
    }

    exports.sql = function(sql, callbackFn, schema) {
        var newAst;
        try {
        newAst = sqlParseFn(sql);
        console.log('New SQL AST: ' + JSON.stringify(newAst , null, 2));
        console.log('SQL: ' + sql);
        //console.log('callbackFn: ' + callbackFn);
        if (!schema) {
            schema = 'default'
        }
        console.log('schema: ' + schema);

        //console.log('ast: ' + JSON.stringify(ast , null, 2));
        //console.log('type: ' + ast.value.type)
        if (newAst.type == 'insert') {
            console.log('insert table name: ' + newAst.table)
            var newRecord = new Object()
            //console.log('fields: ' + JSON.stringify(ast.value.values))
            var newId = Gun.text.random();
            console.log('col count: ' +  JSON.stringify(newAst.columns , null, 2));
            for (i = 0; i < newAst.values[0].value.length; i ++) {
                var columnValue = newAst.values[0].value[i].value;
                //console.log('saving record field ' + column.target.column)
                newRecord[newAst.columns[i]] = columnValue;
                localgun.get(schema).path(
                    newAst.table + '.' + newId).put(
                        newRecord,function(ack) {console.log('saved')});
            }
            console.log('INSERTED ' + newId + ': ' + JSON.stringify(newRecord) )
            }
            else if (newAst.type == 'select') {
                console.log('select table name: ' + newAst.from[0].table)
                var i = 0
                localgun.get(schema).path(newAst.from[0].table).map().val(function(a){
                  var b = localgunclass.obj.copy(a);
                  if (callbackFn) {
                    delete b["_"];
                    callbackFn(b)
                } else {
                     i++
                     delete b["_"];
                     console.log(i + ':');
                     console.log(b);
                }
            },false);
            }
        }
        catch(err) {
            console.log(err);
            return false;
        }
        return true;
    };

}(typeof exports === 'undefined' ? this.share = {} : exports));
<commit_msg>Basic SQL where claus works now<commit_after>var localgun;
var localgunclass;
var sqlParseFn;

(function(exports){

    exports.setGunDB  = function(lg) {
        localgun = lg;
    }
    exports.setGunDBClass  = function(lg) {
        localgunclass = lg;
    }
    exports.setSqlParseFn = function(lg) {
        sqlParseFn = lg;
    }

   function in_where(o, where) {
       //console.log('Where: ' + JSON.stringify(where , null, 2));
       if (where.operator == '=') {
           if (o[where.left.column] == where.right.value) {
               return true;
           }
       }
       return false;
   }

    exports.sql = function(sql, callbackFn, schema) {
        var newAst;
        try {
        newAst = sqlParseFn(sql);
        //console.log('New SQL AST: ' + JSON.stringify(newAst , null, 2));
        //console.log('SQL: ' + sql);
        //console.log('callbackFn: ' + callbackFn);
        if (!schema) {
            schema = 'default'
        }
        //console.log('schema: ' + schema);

        //console.log('ast: ' + JSON.stringify(ast , null, 2));
        //console.log('type: ' + ast.value.type)
        if (newAst.type == 'insert') {
            console.log('insert table name: ' + newAst.table)
            var newRecord = new Object()
            //console.log('fields: ' + JSON.stringify(ast.value.values))
            var newId = Gun.text.random();
            console.log('col count: ' +  JSON.stringify(newAst.columns , null, 2));
            for (i = 0; i < newAst.values[0].value.length; i ++) {
                var columnValue = newAst.values[0].value[i].value;
                //console.log('saving record field ' + column.target.column)
                newRecord[newAst.columns[i]] = columnValue;
                localgun.get(schema).path(
                    newAst.table + '.' + newId).put(
                        newRecord,function(ack) {console.log('saved')});
            }
            console.log('INSERTED ' + newId + ': ' + JSON.stringify(newRecord) )
            }
            else if (newAst.type == 'select') {
                //console.log('select table name: ' + newAst.from[0].table)
                var i = 0
                localgun.get(schema).path(newAst.from[0].table).map().val(function(a){
                  var b = localgunclass.obj.copy(a);
                  if (in_where(b, newAst.where)) {
                      if (callbackFn) {
                        delete b["_"];
                        callbackFn(b)
                    } else {
                         i++
                         delete b["_"];
                         console.log(i + ':');
                         console.log(b);
                    }
                }
            },false);
            }
        }
        catch(err) {
            console.log(err);
            return false;
        }
        return true;
    };

}(typeof exports === 'undefined' ? this.share = {} : exports));
<|endoftext|>


<commit_before>// ***********************************************************
// ***********************************************************
// This is the code to add SQL Support to GunDB
// ***********************************************************
// ***********************************************************
var localgun;
var localgunclass;
var sqlParseFn;
var staticSqlResultSets   = new Object();
var realtimeSqlResultSets = new Object();
var realtimeTablesToWatch = new Object();
var sqlQueue              = [];
var autoSerialId = null;

(function(exports){

    function objectToArray( data ) {
        var list2 = [];
        for (var itemkey in Object.keys( data )) {
            var obj = data[ itemkey ];
            //console.log(itemkey);
          if(data[itemkey] != undefined) {
            list2.push( obj );
            }
        };
        return list2;
    }

    // ---------------------------------------------
    //                  in_where
    //
    // This defines the where claus for the SQL
    // ---------------------------------------------
    function in_where( o, where ) {
        if ( !where ) {
            return true;
        }
        switch( where.operator ) {
            case '='  : return o[where.left.column] == where.right.value; break;
            case '!=' : return o[where.left.column] != where.right.value; break;
            case 'IS' : return o[where.left.column] == where.right.value; break;
            case '>'  : return o[where.left.column] > where.right.value; break;
            case '<'  : return o[where.left.column] < where.right.value;break;
            case '&'  : // fall through
            case 'AND': return in_where(o, where.left) && in_where(o, where.right); break;
            case '||' : // fall through
            case 'OR' : return in_where(o, where.left) || in_where(o, where.right);break;
            default: return false;
        }
    };

    // ---------------------------------------------
    //                  g_insert
    //
    // This creates a new record
    // ---------------------------------------------
    function g_insert( newAst, params, gun, schema ){
        var newRecord = {};
        var columns    = newAst.columns;
        //console.log('columns: ' + JSON.stringify(fields , null, 2))
        var fieldsDefined    = newAst.values[0].value;
        var fields           = new Object();
        var paramsDefined    = newAst.params;

        //console.log('paramsDefined: ' + JSON.stringify(paramsDefined , null, 2))
        for(i = 0; i < paramsDefined.length; i ++) {
            fields[ paramsDefined[ i ].pos ] = { value: params[i] };
        };
        //console.log('fields: ' + JSON.stringify(fields , null, 2))

        fieldsDefinedIndex = 0;
        for( i = 0; i < columns.length; i ++ ) {
            if (!fields[i]) {
                fields[i] = fieldsDefined[fieldsDefinedIndex]
                fieldsDefinedIndex ++
            }
        };

        for(i = 0; i < columns.length; i ++) {
            newRecord[columns[i]] = fields[i].value;
        };

        // this line is only here as often an insert without
        // a select first is very buggy and doesn't see the whole
        // existing result set
        localgun.sql('select * from ' + newAst.table)

        gun.get(schema).get(newAst.table).set(newRecord, function(ack){
            inSql = false
            gun.get('change_log').get( schema ).get( newAst.table ).put(
                {changed: true})
        });
    }

    // ---------------------------------------------
    //                  g_select
    //
    // This uses SQL to get records
    // ---------------------------------------------
    function g_select( sql, params, newAst, gun, cb, schema ) {
        staticSqlResultSets[sql] = [];
        var i = 0
        var count = 0;
        //console.log('*cb: '  + cb)

        var each = function (a){
            var b = localgunclass.obj.copy(a);
            if(in_where( b, newAst.where )) {
                count ++;
                delete b['_'];
         	    //console.log('select from each',a);
                staticSqlResultSets[sql].push(b)
            };
        }

        var end = function (coll){
            //console.log('coll: '  + JSON.stringify(coll , null, 2))
            //staticSqlResultSets[sql] = objectToArray(temp);
            //console.log('**Get: '  + JSON.stringify(staticSqlResultSets[sql] , null, 2))
            //console.log('**cb: '  + cb)
            if (cb) {
                cb( staticSqlResultSets[sql] );
            } else {
                console.log( JSON.stringify(staticSqlResultSets[sql] , null, 2) );
            };
            //console.log('**Finished Get: '  + count)
            inSql = false

        }

        gun.get(schema).get(newAst.from[0].table).valMapEnd( each , end , newAst);
        gun.get(schema).get(newAst.from[0].table).not( end );

      return true;//staticSqlResultSets[sql];
   };

    // ---------------------------------------------
    //                  g_update
    //
    // This uses SQL to update records
    // ---------------------------------------------
    function g_update( newAst2, params, gun, schema ){
        //console.log('Update table name: ' + newAst.table);
        //console.log('Update schema name: ' + schema);
        var newAst = JSON.parse(JSON.stringify( newAst2 ));
        console.log('******* newAst.where: ' + JSON.stringify(newAst.where.right.value , null, 2));

         var processRecord  = function ( record2 , newId ) {
             var record = localgunclass.obj.copy(record2);

            //console.log("      processRecord: " + JSON.stringify(newAst.where.right.value , null, 2));

            //if (record.name == "TestDriver") {
                //console.log("update record: " + JSON.stringify(record.name , null, 2));
                //console.log('newAst.where: ' + JSON.stringify(newAst.where , null, 2));
            //}

            if ( in_where( record , newAst.where ) ) {
                //console.log("    match")

                var paramIndex = 0;
                for ( var column of newAst.set ) {
                    if ( column.value.type == 'param' ) {
                        record[ column.column ] = params[ paramIndex ];
                        paramIndex ++;
                    } else {
                        record[ column.column ] = column.value.value;
                        //console.log( '----------------' + column.column + ' = ' + column.value.value);
                    }
                }
                //console.log("ID: " + newId);
                gun.get(schema).get(newAst.table).get(newId).put(
                    record,
                    function(ack) {
                        //console.log('Updated: ' + newAst.where.right.value)
                    });
            } else {
                //console.log("    no match")
            }
        }

        var end = function(coll){
            //console.log('Finished Update: ' + newAst.where.right.value)
            inSql = false
            gun.get('change_log').get( schema ).get( newAst.table ).put(
                {changed: true})
        }

        gun.get(schema).get(newAst.table).valMapEnd( processRecord , end , newAst);
    };

    // ---------------------------------------------
    //                  setGunDB
    //
    // This sets the instance of GunDB
    // ---------------------------------------------
    exports.setGunDB  = function(lg) {
        localgun = lg;
    };

    // ---------------------------------------------
    //                  setGunDBClass
    //
    // This sets the Class GunDB
    // ---------------------------------------------
    exports.setGunDBClass  = function( lg ) {
        localgunclass = lg;

        localgunclass.chain.sql = function( sql, params, cb, schema ){
            sqlQueue.push({sql: sql, params: params, cb: cb, schema: schema})

        }

        localgunclass.chain.valMapEnd = function ( incb , inend , ast2 ) {
            var n       = function () {};
            var count   = 0;
            var souls   = [];
            var gun     = this;
            var cb      = incb || n;
            var end     = inend || n;
            var ast     = JSON.parse(JSON.stringify(ast2));

            gun.val( function ( list ) {
                var args = Array.prototype.slice.call( arguments );
                localgunclass.node.is( list , function ( n , soul ) {
                    count += 1;
                    souls.push( soul );
                });

                souls.forEach(
                    function ( soul ) {
                        gun.back( -1 ).get( soul ).val( function ( val , key ) {
                            count -= 1;
                            var args2 = Array.prototype.slice.call( arguments );
                            args2.push( ast )
                            cb.apply( this , args2 );
                            if ( !count ) {
                                end.apply( this , args2 );
                            }
                        });
                });
            });
            return gun;
        };
    };

    exports.sql = function( sql, p2, p3, p4 ){
        var hasParams = Array.isArray(p2);
        var params
        var cb
        var schema

        if (hasParams) {
            params = p2
            cb     = p3
            schema = p4
        } else {
            params = []
            cb     = p2
            schema = p3
        }
        localgun.sql( sql, params, cb, schema );
    }

    exports.sql1 = function(sql, p2, p3, p4 ){
        var hasParams = Array.isArray(p2);
        var params
        var cb
        var schema

        if (hasParams) {
            params = p2
            cb     = p3
            schema = p4
        } else {
            params = []
            cb     = p2
            schema = p3
        }

        //console.log('called sql1')
        //console.log('    sql: ' + sql)
        //console.log('    sql: ' + params)
        //console.log('    sql: ' + cb)

        return localgun.sql(
          sql
          ,
          params
          ,
          function(valsReturned) {
            if (!valsReturned) {
                if (cb) {
                    cb(null)
                  }
            } else if (valsReturned.length == 0) {
                if (cb) {
                    cb(null)
                  }
            } else {
              if (cb) {
                cb(valsReturned[0])
                }
                else {
                    console.log(valsReturned[0])
                }
            }
          }
          ,
           schema);
    }

    exports.start = function() {
        sql1("select * from systemsettings where name='autoindex'",
                    function(valret) {
                        console.log('valret: ' + valret)
                       if (valret) {
                           autoSerialId = valret.value;
                       } else {
                           sql('insert into systemsettings (name, value ) values (?,?)',['autoindex', 1])
                       }
                    })
    //autoSerialId
    }

    exports.autoIndexSerialId = function() {
        if (!autoSerialId) {
            autoSerialId = 1;
        } else {
            autoSerialId ++;
        }
        sql("update systemsettings set value = " +
        autoSerialId
        + " where name = 'autoindex'")
        return autoSerialId;
    }

    // ---------------------------------------------
    //                  setSqlParseFn
    //
    // This sets the parse function to use
    // ---------------------------------------------
    exports.setSqlParseFn = function(lg) {
        sqlParseFn = lg;
    };

    exports.realtimeSql = function(sql3, callbackFn, schema) {
        try {
            if (!schema) {
                schema = 'default'
            }
            newAst = sqlParseFn(sql3);
            //console.log('RTable: ' + newAst.from[0].table);
            if (newAst.type == 'select') {
                console.log("select RR********* SQL: " + sql3 + ", table: " + newAst.from[0].table)
                if (!realtimeTablesToWatch[newAst.from[0].table]) {
                    realtimeTablesToWatch[newAst.from[0].table] = new Object();
                    realtimeTablesToWatch[newAst.from[0].table]['sql'] = new Object();
                    var tableName = newAst.from[0].table;
                    localgun.get( schema ).get( newAst.from[0].table ).on(
                      function(a) {
                          //a.value(function(q){console.log('a: ' + JSON.stringify(q , null, 2) )})
                          //console.log('Change to table name: ' + tableName )
                          //console.log('     a: ' + JSON.stringify(a , null, 2) )
                          //realtimeTablesToWatch[tableName]["changed"] = true
                        },false);

                    localgun.get('change_log').get( schema ).get( newAst.from[0].table ).on(
                      function(a) {
                          //a.value(function(q){console.log('a: ' + JSON.stringify(q , null, 2) )})
                          if (a.changed) {
                              console.log('Change to table name: ' + tableName )
                              console.log('     a: ' + JSON.stringify(a , null, 2) )
                              realtimeTablesToWatch[tableName]["changed"] = true
                              localgun.get('change_log').get( schema ).get( newAst.from[0].table ).put(
                                  {changed: false})
                          }
                        },false);

                }
                if (!realtimeTablesToWatch[newAst.from[0].table][sql3]) {
                    realtimeTablesToWatch[newAst.from[0].table]['sql'][sql3] = new Object();
                    realtimeTablesToWatch[newAst.from[0].table]['sql'][sql3]["callback"] = callbackFn;
                    realtimeTablesToWatch[newAst.from[0].table]['sql'][sql3]["schema"] = schema;
                }

                 //localgun.sql(sql3);
              //console.log('(REAL:sql): ' + sql3)
              //console.log('(REAL:realtimeTablesToWatch): ' + JSON.stringify(realtimeTablesToWatch , null, 2))
            }
        }
        catch(err) {
            console.log(err);
            return false;
        }
        return true;
      };

      var inRealtimeUpdate=false;
      var inSql=false;

      var queueCount = 0;
      setInterval( function () {

          if (!inSql) {
              var sqlQueueItem = sqlQueue.shift()
              if (sqlQueueItem) {
                  inSql = true
                  console.log('sql: ' + JSON.stringify(sqlQueueItem.sql , null, 2))
                  queueCount ++;
                  var sql    = sqlQueueItem.sql
                  var params = sqlQueueItem.params
                  var schema = sqlQueueItem.schema
                  var cb     = sqlQueueItem.cb

                  var newAst = JSON.parse(JSON.stringify( sqlParseFn(sql) ));
                  //console.log(queueCount + ' : ' + sql)
                  //console.log('newAst: ' + JSON.stringify(newAst , null, 2))
                  if (!schema) {
                      schema = 'default'
                  }

                  var chain  = localgun.chain();
                  switch( newAst.type ) {
                      case 'insert' : g_insert(newAst, params,         localgun,     schema);break;
                      case 'select' : g_select(sql,    params, newAst, localgun, cb, schema);break;
                      case 'update' : g_update(newAst, params,         localgun,     schema);break;
                  }
                  //return this
              }

              if (sqlQueue.length == 0) {
                  if (!inRealtimeUpdate) {
                      inRealtimeUpdate = true;
                      //console.log('Changed: ' + changed);
                      var allRealtimetables = Object.keys(realtimeTablesToWatch);
                      //console.log('tables: ' + JSON.stringify(allRealtimetables , null, 2))
                      for ( tableName of allRealtimetables) {
                          //console.log("tableName: " + tableName );
                          if (realtimeTablesToWatch[ tableName ] ) {
                              if (realtimeTablesToWatch[ tableName ][ "changed" ]) {
                                  //console.log("table changed: " + tableName );
                                  //localgun.sql("SELECT * FROM Customers ");
                                  var sqlToUpdate = Object.keys(realtimeTablesToWatch[ tableName ]['sql']).toString()
                                  //console.log('    sql: ' + JSON.stringify(sqlToUpdate , null, 2))
                                  var cbb = realtimeTablesToWatch[tableName]['sql'][sqlToUpdate]["callback"];
                                  if (cbb) {
                                      console.log('**HAS A CALLBACK on SQL: ' + sqlToUpdate);
                                      //console.log('localgun: ' + localgun.sql(sqlToUpdate));
                                      localgun.sql(sqlToUpdate, null, cbb);
                                  };

                                  realtimeTablesToWatch[ tableName ][ "changed" ] = false
                              }
                          }
                      }
                      inRealtimeUpdate = false;
                  }
              }

          }

      }, 200)

}(typeof exports === 'undefined' ? this.share = {} : exports));
<commit_msg>Set all realtimes table as default to changed<commit_after>// ***********************************************************
// ***********************************************************
// This is the code to add SQL Support to GunDB
// ***********************************************************
// ***********************************************************
var localgun;
var localgunclass;
var sqlParseFn;
var staticSqlResultSets   = new Object();
var realtimeSqlResultSets = new Object();
var realtimeTablesToWatch = new Object();
var sqlQueue              = [];
var autoSerialId = null;

(function(exports){

    function objectToArray( data ) {
        var list2 = [];
        for (var itemkey in Object.keys( data )) {
            var obj = data[ itemkey ];
            //console.log(itemkey);
          if(data[itemkey] != undefined) {
            list2.push( obj );
            }
        };
        return list2;
    }

    // ---------------------------------------------
    //                  in_where
    //
    // This defines the where claus for the SQL
    // ---------------------------------------------
    function in_where( o, where ) {
        if ( !where ) {
            return true;
        }
        switch( where.operator ) {
            case '='  : return o[where.left.column] == where.right.value; break;
            case '!=' : return o[where.left.column] != where.right.value; break;
            case 'IS' : return o[where.left.column] == where.right.value; break;
            case '>'  : return o[where.left.column] > where.right.value; break;
            case '<'  : return o[where.left.column] < where.right.value;break;
            case '&'  : // fall through
            case 'AND': return in_where(o, where.left) && in_where(o, where.right); break;
            case '||' : // fall through
            case 'OR' : return in_where(o, where.left) || in_where(o, where.right);break;
            default: return false;
        }
    };

    // ---------------------------------------------
    //                  g_insert
    //
    // This creates a new record
    // ---------------------------------------------
    function g_insert( newAst, params, gun, schema ){
        var newRecord = {};
        var columns    = newAst.columns;
        //console.log('columns: ' + JSON.stringify(fields , null, 2))
        var fieldsDefined    = newAst.values[0].value;
        var fields           = new Object();
        var paramsDefined    = newAst.params;

        //console.log('paramsDefined: ' + JSON.stringify(paramsDefined , null, 2))
        for(i = 0; i < paramsDefined.length; i ++) {
            fields[ paramsDefined[ i ].pos ] = { value: params[i] };
        };
        //console.log('fields: ' + JSON.stringify(fields , null, 2))

        fieldsDefinedIndex = 0;
        for( i = 0; i < columns.length; i ++ ) {
            if (!fields[i]) {
                fields[i] = fieldsDefined[fieldsDefinedIndex]
                fieldsDefinedIndex ++
            }
        };

        for(i = 0; i < columns.length; i ++) {
            newRecord[columns[i]] = fields[i].value;
        };

        // this line is only here as often an insert without
        // a select first is very buggy and doesn't see the whole
        // existing result set
        localgun.sql('select * from ' + newAst.table)

        gun.get(schema).get(newAst.table).set(newRecord, function(ack){
            inSql = false
            gun.get('change_log').get( schema ).get( newAst.table ).put(
                {changed: true})
        });
    }

    // ---------------------------------------------
    //                  g_select
    //
    // This uses SQL to get records
    // ---------------------------------------------
    function g_select( sql, params, newAst, gun, cb, schema ) {
        staticSqlResultSets[sql] = [];
        var i = 0
        var count = 0;
        //console.log('*cb: '  + cb)

        var each = function (a){
            var b = localgunclass.obj.copy(a);
            if(in_where( b, newAst.where )) {
                count ++;
                delete b['_'];
         	    //console.log('select from each',a);
                staticSqlResultSets[sql].push(b)
            };
        }

        var end = function (coll){
            //console.log('coll: '  + JSON.stringify(coll , null, 2))
            //staticSqlResultSets[sql] = objectToArray(temp);
            //console.log('**Get: '  + JSON.stringify(staticSqlResultSets[sql] , null, 2))
            //console.log('**cb: '  + cb)
            if (cb) {
                cb( staticSqlResultSets[sql] );
            } else {
                console.log( JSON.stringify(staticSqlResultSets[sql] , null, 2) );
            };
            //console.log('**Finished Get: '  + count)
            inSql = false

        }

        gun.get(schema).get(newAst.from[0].table).valMapEnd( each , end , newAst);
        gun.get(schema).get(newAst.from[0].table).not( end );

      return true;//staticSqlResultSets[sql];
   };

    // ---------------------------------------------
    //                  g_update
    //
    // This uses SQL to update records
    // ---------------------------------------------
    function g_update( newAst2, params, gun, schema ){
        //console.log('Update table name: ' + newAst.table);
        //console.log('Update schema name: ' + schema);
        var newAst = JSON.parse(JSON.stringify( newAst2 ));
        console.log('******* newAst.where: ' + JSON.stringify(newAst.where.right.value , null, 2));

         var processRecord  = function ( record2 , newId ) {
             var record = localgunclass.obj.copy(record2);

            //console.log("      processRecord: " + JSON.stringify(newAst.where.right.value , null, 2));

            //if (record.name == "TestDriver") {
                //console.log("update record: " + JSON.stringify(record.name , null, 2));
                //console.log('newAst.where: ' + JSON.stringify(newAst.where , null, 2));
            //}

            if ( in_where( record , newAst.where ) ) {
                //console.log("    match")

                var paramIndex = 0;
                for ( var column of newAst.set ) {
                    if ( column.value.type == 'param' ) {
                        record[ column.column ] = params[ paramIndex ];
                        paramIndex ++;
                    } else {
                        record[ column.column ] = column.value.value;
                        //console.log( '----------------' + column.column + ' = ' + column.value.value);
                    }
                }
                //console.log("ID: " + newId);
                gun.get(schema).get(newAst.table).get(newId).put(
                    record,
                    function(ack) {
                        //console.log('Updated: ' + newAst.where.right.value)
                    });
            } else {
                //console.log("    no match")
            }
        }

        var end = function(coll){
            //console.log('Finished Update: ' + newAst.where.right.value)
            inSql = false
            gun.get('change_log').get( schema ).get( newAst.table ).put(
                {changed: true})
        }

        gun.get(schema).get(newAst.table).valMapEnd( processRecord , end , newAst);
    };

    // ---------------------------------------------
    //                  setGunDB
    //
    // This sets the instance of GunDB
    // ---------------------------------------------
    exports.setGunDB  = function(lg) {
        localgun = lg;
    };

    // ---------------------------------------------
    //                  setGunDBClass
    //
    // This sets the Class GunDB
    // ---------------------------------------------
    exports.setGunDBClass  = function( lg ) {
        localgunclass = lg;

        localgunclass.chain.sql = function( sql, params, cb, schema ){
            sqlQueue.push({sql: sql, params: params, cb: cb, schema: schema})

        }

        localgunclass.chain.valMapEnd = function ( incb , inend , ast2 ) {
            var n       = function () {};
            var count   = 0;
            var souls   = [];
            var gun     = this;
            var cb      = incb || n;
            var end     = inend || n;
            var ast     = JSON.parse(JSON.stringify(ast2));

            gun.val( function ( list ) {
                var args = Array.prototype.slice.call( arguments );
                localgunclass.node.is( list , function ( n , soul ) {
                    count += 1;
                    souls.push( soul );
                });

                souls.forEach(
                    function ( soul ) {
                        gun.back( -1 ).get( soul ).val( function ( val , key ) {
                            count -= 1;
                            var args2 = Array.prototype.slice.call( arguments );
                            args2.push( ast )
                            cb.apply( this , args2 );
                            if ( !count ) {
                                end.apply( this , args2 );
                            }
                        });
                });
            });
            return gun;
        };
    };

    exports.sql = function( sql, p2, p3, p4 ){
        var hasParams = Array.isArray(p2);
        var params
        var cb
        var schema

        if (hasParams) {
            params = p2
            cb     = p3
            schema = p4
        } else {
            params = []
            cb     = p2
            schema = p3
        }
        localgun.sql( sql, params, cb, schema );
    }

    exports.sql1 = function(sql, p2, p3, p4 ){
        var hasParams = Array.isArray(p2);
        var params
        var cb
        var schema

        if (hasParams) {
            params = p2
            cb     = p3
            schema = p4
        } else {
            params = []
            cb     = p2
            schema = p3
        }

        //console.log('called sql1')
        //console.log('    sql: ' + sql)
        //console.log('    sql: ' + params)
        //console.log('    sql: ' + cb)

        return localgun.sql(
          sql
          ,
          params
          ,
          function(valsReturned) {
            if (!valsReturned) {
                if (cb) {
                    cb(null)
                  }
            } else if (valsReturned.length == 0) {
                if (cb) {
                    cb(null)
                  }
            } else {
              if (cb) {
                cb(valsReturned[0])
                }
                else {
                    console.log(valsReturned[0])
                }
            }
          }
          ,
           schema);
    }

    exports.start = function() {
        sql1("select * from systemsettings where name='autoindex'",
                    function(valret) {
                        console.log('valret: ' + valret)
                       if (valret) {
                           autoSerialId = valret.value;
                       } else {
                           sql('insert into systemsettings (name, value ) values (?,?)',['autoindex', 1])
                       }
                    })
    //autoSerialId
    }

    exports.autoIndexSerialId = function() {
        if (!autoSerialId) {
            autoSerialId = 1;
        } else {
            autoSerialId ++;
        }
        sql("update systemsettings set value = " +
        autoSerialId
        + " where name = 'autoindex'")
        return autoSerialId;
    }

    // ---------------------------------------------
    //                  setSqlParseFn
    //
    // This sets the parse function to use
    // ---------------------------------------------
    exports.setSqlParseFn = function(lg) {
        sqlParseFn = lg;
    };

    exports.realtimeSql = function(sql3, callbackFn, schema) {
        try {
            if (!schema) {
                schema = 'default'
            }
            newAst = sqlParseFn(sql3);
            //console.log('RTable: ' + newAst.from[0].table);
            if (newAst.type == 'select') {
                console.log("select RR********* SQL: " + sql3 + ", table: " + newAst.from[0].table)
                if (!realtimeTablesToWatch[newAst.from[0].table]) {
                    realtimeTablesToWatch[newAst.from[0].table] = new Object();
                    realtimeTablesToWatch[newAst.from[0].table]['sql'] = new Object();
                    var tableName = newAst.from[0].table;

                    realtimeTablesToWatch[tableName]["changed"] = true
                    localgun.get('change_log').get( schema ).get( newAst.from[0].table ).on(
                      function(a) {
                          //a.value(function(q){console.log('a: ' + JSON.stringify(q , null, 2) )})
                          if (a.changed) {
                              console.log('Change to table name: ' + tableName )
                              //console.log('     a: ' + JSON.stringify(a , null, 2) )
                              realtimeTablesToWatch[tableName]["changed"] = true
                              localgun.get('change_log').get( schema ).get( newAst.from[0].table ).put(
                                  {changed: false})
                          }
                        },false);

                }
                if (!realtimeTablesToWatch[newAst.from[0].table][sql3]) {
                    realtimeTablesToWatch[newAst.from[0].table]['sql'][sql3] = new Object();
                    realtimeTablesToWatch[newAst.from[0].table]['sql'][sql3]["callback"] = callbackFn;
                    realtimeTablesToWatch[newAst.from[0].table]['sql'][sql3]["schema"] = schema;
                }

                 //localgun.sql(sql3);
              //console.log('(REAL:sql): ' + sql3)
              //console.log('(REAL:realtimeTablesToWatch): ' + JSON.stringify(realtimeTablesToWatch , null, 2))
            }
        }
        catch(err) {
            console.log(err);
            return false;
        }
        return true;
      };

      var inRealtimeUpdate=false;
      var inSql=false;

      var queueCount = 0;
      setInterval( function () {

          if (!inSql) {
              var sqlQueueItem = sqlQueue.shift()
              if (sqlQueueItem) {
                  inSql = true
                  console.log('sql: ' + JSON.stringify(sqlQueueItem.sql , null, 2))
                  queueCount ++;
                  var sql    = sqlQueueItem.sql
                  var params = sqlQueueItem.params
                  var schema = sqlQueueItem.schema
                  var cb     = sqlQueueItem.cb

                  var newAst = JSON.parse(JSON.stringify( sqlParseFn(sql) ));
                  //console.log(queueCount + ' : ' + sql)
                  //console.log('newAst: ' + JSON.stringify(newAst , null, 2))
                  if (!schema) {
                      schema = 'default'
                  }

                  var chain  = localgun.chain();
                  switch( newAst.type ) {
                      case 'insert' : g_insert(newAst, params,         localgun,     schema);break;
                      case 'select' : g_select(sql,    params, newAst, localgun, cb, schema);break;
                      case 'update' : g_update(newAst, params,         localgun,     schema);break;
                  }
                  //return this
              }

              if (sqlQueue.length == 0) {
                  if (!inRealtimeUpdate) {
                      inRealtimeUpdate = true;
                      //console.log('Changed: ' + changed);
                      var allRealtimetables = Object.keys(realtimeTablesToWatch);
                      //console.log('tables: ' + JSON.stringify(allRealtimetables , null, 2))
                      for ( tableName of allRealtimetables) {
                          //console.log("tableName: " + tableName );
                          if (realtimeTablesToWatch[ tableName ] ) {
                              if (realtimeTablesToWatch[ tableName ][ "changed" ]) {
                                  //console.log("table changed: " + tableName );
                                  //localgun.sql("SELECT * FROM Customers ");
                                  var sqlToUpdate = Object.keys(realtimeTablesToWatch[ tableName ]['sql']).toString()
                                  //console.log('    sql: ' + JSON.stringify(sqlToUpdate , null, 2))
                                  var cbb = realtimeTablesToWatch[tableName]['sql'][sqlToUpdate]["callback"];
                                  if (cbb) {
                                      console.log('**HAS A CALLBACK on SQL: ' + sqlToUpdate);
                                      //console.log('localgun: ' + localgun.sql(sqlToUpdate));
                                      localgun.sql(sqlToUpdate, null, cbb);
                                  };

                                  realtimeTablesToWatch[ tableName ][ "changed" ] = false
                              }
                          }
                      }
                      inRealtimeUpdate = false;
                  }
              }

          }

      }, 200)

}(typeof exports === 'undefined' ? this.share = {} : exports));
<|endoftext|>


<commit_before>$(document).ready(function() {
    executeOnLoadTasks();
});

function executeOnLoadTasks() {

    $('.get-cards-button').click(function() {

        var $cardsContent = $('.cards-content');
        $('.admin-loading').removeClass('hide');
        $cardsContent.empty();
        $cardsContent.addClass('hide');
        $('.total-cards-content').addClass('hide');

        var username = $('.username-entry').val();
        if (username && username !== '') {
            getCards(username);
            showCards($cardsContent);
        }
    });

}

function showCards($cardsContent) {
    deferred.done(function (cardsArray) {
        buildCardDetail(cardsArray, $cardsContent);
        $cardsContent.removeClass('hide');
        $('.total-cards-content').removeClass('hide');
        $('.admin-loading').addClass('hide');
    });
}

function buildCardDetail(cardsArray, $cardsContent) {
    var lastDate = '';
    var $activeDateSection;
    var cardsPerDate;
    var datesCount = 0;

    for (var i = 0; i < cardsArray.length; i++) {
        var cardData = cardsArray[i];
        if (cardData.type === 'date') {
            if ($activeDateSection !== undefined) {
                $activeDateSection.find('.card-qty').text('Cards: ' + cardsPerDate);
            }
            datesCount++;
            cardsPerDate = 0;
            $activeDateSection = addDateSection(cardData, $cardsContent);
        } else {
            cardsPerDate++;
            addCardDetail(cardData, $activeDateSection);
        }
    }

    if ($activeDateSection !== undefined) {
        $activeDateSection.find('.card-count').text('Cards: ' + cardsPerDate);
    }

    $('.total-days').text(datesCount + ' days');
    $('.total-cards').text(cardsArray.length + ' cards');
}

function addDateSection(cardData, $cardsContent) {
    var $dateSection = $('.cards-section.template').clone();
    $dateSection.removeClass('template');
    $dateSection.find('.date-text').text(cardData.cardDate);
    $cardsContent.append($dateSection);
    return $dateSection;
}

function addCardDetail(cardData, $dateSection) {
    var $cardRow = $('.card-row.template').clone();
    var $separator = $('.card-separator.template').clone();
    $cardRow.removeClass('template');
    $separator.removeClass('template');

    createCardText(cardData);

    $cardRow.find('.card-text').html(cardData.cardText.description);
    $cardRow.find('.card-comparitor').html(cardData.cardText.comparitor);
    $cardRow.find('.service').addClass(getDataSource(cardData));

    $cardsDiv = $dateSection.find('.cards-for-date');
    $cardsDiv.append($cardRow);
    $cardsDiv.append($separator);
}<commit_msg>fix problem with not showing service icon<commit_after>$(document).ready(function() {
    executeOnLoadTasks();
});

function executeOnLoadTasks() {

    $('.get-cards-button').click(function() {

        var $cardsContent = $('.cards-content');
        $('.admin-loading').removeClass('hide');
        $cardsContent.empty();
        $cardsContent.addClass('hide');
        $('.total-cards-content').addClass('hide');

        var username = $('.username-entry').val();
        if (username && username !== '') {
            getCards(username);
            showCards($cardsContent);
        }
    });

}

function showCards($cardsContent) {
    deferred.done(function (cardsArray) {
        buildCardDetail(cardsArray, $cardsContent);
        $cardsContent.removeClass('hide');
        $('.total-cards-content').removeClass('hide');
        $('.admin-loading').addClass('hide');
    });
}

function buildCardDetail(cardsArray, $cardsContent) {
    var lastDate = '';
    var $activeDateSection;
    var cardsPerDate;
    var datesCount = 0;

    for (var i = 0; i < cardsArray.length; i++) {
        var cardData = cardsArray[i];
        if (cardData.type === 'date') {
            if ($activeDateSection !== undefined) {
                $activeDateSection.find('.card-qty').text('Cards: ' + cardsPerDate);
            }
            datesCount++;
            cardsPerDate = 0;
            $activeDateSection = addDateSection(cardData, $cardsContent);
        } else {
            cardsPerDate++;
            addCardDetail(cardData, $activeDateSection);
        }
    }

    if ($activeDateSection !== undefined) {
        $activeDateSection.find('.card-count').text('Cards: ' + cardsPerDate);
    }

    $('.total-days').text(datesCount + ' days');
    $('.total-cards').text(cardsArray.length + ' cards');
}

function addDateSection(cardData, $cardsContent) {
    var $dateSection = $('.cards-section.template').clone();
    $dateSection.removeClass('template');
    $dateSection.find('.date-text').text(cardData.cardDate);
    $cardsContent.append($dateSection);
    return $dateSection;
}

function addCardDetail(cardData, $dateSection) {
    var $cardRow = $('.card-row.template').clone();
    var $separator = $('.card-separator.template').clone();
    $cardRow.removeClass('template');
    $separator.removeClass('template');
    $cardRow.find('.service').addClass(getDataSource(cardData));

    createCardText(cardData);

    $cardRow.find('.card-text').html(cardData.cardText.description);
    $cardRow.find('.card-comparitor').html(cardData.cardText.comparitor);

    $cardsDiv = $dateSection.find('.cards-for-date');
    $cardsDiv.append($cardRow);
    $cardsDiv.append($separator);
}<|endoftext|>