<commit_before>"use strict";
/**
 * Factory which provides methods to perform on thisisoon FM API
 * transport endpoint. Which controls the playback of the current song
 * @class PlayerTransportResource
 */
angular.module("sn.fm.api").factory("PlayerTransportResource", [
    "$resource",
    "ENV",
    /**
     * @constructor
     * @param {Service} $resource
     * @param {Object}  ENV
     */
    function ($resource, ENV) {

        return $resource(
            ENV.FM_API_SERVER_ADDRESS + "player/current",
            // Default values for url parameters.
            {},
            // Hash with declaration of custom action that should
            // extend the default set of resource actions
            {
                pause: {
                    method: "POST",
                    url: SERVER_ADDRESS + "player/pause"
                },

                resume: {
                    method: "DELETE",
                    url: SERVER_ADDRESS + "player/pause"
                }
            }

        );

    }
]);
<commit_msg>missed some references to old constant value<commit_after>"use strict";
/**
 * Factory which provides methods to perform on thisisoon FM API
 * transport endpoint. Which controls the playback of the current song
 * @class PlayerTransportResource
 */
angular.module("sn.fm.api").factory("PlayerTransportResource", [
    "$resource",
    "ENV",
    /**
     * @constructor
     * @param {Service} $resource
     * @param {Object}  ENV
     */
    function ($resource, ENV) {

        return $resource(
            ENV.FM_API_SERVER_ADDRESS + "player/current",
            // Default values for url parameters.
            {},
            // Hash with declaration of custom action that should
            // extend the default set of resource actions
            {
                pause: {
                    method: "POST",
                    url: ENV.FM_API_SERVER_ADDRESS + "player/pause"
                },

                resume: {
                    method: "DELETE",
                    url: ENV.FM_API_SERVER_ADDRESS + "player/pause"
                }
            }

        );

    }
]);
<|endoftext|>


<commit_before>(function (GLOBAL) {
    var JSEpub = function (blob) {
        this.blob = blob;
    }

    GLOBAL.JSEpub = JSEpub;

    JSEpub.prototype = {
        // For mockability
        unzipperConstructor: JSUnzip,
        inflater: JSInflate,

        unzipBlob: function () {
            var unzipper = new this.unzipperConstructor(this.blob);
            if (!unzipper.isZipFile()) {
                throw new Error("Provided file was not a zip file.");
            }

            unzipper.readEntries();
            this.entries = unzipper.entries;
        },

	readEntries: function () {
            this.files = {};

            for (var i = 0, il = this.entries.length; i < il; i++) {
                var entry = this.entries[i];
                var data;

                if (entry.compressionMethod === 0) {
                    data = entry.data;
                } else if (entry.compressionMethod === 8) {
                    data = this.inflater.inflate(entry.data);
                } else {
                    throw new Error("Unknown compression method "
                                    + entry.compressionMethod
                                    + " encountered.");
                }

                if (entry.fileName === "META-INF/container.xml") {
                    this.container = data;
                } else if (entry.fileName === "mimetype") {
                    this.mimetype = data;
                } else {
                    this.files[entry.fileName] = entry.data;
                }
            }
        },

        getOpfPathFromContainer: function () {
            var doc = this.xmlDocument(this.container);
            return doc
                .getElementsByTagName("rootfile")[0]
                .getAttribute("full-path");
        },

        readOpf: function (xml) {
            var doc = this.xmlDocument(xml);

            try {
                var opf = {
                    metadata: {},
                    manifest: {},
                    spine: []
                };

                var metadataNodes = doc
                    .getElementsByTagName("metadata")[0]
                    .childNodes;

                for (var i = 0, il = metadataNodes.length; i < il; i++) {
                    var node = metadataNodes[i];
                    var key = node.nodeName.toLowerCase();
                    if (key === "#text") { continue }
                    var attrs = {};
                    for (var i2 = 0, il2 = node.attributes.length; i2 < il2; i2++) {
                        var attr = node.attributes[i2];
                        attrs[attr.name] = attr.value;
                    }
                    attrs._text = node.textContent;
                    opf.metadata[key] = attrs;
                }

                var manifestEntries = doc
                    .getElementsByTagName("manifest")[0]
                    .getElementsByTagName("item");

                for (var i = 0, il = manifestEntries.length; i < il; i++) {
                    var node = manifestEntries[i];
                    var attrs = {};
                    for (var i2 = 0, il2 = node.attributes.length; i2 < il2; i2++) {
                        var attr = node.attributes[i2];
                        if (attr.name === "id") { continue }
                        attrs[attr.name] = attr.value;
                    }
                    opf.manifest[node.getAttribute("id")] = attrs;
                }

                var spineEntries = doc
                    .getElementsByTagName("spine")[0]
                    .getElementsByTagName("itemref");

                for (var i = 0, il = spineEntries.length; i < il; i++) {
                    var node = spineEntries[i];
                    opf.spine.push(node.getAttribute("idref"));
                }

                return opf;
            } catch(e) {
                // The DOMParser will not throw an error if the XML is invalid.
                // It will return an XML error document, and it will be in
                // here:
                // doc.childNodes[1].childNodes[0].nodeValue
                throw(e)
            }
        },

        validate: function () {
            if (this.container === undefined) {
                throw new Error("META-INF/container.xml file not found.");
            }

            if (this.mimetype === undefined) {
                throw new Error("Mimetype file not found.");
            }

            if (this.mimetype !== "application/epub+zip") {
                throw new Error("Incorrect mimetype " + this.mimetype);
            }
        },

        xmlDocument: function (xml) {
            return new DOMParser().parseFromString(xml, "text/xml");
        }
    }
}(this));<commit_msg>Using nodeType to detect text nodes.<commit_after>(function (GLOBAL) {
    var JSEpub = function (blob) {
        this.blob = blob;
    }

    GLOBAL.JSEpub = JSEpub;

    JSEpub.prototype = {
        // For mockability
        unzipperConstructor: JSUnzip,
        inflater: JSInflate,

        unzipBlob: function () {
            var unzipper = new this.unzipperConstructor(this.blob);
            if (!unzipper.isZipFile()) {
                throw new Error("Provided file was not a zip file.");
            }

            unzipper.readEntries();
            this.entries = unzipper.entries;
        },

	readEntries: function () {
            this.files = {};

            for (var i = 0, il = this.entries.length; i < il; i++) {
                var entry = this.entries[i];
                var data;

                if (entry.compressionMethod === 0) {
                    data = entry.data;
                } else if (entry.compressionMethod === 8) {
                    data = this.inflater.inflate(entry.data);
                } else {
                    throw new Error("Unknown compression method "
                                    + entry.compressionMethod
                                    + " encountered.");
                }

                if (entry.fileName === "META-INF/container.xml") {
                    this.container = data;
                } else if (entry.fileName === "mimetype") {
                    this.mimetype = data;
                } else {
                    this.files[entry.fileName] = entry.data;
                }
            }
        },

        getOpfPathFromContainer: function () {
            var doc = this.xmlDocument(this.container);
            return doc
                .getElementsByTagName("rootfile")[0]
                .getAttribute("full-path");
        },

        readOpf: function (xml) {
            var doc = this.xmlDocument(xml);

            try {
                var opf = {
                    metadata: {},
                    manifest: {},
                    spine: []
                };

                var metadataNodes = doc
                    .getElementsByTagName("metadata")[0]
                    .childNodes;

                for (var i = 0, il = metadataNodes.length; i < il; i++) {
                    var node = metadataNodes[i];
                    // Skip text nodes (whitespace)
                    if (node.nodeType === 3) { continue }

                    var attrs = {};
                    for (var i2 = 0, il2 = node.attributes.length; i2 < il2; i2++) {
                        var attr = node.attributes[i2];
                        attrs[attr.name] = attr.value;
                    }
                    attrs._text = node.textContent;
                    opf.metadata[node.nodeName] = attrs;
                }

                var manifestEntries = doc
                    .getElementsByTagName("manifest")[0]
                    .getElementsByTagName("item");

                for (var i = 0, il = manifestEntries.length; i < il; i++) {
                    var node = manifestEntries[i];
                    var attrs = {};
                    for (var i2 = 0, il2 = node.attributes.length; i2 < il2; i2++) {
                        var attr = node.attributes[i2];
                        if (attr.name === "id") { continue }
                        attrs[attr.name] = attr.value;
                    }
                    opf.manifest[node.getAttribute("id")] = attrs;
                }

                var spineEntries = doc
                    .getElementsByTagName("spine")[0]
                    .getElementsByTagName("itemref");

                for (var i = 0, il = spineEntries.length; i < il; i++) {
                    var node = spineEntries[i];
                    opf.spine.push(node.getAttribute("idref"));
                }

                return opf;
            } catch(e) {
                // The DOMParser will not throw an error if the XML is invalid.
                // It will return an XML error document, and it will be in
                // here:
                // doc.childNodes[1].childNodes[0].nodeValue
                throw(e)
            }
        },

        validate: function () {
            if (this.container === undefined) {
                throw new Error("META-INF/container.xml file not found.");
            }

            if (this.mimetype === undefined) {
                throw new Error("Mimetype file not found.");
            }

            if (this.mimetype !== "application/epub+zip") {
                throw new Error("Incorrect mimetype " + this.mimetype);
            }
        },

        xmlDocument: function (xml) {
            return new DOMParser().parseFromString(xml, "text/xml");
        }
    }
}(this));<|endoftext|>


