<commit_before>

  // gracefully handle mailto between chrome/outlook type systems/no mail client
  // (i.e. - don't leave the page on blank tab)
  var mailTo = function(url) {
    // I have often experienced Firefox errors with protocol handlers
    // so better be on the safe side.
    try {
      var mailer = window.open(url, 'Mailer');
    } catch(e) {
      console.warn('There was an error opening a mail composer.', e);
    }

    setTimeout(function() {
      // This needs to be in a try/catch block because a Security
      // error is thrown if the protocols doesn't match
      try {
        // At least in Firefox the location is changed to about:blank
        if(mailer.location.href === url || mailer.location.href.substr(0, 6) === 'about:') {
          mailer.close();
        }
      } catch(e) {
        console.warn('There was an error opening a mail composer.', e);
      }
    }, 500);
  }

  function listenToClick(element, name, fn) {
    if (document.addEventListener) {
      element.addEventListener(name, fn, false);
    } else {
      element.attachEvent((name === 'click') ? 'onclick' : name, fn);
    }
  }

  function handleClicks(elem, fn) {
    if (!elem) return;

    if (document.addEventListener) {
      // For all major browsers, except IE 8 and earlier
      elem.addEventListener("click", fn, false);
      elem.addEventListener("touchstart", fn, false);
    } else if (document.attachEvent) {
      // For IE 8 and earlier versions
      elem.attachEvent("onclick", fn, false);
      elem.attachEvent("touchstart", fn, false);
    }
  }

  function hasClass(el, className) {
    if (el.classList)
      return el.classList.contains(className)
    else
      return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
  }

  function my_addClass(el, className) {
    if (el.classList)
      el.classList.add(className)
    else if (!hasClass(el, className)) el.className += " " + className
  }

  function my_removeClass(el, className) {
    if (el.classList)
      el.classList.remove(className)
    else if (hasClass(el, className)) {
      var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
      el.className=el.className.replace(reg, ' ')
    }
  }

  function scrollTop(element, to, duration) {
    var start = element.scrollTop,
        change = to - start,
        currentTime = 0,
        increment = 20;

    var animateScroll = function(){
      currentTime += increment;
      var val = Math.easeInOutQuad(currentTime, start, change, duration);
      element.scrollTop = val;
      if(currentTime < duration) {
        setTimeout(animateScroll, increment);
      }
    };
    animateScroll();
  }

  //t = current time
  //b = start value
  //c = change in value
  //d = duration
  Math.easeInOutQuad = function (t, b, c, d) {
    t /= d/2;
    if (t < 1) return c/2*t*t + b;
    t--;
    return -c/2 * (t*(t-2) - 1) + b;
  }

  function each(o, cb, s){
    var n;
    if (!o){
      return 0;
    }
    s = !s ? o : s;
    if (o instanceof Array){
      // Indexed arrays, needed for Safari
      for (n=0; n<o.length; n++) {
        if (cb.call(s, o[n], n, o) === false){
          return 0;
        }
      }
    } else {
      // Hashtables
      for (n in o){
        if (o.hasOwnProperty(n)) {
          if (cb.call(s, o[n], n, o) === false){
            return 0;
          }
        }
      }
    }
    return 1;
  }

  var isValidEmail = function(email) {
    return /^.+@.+\..+$/.test(email);
  }
<commit_msg>EM - morp sync<commit_after>

  // gracefully handle mailto between chrome/outlook type systems/no mail client
  // (i.e. - don't leave the page on blank tab)
  var mailTo = function(url) {
    // I have often experienced Firefox errors with protocol handlers
    // so better be on the safe side.
    try {
      var mailer = window.open(url, 'Mailer');
    } catch(e) {
      console.warn('There was an error opening a mail composer.', e);
    }

    setTimeout(function() {
      // This needs to be in a try/catch block because a Security
      // error is thrown if the protocols doesn't match
      try {
        // At least in Firefox the location is changed to about:blank
        if(mailer.location.href === url || mailer.location.href.substr(0, 6) === 'about:') {
          mailer.close();
        }
      } catch(e) {
        console.warn('There was an error opening a mail composer.', e);
      }
    }, 500);
  }

  function listenToClick(element, name, fn) {
    if (document.addEventListener) {
      element.addEventListener(name, fn, false);
    } else {
      element.attachEvent((name === 'click') ? 'onclick' : name, fn);
    }
  }

  function handleClicks(elem, fn) {
    if (!elem) return;

    if (document.addEventListener) {
      // For all major browsers, except IE 8 and earlier
      elem.addEventListener("click", fn, false);
      elem.addEventListener("touchstart", fn, false);
    } else if (document.attachEvent) {
      // For IE 8 and earlier versions
      elem.attachEvent("onclick", fn, false);
      elem.attachEvent("touchstart", fn, false);
    }
  }

  function hasClass(el, className) {
    if (el.classList)
      return el.classList.contains(className)
    else
      return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
  }

  function my_addClass(el, className) {
    if (el.classList)
      el.classList.add(className)
    else if (!hasClass(el, className)) el.className += " " + className
  }

  function my_removeClass(el, className) {
    if (el.classList)
      el.classList.remove(className)
    else if (hasClass(el, className)) {
      var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
      el.className=el.className.replace(reg, ' ')
    }
  }

  function scrollTop(element, to, duration) {
    var start = element.scrollTop,
        change = to - start,
        currentTime = 0,
        increment = 20;

    var animateScroll = function(){
      currentTime += increment;
      var val = Math.easeInOutQuad(currentTime, start, change, duration);
      element.scrollTop = val;
      if(currentTime < duration) {
        setTimeout(animateScroll, increment);
      }
    };
    animateScroll();
  }

  //t = current time
  //b = start value
  //c = change in value
  //d = duration
  Math.easeInOutQuad = function (t, b, c, d) {
    t /= d/2;
    if (t < 1) return c/2*t*t + b;
    t--;
    return -c/2 * (t*(t-2) - 1) + b;
  }

  function each(o, cb, s){
    var n;
    if (!o){
      return 0;
    }
    s = !s ? o : s;
    if (o instanceof Array){
      // Indexed arrays, needed for Safari
      for (n=0; n<o.length; n++) {
        if (cb.call(s, o[n], n, o) === false){
          return 0;
        }
      }
    } else {
      // Hashtables
      for (n in o){
        if (o.hasOwnProperty(n)) {
          if (cb.call(s, o[n], n, o) === false){
            return 0;
          }
        }
      }
    }
    return 1;
  }

  var isValidEmail = function(email) {
    return /^.+@.+\..+$/.test(email);
  }

  var isDOMElement = function(element) {
    return (element && element.nodeType === 1);
  }
<|endoftext|>


<commit_before><commit_msg>Makes the autocomplete UI start as hidden by default<commit_after><|endoftext|>


<commit_before>var helper = require("../../helper");
// var Manager = require("../../../src/etl/fact-purchasing-etl-manager");
var Manager = require("../../../src/etl/fact-pembelian");
var instanceManager = null;
var should = require("should");
var sqlHelper = require("../../sql-helper");

before("#00. connect db", function (done) {
    Promise.all([helper, sqlHelper])
        .then((result) => {
            var db = result[0];
            var sql = result[1];
            db.getDb().then((db) => {
                instanceManager = new Manager(db, {
                    username: "unit-test"
                }, sql);
                done();
            })
                .catch((e) => {
                    done(e);
                })
        });
});

// it("#01. should success when create etl fact-purchasing", function (done) {
//     instanceManager.run()
//         .then((a) => {
//             console.log(a);
//             done();
//         })
//         .catch((e) => {
//             console.log(e);
//             done(e);
//         });
// });

it("#02. should success when transforming data", function (done) {
    var data = [
        {
            purchaseOrder: {
                _createdDate: new Date(),
                purchaseOrderExternal: {
                    date: new Date(1970, 1, 1)
                },
                items: [
                    {
                        fulfillments: [
                            {
                                deliveryOrderDate: new Date()
                            }
                            ]
                    }
                ]
            },
            purchaseRequest: {
                category: {
                    name: ""
                },
                date: new Date(1970, 1, 1)
            }
        }
    ];
    instanceManager.transform(data)
        .then(() => {
            done();
        })
        .catch((e) => {
            done(e);
        });
});

// it("#03. should success when extracting PR from PO", function (done) {
//     var data = [];
//     instanceManager.getPRFromPO(data)
//         .then(() => {
//             done();
//         })
//         .catch((e) => {
//             done(e);
//         });
// });

// it("#04. should success when joining PR to PO", function (done) {
//     var data = [];
//     instanceManager.joinPurchaseOrder(data)
//         .then(() => {
//             done();
//         })
//         .catch((e) => {
//             done(e);
//         });
// });

// it("#05. should success when remove duplicate data", function (done) {
//     var arr = [{ no: {} }, { no: {} }];
//     instanceManager.removeDuplicates(arr)
//         .then((a) => {
//             done();
//         })
//         .catch((e) => {
//             done(e);
//         });
// });

// it("#06. should error when load empty data", function (done) {
//     instanceManager.load({})
//         .then(id => {
//             done("should error when create with empty data");
//         })
//         .catch((e) => {
//             try {
//                 done();
//             }
//             catch (ex) {
//                 done(ex);
//             }
//         });
// });

// it("#07. should error when insert empty data", function (done) {
//     instanceManager.insertQuery(this.sql, "")
//         .then((id) => {
//             done("should error when create with empty data");
//         })
//         .catch((e) => {
//             try {
//                 done();
//             }
//             catch (ex) {
//                 done(ex);
//             }
//         });
// });
<commit_msg>update etl<commit_after>var helper = require("../../helper");
// var Manager = require("../../../src/etl/fact-purchasing-etl-manager");
var Manager = require("../../../src/etl/fact-pembelian");
var instanceManager = null;
var should = require("should");
var sqlHelper = require("../../sql-helper");

before("#00. connect db", function (done) {
    Promise.all([helper, sqlHelper])
        .then((result) => {
            var db = result[0];
            var sql = result[1];
            db.getDb().then((db) => {
                instanceManager = new Manager(db, {
                    username: "unit-test"
                }, sql);
                done();
            })
                .catch((e) => {
                    done(e);
                })
        });
});

it("#01. should success when create etl fact-purchasing", function (done) {
    instanceManager.run()
        .then((a) => {
            console.log(a);
            done();
        })
        .catch((e) => {
            console.log(e);
            done(e);
        });
});

