<commit_before>javascript: (function() {
    /**
     * facebook-page-invite.js
     * A Shravya Core project.
     * Like using our stuff? Like our page at fb.me/shravyacore to keep
     * up-to-date with our latest releases and thoughts.
     *
     * We do not use slash-slash comments here so that the code can work when
     * converted to a bookmarklet.
     */

    /*
     * Isolate the selectors so that we can change them easily
     * if Facebook updates the layout
     */
    var inviteProfileClass = 'uiProfileBlockContent';
    var inviteClass = '_42ef';
    var chatWholeElement = '_42fz';
    var elementId = 'uiButton _1sm';
    var buttonText = 'uiButtonText';
    var isOnlineButton = '_568-';
    var text = 'text';

    var debug = false;

    /*
     * Limit the maximum number of invites sent so as to
     * prevent Facebook from blocking you from inviting people.
     */
    var max_invites = 500;

    /**
     * Recursively traverses through an element's child
     * nodes, looking for the specified subclass.
     */
    function findSubClass(element, className) {
        "use strict";
        if (!element) {
            return null;
        }
        var foundElement = null,
            found;

        function recurse(element, className, found) {
            for (var i = 0; i < element.childNodes.length && !found; i++) {
                var el = element.childNodes[i];
                var classes = el.className != undefined ? el.className.split(" ") : [];
                for (var j = 0, jl = classes.length; j < jl; j++) {
                    if (classes[j] == className) {
                        found = true;
                        foundElement = element.childNodes[i];
                        break;
                    }
                }
                if (found)
                    break;
                recurse(element.childNodes[i], className, found);
            }
        }
        recurse(element, className, false);
        return foundElement;
    }

    /**
     * Sleeps for a given length of time.
     */
    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    /**
     * Generates a random number between the min and the max.
     */
    function getRandomBetween(min, max) {
        return Math.random() * (max - min) + min;
    }

    /**
     * A smart invite function that only invites people if
     * they are currently online. This increases engagement
     * as more people will see the invite notification and
     * it will not be buried by other notifications when they
     * come back online.
     */
    async function smartInvite() {
        var inviteBlocks = document.getElementsByClassName(inviteClass);
        var inputs = document.getElementsByClassName(elementId);

        var invite_count = 0;
        for (var i = 0; i < inviteBlocks.length; i++) {
            var inviteElement = inviteBlocks[i];
            var profileElement = findSubClass(inviteElement, inviteProfileClass);
            var textElement = findSubClass(profileElement, text);

            if (textElement) {
                var inviteName = textElement.innerText.trim() || textElement.textContent.trim();

                if (debug) { console.log("Invite Name " + inviteName); }
                var peopleOnline = document.getElementsByClassName(chatWholeElement);
                for (var j = 0; j < peopleOnline.length; j++) {
                    element = peopleOnline[j];
                    var messageName = element.innerText.trim() || element.textContent.trim();
                    if (debug) { console.log("Message Name " + messageName); }
                    if (messageName === inviteName) {
                        if (debug) { console.log(messageName + " = " + inviteName); }

                        /** Check if the person is currently online **/
                        var onlineButton = findSubClass(element, isOnlineButton);
                        if (onlineButton) {
                            if (!onlineButton.hasChildNodes()) {
                                if (debug) { console.log(inviteName + " is online!"); }
                                if (debug) { console.log(inviteElement); }
                                if (debug) { console.log(elementId); }
                                var button = findSubClass(inviteElement, buttonText);
                                if (debug) { console.log(button); }
                                if (button) {
                                    console.log("Inviting " + inviteName + "...");
                                    button.click();
                                    /* Make sure that we do not exceed the maximum number of invites */
                                    invite_count++;
                                    if (invite_count >= max_invites) {
                                        return;
                                    }
                                    await sleep(getRandomBetween(5000, 8000));
                                } else {
                                    if (debug) { console.log("Error: button is undefined (name: " + inviteName + ").") }
                                    console.log(inviteName + " has already been invited.");
                                }
                            } else {
                                console.log(inviteName + " is offline.");
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * Just invites everyone as quickly as it can.
     * Only recommended to run after exhausting smart invite,
     * as some users permanently mark themselves offline and thus
     * would not be invited at all by smart invite.
     */
    async function fastInvite() {
        var inputs = document.getElementsByClassName(elementId);
        for (var i = 0; i < max_invites; i++) {
            inputs[i].click();
            await sleep(getRandomBetween(1000, 3000));
        }
    }

    smartInvite();
})();
<commit_msg>Replace double quote with single quote<commit_after>javascript: (function() {
    /**
     * facebook-page-invite.js
     * A Shravya Core project.
     * Like using our stuff? Like our page at fb.me/shravyacore to keep
     * up-to-date with our latest releases and thoughts.
     *
     * We do not use slash-slash comments here so that the code can work when
     * converted to a bookmarklet.
     */

    /*
     * Isolate the selectors so that we can change them easily
     * if Facebook updates the layout
     */
    var inviteProfileClass = 'uiProfileBlockContent';
    var inviteClass = '_42ef';
    var chatWholeElement = '_42fz';
    var elementId = 'uiButton _1sm';
    var buttonText = 'uiButtonText';
    var isOnlineButton = '_568-';
    var text = 'text';

    var debug = false;

    /*
     * Limit the maximum number of invites sent so as to
     * prevent Facebook from blocking you from inviting people.
     */
    var max_invites = 500;

    /**
     * Recursively traverses through an element's child
     * nodes, looking for the specified subclass.
     */
    function findSubClass(element, className) {
        'use strict';
        if (!element) {
            return null;
        }
        var foundElement = null,
            found;

        function recurse(element, className, found) {
            for (var i = 0; i < element.childNodes.length && !found; i++) {
                var el = element.childNodes[i];
                var classes = el.className != undefined ? el.className.split(' ') : [];
                for (var j = 0, jl = classes.length; j < jl; j++) {
                    if (classes[j] == className) {
                        found = true;
                        foundElement = element.childNodes[i];
                        break;
                    }
                }
                if (found)
                    break;
                recurse(element.childNodes[i], className, found);
            }
        }
        recurse(element, className, false);
        return foundElement;
    }

    /**
     * Sleeps for a given length of time.
     */
    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    /**
     * Generates a random number between the min and the max.
     */
    function getRandomBetween(min, max) {
        return Math.random() * (max - min) + min;
    }

    /**
     * A smart invite function that only invites people if
     * they are currently online. This increases engagement
     * as more people will see the invite notification and
     * it will not be buried by other notifications when they
     * come back online.
     */
    async function smartInvite() {
        var inviteBlocks = document.getElementsByClassName(inviteClass);
        var inputs = document.getElementsByClassName(elementId);

        var invite_count = 0;
        for (var i = 0; i < inviteBlocks.length; i++) {
            var inviteElement = inviteBlocks[i];
            var profileElement = findSubClass(inviteElement, inviteProfileClass);
            var textElement = findSubClass(profileElement, text);

            if (textElement) {
                var inviteName = textElement.innerText.trim() || textElement.textContent.trim();

                if (debug) { console.log('Invite Name ' + inviteName); }
                var peopleOnline = document.getElementsByClassName(chatWholeElement);
                for (var j = 0; j < peopleOnline.length; j++) {
                    element = peopleOnline[j];
                    var messageName = element.innerText.trim() || element.textContent.trim();
                    if (debug) { console.log('Message Name ' + messageName); }
                    if (messageName === inviteName) {
                        if (debug) { console.log(messageName + ' = ' + inviteName); }

                        /** Check if the person is currently online **/
                        var onlineButton = findSubClass(element, isOnlineButton);
                        if (onlineButton) {
                            if (!onlineButton.hasChildNodes()) {
                                if (debug) { console.log(inviteName + ' is online!'); }
                                if (debug) { console.log(inviteElement); }
                                if (debug) { console.log(elementId); }
                                var button = findSubClass(inviteElement, buttonText);
                                if (debug) { console.log(button); }
                                if (button) {
                                    console.log('Inviting ' + inviteName + '...');
                                    button.click();
                                    /* Make sure that we do not exceed the maximum number of invites */
                                    invite_count++;
                                    if (invite_count >= max_invites) {
                                        return;
                                    }
                                    await sleep(getRandomBetween(5000, 8000));
                                } else {
                                    if (debug) { console.log('Error: button is undefined (name: ' + inviteName + ').') }
                                    console.log(inviteName + ' has already been invited.');
                                }
                            } else {
                                console.log(inviteName + ' is offline.');
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * Just invites everyone as quickly as it can.
     * Only recommended to run after exhausting smart invite,
     * as some users permanently mark themselves offline and thus
     * would not be invited at all by smart invite.
     */
    async function fastInvite() {
        var inputs = document.getElementsByClassName(elementId);
        for (var i = 0; i < max_invites; i++) {
            inputs[i].click();
            await sleep(getRandomBetween(1000, 3000));
        }
    }

    smartInvite();
})();
<|endoftext|>


<commit_before>/*
 * Copyright © 2013 VillageReach.  All Rights Reserved.  This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
 *
 * If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

function CreateRequisitionController($scope, requisition, currency, rnrColumns, lossesAndAdjustmentsTypes, facilityApprovedProducts, requisitionRights, RequisitionComment, $location, Requisitions, $routeParams, $rootScope, $dialog) {
  $scope.showNonFullSupply = $routeParams.supplyType == 'non-full-supply';
  $scope.baseUrl = "/create-rnr/" + $routeParams.rnr + '/' + $routeParams.facility + '/' + $routeParams.program;
  $scope.fullSupplyLink = $scope.baseUrl + "?supplyType=full-supply&page=1";
  $scope.nonFullSupplyLink = $scope.baseUrl + "?supplyTpe=non-full-supply&page=1";

  $scope.rnr = requisition;
  $scope.allTypes = lossesAndAdjustmentsTypes;
  $scope.facilityApprovedProducts = facilityApprovedProducts;
  $scope.visibleColumns = _.where(rnrColumns, {'visible':true});
  $scope.programRnrColumnList = rnrColumns;
  $scope.requisitionRights = requisitionRights;
  $scope.addNonFullSupplyLineItemButtonShown = _.findWhere($scope.programRnrColumnList, {'name':'quantityRequested'});
  $scope.errorPages = {fullSupply:[], nonFullSupply:[]};
  $rootScope.fullScreen = false;

  $scope.getFullScreen = function() {
    $rootScope.fullScreen = !$rootScope.fullScreen;
    angular.element(window).scrollTop(0);
  }

  $scope.fillPagedGridData = function () {
    var gridLineItems = $scope.showNonFullSupply ? $scope.rnr.nonFullSupplyLineItems : $scope.rnr.fullSupplyLineItems;
    $scope.numberOfPages = Math.ceil(gridLineItems.length / $scope.pageSize) ? Math.ceil(gridLineItems.length / $scope.pageSize) : 1;
    $scope.currentPage = (utils.isValidPage($routeParams.page, $scope.numberOfPages)) ? parseInt($routeParams.page, 10) : 1;
    $scope.pageLineItems = gridLineItems.slice(($scope.pageSize * ($scope.currentPage - 1)), $scope.pageSize * $scope.currentPage);
  };

  $scope.hasPermission = function (permission) {
    return _.find($scope.requisitionRights, function (right) {
      return right.right == permission
    });
  };

  prepareRnr();

  $scope.currency = currency;

  $scope.checkErrorOnPage = function (page) {
    return $scope.showNonFullSupply ? _.contains($scope.errorPages.nonFullSupply, page) : _.contains($scope.errorPages.fullSupply, page);
  };

  if ($scope.programRnrColumnList && $scope.programRnrColumnList.length > 0) {
  } else {
    $scope.error = "error.rnr.template.not.defined";
    $location.path("/init-rnr");
  }

  $scope.currentPage = ($routeParams.page) ? parseInt($routeParams.page) || 1 : 1;

  $scope.switchSupplyType = function (supplyType) {
    $scope.showNonFullSupply = supplyType == 'non-full-supply';
    $location.search('page', 1);
    $location.search('supplyType', supplyType);
  };

  $scope.goToPage = function (page, event) {
    angular.element(event.target).parents(".dropdown").click();
    $location.search('page', page);
  };

  $scope.$on('$routeUpdate', function () {
    $scope.showNonFullSupply = $routeParams.supplyType == "non-full-supply";
    if ($scope.saveRnrForm.$dirty) $scope.saveRnr();
    $scope.fillPagedGridData();
  });

  $scope.$watch("currentPage", function () {
    $location.search("page", $scope.currentPage);
  });

  $scope.saveRnr = function (preventMessage) {
    if (!$scope.saveRnrForm.$dirty) {
      return;
    }
    resetFlags();
    var rnr = removeExtraDataForPostFromRnr();
    Requisitions.update({id:$scope.rnr.id, operation:"save"}, rnr, function (data) {
      if (preventMessage) return;
      $scope.message = data.success;
      setTimeout(function () {
        $scope.$apply(function () {
          angular.element("#saveSuccessMsgDiv").fadeOut('slow', function () {
            $scope.message = '';
          });
        });
      }, 3000);
      $scope.saveRnrForm.$setPristine();;
    }, function (data) {
      $scope.error = data.error;
    });
  };

  function validateAndSetErrorClass() {
    $scope.inputClass = true;
    var fullSupplyError = $scope.rnr.validateFullSupply();
    var nonFullSupplyError = $scope.rnr.validateNonFullSupply();
    $scope.fullSupplyTabError = !!fullSupplyError;
    $scope.nonFullSupplyTabError = !!nonFullSupplyError;

    return fullSupplyError || nonFullSupplyError;
  }

  function setErrorPages() {
    $scope.errorPages = $scope.rnr.getErrorPages($scope.pageSize);
  }

  $scope.submitRnr = function () {
    resetFlags();
    resetErrorPages();
    $scope.saveRnr(true);
    var errorMessage = validateAndSetErrorClass();
    if (errorMessage) {
      setErrorPages();
      $scope.submitError = errorMessage;
      return;
    }
    showConfirmModal();
  };

  var submitValidatedRnr = function () {
    Requisitions.update({id:$scope.rnr.id, operation:"submit"},
      {}, function (data) {
        $scope.rnr.status = "SUBMITTED";
        $scope.formDisabled = !$scope.hasPermission('AUTHORIZE_REQUISITION');
        $scope.submitMessage = data.success;
      }, function (data) {
        $scope.submitError = data.data.error;
      });
  };

  $scope.dialogCloseCallback = function (result) {
    if (result && $scope.rnr.status == 'INITIATED')
      submitValidatedRnr();
    if (result && $scope.rnr.status == 'SUBMITTED')
      authorizeValidatedRnr();
  };

  showConfirmModal = function () {
    var options = {
      id:"confirmDialog",
      header:"Confirm Action",
      body:"Are you sure? Please confirm."
    };
    OpenLmisDialog.newDialog(options, $scope.dialogCloseCallback, $dialog);
  };

  $scope.authorizeRnr = function () {
    resetFlags();
    resetErrorPages();
    $scope.saveRnr(true);
    var errorMessage = validateAndSetErrorClass();
    if (errorMessage) {
      setErrorPages();
      $scope.submitError = errorMessage;
      return;
    }
    showConfirmModal();
  };

  var authorizeValidatedRnr = function () {
    Requisitions.update({id:$scope.rnr.id, operation:"authorize"}, {}, function (data) {
      resetFlags();
      $scope.rnr.status = "AUTHORIZED";
      $scope.formDisabled = true;
      $scope.submitMessage = data.success;
    }, function (data) {
      $scope.submitError = data.data.error;
    });
  };

  $scope.hide = function () {
    return "";
  };

  $scope.highlightRequired = function (value) {
    if ($scope.inputClass && (isUndefined(value))) {
      return "required-error";
    }
    return null;
  };

  $scope.highlightRequiredFieldInModal = function (value) {
    if (isUndefined(value)) return "required-error";
    return null;
  };

  $scope.highlightWarningBasedOnField = function (value, field) {
    if ($scope.inputClass && (isUndefined(value) || value == false) && field) {
      return "warning-error";
    }
    return null;
  };

  $scope.highlightWarning = function (value) {
    if ($scope.inputClass && (isUndefined(value) || value == false)) {
      return "warning-error";
    }
    return null;
  };

  $scope.showCategory = function (index) {
    return !((index > 0 ) && ($scope.pageLineItems[index].productCategory == $scope.pageLineItems[index - 1].productCategory));
  };

  $scope.getCellErrorClass = function (rnrLineItem) {
    return (typeof(rnrLineItem.getErrorMessage) != "undefined" && rnrLineItem.getErrorMessage()) ? 'cell-error-highlight' : '';
  };

  $scope.getRowErrorClass = function (rnrLineItem) {
    return $scope.getCellErrorClass(rnrLineItem) ? 'row-error-highlight' : '';
  };

  function resetCostsIfNull() {
    var rnr = $scope.rnr;
    if (rnr == null) return;
    if (!rnr.fullSupplyItemsSubmittedCost)
      rnr.fullSupplyItemsSubmittedCost = 0;
    if (!rnr.nonFullSupplyItemsSubmittedCost)
      rnr.nonFullSupplyItemsSubmittedCost = 0;
  }

  function prepareRnr() {
    var rnr = $scope.rnr;
    $scope.rnr = new Rnr(rnr, rnrColumns);

    resetCostsIfNull();
    $scope.fillPagedGridData();
    $scope.formDisabled = (function () {
      if ($scope.rnr) {
        var status = $scope.rnr.status;
        if (status == 'INITIATED' && $scope.hasPermission('CREATE_REQUISITION')) return false;
        if (status == 'SUBMITTED' && $scope.hasPermission('AUTHORIZE_REQUISITION')) return false;
      }
      return true;
    })();
  }

  function resetErrorPages() {
    $scope.errorPages = {fullSupply:[], nonFullSupply:[]};
  }

  function resetFlags() {
    $scope.submitError = "";
    $rootScope.submitMessage = "";
    $scope.error = "";
    $scope.message = "";
  }

  function removeExtraDataForPostFromRnr() {
    var rnr = {"id":$scope.rnr.id, "fullSupplyLineItems":[], "nonFullSupplyLineItems":[]};
    if (!$scope.pageLineItems[0].fullSupply) {
      _.each($scope.rnr.nonFullSupplyLineItems, function (lineItem) {
        rnr.nonFullSupplyLineItems.push(_.omit(lineItem, ['rnr', 'programRnrColumnList']));
      });
    } else {
      _.each($scope.pageLineItems, function (lineItem) {
        rnr.fullSupplyLineItems.push(_.omit(lineItem, ['rnr', 'programRnrColumnList']));
      });
    }

    return rnr;
  }
}

CreateRequisitionController.resolve = {
  requisition:function ($q, $timeout, RequisitionById, $route, $rootScope) {
    var deferred = $q.defer();
    $timeout(function () {
      var rnr = $rootScope.rnr;
      if (rnr) {
        deferred.resolve(rnr);
        $rootScope.rnr = undefined;
        return;
      }
      RequisitionById.get({id:$route.current.params.rnr}, function (data) {
        deferred.resolve(data.rnr);
      }, {});
    }, 100);
    return deferred.promise;
  },

  rnrColumns:function ($q, $timeout, ProgramRnRColumnList, $route) {
    var deferred = $q.defer();
    $timeout(function () {
      ProgramRnRColumnList.get({programId:$route.current.params.program}, function (data) {
        deferred.resolve(data.rnrColumnList);
      }, {});
    }, 100);
    return deferred.promise;
  },

  currency:function ($q, $timeout, ReferenceData) {
    var deferred = $q.defer();
    $timeout(function () {
      ReferenceData.get({}, function (data) {
        deferred.resolve(data.currency);
      }, {});
    }, 100);
    return deferred.promise;
  },

  lossesAndAdjustmentsTypes:function ($q, $timeout, LossesAndAdjustmentsReferenceData) {
    var deferred = $q.defer();
    $timeout(function () {
      LossesAndAdjustmentsReferenceData.get({}, function (data) {
        deferred.resolve(data.lossAdjustmentTypes);
      }, {});
    }, 100);
    return deferred.promise;
  },

  facilityApprovedProducts:function ($q, $timeout, $route, FacilityApprovedProducts) {
    var deferred = $q.defer();
    $timeout(function () {
      FacilityApprovedProducts.get({facilityId:$route.current.params.facility, programId:$route.current.params.program}, function (data) {
        deferred.resolve(data.nonFullSupplyProducts);
      }, {});
    }, 100);
    return deferred.promise;
  },

  requisitionRights:function ($q, $timeout, $route, FacilityProgramRights) {
    var deferred = $q.defer();
    $timeout(function () {
      FacilityProgramRights.get({facilityId:$route.current.params.facility, programId:$route.current.params.program}, function (data) {
        deferred.resolve(data.rights);
      }, {});
    }, 100);
    return deferred.promise;
  }
};

<commit_msg>|#833|+Balvinder| Fixing bug.<commit_after>/*
 * Copyright © 2013 VillageReach.  All Rights Reserved.  This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
 *
 * If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

function CreateRequisitionController($scope, requisition, currency, rnrColumns, lossesAndAdjustmentsTypes, facilityApprovedProducts, requisitionRights, RequisitionComment, $location, Requisitions, $routeParams, $rootScope, $dialog) {
  $scope.showNonFullSupply = $routeParams.supplyType == 'non-full-supply';
  $scope.baseUrl = "/create-rnr/" + $routeParams.rnr + '/' + $routeParams.facility + '/' + $routeParams.program;
  $scope.fullSupplyLink = $scope.baseUrl + "?supplyType=full-supply&page=1";
  $scope.nonFullSupplyLink = $scope.baseUrl + "?supplyTpe=non-full-supply&page=1";

  $scope.rnr = requisition;
  $scope.allTypes = lossesAndAdjustmentsTypes;
  $scope.facilityApprovedProducts = facilityApprovedProducts;
  $scope.visibleColumns = _.where(rnrColumns, {'visible':true});
  $scope.programRnrColumnList = rnrColumns;
  $scope.requisitionRights = requisitionRights;
  $scope.addNonFullSupplyLineItemButtonShown = _.findWhere($scope.programRnrColumnList, {'name':'quantityRequested'});
  $scope.errorPages = {fullSupply:[], nonFullSupply:[]};
  $rootScope.fullScreen = false;

  $scope.getFullScreen = function () {
    $rootScope.fullScreen = !$rootScope.fullScreen;
    angular.element(window).scrollTop(0);
  };

  $scope.fillPagedGridData = function () {
    var gridLineItems = $scope.showNonFullSupply ? $scope.rnr.nonFullSupplyLineItems : $scope.rnr.fullSupplyLineItems;
    $scope.numberOfPages = Math.ceil(gridLineItems.length / $scope.pageSize) ? Math.ceil(gridLineItems.length / $scope.pageSize) : 1;
    $scope.currentPage = (utils.isValidPage($routeParams.page, $scope.numberOfPages)) ? parseInt($routeParams.page, 10) : 1;
    $scope.pageLineItems = gridLineItems.slice(($scope.pageSize * ($scope.currentPage - 1)), $scope.pageSize * $scope.currentPage);
  };

  $scope.hasPermission = function (permission) {
    return _.find($scope.requisitionRights, function (right) {
      return right.right == permission
    });
  };

  prepareRnr();

  $scope.currency = currency;

  $scope.checkErrorOnPage = function (page) {
    return $scope.showNonFullSupply ? _.contains($scope.errorPages.nonFullSupply, page) : _.contains($scope.errorPages.fullSupply, page);
  };

  if ($scope.programRnrColumnList && $scope.programRnrColumnList.length > 0) {
  } else {
    $scope.error = "error.rnr.template.not.defined";
    $location.path("/init-rnr");
  }

  $scope.currentPage = ($routeParams.page) ? parseInt($routeParams.page) || 1 : 1;

  $scope.switchSupplyType = function (supplyType) {
    $scope.showNonFullSupply = supplyType == 'non-full-supply';
    $location.search('page', 1);
    $location.search('supplyType', supplyType);
  };

  $scope.goToPage = function (page, event) {
    angular.element(event.target).parents(".dropdown").click();
    $location.search('page', page);
  };

  $scope.$on('$routeUpdate', function () {
    $scope.showNonFullSupply = $routeParams.supplyType == "non-full-supply";
    if ($scope.saveRnrForm.$dirty) $scope.saveRnr();
    $scope.fillPagedGridData();
  });

  $scope.$watch("currentPage", function () {
    $location.search("page", $scope.currentPage);
  });

  $scope.saveRnr = function (preventMessage) {
    if (!$scope.saveRnrForm.$dirty) {
      return;
    }
    resetFlags();
    var rnr = removeExtraDataForPostFromRnr();
    Requisitions.update({id:$scope.rnr.id, operation:"save"}, rnr, function (data) {
      if (preventMessage) return;
      $scope.message = data.success;
      setTimeout(function () {
        $scope.$apply(function () {
          angular.element("#saveSuccessMsgDiv").fadeOut('slow', function () {
            $scope.message = '';
          });
        });
      }, 3000);
      $scope.saveRnrForm.$setPristine();
      ;
    }, function (data) {
      $scope.error = data.error;
    });
  };

  function validateAndSetErrorClass() {
    $scope.inputClass = true;
    var fullSupplyError = $scope.rnr.validateFullSupply();
    var nonFullSupplyError = $scope.rnr.validateNonFullSupply();
    $scope.fullSupplyTabError = !!fullSupplyError;
    $scope.nonFullSupplyTabError = !!nonFullSupplyError;

    return fullSupplyError || nonFullSupplyError;
  }

  function setErrorPages() {
    $scope.errorPages = $scope.rnr.getErrorPages($scope.pageSize);
  }

  $scope.submitRnr = function () {
    resetFlags();
    resetErrorPages();
    $scope.saveRnr(true);
    var errorMessage = validateAndSetErrorClass();
    if (errorMessage) {
      setErrorPages();
      $scope.submitError = errorMessage;
      return;
    }
    showConfirmModal();
  };

  var submitValidatedRnr = function () {
    Requisitions.update({id:$scope.rnr.id, operation:"submit"},
      {}, function (data) {
        $scope.rnr.status = "SUBMITTED";
        $scope.formDisabled = !$scope.hasPermission('AUTHORIZE_REQUISITION');
        $scope.submitMessage = data.success;
      }, function (data) {
        $scope.submitError = data.data.error;
      });
  };

  $scope.dialogCloseCallback = function (result) {
    if (result && $scope.rnr.status == 'INITIATED')
      submitValidatedRnr();
    if (result && $scope.rnr.status == 'SUBMITTED')
      authorizeValidatedRnr();
  };

  showConfirmModal = function () {
    var options = {
      id:"confirmDialog",
      header:"Confirm Action",
      body:"Are you sure? Please confirm."
    };
    OpenLmisDialog.newDialog(options, $scope.dialogCloseCallback, $dialog);
  };

  $scope.authorizeRnr = function () {
    resetFlags();
    resetErrorPages();
    $scope.saveRnr(true);
    var errorMessage = validateAndSetErrorClass();
    if (errorMessage) {
      setErrorPages();
      $scope.submitError = errorMessage;
      return;
    }
    showConfirmModal();
  };

  var authorizeValidatedRnr = function () {
    Requisitions.update({id:$scope.rnr.id, operation:"authorize"}, {}, function (data) {
      resetFlags();
      $scope.rnr.status = "AUTHORIZED";
      $scope.formDisabled = true;
      $scope.submitMessage = data.success;
    }, function (data) {
      $scope.submitError = data.data.error;
    });
  };

  $scope.hide = function () {
    return "";
  };

  $scope.highlightRequired = function (value) {
    if ($scope.inputClass && (isUndefined(value))) {
      return "required-error";
    }
    return null;
  };

  $scope.highlightRequiredFieldInModal = function (value) {
    if (isUndefined(value)) return "required-error";
    return null;
  };

  $scope.highlightWarningBasedOnField = function (value, field) {
    if ($scope.inputClass && (isUndefined(value) || value == false) && field) {
      return "warning-error";
    }
    return null;
  };

  $scope.highlightWarning = function (value) {
    if ($scope.inputClass && (isUndefined(value) || value == false)) {
      return "warning-error";
    }
    return null;
  };

  $scope.showCategory = function (index) {
    return !((index > 0 ) && ($scope.pageLineItems[index].productCategory == $scope.pageLineItems[index - 1].productCategory));
  };

  $scope.getCellErrorClass = function (rnrLineItem) {
    return (typeof(rnrLineItem.getErrorMessage) != "undefined" && rnrLineItem.getErrorMessage()) ? 'cell-error-highlight' : '';
  };

  $scope.getRowErrorClass = function (rnrLineItem) {
    return $scope.getCellErrorClass(rnrLineItem) ? 'row-error-highlight' : '';
  };

  function resetCostsIfNull() {
    var rnr = $scope.rnr;
    if (rnr == null) return;
    if (!rnr.fullSupplyItemsSubmittedCost)
      rnr.fullSupplyItemsSubmittedCost = 0;
    if (!rnr.nonFullSupplyItemsSubmittedCost)
      rnr.nonFullSupplyItemsSubmittedCost = 0;
  }

  function prepareRnr() {
    var rnr = $scope.rnr;
    $scope.rnr = new Rnr(rnr, rnrColumns);

    resetCostsIfNull();
    $scope.fillPagedGridData();
    $scope.formDisabled = (function () {
      if ($scope.rnr) {
        var status = $scope.rnr.status;
        if (status == 'INITIATED' && $scope.hasPermission('CREATE_REQUISITION')) return false;
        if (status == 'SUBMITTED' && $scope.hasPermission('AUTHORIZE_REQUISITION')) return false;
      }
      return true;
    })();
  }

  function resetErrorPages() {
    $scope.errorPages = {fullSupply:[], nonFullSupply:[]};
  }

  function resetFlags() {
    $scope.submitError = "";
    $rootScope.submitMessage = "";
    $scope.error = "";
    $scope.message = "";
  }

  function removeExtraDataForPostFromRnr() {
    var rnr = {"id":$scope.rnr.id, "fullSupplyLineItems":[], "nonFullSupplyLineItems":[]};
    if (!$scope.pageLineItems.length) return rnr;
    if (!$scope.pageLineItems[0].fullSupply) {
      _.each($scope.rnr.nonFullSupplyLineItems, function (lineItem) {
        rnr.nonFullSupplyLineItems.push(_.omit(lineItem, ['rnr', 'programRnrColumnList']));
      });
    } else {
      _.each($scope.pageLineItems, function (lineItem) {
        rnr.fullSupplyLineItems.push(_.omit(lineItem, ['rnr', 'programRnrColumnList']));
      });
    }

    return rnr;
  }
}

CreateRequisitionController.resolve = {
  requisition:function ($q, $timeout, RequisitionById, $route, $rootScope) {
    var deferred = $q.defer();
    $timeout(function () {
      var rnr = $rootScope.rnr;
      if (rnr) {
        deferred.resolve(rnr);
        $rootScope.rnr = undefined;
        return;
      }
      RequisitionById.get({id:$route.current.params.rnr}, function (data) {
        deferred.resolve(data.rnr);
      }, {});
    }, 100);
    return deferred.promise;
  },

  rnrColumns:function ($q, $timeout, ProgramRnRColumnList, $route) {
    var deferred = $q.defer();
    $timeout(function () {
      ProgramRnRColumnList.get({programId:$route.current.params.program}, function (data) {
        deferred.resolve(data.rnrColumnList);
      }, {});
    }, 100);
    return deferred.promise;
  },

  currency:function ($q, $timeout, ReferenceData) {
    var deferred = $q.defer();
    $timeout(function () {
      ReferenceData.get({}, function (data) {
        deferred.resolve(data.currency);
      }, {});
    }, 100);
    return deferred.promise;
  },

  lossesAndAdjustmentsTypes:function ($q, $timeout, LossesAndAdjustmentsReferenceData) {
    var deferred = $q.defer();
    $timeout(function () {
      LossesAndAdjustmentsReferenceData.get({}, function (data) {
        deferred.resolve(data.lossAdjustmentTypes);
      }, {});
    }, 100);
    return deferred.promise;
  },

  facilityApprovedProducts:function ($q, $timeout, $route, FacilityApprovedProducts) {
    var deferred = $q.defer();
    $timeout(function () {
      FacilityApprovedProducts.get({facilityId:$route.current.params.facility, programId:$route.current.params.program}, function (data) {
        deferred.resolve(data.nonFullSupplyProducts);
      }, {});
    }, 100);
    return deferred.promise;
  },

  requisitionRights:function ($q, $timeout, $route, FacilityProgramRights) {
    var deferred = $q.defer();
    $timeout(function () {
      FacilityProgramRights.get({facilityId:$route.current.params.facility, programId:$route.current.params.program}, function (data) {
        deferred.resolve(data.rights);
      }, {});
    }, 100);
    return deferred.promise;
  }
};

<|endoftext|>


<commit_before>/*
 * Licensed to Jasig under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Jasig licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a
 * copy of the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/**
 * portal_window.js contains setup information for the
 * main portal navigation tab.
 */

// library includes

var win = Titanium.UI.currentWindow,
    app = win.app,
    portalView,
    portletView,
    portalGridView,
    createPortalView,
    drawHomeGrid,
    drawAndroidGrid,
    drawiOSGrid,
    getShowPortletFunc,
    getIconUrl,
    pathToRoot = '../../';

createPortalView = function () {
    if (portalView) {
        Ti.API.debug("Removing the existing portal home view");
        win.remove(portalView);
    }

    Ti.API.debug("Creating a new portal home view");
	portalView = Titanium.UI.createView(app.styles.homeGrid);

	var titleBar = new app.views.GenericTitleBar({
	    app: app,
	    windowKey: 'home',
	    title:app.localDictionary.uMobile,
	    settingsButton: true,
	    homeButton: false
	});
	win.add(titleBar);
    win.add(portalView);

    win.initialized = true;
};

getShowPortletFunc = function (portlet) {
    return function () {
        if (portlet.url) {
            Titanium.App.fireEvent('showPortlet', portlet);
        } else {
            Titanium.App.fireEvent(
                'showWindow',
                {
                    oldWindow: 'home',
                    newWindow: portlet.window
                }
            );
        }
    };
};

var sortPortlets = function(a, b) {

    // get the values for the configured property from
    // each object and transform them to lower case
    var aprop = a.title.toLowerCase();
    var bprop = b.title.toLowerCase();

    // if the values are identical, indicate an equals
    if (aprop === bprop) {
        return 0;
    }

    // otherwise perform a normal alphabetic sort
    if (aprop > bprop) {
        return 1;
    } else {
        return -1;
    }

};

getIconUrl = function (p) {
    var _iconUrl;

    if (!p.url && p.iconUrl) {
        _iconUrl = pathToRoot + p.iconUrl;
    }
    else if (p.iconUrl) {
        _iconUrl = win.app.UPM.BASE_PORTAL_URL + p.iconUrl;
    }
    else {
        _iconUrl = win.app.UPM.BASE_PORTAL_URL + '/ResourceServingWebapp/rs/tango/0.8.90/32x32/categories/applications-other.png';
    }

    return _iconUrl;
};

drawAndroidGrid = function (portlets) {
    Ti.API.debug("Preparing to iterate through portlets in drawAndroidGrid");
    for (var i=0, iLength = portlets.length; i<iLength; i++ ) {
        Ti.API.debug("Portlet iteration " + i + ", " + portlets[i].title);
        var _portlet, top, left, gridItem, gridItemLabel, gridItemIcon, gridBadgeBackground, gridBadgeNumber;
        _portlet = portlets[i];

        var completeWidth = app.styles.gridItem.width + 2 * app.styles.gridItem.padding;
        var completeHeight = app.styles.gridItem.width + 2 * app.styles.gridItem.padding;

        // calculate the appropriate number of columns based on the device
        // width and desired item size
        var numColumns = Math.floor(Ti.Platform.displayCaps.platformWidth / completeWidth);

        // calculate extra left padding to add to center the item grid
        var leftPadding = Math.floor(((Ti.Platform.displayCaps.platformWidth - (completeWidth * numColumns))) / 2);

        // Calculate the position for this grid item
        top = app.styles.gridItem.padding + Math.floor(i / numColumns) * completeHeight;
        left = leftPadding + app.styles.gridItem.padding + (i % numColumns) * completeWidth;

        // Create the container for the grid item
        var gridItemDefaults = app.styles.gridItem;
        gridItemDefaults.top = top;
        gridItemDefaults.left = left;
        gridItem = Titanium.UI.createView(gridItemDefaults);

        //Add a label to the grid item
        var gridItemLabelDefaults = app.styles.gridItemLabel;
        gridItemLabelDefaults.text =  _portlet.title.toLowerCase();
        gridItemLabel = Titanium.UI.createLabel(gridItemLabelDefaults);
        gridItem.add(gridItemLabel);

        //Add an icon to the grid item
        gridItemIconDefaults = app.styles.gridIcon;
        gridItemIconDefaults.image = getIconUrl(_portlet);
        gridItemIcon = Titanium.UI.createImageView(gridItemIconDefaults);
        gridItem.add(gridItemIcon);

        // TODO: hook up to actual badge icon service
        if (_portlet.newItemCount > 0) {
            Ti.API.info("blackboard");
            var gridBadgeBackgroundDefaults = app.styles.gridBadgeBackground;
            gridBadgeBackgroundDefaults.image = "../../icons/badgeBackground.png";
            gridBadgeBackground = Titanium.UI.createImageView(gridBadgeBackgroundDefaults);
            gridItem.add(gridBadgeBackground);

            var gridBadgeNumberDefaults = app.styles.gridBadgeNumber;
            gridBadgeNumberDefaults.text = _portlet.newItemCount;
            gridBadgeNumber = Titanium.UI.createLabel(gridBadgeNumberDefaults);
            gridItem.add(gridBadgeNumber);
        }

        Ti.API.debug("Placing the portlet in the portalView");
        //Place the item in the scrollview and listen for singletaps
        portalView.add(gridItem);
        gridItem.addEventListener("singletap", getShowPortletFunc(_portlet));
    }
};

drawiOSGrid = function (portlets) {
    var dashboardItems = [], dashboard;

    //Create the dashboard item to be placed  on the home screen
    for (var i=0, iLength=portlets.length; i<iLength; i++) {
        var _portlet, _dashboardItem, _iconContainer;
        _portlet = portlets[i];

        //Get the icon image for the portlet, or default.
        _dashboardItem = Titanium.UI.createDashboardItem({
            canDelete: false
        });

        _iconContainer = Titanium.UI.createView({
            width: 70,
            height: 70,
            borderRadius: 10,
            backgroundColor: '#eee',
            touchEnabled: true
        });
        _dashboardItem.add(_iconContainer);

        var _imageView = Titanium.UI.createImageView({
            image: getIconUrl(_portlet),
            width: 57,
            height: 57
        });
        _iconContainer.add(_imageView);
        _dashboardItem.add(Titanium.UI.createLabel({
            text: _portlet.title.toLowerCase(),
            textAlign: 'center',
            top: 45,
            height: 15,
            font: {
                fontSize: 13
            }
        }));

        dashboardItems.push(_dashboardItem);
    }

    //Create the dashboard to layout the dashboard items in the home screen
    dashboard = Titanium.UI.createDashboardView({
        backgroundColor: '#fff',
        height: Ti.Platform.displayCaps.platformHeight - win.app.UPM.TITLEBAR_HEIGHT,
        top: win.app.UPM.TITLEBAR_HEIGHT,
        data: dashboardItems
    });
    var doneButton = Titanium.UI.createButton({
        title: win.app.localDictionary.doneEditing,
        height: 30,
        width: Ti.Platform.displayCaps.platformWidth - 20,
        top: Ti.Platform.displayCaps.platformHeight - 100
    });
    dashboard.add(doneButton);
    doneButton.hide();
    win.add(dashboard);

    dashboard.addEventListener('edit',function(e){
        doneButton.show();
    });
    dashboard.addEventListener('commit',function(e){
        doneButton.hide();
    });
    doneButton.addEventListener('click',function(e){
        dashboard.stopEditing();
    });
};

drawHomeGrid = function (portlets) {
    portlets.sort(sortPortlets);

    if (Ti.Platform.osname === ('iphone' || 'ipad')) {
        // drawiOSGrid(portlets); //Temporarily drawing it the old way until this question is resolved: http://developer.appcelerator.com/question/117405/events-not-working-in-dashboarditem-after-adding-views.
        // Can resort to listening for click events on the whole dashboard view, and determining what to do based on the clicksource.
        drawAndroidGrid(portlets);
    }
    else if (Ti.Platform.osname === 'android') {
        Ti.API.debug('OS is Android, calling drawAndroidGrid');
        drawAndroidGrid(portlets);
    }
    win.initialized = true;
};

createPortalView();

var getPortletsForUser = function(onload) {
    var portlets;

    // Display a loading indicator until we can finish downloading the user
    // layout and creating the initial view
    win.add(app.views.GlobalActivityIndicator);
    app.views.GlobalActivityIndicator.message = app.localDictionary.loading;
    app.views.GlobalActivityIndicator.show();

    // Get the module list for this user from the portal server and create a
    // layout based on this list.
    portlets = app.UPM.getPortletList();
    app.lastUpdate = new Date();
    drawHomeGrid(portlets);

    // Remove our loading indicator
    app.views.GlobalActivityIndicator.hide();

};

var showSettings = function() {
    Ti.App.fireEvent(
        'showWindow',
        {
            oldWindow: 'home',
            newWindow: 'settings',
            transition: Titanium.UI.iPhone.AnimationStyle.FLIP_FROM_LEFT
        }
    );
};

win.app.UPM.establishSession(getPortletsForUser, showSettings);

Ti.App.addEventListener('credentialUpdate', function(e){
    createPortalView();
    win.app.UPM.establishSession(getPortletsForUser);
});
<commit_msg>UMOBILE-35 ensuring full icon URLs work<commit_after>/*
 * Licensed to Jasig under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Jasig licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a
 * copy of the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/**
 * portal_window.js contains setup information for the
 * main portal navigation tab.
 */

// library includes

var win = Titanium.UI.currentWindow,
    app = win.app,
    portalView,
    portletView,
    portalGridView,
    createPortalView,
    drawHomeGrid,
    drawAndroidGrid,
    drawiOSGrid,
    getShowPortletFunc,
    getIconUrl,
    pathToRoot = '../../';

createPortalView = function () {
    if (portalView) {
        Ti.API.debug("Removing the existing portal home view");
        win.remove(portalView);
    }

    Ti.API.debug("Creating a new portal home view");
	portalView = Titanium.UI.createView(app.styles.homeGrid);

	var titleBar = new app.views.GenericTitleBar({
	    app: app,
	    windowKey: 'home',
	    title:app.localDictionary.uMobile,
	    settingsButton: true,
	    homeButton: false
	});
	win.add(titleBar);
    win.add(portalView);

    win.initialized = true;
};

getShowPortletFunc = function (portlet) {
    return function () {
        if (portlet.url) {
            Titanium.App.fireEvent('showPortlet', portlet);
        } else {
            Titanium.App.fireEvent(
                'showWindow',
                {
                    oldWindow: 'home',
                    newWindow: portlet.window
                }
            );
        }
    };
};

var sortPortlets = function(a, b) {

    // get the values for the configured property from
    // each object and transform them to lower case
    var aprop = a.title.toLowerCase();
    var bprop = b.title.toLowerCase();

    // if the values are identical, indicate an equals
    if (aprop === bprop) {
        return 0;
    }

    // otherwise perform a normal alphabetic sort
    if (aprop > bprop) {
        return 1;
    } else {
        return -1;
    }

};

getIconUrl = function (p) {
    var _iconUrl;

    if (p.iconUrl && p.iconUrl.indexOf('/') == 0) {
        _iconUrl = win.app.UPM.BASE_PORTAL_URL + p.iconUrl;
    }
    else if (p.iconUrl) {
        _iconUrl = pathToRoot + p.iconUrl;
    }
    else {
        _iconUrl = win.app.UPM.BASE_PORTAL_URL + '/ResourceServingWebapp/rs/tango/0.8.90/32x32/categories/applications-other.png';
    }

    return _iconUrl;
};

drawAndroidGrid = function (portlets) {
    Ti.API.debug("Preparing to iterate through portlets in drawAndroidGrid");
    for (var i=0, iLength = portlets.length; i<iLength; i++ ) {
        Ti.API.debug("Portlet iteration " + i + ", " + portlets[i].title);
        var _portlet, top, left, gridItem, gridItemLabel, gridItemIcon, gridBadgeBackground, gridBadgeNumber;
        _portlet = portlets[i];

        var completeWidth = app.styles.gridItem.width + 2 * app.styles.gridItem.padding;
        var completeHeight = app.styles.gridItem.width + 2 * app.styles.gridItem.padding;

        // calculate the appropriate number of columns based on the device
        // width and desired item size
        var numColumns = Math.floor(Ti.Platform.displayCaps.platformWidth / completeWidth);

        // calculate extra left padding to add to center the item grid
        var leftPadding = Math.floor(((Ti.Platform.displayCaps.platformWidth - (completeWidth * numColumns))) / 2);

        // Calculate the position for this grid item
        top = app.styles.gridItem.padding + Math.floor(i / numColumns) * completeHeight;
        left = leftPadding + app.styles.gridItem.padding + (i % numColumns) * completeWidth;

        // Create the container for the grid item
        var gridItemDefaults = app.styles.gridItem;
        gridItemDefaults.top = top;
        gridItemDefaults.left = left;
        gridItem = Titanium.UI.createView(gridItemDefaults);

        //Add a label to the grid item
        var gridItemLabelDefaults = app.styles.gridItemLabel;
        gridItemLabelDefaults.text =  _portlet.title.toLowerCase();
        gridItemLabel = Titanium.UI.createLabel(gridItemLabelDefaults);
        gridItem.add(gridItemLabel);

        //Add an icon to the grid item
        gridItemIconDefaults = app.styles.gridIcon;
        gridItemIconDefaults.image = getIconUrl(_portlet);
        gridItemIcon = Titanium.UI.createImageView(gridItemIconDefaults);
        gridItem.add(gridItemIcon);

        // TODO: hook up to actual badge icon service
        if (_portlet.newItemCount > 0) {
            Ti.API.info("blackboard");
            var gridBadgeBackgroundDefaults = app.styles.gridBadgeBackground;
            gridBadgeBackgroundDefaults.image = "../../icons/badgeBackground.png";
            gridBadgeBackground = Titanium.UI.createImageView(gridBadgeBackgroundDefaults);
            gridItem.add(gridBadgeBackground);

            var gridBadgeNumberDefaults = app.styles.gridBadgeNumber;
            gridBadgeNumberDefaults.text = _portlet.newItemCount;
            gridBadgeNumber = Titanium.UI.createLabel(gridBadgeNumberDefaults);
            gridItem.add(gridBadgeNumber);
        }

        Ti.API.debug("Placing the portlet in the portalView");
        //Place the item in the scrollview and listen for singletaps
        portalView.add(gridItem);
        gridItem.addEventListener("singletap", getShowPortletFunc(_portlet));
    }
};

drawiOSGrid = function (portlets) {
    var dashboardItems = [], dashboard;

    //Create the dashboard item to be placed  on the home screen
    for (var i=0, iLength=portlets.length; i<iLength; i++) {
        var _portlet, _dashboardItem, _iconContainer;
        _portlet = portlets[i];

        //Get the icon image for the portlet, or default.
        _dashboardItem = Titanium.UI.createDashboardItem({
            canDelete: false
        });

        _iconContainer = Titanium.UI.createView({
            width: 70,
            height: 70,
            borderRadius: 10,
            backgroundColor: '#eee',
            touchEnabled: true
        });
        _dashboardItem.add(_iconContainer);

        var _imageView = Titanium.UI.createImageView({
            image: getIconUrl(_portlet),
            width: 57,
            height: 57
        });
        _iconContainer.add(_imageView);
        _dashboardItem.add(Titanium.UI.createLabel({
            text: _portlet.title.toLowerCase(),
            textAlign: 'center',
            top: 45,
            height: 15,
            font: {
                fontSize: 13
            }
        }));

        dashboardItems.push(_dashboardItem);
    }

    //Create the dashboard to layout the dashboard items in the home screen
    dashboard = Titanium.UI.createDashboardView({
        backgroundColor: '#fff',
        height: Ti.Platform.displayCaps.platformHeight - win.app.UPM.TITLEBAR_HEIGHT,
        top: win.app.UPM.TITLEBAR_HEIGHT,
        data: dashboardItems
    });
    var doneButton = Titanium.UI.createButton({
        title: win.app.localDictionary.doneEditing,
        height: 30,
        width: Ti.Platform.displayCaps.platformWidth - 20,
        top: Ti.Platform.displayCaps.platformHeight - 100
    });
    dashboard.add(doneButton);
    doneButton.hide();
    win.add(dashboard);

    dashboard.addEventListener('edit',function(e){
        doneButton.show();
    });
    dashboard.addEventListener('commit',function(e){
        doneButton.hide();
    });
    doneButton.addEventListener('click',function(e){
        dashboard.stopEditing();
    });
};

drawHomeGrid = function (portlets) {
    portlets.sort(sortPortlets);

    if (Ti.Platform.osname === ('iphone' || 'ipad')) {
        // drawiOSGrid(portlets); //Temporarily drawing it the old way until this question is resolved: http://developer.appcelerator.com/question/117405/events-not-working-in-dashboarditem-after-adding-views.
        // Can resort to listening for click events on the whole dashboard view, and determining what to do based on the clicksource.
        drawAndroidGrid(portlets);
    }
    else if (Ti.Platform.osname === 'android') {
        Ti.API.debug('OS is Android, calling drawAndroidGrid');
        drawAndroidGrid(portlets);
    }
    win.initialized = true;
};

createPortalView();

var getPortletsForUser = function(onload) {
    var portlets;

    // Display a loading indicator until we can finish downloading the user
    // layout and creating the initial view
    win.add(app.views.GlobalActivityIndicator);
    app.views.GlobalActivityIndicator.message = app.localDictionary.loading;
    app.views.GlobalActivityIndicator.show();

    // Get the module list for this user from the portal server and create a
    // layout based on this list.
    portlets = app.UPM.getPortletList();
    app.lastUpdate = new Date();
    drawHomeGrid(portlets);

    // Remove our loading indicator
    app.views.GlobalActivityIndicator.hide();

};

var showSettings = function() {
    Ti.App.fireEvent(
        'showWindow',
        {
            oldWindow: 'home',
            newWindow: 'settings',
            transition: Titanium.UI.iPhone.AnimationStyle.FLIP_FROM_LEFT
        }
    );
};

win.app.UPM.establishSession(getPortletsForUser, showSettings);

Ti.App.addEventListener('credentialUpdate', function(e){
    createPortalView();
    win.app.UPM.establishSession(getPortletsForUser);
});
<|endoftext|>


<commit_before>require('proof')(15, prove)

function prove (assert) {
    var Interrupt = require('..').createInterrupter('bigeasy.example')
    try {
        var error = new Error('x')
        error.code = 'ENOENT'
        throw new Interrupt('bar', {
            url: 'http://127.0.0.1:8080/foo',
            statusCode: 404,
            error: error, // Test JSON5 serialization of error ojbects.
            headers: {
                sent: {
                    'content-type': 'text/plain',
                    'content-length': '10'
                },
                received: {
                    'content-type': 'text/plain',
                    'content-length': '10'
                }
            }
        }, {
            value: 1
        })
    } catch (e) {
        console.log(e.stack)
        assert(/^bigeasy.example#bar$/m.test(e.message), 'message')
        assert(e.qualified, 'bigeasy.example#bar', 'interrupt')
        assert(e.statusCode, 404, 'context set')
        assert(e.value, 1, 'properties set')
    }
    try {
        try {
            throw new Error('foo')
        } catch (e) {
            throw new Interrupt('bar', { cause: e })
        }
    } catch (e) {
        console.log(e.stack)
        assert(/^bigeasy.example#bar$/m.test(e.message), 'no context')
        assert(e.causes[0].message, 'foo', 'cause')
        // TODO Assert cause.
    }
    try {
        try {
            throw new Error('foo')
        } catch (foo) {
            try {
                try {
                    throw new Error('bar')
                } catch (bar) {
                    throw new Interrupt('baz', { cause: bar, value: 2 })
                }
            } catch (baz) {
                console.log(baz.stack)
                throw new Interrupt('quux', { causes: [[ foo ], [ baz, { value: 1 } ], [ 1 ]] })
            }
        }
    } catch (e) {
        console.log(e.stack)
        assert(/^bigeasy.example#quux$/m.test(e.message), 'nested mulitple causes')
        assert(e.contexts[1].value, 1, 'cause context')
        assert(e.causes[1].causes[0].message, 'bar', 'nested')
        assert(e.causes[2], 1, 'nested and not an `Error`')
        // TODO Assert cause.
    }
    try {
        throw new Interrupt('bar', { depth: 2, key: 'value' })
    } catch (e) {
        console.log(e.stack)
        assert(/^bigeasy.example#bar$/m.test(e.message), 'no cause')
    }
    try {
        throw new Interrupt('bar')
    } catch (e) {
        console.log(e.stack)
        assert(/^bigeasy.example#bar$/m.test(e.message), 'nothing but message')
    }

    Interrupt.assert(true, 'assert')
    try {
        Interrupt.assert(false, 'assert')
    } catch (e) {
        console.log(e.stack)
        assert(/^bigeasy.example#assert$/m.test(e.message), 'assert failed')
    }

    Interrupt = require('../bootstrap').createInterrupterCreator(function () {})('bigeasy.example')

    try {
        throw new Interrupt('foo', { causes: [[ new Interrupt('bar', { value: 1 } ), { value: 1 } ]] })
    } catch (e) {
        console.log(e.message)
        assert(e.stack == null, 'no capture stack trace')
        assert(/^bigeasy.example#foo$/m.test(e.message), 'no captureStackTrace')
    }
}
<commit_msg>Rename `assert` to `okay`.<commit_after>require('proof')(15, prove)

function prove (okay) {
    var Interrupt = require('..').createInterrupter('bigeasy.example')
    try {
        var error = new Error('x')
        error.code = 'ENOENT'
        throw new Interrupt('bar', {
            url: 'http://127.0.0.1:8080/foo',
            statusCode: 404,
            error: error, // Test JSON5 serialization of error ojbects.
            headers: {
                sent: {
                    'content-type': 'text/plain',
                    'content-length': '10'
                },
                received: {
                    'content-type': 'text/plain',
                    'content-length': '10'
                }
            }
        }, {
            value: 1
        })
    } catch (e) {
        console.log(e.stack)
        okay(/^bigeasy.example#bar$/m.test(e.message), 'message')
        okay(e.qualified, 'bigeasy.example#bar', 'interrupt')
        okay(e.statusCode, 404, 'context set')
        okay(e.value, 1, 'properties set')
    }
    try {
        try {
            throw new Error('foo')
        } catch (e) {
            throw new Interrupt('bar', { cause: e })
        }
    } catch (e) {
        console.log(e.stack)
        okay(/^bigeasy.example#bar$/m.test(e.message), 'no context')
        okay(e.causes[0].message, 'foo', 'cause')
        // TODO Assert cause.
    }
    try {
        try {
            throw new Error('foo')
        } catch (foo) {
            try {
                try {
                    throw new Error('bar')
                } catch (bar) {
                    throw new Interrupt('baz', { cause: bar, value: 2 })
                }
            } catch (baz) {
                console.log(baz.stack)
                throw new Interrupt('quux', { causes: [[ foo ], [ baz, { value: 1 } ], [ 1 ]] })
            }
        }
    } catch (e) {
        console.log(e.stack)
        okay(/^bigeasy.example#quux$/m.test(e.message), 'nested mulitple causes')
        okay(e.contexts[1].value, 1, 'cause context')
        okay(e.causes[1].causes[0].message, 'bar', 'nested')
        okay(e.causes[2], 1, 'nested and not an `Error`')
        // TODO Assert cause.
    }
    try {
        throw new Interrupt('bar', { depth: 2, key: 'value' })
    } catch (e) {
        console.log(e.stack)
        okay(/^bigeasy.example#bar$/m.test(e.message), 'no cause')
    }
    try {
        throw new Interrupt('bar')
    } catch (e) {
        console.log(e.stack)
        okay(/^bigeasy.example#bar$/m.test(e.message), 'nothing but message')
    }

    Interrupt.assert(true, 'assert')
    try {
        Interrupt.assert(false, 'assert')
    } catch (e) {
        console.log(e.stack)
        okay(/^bigeasy.example#assert$/m.test(e.message), 'assert failed')
    }

    Interrupt = require('../bootstrap').createInterrupterCreator(function () {})('bigeasy.example')

    try {
        throw new Interrupt('foo', { causes: [[ new Interrupt('bar', { value: 1 } ), { value: 1 } ]] })
    } catch (e) {
        console.log(e.message)
        okay(e.stack == null, 'no capture stack trace')
        okay(/^bigeasy.example#foo$/m.test(e.message), 'no captureStackTrace')
    }
}
<|endoftext|>


<commit_before>'use strict'; define('web-ext-utils/tabview', [
], function(
) {

const styles = {
	default: `
		.content, .tablist, .tab {
			box-sizing: border-box;
		}
		.content {
			position: absolute;
			overflow: auto;
		}
		.tablist {
			position: absolute;
		}
		.tab {
			border-color: transparent;
			border-style: solid;
			border-width: 0;
			background-repeat: no-repeat;
			background-position: center left;
			transition-property: color, fill, background-color, border-color;
			transition-duration: 0.21s;
			cursor: pointer;
			-webkit-user-select: none;
			-moz-user-select: none;
		}
	`,
	vertical: `
		.content {
			top: 0px; height: 100%;
			right: 0px; width: calc(100% - 200px);
		}
		.tablist {
			top: 0px; height: 100%;
			left: 0px; width: 200px;
			padding-top: 54px;
		}
		.tab {
			height: 54px;
			line-height: 54px;
			padding-left: 54px;
			font-size: 24px;
			border-left-width: 5px;
			background-size: 48px;
		}
	`,
	horizontal: `
		.content {
			left: 0px; width: 100%;
			bottom: 0px; height: calc(100% - 40px);
		}
		.tablist {
			left: 0px; width: 100%;
			top: 0px; height: 40px;
		}
		.tab {
			float: left;
			height: 100%;
			line-height: 35px;
			padding-left: 32px;
			padding-right: 10px;
			background-position-x: 10px;
			background-size: 20px;
			border-bottom-width: 5px;
		}
	`,
	firefox: `
		.tablist {
			background-color: #424F5A;
		}
		.tab.active {
			color: #F2F2F2;
			border-color: orange;
			background-color: #343F48;
		}
		.tab:not(.active):hover {
			background-color: #5E6972;
		}
		.tab {
			color: #C1C1C1;
		}
	`,
};

return class Home {
	constructor({ host, content, tabs, active, onSelect, style, }) {
		this.style = host.appendChild(document.createElement('style'));
		this.style.scoped = true;
		this.style.textContent = typeof style !== 'string' ? '' : styles.default + style.split(' ').map(style => styles[style]).join('\n');
		this.tablist = host.appendChild(document.createElement('div'));
		this.tablist.classList = 'tablist';
		this.content = host.appendChild(content);
		this.content.classList = 'content';
		tabs.forEach(tab => this.add(tab));
		this.onSelect = onSelect;
		this.active = active;
	}

	set active(id) {
		const old = this.tablist.querySelector('.active');
		old && old.classList.remove('active');
		const now = this.get(id);
		now.classList.add('active');
		try { this.onSelect && this.onSelect(now); } catch (error) { console.error(error); }
	}
	get active() {
		return this.tablist.querySelector('.active').id;
	}

	add({ id, title, icon, position = Infinity, data, }) {
		const tab = this.tablist.insertBefore(document.createElement('div'), this.tablist.children[position]);
		tab.dataset.id = id;
		tab.className = 'tab';
		tab.style.backgroundImage = `url(${ icon })`;
		tab.textContent = title;
		tab.data = data;
		tab.onclick = ({ button, }) => !button && (this.active = id);
	}

	set(props) {
		const tab = this.get(props.id);
		'title' in props && (tab.textContent = props.title);
	}

	remove(id) {
		this.get(id).remove();
	}

	get(id) {
		return this.tablist.querySelector('.tab[data-id="'+ id +'"]');
	}
};

});
<commit_msg>allow an element as tabview tab icon<commit_after>'use strict'; define('web-ext-utils/tabview', [
], function(
) {

const styles = {
	default: `
		.content, .tablist, .tab {
			box-sizing: border-box;
			font-family: "Segoe UI";
		}
		.content {
			position: absolute;
			overflow: auto;
		}
		.tabwrapper {
			position: absolute;
			overflow: hidden;
		}
		.tablist {
			position: absolute;
			top: 0px; right: 0px; bottom: 0px; left: 0px;
			overflow: auto;
		}
		.tab {
			border-color: transparent;
			border-style: solid;
			border-width: 0;
			transition-property: color, fill, background-color, border-color;
			transition-duration: 0.21s;
			cursor: pointer;
			-webkit-user-select: none;
			-moz-user-select: none;
		}
		.tab>.icon {
			display: inline-block;
			background-size: 100%;
			background-repeat: no-repeat;
			background-position: center center;
			text-align: center;
		}
		.tab>.title {
		}
	`,
	vertical: `
		.content {
			top: 0px; height: 100%;
			right: 0px; width: calc(100% - 200px);
		}
		.tabwrapper {
			top: 0px; height: 100%;
			left: 0px; width: 200px;
		}
		.tablist {
			padding-top: 54px;
			overflow-y: scroll;
			overflow-x: hidden;
			margin-right: -17px;
		}
		.tab {
			height: 54px;
			line-height: 54px;
			font-size: 24px;
			border-left-width: 5px;
			padding: 3px;
		}
		.tab>.icon {
			height: 48px;
			width: 48px;
		}
		.tab>.title {
			position: relative;
			top: -15px;
		}
	`,
	horizontal: `
		.content {
			left: 0px; width: 100%;
			bottom: 0px; height: calc(100% - 40px);
		}
		.tabwrapper {
			left: 0px; width: 100%;
			top: 0px; height: 40px;
		}
		.tablist {
			/*overflow-y: hidden;*/
			/*overflow-x: scroll;*/
			/*margin-bottom: -17px;*/
		}
		.tab {
			float: left;
			height: 100%;
			line-height: 35px;
			padding-left: 0px;
			padding-right: 10px;
			border-bottom-width: 5px;
			padding: 6px;
		}
		.tab>.icon {
			height: 24px;
			width: 24px;
		}
		.tab>.title {
			position: relative;
			top: -7px;
			padding-left: 4px;
		}
	`,
	firefox: `
		.tablist {
			background-color: #424F5A;
		}
		.tab.active {
			color: #F2F2F2;
			border-color: orange;
			background-color: #343F48;
		}
		.tab:not(.active):hover {
			background-color: #5E6972;
		}
		.tab {
			color: #C1C1C1;
		}
	`,
};

return class Home {
	constructor({ host, content, tabs, active, onSelect, style, }) {
		this.style = host.appendChild(document.createElement('style'));
		this.style.scoped = true;
		this.style.textContent = typeof style !== 'string' ? '' : styles.default + style.split(' ').map(style => styles[style]).join('\n');
		this.tabwrapper = host.appendChild(document.createElement('div'));
		this.tabwrapper.classList = 'tabwrapper';
		this.tablist = this.tabwrapper.appendChild(document.createElement('div'));
		this.tablist.classList = 'tablist';
		this.content = host.appendChild(content);
		this.content.classList = 'content';
		tabs.forEach(tab => this.add(tab));
		this.onSelect = onSelect;
		this.active = active;
	}

	set active(id) {
		const old = this.tablist.querySelector('.active');
		old && old.classList.remove('active');
		const now = this.get(id);
		now.classList.add('active');
		try { this.onSelect && this.onSelect(now); } catch (error) { console.error(error); }
	}
	get active() {
		return this.tablist.querySelector('.active').id;
	}

	add({ id, title, icon, position = Infinity, data, }) {
		const tab = this.tablist.insertBefore(document.createElement('div'), this.tablist.children[position]);
		tab.className = 'tab';
		tab.dataset.id = id;
		tab.icon = tab.appendChild(document.createElement('div'));
		tab.icon.classList = 'icon';
		setIcon(tab, icon);
		tab._title = tab.appendChild(document.createElement('span'));
		tab._title.classList = 'title';
		tab._title.textContent = title;
		tab.data = data;
		tab.onclick = ({ button, }) => !button && (this.active = id);
	}

	set(props) {
		const tab = this.get(props.id);
		'title' in props && (tab._title.textContent = props.title);
		'icon' in props && setIcon(tab, props.icon);
	}

	remove(id) {
		this.get(id).remove();
	}

	get(id) {
		return this.tablist.querySelector('.tab[data-id="'+ id +'"]');
	}
};

function setIcon(tab, icon) {
	tab.icon.textContent = '';
	tab.icon.style.backgroundImage = '';
	if (typeof icon === 'string') {
		tab.icon.style.backgroundImage = `url(${ icon })`;
	} else if (icon instanceof Element) {
		tab.icon.appendChild(icon);
	}
}

});
<|endoftext|>


<commit_before>/*
 * grunt-acetate
 * https://github.com/patricklocal/grunt-acetate
 *
 * Copyright (c) 2014 Patrick Arlt
 * Licensed under the MIT license.
 */

'use strict';

var Acetate = require('acetate');
var server = require('acetate/lib/modes/server.js');
var watcher = require('acetate/lib/modes/watcher.js');
var builder = require('acetate/lib/modes/builder.js');

module.exports = function (grunt) {
  grunt.registerMultiTask('acetate', 'Grunt plugin for Acetate.', function () {
    var done = this.async();
    var target = this.target;
    var logHeader = false;
    var options = this.options({
      keepalive: false,
      args: {}
    });

    if (!options.mode) {
      grunt.fatal('no `mode` specificed in Acetate options.');
    }

    var acetate = new Acetate(options);

    // whenever we log anything spit out a header
    // cleaner output when using grunt watch
    function printLogHeader (e) {
      if (e.show && logHeader) {
        logHeader = false;
        grunt.log.header('Task "acetate:' + target + '" running');
      }
    }

    acetate.on('log', printLogHeader);

    // whenever grunt watch activates it spits out a header
    // we can spit out a header next time we log anything
    grunt.event.on('watch', function () {
      grunt.log.writeln();
      logHeader = true;
    });

    // rebind the log header whenever we restart Acetate
    acetate.on('config:loaded', function () {
      acetate.on('log', printLogHeader);
    });

    // if building end the task once we are done, unless keepalive is true
    if (options.mode === 'build') {
      builder(acetate).then(done).catch(done);
    }

    // if watching end the task as soon as the watcher starts, unless keepalive is true
    if (options.mode === 'watch') {
      watcher(acetate);

      acetate.once('watcher:ready', function () {
        logHeader = true;
        if (!options.keepalive) {
          done();
        }
      });
    }

    // if serving end the task as soon as the server starts, unless keepalive is true
    if (options.mode === 'server') {
      server(acetate, options.server);

      acetate.once('watcher:ready', function () {
        logHeader = true;
        if (!options.keepalive) {
          done();
        }
      });
    }
  });
};
<commit_msg>watcher<commit_after>/*
 * grunt-acetate
 * https://github.com/patricklocal/grunt-acetate
 *
 * Copyright (c) 2014 Patrick Arlt
 * Licensed under the MIT license.
 */

'use strict';

var Acetate = require('acetate');
var server = require('acetate/lib/modes/server.js');
var watcher = require('acetate/lib/modes/watcher.js');
var builder = require('acetate/lib/modes/builder.js');

module.exports = function (grunt) {
  grunt.registerMultiTask('acetate', 'Grunt plugin for Acetate.', function () {
    var done = this.async();
    var target = this.target;
    var logHeader = false;
    var options = this.options({
      keepalive: false,
      args: {}
    });

    if (!options.mode) {
      grunt.fatal('no `mode` specificed in Acetate options.');
    }

    var acetate = new Acetate(options);

    // whenever we log anything spit out a header
    // cleaner output when using grunt watch
    function printLogHeader (e) {
      if (e.show && logHeader) {
        logHeader = false;
        grunt.log.header('Task "acetate:' + target + '" running');
      }
    }

    acetate.on('log', printLogHeader);

    // whenever grunt watch activates it spits out a header
    // we can spit out a header next time we log anything
    grunt.event.on('watch', function () {
      grunt.log.writeln();
      logHeader = true;
    });

    // rebind the log header whenever we restart Acetate
    acetate.on('config:loaded', function () {
      acetate.on('log', printLogHeader);
    });

    // if building end the task once we are done, unless keepalive is true
    if (options.mode === 'build') {
      builder(acetate).then(done).catch(done);
    }

    // if watching end the task as soon as the watcher starts, unless keepalive is true
    if (options.mode === 'watcher') {
      watcher(acetate);

      acetate.once('watcher:ready', function () {
        logHeader = true;
        if (!options.keepalive) {
          done();
        }
      });
    }

    // if serving end the task as soon as the server starts, unless keepalive is true
    if (options.mode === 'server') {
      server(acetate, options.server);

      acetate.once('watcher:ready', function () {
        logHeader = true;
        if (!options.keepalive) {
          done();
        }
      });
    }
  });
};
<|endoftext|>


<commit_before>/*
 * grunt-builder
 * https://github.com/amkirwan/grunt-builder
 *
 * Copyright (c) 2014 Anthony Kirwan
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  var semver = require('semver');

  var newVersion;
  var versionFileRegExp = /^([\d||A-a|.|-]+)$/im;
  var versionRegExp = /([\'|\"]?version[\'|\"]?[ ]*:[ ]*[\'|\"]?)([\d||A-a|.|-]*)([\'|\"]?)/i;
  var readmeRegExp;
  var versionType;
  var tagName;
  var tagMessage;
  var commitMessage;

  grunt.registerMultiTask('builder', 'Grunt plugin for versioning, building and tagging your Git project.', function(type) {
    // set versionType
    versionType = type || 'patch';
    // reset newVersion for each grunt task
    newVersion = undefined;

    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      bump: true,
      file: 'VERSION',
      readmeText: 'Current Version:',
      tagMessage: 'Version <%= newVersion %>',
      commitMesage: 'Version <%= newVersion %>',
    });

    // setup the newVersion
    (function() {
      if (!grunt.file.exists(options.file)) {
        grunt.log.error('Version source file "' + options.file + '" not found.');
      }
      var version = grunt.file.read(options.file);
      bumpIt(version);
    })();

    var templateData = {
      data: {
        newVersion: newVersion
      }
    };

    // replace 'version in the template'
    options.tagName = grunt.template.process(options.tagName || 'v<%= newVersion %>', templateData);
    options.commitMessage = grunt.template.process(options.commitMessage || 'release <%= newVersion %>', templateData);
    options.tagMessage = grunt.template.process(options.commitMessage || 'version <%= newVersion %>', templateData);
    readmeRegExp = new RegExp("(^" + options.readmeText + ".*\\[)([\\d|.|\\-|a-z]+)(\\].*\\/)([\\d|.|\\-|a-z]+)(\\).*)", "img");

    // Iterate over all specified file groups.
    this.files.forEach(function(f) {
      // Concat specified files.
      var content = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.error('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        // Read file source.
        return grunt.file.read(filepath);
      }).toString();

      var updatedContent = bumpVersion(content, options);

      // Write the destination file.
      grunt.file.write(f.dest, updatedContent);

      // Print a success message.
      grunt.log.writeln('File "' + f.dest + '" created.');
    });
  });

  var bumpIt = function(parsedVersion) {
    if (newVersion === undefined) {
      newVersion = semver.inc(parsedVersion, versionType || 'patch');
    }
    return newVersion;
  };

  var bumpVersion = function(content, opts) {
    var newContent;
    if (content.match(readmeRegExp)) {
      newContent = content.replace(readmeRegExp, function(match, leadText, parsedVersion, urlUpToTag, versionUrl, endText,  offset, string) {
        return  leadText + newVersion + urlUpToTag + opts.tagName + endText;
      });
    } else if (content.match(versionRegExp)) {
      newContent = content.replace(versionRegExp, function(match, prefix, parsedVersion, suffix) {
        return prefix + newVersion + suffix;
      });
    } else if (content.match(versionFileRegExp)) {
      newContent = content.replace(versionFileRegExp, function(match, parsedVersion) {
        return newVersion;
      });
    }
    return newContent;
  };

};
<commit_msg>check if the optins.file is VERSION or package.json<commit_after>/*
 * grunt-builder
 * https://github.com/amkirwan/grunt-builder
 *
 * Copyright (c) 2014 Anthony Kirwan
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  var semver = require('semver');

  var newVersion;
  var versionFileRegExp = /^([\d||A-a|.|-]+)$/im;
  var versionRegExp = /([\'|\"]?version[\'|\"]?[ ]*:[ ]*[\'|\"]?)([\d||A-a|.|-]*)([\'|\"]?)/i;
  var readmeRegExp;
  var versionType;
  var tagName;
  var tagMessage;
  var commitMessage;

  grunt.registerMultiTask('builder', 'Grunt plugin for versioning, building and tagging your Git project.', function(type) {
    // set versionType
    versionType = type || 'patch';
    // reset newVersion for each grunt task
    newVersion = undefined;

    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      bump: true,
      file: 'VERSION',
      readmeText: 'Current Version:',
      tagMessage: 'Version <%= newVersion %>',
      commitMesage: 'Version <%= newVersion %>',
    });

    // setup the newVersion
    (function() {
      if (!grunt.file.exists(options.file)) {
        grunt.log.error('Version source file "' + options.file + '" not found.');
      }
      var version;
      if (options.file === 'package.json') {
        version = grunt.file.readJSON(options.file).version;
      } else {
        version = grunt.file.read(options.file);
      }
      bumpIt(version);
    })();

    var templateData = {
      data: {
        newVersion: newVersion
      }
    };

    // replace 'version in the template'
    options.tagName = grunt.template.process(options.tagName || 'v<%= newVersion %>', templateData);
    options.commitMessage = grunt.template.process(options.commitMessage || 'release <%= newVersion %>', templateData);
    options.tagMessage = grunt.template.process(options.commitMessage || 'version <%= newVersion %>', templateData);
    readmeRegExp = new RegExp("(^" + options.readmeText + ".*\\[)([\\d|.|\\-|a-z]+)(\\].*\\/)([\\d|.|\\-|a-z]+)(\\).*)", "img");

    // Iterate over all specified file groups.
    this.files.forEach(function(f) {
      // Concat specified files.
      var content = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.error('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        // Read file source.
        return grunt.file.read(filepath);
      }).toString();

      var updatedContent = bumpVersion(content, options);

      // Write the destination file.
      grunt.file.write(f.dest, updatedContent);

      // Print a success message.
      grunt.log.writeln('File "' + f.dest + '" created.');
    });
  });

  var bumpIt = function(parsedVersion) {
    if (newVersion === undefined) {
      newVersion = semver.inc(parsedVersion, versionType || 'patch');
    }
    return newVersion;
  };

  var bumpVersion = function(content, opts) {
    var newContent;
    if (content.match(readmeRegExp)) {
      newContent = content.replace(readmeRegExp, function(match, leadText, parsedVersion, urlUpToTag, versionUrl, endText,  offset, string) {
        return  leadText + newVersion + urlUpToTag + opts.tagName + endText;
      });
    } else if (content.match(versionRegExp)) {
      newContent = content.replace(versionRegExp, function(match, prefix, parsedVersion, suffix) {
        return prefix + newVersion + suffix;
      });
    } else if (content.match(versionFileRegExp)) {
      newContent = content.replace(versionFileRegExp, function(match, parsedVersion) {
        return newVersion;
      });
    }
    return newContent;
  };

};
<|endoftext|>


<commit_before>/*
 * grunt-builder
 * https://github.com/amkirwan/grunt-builder
 *
 * Copyright (c) 2014 Anthony Kirwan
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  var shell = require('shelljs');
  var semver = require('semver');

  grunt.registerMultiTask('builder', 'Grunt plugin for versioning, building and tagging your Git project.', function(versionType) {

    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      bump: true,
      file: 'package.json',
      gitAdd: true,
      gitCommit: true,
      gitPush: true,
      gitPushTag: true,
      readmeText: 'Current Version:',
      tagMessage: 'Version <%= newVersion %>',
      commitMesage: 'Version <%= newVersion %>'
    });

    var newVersion;
    var versionFileRegExp = /^([\d||A-a|.|-]+)$/im;
    var versionJSFileRegExp = /([\'|\"]?version[\'|\"]?\s*[:|=]\s*[\'|\"]?)([\d||A-a|.|-]*)([\'|\"]?)/i;
    var readmeRegExp = new RegExp("(^" + options.readmeText + ".*\\[)([\\d|.|\\-|a-z]+)(\\].*\\/)([\\d|.|\\-|a-z]+)(\\).*)", "img");

    // setup the newVersion
    (function() {
      if (!grunt.file.exists(options.file)) {
        grunt.log.error('Version source file "' + options.file + '" not found.');
      }
      // set versionType
      options.versionType = options.versionType || versionType || 'patch';

      // get the current version
      // var version = grunt.file.match(options.matchBase, 'package.json') ? grunt.file.readJSON(options.file).version : grunt.file.read(options.file);
      var version = (grunt.file.isMatch({matchBase: true}, '*.json', options.file)) ? grunt.file.readJSON(options.file).version : grunt.file.read(options.file);
      bumpIt(version); // set the newVersion
    })();

    var templateData = {
      data: {
        newVersion: newVersion
      }
    };

    // replace 'newVersion in the template', and update the options message
    options.tagName = grunt.template.process(options.tagName || 'v<%= newVersion %>', templateData);
    options.commitMessage = grunt.template.process(options.commitMessage || 'release <%= newVersion %>', templateData);
    options.tagMessage = grunt.template.process(options.commitMessage || 'version <%= newVersion %>', templateData);

    // Iterate over all specified file groups.
    this.files.forEach(function(f) {
      // Concat specified files.
      var content = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.error('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        // Read file source.
        return grunt.file.read(filepath);
      }).toString();

      var updatedContent = bumpVersion(content);

      // Write the destination file.
      grunt.file.write(f.dest, updatedContent);

      // Print a success message.
      grunt.log.writeln('File "' + f.dest + '" created.');
    });

    function gitAdd(file) {
      shell.exec('git add ' + file.src);
    }

    function bumpIt(parsedVersion) {
      if (options.setVersion !== undefined && newVersion === undefined) {
        newVersion = options.setVersion;
      } else if (newVersion === undefined) {
        newVersion = semver.inc(parsedVersion, options.versionType || 'patch');
      }
      return newVersion;
    }

    function bumpVersion(content) {
      var newContent;
      if (content.match(readmeRegExp)) {
        newContent = content.replace(readmeRegExp, function(match, leadText, parsedVersion, urlUpToTag, versionUrl, endText,  offset, string) {
          return  leadText + newVersion + urlUpToTag + options.tagName + endText;
        });
      } else if (content.match(versionJSFileRegExp)) {
        newContent = content.replace(versionJSFileRegExp, function(match, prefix, parsedVersion, suffix) {
          return prefix + newVersion + suffix;
        });
      } else if (content.match(versionFileRegExp)) {
        newContent = content.replace(versionFileRegExp, function(match, parsedVersion) {
          return newVersion;
        });
      }
      return newContent;
    }

  });
};
<commit_msg>added git commands<commit_after>/*
 * grunt-builder
 * https://github.com/amkirwan/grunt-builder
 *
 * Copyright (c) 2014 Anthony Kirwan
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  var shell = require('shelljs');
  var semver = require('semver');

  grunt.registerMultiTask('builder', 'Grunt plugin for versioning, building and tagging your Git project.', function(versionType) {

    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      bump: true,
      file: 'package.json',
      gitAdd: true,
      gitCommit: true,
      gitPush: true,
      gitPushTag: true,
      readmeText: 'Current Version:'
    });

    var newVersion;
    var versionFileRegExp = /^([\d||A-a|.|-]+)$/im;
    var versionJSFileRegExp = /([\'|\"]?version[\'|\"]?\s*[:|=]\s*[\'|\"]?)([\d||A-a|.|-]*)([\'|\"]?)/i;
    var readmeRegExp = new RegExp("(^" + options.readmeText + ".*\\[)([\\d|.|\\-|a-z]+)(\\].*\\/)([\\d|.|\\-|a-z]+)(\\).*)", "img");

    // setup the newVersion
    (function() {
      if (!grunt.file.exists(options.file)) {
        grunt.log.error('Version source file "' + options.file + '" not found.');
      }
      // set versionType
      options.versionType = options.versionType || versionType || 'patch';

      // get the current version
      // var version = grunt.file.match(options.matchBase, 'package.json') ? grunt.file.readJSON(options.file).version : grunt.file.read(options.file);
      var version = (grunt.file.isMatch({matchBase: true}, '*.json', options.file)) ? grunt.file.readJSON(options.file).version : grunt.file.read(options.file);
      bumpIt(version); // set the newVersion
    })();

    var templateData = {
      data: {
        newVersion: newVersion
      }
    };

    // replace 'newVersion in the template', and update the options message
    options.tagName = grunt.template.process(options.tagName || 'v<%= newVersion %>', templateData);
    options.commitMessage = grunt.template.process(options.commitMessage || 'Release: <%= newVersion %>', templateData);
    options.tagMessage = (options.tagMessage || 'Version: ' + options.tagName);

    // Iterate over all specified file groups.
    this.files.forEach(function(f) {
      // Concat specified files.
      var content = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.error('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        // Read file source.
        return grunt.file.read(filepath);
      }).toString();

      var updatedContent = bumpVersion(content);

      // Write the destination file.
      grunt.file.write(f.dest, updatedContent);

      // Print a success message.
      grunt.log.writeln('File "' + f.dest + '" created.');

      if (options.gitAdd) gitAdd(file);
    });
    // git commit and push
    if (options.gitTag) gitCommit();
    if (options.gitTag) gitTag();
    if (options.gitPush) gitPush();
    if (options.gitPushTag) gitPushTag();

    function gitAdd(file) {
      shell.exec('git add ' + file.src);
    }

    function gitCommit() {
      shell.exec('git commit -m' + options.commitMessage);
    }

    function gitTag() {
      shell.exec('git tag -a' + options.tagName + ' -m ' + options.tagMessage);
    }

    function gitPushTag() {
      shell.exec('git push --tags ');
    }

    function gitPush() {
      shell.exec('git push', 'pushed to remote');
    }

    function bumpIt(parsedVersion) {
      if (options.setVersion !== undefined && newVersion === undefined) {
        newVersion = options.setVersion;
      } else if (newVersion === undefined) {
        newVersion = semver.inc(parsedVersion, options.versionType || 'patch');
      }
      return newVersion;
    }

    function bumpVersion(content) {
      var newContent;
      if (content.match(readmeRegExp)) {
        newContent = content.replace(readmeRegExp, function(match, leadText, parsedVersion, urlUpToTag, versionUrl, endText,  offset, string) {
          return  leadText + newVersion + urlUpToTag + options.tagName + endText;
        });
      } else if (content.match(versionJSFileRegExp)) {
        newContent = content.replace(versionJSFileRegExp, function(match, prefix, parsedVersion, suffix) {
          return prefix + newVersion + suffix;
        });
      } else if (content.match(versionFileRegExp)) {
        newContent = content.replace(versionFileRegExp, function(match, parsedVersion) {
          return newVersion;
        });
      }
      return newContent;
    }

  });
};
<|endoftext|>


<commit_before>/*
 * grunt-csscomb
 * https://github.com/t32k/grunt-csscomb
 *
 * Copyright (c) 2013 Koji Ishimoto
 * Licensed under the MIT license.
 */
'use strict';
module.exports = function (grunt) {

  grunt.registerMultiTask('csscomb', 'Sorting CSS properties in specific order.', function () {

    var async = require('async'),
      Comb = require('csscomb'),
      defaultConfig = require('../node_modules/csscomb/.csscomb.json'),
      done = this.async();

    async.eachSeries(this.files, function (file, next) {
      // Get config file from task's options:
      var config = grunt.task.current.options().sortOrder;

      // Check if config file is set and exists. If not, use default one:
      if (config && grunt.file.exists(config)) {
        grunt.log.ok('Using custom config file "' + config + '"...');
        config = grunt.file.readJSON(config);
      } else {
        config = defaultConfig;
      }

      // Check if source file exists. If not, display a warning:
      if (file.src.length === 0) {
        grunt.log.error('Source file "' + file.orig.src + '" not found.');
        return;
      }

      // Create a new instance of csscomb and configure it:
      var comb = new Comb();
      comb.configure(config);

      // Get CSS from a source file:
      var css = grunt.file.read(file.src);
      // Comb it:
      grunt.log.ok('Sorting file "' + file.src + '"...');
      var combed = comb.processString(css);
      // Write result to a destination file:
      grunt.file.write(file.dest, combed);
      grunt.log.ok('OK.');

      // Repeat:
      next();
    }, done);
  });
};
<commit_msg>Update<commit_after>/*
 * grunt-csscomb
 * https://github.com/csscomb/grunt-csscomb
 *
 * Copyright (c) 2013 Koji Ishimoto, contributors
 * Licensed under the MIT license.
 */
'use strict';
module.exports = function (grunt) {

  grunt.registerMultiTask('csscomb', 'Sorting CSS properties in specific order.', function () {

    var async = require('async'),
        Comb = require('csscomb'),
        defaultConfig = require('../node_modules/csscomb/.csscomb.json'),
        done = this.async();

    async.eachSeries(this.files, function (file, next) {
      // Get config file from task's options:
      var config = grunt.task.current.options().sortOrder;

      // Check if config file is set and exists. If not, use default one:
      if (config && grunt.file.exists(config)) {
        grunt.log.ok('Using custom config file "' + config + '"...');
        config = grunt.file.readJSON(config);
      } else {
        config = defaultConfig;
      }

      // Check if source file exists. If not, display a warning:
      if (file.src.length === 0) {
        grunt.log.error('Source file "' + file.orig.src + '" not found.');
        return;
      }

      // Create a new instance of csscomb and configure it:
      var comb = new Comb();
      comb.configure(config);

      // Get CSS from a source file:
      var css = grunt.file.read(file.src);
      // Comb it:
      grunt.log.ok('Sorting file "' + file.src + '"...');
      var combed = comb.processString(css);
      // Write result to a destination file:
      grunt.file.write(file.dest, combed);
      grunt.log.ok('OK.');

      // Repeat:
      next();
    }, done);
  });
};
<|endoftext|>