<commit_before>app.controller('userTimesheetController', ['$scope', '$rootScope', '$location', 'UserService', 'AuthService',
function($scope, $rootScope, $location, UserService, AuthService) {
  $scope.employees = null;
  $scope.token = null;
  var cookieObj = AuthService.getAccessToken();
  if (cookieObj != null) {
    $scope.token = cookieObj.token;
    $scope.employees = cookieObj.userObj;
  } else {
    // fetch login's userdata from service
    var userObj = UserService.getProperty();
    if(userObj) {
      if (userObj.success && userObj.data[0]) {
        $scope.employees = userObj.data[0];
      }
    } else {
        $location.path('/login');
    }
  }

  var currentDate = new Date();
  var currentMonth = currentDate.getMonth();
  // it gives 0 based result.
  var currentYear = currentDate.getFullYear();
  var monthList = ['January', 'Feburary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  $scope.weeksOptions = [];
  $scope.curYear = currentYear;
  $scope.curMonth = currentMonth;

  $scope.newCurrentYear = '';
  var timesheetArr = {};
  $scope.timesheetData = {};
  var dayArr = [] ; // store the day corresponding to the timesheet
  var weekList = ['Sunday', 'Monday','Tuesday', 'Wednesday', 'Thrusday', 'Friday', 'Saturday'];
  $rootScope.detailTimesheetByIndex = {};

  // get weeks by date in a month
  function getWeeksInMonth(month, year) {
    var weeks = [],
    firstDate = new Date(year, month, 1),
    lastDate = new Date(year, month + 1, 0),
    numDays = lastDate.getDate();
    var start = 1;
    var end = 7 - firstDate.getDay();
    weeks.push({
      'key' : '--Weeks--',
      'start' : null,
      'end' : null
    });
    while (start <= numDays) {
      var upto = start + ' to ' + end;
      weeks.push({
        'key' : upto,
        'start' : start,
        'end' : end
      });
      start = end + 1;
      end = end + 7;
      if (end > numDays)
        end = numDays;
    }
    return weeks;
  }

  // append suffix to week numbers (NOT IN USE RIGHT NOW)
  function weekSuffix(num) {
    var i = num % 10;
    var suffix = '';
    if (num == 1) {
      suffix = 'st';
    } else if (i == 2) {
      suffix = 'nd';
    } else if (i == 3) {
      suffix = 'rd';
    } else {
      suffix = 'th';
    }
    return num + suffix;
  }

  function formateDate(date, flag) {
    var momentObj = moment(date, ["DD-MM-YYYY"]);
    if (flag == 1)
      var dDay = momentObj.date();
    else if (flag == 2) {
      var dDay = momentObj.day();
      dDay = weekList[dDay];
    }
    return dDay;
  }
  function fromatHours(hours){
    var splitHrs = hours.split(':');
    var perDayMins = parseInt((splitHrs[0]*60)) + parseInt(splitHrs[1]);
    return perDayMins;
  }

  function calculatetime(timesheetData){
    var totalMins = 0;
    for(var i = 0; i < timesheetData.length; i++){
      var hours = timesheetData[i].totalHour;
      var perDayMins = fromatHours(hours);
      totalMins = parseInt(perDayMins) + parseInt(totalMins);
    }
    var perHrs = parseInt(totalMins / 60);
    var perMins = parseInt(totalMins % 60);
    totalMins = perHrs+':'+perMins;
    return totalMins;
  }
  function populateTimesheet(res){
    var localDS = {};
    var workDate = null ;
    var dDate = null;
    var dDay = null;
    var status = false;
    var monthIndex = $scope.monthsOptions.currentmonth.value;
    var yearIndex = $scope.yearOptions.current.value;
    //TODO: why added +1 in month index
    var lastDate = new Date(yearIndex, monthIndex+1, 0);
    var days = lastDate.getDate();
    var monthlyTimesheet = [];
    for(var index = 1, j = 0; index <= days; index++) {
      if (res[j] != undefined) {
        workDate = res[j].workDate;
        dDate = formateDate(workDate, 1);
        dDay = formateDate(workDate, 2);
        localDS = res[j];
        localDS.length = 1;
        localDS.day = dDate;
        localDS.dayName = dDay;
        status = false;
      } else {
        status = true;
      }

      if ((localDS.length > 0) || status){
        if(localDS.day == index) {
          monthlyTimesheet.push(localDS);
          $rootScope.detailTimesheetByIndex[workDate] = localDS;
          j++;
          localDS = {};
        } else {
          workDate = index+'-'+(monthIndex+1)+'-'+yearIndex ;
          dDate = formateDate(workDate, 1);
          dDay = formateDate(workDate, 2);
          var oneDayData = {'day': dDate, 'dayName': dDay, 'in': '0:00', 'lunchIn': '0:00', 'lunchOut': '0:00', 'nightIn': '0:00',
          'nightOut': '0:00', 'out': '0:00', 'totalHour': '0:00', 'workDate': workDate, 'workDesc': ''};
          monthlyTimesheet.push(oneDayData);
          $rootScope.detailTimesheetByIndex[workDate] = oneDayData;
        }
      }
    }
    return monthlyTimesheet;
  }

  // time sheet
  $scope.showTimesheet = function(perMonthEmpObj) {
    var totalhrs = 0;
    timesheetArr = {};
    $scope.timesheetData = {};
    var monthlyData = UserService.timesheetData(perMonthEmpObj);
    monthlyData.then(function(res){console.log(res);
      if (res.success) {
        $scope.message = '';
        if (res.data.length > 0) {
          timesheetArr = populateTimesheet(res.data);
          totalhrs = calculatetime(timesheetArr);
          timesheetArr.totalHours = totalhrs;
          $scope.timesheetData = timesheetArr;
        }
        else {
          $scope.message = 'No data available for this month !';
        }
    }, function(error){
      console.log(error);
    });
  };

  this.weekUpdate = function() {
    $scope.timesheetData = {};
    if ($scope.weekDay.start && $scope.weekDay.end) {
      var startDate = $scope.weekDay.start;
      var endDate = $scope.weekDay.end;
      $scope.weeksDateStr = weekSuffix(startDate) + ' to ' + weekSuffix(endDate);

      var i = 0;
      for (var j = 0; j < timesheetArr.length; j++) {
        if((timesheetArr[j] != undefined) && (timesheetArr[j].day >= startDate) && (timesheetArr[j].day <= endDate)) {
          $scope.timesheetData[i] = timesheetArr[j];
          i++;
        }
        $scope.timesheetData.length = i;
      }
      var totalHours = calculatetime($scope.timesheetData);
      $scope.timesheetData.totalHours = totalHours;
    } else {
      $scope.weeksDateStr = '';
      $scope.timesheetData = timesheetArr;
    }
  };
  function initializeWeek(newCurrentMonth, newCurrentYear) {
    var nweeks = getWeeksInMonth(newCurrentMonth, newCurrentYear);
    $scope.weeksOptions.weeks = nweeks;
    $scope.weekDay = $scope.weeksOptions.weeks[0];

  }

  // Initialize the week options

  if (currentMonth != '' && currentYear != '') {
    initializeWeek(currentMonth, currentYear);
  }

  // Generate month options
  function generateMonthSelectBox(start, current, selectedYear) {
    var i = 0;
    var obj = {};
    var selectOptions = [];
    if ((startYear == selectedYear) && (selectedYear != currentYear)) {
      i = start;
      obj = {
        'value' : start,
        'label' : monthList[start]
      };
      current = 11;
    } else if ((startYear == selectedYear) && (selectedYear == currentYear)) {
      i = start;
      obj = {
        'value' : current,
        'label' : monthList[current]
      };
    } else if (selectedYear == currentYear) {
      obj = {
        'value' : current,
        'label' : monthList[current]
      };

    } else {
      i = 0;
      current = 11;
      obj = {
        'value' : i,
        'label' : monthList[i]
      };
    }
    for (i; i <= current; i++) {
      selectOptions.push({
        'value' : i,
        'label' : monthList[i]
      });
    }
    selectOptions.currentmonth = obj;
    $scope.selectedMonth = obj.label;
    return selectOptions;
  }

  // Generate year options

  function generateYearSelectBox(start, current) {
    var selectOptions = [];
    for (var i = current; i >= start; i--) {
      selectOptions.push({
        'value' : i,
        'label' : i
      });
    }
    selectOptions.current = {
      'value' : current,
      'label' : current
    };
    return selectOptions;
  }

  //Restrict the month and year to date of joining

  var cookieObj = AuthService.getAccessToken();
  if (cookieObj) {
    $scope.employees = cookieObj.userObj;
    $scope.token = cookieObj.token;
  } else {
    // fetch login's userdata from service
    var userObj = UserService.getProperty();
    if (userObj != '') {
      if (userObj.success && userObj.data[0]) {
        $scope.employees = userObj.data[0];
        $scope.token = userObj.data[1];
      }
    } else {
      $location.path('/login');
    }
  }
  if ($scope.employees != null) {
    var doj = parseInt($scope.employees.doj);
    var dojYear = new Date(doj);
    var startYear = dojYear.getFullYear();
    $scope.yearOptions = generateYearSelectBox(startYear, currentYear);
    var startMonth = dojYear.getMonth();
    $scope.monthsOptions = generateMonthSelectBox(startMonth, currentMonth, currentYear);
    var monthLabel = $scope.selectedMonth;
    var perMonthEmpObj = {'empId': $scope.employees.id, 'year': currentYear, 'month': monthLabel, 'token': $scope.token.token};
    $scope.showTimesheet(perMonthEmpObj);
  }
  // Update year
  this.yearUpdate = function() {
    var newCurrentYear = $scope.yearOptions.current.value;
    $scope.monthsOptions = generateMonthSelectBox(startMonth, currentMonth, newCurrentYear);
    $scope.weeksDateStr = '';
    initializeWeek(currentMonth, newCurrentYear);
    var monthLabel = $scope.selectedMonth;
    var perMonthEmpObj = {'empId': $scope.employees.id, 'year': newCurrentYear, 'month': monthLabel, 'token': $scope.token.token};
    $scope.showTimesheet(perMonthEmpObj);
  };

  // Update Month

  this.monthUpdate = function() {
    var newCurrentMonth = $scope.monthsOptions.currentmonth.value;
    var newCurrentYear = $scope.yearOptions.current.value;
    $scope.selectedMonth = monthList[newCurrentMonth];
    initializeWeek(newCurrentMonth, newCurrentYear);
    $scope.weeksDateStr = '';
    var monthLabel = $scope.selectedMonth;
    var perMonthEmpObj = {'empId': $scope.employees.id, 'year': newCurrentYear, 'month': monthLabel, 'token': $scope.token.token};
    $scope.showTimesheet(perMonthEmpObj);
  };
  //email excel sheet
  $scope.emailme = function() {
    if ($scope.employees != null) {
      var month = $scope.monthsOptions.currentmonth.label;
      var year = $scope.yearOptions.current.value;
      //var emailTimesheetObj = {empId: ($scope.employees.id).toString(), month: month, year: year.toString() };
      var emailPromise = UserService.emailme(userObj);
      emailPromise.then(function(res) {
        $scope.message = res.data;
        if ($scope.message.length > 0) {
          $scope.message = $scope.message[0].msg;
        }
      }, function(error) {
        console.log(error);
      });
    }
  };
  // logout user
  $scope.logout = function() {
    var status = UserService.endSession();
    if (status) {
      $location.path('/login');
    }
  };

}]);<commit_msg>conflict resolve<commit_after>app.controller('userTimesheetController', ['$scope', '$rootScope', '$location', 'UserService', 'AuthService',
function($scope, $rootScope, $location, UserService, AuthService) {
  $scope.employees = null;
  $scope.token = null;
  var cookieObj = AuthService.getAccessToken();
  if (cookieObj != null) {
    $scope.token = cookieObj.token;
    $scope.employees = cookieObj.userObj;
  } else {
    // fetch login's userdata from service
    var userObj = UserService.getProperty();
    if(userObj) {
      if (userObj.success && userObj.data[0]) {
        $scope.employees = userObj.data[0];
      }
    } else {
        $location.path('/login');
    }
  }

  var currentDate = new Date();
  var currentMonth = currentDate.getMonth();
  // it gives 0 based result.
  var currentYear = currentDate.getFullYear();
  var monthList = ['January', 'Feburary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  $scope.weeksOptions = [];
  $scope.curYear = currentYear;
  $scope.curMonth = currentMonth;

  $scope.newCurrentYear = '';
  var timesheetArr = {};
  $scope.timesheetData = {};
  var dayArr = [] ; // store the day corresponding to the timesheet
  var weekList = ['Sunday', 'Monday','Tuesday', 'Wednesday', 'Thrusday', 'Friday', 'Saturday'];
  $rootScope.detailTimesheetByIndex = {};

  // get weeks by date in a month
  function getWeeksInMonth(month, year) {
    var weeks = [],
    firstDate = new Date(year, month, 1),
    lastDate = new Date(year, month + 1, 0),
    numDays = lastDate.getDate();
    var start = 1;
    var end = 7 - firstDate.getDay();
    weeks.push({
      'key' : '--Weeks--',
      'start' : null,
      'end' : null
    });
    while (start <= numDays) {
      var upto = start + ' to ' + end;
      weeks.push({
        'key' : upto,
        'start' : start,
        'end' : end
      });
      start = end + 1;
      end = end + 7;
      if (end > numDays)
        end = numDays;
    }
    return weeks;
  }

  // append suffix to week numbers (NOT IN USE RIGHT NOW)
  function weekSuffix(num) {
    var i = num % 10;
    var suffix = '';
    if (num == 1) {
      suffix = 'st';
    } else if (i == 2) {
      suffix = 'nd';
    } else if (i == 3) {
      suffix = 'rd';
    } else {
      suffix = 'th';
    }
    return num + suffix;
  }

  function formateDate(date, flag) {
    var momentObj = moment(date, ["DD-MM-YYYY"]);
    if (flag == 1)
      var dDay = momentObj.date();
    else if (flag == 2) {
      var dDay = momentObj.day();
      dDay = weekList[dDay];
    }
    return dDay;
  }
  function fromatHours(hours){
    var splitHrs = hours.split(':');
    var perDayMins = parseInt((splitHrs[0]*60)) + parseInt(splitHrs[1]);
    return perDayMins;
  }

  function calculatetime(timesheetData){
    var totalMins = 0;
    for(var i = 0; i < timesheetData.length; i++){
      var hours = timesheetData[i].totalHour;
      var perDayMins = fromatHours(hours);
      totalMins = parseInt(perDayMins) + parseInt(totalMins);
    }
    var perHrs = parseInt(totalMins / 60);
    var perMins = parseInt(totalMins % 60);
    totalMins = perHrs+':'+perMins;
    return totalMins;
  }
  function populateTimesheet(res){
    var localDS = {};
    var workDate = null ;
    var dDate = null;
    var dDay = null;
    var status = false;
    var monthIndex = $scope.monthsOptions.currentmonth.value;
    var yearIndex = $scope.yearOptions.current.value;
    //TODO: why added +1 in month index
    var lastDate = new Date(yearIndex, monthIndex+1, 0);
    var days = lastDate.getDate();
    var monthlyTimesheet = [];
    for(var index = 1, j = 0; index <= days; index++) {
      if (res[j] != undefined) {
        workDate = res[j].workDate;
        dDate = formateDate(workDate, 1);
        dDay = formateDate(workDate, 2);
        localDS = res[j];
        localDS.length = 1;
        localDS.day = dDate;
        localDS.dayName = dDay;
        status = false;
      } else {
        status = true;
      }

      if ((localDS.length > 0) || status){
        if(localDS.day == index) {
          monthlyTimesheet.push(localDS);
          $rootScope.detailTimesheetByIndex[workDate] = localDS;
          j++;
          localDS = {};
        } else {
          workDate = index+'-'+(monthIndex+1)+'-'+yearIndex ;
          dDate = formateDate(workDate, 1);
          dDay = formateDate(workDate, 2);
          var oneDayData = {'day': dDate, 'dayName': dDay, 'in': '0:00', 'lunchIn': '0:00', 'lunchOut': '0:00', 'nightIn': '0:00',
          'nightOut': '0:00', 'out': '0:00', 'totalHour': '0:00', 'workDate': workDate, 'workDesc': ''};
          monthlyTimesheet.push(oneDayData);
          $rootScope.detailTimesheetByIndex[workDate] = oneDayData;
        }
      }
    }
    return monthlyTimesheet;
  }

  // time sheet
  $scope.showTimesheet = function(perMonthEmpObj) {
    var totalhrs = 0;
    timesheetArr = {};
    $scope.timesheetData = {};
    var monthlyData = UserService.timesheetData(perMonthEmpObj);
    monthlyData.then(function(res){
      if (res.success) {
        $scope.message = '';
        if (res.data.length > 0) {
          timesheetArr = populateTimesheet(res.data);
          totalhrs = calculatetime(timesheetArr);
          timesheetArr.totalHours = totalhrs;
          $scope.timesheetData = timesheetArr;
        }
        else {
          $scope.message = 'No data available for this month !';
        }
      }
    }, function(error){
      console.log(error);
    });
  };

  this.weekUpdate = function() {
    $scope.timesheetData = {};
    if ($scope.weekDay.start && $scope.weekDay.end) {
      var startDate = $scope.weekDay.start;
      var endDate = $scope.weekDay.end;
      $scope.weeksDateStr = weekSuffix(startDate) + ' to ' + weekSuffix(endDate);

      var i = 0;
      for (var j = 0; j < timesheetArr.length; j++) {
        if((timesheetArr[j] != undefined) && (timesheetArr[j].day >= startDate) && (timesheetArr[j].day <= endDate)) {
          $scope.timesheetData[i] = timesheetArr[j];
          i++;
        }
        $scope.timesheetData.length = i;
      }
      var totalHours = calculatetime($scope.timesheetData);
      $scope.timesheetData.totalHours = totalHours;
    } else {
      $scope.weeksDateStr = '';
      $scope.timesheetData = timesheetArr;
    }
  };
  function initializeWeek(newCurrentMonth, newCurrentYear) {
    var nweeks = getWeeksInMonth(newCurrentMonth, newCurrentYear);
    $scope.weeksOptions.weeks = nweeks;
    $scope.weekDay = $scope.weeksOptions.weeks[0];

  }

  // Initialize the week options

  if (currentMonth != '' && currentYear != '') {
    initializeWeek(currentMonth, currentYear);
  }

  // Generate month options
  function generateMonthSelectBox(start, current, selectedYear) {
    var i = 0;
    var obj = {};
    var selectOptions = [];
    if ((startYear == selectedYear) && (selectedYear != currentYear)) {
      i = start;
      obj = {
        'value' : start,
        'label' : monthList[start]
      };
      current = 11;
    } else if ((startYear == selectedYear) && (selectedYear == currentYear)) {
      i = start;
      obj = {
        'value' : current,
        'label' : monthList[current]
      };
    } else if (selectedYear == currentYear) {
      obj = {
        'value' : current,
        'label' : monthList[current]
      };

    } else {
      i = 0;
      current = 11;
      obj = {
        'value' : i,
        'label' : monthList[i]
      };
    }
    for (i; i <= current; i++) {
      selectOptions.push({
        'value' : i,
        'label' : monthList[i]
      });
    }
    selectOptions.currentmonth = obj;
    $scope.selectedMonth = obj.label;
    return selectOptions;
  }

  // Generate year options

  function generateYearSelectBox(start, current) {
    var selectOptions = [];
    for (var i = current; i >= start; i--) {
      selectOptions.push({
        'value' : i,
        'label' : i
      });
    }
    selectOptions.current = {
      'value' : current,
      'label' : current
    };
    return selectOptions;
  }

  //Restrict the month and year to date of joining

  var cookieObj = AuthService.getAccessToken();
  if (cookieObj) {
    $scope.employees = cookieObj.userObj;
    $scope.token = cookieObj.token;
  } else {
    // fetch login's userdata from service
    var userObj = UserService.getProperty();
    if (userObj != '') {
      if (userObj.success && userObj.data[0]) {
        $scope.employees = userObj.data[0];
        $scope.token = userObj.data[1];
      }
    } else {
      $location.path('/login');
    }
  }
  if ($scope.employees != null) {
    var doj = parseInt($scope.employees.doj);
    var dojYear = new Date(doj);
    var startYear = dojYear.getFullYear();
    $scope.yearOptions = generateYearSelectBox(startYear, currentYear);
    var startMonth = dojYear.getMonth();
    $scope.monthsOptions = generateMonthSelectBox(startMonth, currentMonth, currentYear);
    var monthLabel = $scope.selectedMonth;
    var perMonthEmpObj = {'empId': $scope.employees.id, 'year': currentYear, 'month': monthLabel, 'token': $scope.token.token};
    $scope.showTimesheet(perMonthEmpObj);
  }
  // Update year
  this.yearUpdate = function() {
    var newCurrentYear = $scope.yearOptions.current.value;
    $scope.monthsOptions = generateMonthSelectBox(startMonth, currentMonth, newCurrentYear);
    $scope.weeksDateStr = '';
    initializeWeek(currentMonth, newCurrentYear);
    var monthLabel = $scope.selectedMonth;
    var perMonthEmpObj = {'empId': $scope.employees.id, 'year': newCurrentYear, 'month': monthLabel, 'token': $scope.token.token};
    $scope.showTimesheet(perMonthEmpObj);
  };

  // Update Month

  this.monthUpdate = function() {
    var newCurrentMonth = $scope.monthsOptions.currentmonth.value;
    var newCurrentYear = $scope.yearOptions.current.value;
    $scope.selectedMonth = monthList[newCurrentMonth];
    initializeWeek(newCurrentMonth, newCurrentYear);
    $scope.weeksDateStr = '';
    var monthLabel = $scope.selectedMonth;
    var perMonthEmpObj = {'empId': $scope.employees.id, 'year': newCurrentYear, 'month': monthLabel, 'token': $scope.token.token};
    $scope.showTimesheet(perMonthEmpObj);
  };
  //email excel sheet
  $scope.emailme = function() {
    if ($scope.employees != null) {
      var month = $scope.monthsOptions.currentmonth.label;
      var year = $scope.yearOptions.current.value;
      //var emailTimesheetObj = {empId: ($scope.employees.id).toString(), month: month, year: year.toString() };
      var emailPromise = UserService.emailme(userObj);
      emailPromise.then(function(res) {
        $scope.message = res.data;
        if ($scope.message.length > 0) {
          $scope.message = $scope.message[0].msg;
        }
      }, function(error) {
        console.log(error);
      });
    }
  };
  // logout user
  $scope.logout = function() {
    var status = UserService.endSession();
    if (status) {
      $location.path('/login');
    }
  };

}]);<|endoftext|>


<commit_before>/**
 * Created by zbeboy on 2017/7/20.
 */
require(["jquery", "nav_active", "handlebars", "messenger", "jquery.address",
    "jquery.showLoading", "tablesaw", "bootstrap"], function ($, nav_active, Handlebars) {
    /*
     ajax url.
     */
    var ajax_url = {
        data_url: '/anyone/graduate/design/defense/order/data',
        timer_url: '/web/graduate/design/reorder/timer',
        back: '/web/menu/graduate/design/reorder'
    };

    /*
     参数id
     */
    var paramId = {
        studentName: '#search_student_name',
        studentNumber: '#search_student_number'
    };

    /*
     参数
     */
    var param = {
        graduationDesignReleaseId: init_page_param.graduationDesignReleaseId,
        defenseGroupId: init_page_param.defenseGroupId,
        studentName: $(paramId.studentName).val(),
        studentNumber: $(paramId.studentNumber).val()
    };

    // 刷新时选中菜单
    nav_active(ajax_url.back);

    function startLoading() {
        // 显示遮罩
        $('#page-wrapper').showLoading();
    }

    function endLoading() {
        // 去除遮罩
        $('#page-wrapper').hideLoading();
    }

    $('#refresh').click(function () {
        init();
    });

    /*
     清空参数
     */
    function cleanParam() {
        $(paramId.studentName).val('');
        $(paramId.studentNumber).val('');
    }

    /**
     * 刷新查询参数
     */
    function refreshSearch() {
        param.studentName = $(paramId.studentName).val();
        param.studentNumber = $(paramId.studentNumber).val();
    }

    /*
     搜索
     */
    $('#search').click(function () {
        refreshSearch();
        init();
    });

    /*
     重置
     */
    $('#reset_search').click(function () {
        cleanParam();
        refreshSearch();
        init();
    });

    $(paramId.studentName).keyup(function (event) {
        if (event.keyCode === 13) {
            refreshSearch();
            init();
        }
    });

    $(paramId.studentNumber).keyup(function (event) {
        if (event.keyCode === 13) {
            refreshSearch();
            init();
        }
    });

    var tableData = '#tableData';

    /*
     返回
     */
    $('#page_back').click(function () {
        $.address.value(ajax_url.back);
    });

    init();

    function init() {
        startLoading();
        $.get(web_path + ajax_url.data_url, param, function (data) {
            endLoading();
            if (data.state) {
                listData(data);
            } else {
                Messenger().post({
                    message: data.msg,
                    type: 'error',
                    showCloseButton: true
                });
            }
        });
    }

    /**
     * 列表数据
     * @param data 数据
     */
    function listData(data) {
        var template = Handlebars.compile($("#order-template").html());
        Handlebars.registerHelper('subject', function () {
            var v = '';
            if (this.subject !== null) {
                if (this.subject.length > 5) {
                    v = this.subject.substring(0, 5) + '...';
                } else {
                    v = this.subject;
                }
            }
            return '<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="' + this.subject + '">' + v + '</button>';
        });

        Handlebars.registerHelper('operator', function () {
            return buildOperatorButton(this);
        });

        Handlebars.registerHelper('defense_status', function () {
            var v = '';
            if(this.defenseStatus === 0){
                v = '未开始';
            } else if(this.defenseStatus === 1){
                v = '进行中';
            } else if(this.defenseStatus === 2){
                v = '已结束';
            } else if(this.defenseStatus === 3){
                v = '缺席';
            }
            return new Handlebars.SafeString(Handlebars.escapeExpression(v));
        });

        $(tableData).html(template(data));
        $('[data-toggle="tooltip"]').tooltip();
        $('#tablesawTable').tablesaw().data("tablesaw").refresh();
    }

    /**
     * 构建操作按钮
     * @param c
     */
    function buildOperatorButton(c) {
        // 预编译模板
        var template = Handlebars.compile($("#operator_button").html());
        var context =
            {
                func: [
                    {
                        "name": "计时",
                        "css": "timer",
                        "type": "primary",
                        "defenseOrderId": c.defenseOrderId,
                        "sortNum": c.sortNum,
                        "studentName": c.studentName
                    },
                    {
                        "name": "问题",
                        "css": "",
                        "type": "default",
                        "defenseOrderId": c.defenseOrderId,
                        "sortNum": c.sortNum,
                        "studentName": c.studentName
                    }
                ]
            };

        // 是管理员或系统
        if (init_page_param.reorderIsSuper) {
            context =
                {
                    func: [
                        {
                            "name": "计时",
                            "css": "timer",
                            "type": "primary",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "状态",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "打分",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "成绩",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "问题",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        }
                    ]
                };
        } else if (init_page_param.reorderIsLeader) {
            context =
                {
                    func: [
                        {
                            "name": "计时",
                            "css": "timer",
                            "type": "primary",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "状态",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "打分",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "成绩",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "问题",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        }
                    ]
                };
        } else if (init_page_param.reorderIsSecretary) {
            context =
                {
                    func: [
                        {
                            "name": "计时",
                            "css": "timer",
                            "type": "primary",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "状态",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "成绩",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "问题",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        }
                    ]
                };
        } else if (init_page_param.reorderIsMember) {
            context =
                {
                    func: [
                        {
                            "name": "计时",
                            "css": "timer",
                            "type": "primary",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "打分",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "问题",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        }
                    ]
                };
        }

        return template(context);
    }

    /*
     设置
     */
    $(tableData).delegate('.timer', "click", function () {
        var id = $(this).attr('data-id');
        var name = $(this).attr('data-student');
        $('#timerDefenseOrderId').val(id);
        $('#timerModalLabel').text(name);
        $('#timerModal').modal('show');
    });

    // 计时
    $('#toTimer').click(function () {
        var id = $('#timerDefenseOrderId').val();
        var timer = Math.round(Number($('#timerInput').val()));
        $('#timerModal').modal('hide');
        window.open(web_path + ajax_url.timer_url + '?defenseOrderId=' + id + '&timer=' + timer);
    });

});<commit_msg>毕业设计答辩顺序动态菜单<commit_after>/**
 * Created by zbeboy on 2017/7/20.
 */
require(["jquery", "nav_active", "handlebars", "messenger", "jquery.address",
    "jquery.showLoading", "tablesaw", "bootstrap"], function ($, nav_active, Handlebars) {
    /*
     ajax url.
     */
    var ajax_url = {
        data_url: '/anyone/graduate/design/defense/order/data',
        timer_url: '/web/graduate/design/reorder/timer',
        back: '/web/menu/graduate/design/reorder'
    };

    /*
     参数id
     */
    var paramId = {
        studentName: '#search_student_name',
        studentNumber: '#search_student_number'
    };

    /*
     参数
     */
    var param = {
        graduationDesignReleaseId: init_page_param.graduationDesignReleaseId,
        defenseGroupId: init_page_param.defenseGroupId,
        studentName: $(paramId.studentName).val(),
        studentNumber: $(paramId.studentNumber).val()
    };

    // 刷新时选中菜单
    nav_active(ajax_url.back);

    function startLoading() {
        // 显示遮罩
        $('#page-wrapper').showLoading();
    }

    function endLoading() {
        // 去除遮罩
        $('#page-wrapper').hideLoading();
    }

    $('#refresh').click(function () {
        init();
    });

    /*
     清空参数
     */
    function cleanParam() {
        $(paramId.studentName).val('');
        $(paramId.studentNumber).val('');
    }

    /**
     * 刷新查询参数
     */
    function refreshSearch() {
        param.studentName = $(paramId.studentName).val();
        param.studentNumber = $(paramId.studentNumber).val();
    }

    /*
     搜索
     */
    $('#search').click(function () {
        refreshSearch();
        init();
    });

    /*
     重置
     */
    $('#reset_search').click(function () {
        cleanParam();
        refreshSearch();
        init();
    });

    $(paramId.studentName).keyup(function (event) {
        if (event.keyCode === 13) {
            refreshSearch();
            init();
        }
    });

    $(paramId.studentNumber).keyup(function (event) {
        if (event.keyCode === 13) {
            refreshSearch();
            init();
        }
    });

    var tableData = '#tableData';

    /*
     返回
     */
    $('#page_back').click(function () {
        $.address.value(ajax_url.back);
    });

    init();

    function init() {
        startLoading();
        $.get(web_path + ajax_url.data_url, param, function (data) {
            endLoading();
            if (data.state) {
                listData(data);
            } else {
                Messenger().post({
                    message: data.msg,
                    type: 'error',
                    showCloseButton: true
                });
            }
        });
    }

    /**
     * 列表数据
     * @param data 数据
     */
    function listData(data) {
        var template = Handlebars.compile($("#order-template").html());
        Handlebars.registerHelper('subject', function () {
            var v = '';
            if (this.subject !== null) {
                if (this.subject.length > 5) {
                    v = this.subject.substring(0, 5) + '...';
                } else {
                    v = this.subject;
                }
            }
            return '<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="' + this.subject + '">' + v + '</button>';
        });

        Handlebars.registerHelper('operator', function () {
            return buildOperatorButton(this);
        });

        Handlebars.registerHelper('defense_status', function () {
            var v = '';
            if(this.defenseStatus === 0){
                v = '未开始';
            } else if(this.defenseStatus === 1){
                v = '进行中';
            } else if(this.defenseStatus === 2){
                v = '已结束';
            } else if(this.defenseStatus === 3){
                v = '缺席';
            }
            return new Handlebars.SafeString(Handlebars.escapeExpression(v));
        });

        $(tableData).html(template(data));
        $('[data-toggle="tooltip"]').tooltip();
        $('#tablesawTable').tablesaw().data("tablesaw").refresh();
    }

    /**
     * 构建操作按钮
     * @param c
     */
    function buildOperatorButton(c) {
        // 预编译模板
        var template = Handlebars.compile($("#operator_button").html());
        var context =
            {
                func: [
                    {
                        "name": "计时",
                        "css": "timer",
                        "type": "primary",
                        "defenseOrderId": c.defenseOrderId,
                        "sortNum": c.sortNum,
                        "studentName": c.studentName
                    },
                    {
                        "name": "问题",
                        "css": "",
                        "type": "default",
                        "defenseOrderId": c.defenseOrderId,
                        "sortNum": c.sortNum,
                        "studentName": c.studentName
                    }
                ]
            };

        // 是管理员或系统
        if (init_page_param.reorderIsSuper) {
            context =
                {
                    func: [
                        {
                            "name": "计时",
                            "css": "timer",
                            "type": "primary",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "状态",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "成绩",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "问题",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        }
                    ]
                };
        } else if (init_page_param.reorderIsLeader) {
            context =
                {
                    func: [
                        {
                            "name": "计时",
                            "css": "timer",
                            "type": "primary",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "状态",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "打分",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "成绩",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "问题",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        }
                    ]
                };
        } else if (init_page_param.reorderIsSecretary) {
            context =
                {
                    func: [
                        {
                            "name": "计时",
                            "css": "timer",
                            "type": "primary",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "状态",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "成绩",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "问题",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        }
                    ]
                };
        } else if (init_page_param.reorderIsMember) {
            context =
                {
                    func: [
                        {
                            "name": "计时",
                            "css": "timer",
                            "type": "primary",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "打分",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        },
                        {
                            "name": "问题",
                            "css": "",
                            "type": "default",
                            "defenseOrderId": c.defenseOrderId,
                            "sortNum": c.sortNum,
                            "studentName": c.studentName
                        }
                    ]
                };
        }

        return template(context);
    }

    /*
     设置
     */
    $(tableData).delegate('.timer', "click", function () {
        var id = $(this).attr('data-id');
        var name = $(this).attr('data-student');
        $('#timerDefenseOrderId').val(id);
        $('#timerModalLabel').text(name);
        $('#timerModal').modal('show');
    });

    // 计时
    $('#toTimer').click(function () {
        var id = $('#timerDefenseOrderId').val();
        var timer = Math.round(Number($('#timerInput').val()));
        $('#timerModal').modal('hide');
        window.open(web_path + ajax_url.timer_url + '?defenseOrderId=' + id + '&timer=' + timer);
    });

});<|endoftext|>


<commit_before>/**
 * UI module for server model tool.
 *
 * @author Tim.Liu
 * @created 2013.10.01
 */

;(function(app){

	var context = app.Context.get('_Dev');
	var module = context.module('ServerModelGen');

	_.extend(module, {

		label: _.string.titleize(_.string.humanize(module.moduleName)),
		icon: 'icon-plus-sign',

		View: {
			ModelListItem: Backbone.Marionette.ItemView.extend({
				template: '#custom-module-_dev-servermodelgen-modelitem-tpl',
				tagName: 'span',
				onRender: function(){
					var size = 70;
					this.$el.css({
						backgroundColor: '#eee',
						borderRadius: size + 'px',
						width: size + 'px',
						height: size + 'px',
						textAlign: 'center',
						lineHeight: size * 0.95 + 'px',
						marginLeft: size/10 + 'px',
						cursor:'pointer',
						float: 'left'
					});
				}
			}),
			ModelList: Backbone.Marionette.CompositeView.extend({
				template: '#custom-module-_dev-servermodelgen-modellist-tpl',
				itemViewContainer: '[item-view-ct]',
				initialize: function(options){
					this.itemView = options.itemView || module.View.ModelListItem;
				},
				onShow:function(){
					this.collection.fetch();
				}
			}),

			ModelFormField: Backbone.Marionette.ItemView.extend({
				template: '#custom-module-_dev-servermodelgen-modelform-field-tpl',
				initialize: function(options){
					this.model.set('cid', this.model.cid);
				}
			}),

			ModelForm: Backbone.Marionette.CompositeView.extend({
				template: '#custom-module-_dev-servermodelgen-modelform-tpl',
				itemViewContainer: '[model-field-list]',
				initialize: function(options){
					this.itemView = options.itemView || module.View.ModelFormField;
				},
				onShow: function(){
					this.$el.css({
						padding: '10px',
						borderTop: '5px dotted #eee'
					});
				},
				ui: {
					'modelNameInput': '[name=modelname]'
				}
			}),

			Default: Backbone.Marionette.Layout.extend({
				template: '#custom-module-_dev-servermodelgen-tpl',
				className: 'tab-pane',
				regions: {
					'list': '[region=modellist]',
					'form': '[region=addmodel]'
				},
				onShow: function(){
					this.list.show(new module.View.ModelList({
						collection: new (Backbone.Collection.extend({
							url: '/dev/models/',
							parse: function(res){
								var models = _.map(res, function(modelPath, modelName){
									return {name: modelName, path: modelPath};
								});
								return _.sortBy(models, function(m){
									return m.path;
								}).reverse();
							}
						}))
					}));
					//TBI: hook up the model search input.

				},
				//General Actions
				events: {
					'click [action]': '_doAction'
				},
				_doAction: function(e){
					e.stopPropagation();
					var $el = $(e.currentTarget);
					var doer = this.actions[$el.attr('action')];
					if(doer) {
						doer = _.bind(doer, this);
						doer($el);
					}else throw new Error('DEV::DEV Tools::You have not yet implemented this action');
				},
				actions: {
					showNewModelForm: function($action){
						if($action.hasClass('disabled'))
							return;
						this.form.show(new module.View.ModelForm({
							collection: new Backbone.Collection([{
								fieldName: '',
								type: 'UNKNOWN'
							}])
						}));
						$action.addClass('disabled'); //disable the button
					},

					addField: function($action){
						this.form.currentView.collection.add({
								fieldName: '',
								type: 'UNKNOWN'
						});
					},

					removeField: function($action){
						var target = $action.attr('cid');
						if(this.form.currentView.collection.length > 1)
							this.form.currentView.collection.remove(target);
					},

					cancelModelForm: function($action){
						this.form.close();
						this.list.getEl('span[action=showNewModelForm]').removeClass('disabled');
					},

					submitModelDef: function($action){
						var name = this.form.currentView.ui.modelNameInput.val();
						var fNames = this.form.getEl('[name=fieldname]').map(function(index, el){
							return _.string.slugify($(this).val());
						}).get();
						var fTypes = this.form.getEl('[name=fieldtype]').map(function(index, el){
							return $(this).val();
						}).get();
						var fields = _.object(fNames, fTypes);
						$.ajax({
							url: '/dev/models/',
							type: 'POST',
							notify: true,
							contentType: 'application/json',
							data: JSON.stringify({
								name: _.string.classify(name),
								fields: fields
							}),
							success: _.bind(function(res){
								this.form.getEl('span[action=cancelModelForm]').click();
							}, this)
						})
					},

					refreshModelList: function($action){
						this.list.currentView.collection.fetch();
					}
				}
			})
		}

	});

})(Application);

Template.extend('custom-module-_dev-servermodelgen-modelitem-tpl',
[
	'{{name}}'
]
);

Template.extend('custom-module-_dev-servermodelgen-modellist-tpl',
[
	'

',
	'
',
		'',
		'<input type="text" placeholder="Find Model..." class="input input-medium">', //model search/filter box
		' Server Model', //+ Server Model button, show model form.
		' Refresh List',
	'
'
]
);

Template.extend('custom-module-_dev-servermodelgen-modelform-field-tpl', //single field inputs row
[
	'
',
		'<input class="span3" name="fieldname" type="text" placeholder="Name of the variable/field">', //field name input
		'<input class="span2" name="fieldtype" type="text" placeholder="Type of the field">', //field type input
		'', //remove field
	'
'
]
);

Template.extend('custom-module-_dev-servermodelgen-modelform-tpl',
[
	'
',
		'Name',
		'
',
			'<input type="text" name="modelname" id="inputModelName" placeholder="Your Model Name Here...">', //model name input
		'
',
	'
',
		'
', //help text on available field types [+]
			'
Available Types: String, Number, Date, Buffer, Boolean, Mixed, Objectid, Array
',
			'e.g [String] or [Number]',
			'or [\'Your Model Name\'] - shortcut for [Objectid] ref:\'Your Model\'',
			'or ^[\'Your Model Name\'] - sub:\'Your Model\' see - /util/objectfactory.js',
			'MongooseJS Schema Types see - http://mongoosejs.com/docs/schematypes.html',
		'
', //help text on available field types [.]
	'
Fields
', //add field
	'

',
	'
Submit Cancel
' //submit model or cancel.
]
);

Template.extend('custom-module-_dev-servermodelgen-tpl',
[
	'

',
	'

'
]);
<commit_msg>Finished preview model definition in servermodelgen<commit_after>/**
 * UI module for server model tool.
 *
 * @author Tim.Liu
 * @created 2013.10.01
 */

;(function(app){

	var context = app.Context.get('_Dev');
	var module = context.module('ServerModelGen');

	_.extend(module, {

		label: _.string.titleize(_.string.humanize(module.moduleName)),
		icon: 'icon-plus-sign',
		toolURL: '/dev/models/',

		View: {

			//------------Model List--------------
			ModelListItemDetail: Backbone.Marionette.ItemView.extend({
				template: '#custom-module-_dev-servermodelgen-modelitem-detail-tpl',

			}),

			ModelListItem: Backbone.Marionette.ItemView.extend({
				template: '#custom-module-_dev-servermodelgen-modelitem-tpl',
				className: 'tool-servergen-model-list-item',
				ui: {
					model: 'span[model]' //for locating the model tpl tags. (used for tooltip)
				},
				onRender: function(){
					var size = 70;
					this.$el.css({
						backgroundColor: '#eee',
						borderRadius: size + 'px',
						width: size + 'px',
						height: size + 'px',
						textAlign: 'center',
						lineHeight: size * 0.95 + 'px',
						marginLeft: size/10 + 'px',
						cursor:'pointer',
						float:'left',
					}).tooltip({
						title: _.bind(function(){
							return this.ui.model.attr('path');
						}, this)
					});
				},
				events: {
					'click': function(e){
						if(e.target !== e.currentTarget) { //let the event pass to View.Default's action event handler;
							return;
						}
						e.stopPropagation();
						this.ui.model.click(); //pass the click event to model tpl span[action]
					}
				}
			}),

			ModelList: Backbone.Marionette.CompositeView.extend({
				template: '#custom-module-_dev-servermodelgen-modellist-tpl',
				itemViewContainer: '[item-view-ct]',
				initialize: function(options){
					this.itemView = options.itemView || module.View.ModelListItem;
				},
				onShow:function(){
					this.collection.fetch();
				}
			}),
			//-------------Form------------
			ModelFormField: Backbone.Marionette.ItemView.extend({
				template: '#custom-module-_dev-servermodelgen-modelform-field-tpl',
				initialize: function(options){
					this.model.set('cid', this.model.cid);
				}
			}),

			ModelForm: Backbone.Marionette.CompositeView.extend({
				template: '#custom-module-_dev-servermodelgen-modelform-tpl',
				itemViewContainer: '[model-field-list]',
				initialize: function(options){
					this.itemView = options.itemView || module.View.ModelFormField;
				},
				onShow: function(){
					this.$el.css({
						padding: '10px',
						borderTop: '5px dotted #eee'
					});
				},
				ui: {
					'modelNameInput': '[name=modelname]'
				}
			}),

			//----------Default View [as action coordinator]---------
			Default: Backbone.Marionette.Layout.extend({
				template: '#custom-module-_dev-servermodelgen-tpl',
				className: 'tab-pane',
				regions: {
					'list': '[region=modellist]',
					'form': '[region=addmodel]'
				},
				initialize: function(options){
					//bind all action listeners and util funcs to this.
					var that = this;
					_.each(['actions', 'utils'], function(funcGroup){
						_.each(that[funcGroup], function(func, name){
							that[funcGroup][name] = _.bind(func, that);
						});
					});
				},
				onShow: function(){
					this.list.show(new module.View.ModelList({
						collection: new (Backbone.Collection.extend({
							url: module.toolURL,
							parse: function(res){
								var models = _.map(res, function(modelPath, modelName){
									return {name: modelName, path: modelPath};
								});
								return _.sortBy(models, function(m){
									return m.path;
								}).reverse();
							}
						}))
					}));
					//TBI: hook up the model search input.

				},
				//========General Actions==========
				events: {
					'click [action]': '_doAction'
				},
				_doAction: function(e){
					e.stopPropagation();
					var $el = $(e.currentTarget);
					var doer = this.actions[$el.attr('action')];
					if(doer) {
						doer($el);
					}else throw new Error('DEV::DEV Tools::You have not yet implemented this action');
				},
				actions: {
					showNewModelForm: function($action){
						if($action.hasClass('disabled'))
							return;
						this.utils.clearModelSelection();//clear model listing selection highlight first;
						this.form.show(new module.View.ModelForm({
							collection: new Backbone.Collection([{
								fieldName: '',
								type: 'UNKNOWN'
							}])
						}));
						$action.addClass('disabled'); //disable the button
					},

					addField: function($action){
						this.form.currentView.collection.add({
								fieldName: '',
								type: 'UNKNOWN'
						});
					},

					removeField: function($action){
						var target = $action.attr('cid');
						if(this.form.currentView.collection.length > 1)
							this.form.currentView.collection.remove(target);
					},

					cancelModelForm: function($action){
						this.form.close();
						this.list.getEl('span[action=showNewModelForm]').removeClass('disabled');
					},

					submitModelDef: function($action){
						var name = this.form.currentView.ui.modelNameInput.val();
						var fNames = this.form.getEl('[name=fieldname]').map(function(index, el){
							return _.string.slugify($(this).val());
						}).get();
						var fTypes = this.form.getEl('[name=fieldtype]').map(function(index, el){
							return $(this).val();
						}).get();
						var fields = _.object(fNames, fTypes);
						$.ajax({
							url: module.toolURL,
							type: 'POST',
							notify: true,
							contentType: 'application/json',
							data: JSON.stringify({
								name: _.string.classify(name),
								fields: fields
							}),
							success: _.bind(function(res){
								this.form.getEl('span[action=cancelModelForm]').click();
							}, this)
						})
					},

					refreshModelList: function($action){
						this.list.currentView.collection.fetch();
					},

					showModelDefDetails: function($action){
						$.ajax({
							url: module.toolURL + $action.attr('model'),
							success: _.bind(function(res){
								/*WARNING::Hardcoded Section::According to server model definition structure*/
								//pre-process the model description
								var modeldetails = _.extend({fields: {}}, _.pick(res, 'meta', 'restriction'));
								_.each(res.Schema.paths, function(description, fieldName){
									var type = description.instance || (description.caster && description.caster.instance);
									if(description.caster){
										//array
										if(res.meta.ref && res.meta.ref[fieldName]){
											type = "ref:'" + res.meta.ref[fieldName].model + "'";
										}else if(res.meta.sub && res.meta.sub[fieldName])
											type = "sub:'" + res.meta.sub[fieldName].model + "'";
										type = '[' + type + ']';
									}else {
										type = type || 'Date/Mixed';
									}
									modeldetails.fields[fieldName] = {
										name: fieldName,
										type: type
									};
								});
								//console.log(modeldetails);
								/*===========================================================================*/

								//show it with proper view tpl
								this.form.show(new module.View.ModelListItemDetail({
									model: new Backbone.Model(modeldetails)
								}));
								this.utils.clearModelSelection();
								$action.parent().addClass('btn-info');
							},this)
						})
					}
				},
				utils: {
					clearModelSelection: function(){
						this.list.getEl('.tool-servergen-model-list-item').removeClass('btn-info');
					}
				}
			})
		}

	});

})(Application);

Template.extend('custom-module-_dev-servermodelgen-modelitem-tpl',
[
	'{{name}}'
]
);

Template.extend('custom-module-_dev-servermodelgen-modellist-tpl',
[
	'

',
	'
',
		'',
		'<input type="text" placeholder="Find Model..." class="input input-medium">', //model search/filter box
		' Server Model', //+ Server Model button, show model form.
		' Refresh List',
	'
'
]
);

Template.extend('custom-module-_dev-servermodelgen-modelitem-detail-tpl',
[
	'
Model Definition Details for  {{meta.name}}
',
	'
',
		'

Field	Type

',
		'{{#each fields}}',
			'
',
				'{{name}}	',
				'{{type}}	',
			'
',
		'{{/each}}',
	'
'
]
);

Template.extend('custom-module-_dev-servermodelgen-modelform-field-tpl', //single field inputs row
[
	'
',
		'<input class="span3" name="fieldname" type="text" placeholder="Name of the variable/field">', //field name input
		'<input class="span2" name="fieldtype" type="text" placeholder="Type of the field">', //field type input
		'', //remove field
	'
'
]
);

Template.extend('custom-module-_dev-servermodelgen-modelform-tpl',
[
	'
',
		'Name',
		'
',
			'<input type="text" name="modelname" id="inputModelName" placeholder="Your Model Name Here...">', //model name input
		'
',
	'
',
		'
', //help text on available field types [+]
			'
Available Types: String, Number, Date, Buffer, Boolean, Mixed, Objectid, Array
',
			'e.g [String] or [Number]',
			'or [\'Your Model Name\'] - shortcut for [Objectid] ref:\'Your Model\'',
			'or ^[\'Your Model Name\'] - sub:\'Your Model\' see - /util/objectfactory.js',
			'MongooseJS Schema Types see - http://mongoosejs.com/docs/schematypes.html',
		'
', //help text on available field types [.]
	'
Fields
', //add field
	'

',
	'
Submit Cancel
' //submit model or cancel.
]
);

Template.extend('custom-module-_dev-servermodelgen-tpl',
[
	'

',
	'

'
]);
<|endoftext|>


<commit_before>// comfy is good for your health, dummy
//
// Developed by Filipe Dobreira in Gabriele's living room couch.

"use strict";

/**
 * Tiny helper defining the syntax for defining properties, and
 * container for the resolved properties.
 *
 * @class
 */
function Comfy(env) {
  this._env = env;
}

/**
 * Defines a required property.
 *
 * @example
 * this.required("github_api_key");
 *
 * @example
 * // Same as the following:
 * this.property("github_api_key", { required: true });
 *
 * @arg  {string} name
 * @arg  {Object} options
 */
Comfy.prototype.required = function (name, options) {
  var newOptions = this.withOptions(options);

  newOptions.required = true;

  this.property(name, newOptions);
};

/**
 * Defines an optional property.
 *
 * @example
 * this.optional("s3_bucket", "default_bucket_ident")
 *
 * @example
 * // Same as the following:
 * this.property
 *
 * @arg  {string} name
 * @arg  defaultValue
 * @arg  {Object} options
 */
Comfy.prototype.optional = function (name, defaultValue, options) {
  var newOptions = this.withOptions(options);

  if (typeof defaultValue === "undefined") {
    throw "Optional property " + name + " with no default (got undefined)";
  }

  newOptions.optional = true;
  newOptions.defaultValue = defaultValue;

  this.property(name, newOptions);
};

/**
 * Defines a property. This method is the lowest level API available
 * for defining configuration through comfy; for more concise options
 * see other methods: required, optional
 *
 * @arg {string} name
 * @arg {Object} options
 */
Comfy.prototype.property = function (name, options) {
  var opts = this.withOptions(options);

  var envName = this.nameToEnvKey(name);
  var envValue = this._env[envName];

  if (typeof envValue === "undefined") {
    if (opts.optional) {
      envValue = opts.defaultValue;
    } else {
      throw "Required property " + envName + " not present in env:" + this._env;
    }
  }

  if (opts.transform) {
    envValue = opts.transform.call(null, envValue);
  }

  if (opts.alias) {
    name = opts.alias;
  }

  this.setProperty(name, envValue);
};

/**
 * @param {string} name
 * @param value
 */
Comfy.prototype.setProperty = function (name, value) {
  this[name] = value;
  this[this.nameToCamelCaseKey(name)] = value;
};

/**
 * Transforms a snake_case property name into the correct name format
 * to scan for a matching environment variable.
 *
 * @param {string} name
 * @returns {string}
 */
Comfy.prototype.nameToEnvKey = function (name) {
  return name.toUpperCase();
};

/**
 * Transforms a snake_case property name into camelCase
 *
 * @param {string} name
 * @returns {string}
 */
Comfy.prototype.nameToCamelCaseKey = function (name) {
  return name.replace(/(\_\w)/g, function (m) {
    return m[1].toUpperCase();
  });
};

/**
 * Normalizes the options object and discards anything it
 * doesn't understand.
 *
 * @todo Complain loudly if an unknown property is provided
 *
 * @arg {Object} options
 * @returns {Object}
 */
Comfy.prototype.withOptions = function (options) {
  var opts = options || {};

  return {
    required: opts.required || false,
    transform: opts.transform || null,
    optional: opts.optional || false,
    defaultValue: opts.defaultValue || undefined,
    alias: opts.alias || null
  };
};

module.exports = {
  build: function (definition, customEnv) {
    var env = customEnv || process.env;
    var config = new Comfy(env);

    definition.call(null, config);

    return config;
  }
};
<commit_msg>Properly handle ALL_UPPER_CASE config definitions<commit_after>// comfy is good for your health, dummy
//
// Developed by Filipe Dobreira in Gabriele's living room couch.

"use strict";

/**
 * Tiny helper defining the syntax for defining properties, and
 * container for the resolved properties.
 *
 * @class
 */
function Comfy(env) {
  this.env = env;
}

/**
 * Defines a required property.
 *
 * @example
 * this.required("github_api_key");
 *
 * @example
 * // Same as the following:
 * this.property("github_api_key", { required: true });
 *
 * @arg  {string} name
 * @arg  {Object} options
 */
Comfy.prototype.required = function (name, options) {
  var newOptions = this.withOptions(options);

  newOptions.required = true;

  this.property(name, newOptions);
};

/**
 * Defines an optional property.
 *
 * @example
 * this.optional("s3_bucket", "default_bucket_ident")
 *
 * @example
 * // Same as the following:
 * this.property
 *
 * @arg  {string} name
 * @arg  defaultValue
 * @arg  {Object} options
 */
Comfy.prototype.optional = function (name, defaultValue, options) {
  var newOptions = this.withOptions(options);

  if (typeof defaultValue === "undefined") {
    throw "Optional property " + name + " with no default (got undefined)";
  }

  newOptions.optional = true;
  newOptions.defaultValue = defaultValue;

  this.property(name, newOptions);
};

/**
 * Defines a property. This method is the lowest level API available
 * for defining configuration through comfy; for more concise options
 * see other methods: required, optional
 *
 * @arg {string} name
 * @arg {Object} options
 */
Comfy.prototype.property = function (name, options) {
  var opts = this.withOptions(options);

  var envName = this.nameToEnvKey(name);
  var envValue = this.env[envName];

  if (typeof envValue === "undefined") {
    if (opts.optional) {
      envValue = opts.defaultValue;
    } else {
      throw "Required property " + envName + " not present in env:" + this.env;
    }
  }

  if (opts.transform) {
    envValue = opts.transform.call(null, envValue);
  }

  if (opts.alias) {
    name = opts.alias;
  }

  this.setProperty(name, envValue);
};

/**
 * @param {string} name
 * @param value
 */
Comfy.prototype.setProperty = function (name, value) {
  this[name] = value;
  this[this.nameToCamelCaseKey(name)] = value;
};

/**
 * Transforms a snake_case property name into the correct name format
 * to scan for a matching environment variable.
 *
 * @param {string} name
 * @returns {string}
 */
Comfy.prototype.nameToEnvKey = function (name) {
  return name.toUpperCase();
};

/**
 * Transforms a snake_case property name into camelCase
 *
 * @param {string} name
 * @returns {string}
 */
Comfy.prototype.nameToCamelCaseKey = function (name) {
  return name.replace(/(\_\w)/g, function (m) {
    return m[1].toUpperCase();
  });
};

/**
 * Normalizes the options object and discards anything it
 * doesn't understand.
 *
 * @todo Complain loudly if an unknown property is provided
 *
 * @arg {Object} options
 * @returns {Object}
 */
Comfy.prototype.withOptions = function (options) {
  var opts = options || {};

  return {
    required: opts.required || false,
    transform: opts.transform || null,
    optional: opts.optional || false,
    defaultValue: opts.defaultValue || undefined,
    alias: opts.alias || null
  };
};

module.exports = {
  build: function (definition, customEnv) {
    var env = customEnv || process.env;
    var config = new Comfy(env);

    definition.call(null, config);

    return config;
  }
};
<|endoftext|>


<commit_before>
define([
    'flight/lib/component',
    'tpl!./image',
    'tpl!util/blur/blur-svg'
], function(defineComponent, template, blur, Jcrop) {
    'use strict';

    return defineComponent(ImageView);

    function ImageView() {

        this.defaultAttrs({
            imageSelector: 'img',
            boxSelector: '.facebox',
            boxEditingSelector: '.facebox.editing',
            svgPrefix: 'detail-pane'
        });

        this.after('initialize', function() {
            var html = template({ data: this.attr.data });

            this.$node.css({
                backgroundImage: this.attr.src
            }).html(html);

            this.setupEditingFacebox();

            this.$node.closest('.detail-pane').on('DetectedObjectEnter', this.onHover.bind(this));
            this.$node.closest('.detail-pane').on('DetectedObjectLeave', this.onHoverLeave.bind(this));
            this.$node.closest('.detail-pane').on('DetectedObjectEdit', this.onEdit.bind(this));
            this.$node.closest('.detail-pane').on('DetectedObjectDoneEditing', this.onDoneEditing.bind(this));
            this.before('teardown',function () {
                this.$node.closest('.detail-pane').off('DetectedObjectEnter');
                this.$node.closest('.detail-pane').off('DetectedObjectLeave');
                this.$node.closest('.detail-pane').off('DetectedObjectDoneEditing');
            });
        });

        this.setupEditingFacebox = function() {
            var self = this,
                image = this.select('imageSelector'),
                naturalWidth = image[0].naturalWidth,
                naturalHeight = image[0].naturalHeight;

            if (naturalWidth === 0 || naturalHeight === 0) {
                image.on('load', this.setupEditingFacebox.bind(this));
                return;
            }

            this.on('click', function(event) {
                var $target = $(event.target);
                if ($target.closest('.facebox').length) return;
                this.select('boxSelector').hide();
                this.currentlyEditing = null;
            });
            this.on('mousedown', function(event) {
                var $target = $(event.target);
                if ($target.closest('.facebox').length) return;

                event.stopPropagation();
                event.preventDefault();

                var box = this.select('boxEditingSelector'),
                    offsetParent = this.$node.offset(),
                    offsetParentWidth = this.$node.width(),
                    offsetParentHeight = this.$node.height(),
                    startPosition = {
                        left: event.pageX - offsetParent.left,
                        top: event.pageY - offsetParent.top,
                        width: 1,
                        height: 1
                    };
                $(document).on('mousemove.facebox', function(evt) {
                        var currentPosition = {
                                left: Math.min(offsetParentWidth, Math.max(0, evt.pageX - offsetParent.left)),
                                top: Math.min(offsetParentHeight, Math.max(0, evt.pageY - offsetParent.top))
                            },
                            width = Math.abs(startPosition.left - currentPosition.left),
                            height = Math.abs(startPosition.top - currentPosition.top);

                        if (width >= 5 && height >= 5) {
                            box.css({
                                left: Math.min(startPosition.left, currentPosition.left),
                                top: Math.min(startPosition.top, currentPosition.top),
                                width: width,
                                height: height
                            }).show();
                        } else {
                            box.hide();
                        }
                    })
                    .on('mouseup.facebox', function(evt) {
                        $(document).off('mouseup.facebox mousemove.facebox');
                        self.currentlyEditing = 'NEW';
                        convertToPercentageAndTrigger(evt, { element:box });
                    });

                box.css(startPosition).hide();
            });

            this.select('boxEditingSelector')
                .resizable({
                    containment: this.$node,
                    handles: 'all',
                    minWidth: 5,
                    minHeight: 5,
                    start: function(event, ui) {
                        // Make fixed percentages during drag
                        ui.element.css(
                            $.extend({}, ui.element.position(), {
                                width:ui.element.width(),
                                height:ui.element.height()
                            })
                        );
                    },
                    stop: convertToPercentageAndTrigger
                }).draggable({
                    containment: this.$node,
                    cursor: "move",
                    stop: convertToPercentageAndTrigger
                });

            function convertToPercentageAndTrigger(event, ui) {
                // Make percentages for fluid
                var el = ui.element || ui.helper,
                    position = el.position(),
                    offsetParent = el.offsetParent(),
                    width = offsetParent.width(),
                    height = offsetParent.height(),
                    t = position.top / height,
                    l = position.left / width,
                    w = el.width() / width,
                    h = el.height() / height;

                el.css({
                    top: t * 100 + '%',
                    left: l * 100 + '%',
                    width: w * 100 + '%',
                    height: h * 100 + '%'
                });

                self.trigger('DetectedObjectCoordsChange', {
                    id: self.currentlyEditing,
                    x1: (l * naturalWidth).toFixed(2) + '',
                    x2: ((l + w) * naturalWidth).toFixed(2) + '',
                    y1: (t * naturalHeight).toFixed(2) + '',
                    y2: ((t + h) * naturalHeight).toFixed(2) + ''
                });
            }
        };

        this.showFacebox = function(data, toEdit) {
            var box = toEdit ? this.select('boxEditingSelector') :
                        this.select('boxSelector').not('.editing');
            var image = this.select('imageSelector');
            var width = image.width(),
                height = image.height(),
                aspectWidth = width / image[0].naturalWidth,
                aspectHeight = height / image[0].naturalHeight,
                w = (data.x2 - data.x1) * aspectWidth / width * 100,
                h = (data.y2 - data.y1) * aspectHeight / height * 100,
                x = data.x1 * aspectWidth / width * 100,
                y = data.y1 * aspectHeight / height * 100;
            box.css({
                    width: w + '%',
                    height: h + '%',
                    left: x + '%',
                    top: y + '%'
                })
                .show();
        };

        this.showFaceboxForEdit = function(data) {
            this.showFacebox(data, true);
        };

        this.onHover = function(event, data) {
            this.showFacebox(data);
        };

        this.onHoverLeave = function(event, data) {
            var toHide = this.select('boxSelector');

            if (this.currentlyEditing) {
                toHide = toHide.not('.editing');
            }

            toHide.hide();
        };

        this.onEdit = function(event, data) {
            if (data.graphVertexId === this.currentlyEditing) return;
            this.currentlyEditing = data.graphVertexId;

            this.showFaceboxForEdit(data);
        };

        this.onDoneEditing = function(event) {
            this.currentlyEditing = null;
            this.select('boxSelector').hide();
        };
    }
});
<commit_msg>[#66238924] show editing facebox when editing faces detected by system<commit_after>
define([
    'flight/lib/component',
    'tpl!./image',
    'tpl!util/blur/blur-svg'
], function(defineComponent, template, blur, Jcrop) {
    'use strict';

    return defineComponent(ImageView);

    function ImageView() {

        this.defaultAttrs({
            imageSelector: 'img',
            boxSelector: '.facebox',
            boxEditingSelector: '.facebox.editing',
            svgPrefix: 'detail-pane'
        });

        this.after('initialize', function() {
            var html = template({ data: this.attr.data });

            this.$node.css({
                backgroundImage: this.attr.src
            }).html(html);

            this.setupEditingFacebox();

            this.$node.closest('.detail-pane').on('DetectedObjectEnter', this.onHover.bind(this));
            this.$node.closest('.detail-pane').on('DetectedObjectLeave', this.onHoverLeave.bind(this));
            this.$node.closest('.detail-pane').on('DetectedObjectEdit', this.onEdit.bind(this));
            this.$node.closest('.detail-pane').on('DetectedObjectDoneEditing', this.onDoneEditing.bind(this));
            this.before('teardown',function () {
                this.$node.closest('.detail-pane').off('DetectedObjectEnter');
                this.$node.closest('.detail-pane').off('DetectedObjectLeave');
                this.$node.closest('.detail-pane').off('DetectedObjectDoneEditing');
            });
        });

        this.setupEditingFacebox = function() {
            var self = this,
                image = this.select('imageSelector'),
                naturalWidth = image[0].naturalWidth,
                naturalHeight = image[0].naturalHeight;

            if (naturalWidth === 0 || naturalHeight === 0) {
                image.on('load', this.setupEditingFacebox.bind(this));
                return;
            }

            this.on('click', function(event) {
                var $target = $(event.target);
                if ($target.closest('.facebox').length) return;
                this.select('boxSelector').hide();
                this.currentlyEditing = null;
            });
            this.on('mousedown', function(event) {
                var $target = $(event.target);
                if ($target.closest('.facebox').length) return;

                event.stopPropagation();
                event.preventDefault();

                var box = this.select('boxEditingSelector'),
                    offsetParent = this.$node.offset(),
                    offsetParentWidth = this.$node.width(),
                    offsetParentHeight = this.$node.height(),
                    startPosition = {
                        left: event.pageX - offsetParent.left,
                        top: event.pageY - offsetParent.top,
                        width: 1,
                        height: 1
                    };
                $(document).on('mousemove.facebox', function(evt) {
                        var currentPosition = {
                                left: Math.min(offsetParentWidth, Math.max(0, evt.pageX - offsetParent.left)),
                                top: Math.min(offsetParentHeight, Math.max(0, evt.pageY - offsetParent.top))
                            },
                            width = Math.abs(startPosition.left - currentPosition.left),
                            height = Math.abs(startPosition.top - currentPosition.top);

                        if (width >= 5 && height >= 5) {
                            box.css({
                                left: Math.min(startPosition.left, currentPosition.left),
                                top: Math.min(startPosition.top, currentPosition.top),
                                width: width,
                                height: height
                            }).show();
                        } else {
                            box.hide();
                        }
                    })
                    .on('mouseup.facebox', function(evt) {
                        $(document).off('mouseup.facebox mousemove.facebox');
                        self.currentlyEditing = 'NEW';
                        convertToPercentageAndTrigger(evt, { element:box });
                    });

                box.css(startPosition).hide();
            });

            this.select('boxEditingSelector')
                .resizable({
                    containment: this.$node,
                    handles: 'all',
                    minWidth: 5,
                    minHeight: 5,
                    start: function(event, ui) {
                        // Make fixed percentages during drag
                        ui.element.css(
                            $.extend({}, ui.element.position(), {
                                width:ui.element.width(),
                                height:ui.element.height()
                            })
                        );
                    },
                    stop: convertToPercentageAndTrigger
                }).draggable({
                    containment: this.$node,
                    cursor: "move",
                    stop: convertToPercentageAndTrigger
                });

            function convertToPercentageAndTrigger(event, ui) {
                // Make percentages for fluid
                var el = ui.element || ui.helper,
                    position = el.position(),
                    offsetParent = el.offsetParent(),
                    width = offsetParent.width(),
                    height = offsetParent.height(),
                    t = position.top / height,
                    l = position.left / width,
                    w = el.width() / width,
                    h = el.height() / height;

                el.css({
                    top: t * 100 + '%',
                    left: l * 100 + '%',
                    width: w * 100 + '%',
                    height: h * 100 + '%'
                });

                self.trigger('DetectedObjectCoordsChange', {
                    id: self.currentlyEditing,
                    x1: (l * naturalWidth).toFixed(2) + '',
                    x2: ((l + w) * naturalWidth).toFixed(2) + '',
                    y1: (t * naturalHeight).toFixed(2) + '',
                    y2: ((t + h) * naturalHeight).toFixed(2) + ''
                });
            }
        };

        this.showFacebox = function(data, toEdit) {
            var box = toEdit ? this.select('boxEditingSelector') :
                        this.select('boxSelector').not('.editing');
            var image = this.select('imageSelector');
            var width = image.width(),
                height = image.height(),
                aspectWidth = width / image[0].naturalWidth,
                aspectHeight = height / image[0].naturalHeight,
                w = (data.x2 - data.x1) * aspectWidth / width * 100,
                h = (data.y2 - data.y1) * aspectHeight / height * 100,
                x = data.x1 * aspectWidth / width * 100,
                y = data.y1 * aspectHeight / height * 100;
            box.css({
                    width: w + '%',
                    height: h + '%',
                    left: x + '%',
                    top: y + '%'
                })
                .show();
        };

        this.showFaceboxForEdit = function(data) {
            this.showFacebox(data, true);
        };

        this.onHover = function(event, data) {
            this.showFacebox(data);
        };

        this.onHoverLeave = function(event, data) {
            var toHide = this.select('boxSelector');

            if (this.currentlyEditing) {
                toHide = toHide.not('.editing');
            }

            toHide.hide();
        };

        this.onEdit = function(event, data) {
            if (this.currentlyEditing && data.graphVertexId === this.currentlyEditing) return;
            this.currentlyEditing = !data.graphVertexId ? 'NEW' : data.graphVertexId;
            this.showFaceboxForEdit(data);
        };

        this.onDoneEditing = function(event) {
            this.currentlyEditing = null;
            this.select('boxSelector').hide();
        };
    }
});
<|endoftext|>


<commit_before>(function (OC, window, $, undefined) {
    'use strict';

    $(document).ready(function () {

        // this notes object holds all our notes
        var Papers = function (baseUrl) {
            this._baseUrl = baseUrl;
            this._papers = [];
            this._activePaper = undefined;
        };

        Papers.prototype = {
            load: function (id) {
                var self = this;
                this._papers.forEach(function (paper) {
                    if (paper.id === id) {
                        paper.active = true;
                        self._activeNote = paper;
                    } else {
                        paper.active = false;
                    }
                });
            },
            getActive: function () {
                return this._activePaper;
            },
            getAll: function () {
                return this._papers;
            },
            loadAll: function () {
                var deferred = $.Deferred();
                var self = this;
                $.get(this._baseUrl).done(function (papers) {
                    self._activePaper = undefined;
                    self._papers = papers;
                    deferred.resolve();
                }).fail(function () {
                    deferred.reject();
                });
                return deferred.promise();
            }
        };

        // this will be the view that is used to update the html
        var View = function (papers) {
            this._papers = papers;
        };

        View.prototype = {
            renderContent: function () {

            },
            renderList: function () {

            },
            renderNavigation: function () {

            },
            render: function () {
                this.renderContent();
                this.renderList();
                this.renderNavigation();
            }
        };

        var papers = new Papers(OC.generateUrl('/apps/paper/papers'));
        var view = new View(papers);
        papers.loadAll().done(function () {
            view.render();
        }).fail(function () {
            alert('Could not load papers');
        });
    });

})(OC, window, jQuery);<commit_msg>Activating handlebars<commit_after>(function (OC, window, $, undefined) {
    'use strict';

    $(document).ready(function () {

        // this notes object holds all our notes
        var Papers = function (baseUrl) {
            this._baseUrl = baseUrl;
            this._papers = [];
            this._activePaper = undefined;
        };

        Papers.prototype = {
            load: function (id) {
                var self = this;
                this._papers.forEach(function (paper) {
                    if (paper.id === id) {
                        paper.active = true;
                        self._activeNote = paper;
                    } else {
                        paper.active = false;
                    }
                });
            },
            getActive: function () {
                return this._activePaper;
            },
            getAll: function () {
                return this._papers;
            },
            loadAll: function () {
                var deferred = $.Deferred();
                var self = this;
                $.get(this._baseUrl).done(function (papers) {
                    self._activePaper = undefined;
                    self._papers = papers;
                    deferred.resolve();
                }).fail(function () {
                    deferred.reject();
                });
                return deferred.promise();
            }
        };

        // this will be the view that is used to update the html
        var View = function (papers) {
            this._papers = papers;
        };

        View.prototype = {
            renderContent: function () {
            },
            renderList: function () {
                var source = $('#list-tpl').html();
                var template = Handlebars.compile(source);
            },
            renderNavigation: function () {
                var source = $('#navigation-tpl').html();
                var template = Handlebars.compile(source);
            },
            render: function () {
                this.renderContent();
                this.renderList();
                this.renderNavigation();
            }
        };

        var papers = new Papers(OC.generateUrl('/apps/paper/papers'));
        var view = new View(papers);
        papers.loadAll().done(function () {
            view.render();
        }).fail(function () {
            alert('Could not load papers');
        });
    });

})(OC, window, jQuery);<|endoftext|>


<commit_before>import { inject as service } from '@ember/service';
import Component from '@ember/component';
import Errors from 'ui/utils/errors';
import layout from './template';
import { get, set, observer, computed, setProperties } from '@ember/object';
import { on } from '@ember/object/evented';

export default Component.extend({
  layout,
  tagName:     'section',
  classNames:  ['well'],
  settings:    service(),
  access:      service(),
  github:      service(),
  intl:        service(),

  model:       null,
  individuals: 'siteAccess.users',
  collection:  'siteAccess.groups',
  principals:  null,

  saved:       true,
  errors:      null,

  actions: {
    addAuthorized(principal) {

      if ( !principal ) {
        return;
      }

      this.send('clearError');

      set(this, 'saved', false);

      if (this.checkDuplicate(principal)) {

        this.send('gotError', get(this, 'intl').t('siteAccess.dupe'))

      } else {

        get(this, 'model.allowedPrincipalIds').pushObject(principal.id);

      }
    },

    removeAuthorized(id) {

      set(this, 'saved', false);

      get(this, 'model.allowedPrincipalIds').removeObject(id);

    },

    save(btnCb) {
      this.send('clearError');

      if ( get(this, 'model.accessMode') === 'required' && !get(this, 'model.allowedPrincipalIds.length') ) {

        this.send('gotError', get(this, 'intl').t('siteAccess.minimum'));

        btnCb();

        return;

      }

      set(this, 'saved', false);

      const model = get(this, 'model');

      model.save().then(() => {

        set(this, 'saved', true);

      }).catch((err) => {

        this.send('gotError', err);

      }).finally(() => {

        btnCb();

      });
    },

    gotError(err) {
      set(this, 'errors', [Errors.stringify(err)]);
    },

    clearError() {

      set(this, 'errors', null);

      setProperties(this, {
        errors:    null,
      });

    },
  },

  showList: computed('model.accessMode', function() {
    return get(this, 'model.accessMode') !== 'unrestricted';
  }),

  accessModeChanged: on('init', observer('model.accessMode', function() {

    set(this, 'saved',false);

    const allowedPrincipals = get(this, 'model.allowedPrincipalIds') || []; // ['princ_id1://yada']

    if ( get(this, 'model.accessMode') !== 'unrestricted' ) {

      const me    = get(this, 'access.principal')||[];
      const found = allowedPrincipals.filter(ident => get(me, 'id') === ident).length > 0;

      if ( !found ) {
        allowedPrincipals.pushObject(get(me, 'id'));
      }
    }

    set(this, 'model.allowedPrincipalIds', allowedPrincipals);

  })),

  checkDuplicate(principal) {
    return (get(this, 'model.allowedPrincipalIds')||[]).includes(principal.id) ? true : false;
  },

});
<commit_msg>fixup<commit_after>import { inject as service } from '@ember/service';
import Component from '@ember/component';
import Errors from 'ui/utils/errors';
import layout from './template';
import { get, set, observer, computed, setProperties } from '@ember/object';
import { on } from '@ember/object/evented';

export default Component.extend({
  layout,
  tagName:     'section',
  classNames:  ['well'],
  settings:    service(),
  access:      service(),
  github:      service(),
  intl:        service(),

  model:       null,
  individuals: 'siteAccess.users',
  collection:  'siteAccess.groups',
  principals:  null,

  saved:       true,
  errors:      null,

  actions: {
    addAuthorized(principal) {
      if ( !principal ) {
        return;
      }

      this.send('clearError');

      set(this, 'saved', false);

      if (this.checkDuplicate(principal)) {
        this.send('gotError', get(this, 'intl').t('siteAccess.dupe'))
      } else {
        get(this, 'model.allowedPrincipalIds').pushObject(principal.id);
      }
    },

    removeAuthorized(id) {
      set(this, 'saved', false);

      get(this, 'model.allowedPrincipalIds').removeObject(id);
    },

    save(btnCb) {
      this.send('clearError');

      if ( get(this, 'model.accessMode') === 'required' && !get(this, 'model.allowedPrincipalIds.length') ) {
        this.send('gotError', get(this, 'intl').t('siteAccess.minimum'));

        btnCb();

        return;
      }

      set(this, 'saved', false);

      const model = get(this, 'model');

      model.save().then(() => {
        set(this, 'saved', true);
      }).catch((err) => {
        this.send('gotError', err);
      }).finally(() => {
        btnCb();
      });
    },

    gotError(err) {
      set(this, 'errors', [Errors.stringify(err)]);
    },

    clearError() {
      set(this, 'errors', null);

      setProperties(this, {
        errors:    null,
      });
    },
  },

  showList: computed('model.accessMode', function() {
    return get(this, 'model.accessMode') !== 'unrestricted';
  }),

  accessModeChanged: on('init', observer('model.accessMode', function() {
    set(this, 'saved',false);

    const allowedPrincipals = get(this, 'model.allowedPrincipalIds') || []; // ['princ_id1://yada']

    if ( get(this, 'model.accessMode') !== 'unrestricted' ) {

      const me    = get(this, 'access.principal')||[];
      const found = allowedPrincipals.filter(ident => get(me, 'id') === ident).length > 0;

      if ( !found ) {
        allowedPrincipals.pushObject(get(me, 'id'));
      }
    }

    set(this, 'model.allowedPrincipalIds', allowedPrincipals);
  })),

  checkDuplicate(principal) {
    return (get(this, 'model.allowedPrincipalIds')||[]).includes(principal.id) ? true : false;
  },

});
<|endoftext|>