it("#02. should success when transforming data", function (done) {
    var data = [
        {
            purchaseOrder: {
                _createdDate: new Date(),
                purchaseOrderExternal: {
                    date: new Date(1970, 1, 1)
                },
                items: [
                    {
                        fulfillments: [
                            {
                                deliveryOrderDate: new Date()
                            }
                            ]
                    }
                ]
            },
            purchaseRequest: {
                category: {
                    name: ""
                },
                date: new Date(1970, 1, 1)
            }
        }
    ];
    instanceManager.transform(data)
        .then(() => {
            done();
        })
        .catch((e) => {
            done(e);
        });
});

it("#03. should success when extracting PR from PO", function (done) {
    var data = [];
    instanceManager.getPRFromPO(data)
        .then(() => {
            done();
        })
        .catch((e) => {
            done(e);
        });
});

it("#04. should success when joining PR to PO", function (done) {
    var data = [];
    instanceManager.joinPurchaseOrder(data)
        .then(() => {
            done();
        })
        .catch((e) => {
            done(e);
        });
});

it("#05. should success when remove duplicate data", function (done) {
    var arr = [{ no: {} }, { no: {} }];
    instanceManager.removeDuplicates(arr)
        .then((a) => {
            done();
        })
        .catch((e) => {
            done(e);
        });
});

it("#06. should error when load empty data", function (done) {
    instanceManager.load({})
        .then(id => {
            done("should error when create with empty data");
        })
        .catch((e) => {
            try {
                done();
            }
            catch (ex) {
                done(ex);
            }
        });
});

it("#07. should error when insert empty data", function (done) {
    instanceManager.insertQuery(this.sql, "")
        .then((id) => {
            done("should error when create with empty data");
        })
        .catch((e) => {
            try {
                done();
            }
            catch (ex) {
                done(ex);
            }
        });
});
<|endoftext|>


<commit_before>'use strict';

/* this is the spaghetti'est thing I've ever seen. I'm not touching this. */
/* eslint-disable promise/always-return */

define(['angular'], function(angular) {
  return angular.module('portal.features.services', [])
  .factory('portalFeaturesService', [
    '$http',
    '$q',
    'miscService',
    'keyValueService',
    'PortalGroupService',
    '$log',
    '$localStorage',
    '$sessionStorage',
    'filterFilter',
    'KV_KEYS',
    'FEATURES',
    function(
      $http,
      $q,
      miscService,
      keyValueService,
      PortalGroupService,
      $log,
      $localStorage,
      $sessionStorage,
      filterFilter,
      KV_KEYS,
      FEATURES
    ) {
    var featuresPromise;
    var filteredFeaturesPromise;
    var getFeatures = function() {
      if(!featuresPromise) {
        featuresPromise = $http.get(FEATURES.serviceURL, {cache: true})
           .then(function(results, status) { // success function
              return results.data;
           }, function(data, status) { // failure function
              miscService.redirectUser(status, 'Get features info');
           });
      }
      if (FEATURES.groupFiltering &&
        PortalGroupService.groupsServiceEnabled &&
        !$localStorage.disableGroupAnnouncementFiltering) {
        if (filteredFeaturesPromise) {
          // cache shortcut
          return filteredFeaturesPromise;
        }
        var successFn = function(results) {
          var array = results[0];
          var groups = results[1];
          return PortalGroupService.filterArrayByGroups(
            array, groups, 'groups');
        };
        var errorFn = function(reason) {
          miscService.redirectUser(reason.status, 'q for filtered features');
        };

        filteredFeaturesPromise = $q
          .all([featuresPromise,
            PortalGroupService.getGroups(),
          ])
          .then(successFn, errorFn);

        return filteredFeaturesPromise;
      } else {
        return featuresPromise;
      }
    };// end get features

    /**
     * If keyValueService is Active and there exists legacy announcement storage
     * this will convert that to the new store all seen announcement ids rather
     * than just the latest.  Will then delete the legacy announcement storage
     */
    var updateLegacySeenAnnouncements = function() {
      if (!keyValueService.isKVStoreActivated()) {
        return $q.resolve(null);
      }

      return keyValueService
        .getValue('lastviewedannouncementid')
        .then(function(data) {
          if (!data || !data.id) {
            throw Error('no legacy seenAnnouncements');
          }
          // create an array with the seen ids
          var seenAnnouncements = [];
          for (var i = 0; i <= data.id; i++) {
            seenAnnouncements.push(i);
          }
          $sessionStorage.seenAnnouncementIds = seenAnnouncements;
          return keyValueService.setValue(
            KV_KEYS.VIEWED_ANNOUNCEMENT_IDS,
            $sessionStorage.seenAnnouncementIds
          );
        })
        .then(function(data) {
          return keyValueService.deleteValue('lastviewedannouncementid');
        });
    };

    /*
     * If keyValueService is Active and there exists legacy popup storage
     * this will convert that to the new store all seen popup ids rather
     * than just the latest.  Will then delete the legacy popup storage
     */
    var updateLegacyPopups = function() {
      if (!keyValueService.isKVStoreActivated()) {
        return $q.resolve(null);
      }

      return keyValueService
        .getValue('lastviewedpopupid')
        .then(function(data) {
          if (!data || !data.id) {
            throw Error('no legacy popups');
          }
          // create an array with the seen ids
          var seenPopups = [];
          for (var i = 0; i <= data.id; i++) {
            seenPopups.push(i);
          }
          $sessionStorage.seenPopupIds = seenPopups;
          return keyValueService.setValue(
            KV_KEYS.VIEWED_POPUP_IDS, $sessionStorage.seenPopupIds);
      })
      .then(function(data) {
        return keyValueService.deleteValue('lastviewedpopupid');
      });
    };

    var getSeenAnnouncements = function() {
      if (sessionStorage.seenAnnouncementIds) {
        return $q.resolve($sessionStorage.seenAnnouncementIds);
      }

      return updateLegacySeenAnnouncements()
        .then(function() {
          return keyValueService.getValue(KV_KEYS.VIEWED_ANNOUNCEMENT_IDS);
        })
        .then(function(data) {
          if (angular.isArray(data)) {
            $sessionStorage.seenAnnouncementIds = data;
          } else {
            $sessionStorage.seenAnnouncementIds = [];
          }

          return $sessionStorage.seenAnnouncementIds;
        });
    };

    var getSeenPopups = function() {
      if (sessionStorage.seenPopupIds) {
        return $q.resolve($sessionStorage.seenPopupIds);
      }

      return updateLegacyPopups()
        .then(function() {
            return keyValueService.getValue(KV_KEYS.VIEWED_POPUP_IDS);
        })
        .then(function(data) {
          if (angular.isArray(data)) {
            $sessionStorage.seenPopupIds = data;
          } else {
            $sessionStorage.seenPopupIds = [];
          }

          return $sessionStorage.seenPopupIds;
        });
    };

    var markAnnouncementSeen = function(announcementID) {
      if ($sessionStorage.seenAnnouncementIds) {
        $sessionStorage.seenAnnouncementIds.push(announcementID);
      } else {
        $sessionStorage.seenAnnouncementIds = [announcementID];
      }

      if (!keyValueService.isKVStoreActivated()) {
        return $q.resolve($sessionStorage.seenAnnouncementIds);
      }

      return keyValueService
        .setValue(
          KV_KEYS.VIEWED_ANNOUNCEMENT_IDS,
          $sessionStorage.seenAnnouncementIds)
        .then(function(data) {
          return $sessionStorage.seenAnnouncementIds;
        });
    };

    var markPopupSeen = function(popupID) {
      // Store in session storage
      if ($sessionStorage.seenPopupIds) {
        $sessionStorage.seenPopupIds.push(popupID);
      } else {
        $sessionStorage.seenPopupIds = [popupID];
      }

      // Store in keyvalueStorage if able
      if (!keyValueService.isKVStoreActivated()) {
        return $q.resolve($sessionStorage.seenPopupIds);
      }

      return keyValueService
        .setValue(KV_KEYS.VIEWED_POPUP_IDS, $sessionStorage.seenPopupIds)
        .then(function(data) {
          return $sessionStorage.seenPopupIds;
        });
    };

    var getUnseenAnnouncements = function() {
      var successFn = function(data) {
        // features in data[0]  //seenAnnouncements in data[1]
        var announcements = filterFilter(data[0], {isBuckyAnnouncement: true});
        if (announcements && announcements.length != 0) {
         // filter down to ones they haven't seen
          var hasNotSeen = function(feature) {
            if (data[1].indexOf(feature.id) !== -1) {
              return false;
            } else {
              // check dates
              var today = new Date().getTime();
              var startDate = new Date(
                feature.goLiveYear, feature.goLiveMonth, feature.goLiveDay
              ).getTime();
              var expirationDate = feature.buckyAnnouncement.endDate;
              if (angular.isString(expirationDate)) {
                  expirationDate = new Date(expirationDate).getTime();
              }

              return startDate <= today && today <= expirationDate;
            }
          };
          return announcements.filter(hasNotSeen);
        }
      };
      var errorFn = function(reason) {
        $log.error('error retrieving unseenAnnouncements: ' + reason.status);
        return reason;
      };

      return $q.all([getFeatures(), getSeenAnnouncements()])
        .then(successFn).catch(errorFn);
    };

    var getUnseenPopups = function() {
      var successFn = function(data) {
        var popupFeatures = filterFilter(data[0], {isPopup: true});
        if (popupFeatures.length != 0) {
          var today = new Date().getTime();
          var filterExpiredPopups = function(feature) {
            var startDate = new Date(
              feature.popup.startYear,
              feature.popup.startMonth,
              feature.popup.startDay
            ).getTime();
            var endDate = new Date(
              feature.popup.endYear,
              feature.popup.endMonth,
              feature.popup.endDay
            ).getTime();
            return today > startDate && today < endDate;
          };
          var filterUnEnabledPopups = function(feature) {
              return feature.popup.enabled;
          };
          var filterSeenPopups = function(feature) {
            return !(data[1].indexOf(feature.id) !== -1);
          };
          return popupFeatures
            .filter(filterSeenPopups)
            .filter(filterExpiredPopups)
            .filter(filterUnEnabledPopups);
        }
      };
      var errorFn = function(reason) {
        $log.error('error retrieving unseenPopups: ' + reason.status);
        return reason;
      };

      return $q.all([getFeatures(), getSeenPopups()])
        .then(successFn).catch(errorFn);
    };

    return {
      getFeatures: getFeatures,
      getUnseenAnnouncements: getUnseenAnnouncements,
      markAnnouncementSeen: markAnnouncementSeen,
      markPopupSeen: markPopupSeen,
      getUnseenPopups: getUnseenPopups,
    };
  }]);
});
<commit_msg>fixing errors and not returning reasons<commit_after>'use strict';