<commit_before>define(['app','linqjs', 'utilities/realm','utilities/workflows'], function(app,Enumerable) {
  'use strict';
  app.factory('guid', function() {
  	function S4() {
  		return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  	}
  	return function() {
  		return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4()).toUpperCase();
  	};
  });
  app.factory("htmlUtility", function() {
    return {
      encode: function(srcText) {
        return $('<div/>').text(srcText).html();
      }
    };
  });

  app.factory('Enumerable', [function() {

		return Enumerable;
	}]);

	app.factory('linqjs', [function() {
		return Enumerable;
	}]);
  app.factory('Thesaurus', ['linqjs', function(Enumerable) {
      return {
          buildTree: function(terms) {
              var oTerms = [];
              var oTermsMap = {};

              Enumerable.from(terms).forEach(function(value) {
                  var oTerm = {
                      identifier: value.identifier,
                      title: value.title,
                      description: value.description
                  }

                  oTerms.push(oTerm);
                  oTermsMap[oTerm.identifier] = oTerm;
              });

              for (var i = 0; i < oTerms.length; ++i) {
                  var oRefTerm = terms[i];
                  var oBroader = oTerms[i];

                  if (oRefTerm.narrowerTerms && oRefTerm.narrowerTerms.length > 0) {
                      angular.forEach(oRefTerm.narrowerTerms, function(identifier) {
                          var oNarrower = oTermsMap[identifier];

                          if (oNarrower) {
                              oBroader.narrowerTerms = oBroader.narrowerTerms || [];
                              oNarrower.broaderTerms = oNarrower.broaderTerms || [];

                              oBroader.narrowerTerms.push(oNarrower);
                              oNarrower.broaderTerms.push(oBroader);
                          }
                      });
                  }
              }

              return Enumerable.from(oTerms).where("o=>!o.broaderTerms").toArray();
          }
      }
  }]);
  app.factory('underscore', [function() {
  return _;
}]);
  app.factory('editFormUtility', ["IStorage", "workflows", "$q", "$route", "realm", function(storage, workflows, $q, $route, realm) {

    var schemasWorkflowTypes = {

      "organization"              : { name: "publishReferenceRecord", version: undefined },
      "undbActor"                 : { name: "publishReferenceRecord", version: undefined },
      "event"                     : { name: "publishReferenceRecord", version: undefined },
      "undbBizBioPledge"          : { name: "publishReferenceRecord", version: undefined },
      "undbParty"                 : { name: "publishReferenceRecord", version:  undefined },

    };

    var _self = {

      //==================================
      //
      //==================================
      load: function(identifier, expectedSchema) {

        return storage.drafts.get(identifier, {
          info: ""
        }).then(
          function(success) {
            return success;
          },
          function(error) {
            if (error.status == 404)
              return storage.documents.get(identifier, {
                info: ""
              });
            throw error;
          }).then(
          function(success) {
            var info = success.data;

            if (expectedSchema && info.type != expectedSchema)
              throw {
                data: {
                  error: "Invalid schema type"
                },
                status: "badSchema"
              };

            var hasDraft = !!info.workingDocumentCreatedOn;
            var securityPromise = hasDraft ?
              storage.drafts.security.canUpdate(info.identifier, info.type) :
              storage.drafts.security.canCreate(info.identifier, info.type);

            return securityPromise.then(
              function(isAllowed) {
                if (!isAllowed)
                  throw {
                    data: {
                      error: "Not allowed"
                    },
                    status: "notAuthorized"
                  };

                var documentPromise = hasDraft ?
                  storage.drafts.get(identifier) :
                  storage.documents.get(identifier);

                return documentPromise.then(
                  function(success) {
                    return success.data;
                  });
              });
          });
      },

      //==================================
      //
      //==================================
      draftExists: function(identifier) {

        return storage.drafts.get(identifier, {
          info: ""
        }).then(function() {
          return true;
        }, function(error) {
          if (error.status == 404)
            return false;
          throw error;
        });
      },

      //==================================
      //
      //==================================
      saveDraft: function(document) {

        var identifier = document.header.identifier;
        var metadata = {};

        if (document.government)
          metadata.government = document.government.identifier;

        return _self.draftExists(identifier).then(
          function(hasDraft) {

            var securityPromise = hasDraft ?
              storage.drafts.security.canUpdate(identifier, document.header.schema, metadata) :
              storage.drafts.security.canCreate(identifier, document.header.schema, metadata);

            return securityPromise.then(
              function(isAllowed) {
                if (!isAllowed)
                  throw {
                    error: "Not authorized to save draft"
                  };

                return storage.drafts.put(identifier, document);
              });
          });
      },

      //==================================
      //
      //==================================
      documentExists: function(identifier) {

        return storage.documents.get(identifier).then(function() {
          return true;
        }, function(error) {
          if (error.status == 404)
            return false;
          throw error;
        });
      },

      //==================================
      //
      //==================================
      canPublish: function(document) {

        var identifier = document.header.identifier;
        var schema = document.header.schema;
        var metadata = {};

        if (document.government)
          metadata.government = document.government.identifier;

        // Check if document exists

        return _self.documentExists(identifier).then(function(exists) {

          // Check user security on document

          var qCanWrite = exists ? storage.documents.security.canUpdate(identifier, schema, metadata) :
            storage.documents.security.canCreate(identifier, schema, metadata);

          return qCanWrite;

        });
      },

      //==================================
      //
      //==================================
      publish: function(document) {

        var identifier = document.header.identifier;
        var schema = document.header.schema;
        var metadata = {};

        if (document.government)
          metadata.government = document.government.identifier;

        // Check if document exists

        return _self.documentExists(identifier).then(function(exists) {

          // Check user security on document

          var qCanWrite = exists ? storage.documents.security.canUpdate(identifier, schema, metadata) :
            storage.documents.security.canCreate(identifier, schema, metadata);

          return qCanWrite;

        }).then(function(canWrite) {

          if (!canWrite)
            throw {
              error: "Not allowed"
            };

          //Save document
          var processRequest;
          if ($route.current.params.workflowId) {
            // if the user is editing a locked record, remove the lock, update draft,
            // lock the draft and then update the workflow status.
            var metadata = {};
            processRequest = storage.drafts.locks.get(document.header.identifier, {
                lockID: ''
              })
              .then(function(lockInfo) {
                return storage.drafts.locks.delete(document.header.identifier, lockInfo.data[0].lockID)
                  .then(function() {
                    return storage.drafts.put(document.header.identifier, document);
                  })
                  .then(function(draftInfo) {
                    return storage.drafts.locks.put(document.header.identifier, {
                      lockID: lockInfo.data[0].lockID
                    });
                  }).then(function(draftInfo) {
                    console.log(draftInfo);

                  });
              })
              .then(function(data) {
                return workflows.updateActivity($route.current.params.workflowId, 'publishRecord', {
                  action: 'approve'
                })
              });
          } else {
            processRequest = storage.drafts.put(identifier, document).then(function(draftInfo) {
              return createWorkflow(draftInfo); // return workflow info
            }); //editFormUtility.publish(document);
          }
          return $q.when(processRequest);
        });
      },

      //==================================
      //
      //==================================
      publishRequest: function(document) {

        var identifier = document.header.identifier;
        var schema = document.header.schema;
        var metadata = {};

        if (document.government)
          metadata.government = document.government.identifier;

        // Check if doc & draft exists

        return _self.draftExists(identifier).then(function(exists) {

          // Check user security on drafts

          var qCanWrite = exists ?
            storage.drafts.security.canUpdate(identifier, schema, metadata) :
            storage.drafts.security.canCreate(identifier, schema, metadata);

          return qCanWrite;

        }).then(function(canWrite) {

          if (!canWrite)
            throw {
              error: "Not allowed"
            };

          //Save draft
          return storage.drafts.put(identifier, document);

        }).then(function(draftInfo) {
          return createWorkflow(draftInfo); // return workflow info
        });
      }
    };

    function createWorkflow(draftInfo, additionalInfo) {
      var type = schemasWorkflowTypes[draftInfo.type];

      if (!type)
        throw "No workflow type defined for this record type: " + draftInfo.type;

      var workflowData = {
        "realm": realm,
        "documentID": draftInfo.documentID,
        "identifier": draftInfo.identifier,
        "title": draftInfo.workingDocumentTitle,
        "abstract": draftInfo.workingDocumentSummary,
        "metadata": draftInfo.workingDocumentMetadata,
        "additionalInfo": additionalInfo
      };

      return workflows.create(type.name, type.version, workflowData); // return workflow info
    }

    return _self;

  }]);

});
<commit_msg>return docs realm<commit_after>define(['app','linqjs', 'utilities/realm','utilities/workflows','utilities/km-storage'], function(app,Enumerable) {
  'use strict';
  app.factory('guid', function() {
  	function S4() {
  		return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  	}
  	return function() {
  		return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4()).toUpperCase();
  	};
  });
  app.factory("htmlUtility", function() {
    return {
      encode: function(srcText) {
        return $('<div/>').text(srcText).html();
      }
    };
  });

  app.factory('Enumerable', [function() {

		return Enumerable;
	}]);

	app.factory('linqjs', [function() {
		return Enumerable;
	}]);
  app.factory('Thesaurus', ['linqjs', function(Enumerable) {
      return {
          buildTree: function(terms) {
              var oTerms = [];
              var oTermsMap = {};

              Enumerable.from(terms).forEach(function(value) {
                  var oTerm = {
                      identifier: value.identifier,
                      title: value.title,
                      description: value.description
                  }

                  oTerms.push(oTerm);
                  oTermsMap[oTerm.identifier] = oTerm;
              });

              for (var i = 0; i < oTerms.length; ++i) {
                  var oRefTerm = terms[i];
                  var oBroader = oTerms[i];

                  if (oRefTerm.narrowerTerms && oRefTerm.narrowerTerms.length > 0) {
                      angular.forEach(oRefTerm.narrowerTerms, function(identifier) {
                          var oNarrower = oTermsMap[identifier];

                          if (oNarrower) {
                              oBroader.narrowerTerms = oBroader.narrowerTerms || [];
                              oNarrower.broaderTerms = oNarrower.broaderTerms || [];

                              oBroader.narrowerTerms.push(oNarrower);
                              oNarrower.broaderTerms.push(oBroader);
                          }
                      });
                  }
              }

              return Enumerable.from(oTerms).where("o=>!o.broaderTerms").toArray();
          }
      }
  }]);
  app.factory('underscore', [function() {
  return _;
}]);
  app.factory('editFormUtility', ["IStorage", "workflows", "$q", "$route", "realm", function(storage, workflows, $q, $route, realm) {

    var schemasWorkflowTypes = {

      "organization"              : { name: "publishReferenceRecord", version: undefined },
      "undbActor"                 : { name: "publishReferenceRecord", version: undefined },
      "event"                     : { name: "publishReferenceRecord", version: undefined },
      "undbBizBioPledge"          : { name: "publishReferenceRecord", version: undefined },
      "undbParty"                 : { name: "publishReferenceRecord", version:  undefined },

    };

    var _self = {
        //==================================
        //
        //==================================
        getRealm: function(identifier) {

          return storage.drafts.get(identifier, {
            info: ""
          }).then(
            function(success) {
              return success;
            },
            function(error) {
              if (error.status == 404)
                return storage.documents.get(identifier, {
                  info: ""
                });
              throw error;
            }).then(
            function(success) {
              var info = success.data;
              if(!info.Realm) return false;
              return info.Realm;

          },
          function(error) {
              if (error.status == 404)
                return false;
              throw error;
          });
        },
      //==================================
      //
      //==================================
      load: function(identifier, expectedSchema) {

        return storage.drafts.get(identifier, {
          info: ""
        }).then(
          function(success) {
            return success;
          },
          function(error) {
            if (error.status == 404)
              return storage.documents.get(identifier, {
                info: ""
              });
            throw error;
          }).then(
          function(success) {
            var info = success.data;

            if (expectedSchema && info.type != expectedSchema)
              throw {
                data: {
                  error: "Invalid schema type"
                },
                status: "badSchema"
              };

            var hasDraft = !!info.workingDocumentCreatedOn;
            var securityPromise = hasDraft ?
              storage.drafts.security.canUpdate(info.identifier, info.type) :
              storage.drafts.security.canCreate(info.identifier, info.type);

            return securityPromise.then(
              function(isAllowed) {
                if (!isAllowed)
                  throw {
                    data: {
                      error: "Not allowed"
                    },
                    status: "notAuthorized"
                  };

                var documentPromise = hasDraft ?
                  storage.drafts.get(identifier) :
                  storage.documents.get(identifier);

                return documentPromise.then(
                  function(success) {
                    return success.data;
                  });
              });
          });
      },

      //==================================
      //
      //==================================
      draftExists: function(identifier) {

        return storage.drafts.get(identifier, {
          info: ""
        }).then(function() {
          return true;
        }, function(error) {
          if (error.status == 404)
            return false;
          throw error;
        });
      },

      //==================================
      //
      //==================================
      saveDraft: function(document) {

        var identifier = document.header.identifier;
        var metadata = {};

        if (document.government)
          metadata.government = document.government.identifier;

        return _self.draftExists(identifier).then(
          function(hasDraft) {

            var securityPromise = hasDraft ?
              storage.drafts.security.canUpdate(identifier, document.header.schema, metadata) :
              storage.drafts.security.canCreate(identifier, document.header.schema, metadata);

            return securityPromise.then(
              function(isAllowed) {
                if (!isAllowed)
                  throw {
                    error: "Not authorized to save draft"
                  };

                return storage.drafts.put(identifier, document);
              });
          });
      },

      //==================================
      //
      //==================================
      documentExists: function(identifier) {

        return storage.documents.get(identifier).then(function() {
          return true;
        }, function(error) {
          if (error.status == 404)
            return false;
          throw error;
        });
      },

      //==================================
      //
      //==================================
      canPublish: function(document) {

        var identifier = document.header.identifier;
        var schema = document.header.schema;
        var metadata = {};

        if (document.government)
          metadata.government = document.government.identifier;

        // Check if document exists

        return _self.documentExists(identifier).then(function(exists) {

          // Check user security on document

          var qCanWrite = exists ? storage.documents.security.canUpdate(identifier, schema, metadata) :
            storage.documents.security.canCreate(identifier, schema, metadata);

          return qCanWrite;

        });
      },

      //==================================
      //
      //==================================
      publish: function(document) {

        var identifier = document.header.identifier;
        var schema = document.header.schema;
        var metadata = {};

        if (document.government)
          metadata.government = document.government.identifier;

        // Check if document exists

        return _self.documentExists(identifier).then(function(exists) {

          // Check user security on document

          var qCanWrite = exists ? storage.documents.security.canUpdate(identifier, schema, metadata) :
            storage.documents.security.canCreate(identifier, schema, metadata);

          return qCanWrite;

        }).then(function(canWrite) {

          if (!canWrite)
            throw {
              error: "Not allowed"
            };

          //Save document
          var processRequest;
          if ($route.current.params.workflowId) {
            // if the user is editing a locked record, remove the lock, update draft,
            // lock the draft and then update the workflow status.
            var metadata = {};
            processRequest = storage.drafts.locks.get(document.header.identifier, {
                lockID: ''
              })
              .then(function(lockInfo) {
                return storage.drafts.locks.delete(document.header.identifier, lockInfo.data[0].lockID)
                  .then(function() {
                    return storage.drafts.put(document.header.identifier, document);
                  })
                  .then(function(draftInfo) {
                    return storage.drafts.locks.put(document.header.identifier, {
                      lockID: lockInfo.data[0].lockID
                    });
                  }).then(function(draftInfo) {
                    console.log(draftInfo);

                  });
              })
              .then(function(data) {
                return workflows.updateActivity($route.current.params.workflowId, 'publishRecord', {
                  action: 'approve'
                })
              });
          } else {
            processRequest = storage.drafts.put(identifier, document).then(function(draftInfo) {
              return createWorkflow(draftInfo); // return workflow info
            }); //editFormUtility.publish(document);
          }
          return $q.when(processRequest);
        });
      },

      //==================================
      //
      //==================================
      publishRequest: function(document) {

        var identifier = document.header.identifier;
        var schema = document.header.schema;
        var metadata = {};

        if (document.government)
          metadata.government = document.government.identifier;

        // Check if doc & draft exists

        return _self.draftExists(identifier).then(function(exists) {

          // Check user security on drafts

          var qCanWrite = exists ?
            storage.drafts.security.canUpdate(identifier, schema, metadata) :
            storage.drafts.security.canCreate(identifier, schema, metadata);

          return qCanWrite;

        }).then(function(canWrite) {

          if (!canWrite)
            throw {
              error: "Not allowed"
            };

          //Save draft
          return storage.drafts.put(identifier, document);

        }).then(function(draftInfo) {
          return createWorkflow(draftInfo); // return workflow info
        });
      }
    };

    function createWorkflow(draftInfo, additionalInfo) {
      var type = schemasWorkflowTypes[draftInfo.type];

      if (!type)
        throw "No workflow type defined for this record type: " + draftInfo.type;

      var workflowData = {
        "realm": realm,
        "documentID": draftInfo.documentID,
        "identifier": draftInfo.identifier,
        "title": draftInfo.workingDocumentTitle,
        "abstract": draftInfo.workingDocumentSummary,
        "metadata": draftInfo.workingDocumentMetadata,
        "additionalInfo": additionalInfo
      };

      return workflows.create(type.name, type.version, workflowData); // return workflow info
    }

    return _self;

  }]);

});
<|endoftext|>


