<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF 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.
 */

var gadgets = gadgets || {};

/**
 * @fileoverview Provides remote content retrieval facilities.
 *     Available to every gadget.
 */

/**
 * @static
 * @class Provides remote content retrieval functions.
 * @name gadgets.io
 */

gadgets.io = function() {
  /**
   * Holds configuration-related data such as proxy urls.
   */
  var config = {};

  /**
   * Holds state for OAuth.
   */
  var oauthState;

  /**
   * Internal facility to create an xhr request.
   */
  function makeXhr() {
    if (window.XMLHttpRequest) {
      return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
      var x = new ActiveXObject("Msxml2.XMLHTTP");
      if (!x) {
        x = new ActiveXObject("Microsoft.XMLHTTP");
      }
      return x;
    }
  }

  /**
   * Checks the xobj for errors, may call the callback with an error response
   * if the error is fatal.
   *
   * @param {Object} xobj The XHR object to check
   * @param {Function} callback The callback to call if the error is fatal
   * @return true if the xobj is not ready to be processed
   */
  function hadError(xobj, callback) {
    if (xobj.readyState !== 4) {
      return true;
    }
    if (xobj.status !== 200) {
      // TODO Need to work on standardizing errors
      callback({errors : ["Error " + xobj.status]});
      return true;
    }
    return false;
  }

  /**
   * Handles non-proxied XHR callback processing.
   *
   * @param {String} url
   * @param {Function} callback
   * @param {Object} params
   * @param {Object} xobj
   */
  function processNonProxiedResponse(url, callback, params, xobj) {
    if (hadError(xobj, callback)) {
      return;
    }
    var data = {
      body: xobj.responseText
    };
    callback(transformResponseData(params, data));
  }

  var UNPARSEABLE_CRUFT = "throw 1; < don't be evil' >";

  /**
   * Handles XHR callback processing.
   *
   * @param {String} url
   * @param {Function} callback
   * @param {Object} params
   * @param {Object} xobj
   */
  function processResponse(url, callback, params, xobj) {
    if (hadError(xobj, callback)) {
      return;
    }
    var txt = xobj.responseText;
    // remove unparseable cruft.
    // TODO: really remove this by eliminating it. It's not any real security
    //    to begin with, and we can solve this problem by using post requests
    //    and / or passing the url in the http headers.
    txt = txt.substr(UNPARSEABLE_CRUFT.length);
    // We are using eval directly here because the outer response comes from a
    // trusted source, and json parsing is slow in IE.
    var data = eval("(" + txt + ")");
    data = data[url];
    // Save off any transient OAuth state the server wants back later.
    if (data.oauthState) {
      oauthState = data.oauthState;
    }
    callback(transformResponseData(params, data));
  }

  function transformResponseData(params, data) {
    var resp = {
     text: data.body,
     approvalUrl: data.approvalUrl,
     errors: []
    };
    switch (params.CONTENT_TYPE) {
      case "JSON":
        // Same as before, but specific to JSON (not FEED)
        resp.data = gadgets.json.parse(resp.text);
        if (!resp.data) {
          resp.errors.push("failed to parse JSON");
          resp.data = null;
        }
        break;
      case "FEED":
        if (!data.body) {
          resp.errors.push("failed to parse JSON");
          resp.data = null;
        }
        else {
          // Straight into the Feed object - override usual resp structure
          resp = data.body;
        }
        break;
      case "DOM":
        var dom;
        if (window.ActiveXObject) {
          dom = new ActiveXObject("Microsoft.XMLDOM");
          dom.async = false;
          dom.validateOnParse = false;
          dom.resolveExternals = false;
          if (!dom.loadXML(resp.text)) {
            resp.errors.push("failed to parse XML");
          } else {
            resp.data = dom;
          }
        } else {
          var parser = new DOMParser();
          dom = parser.parseFromString(resp.text, "text/xml");
          if ("parsererror" === dom.documentElement.nodeName) {
            resp.errors.push("failed to parse XML");
          } else {
            resp.data = dom;
          }
        }
        break;
      default:
        resp.data = resp.text;
        break;
    }

    return resp;
  }

  /**
   * Sends an XHR post or get request
   *
   * @param realUrl The url to fetch data from that was requested by the gadget
   * @param proxyUrl The url to proxy through
   * @param callback The function to call once the data is fetched
   * @param postData The data to post to the proxyUrl
   * @param params The params to use when processing the response
   * @param processResponseFunction The function that should process the
   *     response from the sever before calling the callback
   */
  function makeXhrRequest(realUrl, proxyUrl, callback, paramData, method,
      params, processResponseFunction) {
    var xhr = makeXhr();

    xhr.open(method, proxyUrl, true);
    if (callback) {
      xhr.onreadystatechange = gadgets.util.makeClosure(
          null, processResponseFunction, realUrl, callback, params, xhr);
    }
    if (paramData != null) {
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send(paramData);
    } else {
        xhr.send(null);
    }
  }

  /**
   * Satisfy a request with data that is prefetched as per the gadget Preload
   * directive. The preloader will only satisfy a request for a specific piece
   * of content once.
   *
   * @param postData The definition of the request to be executed by the proxy
   * @param params The params to use when processing the response
   * @param callback The function to call once the data is fetched
   * @return true if the request can be satisfied by the preloaded content
   *         false otherwise
   */
  function respondWithPreload(postData, params, callback) {
    if (gadgets.io.preloaded_ && gadgets.io.preloaded_[postData.url]) {
      var preload = gadgets.io.preloaded_[postData.url];
      if (postData.httpMethod == "GET") {
        delete gadgets.io.preloaded_[postData.url];
        if (preload.rc !== 200) {
          callback({errors : ["Error " + preload.rc]});
        } else {
          callback(transformResponseData(params, { body: preload.body }));
        }
        return true;
      }
    }
    return false;
  }

  /**
   * @param {Object} configuration Configuration settings
   * @private
   */
  function init (configuration) {
    config = configuration["core.io"];
  }

  var requiredConfig = {
    proxyUrl: new gadgets.config.RegExValidator(/.*%url%.*/),
    jsonProxyUrl: gadgets.config.NonEmptyStringValidator
  };
  gadgets.config.register("core.io", requiredConfig, init);

  return /** @scope gadgets.io */ {
    /**
     * Fetches content from the provided URL and feeds that content into the
     * callback function.
     *
     * Example:
     *

     * gadgets.io.makeRequest(url, fn,
     *    {contentType: gadgets.io.ContentType.FEED});
     *

     *
     * @param {String} url The URL where the content is located
     * @param {Function} callback The function to call with the data from the
     *     URL once it is fetched
     * @param {Map.<gadgets.io.RequestParameters, Object>} opt_params
     *     Additional
     *     parameters
     *     to pass to the request
     *
     * @member gadgets.io
     */
    makeRequest : function (url, callback, opt_params) {
      // TODO: This method also needs to respect all members of
      // gadgets.io.RequestParameters, and validate them.

      var params = opt_params || {};

      // Check if authorization is requested
      var auth, st;
      var reqState, oauthService, oauthToken;
      if (params.AUTHORIZATION && params.AUTHORIZATION !== "NONE") {
        auth = params.AUTHORIZATION.toLowerCase();
        st = gadgets.util.getUrlParameters().st;
        if (params.AUTHORIZATION === "AUTHENTICATED") {
          reqState = oauthState;
          oauthService = params.OAUTH_SERVICE;
          oauthToken = params.OAUTH_TOKEN;
        }
      } else {
        // Non auth'd & non post'd requests are cachable
        if (!params.REFRESH_INTERVAL && !params.POST_DATA) {
          params.REFRESH_INTERVAL = 3600;
         }
      }
      var signOwner = params.OWNER_SIGNED;
      var signViewer = params.VIEWER_SIGNED;

      var headers = params.HEADERS || {};
      if (params.METHOD === "POST" && !headers["Content-Type"]) {
        headers["Content-Type"] = "application/x-www-form-urlencoded";
      }

      var paramData = {
        url: url,
        httpMethod : params.METHOD || "GET",
        headers: gadgets.io.encodeValues(headers, false),
        postData : params.POST_DATA || "",
        authz : auth || "",
        st : st || "",
        oauthState : reqState || "",
        oauthService : oauthService || "",
        oauthToken : oauthToken || "",
        contentType : params.CONTENT_TYPE || "TEXT",
        numEntries : params.NUM_ENTRIES || "3",
        getSummaries : !!params.GET_SUMMARIES,
        signOwner : signOwner || "true",
        signViewer : signViewer || "true"
      };

      if (!respondWithPreload(paramData, params, callback, processResponse)) {
        var refreshInterval = params.REFRESH_INTERVAL || 0;

        if (refreshInterval > 0) {
          // this content should be cached
          // Add paramData to the URL
          var extraparams = "&refresh=" + refreshInterval + '&'
              + gadgets.io.encodeValues(paramData);

          makeXhrRequest(url, config.jsonProxyUrl + extraparams, callback,
              null, "GET", params, processResponse);

        } else {
          makeXhrRequest(url, config.jsonProxyUrl, callback,
              gadgets.io.encodeValues(paramData), "POST", params,
              processResponse);
        }
      }
    },

    /**
     * @private
     */
    makeNonProxiedRequest : function (relativeUrl, callback, opt_params) {
      var params = opt_params || {};
      makeXhrRequest(relativeUrl, relativeUrl, callback, params.POST_DATA,
          params.METHOD, params, processNonProxiedResponse);
    },

    /**
     * Converts an input object into a URL-encoded data string.
     * (key=value&...)
     *
     * @param {Object} fields The post fields you wish to encode
     * @param {Boolean} opt_noEscaping An optional parameter specifying whether
     *     to turn off escaping of the parameters. Defaults to false.
     * @return {String} The processed post data in www-form-urlencoded format.
     *
     * @member gadgets.io
     */
    encodeValues : function (fields, opt_noEscaping) {
      var escape = !opt_noEscaping;

      var buf = [];
      var first = false;
      for (var i in fields) if (fields.hasOwnProperty(i)) {
        if (!first) {
          first = true;
        } else {
          buf.push("&");
        }
        buf.push(escape ? encodeURIComponent(i) : i);
        buf.push("=");
        buf.push(escape ? encodeURIComponent(fields[i]) : fields[i]);
      }
      return buf.join("");
    },

    /**
     * Gets the proxy version of the passed-in URL.
     *
     * @param {String} url The URL to get the proxy URL for
     * @return {String} The proxied version of the URL
     *
     * @member gadgets.io
     */
    getProxyUrl : function (url) {
      return config.proxyUrl.replace("%url%", encodeURIComponent(url));
    }
  };
}();