/* eslint-disable promise/always-return */

define(['angular'], function(angular) {
  return angular.module('portal.features.services', [])
  .factory('portalFeaturesService', [
    '$http',
    '$q',
    'miscService',
    'keyValueService',
    'PortalGroupService',
    '$log',
    '$localStorage',
    '$sessionStorage',
    'filterFilter',
    'KV_KEYS',
    'FEATURES',
    function(
      $http,
      $q,
      miscService,
      keyValueService,
      PortalGroupService,
      $log,
      $localStorage,
      $sessionStorage,
      filterFilter,
      KV_KEYS,
      FEATURES
    ) {
    var featuresPromise;
    var filteredFeaturesPromise;
    var getFeatures = function() {
      if(!featuresPromise) {
        featuresPromise = $http.get(FEATURES.serviceURL, {cache: true})
           .then(function(results, status) { // success function
              return results.data;
           }, function(data, status) { // failure function
              miscService.redirectUser(status, 'Get features info');
           });
      }
      if (FEATURES.groupFiltering &&
        PortalGroupService.groupsServiceEnabled &&
        !$localStorage.disableGroupAnnouncementFiltering) {
        if (filteredFeaturesPromise) {
          // cache shortcut
          return filteredFeaturesPromise;
        }
        var successFn = function(results) {
          var array = results[0];
          var groups = results[1];
          return PortalGroupService.filterArrayByGroups(
            array, groups, 'groups');
        };
        var errorFn = function(reason) {
          miscService.redirectUser(reason.status, 'q for filtered features');
        };

        filteredFeaturesPromise = $q
          .all([featuresPromise,
            PortalGroupService.getGroups(),
          ])
          .then(successFn, errorFn);

        return filteredFeaturesPromise;
      } else {
        return featuresPromise;
      }
    };// end get features

    /**
     * If keyValueService is Active and there exists legacy announcement storage
     * this will convert that to the new store all seen announcement ids rather
     * than just the latest.  Will then delete the legacy announcement storage
     */
    var updateLegacySeenAnnouncements = function() {
      if (!keyValueService.isKVStoreActivated()) {
        return $q.resolve(null);
      }

      return keyValueService
        .getValue('lastviewedannouncementid')
        .then(function(data) {
          if (!data || !data.id) {
            return $q.reject('no legacy seenAnnouncements');
          }
          // create an array with the seen ids
          var seenAnnouncements = [];
          for (var i = 0; i <= data.id; i++) {
            seenAnnouncements.push(i);
          }
          $sessionStorage.seenAnnouncementIds = seenAnnouncements;
          return keyValueService.setValue(
            KV_KEYS.VIEWED_ANNOUNCEMENT_IDS,
            $sessionStorage.seenAnnouncementIds
          );
        })
        .then(function(data) {
          return keyValueService.deleteValue('lastviewedannouncementid');
        });
    };

    /*
     * If keyValueService is Active and there exists legacy popup storage
     * this will convert that to the new store all seen popup ids rather
     * than just the latest.  Will then delete the legacy popup storage
     */
    var updateLegacyPopups = function() {
      if (!keyValueService.isKVStoreActivated()) {
        return $q.resolve(null);
      }

      return keyValueService
        .getValue('lastviewedpopupid')
        .then(function(data) {
          if (!data || !data.id) {
            return $q.reject('no legacy popups');
          }
          // create an array with the seen ids
          var seenPopups = [];
          for (var i = 0; i <= data.id; i++) {
            seenPopups.push(i);
          }
          $sessionStorage.seenPopupIds = seenPopups;
          return keyValueService.setValue(
            KV_KEYS.VIEWED_POPUP_IDS, $sessionStorage.seenPopupIds);
        })
        .then(function(data) {
          return keyValueService.deleteValue('lastviewedpopupid');
        });
    };

    var getSeenAnnouncements = function() {
      if (sessionStorage.seenAnnouncementIds) {
        return $q.resolve($sessionStorage.seenAnnouncementIds);
      }

      return updateLegacySeenAnnouncements()
        .then(function() {
          return keyValueService.getValue(KV_KEYS.VIEWED_ANNOUNCEMENT_IDS);
        })
        .then(function(data) {
          if (angular.isArray(data)) {
            $sessionStorage.seenAnnouncementIds = data;
          } else {
            $sessionStorage.seenAnnouncementIds = [];
          }

          return $sessionStorage.seenAnnouncementIds;
        });
    };

    var getSeenPopups = function() {
      if (sessionStorage.seenPopupIds) {
        return $q.resolve($sessionStorage.seenPopupIds);
      }

      return updateLegacyPopups()
        .then(function() {
            return keyValueService.getValue(KV_KEYS.VIEWED_POPUP_IDS);
        })
        .then(function(data) {
          if (angular.isArray(data)) {
            $sessionStorage.seenPopupIds = data;
          } else {
            $sessionStorage.seenPopupIds = [];
          }

          return $sessionStorage.seenPopupIds;
        });
    };

    var markAnnouncementSeen = function(announcementID) {
      if ($sessionStorage.seenAnnouncementIds) {
        $sessionStorage.seenAnnouncementIds.push(announcementID);
      } else {
        $sessionStorage.seenAnnouncementIds = [announcementID];
      }

      if (!keyValueService.isKVStoreActivated()) {
        return $q.resolve($sessionStorage.seenAnnouncementIds);
      }

      return keyValueService
        .setValue(
          KV_KEYS.VIEWED_ANNOUNCEMENT_IDS,
          $sessionStorage.seenAnnouncementIds)
        .then(function(data) {
          return $sessionStorage.seenAnnouncementIds;
        });
    };

    var markPopupSeen = function(popupID) {
      // Store in session storage
      if ($sessionStorage.seenPopupIds) {
        $sessionStorage.seenPopupIds.push(popupID);
      } else {
        $sessionStorage.seenPopupIds = [popupID];
      }

      // Store in keyvalueStorage if able
      if (!keyValueService.isKVStoreActivated()) {
        return $q.resolve($sessionStorage.seenPopupIds);
      }

      return keyValueService
        .setValue(KV_KEYS.VIEWED_POPUP_IDS, $sessionStorage.seenPopupIds)
        .then(function(data) {
          return $sessionStorage.seenPopupIds;
        });
    };

    var getUnseenAnnouncements = function() {
      var successFn = function(data) {
        // features in data[0]  //seenAnnouncements in data[1]
        var announcements = filterFilter(data[0], {isBuckyAnnouncement: true});
        if (announcements && announcements.length != 0) {
         // filter down to ones they haven't seen
          var hasNotSeen = function(feature) {
            if (data[1].indexOf(feature.id) !== -1) {
              return false;
            } else {
              // check dates
              var today = new Date().getTime();
              var startDate = new Date(
                feature.goLiveYear, feature.goLiveMonth, feature.goLiveDay
              ).getTime();
              var expirationDate = feature.buckyAnnouncement.endDate;
              if (angular.isString(expirationDate)) {
                  expirationDate = new Date(expirationDate).getTime();
              }

              return startDate <= today && today <= expirationDate;
            }
          };
          return announcements.filter(hasNotSeen);
        }
      };
      var errorFn = function(reason) {
        $log.error('error retrieving unseenAnnouncements: ' + reason);
        return [];
      };

      return $q.all([getFeatures(), getSeenAnnouncements()])
        .then(successFn).catch(errorFn);
    };

    var getUnseenPopups = function() {
      var successFn = function(data) {
        var popupFeatures = filterFilter(data[0], {isPopup: true});
        if (popupFeatures.length != 0) {
          var today = new Date().getTime();
          var filterExpiredPopups = function(feature) {
            var startDate = new Date(
              feature.popup.startYear,
              feature.popup.startMonth,
              feature.popup.startDay
            ).getTime();
            var endDate = new Date(
              feature.popup.endYear,
              feature.popup.endMonth,
              feature.popup.endDay
            ).getTime();
            return today > startDate && today < endDate;
          };
          var filterUnEnabledPopups = function(feature) {
              return feature.popup.enabled;
          };
          var filterSeenPopups = function(feature) {
            return !(data[1].indexOf(feature.id) !== -1);
          };
          return popupFeatures
            .filter(filterSeenPopups)
            .filter(filterExpiredPopups)
            .filter(filterUnEnabledPopups);
        }
      };
      var errorFn = function(reason) {
        $log.error('error retrieving unseenPopups: ' + reason);
        return [];
      };

      return $q.all([getFeatures(), getSeenPopups()])
        .then(successFn).catch(errorFn);
    };

    return {
      getFeatures: getFeatures,
      getUnseenAnnouncements: getUnseenAnnouncements,
      markAnnouncementSeen: markAnnouncementSeen,
      markPopupSeen: markPopupSeen,
      getUnseenPopups: getUnseenPopups,
    };
  }]);
});
<|endoftext|>


<commit_before>var v = 1.2;
if ('undefined' === typeof window) {
    importScripts('manifest.js');
}
this.addEventListener('install', function (event) {
    console.log("install event");
    event.waitUntil(
        caches.open(v).then(function (cache) {
            //return cache.addAll([
            //    '/app/view1/view1.html',
            //    '/app/view2/view2.html',
            //    '/app/view1/fallback.html'
            //]);
            return cache.addAll(OFFLINK_CACHE);
        })
    );
});

this.addEventListener('fetch', function (event) {
    console.log("fetch event");
    var response;
    event.respondWith(caches.match(event.request).catch(function () {
        return fetch(event.request);
    }).then(function (r) {
        response = r;
        caches.open(v).then(function (cache) {
            cache.put(event.request, response);
        });
        return response.clone();
    }).catch(function () {
        console.log("fallback!");
        return caches.match('/app/view1/fallback.html');
    }));
});