<commit_before>Kwf.enableOnReadyConsoleProfile = false;

/* fn: fn,
 * scope: scope,
 * options: options || {},
 * type: [jquery|ext],
 * num: unique number, //used to mark in initDone
 * selector: selector, // null if onContentReady
 * */
Kwf._readyHandlers = [];

if (!Kwf.isApp) {
    $(document).ready(function() {
        if (!document.body) {
            //this happens if a redirect by changing location in JS is done
            //in that case no contentReady needs to be called
            return;
        }
        var t = Kwf.Utils.BenchmarkBox.now();
        if (Kwf.enableOnReadyConsoleProfile) console.profile("callOnContentReady body");
        Kwf._skipDeferred = true;
        Kwf.callOnContentReady(document.body, { action: 'render' });
        delete Kwf._skipDeferred;
        if (Kwf.enableOnReadyConsoleProfile) console.profileEnd();
        Kwf.Utils.BenchmarkBox.time('time', Kwf.Utils.BenchmarkBox.now()-t);
        Kwf.Utils.BenchmarkBox.create({
            counters: Kwf._onReadyStats,
            type: 'onReady'
        });
        (function() {
            Kwf._deferredStart = Kwf.Utils.BenchmarkBox.now();
            if (Kwf.enableOnReadyConsoleProfile) console.profile("callOnContentReady body deferred");
            Kwf._skipDeferred = false;
            Kwf.callOnContentReady(document.body, { action: 'render' });
            delete Kwf._skipDeferred;
        }).defer(10);

        Ext.fly(window).on('resize', function() {
            Kwf.callOnContentReady(document.body, { action: 'widthChange' } );
        }, this, { buffer: 100 });
    });
}

Kwf._skipDeferred;
Kwf._deferredStart = null;
Kwf._onReadyIsCalling = false;
Kwf._onReadyCallQueue = [];
Kwf._onReadyElQueue = [];
Kwf._elQueueNum = 0;
Kwf._onReadyElSortCache = {};
Kwf._elCacheBySelector = {};

Kwf._addReadyHandler = function(type, onAction, selector, fn, options)
{
    Kwf._readyHandlers.push({
        selector: selector,
        fn: fn,
        options: options || {},
        num: Kwf._readyHandlers.length, //unique number
        type: type,
        onAction: onAction
    });
};

/**
 * @param element the added/changed dom element
 * @param options newRender (bool): if new elements have been added to the dom or just visiblity/width changed
 */