gadgets.io.RequestParameters = gadgets.util.makeEnum([
  "METHOD",
  "CONTENT_TYPE",
  "POST_DATA",
  "HEADERS",
  "AUTHORIZATION",
  "NUM_ENTRIES",
  "GET_SUMMARIES",
  "REFRESH_INTERVAL",
  "OAUTH_SERVICE",
  "OAUTH_TOKEN"
]);

// PUT, DELETE, and HEAD not supported currently.
gadgets.io.MethodType = gadgets.util.makeEnum([
  "GET", "POST", "PUT", "DELETE", "HEAD"
]);

gadgets.io.ContentType = gadgets.util.makeEnum([
  "TEXT", "DOM", "JSON", "FEED"
]);

gadgets.io.AuthorizationType = gadgets.util.makeEnum([
  "NONE", "SIGNED", "AUTHENTICATED"
]);
<commit_msg>Previous patch broke consistency in the response object returned bygadgets.io.makeRequest<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF 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.
 */

var gadgets = gadgets || {};

/**
 * @fileoverview Provides remote content retrieval facilities.
 *     Available to every gadget.
 */

/**
 * @static
 * @class Provides remote content retrieval functions.
 * @name gadgets.io
 */

gadgets.io = function() {
  /**
   * Holds configuration-related data such as proxy urls.
   */
  var config = {};

  /**
   * Holds state for OAuth.
   */
  var oauthState;

  /**
   * Internal facility to create an xhr request.
   */
  function makeXhr() {
    if (window.XMLHttpRequest) {
      return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
      var x = new ActiveXObject("Msxml2.XMLHTTP");
      if (!x) {
        x = new ActiveXObject("Microsoft.XMLHTTP");
      }
      return x;
    }
  }

  /**
   * Checks the xobj for errors, may call the callback with an error response
   * if the error is fatal.
   *
   * @param {Object} xobj The XHR object to check
   * @param {Function} callback The callback to call if the error is fatal
   * @return true if the xobj is not ready to be processed
   */
  function hadError(xobj, callback) {
    if (xobj.readyState !== 4) {
      return true;
    }
    if (xobj.status !== 200) {
      // TODO Need to work on standardizing errors
      callback({errors : ["Error " + xobj.status]});
      return true;
    }
    return false;
  }

  /**
   * Handles non-proxied XHR callback processing.
   *
   * @param {String} url
   * @param {Function} callback
   * @param {Object} params
   * @param {Object} xobj
   */
  function processNonProxiedResponse(url, callback, params, xobj) {
    if (hadError(xobj, callback)) {
      return;
    }
    var data = {
      body: xobj.responseText
    };
    callback(transformResponseData(params, data));
  }

  var UNPARSEABLE_CRUFT = "throw 1; < don't be evil' >";

  /**
   * Handles XHR callback processing.
   *
   * @param {String} url
   * @param {Function} callback
   * @param {Object} params
   * @param {Object} xobj
   */
  function processResponse(url, callback, params, xobj) {
    if (hadError(xobj, callback)) {
      return;
    }
    var txt = xobj.responseText;
    // remove unparseable cruft.
    // TODO: really remove this by eliminating it. It's not any real security
    //    to begin with, and we can solve this problem by using post requests
    //    and / or passing the url in the http headers.
    txt = txt.substr(UNPARSEABLE_CRUFT.length);
    // We are using eval directly here because the outer response comes from a
    // trusted source, and json parsing is slow in IE.
    var data = eval("(" + txt + ")");
    data = data[url];
    // Save off any transient OAuth state the server wants back later.
    if (data.oauthState) {
      oauthState = data.oauthState;
    }
    callback(transformResponseData(params, data));
  }

  function transformResponseData(params, data) {
    var resp = {
     text: data.body,
     approvalUrl: data.approvalUrl,
     errors: []
    };
    switch (params.CONTENT_TYPE) {
      case "JSON":
        // Same as before, but specific to JSON (not FEED)
        resp.data = gadgets.json.parse(resp.text);
        if (!resp.data) {
          resp.errors.push("failed to parse JSON");
          resp.data = null;
        }
        break;
      case "FEED":
        if (!data.body) {
          resp.errors.push("failed to parse JSON");
          resp.data = null;
        } else {
          resp.data = data.body;
        }
        break;
      case "DOM":
        var dom;
        if (window.ActiveXObject) {
          dom = new ActiveXObject("Microsoft.XMLDOM");
          dom.async = false;
          dom.validateOnParse = false;
          dom.resolveExternals = false;
          if (!dom.loadXML(resp.text)) {
            resp.errors.push("failed to parse XML");
          } else {
            resp.data = dom;
          }
        } else {
          var parser = new DOMParser();
          dom = parser.parseFromString(resp.text, "text/xml");
          if ("parsererror" === dom.documentElement.nodeName) {
            resp.errors.push("failed to parse XML");
          } else {
            resp.data = dom;
          }
        }
        break;
      default:
        resp.data = resp.text;
        break;
    }

    return resp;
  }

  /**
   * Sends an XHR post or get request
   *
   * @param realUrl The url to fetch data from that was requested by the gadget
   * @param proxyUrl The url to proxy through
   * @param callback The function to call once the data is fetched
   * @param postData The data to post to the proxyUrl
   * @param params The params to use when processing the response
   * @param processResponseFunction The function that should process the
   *     response from the sever before calling the callback
   */
  function makeXhrRequest(realUrl, proxyUrl, callback, paramData, method,
      params, processResponseFunction) {
    var xhr = makeXhr();

    xhr.open(method, proxyUrl, true);
    if (callback) {
      xhr.onreadystatechange = gadgets.util.makeClosure(
          null, processResponseFunction, realUrl, callback, params, xhr);
    }
    if (paramData != null) {
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send(paramData);
    } else {
        xhr.send(null);
    }
  }

  /**
   * Satisfy a request with data that is prefetched as per the gadget Preload
   * directive. The preloader will only satisfy a request for a specific piece
   * of content once.
   *
   * @param postData The definition of the request to be executed by the proxy
   * @param params The params to use when processing the response
   * @param callback The function to call once the data is fetched
   * @return true if the request can be satisfied by the preloaded content
   *         false otherwise
   */
  function respondWithPreload(postData, params, callback) {
    if (gadgets.io.preloaded_ && gadgets.io.preloaded_[postData.url]) {
      var preload = gadgets.io.preloaded_[postData.url];
      if (postData.httpMethod == "GET") {
        delete gadgets.io.preloaded_[postData.url];
        if (preload.rc !== 200) {
          callback({errors : ["Error " + preload.rc]});
        } else {
          callback(transformResponseData(params, { body: preload.body }));
        }
        return true;
      }
    }
    return false;
  }

  /**
   * @param {Object} configuration Configuration settings
   * @private
   */
  function init (configuration) {
    config = configuration["core.io"];
  }

  var requiredConfig = {
    proxyUrl: new gadgets.config.RegExValidator(/.*%url%.*/),
    jsonProxyUrl: gadgets.config.NonEmptyStringValidator
  };
  gadgets.config.register("core.io", requiredConfig, init);

  return /** @scope gadgets.io */ {
    /**
     * Fetches content from the provided URL and feeds that content into the
     * callback function.
     *
     * Example:
     *

     * gadgets.io.makeRequest(url, fn,
     *    {contentType: gadgets.io.ContentType.FEED});
     *

     *
     * @param {String} url The URL where the content is located
     * @param {Function} callback The function to call with the data from the
     *     URL once it is fetched
     * @param {Map.<gadgets.io.RequestParameters, Object>} opt_params
     *     Additional
     *     parameters
     *     to pass to the request
     *
     * @member gadgets.io
     */
    makeRequest : function (url, callback, opt_params) {
      // TODO: This method also needs to respect all members of
      // gadgets.io.RequestParameters, and validate them.

      var params = opt_params || {};

      // Check if authorization is requested
      var auth, st;
      var reqState, oauthService, oauthToken;
      if (params.AUTHORIZATION && params.AUTHORIZATION !== "NONE") {
        auth = params.AUTHORIZATION.toLowerCase();
        st = gadgets.util.getUrlParameters().st;
        if (params.AUTHORIZATION === "AUTHENTICATED") {
          reqState = oauthState;
          oauthService = params.OAUTH_SERVICE;
          oauthToken = params.OAUTH_TOKEN;
        }
      } else {
        // Non auth'd & non post'd requests are cachable
        if (!params.REFRESH_INTERVAL && !params.POST_DATA) {
          params.REFRESH_INTERVAL = 3600;
         }
      }
      var signOwner = params.OWNER_SIGNED;
      var signViewer = params.VIEWER_SIGNED;

      var headers = params.HEADERS || {};
      if (params.METHOD === "POST" && !headers["Content-Type"]) {
        headers["Content-Type"] = "application/x-www-form-urlencoded";
      }

      var paramData = {
        url: url,
        httpMethod : params.METHOD || "GET",
        headers: gadgets.io.encodeValues(headers, false),
        postData : params.POST_DATA || "",
        authz : auth || "",
        st : st || "",
        oauthState : reqState || "",
        oauthService : oauthService || "",
        oauthToken : oauthToken || "",
        contentType : params.CONTENT_TYPE || "TEXT",
        numEntries : params.NUM_ENTRIES || "3",
        getSummaries : !!params.GET_SUMMARIES,
        signOwner : signOwner || "true",
        signViewer : signViewer || "true"
      };

      if (!respondWithPreload(paramData, params, callback, processResponse)) {
        var refreshInterval = params.REFRESH_INTERVAL || 0;

        if (refreshInterval > 0) {
          // this content should be cached
          // Add paramData to the URL
          var extraparams = "&refresh=" + refreshInterval + '&'
              + gadgets.io.encodeValues(paramData);

          makeXhrRequest(url, config.jsonProxyUrl + extraparams, callback,
              null, "GET", params, processResponse);

        } else {
          makeXhrRequest(url, config.jsonProxyUrl, callback,
              gadgets.io.encodeValues(paramData), "POST", params,
              processResponse);
        }
      }
    },

    /**
     * @private
     */
    makeNonProxiedRequest : function (relativeUrl, callback, opt_params) {
      var params = opt_params || {};
      makeXhrRequest(relativeUrl, relativeUrl, callback, params.POST_DATA,
          params.METHOD, params, processNonProxiedResponse);
    },

    /**
     * Converts an input object into a URL-encoded data string.
     * (key=value&...)
     *
     * @param {Object} fields The post fields you wish to encode
     * @param {Boolean} opt_noEscaping An optional parameter specifying whether
     *     to turn off escaping of the parameters. Defaults to false.
     * @return {String} The processed post data in www-form-urlencoded format.
     *
     * @member gadgets.io
     */
    encodeValues : function (fields, opt_noEscaping) {
      var escape = !opt_noEscaping;

      var buf = [];
      var first = false;
      for (var i in fields) if (fields.hasOwnProperty(i)) {
        if (!first) {
          first = true;
        } else {
          buf.push("&");
        }
        buf.push(escape ? encodeURIComponent(i) : i);
        buf.push("=");
        buf.push(escape ? encodeURIComponent(fields[i]) : fields[i]);
      }
      return buf.join("");
    },

    /**
     * Gets the proxy version of the passed-in URL.
     *
     * @param {String} url The URL to get the proxy URL for
     * @return {String} The proxied version of the URL
     *
     * @member gadgets.io
     */
    getProxyUrl : function (url) {
      return config.proxyUrl.replace("%url%", encodeURIComponent(url));
    }
  };
}();

