<commit_before>

    head(function(){

      //Put paginator in middle
      var paginator_width = $('div.paginate').width();
      $('div.paginate').css('margin-left', ((626-paginator_width)/2) +'px');
      $('div.paginate').show();

      $('a.close').click(function(ev){
        ev.stopPropagation();
        ev.preventDefault();
        $(this).closest('div.section').fadeOut();
      });

      $('div.notification').delay(5000).fadeOut();

      $('ul.your_tables li.last').hover(function(){
        $('div.tables_list div.left div.bottom_white_medium').css('background-position','0 -11px');
      }, function(){
        $('div.tables_list div.left div.bottom_white_medium').css('background-position','0 0');
      });

      //Function for doing the whole cell on the tables list clickable
      $('ul.your_tables li').click(function() {
        window.location.href = $(this).find("h4 > a.tableTitle").attr("href");
      });

      //Close all modal windows
      $('div.mamufas a.cancel, div.mamufas a.close_delete, div.mamufas a.close_settings, div.mamufas a.close_create, div.mamufas a.close').click(function(ev){
        ev.preventDefault();
        ev.stopPropagation();
        $('div.mamufas').fadeOut('fast',function(){
          $('div.mamufas div.settings_window').hide();
          $('div.mamufas div.delete_window').hide();
          $('div.mamufas div.create_window').hide();
          $('div.mamufas div.export_window').hide();
        });
        unbindESC();
      });

      //Delete window
      $('a.delete').click(function(ev){
        ev.preventDefault();
        ev.stopPropagation();
        var table_name = $(this).attr('table-name');
        $('div.mamufas a.confirm_delete').attr('table-name',table_name);
        $('div.mamufas div.delete_window').show();
        $('div.mamufas').fadeIn('fast');
        bindESC();
      });
      $('a.confirm_delete').click(function(ev){
        ev.preventDefault();
        ev.stopPropagation();
        var table_name = $(this).attr('table-name');
        $.ajax({
          type: "DELETE",
          dataType: "text",
          url:global_api_url+'tables/'+table_name,
          headers: {'cartodbclient':true},
          success: function(data, textStatus, XMLHttpRequest) {
						$.cookie('flash', 'Table successfully removed');
            window.location.href = "/dashboard";
          },
          error: function(e) {
            console.debug(e);
          }
        });
      });

      //Export window
      $('a.export_data').click(function(ev){
        stopPropagation(ev);
        if ($('div.mamufas').is(':visible') && $('div.delete_window').is(':visible')) {
          $('div.mamufas div.export_window form').attr('action','/tables/'+$('div.mamufas a.confirm_delete').attr('table-name'));
          $('div.mamufas div.delete_window').hide();
          $('div.mamufas div.export_window').show();
        } else {
          $('div.mamufas div.export_window').show();
          $('div.mamufas').fadeIn('fast');
          bindESC();
        }
      });

      $('div.mamufas div.export_window form a.option').click(function(ev){
        stopPropagation(ev);
				if (!$(this).parent().hasClass('disabled')) {
					var format = $(this).attr('rel');
	        $('div.mamufas div.export_window form ul li').removeClass('selected');
	        $(this).parent().addClass('selected');
	        $('#export_format').val(format);
				}
      });

      $('div.mamufas div.export_window form').submit(function(ev){
				$('div.mamufas').fadeOut('fast',function(){
          $('div.mamufas div.export_window').hide();
        });
      });

      $('#export_format').val($('div.mamufas div.export_window form ul li.selected a.option').attr('rel'));
    });

	$('#hugeUploader').hide();
	//Drop files on the dashboard to import them
    $(document).bind('dragenter', onDragEnter);

    function onDragEnter(event){
  		event.stopPropagation();
  		event.preventDefault();
  		$('#hugeUploader').show();
  		$('.qq-upload-drop-area').show();
  		$('#hugeUploader .qq-upload-drop-area').bind('dragleave', onDragExit);
  		$('#hugeUploader .qq-upload-drop-area').bind('drop', onDragExit);
  		$('#hugeUploader .qq-upload-drop-area').bind('dragover', function(event) {event.stopPropagation(); event.preventDefault();});
  		return false;
    };

    function onDragExit(event){
  		event.stopPropagation();
  		event.preventDefault();
  		$('#hugeUploader').hide();
  		$('.qq-upload-drop-area').hide();
  		return false;
    };

    function bindESC() {
      $(document).keydown(function(event){
        if (event.which == '27') {
          $('div.mamufas').fadeOut('fast',function(){
            $('div.mamufas div.settings_window').hide();
            $('div.mamufas div.delete_window').hide();
            $('div.mamufas div.create_window').hide();
            $('div.mamufas div.export_window').hide();
          });
        }
      });
    }

    function unbindESC() {
      $(document).unbind('keydown');
    }

<commit_msg>blogposts last<commit_after>

    head(function(){

      //Put paginator in middle
      var paginator_width = $('div.paginate').width();
      $('div.paginate').css('margin-left', ((626-paginator_width)/2) +'px');
      $('div.paginate').show();

      $('a.close').click(function(ev){
        ev.stopPropagation();
        ev.preventDefault();
        $(this).closest('div.section').fadeOut();
      });

      $('div.notification').delay(5000).fadeOut();

      $('ul.your_tables li.last').hover(function(){
        $('div.tables_list div.left div.bottom_white_medium').css('background-position','0 -11px');
      }, function(){
        $('div.tables_list div.left div.bottom_white_medium').css('background-position','0 0');
      });

      //Function for doing the whole cell on the tables list clickable
      $('ul.your_tables li').click(function() {
        window.location.href = $(this).find("h4 > a.tableTitle").attr("href");
      });

      //Close all modal windows
      $('div.mamufas a.cancel, div.mamufas a.close_delete, div.mamufas a.close_settings, div.mamufas a.close_create, div.mamufas a.close').click(function(ev){
        ev.preventDefault();
        ev.stopPropagation();
        $('div.mamufas').fadeOut('fast',function(){
          $('div.mamufas div.settings_window').hide();
          $('div.mamufas div.delete_window').hide();
          $('div.mamufas div.create_window').hide();
          $('div.mamufas div.export_window').hide();
        });
        unbindESC();
      });

      //Delete window
      $('a.delete').click(function(ev){
        ev.preventDefault();
        ev.stopPropagation();
        var table_name = $(this).attr('table-name');
        $('div.mamufas a.confirm_delete').attr('table-name',table_name);
        $('div.mamufas div.delete_window').show();
        $('div.mamufas').fadeIn('fast');
        bindESC();
      });
      $('a.confirm_delete').click(function(ev){
        ev.preventDefault();
        ev.stopPropagation();
        var table_name = $(this).attr('table-name');
        $.ajax({
          type: "DELETE",
          dataType: "text",
          url:global_api_url+'tables/'+table_name,
          headers: {'cartodbclient':true},
          success: function(data, textStatus, XMLHttpRequest) {
						$.cookie('flash', 'Table successfully removed');
            window.location.href = "/dashboard";
          },
          error: function(e) {
            console.debug(e);
          }
        });
      });

      //Export window
      $('a.export_data').click(function(ev){
        stopPropagation(ev);
        if ($('div.mamufas').is(':visible') && $('div.delete_window').is(':visible')) {
          $('div.mamufas div.export_window form').attr('action','/tables/'+$('div.mamufas a.confirm_delete').attr('table-name'));
          $('div.mamufas div.delete_window').hide();
          $('div.mamufas div.export_window').show();
        } else {
          $('div.mamufas div.export_window').show();
          $('div.mamufas').fadeIn('fast');
          bindESC();
        }
      });

      $('div.mamufas div.export_window form a.option').click(function(ev){
        stopPropagation(ev);
				if (!$(this).parent().hasClass('disabled')) {
					var format = $(this).attr('rel');
	        $('div.mamufas div.export_window form ul li').removeClass('selected');
	        $(this).parent().addClass('selected');
	        $('#export_format').val(format);
				}
      });

      $('div.mamufas div.export_window form').submit(function(ev){
				$('div.mamufas').fadeOut('fast',function(){
          $('div.mamufas div.export_window').hide();
        });
      });

      $('#export_format').val($('div.mamufas div.export_window form ul li.selected a.option').attr('rel'));
    });

	  $('#hugeUploader').hide();
	  //Drop files on the dashboard to import them
    $(document).bind('dragenter', onDragEnter);

    function onDragEnter(event){
  		event.stopPropagation();
  		event.preventDefault();
  		$('#hugeUploader').show();
  		$('.qq-upload-drop-area').show();
  		$('#hugeUploader .qq-upload-drop-area').bind('dragleave', onDragExit);
  		$('#hugeUploader .qq-upload-drop-area').bind('drop', onDragExit);
  		$('#hugeUploader .qq-upload-drop-area').bind('dragover', function(event) {event.stopPropagation(); event.preventDefault();});
  		return false;
    };

    function onDragExit(event){
  		event.stopPropagation();
  		event.preventDefault();
  		$('#hugeUploader').hide();
  		$('.qq-upload-drop-area').hide();
  		return false;
    };

    function bindESC() {
      $(document).keydown(function(event){
        if (event.which == '27') {
          $('div.mamufas').fadeOut('fast',function(){
            $('div.mamufas div.settings_window').hide();
            $('div.mamufas div.delete_window').hide();
            $('div.mamufas div.create_window').hide();
            $('div.mamufas div.export_window').hide();
          });
        }
      });
    }

    function unbindESC() {
      $(document).unbind('keydown');
    }

<|endoftext|>


<commit_before>var Brick = Class.create(DisplayObject, {

  initialize: function($super) {
    $super();

    this.x = 0;
    this.y = 0;
    this.selected = false;
    this.rotation = 0;
    this.state = "dead";

    this.isDragable = true;

    this.cell = {
      row: 0,
      col: 0
    }
  },

  draw: function(context) {

    context.strokeStyle = (this.selected) ? "#FFFFFF" : "#F6F254";
    context.lineWidth = 1;
    context.fillStyle = "#000000";

    if (this.rotation != 0 || true) this.applyRotation(context);
    if (this.state == "drag") this.applyScale(context);

    this.drawShape(context);

    context.beginPath();
    context.closePath();

  },

  drawShape: function(context) {

    context.save();

      this.applyShadow(context);
      context.fillRect(0, 0, Brick.SIZE, Brick.SIZE);

    context.restore();

    context.strokeRect(0, 0, Brick.SIZE, Brick.SIZE);

  },

  applyShadow: function(context) {
    if (this.state == "field") return;

    var multiplyer = (this.state == "drag") ? 8 : 6;
    var shadowRotation = this.rotation + Math.PI / 4;

    if (Prototype.Browser.Gecko) {

      context.shadowOffsetX = Math.cos(Math.PI / 4) * - multiplyer;
      context.shadowOffsetY = Math.sin(Math.PI / 4) * multiplyer;

    } else {

      context.shadowOffsetX = Math.cos(shadowRotation) * - multiplyer;
      context.shadowOffsetY = Math.sin(shadowRotation) * multiplyer;

    }

    context.shadowBlur = 3;
    context.shadowColor = "rgba(0, 0, 0, 0.3)";

  },

  applyScale: function(context) {

    context.translate(Brick.SIZE / 2, Brick.SIZE / 2);
    context.scale(1.1, 1.1);
    context.translate(- Brick.SIZE / 2, - Brick.SIZE / 2);

  },

  applyRotation: function(context) {

    context.translate(Brick.SIZE / 2, Brick.SIZE / 2);
    context.rotate(this.rotation);
    context.translate(- Brick.SIZE / 2, - Brick.SIZE / 2);

  },

  drawGlobal: function(context) {

    context.save();

      context.translate(this.x, this.y);
      this.draw(context);

    context.restore();

  },

  createBody: function(world) {
    var bodyDefinition = new b2BodyDef(),
      shapeDefinition = new b2PolygonDef();

    bodyDefinition.position.Set(this.cell.col + 0.5, this.cell.row + 0.5);

    this.body = world.CreateBody(bodyDefinition);

    shapeDefinition.SetAsBox(0.5, 0.5);
    shapeDefinition.restitution = 0;
    shapeDefinition.friction = 0.9;

    this.body.CreateShape(shapeDefinition);
    this.body.SetMassFromShapes();
  },

  rotate: function(radian) {
    this.body.SetXForm(this.body.GetPosition(), this.rotation + radian);

    this.rotation = this.body.GetAngle();
  }

});