Kwf.callOnContentReady = function(renderedEl, options)
{
    Kwf.Utils.BenchmarkBox.count('callOnContentReady');
    if (!options) options = {};
    if (options.newRender) {
        delete options.newRender;
        options.action = 'render';
    }
    if (!options.action) {
        if (console && console.warn) console.warn('Please set option action on callOnContentReady');
        options.action = 'render';
    }
    if (!renderedEl) {
        if (console && console && console.warn) console.warn('Please pass element argument on callOnContentReady');
        renderedEl = document.body;
    }
    if (Ext.Element && renderedEl instanceof Ext.Element) renderedEl = renderedEl.dom;
    if (jQuery && renderedEl instanceof jQuery) renderedEl = renderedEl.get();

    Kwf._onReadyCallQueue.push({
        renderedEl: renderedEl,
        options: options
    });

    if (options.action == 'render') {
        //new elements rendered, clear cache
        Kwf._elCacheBySelector = {};

        var t = Kwf.Utils.BenchmarkBox.now();
        var html = renderedEl.innerHTML;
        Kwf.Utils.BenchmarkBox.time('innerHTML', Kwf.Utils.BenchmarkBox.now()-t);
    }

    var addToQueue = function(onActions) {

        for (var i = 0; i < Kwf._readyHandlers.length; i++) {
            var hndl = Kwf._readyHandlers[i];

            //Kwf._skipDeferred gets set before callOnContentReady(body)
            //can not be part of options as it would be missing in recursive calls
            if (Kwf._skipDeferred === true) {
                if (hndl.options.defer) {
                    continue;
                }
            } else if (Kwf._skipDeferred === false) {
                if (!hndl.options.defer) {
                    continue;
                }
            }
            if (onActions.indexOf(hndl.onAction) != -1) {

                if (options.action == 'render' && !Kwf._elCacheBySelector[hndl.selector]) {
                    var t = Kwf.Utils.BenchmarkBox.now();
                    var m = hndl.selector.match(/^[a-z]*\.([a-z]+)/i)
                    if (m) {
                        //do a stupid text search on the selector, using that we can skip query for many selectors that don't exist in the current el
                        if (html.indexOf(m[1]) == -1) {
                            Kwf._elCacheBySelector[hndl.selector] = [];
                        }
                    }
                    Kwf.Utils.BenchmarkBox.time('checkInnerHtml', Kwf.Utils.BenchmarkBox.now()-t);
                }

                if (Kwf._elCacheBySelector[hndl.selector]) {
                    if (Kwf._elCacheBySelector[hndl.selector].length === 0) {
                        //Optimize: if we never got element by that selector, skip query
                        Kwf.Utils.BenchmarkBox.count('querySkip');
                        continue;
                    }
                    Kwf.Utils.BenchmarkBox.count('queryCache');
                    var els = [];
                    for (var j=0; j<Kwf._elCacheBySelector[hndl.selector].length; j++) {
                        if (renderedEl == document.body || $.contains(renderedEl, Kwf._elCacheBySelector[hndl.selector][j])) {
                            els.push(Kwf._elCacheBySelector[hndl.selector][j]);
                        }
                    }
                } else {
                    var t = Kwf.Utils.BenchmarkBox.now();
                    var els = $.makeArray($(renderedEl).find(hndl.selector));
                    Kwf.Utils.BenchmarkBox.time('query', Kwf.Utils.BenchmarkBox.now() - t);
                    if (options.action == 'render' && renderedEl == document.body) {
                        Kwf._elCacheBySelector[hndl.selector] = els;
                    }
                }
                for (var j = 0; j< els.length; ++j) {
                    var alreadyInQueue = false;
                    Kwf._onReadyElQueue.each(function(q) {
                        if (q.num == hndl.num && q.el === els[j]) {
                            alreadyInQueue = true;
                            return true;
                        }
                    }, this);
                    if (!alreadyInQueue) {
                        var parentsCount = 0;
                        var n = els[j];
                        while (n = n.parentNode) {
                            parentsCount++;
                        }
                        Kwf.Utils.BenchmarkBox.count('readyEl');
                        Kwf._onReadyElQueue.push({
                            el: els[j],
                            fn: hndl.fn,
                            options: hndl.options,
                            num: hndl.num,
                            type: hndl.type,
                            onAction: hndl.onAction,
                            selector: hndl.selector,
                            queueNum: Kwf._elQueueNum++,
                            priority: hndl.options.priority || 0,
                            parentsCount: parentsCount
                        });
                    }
                }
            }
        }
    };

    if (options.action == 'render') {
        addToQueue(['render', 'show', 'widthChange']);
    } else if (options.action == 'show') {
        addToQueue(['show', 'widthChange']);
    } else if (options.action == 'hide') {
        addToQueue(['hide']);
    } else if (options.action == 'widthChange') {
        addToQueue(['widthChange']);
    }

    var t = Kwf.Utils.BenchmarkBox.now();
    Kwf._onReadyElQueue.sort(function sortOnReadyElQueue(a, b) {
        if (a.priority != b.priority) {
            return a.priority - b.priority;
        } else {
            if (a.parentsCount != b.parentsCount) {
                return a.parentsCount - b.parentsCount;
            } else {
                return 1;
            }
        }
    });
    Kwf.Utils.BenchmarkBox.time('sort', Kwf.Utils.BenchmarkBox.now() - t);

    if (Kwf._onReadyIsCalling) {
        return;
    }

    Kwf._onReadyIsCalling = true;

    while (Kwf._onReadyCallQueue.length) {
        var queueEntry = Kwf._onReadyCallQueue.pop();

        Kwf._readyHandlers.sort(function(a, b) {
            return (a.options.priority || 0) - (b.options.priority || 0);
        });
        for (var i = 0; i < Kwf._readyHandlers.length; i++) {
            var hndl = Kwf._readyHandlers[i];
            if (hndl.selector == null) {
                var t = Kwf.Utils.BenchmarkBox.now();
                hndl.fn.call(hndl.options.scope || window, queueEntry.renderedEl, queueEntry.options);
                Kwf.Utils.BenchmarkBox.time('onContentReady', Kwf.Utils.BenchmarkBox.now()-t);
            }
        }
    }

    function _callQueueFn(timerName, queueEntry, config)
    {
        var t = Kwf.Utils.BenchmarkBox.now();
        var el = queueEntry.el;
        el = queueEntry.type == 'ext' ? Ext.get(el) : $(el);
        queueEntry.fn.call(queueEntry.options.scope || window, el, config);
        Kwf.Utils.BenchmarkBox.time(timerName, Kwf.Utils.BenchmarkBox.now()-t);
        var fnName = queueEntry.fn.name;
        if (!fnName) {
            fnName = 'unknown';
        }
        Kwf.Utils.BenchmarkBox.time('fn: '+fnName, Kwf.Utils.BenchmarkBox.now()-t);
    };
    function _processOnReadyElQueueEntry()
    {
        var queueEntry = Kwf._onReadyElQueue.shift();
        var el = queueEntry.el;
        if (queueEntry.onAction == 'render') {
            if (queueEntry.options.checkVisibility && Ext.fly(el).getWidth() == 0) {
                return;
            }
            if (!el.initDone) el.initDone = {};
            if (el.initDone[queueEntry.num]) {
                return;
            }
            el.initDone[queueEntry.num] = true;
            var config = {};
            var configEl = $(el).find('> input[type="hidden"]')
            if (configEl.length) {
                try {
                    var v = configEl.get(0).value;
                    if (v.substr(0, 1) == '{') {
                        config = $.parseJSON(v);
                    }
                } catch (err) {}
            }
            _callQueueFn('onRender', queueEntry, config);
        } else {
            if (queueEntry.onAction == 'show') {
                if (Ext.fly(el).getWidth() > 0) {
                    _callQueueFn('onShow', queueEntry);
                }
            } else if (queueEntry.onAction == 'hide') {
                if (Ext.fly(el).getWidth() == 0) {
                    _callQueueFn('onHide', queueEntry);
                }
            } else if (queueEntry.onAction == 'widthChange') {
                _callQueueFn('onWidthChange', queueEntry);
            }

        }
    }

    if (Kwf._skipDeferred === false) {
        var processNext = function processNext() {
            Kwf.Utils.BenchmarkBox.count('chunks');
            var t = Kwf.Utils.BenchmarkBox.now();
            while (Kwf._onReadyElQueue.length && Kwf.Utils.BenchmarkBox.now()-t < 50) {
                _processOnReadyElQueueEntry();
            }
            if (Kwf._onReadyElQueue.length) {
                processNext.defer(this, 1);
            } else {
                Kwf._onReadyIsCalling = false;
                Kwf.Utils.BenchmarkBox.time('time', Kwf.Utils.BenchmarkBox.now()-Kwf._deferredStart);
                if (Kwf.enableOnReadyConsoleProfile) console.profileEnd();
                Kwf.Utils.BenchmarkBox.create({
                    counters: Kwf._onReadyStats,
                    type: 'onReady defer'
                });
            }
        };
        processNext();
    } else {
        while (Kwf._onReadyElQueue.length) {
            _processOnReadyElQueueEntry();
        }
        Kwf._onReadyIsCalling = false;
    }

};

/**
 * Register a function that will be called when content is loaded or shown
 * @param callback function (passed arguments: el, options (newRender=bool))
 * @param options supported are: priority (integer, higher number means it's called after all with lower number, default 0)
 */
Kwf.onContentReady = function(fn, options) {
    if (arguments.length == 3) {
        var scope = arguments[1];
        var options = arguments[2];
        options.scope = scope;
    }
    Kwf._readyHandlers.push({
        selector: null,
        fn: fn,
        options: options || {}
    });
};
<commit_msg>use jquery to detect visiblity<commit_after>Kwf.enableOnReadyConsoleProfile = false;

/* fn: fn,
 * scope: scope,
 * options: options || {},
 * type: [jquery|ext],
 * num: unique number, //used to mark in initDone
 * selector: selector, // null if onContentReady
 * */
Kwf._readyHandlers = [];