gadgets.io.RequestParameters = gadgets.util.makeEnum([
  "METHOD",
  "CONTENT_TYPE",
  "POST_DATA",
  "HEADERS",
  "AUTHORIZATION",
  "NUM_ENTRIES",
  "GET_SUMMARIES",
  "REFRESH_INTERVAL",
  "OAUTH_SERVICE",
  "OAUTH_TOKEN"
]);

// PUT, DELETE, and HEAD not supported currently.
gadgets.io.MethodType = gadgets.util.makeEnum([
  "GET", "POST", "PUT", "DELETE", "HEAD"
]);

gadgets.io.ContentType = gadgets.util.makeEnum([
  "TEXT", "DOM", "JSON", "FEED"
]);

gadgets.io.AuthorizationType = gadgets.util.makeEnum([
  "NONE", "SIGNED", "AUTHENTICATED"
]);
<|endoftext|>


<commit_before>angular.module('app.controllers')

.controller('dishesCtrl', function($scope, $state, DishesService, SharesService, BillService, ionicToast) {

  function init() {

    // scope definitions
    angular.extend($scope, {

      currentDish: DishesService.new(),
      dishes: DishesService.all(),
      people: SharesService.all(),
      billTotal: 0,

      isSelectedPerson: function(person) {
        var currentPeople = $scope.currentDish.people;

        return currentPeople.some(function(currentPerson) {
          return person.name === currentPerson.name;
        });
      },

      togglePerson: function(event, person) {
        var checkbox = event.target;

        if (checkbox.checked) {
          addPersonToCurrentDish(person);
        } else {
          removePersonFromCurrentDish(person);
        }
      },

      addDish: function() {
        var validation = DishesService.save($scope.currentDish);

        if (!validation.valid) {
          return showToast(validation.messages[0]);
        }

        $scope.currentDish = DishesService.new();

        calculateLeftAmount();
      },

      removeDish: function(dish) {
        DishesService.delete(dish);
        $scope.currentDish = DishesService.new();
        calculateLeftAmount();
      },

      editDish: function(dish) {
        $scope.currentDish = angular.copy(dish);
      },

      validateNext : function() {
        if( $scope.billTotal == 0  ) {
          $state.go("pay");
        } else {
          showToast('You have not split all dishes. Please make it until amount goes zero');
        }
      }
    });

    calculateLeftAmount();
  }

  function addPersonToCurrentDish(person) {
    var currentPeople = $scope.currentDish.people;

    currentPeople.push(person);
  }

  function removePersonFromCurrentDish(person) {
    var currentPeople = $scope.currentDish.people,
        currentIndex = currentPeople.findIndex(function(currentPerson) {
          return currentPerson.id === person.id;
        });

    currentPeople.splice(currentIndex, 1);
  }

  function calculateLeftAmount() {
    var billTotal = BillService.getBill().totalAmount;
    var totalShare = 0;

    $scope.dishes.forEach(function(dish){
      totalShare += dish.price;
    })

    $scope.billTotal = billTotal - totalShare;
  }

  function showToast(message) {
    ionicToast.show(message, 'top', false, 2500);
  }

  init();

});
<commit_msg>Scroll to top when editing a dish<commit_after>angular.module('app.controllers')

.controller('dishesCtrl', function($scope, $state, DishesService, SharesService, BillService, ionicToast, $ionicScrollDelegate) {

  function init() {

    // scope definitions
    angular.extend($scope, {

      currentDish: DishesService.new(),
      dishes: DishesService.all(),
      people: SharesService.all(),
      billTotal: 0,

      isSelectedPerson: function(person) {
        var currentPeople = $scope.currentDish.people;

        return currentPeople.some(function(currentPerson) {
          return person.name === currentPerson.name;
        });
      },

      togglePerson: function(event, person) {
        var checkbox = event.target;

        if (checkbox.checked) {
          addPersonToCurrentDish(person);
        } else {
          removePersonFromCurrentDish(person);
        }
      },

      addDish: function() {
        var validation = DishesService.save($scope.currentDish);

        if (!validation.valid) {
          return showToast(validation.messages[0]);
        }

        $scope.currentDish = DishesService.new();

        calculateLeftAmount();
      },

      removeDish: function(dish) {
        DishesService.delete(dish);
        $scope.currentDish = DishesService.new();
        calculateLeftAmount();
      },

      editDish: function(dish) {
        $scope.currentDish = angular.copy(dish);

        $ionicScrollDelegate.scrollTop();
      },

      validateNext : function() {
        if( $scope.billTotal == 0  ) {
          $state.go("pay");
        } else {
          showToast('You have not split all dishes. Please make it until amount goes zero');
        }
      }
    });

    calculateLeftAmount();
  }

  function addPersonToCurrentDish(person) {
    var currentPeople = $scope.currentDish.people;

    currentPeople.push(person);
  }

  function removePersonFromCurrentDish(person) {
    var currentPeople = $scope.currentDish.people,
        currentIndex = currentPeople.findIndex(function(currentPerson) {
          return currentPerson.id === person.id;
        });

    currentPeople.splice(currentIndex, 1);
  }

  function calculateLeftAmount() {
    var billTotal = BillService.getBill().totalAmount;
    var totalShare = 0;

    $scope.dishes.forEach(function(dish){
      totalShare += dish.price;
    })

    $scope.billTotal = billTotal - totalShare;
  }

  function showToast(message) {
    ionicToast.show(message, 'top', false, 2500);
  }

  init();

});
<|endoftext|>


<commit_before>const gh = require('gh-pages')
const path = require('path')
const chalk = require('chalk')

const error = chalk.bold.red
const success = chalk.bold.green

gh.publish(path.join(__dirname, '_site'), (err) => {
  if (err) {
    console.log(error('\nError!'), err)
  } else {
    console.log(success('\nMission accomplished.'))
  }
})
<commit_msg>Delete deploy.js<commit_after><|endoftext|>


<commit_before>// @flow
'use strict'
const sortBy = require('lodash/sortBy')

const types = ['degree', 'major', 'concentration', 'emphasis']
function sortStudiesByType(studies: string[]) {
    return sortBy(studies, s => types.indexOf(s.type))
}

module.exports.sortStudiesByType = sortStudiesByType
<commit_msg>fix an input type<commit_after>// @flow
'use strict'
const sortBy = require('lodash/sortBy')

const types = ['degree', 'major', 'concentration', 'emphasis']
function sortStudiesByType(studies: Array<{type: string}>) {
    return sortBy(studies, s => types.indexOf(s.type))
}

module.exports.sortStudiesByType = sortStudiesByType
<|endoftext|>


<commit_before>/**
	The MIT License (MIT)

	Copyright (c) 2014 MyChannel-Apps.de

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.

	@author		Adrian Preuß <Bizarrus>
	@docs		http://www.mychannel-apps.de/documentation/core/channel
*/