this.addEventListener('activate', function (event) {
    var cacheWhitelist = [v];
    console.log("activate event");
    console.log(cacheWhitelist);
    event.waitUntil(
        caches.keys().then(function (keyList) {
            return Promise.all(keyList.map(function (key) {
                console.log(typeof key);
                if (cacheWhitelist.indexOf(key) === -1) {
                    console.log(cacheWhitelist.indexOf(key));
                    return caches.delete(key);
                }
            }));
        })
    );
});<commit_msg>Remove old cache<commit_after>var v = "1.2";
if ('undefined' === typeof window) {
    importScripts('manifest.js');
}
this.addEventListener('install', function (event) {
    console.log("install event");
    event.waitUntil(
        caches.open(v).then(function (cache) {
            //return cache.addAll([
            //    '/app/view1/view1.html',
            //    '/app/view2/view2.html',
            //    '/app/view1/fallback.html'
            //]);
            return cache.addAll(OFFLINK_CACHE);
        })
    );
});

this.addEventListener('fetch', function (event) {
    console.log("fetch event");
    var response;
    event.respondWith(caches.match(event.request).catch(function () {
        return fetch(event.request);
    }).then(function (r) {
        response = r;
        caches.open(v).then(function (cache) {
            cache.put(event.request, response);
        });
        return response.clone();
    }).catch(function () {
        console.log("fallback!");
        return caches.match('/app/view1/fallback.html');
    }));
});

this.addEventListener('activate', function (event) {
    var cacheWhitelist = [v];
    console.log("activate event");
    console.log(cacheWhitelist);
    event.waitUntil(
        caches.keys().then(function (keyList) {
            return Promise.all(keyList.map(function (key) {
                console.log(typeof key);
                if (cacheWhitelist.indexOf(key) === -1) {
                    console.log(cacheWhitelist.indexOf(key));
                    return caches.delete(key);
                }
            }));
        })
    );
});<|endoftext|>


<commit_before>define(['js/core/Base'], function(Base) {
    return Base.inherit('srv.core.Authentication', {
        ctor: function(user, authenticationData){
            this.user = user;
            this.data = authenticationData;
            this.callBase();
        }
    });
});<commit_msg>set authenticationData and authenticationToken<commit_after>define(['js/core/Base'], function(Base) {
    return Base.inherit('srv.core.Authentication', {
        ctor: function(authenticationProvider) {
            this.authenticationProvider = authenticationProvider;
        },

        setAuthenticationData: function (data) {
            this.data = data;
        },

        setToken: function (token) {
            this.token = token;
        },

        isAuthenticationByToken: function() {
            return !!this.token;
        }

    });
});<|endoftext|>


<commit_before>var test={}
d3.csv("dc.data.csv", function(csv){
	var data = crossfilter(csv);
	//set dimension vars
	var question_half_hour = data.dimension(function (d){
			return d.question_half_hour;
		}),
		question_weekday = data.dimension(function (d){
			return d.question_weekday;
		}),
		location_name = data.dimension(function (d){
			return d.location_name;
		});
	test = question_half_hour;
	//set group vars
	question_half_hour_group = question_half_hour.group().reduceCount();
	question_weekday_group = question_weekday.group().reduceCount();
	location_name_group = location_name.group().reduceCount();

	var question_half_hour_chart = dc.barChart("#question_half_hour")
		.width(1000)
		.height(300)
		.margins({top:10, left:10, right:10, bottom:30})
		.dimension(question_half_hour)
		.group(question_half_hour_group)
		.label(function(d){ return d.key; })
		.colors(d3.scale.category20c())
		.elasticY(true)
		.x(d3.scale.ordinal().domain())
        .xUnits(dc.units.ordinal)
        .renderHorizontalGridLines(true)
        .yAxis().ticks(4);

	var question_weekday = dc.rowChart("#question_weekday")
		.width(250)
		.height(250)
		.margins({top:10, left:10, right:10, bottom:30})
		.dimension(question_weekday)
		.group(question_weekday_group)
		.label(function(d){ return d.key; })
		.colors(["#edf8fb", "#ccece6", "#99d8c9", "#66c2a4", "#41ae76", "#238b45", "#005824"])
		.elasticX(true)
		.xAxis().ticks(4);

	var location_name_chart = dc.pieChart("#location_name")
		.dimension(location_name)
		.group(location_name_group)
		.radius([100])
		.innerRadius([10])
		.colors(["#fdae61", "#ffffbf", "#abdda4", "#2b83ba", "#d7191c"]);

	dc.renderAll();
})
<commit_msg>j err<commit_after>d3.csv("dc.data.csv", function(csv){
	var data = crossfilter(csv);
	//set dimension vars
	var question_half_hour = data.dimension(function (d){
			return d.question_half_hour;
		}),
		question_weekday = data.dimension(function (d){
			return d.question_weekday;
		}),
		location_name = data.dimension(function (d){
			return d.location_name;
		});

	//set group vars
	question_half_hour_group = question_half_hour.group().reduceCount();
	question_weekday_group = question_weekday.group().reduceCount();
	location_name_group = location_name.group().reduceCount();

	question_half_hour.dimension(function(d){
		console.log(d);

	})

	var question_half_hour_chart = dc.barChart("#question_half_hour")
		.width(1000)
		.height(300)
		.margins({top:10, left:10, right:10, bottom:30})
		.dimension(question_half_hour)
		.group(question_half_hour_group)
		.label(function(d){ return d.key; })
		.colors(d3.scale.category20c())
		.elasticY(true)
		.x(d3.scale.ordinal().domain())
        .xUnits(dc.units.ordinal)
        .renderHorizontalGridLines(true)
        .yAxis().ticks(4);

	var question_weekday = dc.rowChart("#question_weekday")
		.width(250)
		.height(250)
		.margins({top:10, left:10, right:10, bottom:30})
		.dimension(question_weekday)
		.group(question_weekday_group)
		.label(function(d){ return d.key; })
		.colors(["#edf8fb", "#ccece6", "#99d8c9", "#66c2a4", "#41ae76", "#238b45", "#005824"])
		.elasticX(true)
		.xAxis().ticks(4);

	var location_name_chart = dc.pieChart("#location_name")
		.dimension(location_name)
		.group(location_name_group)
		.radius([100])
		.innerRadius([10])
		.colors(["#fdae61", "#ffffbf", "#abdda4", "#2b83ba", "#d7191c"]);

	dc.renderAll();
})
<|endoftext|>


<commit_before>'use strict'

let SemitkiRouter = Backbone.Router.extend({
  routes: {
    "": "index",
    "scheduler": "schedulerCreate",
    "dashboard": "dashboard"
  },
  index: () => {
    let view = new LoginView();
    view.render({el:"#container"});
  },

    scheduler: () => {
    let view = new SchedulerCreateView();
    view.render({el:"#container"});
  },
  dashboard: () => {
    let view = new DashboardView();
    view.render({el:"#container"});
  }
});
<commit_msg>Add new function in the file routes.js<commit_after>'use strict'

let SemitkiRouter = Backbone.Router.extend({
  routes: {
    "": "index",
    "scheduler": "schedulerCreate",
    "dashboard": "dashboard",
    "groups": "groupsViews"
  },
  index: () => {
    let view = new LoginView();
    view.render({el:"#container"});
  },

    scheduler: () => {
    let view = new SchedulerCreateView();
    view.render({el:"#container"});
  },
  dashboard: () => {
    let view = new DashboardView();
    view.render({el:"#container"});
  },

  groups: () => {
    let view = new GroupsView();
    view.render({el:"#container"});
}
});
<|endoftext|>