if (!Kwf.isApp) {
    $(document).ready(function() {
        if (!document.body) {
            //this happens if a redirect by changing location in JS is done
            //in that case no contentReady needs to be called
            return;
        }
        var t = Kwf.Utils.BenchmarkBox.now();
        if (Kwf.enableOnReadyConsoleProfile) console.profile("callOnContentReady body");
        Kwf._skipDeferred = true;
        Kwf.callOnContentReady(document.body, { action: 'render' });
        delete Kwf._skipDeferred;
        if (Kwf.enableOnReadyConsoleProfile) console.profileEnd();
        Kwf.Utils.BenchmarkBox.time('time', Kwf.Utils.BenchmarkBox.now()-t);
        Kwf.Utils.BenchmarkBox.create({
            counters: Kwf._onReadyStats,
            type: 'onReady'
        });
        (function() {
            Kwf._deferredStart = Kwf.Utils.BenchmarkBox.now();
            if (Kwf.enableOnReadyConsoleProfile) console.profile("callOnContentReady body deferred");
            Kwf._skipDeferred = false;
            Kwf.callOnContentReady(document.body, { action: 'render' });
            delete Kwf._skipDeferred;
        }).defer(10);

        Ext.fly(window).on('resize', function() {
            Kwf.callOnContentReady(document.body, { action: 'widthChange' } );
        }, this, { buffer: 100 });
    });
}

Kwf._skipDeferred;
Kwf._deferredStart = null;
Kwf._onReadyIsCalling = false;
Kwf._onReadyCallQueue = [];
Kwf._onReadyElQueue = [];
Kwf._elQueueNum = 0;
Kwf._onReadyElSortCache = {};
Kwf._elCacheBySelector = {};

Kwf._addReadyHandler = function(type, onAction, selector, fn, options)
{
    Kwf._readyHandlers.push({
        selector: selector,
        fn: fn,
        options: options || {},
        num: Kwf._readyHandlers.length, //unique number
        type: type,
        onAction: onAction
    });
};

/**
 * @param element the added/changed dom element
 * @param options newRender (bool): if new elements have been added to the dom or just visiblity/width changed
 */
Kwf.callOnContentReady = function(renderedEl, options)
{
    Kwf.Utils.BenchmarkBox.count('callOnContentReady');
    if (!options) options = {};
    if (options.newRender) {
        delete options.newRender;
        options.action = 'render';
    }
    if (!options.action) {
        if (console && console.warn) console.warn('Please set option action on callOnContentReady');
        options.action = 'render';
    }
    if (!renderedEl) {
        if (console && console && console.warn) console.warn('Please pass element argument on callOnContentReady');
        renderedEl = document.body;
    }
    if (Ext.Element && renderedEl instanceof Ext.Element) renderedEl = renderedEl.dom;
    if (jQuery && renderedEl instanceof jQuery) renderedEl = renderedEl.get();

    Kwf._onReadyCallQueue.push({
        renderedEl: renderedEl,
        options: options
    });

    if (options.action == 'render') {
        //new elements rendered, clear cache
        Kwf._elCacheBySelector = {};

        var t = Kwf.Utils.BenchmarkBox.now();
        var html = renderedEl.innerHTML;
        Kwf.Utils.BenchmarkBox.time('innerHTML', Kwf.Utils.BenchmarkBox.now()-t);
    }

    var addToQueue = function(onActions) {

        for (var i = 0; i < Kwf._readyHandlers.length; i++) {
            var hndl = Kwf._readyHandlers[i];

            //Kwf._skipDeferred gets set before callOnContentReady(body)
            //can not be part of options as it would be missing in recursive calls
            if (Kwf._skipDeferred === true) {
                if (hndl.options.defer) {
                    continue;
                }
            } else if (Kwf._skipDeferred === false) {
                if (!hndl.options.defer) {
                    continue;
                }
            }
            if (onActions.indexOf(hndl.onAction) != -1) {

                if (options.action == 'render' && !Kwf._elCacheBySelector[hndl.selector]) {
                    var t = Kwf.Utils.BenchmarkBox.now();
                    var m = hndl.selector.match(/^[a-z]*\.([a-z]+)/i)
                    if (m) {
                        //do a stupid text search on the selector, using that we can skip query for many selectors that don't exist in the current el
                        if (html.indexOf(m[1]) == -1) {
                            Kwf._elCacheBySelector[hndl.selector] = [];
                        }
                    }
                    Kwf.Utils.BenchmarkBox.time('checkInnerHtml', Kwf.Utils.BenchmarkBox.now()-t);
                }

                if (Kwf._elCacheBySelector[hndl.selector]) {
                    if (Kwf._elCacheBySelector[hndl.selector].length === 0) {
                        //Optimize: if we never got element by that selector, skip query
                        Kwf.Utils.BenchmarkBox.count('querySkip');
                        continue;
                    }
                    Kwf.Utils.BenchmarkBox.count('queryCache');
                    var els = [];
                    for (var j=0; j<Kwf._elCacheBySelector[hndl.selector].length; j++) {
                        if (renderedEl == document.body || $.contains(renderedEl, Kwf._elCacheBySelector[hndl.selector][j])) {
                            els.push(Kwf._elCacheBySelector[hndl.selector][j]);
                        }
                    }
                } else {
                    var t = Kwf.Utils.BenchmarkBox.now();
                    var els = $.makeArray($(renderedEl).find(hndl.selector));
                    Kwf.Utils.BenchmarkBox.time('query', Kwf.Utils.BenchmarkBox.now() - t);
                    if (options.action == 'render' && renderedEl == document.body) {
                        Kwf._elCacheBySelector[hndl.selector] = els;
                    }
                }
                for (var j = 0; j< els.length; ++j) {
                    var alreadyInQueue = false;
                    Kwf._onReadyElQueue.each(function(q) {
                        if (q.num == hndl.num && q.el === els[j]) {
                            alreadyInQueue = true;
                            return true;
                        }
                    }, this);
                    if (!alreadyInQueue) {
                        var parentsCount = 0;
                        var n = els[j];
                        while (n = n.parentNode) {
                            parentsCount++;
                        }
                        Kwf.Utils.BenchmarkBox.count('readyEl');
                        Kwf._onReadyElQueue.push({
                            el: els[j],
                            fn: hndl.fn,
                            options: hndl.options,
                            num: hndl.num,
                            type: hndl.type,
                            onAction: hndl.onAction,
                            selector: hndl.selector,
                            queueNum: Kwf._elQueueNum++,
                            priority: hndl.options.priority || 0,
                            parentsCount: parentsCount
                        });
                    }
                }
            }
        }
    };

    if (options.action == 'render') {
        addToQueue(['render', 'show', 'widthChange']);
    } else if (options.action == 'show') {
        addToQueue(['show', 'widthChange']);
    } else if (options.action == 'hide') {
        addToQueue(['hide']);
    } else if (options.action == 'widthChange') {
        addToQueue(['widthChange']);
    }

    var t = Kwf.Utils.BenchmarkBox.now();
    Kwf._onReadyElQueue.sort(function sortOnReadyElQueue(a, b) {
        if (a.priority != b.priority) {
            return a.priority - b.priority;
        } else {
            if (a.parentsCount != b.parentsCount) {
                return a.parentsCount - b.parentsCount;
            } else {
                return 1;
            }
        }
    });
    Kwf.Utils.BenchmarkBox.time('sort', Kwf.Utils.BenchmarkBox.now() - t);

    if (Kwf._onReadyIsCalling) {
        return;
    }

    Kwf._onReadyIsCalling = true;

    while (Kwf._onReadyCallQueue.length) {
        var queueEntry = Kwf._onReadyCallQueue.pop();

        Kwf._readyHandlers.sort(function(a, b) {
            return (a.options.priority || 0) - (b.options.priority || 0);
        });
        for (var i = 0; i < Kwf._readyHandlers.length; i++) {
            var hndl = Kwf._readyHandlers[i];
            if (hndl.selector == null) {
                var t = Kwf.Utils.BenchmarkBox.now();
                hndl.fn.call(hndl.options.scope || window, queueEntry.renderedEl, queueEntry.options);
                Kwf.Utils.BenchmarkBox.time('onContentReady', Kwf.Utils.BenchmarkBox.now()-t);
            }
        }
    }

    function _callQueueFn(timerName, queueEntry, config)
    {
        var t = Kwf.Utils.BenchmarkBox.now();
        var el = queueEntry.el;
        el = queueEntry.type == 'ext' ? Ext.get(el) : $(el);
        queueEntry.fn.call(queueEntry.options.scope || window, el, config);
        Kwf.Utils.BenchmarkBox.time(timerName, Kwf.Utils.BenchmarkBox.now()-t);
        var fnName = queueEntry.fn.name;
        if (!fnName) {
            fnName = 'unknown';
        }
        Kwf.Utils.BenchmarkBox.time('fn: '+fnName, Kwf.Utils.BenchmarkBox.now()-t);
    };
    function _processOnReadyElQueueEntry()
    {
        var queueEntry = Kwf._onReadyElQueue.shift();
        var el = queueEntry.el;
        if (queueEntry.onAction == 'render') {
            if (queueEntry.options.checkVisibility && !$(el).is(':visible')) {
                return;
            }
            if (!el.initDone) el.initDone = {};
            if (el.initDone[queueEntry.num]) {
                return;
            }
            el.initDone[queueEntry.num] = true;
            var config = {};
            var configEl = $(el).find('> input[type="hidden"]')
            if (configEl.length) {
                try {
                    var v = configEl.get(0).value;
                    if (v.substr(0, 1) == '{') {
                        config = $.parseJSON(v);
                    }
                } catch (err) {}
            }
            _callQueueFn('onRender', queueEntry, config);
        } else {
            if (queueEntry.onAction == 'show') {
                if ($(el).is(':visible')) {
                    _callQueueFn('onShow', queueEntry);
                }
            } else if (queueEntry.onAction == 'hide') {
                if (!$(el).is(':visible')) {
                    _callQueueFn('onHide', queueEntry);
                }
            } else if (queueEntry.onAction == 'widthChange') {
                _callQueueFn('onWidthChange', queueEntry);
            }

        }
    }

    if (Kwf._skipDeferred === false) {
        var processNext = function processNext() {
            Kwf.Utils.BenchmarkBox.count('chunks');
            var t = Kwf.Utils.BenchmarkBox.now();
            while (Kwf._onReadyElQueue.length && Kwf.Utils.BenchmarkBox.now()-t < 50) {
                _processOnReadyElQueueEntry();
            }
            if (Kwf._onReadyElQueue.length) {
                processNext.defer(this, 1);
            } else {
                Kwf._onReadyIsCalling = false;
                Kwf.Utils.BenchmarkBox.time('time', Kwf.Utils.BenchmarkBox.now()-Kwf._deferredStart);
                if (Kwf.enableOnReadyConsoleProfile) console.profileEnd();
                Kwf.Utils.BenchmarkBox.create({
                    counters: Kwf._onReadyStats,
                    type: 'onReady defer'
                });
            }
        };
        processNext();
    } else {
        while (Kwf._onReadyElQueue.length) {
            _processOnReadyElQueueEntry();
        }
        Kwf._onReadyIsCalling = false;
    }

};