Brick.isAvailable = function() {
  return true;
};

Brick.SIZE = 27;

Brick.prototype.class = Brick;<commit_msg>rotation fix attempt<commit_after>var Brick = Class.create(DisplayObject, {

  initialize: function($super) {
    $super();

    this.x = 0;
    this.y = 0;
    this.selected = false;
    this.rotation = 0;
    this.state = "dead";

    this.isDragable = true;

    this.cell = {
      row: 0,
      col: 0
    }
  },

  draw: function(context) {

    context.strokeStyle = (this.selected) ? "#FFFFFF" : "#F6F254";
    context.lineWidth = 1;
    context.fillStyle = "#000000";

    if (this.rotation != 0 || true) this.applyRotation(context);
    if (this.state == "drag") this.applyScale(context);

    this.drawShape(context);

    context.beginPath();
    context.closePath();

  },

  drawShape: function(context) {

    context.save();

      this.applyShadow(context);
      context.fillRect(0, 0, Brick.SIZE, Brick.SIZE);

    context.restore();

    context.strokeRect(0, 0, Brick.SIZE, Brick.SIZE);

  },

  applyShadow: function(context) {
    if (this.state == "field") return;

    var multiplyer = (this.state == "drag") ? 8 : 6;
    var shadowRotation = this.rotation + Math.PI / 4;

    if (Prototype.Browser.Gecko) {

      context.shadowOffsetX = Math.cos(Math.PI / 4) * - multiplyer;
      context.shadowOffsetY = Math.sin(Math.PI / 4) * multiplyer;

    } else {

      context.shadowOffsetX = Math.cos(shadowRotation) * - multiplyer;
      context.shadowOffsetY = Math.sin(shadowRotation) * multiplyer;

    }

    context.shadowBlur = 3;
    context.shadowColor = "rgba(0, 0, 0, 0.3)";

  },

  applyScale: function(context) {

    context.translate(Brick.SIZE / 2, Brick.SIZE / 2);
    context.scale(1.1, 1.1);
    context.translate(- Brick.SIZE / 2, - Brick.SIZE / 2);

  },

  applyRotation: function(context) {

    context.translate(Brick.SIZE / 2, Brick.SIZE / 2);
    context.rotate(this.rotation);
    context.translate(- Brick.SIZE / 2, - Brick.SIZE / 2);

  },

  drawGlobal: function(context) {

    context.save();

      context.translate(this.x, this.y);
      this.draw(context);

    context.restore();

  },

  createBody: function(world) {
    var bodyDefinition = new b2BodyDef(),
      shapeDefinition = new b2PolygonDef();

    bodyDefinition.position.Set(this.cell.col + 0.5, this.cell.row + 0.5);

    this.body = world.CreateBody(bodyDefinition);

    shapeDefinition.SetAsBox(0.5, 0.5);
    shapeDefinition.restitution = 0;
    shapeDefinition.friction = 0.9;

    this.body.CreateShape(shapeDefinition);
    this.body.SetMassFromShapes();
  },

  rotate: function(radian) {
    // var newRotation = this.rotation + radian;

    // this.body.SetXForm(this.body.GetPosition(), this.rotation + radian);

    // this.rotation = this.body.GetAngle();

    // if (newRotation != this.body.GetAngle()) {
    //   console.error("Rotation Fail", this.rotation + radian, this.body.GetAngle());
    // }

    this.rotation += radian;

    var matrix = {
      col1: {
        x: Math.cos(this.rotation),
        y: -Math.sin(this.rotation)
      },
      col2: {
        x: Math.sin(this.rotation),
        y: Math.cos(this.rotation)
      }
    };

    this.body.m_xf.R = matrix;
  }

});

Brick.isAvailable = function() {
  return true;
};

Brick.SIZE = 27;

Brick.prototype.class = Brick;<|endoftext|>


<commit_before>/*!
 * AngularJS complaint controllers
 * Version: 1
 *
 * Copyright 2016 Janaagraha.
 *
 * Author: Jeeva D <jeevananthamcse@gmail.com>
 * Related to project of PM University
 */
app.controller('topicCtrl', function ($scope, Data, $uibModal) {
    $scope.topics = [];
    $scope.loading = false;

    /* pagination settings */
    $scope.totalItems = 0;
    $scope.currentPage = 1;
    $scope.itemsPerPage = 10;
    $scope.maxSize = 5;
    $scope.filterTitle = 'All Complaints';

    /* for sorting */
    $scope.state = 'DESC';
    $scope.orderby = 'id';
    getResultsPage();
    function getResultsPage() {
        $scope.loading = true;
        var url = '/api/v1/admin/1/topics?api_token=032FF917-8F9F-7907-E9F9-5DCC1374E38A&locale=en&perPage='+$scope.itemsPerPage+'&page='+$scope.currentPage;
        //var url = '/api/v1/admin/1/topics?locale=en&perPage='+$scope.itemsPerPage+'&page='+$scope.currentPage;
        //Data.post('complaint/lists/' + $scope.itemsPerPage + '/' + $scope.currentPage + '/' + $scope.orderby + '/' + $scope.state,
        Data.get(url,{filters: ''}).then(function (response) {
            $scope.loading = false;
            $scope.topics = response.data.topics;
            //console.log(response.data.topics);
            $scope.totalItems = response.data.total;
        });
    }
});
app.controller('compListCtrl', function ($scope, Data, $uibModal, $filter) {
    $scope.complaints = [];
    $scope.loading = false;
    $scope.checkedAny = false;
    /* pagination settings */
    $scope.totalItems = 0;
    $scope.currentPage = 1;
    $scope.itemsPerPage = 10;
    $scope.maxSize = 5;
    $scope.filterTitle = 'All Complaints';
    /* Status defaults */
    $scope.statusOpen = 0;
    $scope.statusOnthejob = 0;
    $scope.statusResolved = 0;
    /* for sorting */
    $scope.state = 'DESC';
    $scope.orderby = 'id';
    $scope.filter = {city: '', status: '', category: '', ward: '', term: '', priority: ''};
    /*set page*/
    $scope.setPage = function (pageNo) {
        $scope.currentPage = pageNo;
    };
    /*on page change*/
    $scope.pageChanged = function () {
        getResultsPage();
    };
    /* pagination settings */
    /* Check all */
    $scope.toggleAll = function () {
        var toggleStatus = $scope.isAllSelected;
        angular.forEach($scope.complaints, function (itm) {
            itm.cChecked = toggleStatus;
            //$scope.checkedAny = toggleStatus;
        });
    };
    /* Check each check box */
    $scope.optionToggled = function () {
        $scope.isAllSelected = $scope.complaints.every(function (itm) {
            return itm.cChecked;
        });
    };

    $scope.$watch("complaints", function (n, o) {
        var trues = $filter("filter")(n, {cChecked: true});
        $scope.checkedAny = (trues.length) ? true : false;
    }, true);
    /***Date range***/
    $scope.day = 1;
    $scope.date = {
        startDate: moment().subtract($scope.day, "days"),
        endDate: moment()
    };
    $scope.setRange = function (day) {
        $scope.day = day;
        $scope.date = {
            startDate: moment().subtract(day, "days"),
            endDate: moment()
        };
    };

    //Watch for date changes
    $scope.$watch('date', function (newDate) {
        $scope.filter.startDate = newDate.startDate.format('YYYY-MM-DD');
        $scope.filter.endDate = newDate.endDate.format('YYYY-MM-DD');

        var days = Math.round((newDate.endDate - newDate.startDate) / 86400000);
        //console.log('days='+days);

        if ((newDate.endDate.format('YYYY-MM-DD') == moment().format('YYYY-MM-DD')) && (days == 7 || days == 30 || days == 1)) {
            $scope.day = days;
        } else {
            $scope.day = 0;
        }
        getResultsPage();
    }, false);
    /***Date range***/

    /* Filters */
    $scope.sortingList = function (filterColumn, order) {
        $scope.orderby = filterColumn;
        $scope.state = (order == 'DESC') ? 'ASC' : 'DESC';
        getResultsPage()
    }

    $scope.setStatus = function (key, name) {
        $scope.filter.priority = '';
        $scope.filter.status = key;
        $scope.filterTitle = name;
        getResultsPage();
    }
    $scope.setPriority = function (key, name) {
        $scope.filter.priority = key;
        $scope.filter.status = '';
        $scope.filterTitle = name;
        getResultsPage();
    }
    $scope.setCategory = function (key) {
        $scope.filter.category = key;
        getResultsPage();
    }
    $scope.setCity = function (key) {
        $scope.filter.city = key;
        getResultsPage();
    }
    $scope.setWard = function (key) {
        $scope.filter.ward = key;
        getResultsPage();
    }
    $scope.termSearch = function (term) {
        $scope.filter.term = term;
        getResultsPage();
    }
    /* Search */
    $scope.isSearch = false;

    $scope.openSearch = function () {
        $scope.isSearch = true;
    }

    $scope.closeSearch = function () {
        $scope.filter.term = '';
        getResultsPage();
        $scope.isSearch = false;
    }
    /* change priority */
    $scope.savePriority = function (complaintId, priority) {
        Data.put('complaint/changepriority', {complaintId: complaintId, priority: priority}).then(function (response) {
            Data.toast(response);
        });
    }

    function getResultsPage() {
        $scope.loading = true;
        //$scope.complaints = [];
        Data.post('complaint/lists/' + $scope.itemsPerPage + '/' + $scope.currentPage + '/' + $scope.orderby + '/' + $scope.state,
                {filters: $scope.filter}).then(function (response) {
            $scope.loading = false;
            $scope.complaints = response.result;
            $scope.totalItems = response.total_count;
            $scope.statusOpen = response.open;
            $scope.statusOnthejob = response.onthejob;
            $scope.statusResolved = response.resolved;
        });
    }
    $scope.engineers = [];
    Data.get('user/lists/0/' + $scope.currentPage + '/' + $scope.orderby).then(function (response) {
        $scope.engineers = response.result;
    });
    $scope.animationsEnabled = true;
    $scope.complaint_id = '';
    $scope.open = function (complaintId) {
        $scope.complaintId = complaintId;
        var modalInstance = $uibModal.open({
            animation: $scope.animationsEnabled,
            backdrop: 'static',
            templateUrl: 'assignComplaintModal.html',
            controller: 'ModalInstanceCtrl',
            resolve: {
                items: function () {
                    return $scope.engineers;
                },
                id: function () {
                    return $scope.complaintId;
                }
            }
        });
    };
    $scope.escengineers = [];
    Data.get('user/get_escengineers').then(function (response) {
        $scope.escengineers = response.result;
    });
    $scope.animationsEnabled = true;
    $scope.complaint_id = '';
    $scope.openEsc = function (complaintId) {
        $scope.complaintId = complaintId;
        var modalInstance = $uibModal.open({
            animation: $scope.animationsEnabled,
            backdrop: 'static',
            templateUrl: 'assingEscalationModal.html',
            controller: 'EscModalInstanceCtrl',
            resolve: {
                items: function () {
                    return $scope.escengineers;
                },
                id: function () {
                    return $scope.complaintId;
                }
            }
        });
    };
    /* for status popup */
    $scope.statusPopup = function (status, compId) {
        $scope.status = status;
        $scope.compId = compId;
        var modalInstance = $uibModal.open({
            animation: $scope.animationsEnabled,
            backdrop: 'static',
            templateUrl: 'commentForStatusModal.html',
            controller: 'StatusModalInstanceCtrl',
            resolve: {
                comment: function () {
                    return $scope.comment;
                },
                status: function () {
                    return $scope.status;
                },
                compId: function () {
                    return $scope.compId;
                }
            }
        });
    }
});
// Please note that $uibModalInstance represents a modal window (instance) dependency.
// It is not the same as the $uibModal service used above.