var Channel = (new function() {
	var _channel		= KnuddelsServer.getChannel();
	var _configuration	= _channel.getChannelConfiguration();
	var _restrictions	= _channel.getChannelRestrictions();
	var _rights			= _configuration.getChannelRights();

	/*
		@docs	http://www.mychannel-apps.de/documentation/Channel_getChannel
	*/
	this.getName = function() {
		return _channel.getChannelName();
	};

	/*
		@docs	http://www.mychannel-apps.de/documentation/Channel_getModerators
	*/
	this.getModerators = function() {
		return _rights.getChannelModerators();
	};

	/*
		@docs	http://www.mychannel-apps.de/documentation/Channel_getOwners
	*/
	this.getOwners = function() {
		return _rights.getChannelOwners();
	};

	/*
		@docs	http://www.mychannel-apps.de/documentation/Channel_getMods
	*/
	this.getMods = function() {
		return _rights.getEventModerators();
	};

	this.getCMutes = function() {
		return _restrictions.getColorMutedUsers();
	};

	this.getMutes = function() {
		return _restrictions.getMutedUsers();
	};

	this.getCLs = function() {
		return _restrictions.getLockedUsers();
	};

	this.onDev = function() {
		return KnuddelsServer.isTestSystem();
	};

	/*
		@docs	http://www.mychannel-apps.de/documentation/Channel_getUsers

		Example Filter:
		{
			bot:		true,		// AppBot or SystemBot
			cm:			true,
			owner:		true,
			event:		true,
			online:		true,
			inChannel:	true,
			away:		true,
			developer:	true,
			status:		[
							Status.Newbie,
							Status.Family,
							Status.Stammi,
							Status.Ehrenz,
							Status.Admin,
							Status.Sysadmin,
							Status.Bot
						],
			gender:		[
							Gender.Male,
							Gender.Female,
							Gender.Unknown
						]
		}
	*/
	this.getUsers = function(filter) {
		filter 		= filter || {};
		var types	= [UserType.Human];

		if(filter.bot != undefined) {
			if(filter.bot) {
				types.push(UserType.AppBot);
				types.push(UserType.SystemBot);
			}
		}

		var users = [];
		var _users	= _channel.getOnlineUsers(types);

		// Return users if no other filters available
		if(
			!filter.exists('online') &&
			!filter.exists('inChannel') &&
			!filter.exists('away') &&
			!filter.exists('cmute') &&
			!filter.exists('mute') &&
			!filter.exists('cl') &&
			!filter.exists('developer') &&
			!filter.exists('owner') &&
			!filter.exists('event') &&
			!filter.exists('cm') &&
			!filter.exists('status') &&
			!filter.exists('gender') &&
			!filter.exists('age') &&
			!filter.exists('nickname') &&
			!filter.exists('minutes') &&
			!filter.exists('readme')
		) {
			return _users;
		}

		//_users.each(function(user, index) {
		for(var index = 0; index < _users.length; index++) {
			// Is Online
			if(filter.online != undefined && filter.online != _users[index].isOnline()) {
				continue;
			}

			// Is Online in Channel
			if(filter.inChannel != undefined && filter.inChannel != _users[index].isOnlineInChannel()) {
				continue;
			}

			// Is Away
			if(filter.away != undefined && filter.away != _users[index].isAway()) {
				continue;
			}

			// Is CMuted
			if(filter.cmute != undefined && filter.cmute != _users[index].isColorMuted()) {
				continue;
			}

			// Is Muted
			if(filter.mute != undefined && filter.mute != _users[index].isMuted()) {
				continue;
			}

			// Is CMuted
			if(filter.cl != undefined && filter.cl != _users[index].isLocked()) {
				continue;
			}

			// App Developer
			if(filter.developer != undefined && filter.developer != _users[index].isAppDeveloper()) {
				continue;
			}

			// Channel Owner
			if(filter.owner != undefined && filter.owner != _users[index].isChannelOwner()) {
				continue;
			}

			// Event Moderator
			if(filter.event != undefined && filter.event != _users[index].isEventModerator()) {
				continue;
			}

			// ChannelModerator
			if(filter.cm != undefined && filter.cm != _users[index].isChannelModerator()) {
				continue;
			}

			// Status
			if(filter.status != undefined && !filter.status.exists(_users[index].getUserStatus())) {
				continue;
			}

			// Gender
			if(filter.gender != undefined && !filter.gender.exists(_users[index].getGender())) {
			}

			// Age
			if(filter.age != undefined) {
				// user.getAge()
			}

			// Nickname
			if(filter.nickname != undefined) {
				// user.getNick();
			}

			// Minutes
			if(filter.minutes != undefined) {
				// user.getOnlineMinutes();
			}

			// Readme
			if(filter.readme != undefined) {
				// user.getReadme();
			}

			users.push(_users[index]);
		}
		return users;
	};

	this.toString = function() {
		return '[KFramework Channel]';
	};
}());<commit_msg>Channel: getOwner<commit_after>/**
	The MIT License (MIT)

	Copyright (c) 2014 MyChannel-Apps.de

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.

	@author		Adrian Preuß <Bizarrus>
	@docs		http://www.mychannel-apps.de/documentation/core/channel
*/

var Channel = (new function() {
	var _channel		= KnuddelsServer.getChannel();
	var _configuration	= _channel.getChannelConfiguration();
	var _restrictions	= _channel.getChannelRestrictions();
	var _rights			= _configuration.getChannelRights();

	/*
		@docs	http://www.mychannel-apps.de/documentation/Channel_getChannel
	*/
	this.getName = function() {
		return _channel.getChannelName();
	};

	this.getOwner = function() {
		var owners	= this.getOwners();
		var owner	= undefined;

		owners.each(function(user, index) {
			if(user.isOnlineInChannel()) {
				owner = user;
				return;
			}
		});

		return owner;
	};

	/*
		@docs	http://www.mychannel-apps.de/documentation/Channel_getModerators
	*/
	this.getModerators = function() {
		return _rights.getChannelModerators();
	};

	/*
		@docs	http://www.mychannel-apps.de/documentation/Channel_getOwners
	*/
	this.getOwners = function() {
		return _rights.getChannelOwners();
	};

	/*
		@docs	http://www.mychannel-apps.de/documentation/Channel_getMods
	*/
	this.getMods = function() {
		return _rights.getEventModerators();
	};

	this.getCMutes = function() {
		return _restrictions.getColorMutedUsers();
	};

	this.getMutes = function() {
		return _restrictions.getMutedUsers();
	};

	this.getCLs = function() {
		return _restrictions.getLockedUsers();
	};

	this.onDev = function() {
		return KnuddelsServer.isTestSystem();
	};

	/*
		@docs	http://www.mychannel-apps.de/documentation/Channel_getUsers

		Example Filter:
		{
			bot:		true,		// AppBot or SystemBot
			cm:			true,
			owner:		true,
			event:		true,
			online:		true,
			inChannel:	true,
			away:		true,
			developer:	true,
			status:		[
							Status.Newbie,
							Status.Family,
							Status.Stammi,
							Status.Ehrenz,
							Status.Admin,
							Status.Sysadmin,
							Status.Bot
						],
			gender:		[
							Gender.Male,
							Gender.Female,
							Gender.Unknown
						]
		}
	*/
	this.getUsers = function(filter) {
		filter 		= filter || {};
		var types	= [UserType.Human];

		if(filter.bot != undefined) {
			if(filter.bot) {
				types.push(UserType.AppBot);
				types.push(UserType.SystemBot);
			}
		}

		var users = [];
		var _users	= _channel.getOnlineUsers(types);

		// Return users if no other filters available
		if(
			!filter.exists('online') &&
			!filter.exists('inChannel') &&
			!filter.exists('away') &&
			!filter.exists('cmute') &&
			!filter.exists('mute') &&
			!filter.exists('cl') &&
			!filter.exists('developer') &&
			!filter.exists('owner') &&
			!filter.exists('event') &&
			!filter.exists('cm') &&
			!filter.exists('status') &&
			!filter.exists('gender') &&
			!filter.exists('age') &&
			!filter.exists('nickname') &&
			!filter.exists('minutes') &&
			!filter.exists('readme')
		) {
			return _users;
		}

		//_users.each(function(user, index) {
		for(var index = 0; index < _users.length; index++) {
			// Is Online
			if(filter.online != undefined && filter.online != _users[index].isOnline()) {
				continue;
			}

			// Is Online in Channel
			if(filter.inChannel != undefined && filter.inChannel != _users[index].isOnlineInChannel()) {
				continue;
			}

			// Is Away
			if(filter.away != undefined && filter.away != _users[index].isAway()) {
				continue;
			}

			// Is CMuted
			if(filter.cmute != undefined && filter.cmute != _users[index].isColorMuted()) {
				continue;
			}

			// Is Muted
			if(filter.mute != undefined && filter.mute != _users[index].isMuted()) {
				continue;
			}

			// Is CMuted
			if(filter.cl != undefined && filter.cl != _users[index].isLocked()) {
				continue;
			}

			// App Developer
			if(filter.developer != undefined && filter.developer != _users[index].isAppDeveloper()) {
				continue;
			}

			// Channel Owner
			if(filter.owner != undefined && filter.owner != _users[index].isChannelOwner()) {
				continue;
			}

			// Event Moderator
			if(filter.event != undefined && filter.event != _users[index].isEventModerator()) {
				continue;
			}

			// ChannelModerator
			if(filter.cm != undefined && filter.cm != _users[index].isChannelModerator()) {
				continue;
			}

			// Status
			if(filter.status != undefined && !filter.status.exists(_users[index].getUserStatus())) {
				continue;
			}

			// Gender
			if(filter.gender != undefined && !filter.gender.exists(_users[index].getGender())) {
			}

			// Age
			if(filter.age != undefined) {
				// user.getAge()
			}

			// Nickname
			if(filter.nickname != undefined) {
				// user.getNick();
			}

			// Minutes
			if(filter.minutes != undefined) {
				// user.getOnlineMinutes();
			}

			// Readme
			if(filter.readme != undefined) {
				// user.getReadme();
			}

			users.push(_users[index]);
		}
		return users;
	};

	this.toString = function() {
		return '[KFramework Channel]';
	};
}());<|endoftext|>


<commit_before>export default {
  title: 'General Layout System',
  codeSandbox: true,
  typescript: true,
  themeConfig: {
    styles: {
      playground: `
        padding: 32px
      `
    }
  }
}
<commit_msg>base based on hosting<commit_after>export default {
  title: 'General Layout System',
  base: '/gls/',
  codeSandbox: true,
  typescript: true,
  themeConfig: {
    styles: {
      playground: `
        padding: 32px
      `
    }
  }
}
<|endoftext|>


<commit_before>/*
 * Fizzle.js
 * Adapted from Sizzle.js
 */
// TODO: eq, lt, gt, and contains are considered valid selectors and should not be
// TODO: can we do eq as nth-child(x)?
// TODO: can we do gt as nth-child(n+x)?
// TODO: can we do lt as nth-child(~n+x)?
var _ = require('_'),

    _cache         = require('../../../cache'),
    _tokenCache    = _cache(),
    _subqueryCache = _cache(),

    _error = (!console || !console.error) ? _.noop :
        function(selector) {
            console.error('Invalid query selector (caught): ' + selector);
        };