/**
 * Register a function that will be called when content is loaded or shown
 * @param callback function (passed arguments: el, options (newRender=bool))
 * @param options supported are: priority (integer, higher number means it's called after all with lower number, default 0)
 */
Kwf.onContentReady = function(fn, options) {
    if (arguments.length == 3) {
        var scope = arguments[1];
        var options = arguments[2];
        options.scope = scope;
    }
    Kwf._readyHandlers.push({
        selector: null,
        fn: fn,
        options: options || {}
    });
};
<|endoftext|>


<commit_before>export default class FullScreenManager {
    /**
     * @constructor
     */
    constructor() {
        this.request = this.request.bind(this);
        this.close = this.close.bind(this);
    }

    /**
     * Request the fullscreen mode.
     *
     * @param {HTMLElement} [element]
     * @return {void}
     */
    request(element = document.documentElement) {
        if (element.requestFullscreen) {
            element.requestFullscreen();
        } else if (element.mozRequestFullScreen) { /* Firefox */
            element.mozRequestFullScreen();
        } else if (element.webkitRequestFullscreen) { /* Chrome, Safari and Opera */
            element.webkitRequestFullscreen();
        } else if (element.msRequestFullscreen) { /* IE/Edge */
            element.msRequestFullscreen();
        }
    }

    /**
     * Close the fullscreen mode.
     *
     * @return {void}
     */
    close() {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.mozCancelFullScreen) { /* Firefox */
            document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) { /* Chrome, Safari and Opera */
            document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) { /* IE/Edge */
            document.msExitFullscreen();
        }
    }
}
<commit_msg>Clean up<commit_after>export default class FullScreenManager {
    /**
     * @constructor
     */
    constructor() {
        this.request = this.request.bind(this);
        this.close = this.close.bind(this);
    }

    /**
     * Request the fullscreen mode.
     *
     * @param {HTMLElement} [element]
     * @return {void}
     */
    request(element = document.documentElement) {
        if (element.requestFullscreen) {
            element.requestFullscreen();
        }
        // Firefox
        else if (element.mozRequestFullScreen) {
            element.mozRequestFullScreen();
        }
        // Chrome, Safari and Opera
        else if (element.webkitRequestFullscreen) {
            element.webkitRequestFullscreen();
        }
        // IE/Edge
        else if (element.msRequestFullscreen) {
            element.msRequestFullscreen();
        }
    }

    /**
     * Close the fullscreen mode.
     *
     * @return {void}
     */
    close() {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        }
        // Firefox
        else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        }
        // Chrome, Safari and Opera
        else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        }
        // IE/Edge
        else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
    }
}
<|endoftext|>


<commit_before>import * as types from '../constants/action_types';

export function fetchConversations(user) {
    return dispatch => {
        dispatch(requestConversations())
        return fetch(`/api/users/${user}/conversations/`)
            .then(response => response.json())
            .then(conversations => dispatch(receiveConversations(conversations)))
            .catch(error => {throw error});
    }
}

function requestConversations() {
    return {
        type: types.LOAD_CONVERSATIONS
    }
}

function receiveConversations(conversations) {
    return {
        type: types.LOAD_CONVERSATIONS_SUCCESS,
        conversations
    }
}

export function fetchMessages(conversationId) {
    return dispatch => {
        dispatch(requestMessages())
        return fetch(`/api/conversations/${conversationId}`)
            .then(response => response.json())
            .then(messages => dispatch(receiveMessages(messages)))
            .catch(error => {throw error});
    }
}

function requestMessages() {
    return {
        type: types.LOAD_MESSAGES
    }
}

function receiveMessages(messages) {
    return {
        type: types.LOAD_MESSAGES_SUCCESS,
        messages
    }
}

export function sendMessage(conversationId, userId, text) {
    let messageRequestBody = {
        userId: userId,
        conversationId: conversationId,
        text: 'hi'
    };

    let data = new FormData();
    data.append( "json", JSON.stringify( messageRequestBody ) );

    console.log('message ' + messageRequestBody.conversationId);
    return dispatch => {
        return fetch(`/api/messages`, {
            method: 'POST',
            body: data
        }).then(response => response.json())
        .catch(error => { throw error; });
    }
}<commit_msg>Fixed fetch post method<commit_after>import * as types from '../constants/action_types';

export function fetchConversations(user) {
    return dispatch => {
        dispatch(requestConversations())
        return fetch(`/api/users/${user}/conversations/`)
            .then(response => response.json())
            .then(conversations => dispatch(receiveConversations(conversations)))
            .catch(error => {throw error});
    }
}

function requestConversations() {
    return {
        type: types.LOAD_CONVERSATIONS
    }
}

function receiveConversations(conversations) {
    return {
        type: types.LOAD_CONVERSATIONS_SUCCESS,
        conversations
    }
}

export function fetchMessages(conversationId) {
    return dispatch => {
        dispatch(requestMessages())
        return fetch(`/api/conversations/${conversationId}`)
            .then(response => response.json())
            .then(messages => dispatch(receiveMessages(messages)))
            .catch(error => {throw error});
    }
}

function requestMessages() {
    return {
        type: types.LOAD_MESSAGES
    }
}

function receiveMessages(messages) {
    return {
        type: types.LOAD_MESSAGES_SUCCESS,
        messages
    }
}

export function sendMessage(conversationId, userId, text) {
    let messageRequestBody = {
        userId: userId,
        conversationId: conversationId,
        text: 'hi'
    };

    return dispatch => {
        return fetch(`/api/messages`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(messageRequestBody)
        }).then(response => response.json())
        .catch(error => { throw error; });
    }
}<|endoftext|>


<commit_before>// patch to fix Phaser
(function () {
    // resolution problem
    function removeResolutionFromCode (obj, methodName) {
        if (!obj[methodName]) return;
        var code = obj[methodName].toString();
        code = code.replace('this.game.resolution', '1');
        obj[methodName] = window.eval('(' + code + ')');
    }
    removeResolutionFromCode(Phaser.Cache.prototype, "addCompressedTextureMetaData");
    removeResolutionFromCode(Phaser.Cache.prototype, "addImage");
    removeResolutionFromCode(Phaser.Cache.prototype, "addBitmapFont");
    removeResolutionFromCode(Phaser.Cache.prototype, "addSpriteSheet");
    removeResolutionFromCode(Phaser.Cache.prototype, "addTextureAtlas");
    var code = Phaser.Loader.prototype.loadImageTag.toString();
    // fix Firefox black texture issue
    // More info here: https://github.com/photonstorm/phaser/issues/2534
    code = code.replace(
        "if (file.data.complete && file.data.width && file.data.height)",
        "if (!this.game.device.firefox && file.data.complete && file.data.width && file.data.height)"
    );
    Phaser.Loader.prototype.loadImageTag = window.eval('(' + code + ')');
})();

// Finished loading phaser.js
var loading = document.getElementById('loading');
if (window.Phaser) {
    loading.style.display = 'none';
}
else {
    loading.innerHTML = "Unable to load phaser.js";
}

// get renderer config

function getRendererConfig() {
    var renderer;
    try {
        renderer = localStorage.getItem('ShapeClear_renderer');
        switch (renderer){
          case "WEBGL":
          case "CANVAS":
          case "AUTO":
          case "HEADLESS":
            renderer = Phaser[renderer];
            break;
          default:
            renderer = Phaser.AUTO;
        }
    }
    catch (e) {
        renderer = Phaser.AUTO;
    }
    return renderer;
}

function getResolutionConfig() {
    var res;
    try {
        res = +localStorage.getItem('ShapeClear_resolution');
        if (res < 0.25) res = 1;
        if (res != res) res = 1;
        var devicePixelRatio = window.devicePixelRatio || 1;
        devicePixelRatio = Math.round(devicePixelRatio * 4) / 4;
        if (res > devicePixelRatio) res = devicePixelRatio;
    }
    catch (e) {
        res = 1;
    }
    return res;
}

function getWindowSize() {
    var rect = document.body.getClientRects()[0];
    var width = Math.min(Math.floor(rect.width), innerWidth);
    var height = Math.min(Math.floor(rect.height), innerHeight);
    return [width, height];
}