<commit_before>//insert data into MongoDB
module.exports = function(options, opfile, columns, log, timer, moduleCallback) {

  var fs = require('fs'),
    async = require('async');

  var client = require('mongodb').MongoClient,
    creds = require('../../creds/mongo'),
    db,
    collection,
    Stream = require('stream'),
    split = require('split');

  const table = options.table.indexOf('.') > -1 ? options.table : 'dbutil.' + options.table;
  const databaseName = table.split('.')[0];
  const collectionName = table.split('.')[1];

  async.waterfall([
      function(cb) {
        //connect to mongo
        client.connect(creds + databaseName, function(err, database) {
          if (err) return cb(err);
          db = database;
          log.group('MongoDB').log('Connected');
          cb(null);
        })
      },
      function(cb) {
        //sometimes only insert, don't delete data
        if (options.update) {
          log.log('Insert only - not dropping existing data.');
          return cb(null);
        }
        //delete old data
        db.collectionNames(function(err, collections) {
          if (err) return cb(err);
          console.log(collections);
          if (collections) {
            db.collection(collectionName).drop(function(err, results) {
              if (err) return cb(err);
              log.log('Deleted old collection.');
              cb(null);
            })
          }
        })
      },
      function(cb) {
        //create colleciton (if not already existing)
        db.createCollection(collectionName, function(err, coll) {
          if (err) return cb(err);
          collection = coll;
          log.log('Created collection (if not existing) ' + collectionName);
          cb(null);
        })
      },
      function(cb) {
        //insert data one row at a time
        var first = true;
        var mongoWriteStream = new Stream.Writable();
        var rowCount = 0;
        var indexes = [];
        /* indexes */
        for (var i = 0; i < columns.length; i++) {
          //generate key and save for indexes
          var name = columns[i].name.replace(/_IND/ig, '');
          if (columns[i].index) {
            indexes.push(name);
          }
        }
        /* transform stream */
        mongoWriteStream._write = function(chunk, encoding, callback) {
          //write every line
          var data = chunk.toString().split('\t');
          var doc = {};
          //parse types
          for (var i = 0; i < columns.length; i++) {
            //parse data types
            if (!isNaN(Number(data[i]))) {
              doc[name] = Number(data[i]);
            } else if (data[i] === 'true') {
              doc[name] = true;
            } else if (data[i] === 'false') {
              doc[name] = false;
            } else if (
              name.toUpperCase().indexOf('DATE') !== -1 || name.toUpperCase().indexOf('TIMESTAMP') !== -1 || name.toUpperCase().indexOf('DATETIME') !== -1
            ) {
              doc[name] = new Date(data[i]);
            } else {
              doc[name] = data[i];
            }
          }
          if (data.length !== columns.length) return callback();
          //console.log(doc);
          collection.insertOne(doc, function(err, result) {
            if (err) throw err;
            rowCount++;
            callback();
          });

        }
        mongoWriteStream.on('error', function(err) {
          cb(err);
        });
        mongoWriteStream.on('finish', function() {
          cb(null, rowCount, indexes);
        })
        var opfileRStream = opfile.createReadStream();
        opfileRStream.pipe(split()).pipe(mongoWriteStream);
      },
      function(rowCount, indexes, cb) {
        //create indexes
        function makeIndex(i, callback) {
          log.log('makeIndex: ' + i);
          var ndex = {};
          ndex[i] = 1;
          collection.createIndex(ndex, null, function(err, results) {
            if (err) return callback(err);
            callback(null);
          })
        }
        //TODO not making indexes?? WHY??
        async.map(indexes, makeIndex, function(err, results) {
          if (err) return cb(err);

          cb(null, rowCount);
        })
      },
      function(rowCount, cb) {
        collection.count(function(err, count) {
          log.log('Success! Inserted ' + rowCount + ' documents. MongoDB says ' + databaseName + '.' + collectionName + ' now has ' + count + ' docs.');
          cb(null);
        })
      }
    ],
    function(err) {
      try {
        db.close();
      } catch (e) {
        log.error(e);
      }
      if (err) return moduleCallback(err);
      log.group('Finished destination').log(timer.now.str());
      moduleCallback(null, opfile);
    })

}
<commit_msg>delete mongo collection if exists (optional)<commit_after>//insert data into MongoDB
module.exports = function(options, opfile, columns, log, timer, moduleCallback) {

  var fs = require('fs'),
    async = require('async');

  var client = require('mongodb').MongoClient,
    creds = require('../../creds/mongo'),
    db,
    collection,
    Stream = require('stream'),
    split = require('split');

  const table = options.table.indexOf('.') > -1 ? options.table : 'dbutil.' + options.table;
  const databaseName = table.split('.')[0];
  const collectionName = table.split('.')[1];

  async.waterfall([
      function(cb) {
        //connect to mongo
        client.connect(creds + databaseName, function(err, database) {
          if (err) return cb(err);
          db = database;
          log.group('MongoDB').log('Connected');
          cb(null);
        })
      },
      function(cb) {
        //sometimes only insert, don't delete data
        if (options.update) {
          log.log('Insert only - not dropping existing data.');
          return cb(null);
        }
        //delete old data
        db.listCollections({
          name: collectionName
        }).toArray(function(err, collections) {
          if (err) return cb(err);
          if (collections.length) {
            db.collection(collectionName).drop(function(err, results) {
              if (err) return cb(err);
              log.log('Deleted old collection.');
              cb(null);
            })
          } else {
            cb(null)
          }
        })
      },
      function(cb) {
        //create colleciton (if not already existing)
        db.createCollection(collectionName, function(err, coll) {
          if (err) return cb(err);
          collection = coll;
          log.log('Created collection (if not existing) ' + collectionName);
          cb(null);
        })
      },
      function(cb) {
        //insert data one row at a time
        var first = true;
        var mongoWriteStream = new Stream.Writable();
        var rowCount = 0;
        var indexes = [];
        /* indexes */
        for (var i = 0; i < columns.length; i++) {
          //generate key and save for indexes
          var name = columns[i].name.replace(/_IND/ig, '');
          if (columns[i].index) {
            indexes.push(name);
          }
        }
        /* transform stream */
        mongoWriteStream._write = function(chunk, encoding, callback) {
          //write every line
          var data = chunk.toString().split('\t');
          var doc = {};
          //parse types
          for (var i = 0; i < columns.length; i++) {
            //parse data types
            if (!isNaN(Number(data[i]))) {
              doc[name] = Number(data[i]);
            } else if (data[i] === 'true') {
              doc[name] = true;
            } else if (data[i] === 'false') {
              doc[name] = false;
            } else if (
              name.toUpperCase().indexOf('DATE') !== -1 || name.toUpperCase().indexOf('TIMESTAMP') !== -1 || name.toUpperCase().indexOf('DATETIME') !== -1
            ) {
              doc[name] = new Date(data[i]);
            } else {
              doc[name] = data[i];
            }
          }
          if (data.length !== columns.length) return callback();
          //console.log(doc);
          collection.insertOne(doc, function(err, result) {
            if (err) throw err;
            rowCount++;
            callback();
          });

        }
        mongoWriteStream.on('error', function(err) {
          cb(err);
        });
        mongoWriteStream.on('finish', function() {
          cb(null, rowCount, indexes);
        })
        var opfileRStream = opfile.createReadStream();
        opfileRStream.pipe(split()).pipe(mongoWriteStream);
      },
      function(rowCount, indexes, cb) {
        //create indexes
        function makeIndex(i, callback) {
          log.log('makeIndex: ' + i);
          var ndex = {};
          ndex[i] = 1;
          collection.createIndex(ndex, null, function(err, results) {
            if (err) return callback(err);
            callback(null);
          })
        }
        //TODO not making indexes?? WHY??
        async.map(indexes, makeIndex, function(err, results) {
          if (err) return cb(err);

          cb(null, rowCount);
        })
      },
      function(rowCount, cb) {
        collection.count(function(err, count) {
          log.log('Success! Inserted ' + rowCount + ' documents. MongoDB says ' + databaseName + '.' + collectionName + ' now has ' + count + ' docs.');
          cb(null);
        })
      }
    ],
    function(err) {
      try {
        db.close();
      } catch (e) {
        log.error(e);
      }
      if (err) return moduleCallback(err);
      log.group('Finished destination').log(timer.now.str());
      moduleCallback(null, opfile);
    })

}
<|endoftext|>


<commit_before>define([
	'jquery',
	'underscore',
	'backbone',
	'backbone-relational',
	'models/feedui'
],
function($, _, Backbone, no, FeedUIModel) {

	'use strict';

	var FeedUI = Backbone.View.extend({
		initialize: function(options) {
			var _this = this;
			this.feed = options.feed;
			this.setBottom();
			this.model = new FeedUIModel({skip: 0});
			$(window).on('scroll', function() {
				if ($(window).scrollTop() >= _this.bottom) {
					$(this).trigger('hit');
				}
			});
		},
		setBottom: function() {
			var bottom = $('.feed-content').height() - $(window).height(),
				_this = this;

			this.bottom = bottom < 0 ? 0 : bottom;

			$(window).one('hit', function() {
				var skip = _this.model.get('skip') + 25;
				_this.model.set('skip', skip);
				_this.feed.url = '/feed?limit=25&skip='+skip;
				_this.feed.fetch({
					remove: false,
					success: function(view, response) {
						if (!_.isEmpty(response)) {
							_this.setBottom();
						}
					}
				});
			});
			return this.bottom;
		}
	});

	return FeedUI;
});<commit_msg>use current url to get more logs<commit_after>define([
	'jquery',
	'underscore',
	'backbone',
	'backbone-relational',
	'models/feedui'
],
function($, _, Backbone, no, FeedUIModel) {

	'use strict';

	var FeedUI = Backbone.View.extend({
		initialize: function(options) {
			var _this = this;
			this.feed = options.feed;
			this.setBottom();
			this.model = new FeedUIModel({skip: 0});
			$(window).on('scroll', function() {
				if ($(window).scrollTop() >= _this.bottom) {
					$(this).trigger('hit');
				}
			});
		},
		setBottom: function() {
			var bottom = $('.feed-content').height() - $(window).height(),
				_this = this;

			this.bottom = bottom < 0 ? 0 : bottom;

			$(window).one('hit', function() {
				var skip = _this.model.get('skip') + 25,
					queryStart = window.location.search ? '?' : '&';
				_this.model.set('skip', skip);
				_this.feed.url = window.location.pathname+queryStart+'limit=25&skip='+skip;
				_this.feed.fetch({
					remove: false,
					success: function(view, response) {
						if (!_.isEmpty(response)) {
							_this.setBottom();
						}
					}
				});
			});
			return this.bottom;
		}
	});

	return FeedUI;
});<|endoftext|>