var _booleans = 'checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped',

    _fromCharCode = String.fromCharCode,

    // http://www.w3.org/TR/css3-selectors/#whitespace
    _whitespace = '[\\x20\\t\\r\\n\\f]',

    // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
    _identifier = '(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+',

    // NOTE: Leaving double quotes to reduce escaping
    // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
    _attributes = "\\[" + _whitespace + "*(" + _identifier + ")(?:" + _whitespace +
        // Operator (capture 2)
        "*([*^$|!~]?=)" + _whitespace +
        // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
        "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + _identifier + "))|)" + _whitespace +
        "*\\]",

    _pseudos = ":(" + _identifier + ")(?:\\((" +
        // To reduce the number of selectors needing _tokenize in the preFilter, prefer arguments:
        // 1. quoted (capture 3; capture 4 or capture 5)
        "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
        // 2. simple (capture 6)
        "((?:\\\\.|[^\\\\()[\\]]|" + _attributes + ")*)|" +
        // 3. anything else (capture 2)
        ".*" +
        ")\\)|)",

    _rcomma = new RegExp('^' + _whitespace + '*,' + _whitespace + '*'),
    _rcombinators = new RegExp('^' + _whitespace + '*([>+~]|' + _whitespace + ')' + _whitespace + '*'),

    _rpseudo = new RegExp(_pseudos),

    _matchExpr = {
        ID:     new RegExp('^#('   + _identifier + ')'),
        CLASS:  new RegExp('^\\.(' + _identifier + ')'),
        TAG:    new RegExp('^('    + _identifier + '|[*])'),
        ATTR:   new RegExp('^'     + _attributes),
        PSEUDO: new RegExp('^'     + _pseudos),
        CHILD:  new RegExp('^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(' + _whitespace +
            '*(even|odd|(([+-]|)(\\d*)n|)' + _whitespace + '*(?:([+-]|)' + _whitespace +
            '*(\\d+)|))' + _whitespace + '*\\)|)', 'i'),

        // Note: Using double quotes due to parsing weirdness
        bool:   new RegExp("^(?:" + _booleans + ")$", "i"),

        // For use in libraries implementing .is()
        // We use this for POS matching in `select`
        needsContext: new RegExp('^' + _whitespace + '*[>+~]|:(even|odd|nth|eq|gt|lt|first|last)(?:\\(' +
            _whitespace + '*((?:-\\d)?\\d*)' + _whitespace + '*\\)|)(?=[^-]|$)', 'i')
    },

    // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
    _runescape = new RegExp('\\\\([\\da-f]{1,6}' + _whitespace + '?|(' + _whitespace + ')|.)', 'ig'),
    _funescape = function(_, escaped, escapedWhitespace) {
        var high = '0x' + (escaped - 0x10000);
        // NaN means non-codepoint
        // Support: Firefox<24
        // Workaround erroneous numeric interpretation of +'0x'
        return high !== high || escapedWhitespace ?
            escaped :
            high < 0 ?
                // BMP codepoint
                _fromCharCode(high + 0x10000) :
                // Supplemental Plane codepoint (surrogate pair)
                _fromCharCode((high >> 10) | 0xD800, (high & 0x3FF) | 0xDC00);
    },

    _preFilter = {
        ATTR: function(match) {
            match[1] = match[1].replace(_runescape, _funescape);

            // Move the given value to match[3] whether quoted or unquoted
            match[3] = ( match[3] || match[4] || match[5] || '' ).replace(_runescape, _funescape);

            if (match[2] === '~=') {
                match[3] = ' ' + match[3] + ' ';
            }

            return match.slice(0, 4);
        },

        CHILD: function(match) {
            /* matches from _matchExpr['CHILD']
                1 type (only|nth|...)
                2 what (child|of-type)
                3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
                4 xn-component of xn+y argument ([+-]?\d*n|)
                5 sign of xn-component
                6 x of xn-component
                7 sign of y-component
                8 y of y-component
             */
            match[1] = match[1].toLowerCase();

            if (match[1].slice(0, 3) === 'nth') {
                // nth-* requires argument
                if (!match[3]) {
                    throw new Error(match[0]);
                }

                // numeric x and y parameters for Expr.filter.CHILD
                // remember that false/true cast respectively to 0/1
                match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * (match[3] === 'even' || match[3] === 'odd'));
                match[5] = +(( match[7] + match[8]) || match[3] === 'odd');

            // other types prohibit arguments
            } else if (match[3]) {
                throw new Error(match[0]);
            }

            return match;
        },

        PSEUDO: function(match) {
            var excess,
                unquoted = !match[6] && match[2];

            if (_matchExpr.CHILD.test(match[0])) {
                return null;
            }

            // Accept quoted arguments as-is
            if (match[3]) {
                match[2] = match[4] || match[5] || '';

            // Strip excess characters from unquoted arguments
            } else if (unquoted && _rpseudo.test(unquoted) &&
                // Get excess from _tokenize (recursively)
                (excess = _tokenize(unquoted, true)) &&
                // advance to the next closing parenthesis
                (excess = unquoted.indexOf(')', unquoted.length - excess) - unquoted.length)) {

                // excess is a negative index
                match[0] = match[0].slice(0, excess);
                match[2] = unquoted.slice(0, excess);
            }

            // Return only captures needed by the pseudo filter method (type and argument)
            return match.slice(0, 3);
        }
    };

/**
 * Splits the given comma-separated CSS selector into separate sub-queries.
 * @param  {String} selector Full CSS selector (e.g., 'a, input:focus, div[attr="value"]').
 * @param  {Boolean} [parseOnly=false]
 * @return {String[]|Number|unll} Array of sub-queries (e.g., [ 'a', 'input:focus', 'div[attr="(value1),[value2]"]') or null if there was an error parsing.
 * @private
 */
var _tokenize = function(selector, parseOnly) {
    var cached = _tokenCache.get(selector);

    if (cached) {
        return parseOnly ? 0 : cached.slice(0);
    }

    var /** @type {String} */
        type,

        /** @type {RegExp} */
        regex,

        /** @type {Array} */
        match,

        /** @type {String} */
        matched,

        /** @type {String[]} */
        subqueries = [],

        /** @type {String} */
        subquery = '',

        /** @type {String} */
        soFar = selector;

    while (soFar) {
        // Comma and first run
        if (!matched || (match = _rcomma.exec(soFar))) {
            if (match) {
                // Don't consume trailing commas as valid
                soFar = soFar.slice(match[0].length) || soFar;
            }
            if (subquery) { subqueries.push(subquery); }
            subquery = '';
        }

        matched = null;

        // Combinators
        if ((match = _rcombinators.exec(soFar))) {
            matched = match.shift();
            subquery += matched;
            soFar = soFar.slice(matched.length);
        }

        // Filters
        for (type in _matchExpr) {
            regex = _matchExpr[type];
            match = regex.exec(soFar);

            if (match && (!_preFilter[type] || (match = _preFilter[type](match)))) {
                matched = match.shift();
                subquery += matched;
                soFar = soFar.slice(matched.length);

                break;
            }
        }

        if (!matched) {
            break;
        }
    }

    if (subquery) { subqueries.push(subquery); }

    // Return the length of the invalid excess
    // if we're just parsing.
    if (parseOnly) { return soFar.length; }

    if (soFar) { _error(selector); return null; }

    return _tokenCache.set(selector, subqueries).slice();
};

module.exports = {
    /**
     * Splits the given comma-separated CSS selector into separate sub-queries.
     * @param  {String} selector Full CSS selector (e.g., 'a, input:focus, div[attr="value"]').
     * @return {String[]} Array of sub-queries (e.g., [ 'a', 'input:focus', 'div[attr="(value1),[value2]"]').
     */
    subqueries: function(selector) {
        return _subqueryCache.getOrSet(selector, function() {
            return _tokenize(selector);
        });
    }
};
<commit_msg>Minor/ignore - Typo<commit_after>/*
 * Fizzle.js
 * Adapted from Sizzle.js
 */
// TODO: eq, lt, gt, and contains are considered valid selectors and should not be
// TODO: can we do eq as nth-child(x)?
// TODO: can we do gt as nth-child(n+x)?
// TODO: can we do lt as nth-child(~n+x)?
var _ = require('_'),

    _cache         = require('../../../cache'),
    _tokenCache    = _cache(),
    _subqueryCache = _cache(),

    _error = (!console || !console.error) ? _.noop :
        function(selector) {
            console.error('Invalid query selector (caught): ' + selector);
        };