// Start my game!
var windowSize = getWindowSize();
var game = new Phaser.Game({
    "width": windowSize[0],
    "height": windowSize[1],
    "renderer": getRendererConfig(),
    "parent": "gameDiv",
    "enableDebug": false,
    "resolution": getResolutionConfig()
});
var gameScreen = new GameScreen();
game.state.add("GameScreen", gameScreen);
game.state.add("Load", new Load());
var mainMenu = new MainMenu();
game.state.add("MainMenu", mainMenu);
game.state.start("Load");
<commit_msg>fix show matching<commit_after>// patch to fix Phaser
(function () {
    // resolution problem
    function removeResolutionFromCode (obj, methodName) {
        if (!obj[methodName]) return;
        var code = obj[methodName].toString();
        code = code.replace('this.game.resolution', '1');
        obj[methodName] = window.eval('(' + code + ')');
    }
    removeResolutionFromCode(Phaser.Cache.prototype, "addCompressedTextureMetaData");
    removeResolutionFromCode(Phaser.Cache.prototype, "addImage");
    removeResolutionFromCode(Phaser.Cache.prototype, "addBitmapFont");
    removeResolutionFromCode(Phaser.Cache.prototype, "addSpriteSheet");
    removeResolutionFromCode(Phaser.Cache.prototype, "addTextureAtlas");
    var code = Phaser.Loader.prototype.loadImageTag.toString();
    // fix Firefox black texture issue
    // More info here: https://github.com/photonstorm/phaser/issues/2534
    code = code.replace(
        "if (file.data.complete && file.data.width && file.data.height)",
        "if (!this.game.device.firefox && file.data.complete && file.data.width && file.data.height)"
    );
    Phaser.Loader.prototype.loadImageTag = window.eval('(' + code + ')');
    // porting changes from
    // https://github.com/samme/phaser-ce/commit/1bf7ca70be9e45308a4761417caf520e0fb786ac
    Phaser.BitmapData.generateTexture = function (key, callback, callbackContext) {
        var cache = this.game.cache;
        var image = new Image();

        image.src = this.canvas.toDataURL("image/png");

        if (!callback || image.complete)
        {
            var obj = cache.addImage(key, '', image);
            return new PIXI.Texture(obj.base);
        }
        else
        {
            image.onload = function () {
                var obj = cache.addImage(key, '', image);
                var texture = new PIXI.Texture(obj.base);
                callback.call(callbackContext || null, texture);
                image.onload = null;
            };
        }

        return null;
    };
})();

// Finished loading phaser.js
var loading = document.getElementById('loading');
if (window.Phaser) {
    loading.style.display = 'none';
}
else {
    loading.innerHTML = "Unable to load phaser.js";
}

// get renderer config

function getRendererConfig() {
    var renderer;
    try {
        renderer = localStorage.getItem('ShapeClear_renderer');
        switch (renderer){
          case "WEBGL":
          case "CANVAS":
          case "AUTO":
          case "HEADLESS":
            renderer = Phaser[renderer];
            break;
          default:
            renderer = Phaser.AUTO;
        }
    }
    catch (e) {
        renderer = Phaser.AUTO;
    }
    return renderer;
}

function getResolutionConfig() {
    var res;
    try {
        res = +localStorage.getItem('ShapeClear_resolution');
        if (res < 0.25) res = 1;
        if (res != res) res = 1;
        var devicePixelRatio = window.devicePixelRatio || 1;
        devicePixelRatio = Math.round(devicePixelRatio * 4) / 4;
        if (res > devicePixelRatio) res = devicePixelRatio;
    }
    catch (e) {
        res = 1;
    }
    return res;
}

function getWindowSize() {
    var rect = document.body.getClientRects()[0];
    var width = Math.min(Math.floor(rect.width), innerWidth);
    var height = Math.min(Math.floor(rect.height), innerHeight);
    return [width, height];
}

// Start my game!
var windowSize = getWindowSize();
var game = new Phaser.Game({
    "width": windowSize[0],
    "height": windowSize[1],
    "renderer": getRendererConfig(),
    "parent": "gameDiv",
    "enableDebug": false,
    "resolution": getResolutionConfig()
});
var gameScreen = new GameScreen();
game.state.add("GameScreen", gameScreen);
game.state.add("Load", new Load());
var mainMenu = new MainMenu();
game.state.add("MainMenu", mainMenu);
game.state.start("Load");
<|endoftext|>


<commit_before>const NETWORK_ERROR_MESSAGE = 'Unfortunately, connection to server has failed. Please check if you can connect to {apiEndpoint} from your browser and contact support if the error continues.';

export default class ErrorMessageFormatter {

  constructor(ENV, $filter) {
    this.ENV = ENV;
    this.$filter = $filter;
  }

  format(response) {
    /*
    Status code -1 denotes network error.
    Usually it is caused by one of the following reasons:

    - client is not connected to the internet;
    - server is down;
    - server is inaccessible via VPN;
    - server is located in another domain and didn't return valid CORS headers;
    - request has timed out;
    - request was aborted, ie manually cancelled by the client.

    See also: https://fetch.spec.whatwg.org/#concept-filtered-response
    */

    let message;

    if (response.status === -1) {
      message = NETWORK_ERROR_MESSAGE.replace('{apiEndpoint}', this.ENV.apiEndpoint);
    } else {
      message = response.status + ': ' + response.statusText;
    }

    if (response.data) {
      if (response.data.non_field_errors) {
        message += ' ' + response.data.non_field_errors;
      }
      if (response.data.detail) {
        message += ' ' + response.data.detail;
      }
    }

    return message;
  }
}
<commit_msg>Simplify code (WAL-407)<commit_after>const NETWORK_ERROR_MESSAGE = 'Unfortunately, connection to server has failed. Please check if you can connect to {apiEndpoint} from your browser and contact support if the error continues.';

export default class ErrorMessageFormatter {

  constructor(ENV, $filter) {
    this.ENV = ENV;
    this.$filter = $filter;
  }

  format(response) {
    /*
    Status code -1 denotes network error.
    Usually it is caused by one of the following reasons:

    - client is not connected to the internet;
    - server is down;
    - server is inaccessible via VPN;
    - server is located in another domain and didn't return valid CORS headers;
    - request has timed out;
    - request was aborted, ie manually cancelled by the client.

    See also: https://fetch.spec.whatwg.org/#concept-filtered-response
    */

    if (response.status === -1) {
      return NETWORK_ERROR_MESSAGE.replace('{apiEndpoint}', this.ENV.apiEndpoint);
    }

    let message = response.status + ': ' + response.statusText;

    if (response.data) {
      if (response.data.non_field_errors) {
        message += ' ' + response.data.non_field_errors;
      }
      if (response.data.detail) {
        message += ' ' + response.data.detail;
      }
    }

    return message;
  }
}
<|endoftext|>


<commit_before>var Promise = TrelloPowerUp.Promise;
var t = TrelloPowerUp.iframe();

//var oauthUrl = 'https://trello.com/1/authorize?expiration=never' +
//  '&name=[APPNAME]&scope=read&key=[APIKEY]&callback_method=fragment' +
//  '&return_url=[RETURNURL]';

  var oauthUrl = 'https://martinm78.github.io/loginFromTrello.html';

var tokenLooksValid = function(token) {
  //return /^[0-9a-f]{64}$/.test(token);
  return true;
}

var authorizeOpts = {
  height: 680,
  width: 580,
  validToken: tokenLooksValid
};

var authBtn = document.getElementById('authorize');

authBtn.addEventListener('click', function() {

  t.authorize(oauthUrl, authorizeOpts)
  .then(function(token) {
	console.log('then token:' + token);
    return t.set('organization', 'private', 'token', token)
    .catch(t.NotHandled, function() {
      // fall back to storing at board level
      return t.set('board', 'private', 'token', token);
    });
  })
  .then(function() {
	console.log('then closePopup');
    // now that the token is stored, we can close this popup
    // you might alternatively choose to open a new popup

	$.ajax({
		url:"https://martinm78.github.io/ajax.html",
		dataType: 'json',
		success:function(json){
			// do stuff with json (in this case an array)
			alert("Success");
		},
		error:function(){
			alert("Error");
		}
	});

	//return t.closePopup();
  });
});

<commit_msg>cambio prueba<commit_after>var Promise = TrelloPowerUp.Promise;
var t = TrelloPowerUp.iframe();

//var oauthUrl = 'https://trello.com/1/authorize?expiration=never' +
//  '&name=[APPNAME]&scope=read&key=[APIKEY]&callback_method=fragment' +
//  '&return_url=[RETURNURL]';

  var oauthUrl = 'https://martinm78.github.io/loginFromTrello.html';

var tokenLooksValid = function(token) {
  //return /^[0-9a-f]{64}$/.test(token);
  return true;
}

var authorizeOpts = {
  height: 680,
  width: 580,
  validToken: tokenLooksValid
};

var authBtn = document.getElementById('authorize');

authBtn.addEventListener('click', function() {

  t.authorize(oauthUrl, authorizeOpts)
  .then(function(token) {
	console.log('then token:' + token);
    return t.set('organization', 'private', 'token', token)
    .catch(t.NotHandled, function() {
      // fall back to storing at board level
      return t.set('board', 'private', 'token', token);
    });
  })
  .then(function() {
	console.log('then closePopup');
    // now that the token is stored, we can close this popup
    // you might alternatively choose to open a new popup

	$.ajax({
		url:"https://martinm78.github.io/ajax.html?token="+t.get('organization', 'private', 'token'),
		dataType: 'json',
		success:function(json){
			// do stuff with json (in this case an array)
			alert("Success");
		},
		error:function(jqXHR,textStatus){
			alert("Error:"+textStatus);
		}
	});

	//return t.closePopup();
  });
});

<|endoftext|>


<commit_before>'use strict';

/**
 */