<commit_before>function LWJSTE(){
    this.templates = {};
    arguments.callee.escape_character = "#";
    arguments.callee.IF = 0;
    arguments.callee.EACH = 1;
    arguments.callee.SWITCH = 2;
    arguments.callee.LITERAL = 3;
    arguments.callee.VARIABLE = 4;
}
LWJSTE.prototype = {
    _parseTemplate : function(str){
        var LITERAL = 0, EACH = 1, IF = 2, ELIF = 3, ELSE = 4, ID = 5, SWITCH = 6, CASE = 7, DEFAULT = 8, L_CB = 9, R_CB = 10, EACH_END = 12, IF_END = 13, SWITCH_END = 14;
        var tokens = [];
        //lexer
        var token = "";
        var lines_count = 1;
        var literal = true;
        var last_is_escape = false;
        var pushed = false;
        function success(result){
            return [0, result];
        }
        function faild_token(token, message){
            return [1, message == undefined ? "" : message, [token[2], token[1]]];
        }
        function faild_message(message){
            return [1, message, []];
        }
        function push(type, lexeme){
            if(lexeme.length != 0){
                tokens.push([type, lexeme, lines_count]);
                token = "";
            }
        }
        function push_reserved_word(token){
            switch(token.toLowerCase()){
                case "if": push(IF, token); break;
                case "elif": push(ELIF, token); break;
                case "else": push(ELSE, token); break;
                case "/if": push(IF_END, token); break;
                case "each": push(EACH, token); break;
                case "/each": push(EACH_END, token); break;
                case "switch": push(SWITCH, token); break;
                case "case": push(CASE, token); break;
                case "default": push(DEFAULT, token); break;
                case "/switch": push(SWITCH_END, token); break;
                default: push(ID, token);
            }
        }
        for(var i = 0, len = str.length; i < len; i ++){
            if(str[i] == "\n"){
                lines_count ++;
            }
            if(literal){
                if(last_is_escape){
                    last_is_escape = false;
                    if(str[i] == LWJSTE.escape_character){
                        token += LWJSTE.escape_character;
                    }else{
                        token += LWJSTE.escape_character + str[i];
                    }
                }else{
                    if(str[i] == LWJSTE.escape_character){
                        last_is_escape = true;
                    }else if(str[i] == "{"){
                        push(LITERAL, token);
                        push(L_CB, "{");
                        literal = false;
                    }else{
                        token += str[i];
                    }
                }
            }else{
                if(str[i] == "}"){
                    if(token.length != 0){
                        push_reserved_word(token);
                    }
                    push(R_CB, "}");
                    pushed = false;
                    literal = true;
                }else if(str[i] == " "){
                    if(token.length != 0){
                        push_reserved_word(token);
                    }
                }else{
                    token += str[i];
                }
            }
        }
        if(literal){
            if(token.length != 0){
                push(LITERAL, token);
            }
        }else{
            return faild_message("unclosed curly brackets");
        }
        //syntactic analysis
        var progress = 0;
        var token_length = tokens.length;
        var result = []; //output of parser
        var node = result; //pointer to result
        var indexes = []; //indexes of result
        var parent_nodes = []; //used in move_node_parent
        var cb_open = false; //it's true when in curly brackets
        var in_cb = []; //tokens in curly brackets
        var if_opens = 0, else_used = []; //used when in if blocks
        var each_opens = 0; //used when in each blocks
        var switch_opens = 0, case_used = [], default_used = []; //used when in switch blocks
        var unexpected_tokens = [ELIF, ELSE, CASE, DEFAULT, EACH_END, IF_END, SWITCH_END];
        function drop(array, index){
            array.splice(index, 1);
        }
        function set_unexpected_token(token){
            if(token instanceof Array){
                for(var i = 0, len = token.length; i < len; i ++){
                    set_unexpected_token(token[i]);
                }
            }else{
                if(unexpected_tokens.indexOf(token) == -1){
                    unexpected_tokens.push(token);
                }
            }
        }
        function remove_unexpected_token(token){
            if(token instanceof Array){
                for(var i = 0, len = token.length; i < len; i ++){
                    remove_unexpected_token(token[i]);
                }
            }else{
                for(var i = 0, len = unexpected_tokens.length; i < len; i ++){
                    if(token == unexpected_tokens[i]){
                        drop(unexpected_tokens, i);
                        break;
                    }
                }
            }
        }
        function move_node_parent(count){
            drop(indexes, indexes.length - 1);
            indexes[indexes.length - 1] = parent_nodes[parent_nodes.length - 1];
            drop(parent_nodes, parent_nodes.length - 1);
            if(count != undefined && count > 1){
                move_node_parent(count - 1);
            }
        }
        function move_node_child(index){
            if(index == undefined){
                index = node.length - 1;
            }
            parent_nodes.push(indexes[indexes.length - 1]);
            indexes.push(index);
        }
        function move_node(index){
            indexes[indexes.length - 1] = index;
        }
        function get_current_node(){
            node = result;
            for(var i = 0, len = indexes.length; i < len; i ++){
                node = node[indexes[i]];
            }
        }
        function format_statement(){
            var result = [];
            for(var i = 1, len = in_cb.length; i < len; i ++){
                result.push(in_cb[i][1]);
            }
            return result;
        }
        while(progress < token_length){
            if(unexpected_tokens.indexOf(tokens[progress][0]) != -1){
                return faild_token(tokens[progress], "unexpected token");
            }
            get_current_node();
            if(! cb_open){
                switch(tokens[progress][0]){
                    case LITERAL:
                        node.push([LWJSTE.LITERAL, tokens[progress][1]]);
                        break;
                    case L_CB:
                        cb_open = true;
                        in_cb = [];
                        break;
                }
            }else{
                if(tokens[progress][0] == R_CB){
                    cb_open = false;
                    switch(in_cb[0][0]){
                        case IF:
                            if(in_cb.length == 1){
                                return faild_token(tokens[progress]);
                            }else{
                                if_opens ++;
                                else_used.push(false);
                                node.push([LWJSTE.IF, [[format_statement(), []]], []]);
                                move_node_child();
                                move_node_child(1);
                                move_node_child(0);
                                move_node_child(1);
                                remove_unexpected_token([ELIF, ELSE, IF_END]);
                            }
                            break;
                        case ELIF:
                            if(if_opens == 0 || in_cb.length == 1 || else_used[if_opens]){
                                return faild_token(tokens[progress]);
                            }else{
                                move_node_parent(2);
                                get_current_node();
                                node.push([format_statement(), []]);
                                move_node_child();
                                move_node_child(1);
                            }
                            break;
                        case ELSE:
                            if(if_opens == 0 || else_used[if_opens] || in_cb.length != 1){
                                return faild_token(tokens[progress]);
                            }else{
                                else_used[if_opens] = true;
                                move_node_parent(3);
                                move_node_child(2);
                                set_unexpected_token(ELIF);
                            }
                            break;
                        case IF_END:
                            if(if_opens == 0 || in_cb.length != 1){
                                return faild_token(tokens[progress]);
                            }else{
                                if(else_used[if_opens]){
                                    drop(else_used, if_opens);
                                    move_node_parent(2);
                                }else{
                                    move_node_parent(4);
                                }
                                if_opens --;
                                set_unexpected_token([ELIF, ELSE, IF_END]);
                            }
                            break;
                        case EACH:
                            if(in_cb.length != 2){
                                return faild_token(tokens[progress]);
                            }else{
                                each_opens ++;
                                node.push([LWJSTE.EACH, in_cb[1][1], []]);
                                move_node_child();
                                move_node_child(2);
                                remove_unexpected_token(EACH_END);
                            }
                            break;
                        case EACH_END:
                            if(each_opens == 0 || in_cb.length != 1){
                                return faild_token(tokens[progress]);
                            }else{
                                move_node_parent(2);
                                each_opens --;
                                set_unexpected_token(EACH_END);
                            }
                            break;
                        case SWITCH:
                            if(in_cb.length != 2){
                                return faild_token(tokens[progress]);
                            }else{
                                switch_opens ++;
                                case_used.push(false);
                                default_used.push(false);
                                node.push([LWJSTE.SWITCH, in_cb[1][1], [], []]);
                                move_node_child();
                                move_node_child(2);
                                remove_unexpected_token([CASE, DEFAULT, SWITCH_END]);
                                set_unexpected_token([EACH, IF, LITERAL, SWITCH]);
                            }
                            break;
                        case CASE:
                            if(switch_opens == 0 || default_used[switch_opens] || in_cb.length == 1){
                                return faild_token(tokens[progress]);
                            }else{
                                if(case_used[switch_opens]){
                                    parent_nodes(2);
                                    get_current_node();
                                }
                                node.push([format_statement(), []]);
                                move_node_child();
                                move_node_child(1);
                                case_used[switch_opens] = true;
                                remove_unexpected_token([EACH, IF, LITERAL, SWITCH]);
                            }
                            break;
                        case DEFAULT:
                            if(switch_opens == 0 || default_used[switch_opens] || in_cb.length != 1){
                                return faild_token(tokens[progress]);
                            }else{
                                default_used[switch_opens] = true;
                                if(case_used[switch_opens]){
                                    move_node_parent(3);
                                }else{
                                    move_node_parent();
                                }
                                move_node_child(3);
                                set_unexpected_token(CASE);
                                remove_unexpected_token([EACH, IF, LITERAL, SWITCH]);
                            }
                            break;
                        case SWITCH_END:
                            if(switch_opens == 0 || case_used[switch_opens] == false || in_cb.length != 1){
                                return faild_token(tokens[progress]);
                            }else{
                                if(default_used[switch_opens]){
                                    move_node_parent(2);
                                }else if(case_used[switch_opens]){
                                    move_node_parent(4);
                                }
                                switch_opens --;
                                set_unexpected_token([CASE, DEFAULT, SWITCH_END]);
                            }
                            break;
                        case ID:
                            if(in_cb.length != 1){
                                return faild_token(tokens[progress]);
                            }else{
                                node.push([LWJSTE.VARIABLE, in_cb[0][1]]);
                            }
                            break;
                        default:
                            return faild_token(tokens[progress]);
                    }
                    in_cb = [];
                }
                in_cb.push(tokens[progress]);
            }
            progress ++;
        }
        if(switch_opens > 0 || if_opens > 0 || each_opens > 0){
            var if_c = if_opens > 0 ? " " + if_opens + " if" : "";
            var each_c = each_opens > 0 ? " " + each_opens + " each" : "";
            var switch_c = switch_opens > 0 ? " " + switch_opens + " switch" : "";
            return faild_message("found not closed" + if_c + each_c + switch_c);
        }
        return success(result);
    },
    addTemplate : function(name, template){
        var result = this._parseTemplate(template);
        if(result[0] == 0){
            this.templates[name] = result[1];
        }else{
            //TODO error
        }
    },
    _evaluateVariable : function(variable){
        if((variable === false) ||
                (variable == null) ||
                (variable instanceof Array && variable.length == 0)){
            return false;
        }
        return true;
    },
    _useTemplate : function(template, data){
        var result = "";
        for(var i = 0, len = template.length; i < len; i ++){
            switch(template[i][0]){
                case LWJSTE.LITERAL:
                    result += template[i][1];
                    break;
                case LWJSTE.VARIABLE:
                    result += String(data[template[i][1]]);
                    break;
                case LWJSTE.EACH:
                    for(var j = 0, len = data[template[i][1]].length; j < len; j ++){
                        result += this._useTemplate(template[i][2], data[template[i][1]][j]);
                    }
                    break;
                case LWJSTE.IF:
                    var do_else_process = true; //do else process if true
                    for(var j = 0, len = template[i][1].length; j < len; j ++){
                        var do_process = true; //do else process if true
                        //AND
                        for(var k = 0, len = template[i][1][j][0].length; k < len; k ++){
                            if(this._evaluateVariable(data[template[i][1][j][0][k]]) == false){
                                do_process = false;
                                break;
                            }
                        }
                        if(do_process){
                            result += this._useTemplate(template[i][1][j][1], data);
                            do_else_process = false;
                            break;
                        }
                    }
                    if(do_else_process){
                        result += this._useTemplate(template[i][2], data);
                    }
                    break;
                case LWJSTE.SWITCH:
                    var do_default_process = true; //do else process if true
                    for(var j = 0, len = template[i][1].length; j < len; j ++){
                        var do_process = false; //do else process if true
                        //OR
                        for(var k = 0, len = template[i][1][j][0].length; k < len; k ++){
                            if(this._evaluateVariable(data[template[i][1][j][0][k]]) == true){
                                do_process = true;
                                break;
                            }
                        }
                        if(do_process){
                            result += this._useTemplate(template[i][1][j][1], data);
                            do_default_process = false;
                        }
                    }
                    if(do_default_process){
                        result += this._useTemplate(template[i][2], data);
                    }
                    break;
            }
        }
        return result;
    },
    useTemplate : function(name, data){
        return this._useTemplate(this.templates[name], data);
    },
    removeTemplate : function(name){
        if(name == null){
            this.templates = {};
        }else if(name in this.templates){
            delete this.templates[name];
        }
    },
    saveTemplates : function(destination){
    },
    loadTemplates : function(source){
    }
};
lwjste = new LWJSTE();
<commit_msg>skip literals between switch and first case<commit_after>function LWJSTE(){
    this.templates = {};
    arguments.callee.escape_character = "#";
    arguments.callee.IF = 0;
    arguments.callee.EACH = 1;
    arguments.callee.SWITCH = 2;
    arguments.callee.LITERAL = 3;
    arguments.callee.VARIABLE = 4;
}
LWJSTE.prototype = {
    _parseTemplate : function(str){
        var LITERAL = 0, EACH = 1, IF = 2, ELIF = 3, ELSE = 4, ID = 5, SWITCH = 6, CASE = 7, DEFAULT = 8, L_CB = 9, R_CB = 10, EACH_END = 12, IF_END = 13, SWITCH_END = 14;
        var tokens = [];
        //lexer
        var token = "";
        var lines_count = 1;
        var literal = true;
        var last_is_escape = false;
        var pushed = false;
        function success(result){
            return [0, result];
        }
        function faild_token(token, message){
            return [1, message == undefined ? "" : message, [token[2], token[1]]];
        }
        function faild_message(message){
            return [1, message, []];
        }
        function push(type, lexeme){
            if(lexeme.length != 0){
                tokens.push([type, lexeme, lines_count]);
                token = "";
            }
        }
        function push_reserved_word(token){
            switch(token.toLowerCase()){
                case "if": push(IF, token); break;
                case "elif": push(ELIF, token); break;
                case "else": push(ELSE, token); break;
                case "/if": push(IF_END, token); break;
                case "each": push(EACH, token); break;
                case "/each": push(EACH_END, token); break;
                case "switch": push(SWITCH, token); break;
                case "case": push(CASE, token); break;
                case "default": push(DEFAULT, token); break;
                case "/switch": push(SWITCH_END, token); break;
                default: push(ID, token);
            }
        }
        for(var i = 0, len = str.length; i < len; i ++){
            if(str[i] == "\n"){
                lines_count ++;
            }
            if(literal){
                if(last_is_escape){
                    last_is_escape = false;
                    if(str[i] == LWJSTE.escape_character){
                        token += LWJSTE.escape_character;
                    }else{
                        token += LWJSTE.escape_character + str[i];
                    }
                }else{
                    if(str[i] == LWJSTE.escape_character){
                        last_is_escape = true;
                    }else if(str[i] == "{"){
                        push(LITERAL, token);
                        push(L_CB, "{");
                        literal = false;
                    }else{
                        token += str[i];
                    }
                }
            }else{
                if(str[i] == "}"){
                    if(token.length != 0){
                        push_reserved_word(token);
                    }
                    push(R_CB, "}");
                    pushed = false;
                    literal = true;
                }else if(str[i] == " "){
                    if(token.length != 0){
                        push_reserved_word(token);
                    }
                }else{
                    token += str[i];
                }
            }
        }
        if(literal){
            if(token.length != 0){
                push(LITERAL, token);
            }
        }else{
            return faild_message("unclosed curly brackets");
        }
        //syntactic analysis
        var progress = 0;
        var token_length = tokens.length;
        var result = []; //output of parser
        var node = result; //pointer to result
        var indexes = []; //indexes of result
        var parent_nodes = []; //used in move_node_parent
        var cb_open = false; //it's true when in curly brackets
        var in_cb = []; //tokens in curly brackets
        var if_opens = 0, else_used = []; //used when in if blocks
        var each_opens = 0; //used when in each blocks
        var switch_opens = 0, case_used = [], default_used = []; //used when in switch blocks
        var unexpected_tokens = [ELIF, ELSE, CASE, DEFAULT, EACH_END, IF_END, SWITCH_END];
        var literal_skip = false; //not push literal if this was true
        function drop(array, index){
            array.splice(index, 1);
        }
        function set_unexpected_token(token){
            if(token instanceof Array){
                for(var i = 0, len = token.length; i < len; i ++){
                    set_unexpected_token(token[i]);
                }
            }else{
                if(unexpected_tokens.indexOf(token) == -1){
                    unexpected_tokens.push(token);
                }
            }
        }
        function remove_unexpected_token(token){
            if(token instanceof Array){
                for(var i = 0, len = token.length; i < len; i ++){
                    remove_unexpected_token(token[i]);
                }
            }else{
                for(var i = 0, len = unexpected_tokens.length; i < len; i ++){
                    if(token == unexpected_tokens[i]){
                        drop(unexpected_tokens, i);
                        break;
                    }
                }
            }
        }
        function move_node_parent(count){
            drop(indexes, indexes.length - 1);
            indexes[indexes.length - 1] = parent_nodes[parent_nodes.length - 1];
            drop(parent_nodes, parent_nodes.length - 1);
            if(count != undefined && count > 1){
                move_node_parent(count - 1);
            }
        }
        function move_node_child(index){
            if(index == undefined){
                index = node.length - 1;
            }
            parent_nodes.push(indexes[indexes.length - 1]);
            indexes.push(index);
        }
        function move_node(index){
            indexes[indexes.length - 1] = index;
        }
        function get_current_node(){
            node = result;
            for(var i = 0, len = indexes.length; i < len; i ++){
                node = node[indexes[i]];
            }
        }
        function format_statement(){
            var result = [];
            for(var i = 1, len = in_cb.length; i < len; i ++){
                result.push(in_cb[i][1]);
            }
            return result;
        }
        while(progress < token_length){
            if(unexpected_tokens.indexOf(tokens[progress][0]) != -1){
                return faild_token(tokens[progress], "unexpected token");
            }
            get_current_node();
            if(! cb_open){
                switch(tokens[progress][0]){
                    case LITERAL:
                        if(! literal_skip){
                            node.push([LWJSTE.LITERAL, tokens[progress][1]]);
                        }
                        break;
                    case L_CB:
                        cb_open = true;
                        in_cb = [];
                        break;
                }
            }else{
                if(tokens[progress][0] == R_CB){
                    cb_open = false;
                    switch(in_cb[0][0]){
                        case IF:
                            if(in_cb.length == 1){
                                return faild_token(tokens[progress]);
                            }else{
                                if_opens ++;
                                else_used.push(false);
                                node.push([LWJSTE.IF, [[format_statement(), []]], []]);
                                move_node_child();
                                move_node_child(1);
                                move_node_child(0);
                                move_node_child(1);
                                remove_unexpected_token([ELIF, ELSE, IF_END]);
                            }
                            break;
                        case ELIF:
                            if(if_opens == 0 || in_cb.length == 1 || else_used[if_opens]){
                                return faild_token(tokens[progress]);
                            }else{
                                move_node_parent(2);
                                get_current_node();
                                node.push([format_statement(), []]);
                                move_node_child();
                                move_node_child(1);
                            }
                            break;
                        case ELSE:
                            if(if_opens == 0 || else_used[if_opens] || in_cb.length != 1){
                                return faild_token(tokens[progress]);
                            }else{
                                else_used[if_opens] = true;
                                move_node_parent(3);
                                move_node_child(2);
                                set_unexpected_token(ELIF);
                            }
                            break;
                        case IF_END:
                            if(if_opens == 0 || in_cb.length != 1){
                                return faild_token(tokens[progress]);
                            }else{
                                if(else_used[if_opens]){
                                    drop(else_used, if_opens);
                                    move_node_parent(2);
                                }else{
                                    move_node_parent(4);
                                }
                                if_opens --;
                                set_unexpected_token([ELIF, ELSE, IF_END]);
                            }
                            break;
                        case EACH:
                            if(in_cb.length != 2){
                                return faild_token(tokens[progress]);
                            }else{
                                each_opens ++;
                                node.push([LWJSTE.EACH, in_cb[1][1], []]);
                                move_node_child();
                                move_node_child(2);
                                remove_unexpected_token(EACH_END);
                            }
                            break;
                        case EACH_END:
                            if(each_opens == 0 || in_cb.length != 1){
                                return faild_token(tokens[progress]);
                            }else{
                                move_node_parent(2);
                                each_opens --;
                                set_unexpected_token(EACH_END);
                            }
                            break;
                        case SWITCH:
                            if(in_cb.length != 2){
                                return faild_token(tokens[progress]);
                            }else{
                                switch_opens ++;
                                case_used.push(false);
                                default_used.push(false);
                                node.push([LWJSTE.SWITCH, in_cb[1][1], [], []]);
                                move_node_child();
                                move_node_child(2);
                                remove_unexpected_token([CASE, DEFAULT, SWITCH_END]);
                                set_unexpected_token([EACH, IF, SWITCH]);
                                literal_skip = true;
                            }
                            break;
                        case CASE:
                            if(switch_opens == 0 || default_used[switch_opens] || in_cb.length == 1){
                                return faild_token(tokens[progress]);
                            }else{
                                if(case_used[switch_opens]){
                                    move_node_parent(2);
                                    get_current_node();
                                }
                                node.push([format_statement(), []]);
                                move_node_child();
                                move_node_child(1);
                                case_used[switch_opens] = true;
                                remove_unexpected_token([EACH, IF, SWITCH]);
                                literal_skip = false;
                            }
                            break;
                        case DEFAULT:
                            if(switch_opens == 0 || default_used[switch_opens] || in_cb.length != 1){
                                return faild_token(tokens[progress]);
                            }else{
                                default_used[switch_opens] = true;
                                if(case_used[switch_opens]){
                                    move_node_parent(3);
                                }else{
                                    move_node_parent();
                                }
                                move_node_child(3);
                                set_unexpected_token(CASE);
                                remove_unexpected_token([EACH, IF, SWITCH]);
                                literal_skip = false;
                            }
                            break;
                        case SWITCH_END:
                            if(switch_opens == 0 || case_used[switch_opens] == false || in_cb.length != 1){
                                return faild_token(tokens[progress]);
                            }else{
                                if(default_used[switch_opens]){
                                    move_node_parent(2);
                                }else if(case_used[switch_opens]){
                                    move_node_parent(4);
                                }
                                switch_opens --;
                                set_unexpected_token([CASE, DEFAULT, SWITCH_END]);
                                literal_skip = false;
                            }
                            break;
                        case ID:
                            if(in_cb.length != 1){
                                return faild_token(tokens[progress]);
                            }else{
                                node.push([LWJSTE.VARIABLE, in_cb[0][1]]);
                            }
                            break;
                        default:
                            return faild_token(tokens[progress]);
                    }
                    in_cb = [];
                }
                in_cb.push(tokens[progress]);
            }
            progress ++;
        }
        if(switch_opens > 0 || if_opens > 0 || each_opens > 0){
            var if_c = if_opens > 0 ? " " + if_opens + " if" : "";
            var each_c = each_opens > 0 ? " " + each_opens + " each" : "";
            var switch_c = switch_opens > 0 ? " " + switch_opens + " switch" : "";
            return faild_message("found not closed" + if_c + each_c + switch_c);
        }
        return success(result);
    },
    addTemplate : function(name, template){
        var result = this._parseTemplate(template);
        if(result[0] == 0){
            this.templates[name] = result[1];
        }else{
            //TODO error
        }
    },
    _evaluateVariable : function(variable){
        if((variable === false) ||
                (variable == null) ||
                (variable instanceof Array && variable.length == 0)){
            return false;
        }
        return true;
    },
    _useTemplate : function(template, data){
        var result = "";
        for(var i = 0, len = template.length; i < len; i ++){
            switch(template[i][0]){
                case LWJSTE.LITERAL:
                    result += template[i][1];
                    break;
                case LWJSTE.VARIABLE:
                    result += String(data[template[i][1]]);
                    break;
                case LWJSTE.EACH:
                    for(var j = 0, len = data[template[i][1]].length; j < len; j ++){
                        result += this._useTemplate(template[i][2], data[template[i][1]][j]);
                    }
                    break;
                case LWJSTE.IF:
                    var do_else_process = true; //do else process if true
                    for(var j = 0, len = template[i][1].length; j < len; j ++){
                        var do_process = true; //do else process if true
                        //AND
                        for(var k = 0, len = template[i][1][j][0].length; k < len; k ++){
                            if(this._evaluateVariable(data[template[i][1][j][0][k]]) == false){
                                do_process = false;
                                break;
                            }
                        }
                        if(do_process){
                            result += this._useTemplate(template[i][1][j][1], data);
                            do_else_process = false;
                            break;
                        }
                    }
                    if(do_else_process){
                        result += this._useTemplate(template[i][2], data);
                    }
                    break;
                case LWJSTE.SWITCH:
                    var do_default_process = true; //do else process if true
                    for(var j = 0, len = template[i][1].length; j < len; j ++){
                        var do_process = false; //do else process if true
                        //OR
                        for(var k = 0, len = template[i][1][j][0].length; k < len; k ++){
                            if(this._evaluateVariable(data[template[i][1][j][0][k]]) == true){
                                do_process = true;
                                break;
                            }
                        }
                        if(do_process){
                            result += this._useTemplate(template[i][1][j][1], data);
                            do_default_process = false;
                        }
                    }
                    if(do_default_process){
                        result += this._useTemplate(template[i][2], data);
                    }
                    break;
            }
        }
        return result;
    },
    useTemplate : function(name, data){
        return this._useTemplate(this.templates[name], data);
    },
    removeTemplate : function(name){
        if(name == null){
            this.templates = {};
        }else if(name in this.templates){
            delete this.templates[name];
        }
    },
    saveTemplates : function(destination){
    },
    loadTemplates : function(source){
    }
};
lwjste = new LWJSTE();
<|endoftext|>