var _booleans = 'checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped',

    _fromCharCode = String.fromCharCode,

    // http://www.w3.org/TR/css3-selectors/#whitespace
    _whitespace = '[\\x20\\t\\r\\n\\f]',

    // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
    _identifier = '(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+',

    // NOTE: Leaving double quotes to reduce escaping
    // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
    _attributes = "\\[" + _whitespace + "*(" + _identifier + ")(?:" + _whitespace +
        // Operator (capture 2)
        "*([*^$|!~]?=)" + _whitespace +
        // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
        "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + _identifier + "))|)" + _whitespace +
        "*\\]",

    _pseudos = ":(" + _identifier + ")(?:\\((" +
        // To reduce the number of selectors needing _tokenize in the preFilter, prefer arguments:
        // 1. quoted (capture 3; capture 4 or capture 5)
        "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
        // 2. simple (capture 6)
        "((?:\\\\.|[^\\\\()[\\]]|" + _attributes + ")*)|" +
        // 3. anything else (capture 2)
        ".*" +
        ")\\)|)",

    _rcomma = new RegExp('^' + _whitespace + '*,' + _whitespace + '*'),
    _rcombinators = new RegExp('^' + _whitespace + '*([>+~]|' + _whitespace + ')' + _whitespace + '*'),

    _rpseudo = new RegExp(_pseudos),

    _matchExpr = {
        ID:     new RegExp('^#('   + _identifier + ')'),
        CLASS:  new RegExp('^\\.(' + _identifier + ')'),
        TAG:    new RegExp('^('    + _identifier + '|[*])'),
        ATTR:   new RegExp('^'     + _attributes),
        PSEUDO: new RegExp('^'     + _pseudos),
        CHILD:  new RegExp('^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(' + _whitespace +
            '*(even|odd|(([+-]|)(\\d*)n|)' + _whitespace + '*(?:([+-]|)' + _whitespace +
            '*(\\d+)|))' + _whitespace + '*\\)|)', 'i'),

        // Note: Using double quotes due to parsing weirdness
        bool:   new RegExp("^(?:" + _booleans + ")$", "i"),

        // For use in libraries implementing .is()
        // We use this for POS matching in `select`
        needsContext: new RegExp('^' + _whitespace + '*[>+~]|:(even|odd|nth|eq|gt|lt|first|last)(?:\\(' +
            _whitespace + '*((?:-\\d)?\\d*)' + _whitespace + '*\\)|)(?=[^-]|$)', 'i')
    },

    // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
    _runescape = new RegExp('\\\\([\\da-f]{1,6}' + _whitespace + '?|(' + _whitespace + ')|.)', 'ig'),
    _funescape = function(_, escaped, escapedWhitespace) {
        var high = '0x' + (escaped - 0x10000);
        // NaN means non-codepoint
        // Support: Firefox<24
        // Workaround erroneous numeric interpretation of +'0x'
        return high !== high || escapedWhitespace ?
            escaped :
            high < 0 ?
                // BMP codepoint
                _fromCharCode(high + 0x10000) :
                // Supplemental Plane codepoint (surrogate pair)
                _fromCharCode((high >> 10) | 0xD800, (high & 0x3FF) | 0xDC00);
    },

    _preFilter = {
        ATTR: function(match) {
            match[1] = match[1].replace(_runescape, _funescape);

            // Move the given value to match[3] whether quoted or unquoted
            match[3] = ( match[3] || match[4] || match[5] || '' ).replace(_runescape, _funescape);

            if (match[2] === '~=') {
                match[3] = ' ' + match[3] + ' ';
            }

            return match.slice(0, 4);
        },

        CHILD: function(match) {
            /* matches from _matchExpr['CHILD']
                1 type (only|nth|...)
                2 what (child|of-type)
                3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
                4 xn-component of xn+y argument ([+-]?\d*n|)
                5 sign of xn-component
                6 x of xn-component
                7 sign of y-component
                8 y of y-component
             */
            match[1] = match[1].toLowerCase();

            if (match[1].slice(0, 3) === 'nth') {
                // nth-* requires argument
                if (!match[3]) {
                    throw new Error(match[0]);
                }

                // numeric x and y parameters for Expr.filter.CHILD
                // remember that false/true cast respectively to 0/1
                match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * (match[3] === 'even' || match[3] === 'odd'));
                match[5] = +(( match[7] + match[8]) || match[3] === 'odd');

            // other types prohibit arguments
            } else if (match[3]) {
                throw new Error(match[0]);
            }

            return match;
        },

        PSEUDO: function(match) {
            var excess,
                unquoted = !match[6] && match[2];

            if (_matchExpr.CHILD.test(match[0])) {
                return null;
            }

            // Accept quoted arguments as-is
            if (match[3]) {
                match[2] = match[4] || match[5] || '';

            // Strip excess characters from unquoted arguments
            } else if (unquoted && _rpseudo.test(unquoted) &&
                // Get excess from _tokenize (recursively)
                (excess = _tokenize(unquoted, true)) &&
                // advance to the next closing parenthesis
                (excess = unquoted.indexOf(')', unquoted.length - excess) - unquoted.length)) {

                // excess is a negative index
                match[0] = match[0].slice(0, excess);
                match[2] = unquoted.slice(0, excess);
            }

            // Return only captures needed by the pseudo filter method (type and argument)
            return match.slice(0, 3);
        }
    };

/**
 * Splits the given comma-separated CSS selector into separate sub-queries.
 * @param  {String} selector Full CSS selector (e.g., 'a, input:focus, div[attr="value"]').
 * @param  {Boolean} [parseOnly=false]
 * @return {String[]|Number|null} Array of sub-queries (e.g., [ 'a', 'input:focus', 'div[attr="(value1),[value2]"]') or null if there was an error parsing.
 * @private
 */
var _tokenize = function(selector, parseOnly) {
    var cached = _tokenCache.get(selector);

    if (cached) {
        return parseOnly ? 0 : cached.slice(0);
    }

    var /** @type {String} */
        type,

        /** @type {RegExp} */
        regex,

        /** @type {Array} */
        match,

        /** @type {String} */
        matched,

        /** @type {String[]} */
        subqueries = [],

        /** @type {String} */
        subquery = '',

        /** @type {String} */
        soFar = selector;

    while (soFar) {
        // Comma and first run
        if (!matched || (match = _rcomma.exec(soFar))) {
            if (match) {
                // Don't consume trailing commas as valid
                soFar = soFar.slice(match[0].length) || soFar;
            }
            if (subquery) { subqueries.push(subquery); }
            subquery = '';
        }

        matched = null;

        // Combinators
        if ((match = _rcombinators.exec(soFar))) {
            matched = match.shift();
            subquery += matched;
            soFar = soFar.slice(matched.length);
        }

        // Filters
        for (type in _matchExpr) {
            regex = _matchExpr[type];
            match = regex.exec(soFar);

            if (match && (!_preFilter[type] || (match = _preFilter[type](match)))) {
                matched = match.shift();
                subquery += matched;
                soFar = soFar.slice(matched.length);

                break;
            }
        }

        if (!matched) {
            break;
        }
    }

    if (subquery) { subqueries.push(subquery); }

    // Return the length of the invalid excess
    // if we're just parsing.
    if (parseOnly) { return soFar.length; }

    if (soFar) { _error(selector); return null; }

    return _tokenCache.set(selector, subqueries).slice();
};

module.exports = {
    /**
     * Splits the given comma-separated CSS selector into separate sub-queries.
     * @param  {String} selector Full CSS selector (e.g., 'a, input:focus, div[attr="value"]').
     * @return {String[]} Array of sub-queries (e.g., [ 'a', 'input:focus', 'div[attr="(value1),[value2]"]').
     */
    subqueries: function(selector) {
        return _subqueryCache.getOrSet(selector, function() {
            return _tokenize(selector);
        });
    }
};
<|endoftext|>