app.controller('ModalInstanceCtrl', function ($scope, $rootScope, $location, $http, Data, $window, $uibModalInstance, items, id, Data) {
    $scope.items = items;
    $scope.compId = id;
    $scope.assignEngineer = function (compId, engiId) {
        Data.post('complaint/assign_engineer', {complaint_id: compId, engineer_id: engiId}).then(function (response) {
            if (response.status == 'success') {
                Data.toast(response);
                $uibModalInstance.dismiss('cancel');
            } else {
                $scope.error_complaint_assigned = response.message;
            }
        });
    };
    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
});
app.controller('EscModalInstanceCtrl', function ($scope, $rootScope, $location, $http, Data, $window, $uibModalInstance, items, id, Data) {
    $scope.items = items;
    $scope.compId = id;
    $scope.assignEscEngineer = function (compId, engiId) {
        Data.post('complaint/assign_escalation_eng', {complaint_id: compId, engineer_id: engiId}).then(function (response) {
            if (response.status == 'success') {
                Data.toast(response);
                $uibModalInstance.dismiss('cancel');
            } else {
                $scope.error_complaint_assigned = response.message;
            }
        });
    };
    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
});
app.controller('StatusModalInstanceCtrl', function ($scope, $rootScope, $location, $http, Data, $window, $uibModalInstance, comment, status, compId) {
    $scope.comment = comment;
    $scope.compId = compId;
    $scope.status = status;
    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
    $scope.writeComment = function (compId, comment, status) {
        Data.put('complaint/changestatus', {complaintId: compId, comment: comment, status: status}).then(function (response) {
            Data.toast(response);
            $uibModalInstance.dismiss('cancel');
        });
    };
});<commit_msg>Remove token from query string<commit_after>/*!
 * AngularJS complaint controllers
 * Version: 1
 *
 * Copyright 2016 Janaagraha.
 *
 * Author: Jeeva D <jeevananthamcse@gmail.com>
 * Related to project of PM University
 */
app.controller('topicCtrl', function ($scope, Data, $uibModal) {
    $scope.topics = [];
    $scope.loading = false;

    /* pagination settings */
    $scope.totalItems = 0;
    $scope.currentPage = 1;
    $scope.itemsPerPage = 10;
    $scope.maxSize = 5;
    $scope.filterTitle = 'All Complaints';

    /* for sorting */
    $scope.state = 'DESC';
    $scope.orderby = 'id';
    getResultsPage();
    function getResultsPage() {
        $scope.loading = true;
        var url = '/api/v1/admin/1/topics?locale=en&perPage='+$scope.itemsPerPage+'&page='+$scope.currentPage;
        //var url = '/api/v1/admin/1/topics?locale=en&perPage='+$scope.itemsPerPage+'&page='+$scope.currentPage;
        //Data.post('complaint/lists/' + $scope.itemsPerPage + '/' + $scope.currentPage + '/' + $scope.orderby + '/' + $scope.state,
        Data.get(url,{filters: ''}).then(function (response) {
            $scope.loading = false;
            $scope.topics = response.data.topics;
            //console.log(response.data.topics);
            $scope.totalItems = response.data.total;
        });
    }
});
app.controller('compListCtrl', function ($scope, Data, $uibModal, $filter) {
    $scope.complaints = [];
    $scope.loading = false;
    $scope.checkedAny = false;
    /* pagination settings */
    $scope.totalItems = 0;
    $scope.currentPage = 1;
    $scope.itemsPerPage = 10;
    $scope.maxSize = 5;
    $scope.filterTitle = 'All Complaints';
    /* Status defaults */
    $scope.statusOpen = 0;
    $scope.statusOnthejob = 0;
    $scope.statusResolved = 0;
    /* for sorting */
    $scope.state = 'DESC';
    $scope.orderby = 'id';
    $scope.filter = {city: '', status: '', category: '', ward: '', term: '', priority: ''};
    /*set page*/
    $scope.setPage = function (pageNo) {
        $scope.currentPage = pageNo;
    };
    /*on page change*/
    $scope.pageChanged = function () {
        getResultsPage();
    };
    /* pagination settings */
    /* Check all */
    $scope.toggleAll = function () {
        var toggleStatus = $scope.isAllSelected;
        angular.forEach($scope.complaints, function (itm) {
            itm.cChecked = toggleStatus;
            //$scope.checkedAny = toggleStatus;
        });
    };
    /* Check each check box */
    $scope.optionToggled = function () {
        $scope.isAllSelected = $scope.complaints.every(function (itm) {
            return itm.cChecked;
        });
    };

    $scope.$watch("complaints", function (n, o) {
        var trues = $filter("filter")(n, {cChecked: true});
        $scope.checkedAny = (trues.length) ? true : false;
    }, true);
    /***Date range***/
    $scope.day = 1;
    $scope.date = {
        startDate: moment().subtract($scope.day, "days"),
        endDate: moment()
    };
    $scope.setRange = function (day) {
        $scope.day = day;
        $scope.date = {
            startDate: moment().subtract(day, "days"),
            endDate: moment()
        };
    };

    //Watch for date changes
    $scope.$watch('date', function (newDate) {
        $scope.filter.startDate = newDate.startDate.format('YYYY-MM-DD');
        $scope.filter.endDate = newDate.endDate.format('YYYY-MM-DD');

        var days = Math.round((newDate.endDate - newDate.startDate) / 86400000);
        //console.log('days='+days);

        if ((newDate.endDate.format('YYYY-MM-DD') == moment().format('YYYY-MM-DD')) && (days == 7 || days == 30 || days == 1)) {
            $scope.day = days;
        } else {
            $scope.day = 0;
        }
        getResultsPage();
    }, false);
    /***Date range***/

    /* Filters */
    $scope.sortingList = function (filterColumn, order) {
        $scope.orderby = filterColumn;
        $scope.state = (order == 'DESC') ? 'ASC' : 'DESC';
        getResultsPage()
    }

    $scope.setStatus = function (key, name) {
        $scope.filter.priority = '';
        $scope.filter.status = key;
        $scope.filterTitle = name;
        getResultsPage();
    }
    $scope.setPriority = function (key, name) {
        $scope.filter.priority = key;
        $scope.filter.status = '';
        $scope.filterTitle = name;
        getResultsPage();
    }
    $scope.setCategory = function (key) {
        $scope.filter.category = key;
        getResultsPage();
    }
    $scope.setCity = function (key) {
        $scope.filter.city = key;
        getResultsPage();
    }
    $scope.setWard = function (key) {
        $scope.filter.ward = key;
        getResultsPage();
    }
    $scope.termSearch = function (term) {
        $scope.filter.term = term;
        getResultsPage();
    }
    /* Search */
    $scope.isSearch = false;

    $scope.openSearch = function () {
        $scope.isSearch = true;
    }

    $scope.closeSearch = function () {
        $scope.filter.term = '';
        getResultsPage();
        $scope.isSearch = false;
    }
    /* change priority */
    $scope.savePriority = function (complaintId, priority) {
        Data.put('complaint/changepriority', {complaintId: complaintId, priority: priority}).then(function (response) {
            Data.toast(response);
        });
    }

    function getResultsPage() {
        $scope.loading = true;
        //$scope.complaints = [];
        Data.post('complaint/lists/' + $scope.itemsPerPage + '/' + $scope.currentPage + '/' + $scope.orderby + '/' + $scope.state,
                {filters: $scope.filter}).then(function (response) {
            $scope.loading = false;
            $scope.complaints = response.result;
            $scope.totalItems = response.total_count;
            $scope.statusOpen = response.open;
            $scope.statusOnthejob = response.onthejob;
            $scope.statusResolved = response.resolved;
        });
    }
    $scope.engineers = [];
    Data.get('user/lists/0/' + $scope.currentPage + '/' + $scope.orderby).then(function (response) {
        $scope.engineers = response.result;
    });
    $scope.animationsEnabled = true;
    $scope.complaint_id = '';
    $scope.open = function (complaintId) {
        $scope.complaintId = complaintId;
        var modalInstance = $uibModal.open({
            animation: $scope.animationsEnabled,
            backdrop: 'static',
            templateUrl: 'assignComplaintModal.html',
            controller: 'ModalInstanceCtrl',
            resolve: {
                items: function () {
                    return $scope.engineers;
                },
                id: function () {
                    return $scope.complaintId;
                }
            }
        });
    };
    $scope.escengineers = [];
    Data.get('user/get_escengineers').then(function (response) {
        $scope.escengineers = response.result;
    });
    $scope.animationsEnabled = true;
    $scope.complaint_id = '';
    $scope.openEsc = function (complaintId) {
        $scope.complaintId = complaintId;
        var modalInstance = $uibModal.open({
            animation: $scope.animationsEnabled,
            backdrop: 'static',
            templateUrl: 'assingEscalationModal.html',
            controller: 'EscModalInstanceCtrl',
            resolve: {
                items: function () {
                    return $scope.escengineers;
                },
                id: function () {
                    return $scope.complaintId;
                }
            }
        });
    };
    /* for status popup */
    $scope.statusPopup = function (status, compId) {
        $scope.status = status;
        $scope.compId = compId;
        var modalInstance = $uibModal.open({
            animation: $scope.animationsEnabled,
            backdrop: 'static',
            templateUrl: 'commentForStatusModal.html',
            controller: 'StatusModalInstanceCtrl',
            resolve: {
                comment: function () {
                    return $scope.comment;
                },
                status: function () {
                    return $scope.status;
                },
                compId: function () {
                    return $scope.compId;
                }
            }
        });
    }
});
// Please note that $uibModalInstance represents a modal window (instance) dependency.
// It is not the same as the $uibModal service used above.