<commit_before>$(document).ready(function() {

  // Set some default values
  var currentUploads = 0;

  // Initialize autocomplete
  $('.autocomplete.speaker')
    .autocomplete({
      source: [{
        url: '/event/api/user?find=%QUERY%',
        type:'remote'
      }],
      limit: 5,
      minLength: 1,
      titleKey: 'displayname',
      valueKey: 'id',
      getTitle: function(speaker) {
        return speaker.firstname + ' ' + speaker.name;
      },
      getValue: function(speaker) {
        return speaker.firstname + ' ' + speaker.name;
      }
    })
    .on('selected.xdsoft', function(e, speaker) {
      // Set ID in hidden field when suggestion was selected
      var target = $(this).attr('data-hidden-field-id');
      if (target != undefined) {
        $('#' + target).val(speaker.id);
      }
    });

  // Initialize datepicker
  $('.datepicker').datepicker({
    format: 'dd.mm.yyyy',
    weekStart: 1
  });
  $('[data-datepicker-id]').click(function() {
    var id= $(this).attr('data-datepicker-id');
    $('#'+id).datepicker('show');
  });

  // Disable dropzone auto discover for all elements:
  Dropzone.autoDiscover = false;

  $(".dropzone").each(function() {
    // Global dropzone configuration
    var config = {
      method: 'put',
      maxFiles: 1,
      createImageThumbnails: false,
      previewTemplate: $('#preview-template').html(),
      targetId: $(this).attr('data-id-target'),
      sending: function(file) {
        currentUploads++;
      },
      complete: function(file) {
        currentUploads--;
      },
      success: function(file, response) {
        // Set returned ID into hidden field
        $('input[name=' + this.options.targetId + ']').val(response.id);
      },
      error: function(file, message) {
        alert(message.error);
        this.removeFile(file);
      },
      canceled: function(file) {
        this.removeFile(file);
      }
    };

    // Individual dropzone configuration
    switch ($(this).attr('id')) {
      case 'sessionSlides':
        config.acceptedFiles = 'application/pdf,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation';
        break;
      case 'sessionScreenshot':
        config.acceptedFiles = 'image/*';
        break;
      case 'sessionVideo':
        config.acceptedFiles = 'video/*';
        break;
    }

    // Initialize  dropzone
    $(this).dropzone(config);
  });

  // Watch save button
  $('.save-session').click(function() {
    // Cancel submit when at least one upload is still in progress
    if (currentUploads > 0) {
      alert(currentUploads + ' upload(s) in progress. Please wait.');
      return;
    }

    // Check form data
    var formData = {};
    var formErrors = [];
    $('.create-session input[name], .create-session textarea[name]').each(function() {
      if (!$(this).hasClass('optional') && $(this).val() == '') {
        $(this).closest('fieldset').addClass('has-error');
        formErrors.push($(this));
      } else {
        $(this).closest('fieldset').removeClass('has-error');
        formData[$(this).attr('name')] = $(this).val();
      }
    });

    if (formErrors.length > 0) {
      return;
    }

    var session = {
      title: formData.title,
      speakerId: formData.speakerId,
      description: formData.description,
      date: formData.date,
      slidesId: formData.sessionSlidesId,
      screenshotId: formData.sessionScreenshotId,
      videoId: formData.sessionVideoId
    };

    // TODO: post session object to API
    console.log(session);
  });

});
<commit_msg>Put session data to API<commit_after>$(document).ready(function() {

  // Set some default values
  var currentUploads = 0;

  // Initialize autocomplete
  $('.autocomplete.speaker')
    .autocomplete({
      source: [{
        url: '/event/api/user?find=%QUERY%',
        type:'remote'
      }],
      limit: 5,
      minLength: 1,
      titleKey: 'displayname',
      valueKey: 'id',
      getTitle: function(speaker) {
        return speaker.firstname + ' ' + speaker.name;
      },
      getValue: function(speaker) {
        return speaker.firstname + ' ' + speaker.name;
      }
    })
    .on('selected.xdsoft', function(e, speaker) {
      // Set ID in hidden field when suggestion was selected
      var target = $(this).attr('data-hidden-field-id');
      if (target != undefined) {
        $('#' + target).val(speaker.id);
      }
    });

  // Initialize datepicker
  $('.datepicker').datepicker({
    format: 'dd.mm.yyyy',
    weekStart: 1
  });
  $('[data-datepicker-id]').click(function() {
    var id= $(this).attr('data-datepicker-id');
    $('#'+id).datepicker('show');
  });

  // Disable dropzone auto discover for all elements:
  Dropzone.autoDiscover = false;

  $(".dropzone").each(function() {
    // Global dropzone configuration
    var config = {
      method: 'put',
      maxFiles: 1,
      createImageThumbnails: false,
      previewTemplate: $('#preview-template').html(),
      targetId: $(this).attr('data-id-target'),
      sending: function(file) {
        currentUploads++;
      },
      complete: function(file) {
        currentUploads--;
      },
      success: function(file, response) {
        // Set returned ID into hidden field
        $('input[name=' + this.options.targetId + ']').val(response.id);
      },
      error: function(file, message) {
        alert(message.error);
        this.removeFile(file);
      },
      canceled: function(file) {
        this.removeFile(file);
      }
    };

    // Individual dropzone configuration
    switch ($(this).attr('id')) {
      case 'sessionSlides':
        config.acceptedFiles = 'application/pdf,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation';
        break;
      case 'sessionScreenshot':
        config.acceptedFiles = 'image/*';
        break;
      case 'sessionVideo':
        config.acceptedFiles = 'video/*';
        break;
    }

    // Initialize  dropzone
    $(this).dropzone(config);
  });

  // Watch save button
  $('.save-session').click(function() {
    // Cancel submit when at least one upload is still in progress
    if (currentUploads > 0) {
      alert(currentUploads + ' upload(s) in progress. Please wait.');
      return;
    }

    // Check form data
    var formData = {};
    var formErrors = [];
    $('.create-session input[name], .create-session textarea[name]').each(function() {
      if (!$(this).hasClass('optional') && $(this).val() == '') {
        $(this).closest('fieldset').addClass('has-error');
        formErrors.push($(this));
      } else {
        $(this).closest('fieldset').removeClass('has-error');
        formData[$(this).attr('name')] = $(this).val();
      }
    });

    if (formErrors.length > 0) {
      return;
    }

    var session = {
      title:       formData.title,
      speaker_id:  formData.speakerId,
      description: formData.description,
      date:        formData.date,
      files: {
        slides_id:     formData.sessionSlidesId,
        screenshot_id: formData.sessionScreenshotId,
        video_id:      formData.sessionVideoId
      }
    };

    // Post session object to API
    $.ajax({
      url:  '/event/api/session',
      method: 'put',
      data: JSON.stringify(session),
      contentType: 'application/json'
    }).success(function(data, status, xhr) {
      console.log('DONE', data);
    }).error(function(xhr, status, error) {
      console.log('ERROR', xhr, status, error);
    });

  });

});
<|endoftext|>