<commit_before>(function ($) {

    $.fn.reportes = function (data) {
        var _this = $(this);
        var plugin = _this.data('reportes');

        /*Inicializado ?*/
        if (!plugin) {

            plugin = new $.reportes(this, data);

            _this.data('reportes', plugin);

            return plugin;
            /*Si ya fue inizializado regresamos el plugin*/
        } else {
            return plugin;
        }

    };

    $.reportes = function (container, options) {

        var plugin = this;

        /*
         * Important Components
         */
        var $container = $(container);

        var settings;
        var $table;

        var defaults = {
        };

        /*
         * Private methods
         */

        /*
         * Public methods
         */

        plugin.init = function () {

            settings = plugin.settings = $.extend({}, defaults, options);

        }

        var controlBoton = function () {
            var select = true;
            $container.find('select').filter(function () {
                if ($(this).val() == "")
                    select = false;
            });
            var checkbox = false;
            $container.find('.generado').filter(function () {
                if ($(this).prop('checked'))
                    checkbox = true;
            });
            var activar = true;
            if (checkbox && select)
                activar = false;
            $('#generar_reporte').attr('disabled', activar);
            $('#generar_pdf').attr('disabled', activar);
            $('#generar_excel').attr('disabled', activar);
        }

        var controlBotonFormatoInventario = function () {
            var almacen = true;
            var formato = true;
            var checkbox = false;
            var activar = true;

            if ($('select[name=almacen]').val() == "")
                almacen = false;
            if ($('select[name=formato]').val() == "")
                formato = false;

            $container.find('.generado').filter(function () {
                if ($(this).prop('checked'))
                    checkbox = true;
            });

            if (almacen && formato && checkbox)
                activar = false;
            $('#generar_reporte').attr('disabled', activar);
        }

        var recientes = function ($dias) {
            $.ajax({
                async: false,
                type: "GET",
                url: "/reportes/formatoinventario/getrecientes",
                dataType: "json",
                data: {dias: $dias},
                success: function (data) {
                    if (data.length != 0) {
                        for (var k in data) {
                            var tr = $('#producto-' + data[k]).closest("tr");
                            tr.find('input').prop('checked', true);
                        }
                    }
                },
            });
            revisarCheckbox();
        }

        var revisarCheckbox = function () {
            var all_checked = true;
            $container.find('.generadoc').filter(function () {
                var cat_checked = true;
                $container.find('.' + $(this).val()).filter(function () {
                    if (!$(this).prop('checked')) {
                        cat_checked = false;
                    }
                });
                if ($container.find('.' + $(this).val()).length > 0)
                    $(this).prop('checked', cat_checked);
            });

            $container.find('.generadoc').filter(function () {
                if (!$(this).prop('checked')) {
                    all_checked = false;
                }
            });
            $('#todos').prop('checked', all_checked);
        }
        var revisarCheckboxEntradasporcompra = function () {
            var proveedor = false;
            var almacen = false;
            var producto = false;
            $container.find('.proveedor').filter(function () {
                if ($(this).prop('checked'))
                    proveedor = true;
            });

            $container.find('.almacen').filter(function () {
                if ($(this).prop('checked'))
                    almacen = true;
            });

            $container.find('.producto').filter(function () {
                if ($(this).prop('checked'))
                    producto = true;
            });
            var activar = (proveedor && almacen && producto) ? false : true;
            $('#generar_reporte').attr('disabled', activar);
            $('#generar_excel').attr('disabled', activar);
            $('#generar_pdf').attr('disabled', activar);
        }

        plugin.variacioncostos = function (no_data) {
            if (no_data == 1) {
                $('form input,form select,form button[type=submit]').attr('disabled', true);
                $('#no_data').html('No existen registros para reporte')
            } else {
                $container.find('input:checkbox').on('click', function () {
                    var $this = $(this);
                    var id = $this.attr('id');
                    if (id != "todos") {
                        if ($this.val() != "on") {
                            $container.find('.' + $this.val()).filter(function () {
                                if ($this.prop('checked'))
                                    $(this).prop('checked', true);
                                else
                                    $(this).prop('checked', false);
                            });
                        }
                        revisarCheckbox();
                    } else {
                        if ($this.prop('checked')) {
                            $container.find('.generado').prop('checked', true);
                            $container.find('.generadoc').prop('checked', true);
                        } else {
                            $container.find('.generado').prop('checked', false);
                            $container.find('.generadoc').prop('checked', false);
                        }
                    }
                    controlBoton();
                });

                /*
                $('#producto_search').on('keyup', function () {
                    var busqueda = $(this).val();
                    $container.find('#reporte_table tbody tr').filter(function () {

                        var palabra = $(this).find('td').eq(1).text();
                        $(this).attr("hidden", !palabra.includes(busqueda));
                    });
                });
                */

               var table = $container.find('#reporte_table');
                $.ajax({
                    url:'/application/json/datatable/lang_es.json',
                    dataType:'json',
                    success:function(data){
                       table.dataTable({
                           "language":data,
                           "order":[],
                           "bPaginate": false
                       });
                    },
                });
                $container.find('select').on('change', function () {
                    controlBoton();
                });
            }
        }

        plugin.formatoinventario = function () {

            $('select[name=formato]').on('change', function () {
                controlBotonFormatoInventario();
            });

            $('select[name=almacen]').on('change', function () {
                controlBotonFormatoInventario();
            });

            $container.find('input:checkbox').on('click', function () {
                var $this = $(this);
                var id = $this.attr('id');
                if (id != "todos") {
                    if ($this.val() != "on") {
                        $container.find('.' + $this.val()).filter(function () {
                            if ($this.prop('checked'))
                                $(this).prop('checked', true);
                            else
                                $(this).prop('checked', false);
                        });
                    }
                    revisarCheckbox();
                } else {
                    if ($this.prop('checked')) {
                        $container.find('.generado').prop('checked', true);
                        $container.find('.generadoc').prop('checked', true);
                    } else {
                        $container.find('.generado').prop('checked', false);
                        $container.find('.generadoc').prop('checked', false);
                    }
                }
                controlBoton();
            });

            $('#producto_search').on('keyup', function () {
                var busqueda = $(this).val();
                $container.find('#reporte_table tbody tr').filter(function () {
                    var palabra = $(this).find('td').eq(1).text();
                    $(this).attr("hidden", !palabra.includes(busqueda));
                });
            });
        }

        plugin.entradasporcompras = function (mes_min, anio_min, mes_max, anio_max, existencia) {
            revisarCheckboxEntradasporcompra();
            if (existencia == 1) {
                var minDate = new Date(anio_min + '/' + mes_min + '/' + '01');
                var maxDate = new Date(anio_max + '/' + mes_max + '/' + '31');

                container.find('input[name=fecha_inicial]').datepicker({
                    startDate: minDate,
                    endDate: maxDate,
                    format: 'dd/mm/yyyy',
                });

                container.find('input[name=fecha_final]').datepicker({
                    startDate: minDate,
                    endDate: maxDate,
                    format: 'dd/mm/yyyy',
                });
            } else {
                $('input[name=fecha_inicial]').attr('disabled', true);
                $('input[name=fecha_final]').attr('disabled', true);
                $('#generar_reporte').attr('disabled', true);
                $('#generar_excel').attr('disabled', true);
                $('#generar_pdf').attr('disabled', true);
                $('#no_data').html('No existen registros de compras')
            }

            $.ajax({
                url: '/application/json/datatable/lang_es.json',
                dataType: 'json',
                success: function (data) {
                    var table = $container.find('#proveedores_table').dataTable({
                        "lengthMenu": [ 10, 25, 50, 100, 200, 500 ],
                        "language": data,
                        "order": [],
                    });

                    var table2 = $container.find('#productos_table').dataTable({
                        "lengthMenu": [ 10, 25, 50, 100, 200, 500 ],
                        "language": data,
                        "order": [],
                    });

                    var table3 = $container.find('#almacenes_table').dataTable({
                        "lengthMenu": [ 10, 25, 50, 100, 200, 500 ],
                        "language": data,
                        "order": [],
                    });

                    $('form#entradasporcomprasForm').on('submit',function(e){

                        $(table.fnGetNodes()).each(function(){
                            var checkbox = $(this).find('input');
                            if(checkbox.is(":checked")){
                                $('form#entradasporcomprasForm').append(
                                    $('<input>')
                                       .attr('type', 'hidden')
                                       .attr('name', checkbox.attr('name'))
                                       .attr('checked',true)

                                 );
                            }

                        });

                        $(table2.fnGetNodes()).each(function(){
                            var checkbox = $(this).find('input');
                            if(checkbox.is(":checked")){
                                $('form#entradasporcomprasForm').append(
                                    $('<input>')
                                       .attr('type', 'hidden')
                                       .attr('name', checkbox.attr('name'))
                                       .attr('checked',true)

                                 );
                            }

                        });

                        $(table3.fnGetNodes()).each(function(){
                            var checkbox = $(this).find('input');
                            if(checkbox.is(":checked")){
                                $('form#entradasporcomprasForm').append(
                                    $('<input>')
                                       .attr('type', 'hidden')
                                       .attr('name', checkbox.attr('name'))
                                       .attr('checked',true)

                                 );
                            }

                        });

                    });
                },
            });

            var almacenes_table = $container.find('#almacenes_table');
            $.ajax({
                url: '/application/json/datatable/lang_es.json',
                dataType: 'json',
                success: function (data) {
                    almacenes_table.dataTable({
                        "lengthMenu": [ 10, 25, 50, 100, 200, 500 ],
                        "language": data,
                        "order": [],
                    });
                },
            });

            $('#proveedores_sel').on('click', function () {
                $container.find('#proveedores_table input:checkbox').prop('checked', true);
                revisarCheckboxEntradasporcompra();
            });

            $('#proveedores_des').on('click', function () {
                $container.find('#proveedores_table input:checkbox').prop('checked', false);
                revisarCheckboxEntradasporcompra();
            });

            $('#almacenes_sel').on('click', function () {
                $container.find('#almacenes_table input:checkbox').prop('checked', true);
                revisarCheckboxEntradasporcompra();
            });

            $('#almacenes_des').on('click', function () {
                $container.find('#almacenes_table input:checkbox').prop('checked', false);
                revisarCheckboxEntradasporcompra();
            });

            $('#productos_sel').on('click', function () {
                $container.find('#productos_table input:checkbox').prop('checked', true);
                revisarCheckboxEntradasporcompra();
            });

            $('#productos_des').on('click', function () {
                $container.find('#productos_table input:checkbox').prop('checked', false);
                revisarCheckboxEntradasporcompra();
            });

            $container.find('input:checkbox').on('click', function () {
                revisarCheckboxEntradasporcompra();
            });
        }

        plugin.informeacumulados = function (no_data, mes_min, anio_min, mes_max, anio_max, dia_max) {
            if (no_data == 1) {
                $('input[name=fecha_inicial]').attr('disabled', true);
                $('input[name=fecha_final]').attr('disabled', true);
                $('#generar_reporte').attr('disabled', true);
                $('#generar_excel').attr('disabled', true);
                $('#generar_pdf').attr('disabled', true);
                $('#no_data').html('No existen registros de flujo efectivo')
            }

            var minDate = new Date(anio_min + '/' + mes_min + '/' + '01');
            var maxDate = new Date(anio_max + '/' + mes_max + '/' + dia_max);

            container.find('input[name=fecha_inicial]').datepicker({
                startDate: minDate,
                endDate: maxDate,
                format: 'dd/mm/yyyy',
            });

            container.find('input[name=fecha_final]').datepicker({
                startDate: minDate,
                endDate: maxDate,
                format: 'dd/mm/yyyy',
            });
            $('input[name=fecha_inicial]').on('blur', function () {
                if ($(this).val() != "" && $('input[name=fecha_final]').val() != "")
                    $('#generar_reporte').prop("type", "button");
                else
                    $('#generar_reporte').prop("type", "submit");
            });

            $('input[name=fecha_final]').on('blur', function () {
                if ($(this).val() != "" && $('input[name=fecha_inicial]').val() != "")
                    $("#generar_reporte").prop("type", "button");
                else
                    $('#generar_reporte').prop("type", "submit");
            });

            $("#generar_reporte").on('click', function () {
                if ($(this).attr('type') == "button") {
                    var inicio = $('input[name=fecha_inicial]').val();
                    var fin = $('input[name=fecha_final]').val();
                    var table = $('#reporte_table');
                    $.ajax({
                        async: false,
                        type: "POST",
                        url: "/reportes/informeacumulados",
                        dataType: "json",
                        data: {fecha_inicial: inicio, fecha_final: fin},
                        success: function (data) {
                            if (data.length != 0) {
                                $('#reporte_table > tbody').empty();
                                for (var k in data) {
                                    table.append(data[k]);
                                }
                            }
                        },
                    });
                }
            });
        }

        /*
         * Plugin initializing
         */

        plugin.init();

    }
})(jQuery);