app.controller('ModalInstanceCtrl', function ($scope, $rootScope, $location, $http, Data, $window, $uibModalInstance, items, id, Data) {
    $scope.items = items;
    $scope.compId = id;
    $scope.assignEngineer = function (compId, engiId) {
        Data.post('complaint/assign_engineer', {complaint_id: compId, engineer_id: engiId}).then(function (response) {
            if (response.status == 'success') {
                Data.toast(response);
                $uibModalInstance.dismiss('cancel');
            } else {
                $scope.error_complaint_assigned = response.message;
            }
        });
    };
    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
});
app.controller('EscModalInstanceCtrl', function ($scope, $rootScope, $location, $http, Data, $window, $uibModalInstance, items, id, Data) {
    $scope.items = items;
    $scope.compId = id;
    $scope.assignEscEngineer = function (compId, engiId) {
        Data.post('complaint/assign_escalation_eng', {complaint_id: compId, engineer_id: engiId}).then(function (response) {
            if (response.status == 'success') {
                Data.toast(response);
                $uibModalInstance.dismiss('cancel');
            } else {
                $scope.error_complaint_assigned = response.message;
            }
        });
    };
    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
});
app.controller('StatusModalInstanceCtrl', function ($scope, $rootScope, $location, $http, Data, $window, $uibModalInstance, comment, status, compId) {
    $scope.comment = comment;
    $scope.compId = compId;
    $scope.status = status;
    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
    $scope.writeComment = function (compId, comment, status) {
        Data.put('complaint/changestatus', {complaintId: compId, comment: comment, status: status}).then(function (response) {
            Data.toast(response);
            $uibModalInstance.dismiss('cancel');
        });
    };
});<|endoftext|>


<commit_before>// Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
//
// MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

//
// Form Input
// ======================================================================================

_f.ColumnBreak = function() {
	this.set_input = function() { };
}

_f.ColumnBreak.prototype.make_body = function() {
	this.cell = this.frm.layout.addcell(this.df.width);
	$y(this.cell.wrapper, {padding: '8px'});
	_f.cur_col_break_width = this.df.width;

	var fn = this.df.fieldname?this.df.fieldname:this.df.label;
	// header
	if(this.df&&this.df.label){
		this.label = $a(this.cell.wrapper, 'h4', '', '', this.df.label);
	}
}

_f.ColumnBreak.prototype.refresh = function(layout) {
	//if(!this.cell)return; // no perm

	var hidden = 0;
	// we generate column breaks, but hide it based on perms/hidden value
	if((!this.perm[this.df.permlevel]) || (!this.perm[this.df.permlevel][READ]) ||
		this.df.hidden) {
		// do not display, as no permission
		hidden = 1;
	}

	// hidden
	if(this.set_hidden!=hidden) {
		if(hidden)
			this.cell.hide();
		else
			this.cell.show();
		this.set_hidden = hidden;
	}
}

// ======================================================================================

_f.SectionBreak = function() {
	this.fields = [];
	this.set_input = function() { };
	this.make_row = function() {
		this.row = this.df.label ? this.frm.layout.addrow() : this.frm.layout.addsubrow();
	}
}