angular.module('openolitor-admin')
  .controller('ReportsDetailController', ['$scope', '$rootScope', '$filter', '$routeParams',
    '$location', '$uibModal', 'gettext', 'ReportsModel', '$log', 'NgTableParams', 'lodash',
    function($scope, $rootScope, $filter, $routeParams, $location, $uibModal, gettext, ReportsModel, $log, NgTableParams, lodash) {
      $rootScope.viewId = 'D-Rept';

      $scope.isModifying = false;

      $scope.result = {
        entries:[]
      }
      $scope.cols = [];

      var defaults = {
        model: {
          id: undefined
        }
      };

      $scope.search = {
        query: ''
      };

      if (!$routeParams.id || $routeParams.id === 'new') {
        $scope.isModifying = true;
        $scope.report = new ReportsModel(defaults.model);
      } else {
        ReportsModel.get({
          id: $routeParams.id
        }, function(result) {
          result.query = sqlFormatter.format(result.query);
          $scope.report = result;
        });
      }

      $scope.isExisting = function() {
        return angular.isDefined($scope.report) && angular.isDefined($scope.report.id);
      };

      $scope.renderedInput = function($scope, row) {
          if (row[this.field] !== null){
              if (/kundeid|kunde_id|kunde-id/.test(this.field.toLowerCase())){
                return "" + row[this.field] + "";
              } else if (/zusatz-abo-id|zusatz_abo_id|zusatzaboid|zusatzabo_id|zusatzabo-id/.test(this.field.toLowerCase())){
                return row[this.field];
              } else if (/abotypid|abotyp_id|abotyp-id/.test(this.field.toLowerCase())){
                return "" + row[this.field] + "";
              } else if (/aboid|abo_id|abo-id/.test(this.field.toLowerCase())){
                return "" + row[this.field] + "";
              } else if (/tourid|tour_id|tour-id/.test(this.field.toLowerCase())){
                return "" + row[this.field] + "";
              } else if (/depotid|depot_id|depot-id/.test(this.field.toLowerCase())){
                return "" + row[this.field] + "";
              } else if (/produzentid|produzent_id|produzent-id/.test(this.field.toLowerCase())){
                return "" + row[this.field] + "";
              } else {
                return row[this.field];
              }
          }
          return row[this.field];
      };

      $scope.renderedTitles = function(key) {
          if (key !== null){
              if (/kundeid|kunde_id|kunde-id/.test(key.toLowerCase())){
                var items = lodash.map($scope.result.entries,key);
                var uniqueItems = lodash.reject(lodash.uniq(items),_.isEmpty);
                return "" + key + "";
              }
              else if (/zusatz-abo-id|zusatz_abo_id|zusatzaboid|zusatzabo_id|zusatzabo-id/.test(key.toLowerCase())){
                var items = lodash.map($scope.result.entries,key);
                var uniqueItems = lodash.reject(lodash.uniq(items),_.isEmpty);
                return "" + key + "";
              }
              else if (/aboid|abo_id|abo-id/.test(key.toLowerCase())){
                var items = lodash.map($scope.result.entries,key);
                var uniqueItems = lodash.reject(lodash.uniq(items),_.isEmpty);
                return "" + key + "";
              }
              else if (/personid|person_id|person-id/.test(key.toLowerCase())){
                var items = lodash.map($scope.result.entries,key);
                var uniqueItems = lodash.reject(lodash.uniq(items),_.isEmpty);
                return "" + key + "";
              }
              else if (/rechnungpositionid|rechnungposition_id|rechnungposition-id/.test(key.toLowerCase())){
                var items = lodash.map($scope.result.entries,key);
                var uniqueItems = lodash.reject(lodash.uniq(items),_.isEmpty);
                return "" + key + "";
              }
              else if (/einkaufsrechnungid|einkaufsrechnung_id|einkaufsrechnung-id|sammelbestellungid|sammelbestellung-id|sammelbestellung_id/.test(key.toLowerCase())){
                var items = lodash.map($scope.result.entries,key);
                var uniqueItems = lodash.reject(lodash.uniq(items),_.isEmpty);
                return "" + key + "";
              }
              else if (/rechnung_id|rechnungId|rechnung-id/.test(key.toLowerCase())){
                var items = lodash.map($scope.result.entries,key);
                var uniqueItems = lodash.reject(lodash.uniq(items),_.isEmpty);
                return "" + key + "";
              } else {
                return ""+key+"";
              }
          }
          return ""+key+"";
      };

      $scope.executeReport = function() {
        $scope.result = {};
        ReportsModel.executeReport({id: $scope.report.id, query: $scope.report.query}, function(data) {
          if(data && data[0]) {
            $scope.cols = [];
            for(var key in data[0]) {
              if(key.indexOf('$') !== 0 && key !== 'toJSON') {
                $scope.cols.push({
                  field: key,
                  getValue: $scope.renderedInput
                });
              }
            }
          }
          if (!$scope.result || !$scope.result.entries) {
            $scope.result.entries = data;
            $scope.tableParams.reload();
          }
        });
      };

      if (!$scope.tableParams) {
        //use default tableParams
        $scope.tableParams = new NgTableParams({ // jshint ignore:line
          page: 1,
          count: 10,
        }, {
          filterDelay: 0,
          groupOptions: {
            isExpanded: true
          },
          exportODSModel: ReportsModel,
          exportODSFilter: function() {
            return {
              id: $scope.report.id,
              query: $scope.report.query
            };
          },
          getData: function(params) {
            if (!$scope.result || !$scope.result.entries) {
              return;
            }
            // use build-in angular filter
            var dataSet = $filter('filter')($scope.result.entries, $scope.search.query);
            // also filter by ngtable filters
            dataSet = $filter('filter')(dataSet, params.filter());

            params.total(dataSet.length);
            return dataSet.slice((params.page() - 1) * params.count(), params.page() * params.count());
          }
        });
      }

      $scope.save = function() {
        return $scope.report.$save(function(){
          $scope.isModifying = false;
          $scope.reportForm.$setPristine();
        });
      };

      $scope.created = function(id) {
        $location.path('/reports/' + id);
      };

      $scope.backToList = function() {
        $location.path('/reports');
      };

      $scope.delete = function() {
        return $scope.report.$delete();
      };

      $scope.changeReport = function() {
        $scope.result.entries = [];
      };
    }
  ]);
<commit_msg>Links to Overviews and Details fixed<commit_after>'use strict';

/**
 */
angular.module('openolitor-admin')
  .controller('ReportsDetailController', ['$scope', '$rootScope', '$filter', '$routeParams',
    '$location', '$uibModal', 'gettext', 'ReportsModel', '$log', 'NgTableParams', 'lodash',
    function($scope, $rootScope, $filter, $routeParams, $location, $uibModal, gettext, ReportsModel, $log, NgTableParams, lodash) {
      $rootScope.viewId = 'D-Rept';

      $scope.isModifying = false;

      $scope.result = {
        entries: []
      }
      $scope.cols = [];

      var defaults = {
        model: {
          id: undefined
        }
      };

      $scope.search = {
        query: ''
      };

      if (!$routeParams.id || $routeParams.id === 'new') {
        $scope.isModifying = true;
        $scope.report = new ReportsModel(defaults.model);
      } else {
        ReportsModel.get({
          id: $routeParams.id
        }, function(result) {
          result.query = sqlFormatter.format(result.query);
          $scope.report = result;
        });
      }

      $scope.isExisting = function() {
        return angular.isDefined($scope.report) && angular.isDefined($scope.report.id);
      };

      $scope.renderedInput = function($scope, row) {
        if (row[this.field] !== null) {
          if (/kundeid|kunde_id|kunde-id/.test(this.field.toLowerCase())) {
            return '' + row[this.field] + '';
          } else if (/zusatz-abo-id|zusatz_abo_id|zusatzaboid|zusatzabo_id|zusatzabo-id/.test(this.field.toLowerCase())) {
            return row[this.field];
          } else if (/abotypid|abotyp_id|abotyp-id/.test(this.field.toLowerCase())) {
            return '' + row[this.field] + '';
          } else if (/aboid|abo_id|abo-id/.test(this.field.toLowerCase())) {
            return '' + row[this.field] + '';
          } else if (/tourid|tour_id|tour-id/.test(this.field.toLowerCase())) {
            return '' + row[this.field] + '';
          } else if (/depotid|depot_id|depot-id/.test(this.field.toLowerCase())) {
            return '' + row[this.field] + '';
          } else if (/produzentid|produzent_id|produzent-id/.test(this.field.toLowerCase())) {
            return '' + row[this.field] + '';
          } else {
            return row[this.field];
          }
        }
        return row[this.field];
      };

      $scope.renderedTitles = function(key) {
        if (key !== null) {
          if (/kundeid|kunde_id|kunde-id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else if (/zusatz-abo-id|zusatz_abo_id|zusatzaboid|zusatzabo_id|zusatzabo-id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else if (/aboid|abo_id|abo-id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else if (/personid|person_id|person-id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else if (/rechnungpositionid|rechnungposition_id|rechnungposition-id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else if (/einkaufsrechnungid|einkaufsrechnung_id|einkaufsrechnung-id|sammelbestellungid|sammelbestellung-id|sammelbestellung_id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else if (/rechnung_id|rechnungId|rechnung-id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else {
            return '' + key + '';
          }
        }
        return '' + key + '';
      };

      $scope.executeReport = function() {
        $scope.result = {};
        ReportsModel.executeReport({
          id: $scope.report.id,
          query: $scope.report.query
        }, function(data) {
          if (data && data[0]) {
            $scope.cols = [];
            for (var key in data[0]) {
              if (key.indexOf('$') !== 0 && key !== 'toJSON') {
                $scope.cols.push({
                  field: key,
                  getValue: $scope.renderedInput
                });
              }
            }
          }
          if (!$scope.result || !$scope.result.entries) {
            $scope.result.entries = data;
            $scope.tableParams.reload();
          }
        });
      };

      if (!$scope.tableParams) {
        //use default tableParams
        $scope.tableParams = new NgTableParams({ // jshint ignore:line
          page: 1,
          count: 10,
        }, {
          filterDelay: 0,
          groupOptions: {
            isExpanded: true
          },
          exportODSModel: ReportsModel,
          exportODSFilter: function() {
            return {
              id: $scope.report.id,
              query: $scope.report.query
            };
          },
          getData: function(params) {
            if (!$scope.result || !$scope.result.entries) {
              return;
            }
            // use build-in angular filter
            var dataSet = $filter('filter')($scope.result.entries, $scope.search.query);
            // also filter by ngtable filters
            dataSet = $filter('filter')(dataSet, params.filter());

            params.total(dataSet.length);
            return dataSet.slice((params.page() - 1) * params.count(), params.page() * params.count());
          }
        });
      }

      $scope.save = function() {
        return $scope.report.$save(function() {
          $scope.isModifying = false;
          $scope.reportForm.$setPristine();
        });
      };

      $scope.created = function(id) {
        $location.path('/reports/' + id);
      };

      $scope.backToList = function() {
        $location.path('/reports');
      };

      $scope.delete = function() {
        return $scope.report.$delete();
      };

      $scope.changeReport = function() {
        $scope.result.entries = [];
      };
    }
  ]);<|endoftext|>