<commit_msg>aersa<commit_after>(function ($) {

    $.fn.reportes = function (data) {
        var _this = $(this);
        var plugin = _this.data('reportes');

        /*Inicializado ?*/
        if (!plugin) {

            plugin = new $.reportes(this, data);

            _this.data('reportes', plugin);

            return plugin;
            /*Si ya fue inizializado regresamos el plugin*/
        } else {
            return plugin;
        }

    };

    $.reportes = function (container, options) {

        var plugin = this;

        /*
         * Important Components
         */
        var $container = $(container);

        var settings;
        var $table;

        var defaults = {
        };

        /*
         * Private methods
         */

        /*
         * Public methods
         */

        plugin.init = function () {

            settings = plugin.settings = $.extend({}, defaults, options);

        }

        var controlBoton = function () {
            var select = true;
            $container.find('select').filter(function () {
                if ($(this).val() == "")
                    select = false;
            });
            var checkbox = false;
            $container.find('.generado').filter(function () {
                if ($(this).prop('checked'))
                    checkbox = true;
            });
            var activar = true;
            if (checkbox && select)
                activar = false;
            $('#generar_reporte').attr('disabled', activar);
            $('#generar_pdf').attr('disabled', activar);
            $('#generar_excel').attr('disabled', activar);
        }

        var controlBotonFormatoInventario = function () {
            var almacen = true;
            var formato = true;
            var checkbox = false;
            var activar = true;

            if ($('select[name=almacen]').val() == "")
                almacen = false;
            if ($('select[name=formato]').val() == "")
                formato = false;

            $container.find('.generado').filter(function () {
                if ($(this).prop('checked'))
                    checkbox = true;
            });

            if (almacen && formato && checkbox)
                activar = false;
            $('#generar_reporte').attr('disabled', activar);
        }

        var recientes = function ($dias) {
            $.ajax({
                async: false,
                type: "GET",
                url: "/reportes/formatoinventario/getrecientes",
                dataType: "json",
                data: {dias: $dias},
                success: function (data) {
                    if (data.length != 0) {
                        for (var k in data) {
                            var tr = $('#producto-' + data[k]).closest("tr");
                            tr.find('input').prop('checked', true);
                        }
                    }
                },
            });
            revisarCheckbox();
        }

        var revisarCheckbox = function () {
            var all_checked = true;
            $container.find('.generadoc').filter(function () {
                var cat_checked = true;
                $container.find('.' + $(this).val()).filter(function () {
                    if (!$(this).prop('checked')) {
                        cat_checked = false;
                    }
                });
                if ($container.find('.' + $(this).val()).length > 0)
                    $(this).prop('checked', cat_checked);
            });

            $container.find('.generadoc').filter(function () {
                if (!$(this).prop('checked')) {
                    all_checked = false;
                }
            });
            $('#todos').prop('checked', all_checked);
        }
        var revisarCheckboxEntradasporcompra = function () {
            var proveedor = false;
            var almacen = false;
            var producto = false;
            $container.find('.proveedor').filter(function () {
                if ($(this).prop('checked'))
                    proveedor = true;
            });

            $container.find('.almacen').filter(function () {
                if ($(this).prop('checked'))
                    almacen = true;
            });

            $container.find('.producto').filter(function () {
                if ($(this).prop('checked'))
                    producto = true;
            });
            var activar = (proveedor && almacen && producto) ? false : true;
            $('#generar_reporte').attr('disabled', activar);
            $('#generar_excel').attr('disabled', activar);
            $('#generar_pdf').attr('disabled', activar);
        }

        plugin.variacioncostos = function (no_data) {
            if (no_data == 1) {
                $('form input,form select,form button[type=submit]').attr('disabled', true);
                $('#no_data').html('No existen registros para reporte')
            } else {
                $container.find('input:checkbox').on('click', function () {
                    var $this = $(this);
                    var id = $this.attr('id');
                    if (id != "todos") {
                        if ($this.val() != "on") {
                            $container.find('.' + $this.val()).filter(function () {
                                if ($this.prop('checked'))
                                    $(this).prop('checked', true);
                                else
                                    $(this).prop('checked', false);
                            });
                        }
                        revisarCheckbox();
                    } else {
                        if ($this.prop('checked')) {
                            $container.find('.generado').prop('checked', true);
                            $container.find('.generadoc').prop('checked', true);
                        } else {
                            $container.find('.generado').prop('checked', false);
                            $container.find('.generadoc').prop('checked', false);
                        }
                    }
                    controlBoton();
                });

                /*
                $('#producto_search').on('keyup', function () {
                    var busqueda = $(this).val();
                    $container.find('#reporte_table tbody tr').filter(function () {

                        var palabra = $(this).find('td').eq(1).text();
                        $(this).attr("hidden", !palabra.includes(busqueda));
                    });
                });
                */

               var table = $container.find('#reporte_table');
                $.ajax({
                    url:'/application/json/datatable/lang_es.json',
                    dataType:'json',
                    success:function(data){
                       table.dataTable({
                           "language":data,
                           "order":[],
                           "bPaginate": false
                       });
                    },
                });
                $container.find('select').on('change', function () {
                    controlBoton();
                });
            }
        }

        plugin.formatoinventario = function () {

            $('select[name=formato]').on('change', function () {
                controlBotonFormatoInventario();
            });

            $('select[name=almacen]').on('change', function () {
                controlBotonFormatoInventario();
            });

            $container.find('input:checkbox').on('click', function () {
                var $this = $(this);
                var id = $this.attr('id');
                if (id != "todos") {
                    if ($this.val() != "on") {
                        $container.find('.' + $this.val()).filter(function () {
                            if ($this.prop('checked'))
                                $(this).prop('checked', true);
                            else
                                $(this).prop('checked', false);
                        });
                    }
                    revisarCheckbox();
                } else {
                    if ($this.prop('checked')) {
                        $container.find('.generado').prop('checked', true);
                        $container.find('.generadoc').prop('checked', true);
                    } else {
                        $container.find('.generado').prop('checked', false);
                        $container.find('.generadoc').prop('checked', false);
                    }
                }
                controlBoton();
            });

            $('#producto_search').on('keyup', function () {
                var busqueda = $(this).val();
                $container.find('#reporte_table tbody tr').filter(function () {
                    var palabra = $(this).find('td').eq(1).text();
                    $(this).attr("hidden", !palabra.includes(busqueda));
                });
            });
        }

        plugin.entradasporcompras = function (mes_min, anio_min, mes_max, anio_max, existencia) {
            revisarCheckboxEntradasporcompra();
            if (existencia == 1) {
                var minDate = new Date(anio_min + '/' + mes_min + '/' + '01');
                var maxDate = new Date(anio_max + '/' + mes_max + '/' + '31');

                container.find('input[name=fecha_inicial]').datepicker({
                    startDate: minDate,
                    endDate: maxDate,
                    format: 'dd/mm/yyyy',
                });

                container.find('input[name=fecha_final]').datepicker({
                    startDate: minDate,
                    endDate: maxDate,
                    format: 'dd/mm/yyyy',
                });
            } else {
                $('input[name=fecha_inicial]').attr('disabled', true);
                $('input[name=fecha_final]').attr('disabled', true);
                $('#generar_reporte').attr('disabled', true);
                $('#generar_excel').attr('disabled', true);
                $('#generar_pdf').attr('disabled', true);
                $('#no_data').html('No existen registros de compras')
            }

            $.ajax({
                url: '/application/json/datatable/lang_es.json',
                dataType: 'json',
                success: function (data) {
                    var table = $container.find('#proveedores_table').dataTable({
                        "lengthMenu": [ 10, 25, 50, 100, 200, 500 ],
                        "language": data,
                        "order": [],
                    });

                    var table2 = $container.find('#productos_table').dataTable({
                        "lengthMenu": [ 10, 25, 50, 100, 200, 500 ],
                        "language": data,
                        "order": [],
                    });

                    var table3 = $container.find('#almacenes_table').dataTable({
                        "lengthMenu": [ 10, 25, 50, 100, 200, 500 ],
                        "language": data,
                        "order": [],
                    });

                    $('form#entradasporcomprasForm').on('submit',function(e){

                        $(table.fnGetNodes()).each(function(){
                            var checkbox = $(this).find('input');
                            if(checkbox.is(":checked")){
                                $('form#entradasporcomprasForm').append(
                                    $('<input>')
                                       .attr('type', 'hidden')
                                       .attr('name', checkbox.attr('name'))
                                       .attr('checked',true)

                                 );
                            }

                        });

                        $(table2.fnGetNodes()).each(function(){
                            var checkbox = $(this).find('input');
                            if(checkbox.is(":checked")){
                                $('form#entradasporcomprasForm').append(
                                    $('<input>')
                                       .attr('type', 'hidden')
                                       .attr('name', checkbox.attr('name'))
                                       .attr('checked',true)

                                 );
                            }

                        });

                        $(table3.fnGetNodes()).each(function(){
                            var checkbox = $(this).find('input');
                            if(checkbox.is(":checked")){
                                $('form#entradasporcomprasForm').append(
                                    $('<input>')
                                       .attr('type', 'hidden')
                                       .attr('name', checkbox.attr('name'))
                                       .attr('checked',true)

                                 );
                            }

                        });

                    });
                },
            });

            $('#proveedores_sel').on('click', function () {
                $container.find('#proveedores_table input:checkbox').prop('checked', true);
                revisarCheckboxEntradasporcompra();
            });

            $('#proveedores_des').on('click', function () {
                $container.find('#proveedores_table input:checkbox').prop('checked', false);
                revisarCheckboxEntradasporcompra();
            });

            $('#almacenes_sel').on('click', function () {
                $container.find('#almacenes_table input:checkbox').prop('checked', true);
                revisarCheckboxEntradasporcompra();
            });

            $('#almacenes_des').on('click', function () {
                $container.find('#almacenes_table input:checkbox').prop('checked', false);
                revisarCheckboxEntradasporcompra();
            });

            $('#productos_sel').on('click', function () {
                $container.find('#productos_table input:checkbox').prop('checked', true);
                revisarCheckboxEntradasporcompra();
            });

            $('#productos_des').on('click', function () {
                $container.find('#productos_table input:checkbox').prop('checked', false);
                revisarCheckboxEntradasporcompra();
            });

            $container.find('input:checkbox').on('click', function () {
                revisarCheckboxEntradasporcompra();
            });
        }

        plugin.informeacumulados = function (no_data, mes_min, anio_min, mes_max, anio_max, dia_max) {
            if (no_data == 1) {
                $('input[name=fecha_inicial]').attr('disabled', true);
                $('input[name=fecha_final]').attr('disabled', true);
                $('#generar_reporte').attr('disabled', true);
                $('#generar_excel').attr('disabled', true);
                $('#generar_pdf').attr('disabled', true);
                $('#no_data').html('No existen registros de flujo efectivo')
            }

            var minDate = new Date(anio_min + '/' + mes_min + '/' + '01');
            var maxDate = new Date(anio_max + '/' + mes_max + '/' + dia_max);

            container.find('input[name=fecha_inicial]').datepicker({
                startDate: minDate,
                endDate: maxDate,
                format: 'dd/mm/yyyy',
            });

            container.find('input[name=fecha_final]').datepicker({
                startDate: minDate,
                endDate: maxDate,
                format: 'dd/mm/yyyy',
            });
            $('input[name=fecha_inicial]').on('blur', function () {
                if ($(this).val() != "" && $('input[name=fecha_final]').val() != "")
                    $('#generar_reporte').prop("type", "button");
                else
                    $('#generar_reporte').prop("type", "submit");
            });

            $('input[name=fecha_final]').on('blur', function () {
                if ($(this).val() != "" && $('input[name=fecha_inicial]').val() != "")
                    $("#generar_reporte").prop("type", "button");
                else
                    $('#generar_reporte').prop("type", "submit");
            });

            $("#generar_reporte").on('click', function () {
                if ($(this).attr('type') == "button") {
                    var inicio = $('input[name=fecha_inicial]').val();
                    var fin = $('input[name=fecha_final]').val();
                    var table = $('#reporte_table');
                    $.ajax({
                        async: false,
                        type: "POST",
                        url: "/reportes/informeacumulados",
                        dataType: "json",
                        data: {fecha_inicial: inicio, fecha_final: fin},
                        success: function (data) {
                            if (data.length != 0) {
                                $('#reporte_table > tbody').empty();
                                for (var k in data) {
                                    table.append(data[k]);
                                }
                            }
                        },
                    });
                }
            });
        }

        /*
         * Plugin initializing
         */

        plugin.init();

    }
})(jQuery);

<|endoftext|>