_f.SectionBreak.prototype.make_body = function() {
	var me = this;
	this.make_row();

	if(this.df.label) {
		if(!this.df.description)
			this.df.description = '';
		$(this.row.main_head).html(repl('
\

%(label)s
\

%(description)s
\

', this.df));
	} else {
		// simple
		$(this.wrapper).html('

');
	}

	// collapse section
	this.section_collapse = function() {
		$(me.row.main_head).find('.head')
			.html(' \
				Show "' + me.df.label + '"');
		$(me.row.main_body).toggle(false);

	}

	// expand section
	this.section_expand = function(no_animation) {
		$(me.row.main_head).find('.head')
			.html('
 '
				+ me.df.label + '
');
		if(no_animation)
			$(me.row.main_body).toggle(true);
		else
			$(me.row.main_body).slideDown();
	}
}

_f.SectionBreak.prototype.has_data = function() {
	// return true if
	// 1. any field in the section is mandatory & not set as default
	// 2. any field in the section has data that is not default
	// 3. if table, table has rows

	var me = this;
	for(var i in me.fields) {
		var f = me.fields[i];
		var v = f.get_value ? f.get_value() : null;

		// value that is not default
		defaultval = f.df['default'] || sys_defaults[f.fieldname] || user_defaults[f.fieldname];
		if(v && v != defaultval) {
			return true;
		}

		// unfilled mandatory field
		if(f.df.reqd && !v) {
			return true;
		}

		// filled table
		if(f.df.fieldtype=='Table') {
			if(f.grid.get_children().length || f.df.reqd) {
				return true;
			}
		}
	}
	return false;
}

_f.SectionBreak.prototype.refresh = function(from_form) {
	var hidden = 0;
	// we generate section breaks, but hide it based on perms/hidden value
	if((!this.perm[this.df.permlevel]) || (!this.perm[this.df.permlevel][READ]) || this.df.hidden) {
		// no display
		hidden = 1;
	}

	if(hidden) {
		if(this.row)this.row.hide();
	} else {
		if(this.row)this.row.show();
	}
}

// Image field definition
// ======================================================================================

_f.ImageField = function() { this.images = {}; }
_f.ImageField.prototype = new Field();
_f.ImageField.prototype.onrefresh = function() {
	$(this.label_span).toggle(false);
	$(this.wrapper).find("img").remove();
	if(this.df.options && this.frm.doc[this.df.options]) {
		$("")
			.appendTo($(this.wrapper).empty());
	} else {
		$("

")
			.appendTo($(this.wrapper).empty())
	}
}

_f.ImageField.prototype.set_disp = function (val) { }
_f.ImageField.prototype.set = function (val) { }

// Table
// ======================================================================================

_f.TableField = function() { };
_f.TableField.prototype = new Field();
_f.TableField.prototype.with_label = 0;
_f.TableField.prototype.make_body = function() {
	if(this.perm[this.df.permlevel] && this.perm[this.df.permlevel][READ]) {
		this.wrapper = $("
").appendTo(this.parent).get(0);
		this.grid = new _f.FormGrid(this);
		if(this.frm)this.frm.grids[this.frm.grids.length] = this;
		this.grid.make_buttons();

		// description
		if(this.df.description) {
			this.desc_area = $a(this.wrapper, 'div', 'help small',
				{marginBottom:'9px', marginTop:'0px'}, this.df.description)
		}
	}
}

_f.TableField.prototype.refresh = function() {
	if(!this.grid)return;

	// hide / show grid
	var st = this.get_status();

	if(!this.df['default'])
		this.df['default']='';

	this.grid.can_add_rows = false;
	this.grid.can_edit = false
	if(st=='Write') {
		if(cur_frm.editable && this.perm[this.df.permlevel] && this.perm[this.df.permlevel][WRITE]) {
			this.grid.can_edit = true;
			if(this.df['default'].toLowerCase()!='no toolbar')
				this.grid.can_add_rows = true;
		}

		// submitted or cancelled
		if(cur_frm.editable && cur_frm.doc.docstatus > 0) {
			if(this.df.allow_on_submit && cur_frm.doc.docstatus==1) {
				this.grid.can_edit = true;
				if(this.df['default'].toLowerCase()=='no toolbar') {
					this.grid.can_add_rows = false;
				} else {
					this.grid.can_add_rows = true;
				}
			} else {
				this.grid.can_add_rows = false;
				this.grid.can_edit = false;
			}
		}

		if(this.df['default'].toLowerCase()=='no add rows') {
			this.grid.can_add_rows = false;
		}
	}

	if(st=='Write' || st=="Read") {
		$(this.wrapper).toggle(true);
		this.grid.show();
	} else {
		$(this.wrapper).toggle(false);
		this.grid.hide();
	}

	this.grid.refresh();
}

_f.TableField.prototype.set = function(v) { }; // nothing
_f.TableField.prototype.set_input = function(v) { }; // nothing

// ==============================================================

_f.CodeField = function() { };
_f.CodeField.prototype = new Field();
_f.CodeField.prototype.make_input = function() {
	var me = this;

	this.label_span.innerHTML = this.df.label;

	if(this.df.fieldtype=='Text Editor') {
		$(this.input_area).css({"min-height":"360px"});
		this.input = $a(this.input_area, 'text_area', '', {fontSize:'12px'});
		this.myid = wn.dom.set_unique_id(this.input);

		// setup tiny mce
		$(me.input).tinymce({
			// Location of TinyMCE script
			script_url : 'lib/js/lib/tiny_mce_3.5.7/tiny_mce.js',

			// General options
			theme : "advanced",
			plugins : "style,inlinepopups,table,advimage",

			// w/h
			width: '100%',
			height: '360px',

			// buttons
			theme_advanced_buttons1 : "bold,italic,underline,hr,|,justifyleft,justifycenter,|,formatselect,fontsizeselect,|,bullist,numlist,|,outdent,indent,|,link,unlink,|,forecolor,backcolor,|,code",
			theme_advanced_buttons2 : "",
			theme_advanced_buttons3 : "",

			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location: "none",
			theme_advanced_path: false,

			valid_elements : "*[*]",

			content_css: "lib/js/lib/tiny_mce_3.5.7/custom_content.css?q=1",

			oninit: function() { me.init_editor(); }
		});

		this.input.set_input = function(v) {
			if(me.editor) {
				me.editor.setContent(v);
			} else {
				$(me.input).val(v);
			}
		}
		this.input.onchange = function() {
			me.set(me.editor.getContent());
			me.run_trigger();
		}
		this.get_value = function() {
			return me.editor && me.editor.getContent(); // tinyMCE
		}

	} else {
		// setup ace
		wn.require('lib/js/lib/ace/ace.js');

		$(this.input_area).css('border','1px solid #aaa');
		this.pre = $("
").appendTo(this.input_area).get(0);

		this.input = {};
		this.myid = wn.dom.set_unique_id(this.pre);
		this.editor = ace.edit(this.myid);

		if(me.df.options=='Markdown' || me.df.options=='HTML') {
			wn.require('lib/js/lib/ace/mode-html.js');
			var HTMLMode = require("ace/mode/html").Mode;
		    me.editor.getSession().setMode(new HTMLMode());
		}

		else if(me.df.options=='Javascript') {
			wn.require('lib/js/lib/ace/mode-javascript.js');
			var JavascriptMode = require("ace/mode/javascript").Mode;
		    me.editor.getSession().setMode(new JavascriptMode());
		}

		else if(me.df.options=='Python') {
			wn.require('lib/js/lib/ace/mode-python.js');
			var PythonMode = require("ace/mode/python").Mode;
		    me.editor.getSession().setMode(new PythonMode());
		}

		this.input.set_input = function(v) {
			// during field refresh in run trigger, set_input is called
			// if called during on_change, setting doesn't make sense
			// and causes cursor to shift back to first position
			if(me.changing_value) return;

			me.setting_value = true;
			me.editor.getSession().setValue(v);
			me.setting_value = false;
		}

		this.get_value = function() {
			return me.editor.getSession().getValue(); // tinyMCE
		}
		$(cur_frm.wrapper).bind('render_complete', function() {
			me.editor.resize();
			me.editor.getSession().on('change', function() {
				if(me.setting_value) return;
				var val = me.get_value();
				if(locals[cur_frm.doctype][cur_frm.docname][me.df.fieldname] != val) {
					me.set(me.get_value());

					me.changing_value = true;
					me.run_trigger();
					me.changing_value = false;
				}
			})
		});

	}

}

_f.CodeField.prototype.init_editor = function() {
	// attach onchange methods
	var me = this;
	this.editor = tinymce.get(this.myid);
	this.editor.onKeyUp.add(function(ed, e) {
		me.set(ed.getContent());
	});
	this.editor.onPaste.add(function(ed, e) {
		me.set(ed.getContent());
	});
	this.editor.onSetContent.add(function(ed, e) {
		me.set(ed.getContent());
	});

	// reset content
	var c = locals[cur_frm.doctype][cur_frm.docname][this.df.fieldname];
	if(cur_frm && c) {
		this.editor.setContent(c);
	}
}

_f.CodeField.prototype.set_disp = function(val) {
	$y(this.disp_area, {width:'90%'})
	if(this.df.fieldtype=='Text Editor') {
		this.disp_area.innerHTML = val;
	} else {
		this.disp_area.innerHTML = '<textarea class="code_text" readonly=1>'+val+'</textarea>';
	}
}

// ======================================================================================

<commit_msg>tiny_mce:removed added script|embed in extended_valid_elements<commit_after>// Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
//
// MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

//
// Form Input
// ======================================================================================

_f.ColumnBreak = function() {
	this.set_input = function() { };
}

_f.ColumnBreak.prototype.make_body = function() {
	this.cell = this.frm.layout.addcell(this.df.width);
	$y(this.cell.wrapper, {padding: '8px'});
	_f.cur_col_break_width = this.df.width;

	var fn = this.df.fieldname?this.df.fieldname:this.df.label;
	// header
	if(this.df&&this.df.label){
		this.label = $a(this.cell.wrapper, 'h4', '', '', this.df.label);
	}
}

_f.ColumnBreak.prototype.refresh = function(layout) {
	//if(!this.cell)return; // no perm

	var hidden = 0;
	// we generate column breaks, but hide it based on perms/hidden value
	if((!this.perm[this.df.permlevel]) || (!this.perm[this.df.permlevel][READ]) ||
		this.df.hidden) {
		// do not display, as no permission
		hidden = 1;
	}

	// hidden
	if(this.set_hidden!=hidden) {
		if(hidden)
			this.cell.hide();
		else
			this.cell.show();
		this.set_hidden = hidden;
	}
}

// ======================================================================================

_f.SectionBreak = function() {
	this.fields = [];
	this.set_input = function() { };
	this.make_row = function() {
		this.row = this.df.label ? this.frm.layout.addrow() : this.frm.layout.addsubrow();
	}
}

_f.SectionBreak.prototype.make_body = function() {
	var me = this;
	this.make_row();

	if(this.df.label) {
		if(!this.df.description)
			this.df.description = '';
		$(this.row.main_head).html(repl('
\

%(label)s
\

%(description)s
\

', this.df));
	} else {
		// simple
		$(this.wrapper).html('

');
	}

	// collapse section
	this.section_collapse = function() {
		$(me.row.main_head).find('.head')
			.html(' \
				Show "' + me.df.label + '"');
		$(me.row.main_body).toggle(false);

	}

	// expand section
	this.section_expand = function(no_animation) {
		$(me.row.main_head).find('.head')
			.html('
 '
				+ me.df.label + '
');
		if(no_animation)
			$(me.row.main_body).toggle(true);
		else
			$(me.row.main_body).slideDown();
	}
}

_f.SectionBreak.prototype.has_data = function() {
	// return true if
	// 1. any field in the section is mandatory & not set as default
	// 2. any field in the section has data that is not default
	// 3. if table, table has rows

	var me = this;
	for(var i in me.fields) {
		var f = me.fields[i];
		var v = f.get_value ? f.get_value() : null;

		// value that is not default
		defaultval = f.df['default'] || sys_defaults[f.fieldname] || user_defaults[f.fieldname];
		if(v && v != defaultval) {
			return true;
		}

		// unfilled mandatory field
		if(f.df.reqd && !v) {
			return true;
		}

		// filled table
		if(f.df.fieldtype=='Table') {
			if(f.grid.get_children().length || f.df.reqd) {
				return true;
			}
		}
	}
	return false;
}

_f.SectionBreak.prototype.refresh = function(from_form) {
	var hidden = 0;
	// we generate section breaks, but hide it based on perms/hidden value
	if((!this.perm[this.df.permlevel]) || (!this.perm[this.df.permlevel][READ]) || this.df.hidden) {
		// no display
		hidden = 1;
	}

	if(hidden) {
		if(this.row)this.row.hide();
	} else {
		if(this.row)this.row.show();
	}
}

// Image field definition
// ======================================================================================

_f.ImageField = function() { this.images = {}; }
_f.ImageField.prototype = new Field();
_f.ImageField.prototype.onrefresh = function() {
	$(this.label_span).toggle(false);
	$(this.wrapper).find("img").remove();
	if(this.df.options && this.frm.doc[this.df.options]) {
		$("")
			.appendTo($(this.wrapper).empty());
	} else {
		$("

")
			.appendTo($(this.wrapper).empty())
	}
}

_f.ImageField.prototype.set_disp = function (val) { }
_f.ImageField.prototype.set = function (val) { }

// Table
// ======================================================================================

_f.TableField = function() { };
_f.TableField.prototype = new Field();
_f.TableField.prototype.with_label = 0;
_f.TableField.prototype.make_body = function() {
	if(this.perm[this.df.permlevel] && this.perm[this.df.permlevel][READ]) {
		this.wrapper = $("
").appendTo(this.parent).get(0);
		this.grid = new _f.FormGrid(this);
		if(this.frm)this.frm.grids[this.frm.grids.length] = this;
		this.grid.make_buttons();

		// description
		if(this.df.description) {
			this.desc_area = $a(this.wrapper, 'div', 'help small',
				{marginBottom:'9px', marginTop:'0px'}, this.df.description)
		}
	}
}

_f.TableField.prototype.refresh = function() {
	if(!this.grid)return;

	// hide / show grid
	var st = this.get_status();

	if(!this.df['default'])
		this.df['default']='';

	this.grid.can_add_rows = false;
	this.grid.can_edit = false
	if(st=='Write') {
		if(cur_frm.editable && this.perm[this.df.permlevel] && this.perm[this.df.permlevel][WRITE]) {
			this.grid.can_edit = true;
			if(this.df['default'].toLowerCase()!='no toolbar')
				this.grid.can_add_rows = true;
		}

		// submitted or cancelled
		if(cur_frm.editable && cur_frm.doc.docstatus > 0) {
			if(this.df.allow_on_submit && cur_frm.doc.docstatus==1) {
				this.grid.can_edit = true;
				if(this.df['default'].toLowerCase()=='no toolbar') {
					this.grid.can_add_rows = false;
				} else {
					this.grid.can_add_rows = true;
				}
			} else {
				this.grid.can_add_rows = false;
				this.grid.can_edit = false;
			}
		}

		if(this.df['default'].toLowerCase()=='no add rows') {
			this.grid.can_add_rows = false;
		}
	}

	if(st=='Write' || st=="Read") {
		$(this.wrapper).toggle(true);
		this.grid.show();
	} else {
		$(this.wrapper).toggle(false);
		this.grid.hide();
	}

	this.grid.refresh();
}

_f.TableField.prototype.set = function(v) { }; // nothing
_f.TableField.prototype.set_input = function(v) { }; // nothing

// ==============================================================

_f.CodeField = function() { };
_f.CodeField.prototype = new Field();
_f.CodeField.prototype.make_input = function() {
	var me = this;

	this.label_span.innerHTML = this.df.label;

	if(this.df.fieldtype=='Text Editor') {
		$(this.input_area).css({"min-height":"360px"});
		this.input = $a(this.input_area, 'text_area', '', {fontSize:'12px'});
		this.myid = wn.dom.set_unique_id(this.input);

		// setup tiny mce
		$(me.input).tinymce({
			// Location of TinyMCE script
			script_url : 'lib/js/lib/tiny_mce_3.5.7/tiny_mce.js',

			// General options
			theme : "advanced",
			plugins : "style,inlinepopups,table,advimage",
			extended_valid_elements: "script|embed",

			// w/h
			width: '100%',
			height: '360px',

			// buttons
			theme_advanced_buttons1 : "bold,italic,underline,hr,|,justifyleft,justifycenter,|,formatselect,fontsizeselect,|,bullist,numlist,|,outdent,indent,|,link,unlink,|,forecolor,backcolor,|,code",
			theme_advanced_buttons2 : "",
			theme_advanced_buttons3 : "",

			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location: "none",
			theme_advanced_path: false,

			valid_elements : "*[*]",

			content_css: "lib/js/lib/tiny_mce_3.5.7/custom_content.css?q=1",

			oninit: function() { me.init_editor(); }
		});

		this.input.set_input = function(v) {
			if(me.editor) {
				me.editor.setContent(v);
			} else {
				$(me.input).val(v);
			}
		}
		this.input.onchange = function() {
			me.set(me.editor.getContent());
			me.run_trigger();
		}
		this.get_value = function() {
			return me.editor && me.editor.getContent(); // tinyMCE
		}

	} else {
		// setup ace
		wn.require('lib/js/lib/ace/ace.js');

		$(this.input_area).css('border','1px solid #aaa');
		this.pre = $("
").appendTo(this.input_area).get(0);

		this.input = {};
		this.myid = wn.dom.set_unique_id(this.pre);
		this.editor = ace.edit(this.myid);

		if(me.df.options=='Markdown' || me.df.options=='HTML') {
			wn.require('lib/js/lib/ace/mode-html.js');
			var HTMLMode = require("ace/mode/html").Mode;
		    me.editor.getSession().setMode(new HTMLMode());
		}

		else if(me.df.options=='Javascript') {
			wn.require('lib/js/lib/ace/mode-javascript.js');
			var JavascriptMode = require("ace/mode/javascript").Mode;
		    me.editor.getSession().setMode(new JavascriptMode());
		}

		else if(me.df.options=='Python') {
			wn.require('lib/js/lib/ace/mode-python.js');
			var PythonMode = require("ace/mode/python").Mode;
		    me.editor.getSession().setMode(new PythonMode());
		}

		this.input.set_input = function(v) {
			// during field refresh in run trigger, set_input is called
			// if called during on_change, setting doesn't make sense
			// and causes cursor to shift back to first position
			if(me.changing_value) return;

			me.setting_value = true;
			me.editor.getSession().setValue(v);
			me.setting_value = false;
		}

		this.get_value = function() {
			return me.editor.getSession().getValue(); // tinyMCE
		}
		$(cur_frm.wrapper).bind('render_complete', function() {
			me.editor.resize();
			me.editor.getSession().on('change', function() {
				if(me.setting_value) return;
				var val = me.get_value();
				if(locals[cur_frm.doctype][cur_frm.docname][me.df.fieldname] != val) {
					me.set(me.get_value());

					me.changing_value = true;
					me.run_trigger();
					me.changing_value = false;
				}
			})
		});

	}

}

_f.CodeField.prototype.init_editor = function() {
	// attach onchange methods
	var me = this;
	this.editor = tinymce.get(this.myid);
	this.editor.onKeyUp.add(function(ed, e) {
		me.set(ed.getContent());
	});
	this.editor.onPaste.add(function(ed, e) {
		me.set(ed.getContent());
	});
	this.editor.onSetContent.add(function(ed, e) {
		me.set(ed.getContent());
	});

	// reset content
	var c = locals[cur_frm.doctype][cur_frm.docname][this.df.fieldname];
	if(cur_frm && c) {
		this.editor.setContent(c);
	}
}

_f.CodeField.prototype.set_disp = function(val) {
	$y(this.disp_area, {width:'90%'})
	if(this.df.fieldtype=='Text Editor') {
		this.disp_area.innerHTML = val;
	} else {
		this.disp_area.innerHTML = '<textarea class="code_text" readonly=1>'+val+'</textarea>';
	}
}

// ======================================================================================

<|endoftext|>


<commit_before>'use strict';

/**
 * Here is the problem: http://bugs.jquery.com/ticket/7292
 * basically jQuery treats change event on some browsers (IE) as a
 * special event and changes it form 'change' to 'click/keydown' and
 * few others. This horrible hack removes the special treatment
 */
if (window._jQuery) _jQuery.event.special.change = undefined;

if (window.bindJQuery) bindJQuery();

beforeEach(function() {
  // all this stuff is not needed for module tests, where jqlite and publishExternalAPI and jqLite are not global vars
  if (window.publishExternalAPI) {
    publishExternalAPI(angular);

    // workaround for IE bug https://plus.google.com/104744871076396904202/posts/Kqjuj6RSbbT
    // IE overwrite window.jQuery with undefined because of empty jQuery var statement, so we have to
    // correct this, but only if we are not running in jqLite mode
    if (!_jqLiteMode && _jQuery !== jQuery) {
      jQuery = _jQuery;
    }

    // This resets global id counter;
    uid = ['0', '0', '0'];

    // reset to jQuery or default to us.
    bindJQuery();
  }

  angular.element(document.body).html('').removeData();
});

afterEach(function() {
  if (this.$injector) {
    var $rootScope = this.$injector.get('$rootScope');
    var $rootElement = this.$injector.get('$rootElement');
    var $log = this.$injector.get('$log');
    // release the injector
    dealoc($rootScope);
    dealoc($rootElement);

    // check $log mock
    $log.assertEmpty && $log.assertEmpty();
  }

  // complain about uncleared jqCache references
  var count = 0;

  // This line should be enabled as soon as this bug is fixed: http://bugs.jquery.com/ticket/11775
  //var cache = jqLite.cache;
  var cache = angular.element.cache;

  forEachSorted(cache, function(expando, key){
    angular.forEach(expando.data, function(value, key){
      count ++;
      if (value.$element) {
        dump('LEAK', key, value.$id, sortedHtml(value.$element));
      } else {
        dump('LEAK', key, angular.toJson(value));
      }
    });
  });
  if (count) {
    throw new Error('Found jqCache references that were not deallocated! count: ' + count);
  }

  // copied from Angular.js
  // we need these two methods here so that we can run module tests with wrapped angular.js
  function sortedKeys(obj) {
    var keys = [];
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        keys.push(key);
      }
    }
    return keys.sort();
  }

  function forEachSorted(obj, iterator, context) {
    var keys = sortedKeys(obj);
    for ( var i = 0; i < keys.length; i++) {
      iterator.call(context, obj[keys[i]], keys[i]);
    }
    return keys;
  }
});

function dealoc(obj) {
  var jqCache = angular.element.cache;
  if (obj) {
    if (angular.isElement(obj)) {
      cleanup(angular.element(obj));
    } else {
      for(var key in jqCache) {
        var value = jqCache[key];
        if (value.data && value.data.$scope == obj) {
          delete jqCache[key];
        }
      }
    }
  }

  function cleanup(element) {
    element.off().removeData();
    for ( var i = 0, children = element.contents() || []; i < children.length; i++) {
      cleanup(angular.element(children[i]));
    }
  }
}

/**
 * @param {DOMElement} element
 * @param {boolean=} showNgClass
 */
function sortedHtml(element, showNgClass) {
  var html = "";
  forEach(jqLite(element), function toString(node) {

    if (node.nodeName == "#text") {
      html += node.nodeValue.
        replace(/&(\w+[&;\W])?/g, function(match, entity){return entity?match:'&';}).
        replace(/</g, '<').
        replace(/>/g, '>');
    } else if (node.nodeName == "#comment") {
      html += '<!--' + node.nodeValue + '-->';
    } else {
      html += '<' + (node.nodeName || '?NOT_A_NODE?').toLowerCase();
      var attributes = node.attributes || [];
      var attrs = [];
      var className = node.className || '';
      if (!showNgClass) {
        className = className.replace(/ng-[\w-]+\s*/g, '');
      }
      className = trim(className);
      if (className) {
        attrs.push(' class="' + className + '"');
      }
      for(var i=0; i<attributes.length; i++) {
        if (i>0 && attributes[i] == attributes[i-1])
          continue; //IE9 creates dupes. Ignore them!

        var attr = attributes[i];
        if(attr.name.match(/^ng[\:\-]/) ||
            (attr.value || attr.value == '') &&
            attr.value !='null' &&
            attr.value !='auto' &&
            attr.value !='false' &&
            attr.value !='inherit' &&
            (attr.value !='0' || attr.name =='value') &&
            attr.name !='loop' &&
            attr.name !='complete' &&
            attr.name !='maxLength' &&
            attr.name !='size' &&
            attr.name !='class' &&
            attr.name !='start' &&
            attr.name !='tabIndex' &&
            attr.name !='style' &&
            attr.name.substr(0, 6) != 'jQuery') {
          // in IE we need to check for all of these.
          if (/ng-\d+/.exec(attr.name) ||
              attr.name == 'getElementById' ||
              // IE7 has `selected` in attributes
              attr.name == 'selected' ||
              // IE7 adds `value` attribute to all LI tags
              (node.nodeName == 'LI' && attr.name == 'value') ||
              // IE8 adds bogus rowspan=1 and colspan=1 to TD elements
              (node.nodeName == 'TD' && attr.name == 'rowSpan' && attr.value == '1') ||
              (node.nodeName == 'TD' && attr.name == 'colSpan' && attr.value == '1')) {
            continue;
          }

          attrs.push(' ' + attr.name + '="' + attr.value + '"');
        }
      }
      attrs.sort();
      html += attrs.join('');
      if (node.style) {
        var style = [];
        if (node.style.cssText) {
          forEach(node.style.cssText.split(';'), function(value){
            value = trim(value);
            if (value) {
              style.push(lowercase(value));
            }
          });
        }
        for(var css in node.style){
          var value = node.style[css];
          if (isString(value) && isString(css) && css != 'cssText' && value && (1*css != css)) {
            var text = lowercase(css + ': ' + value);
            if (value != 'false' && indexOf(style, text) == -1) {
              style.push(text);
            }
          }
        }
        style.sort();
        var tmp = style;
        style = [];
        forEach(tmp, function(value){
          if (!value.match(/^max[^\-]/))
            style.push(value);
        });
        if (style.length) {
          html += ' style="' + style.join('; ') + ';"';
        }
      }
      html += '>';
      var children = node.childNodes;
      for(var j=0; j<children.length; j++) {
        toString(children[j]);
      }
      html += '</' + node.nodeName.toLowerCase() + '>';
    }
  });
  return html;
}

// TODO(vojta): migrate these helpers into jasmine matchers
/**a
 * This method is a cheap way of testing if css for a given node is not set to 'none'. It doesn't
 * actually test if an element is displayed by the browser. Be aware!!!
 */
function isCssVisible(node) {
  var display = node.css('display');
  return display != 'none';
}

function assertHidden(node) {
  if (isCssVisible(node)) {
    throw new Error('Node should be hidden but was visible: ' + angular.module.ngMock.dump(node));
  }
}

function assertVisible(node) {
  if (!isCssVisible(node)) {
    throw new Error('Node should be visible but was hidden: ' + angular.module.ngMock.dump(node));
  }
}

function provideLog($provide) {
  $provide.factory('log', function() {
      var messages = [];

      function log(msg) {
        messages.push(msg);
        return msg;
      }

      log.toString = function() {
        return messages.join('; ');
      }

      log.toArray = function() {
        return messages;
      }

      log.reset = function() {
        messages = [];
      }

      log.fn = function(msg) {
        return function() {
          log(msg);
        }
      }

      log.$$log = true;

      return log;
    });
}

function pending() {
  dump('PENDING');
};

function trace(name) {
  dump(new Error(name).stack);
}
<commit_msg>fix(dump): Prevented window.dump from being overridden by karma-jasmine.<commit_after>'use strict';

/**
 * Here is the problem: http://bugs.jquery.com/ticket/7292
 * basically jQuery treats change event on some browsers (IE) as a
 * special event and changes it form 'change' to 'click/keydown' and
 * few others. This horrible hack removes the special treatment
 */
if (window._jQuery) _jQuery.event.special.change = undefined;

if (window.bindJQuery) bindJQuery();

beforeEach(function() {
  // all this stuff is not needed for module tests, where jqlite and publishExternalAPI and jqLite are not global vars
  if (window.publishExternalAPI) {
    publishExternalAPI(angular);

    // workaround for IE bug https://plus.google.com/104744871076396904202/posts/Kqjuj6RSbbT
    // IE overwrite window.jQuery with undefined because of empty jQuery var statement, so we have to
    // correct this, but only if we are not running in jqLite mode
    if (!_jqLiteMode && _jQuery !== jQuery) {
      jQuery = _jQuery;
    }

    // This resets global id counter;
    uid = ['0', '0', '0'];

    // reset to jQuery or default to us.
    bindJQuery();
  }

  angular.element(document.body).html('').removeData();
});

afterEach(function() {
  if (this.$injector) {
    var $rootScope = this.$injector.get('$rootScope');
    var $rootElement = this.$injector.get('$rootElement');
    var $log = this.$injector.get('$log');
    // release the injector
    dealoc($rootScope);
    dealoc($rootElement);

    // check $log mock
    $log.assertEmpty && $log.assertEmpty();
  }

  // complain about uncleared jqCache references
  var count = 0;

  // This line should be enabled as soon as this bug is fixed: http://bugs.jquery.com/ticket/11775
  //var cache = jqLite.cache;
  var cache = angular.element.cache;

  forEachSorted(cache, function(expando, key){
    angular.forEach(expando.data, function(value, key){
      count ++;
      if (value.$element) {
        dump('LEAK', key, value.$id, sortedHtml(value.$element));
      } else {
        dump('LEAK', key, angular.toJson(value));
      }
    });
  });
  if (count) {
    throw new Error('Found jqCache references that were not deallocated! count: ' + count);
  }

  // copied from Angular.js
  // we need these two methods here so that we can run module tests with wrapped angular.js
  function sortedKeys(obj) {
    var keys = [];
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        keys.push(key);
      }
    }
    return keys.sort();
  }

  function forEachSorted(obj, iterator, context) {
    var keys = sortedKeys(obj);
    for ( var i = 0; i < keys.length; i++) {
      iterator.call(context, obj[keys[i]], keys[i]);
    }
    return keys;
  }
});

function dealoc(obj) {
  var jqCache = angular.element.cache;
  if (obj) {
    if (angular.isElement(obj)) {
      cleanup(angular.element(obj));
    } else {
      for(var key in jqCache) {
        var value = jqCache[key];
        if (value.data && value.data.$scope == obj) {
          delete jqCache[key];
        }
      }
    }
  }

  function cleanup(element) {
    element.off().removeData();
    for ( var i = 0, children = element.contents() || []; i < children.length; i++) {
      cleanup(angular.element(children[i]));
    }
  }
}

/**
 * @param {DOMElement} element
 * @param {boolean=} showNgClass
 */
function sortedHtml(element, showNgClass) {
  var html = "";
  forEach(jqLite(element), function toString(node) {

    if (node.nodeName == "#text") {
      html += node.nodeValue.
        replace(/&(\w+[&;\W])?/g, function(match, entity){return entity?match:'&';}).
        replace(/</g, '<').
        replace(/>/g, '>');
    } else if (node.nodeName == "#comment") {
      html += '<!--' + node.nodeValue + '-->';
    } else {
      html += '<' + (node.nodeName || '?NOT_A_NODE?').toLowerCase();
      var attributes = node.attributes || [];
      var attrs = [];
      var className = node.className || '';
      if (!showNgClass) {
        className = className.replace(/ng-[\w-]+\s*/g, '');
      }
      className = trim(className);
      if (className) {
        attrs.push(' class="' + className + '"');
      }
      for(var i=0; i<attributes.length; i++) {
        if (i>0 && attributes[i] == attributes[i-1])
          continue; //IE9 creates dupes. Ignore them!

        var attr = attributes[i];
        if(attr.name.match(/^ng[\:\-]/) ||
            (attr.value || attr.value == '') &&
            attr.value !='null' &&
            attr.value !='auto' &&
            attr.value !='false' &&
            attr.value !='inherit' &&
            (attr.value !='0' || attr.name =='value') &&
            attr.name !='loop' &&
            attr.name !='complete' &&
            attr.name !='maxLength' &&
            attr.name !='size' &&
            attr.name !='class' &&
            attr.name !='start' &&
            attr.name !='tabIndex' &&
            attr.name !='style' &&
            attr.name.substr(0, 6) != 'jQuery') {
          // in IE we need to check for all of these.
          if (/ng-\d+/.exec(attr.name) ||
              attr.name == 'getElementById' ||
              // IE7 has `selected` in attributes
              attr.name == 'selected' ||
              // IE7 adds `value` attribute to all LI tags
              (node.nodeName == 'LI' && attr.name == 'value') ||
              // IE8 adds bogus rowspan=1 and colspan=1 to TD elements
              (node.nodeName == 'TD' && attr.name == 'rowSpan' && attr.value == '1') ||
              (node.nodeName == 'TD' && attr.name == 'colSpan' && attr.value == '1')) {
            continue;
          }

          attrs.push(' ' + attr.name + '="' + attr.value + '"');
        }
      }
      attrs.sort();
      html += attrs.join('');
      if (node.style) {
        var style = [];
        if (node.style.cssText) {
          forEach(node.style.cssText.split(';'), function(value){
            value = trim(value);
            if (value) {
              style.push(lowercase(value));
            }
          });
        }
        for(var css in node.style){
          var value = node.style[css];
          if (isString(value) && isString(css) && css != 'cssText' && value && (1*css != css)) {
            var text = lowercase(css + ': ' + value);
            if (value != 'false' && indexOf(style, text) == -1) {
              style.push(text);
            }
          }
        }
        style.sort();
        var tmp = style;
        style = [];
        forEach(tmp, function(value){
          if (!value.match(/^max[^\-]/))
            style.push(value);
        });
        if (style.length) {
          html += ' style="' + style.join('; ') + ';"';
        }
      }
      html += '>';
      var children = node.childNodes;
      for(var j=0; j<children.length; j++) {
        toString(children[j]);
      }
      html += '</' + node.nodeName.toLowerCase() + '>';
    }
  });
  return html;
}

// TODO(vojta): migrate these helpers into jasmine matchers
/**a
 * This method is a cheap way of testing if css for a given node is not set to 'none'. It doesn't
 * actually test if an element is displayed by the browser. Be aware!!!
 */
function isCssVisible(node) {
  var display = node.css('display');
  return display != 'none';
}

function assertHidden(node) {
  if (isCssVisible(node)) {
    throw new Error('Node should be hidden but was visible: ' + angular.module.ngMock.dump(node));
  }
}

function assertVisible(node) {
  if (!isCssVisible(node)) {
    throw new Error('Node should be visible but was hidden: ' + angular.module.ngMock.dump(node));
  }
}

function provideLog($provide) {
  $provide.factory('log', function() {
      var messages = [];

      function log(msg) {
        messages.push(msg);
        return msg;
      }

      log.toString = function() {
        return messages.join('; ');
      }

      log.toArray = function() {
        return messages;
      }

      log.reset = function() {
        messages = [];
      }

      log.fn = function(msg) {
        return function() {
          log(msg);
        }
      }

      log.$$log = true;

      return log;
    });
}

function pending() {
  dump('PENDING');
};

function trace(name) {
  dump(new Error(name).stack);
}

var karmaDump = dump;
window.dump = function () {
  karmaDump(angular.mock.dump.apply(undefined, arguments));
};
<|endoftext|>


<commit_before>/**
 * Created by Antony on 14/11/21.
 */

jsEasyControllers.controller('loginCtrl', ['app','$scope', '$routeParams', 'loginService','$locale','tools',function (app, $scope, $routeParams, loginService,$locale,tools) {
  var langList = ['LOGIN', 'COMMON'];
  for (var i in langList) {
    for (var j in $locale[langList[i]]) {
      $scope[j] = $locale[langList[i]][j];
    }
  }
  tools.testTool();

  $scope.login = function () {
    loginService.login(function(err,result){
      if (result.data.username == $scope.telephone && result.data.password == $scope.password) {
        app.location.search({}).path('/home');
      } else {
        alert($locale.LOGIN.error);
      }
    });
  };

  $scope.submit = function () {
    return false;
  };

  $scope.register = function () {
      if ($scope.telephone) {
        $scope.telephone = '';
      }
      if ($scope.password) {
        $scope.password = '';
      }
  };
}]);<commit_msg>登录机能 前台 完了  初始化 input 为空<commit_after>/**
 * Created by Antony on 14/11/21.
 */

jsEasyControllers.controller('loginCtrl', ['app','$scope', '$routeParams', 'loginService','$locale','tools',function (app, $scope, $routeParams, loginService,$locale,tools) {
  var langList = ['LOGIN', 'COMMON'];
  for (var i in langList) {
    for (var j in $locale[langList[i]]) {
      $scope[j] = $locale[langList[i]][j];
    }
  }
  tools.testTool();

  $scope.telephone = '';
  $scope.password = '';

  $scope.login = function () {
    loginService.login(function(err,result){
      if (result.data.username == $scope.telephone && result.data.password == $scope.password) {
        app.location.search({}).path('/home');
      } else {
        alert($locale.LOGIN.error);
      }
    });
  };

  $scope.submit = function () {
    return false;
  };

  $scope.register = function () {
      if ($scope.telephone) {
        $scope.telephone = '';
      }
      if ($scope.password) {
        $scope.password = '';
      }
  };
}]);<|endoftext|>


<commit_before>var should = require('should'),
    ExpectEvent = require(__dirname+'/../lib/expectevent.js').ExpectEvent,
    fs = require('fs'),
    watchfd = require(__dirname+'/../../watch.js'),
    logFile = 'test1'+Date.now()+Math.random()+'.log';

exports['test events'] = function(beforeExit){

  var changesObservedThroughDefaultListener = 0,
      watcher = watchfd.watch(logFile,{timeout:1000,timeoutInterval:200},function(cur,prev){
        /*dont need to watch change here*/
        changesObservedThroughDefaultListener++;
      }),
      expect = new ExpectEvent(watcher);

  watcher.on('error',function(err){
    throw err;
  });

  //
  // enforce some max execution time for watcher test
  //

  expect.expect('close',function(err,data){
    if(err) {
      watcher.close();
      fs.unlink();
      throw err;
    }
  },20000);

  //cleanup
  var cleanup = function(){
    fs.unlink(logFile);
    if(!changesObservedThroughDefaultListener){
      ("this test should have triggered the default change handler numerous times").should.eql(true);
    }
  };

  beforeExit(cleanup);

  // file descriptors for unlinked events tests
  var fd1 = null;
      fd2 = null;

  var q = {
    //
    "trigger open. expect that it is fired within one second":function(){
      expect.expect('open',function(err,stat){
        if(err) throw err;
        done();
      },1000);

      fs.open(logFile,'a+',function(err,fd){
        (!err).should.eql(true);

        fd1 = fd;

        var buf = new Buffer('party rockin');

        // watchFile does not seem to hit imediately for regular empty files.
        fs.write(fd1,buf,0,buf.length,null,function(err,bytesWritten){
          (!err).should.eql(true);
        });
      });
    },
    //
    "trigger change expect that it is fired within one second":function(){
      expect.expect('change',function(err,data){
        if(err) throw err;
        //must have file descriptor with change events
        (!!data[3].fd).should.eql(true);
        done();
      },1000);

      var buf = new Buffer('party floppin');

      fs.write(fd1,buf,0,buf.length,null,function(err,bytesWritten){
        (!err).should.eql(true);
      });
    },
    //
    "unlink and wait for unlink":function(){
      expect.expect('unlink',function(err,data){
        if(err) throw err;
        done();
      },1000);

      fs.unlink(logFile,function(err){
        (!err).should.eql(true);
      });
    },
    //
    "create again wait for open":function(){
      expect.expect('open',function(err,data){
        if(err) throw err;
        done();
      },10000);

      fs.open(logFile,'w+',function(err,fd){
        (!err).should.eql(true);
        fd2 = fd;

        var buf = new Buffer('new party');

        fs.write(fd2,buf,0,buf.length,null,function(err,bytesWritten){

          (!err).should.eql(true);
        });
      });
    },
    //
    "write data to unlinked fd and wait for change":function(){
      expect.expect('change',function(err,data){
        if(err) throw err;
        done();
      },1000);

      var buf = new Buffer('party unlinked');

      fs.write(fd1,buf,0,buf.length,null,function(err,bytesWritten){
        (!err).should.eql(true);
      });
    },
    //
    "wait for timeout on fd1":function(){

      expect.expect('timeout',function(err,data){
        if(err) throw err;
        Object.keys(watcher.fds).length.should.eql(1);

        done();
      },2000);
    }
  },
  lastStart = Date.now(),
  done = function(){
    var keys = Object.keys(q),
        testKey = keys.shift(),
        test = q[testKey];

    if(test) {
      delete q[testKey];

      var elapsed = Date.now()-lastStart;
      console.log("\telapsed: ",elapsed,'ms');
      console.log('starting test : ',testKey);
      lastStart = Date.now();
      test();
    } else complete();
  },
  complete = function(){
    watcher.close();
    cleanup();
  };
  done();

};

<commit_msg>updated times in test to support slower inital open<commit_after>var should = require('should'),
    ExpectEvent = require(__dirname+'/../lib/expectevent.js').ExpectEvent,
    fs = require('fs'),
    watchfd = require(__dirname+'/../../watch.js'),
    logFile = 'test1'+Date.now()+Math.random()+'.log';

exports['test events'] = function(beforeExit){

  var changesObservedThroughDefaultListener = 0,
      watcher = watchfd.watch(logFile,{timeout:1000,timeoutInterval:200},function(cur,prev){
        /*dont need to watch change here*/
        changesObservedThroughDefaultListener++;
      }),
      expect = new ExpectEvent(watcher);

  watcher.on('error',function(err){
    throw err;
  });

  //
  // enforce some max execution time for watcher test
  //

  expect.expect('close',function(err,data){
    if(err) {
      watcher.close();
      fs.unlink();
      throw err;
    }
  },20000);

  //cleanup
  var cleanup = function(){
    fs.unlink(logFile);
    if(!changesObservedThroughDefaultListener){
      ("this test should have triggered the default change handler numerous times").should.eql(true);
    }
  };

  beforeExit(cleanup);

  // file descriptors for unlinked events tests
  var fd1 = null;
      fd2 = null;

  var q = {
    //
    "trigger open. expect that it is fired within two seconds":function(){
      expect.expect('open',function(err,stat){
        if(err) throw err;
        done();
      },2000);

      fs.open(logFile,'a+',function(err,fd){
        (!err).should.eql(true);

        fd1 = fd;

        var buf = new Buffer('party rockin');

        // watchFile does not seem to hit imediately for regular empty files.
        fs.write(fd1,buf,0,buf.length,null,function(err,bytesWritten){
          (!err).should.eql(true);
        });
      });
    },
    //
    "trigger change expect that it is fired within one second":function(){
      expect.expect('change',function(err,data){
        if(err) throw err;
        //must have file descriptor with change events
        (!!data[3].fd).should.eql(true);
        done();
      },1000);

      var buf = new Buffer('party floppin');

      fs.write(fd1,buf,0,buf.length,null,function(err,bytesWritten){
        (!err).should.eql(true);
      });
    },
    //
    "unlink and wait for unlink":function(){
      expect.expect('unlink',function(err,data){
        if(err) throw err;
        done();
      },1000);

      fs.unlink(logFile,function(err){
        (!err).should.eql(true);
      });
    },
    //
    "create again wait for open":function(){
      expect.expect('open',function(err,data){
        if(err) throw err;
        done();
      },10000);

      fs.open(logFile,'w+',function(err,fd){
        (!err).should.eql(true);
        fd2 = fd;

        var buf = new Buffer('new party');

        fs.write(fd2,buf,0,buf.length,null,function(err,bytesWritten){

          (!err).should.eql(true);
        });
      });
    },
    //
    "write data to unlinked fd and wait for change":function(){
      expect.expect('change',function(err,data){
        if(err) throw err;
        done();
      },1000);

      var buf = new Buffer('party unlinked');

      fs.write(fd1,buf,0,buf.length,null,function(err,bytesWritten){
        (!err).should.eql(true);
      });
    },
    //
    "wait for timeout on fd1":function(){

      expect.expect('timeout',function(err,data){
        if(err) throw err;
        Object.keys(watcher.fds).length.should.eql(1);

        done();
      },2000);
    }
  },
  lastStart = Date.now(),
  done = function(){
    var keys = Object.keys(q),
        testKey = keys.shift(),
        test = q[testKey];

    if(test) {
      delete q[testKey];

      var elapsed = Date.now()-lastStart;
      console.log("\telapsed: ",elapsed,'ms');
      console.log('starting test : ',testKey);
      lastStart = Date.now();
      test();
    } else complete();
  },
  complete = function(){
    watcher.close();
    cleanup();
  };
  done();

};

<|endoftext|>


<commit_before>var buster = require('buster-assertions');
var assert = buster.assert;
var refute = buster.refute;

var proxyquire = require('proxyquire');

var help = require('../lib/validateHelpers.js');
var hook = require('../../lib/hook/jquery.js');

describe('jQuery hook', function () {

    it('should call wrap', function () {

        var calls = 0;
        var api = {
            wrap: function () {
                calls++;
            }
        };

        hook.onResourceReceived({
            url: 'someUrl',
            stage: 'end'
        }, api);

        assert.equals(calls, 0);

        hook.onResourceReceived({
            url: 'jquery.js',
            stage: 'start'
        }, api);

        assert.equals(calls, 0);

        hook.onResourceReceived({
            url: 'jquery.js',
            stage: 'end'
        }, api);

        assert.equals(calls, 1);

        hook.onResourceReceived({
            url: 'jquery.js',
            stage: 'end'
        }, api);

        assert.equals(calls, 1, 'should only wrap once');
    });

    it('should collect wrapped and jquery version', function () {

        var calls = 0;
        var result = {};
        var key = '12345'+Math.random()+Date.now();
        var apiShim = {
            switchToIframe: function () {
                calls++;
            },
            getResultObject: function () {
                return result;
            },
            evaluate: function (fn) {
                global.window = {jQuery: {fn: {jquery: key}}};
                calls++;
                var result = fn();
                global.window = undefined;
                return result;
            }
        };

        hook.onBeforeExit(apiShim);

        assert.equals(calls, 2);
        assert.equals(result.jquery_version, key);

    });

});

describe('jQuery validator', function () {

    it('should report error if animate called', function (done) {
        var validator = require('../../lib/validator/jquery.js');

        var harvested = {
            jquery_animate: [
                [help.getTraceObject(1), help.getTraceObject(2), help.getTraceObject(3)],
                [help.getTraceObject(4), help.getTraceObject(5), help.getTraceObject(6)]
            ]
        };

        var report = help.createReporter.call(this);

        validator.validate(harvested, report, function () {
            var result = report.getResult();
            assert.equals(result.error.length, 2);
            done();
        });

    });

    function shimLatest(cb) {
        cb([{ major: 1, minor: 10, patch: 2, sortKey: 11002},
            { major: 2, minor: 0,  patch: 3, sortKey: 20003}
           ]);
    }

    it('should report error when version doesnt match latest', function (done) {
        var harvested = {
            jquery_version: "1.10.1"
        };

        var report = help.createReporter.call(this);

        var validator = proxyquire('../../lib/validator/jquery.js', {
            './getLatestJquery.js': {
                'getLatest': shimLatest
            }
        });

        // TODO this is doing actual request, neeed to unit test instead
        validator.validate(harvested, report, function () {
            var result = report.getResult();
            assert.equals(result.error.length, 1);
            done();
        });

    });

});
<commit_msg>test doesnt need to getLatestVersion<commit_after>var buster = require('buster-assertions');
var assert = buster.assert;
var refute = buster.refute;

var proxyquire = require('proxyquire');

var help = require('../lib/validateHelpers.js');
var hook = require('../../lib/hook/jquery.js');

describe('jQuery hook', function () {

    it('should call wrap', function () {

        var calls = 0;
        var api = {
            wrap: function () {
                calls++;
            }
        };

        hook.onResourceReceived({
            url: 'someUrl',
            stage: 'end'
        }, api);

        assert.equals(calls, 0);

        hook.onResourceReceived({
            url: 'jquery.js',
            stage: 'start'
        }, api);

        assert.equals(calls, 0);

        hook.onResourceReceived({
            url: 'jquery.js',
            stage: 'end'
        }, api);

        assert.equals(calls, 1);

        hook.onResourceReceived({
            url: 'jquery.js',
            stage: 'end'
        }, api);

        assert.equals(calls, 1, 'should only wrap once');
    });

    it('should collect wrapped and jquery version', function () {

        var calls = 0;
        var result = {};
        var key = '12345'+Math.random()+Date.now();
        var apiShim = {
            switchToIframe: function () {
                calls++;
            },
            getResultObject: function () {
                return result;
            },
            evaluate: function (fn) {
                global.window = {jQuery: {fn: {jquery: key}}};
                calls++;
                var result = fn();
                global.window = undefined;
                return result;
            }
        };

        hook.onBeforeExit(apiShim);

        assert.equals(calls, 2);
        assert.equals(result.jquery_version, key);

    });

});

describe('jQuery validator', function () {
    function shimLatest(cb) {
        cb([{ major: 1, minor: 10, patch: 2, sortKey: 11002},
            { major: 2, minor: 0,  patch: 3, sortKey: 20003}
           ]);
    }
    var validator = proxyquire('../../lib/validator/jquery.js', {
        './getLatestJquery.js': {
            'getLatest': shimLatest
        }
    });

    it('should report error if animate called', function (done) {

        var harvested = {
            jquery_animate: [
                [help.getTraceObject(1), help.getTraceObject(2), help.getTraceObject(3)],
                [help.getTraceObject(4), help.getTraceObject(5), help.getTraceObject(6)]
            ]
        };

        var report = help.createReporter.call(this);

        validator.validate(harvested, report, function () {
            var result = report.getResult();
            assert.equals(result.error.length, 2);
            done();
        });

    });

    it('should report error when version doesnt match latest', function (done) {
        var harvested = {
            jquery_version: "1.10.1"
        };

        var report = help.createReporter.call(this);

        // TODO this is doing actual request, neeed to unit test instead
        validator.validate(harvested, report, function () {
            var result = report.getResult();
            assert.equals(result.error.length, 1);
            done();
        });

    });

});
<|endoftext|>