<commit_before>(function() {
  'use strict';
  angular.module('ps.core.service')
    .factory('versionService', versionService);

  function versionService($q,dataService) {
    return {
      checkVersion: checkVersion,
    };

    function checkVersion(newVersion, oldVersion) {
      var promises = [];
      var p = 1;
      promises[0] = dataService.setData({
        'version': newVersion,
      });
      //from v1.x.x
      if (angular.isUndefined(oldVersion) || oldVersion.charAt(0) < '2') {
        if (angular.isDefined(dataService.data.bookmarkid)) {
          var data = {};
          data.quicklinks = [dataService.data.bookmarkid];
          promises[p] = dataService.setData(data);
          p++;
        }
        oldVersion = '2.0.0';
      }
      //from v2.0.0
      if (oldVersion === '2.0.0') {
        promises[p] = dataService.clearData('layout');
        p++;
      }
      return $q.all(promises);
    }
  }

})();
<commit_msg>Updated version services for RSS feed changes<commit_after>(function() {
  'use strict';
  angular.module('ps.core.service')
    .factory('versionService', versionService);

  function versionService($q, dataService) {
    return {
      checkVersion: checkVersion,
    };

    function checkVersion(newVersion, oldVersion) {
      var promises = [];
      var p = 0;
      // promises[p++] = dataService.setData({
      //   'version': newVersion,
      // });
      //to v2.0.0
      if (angular.isDefined(dataService.data.bookmarkid)) { // compensating for not deleting bokmarkid previously
        if (olderVersion('2.0.0',oldVersion)) {
          var data = {};
          data.quicklinks = [dataService.data.bookmarkid];
          promises[p++] = dataService.setData(data);
        }
        promises[p++] = dataService.clearData('bookmarkid');
      }
      //to v2.1.0
      if (olderVersion('2.1.0',oldVersion)) {
        promises[p++] = dataService.clearData('layout');
      }
      //2.5.0 and above if rss is array
      if (angular.isDefined(dataService.data.rssFeed)
        && angular.isArray(dataService.data.rssFeed)) {
        dataService.data.rssFeed = {
          feeds: dataService.data.rssFeed,
        };
        promises[p++] = dataService.setData({
          rssFeed: dataService.data.rssFeed,
        });
      }

      return $q.all(promises);
    }

    function olderVersion(newVersion, oldVersion) {
      if (angular.isUndefined(oldVersion)) {
        return true;
      } else {
        var nv = newVersion.split('.');
        var ov = oldVersion.split('.');
        if ((+ov[0] < +nv[0])
          || (+ov[0] === +nv[0] && +ov[1] < +nv[1])
          || (+ov[0] === +nv[0] && +ov[1] === +nv[1] && +ov[2] < +nv[2])) {
          return true;
        } else {
          return false;
        }
      }
    }
  }

})();
<|endoftext|>


<commit_before>(function() {
  'use strict';

  function poll(el, wait) {
    var url = el.getAttribute('url')
    if (!url) {
      return
    }

    var xhr = new XMLHttpRequest()

    xhr.onload = function() {
      switch (xhr.status) {
        case 200:
          var container = document.createElement('div')
          container.innerHTML = xhr.responseText
          el.parentNode.replaceChild(container.firstChild, el)
          break
        case 202:
        case 404:
          var retry = poll.bind(this, el, wait * 1.5)
          el._pollId = window.setTimeout(retry, wait)
          break
        default:
          el.classList.add('error')
          break
      }
    }

    xhr.onerror = function() {
      el.classList.add('error')
    }

    xhr.ontimeout = function() {
      el.classList.add('error', 'timeout')
    }

    xhr.timeout = 5 * 1000
    xhr.open('GET', url)
    xhr.send(null)
    return xhr
  }

  var DeferredContentPrototype = Object.create(window.HTMLElement.prototype)

  DeferredContentPrototype.createdCallback = function() {
    this._xhr = null
    this._pollId = null
  }

  DeferredContentPrototype.attachedCallback = function() {
    this._xhr = poll(this, 1000)
  }

  DeferredContentPrototype.detachedCallback = function() {
    if (this._xhr) {
      this._xhr.abort()
      this._xhr = null
    }

    if (this._pollId) {
      window.clearInterval(this._pollId)
      this._pollId = null
    }
  }

  window.DeferredContentElement = document.registerElement('deferred-content', {
    prototype: DeferredContentPrototype
  })
})()
<commit_msg>Use clearTimeout to match setTimeout.<commit_after>(function() {
  'use strict';

  function poll(el, wait) {
    var url = el.getAttribute('url')
    if (!url) {
      return
    }

    var xhr = new XMLHttpRequest()
    xhr.onload = function() {
      switch (xhr.status) {
        case 200:
          var container = document.createElement('div')
          container.innerHTML = xhr.responseText
          el.parentNode.replaceChild(container.firstChild, el)
          break
        case 202:
        case 404:
          var retry = poll.bind(this, el, wait * 1.5)
          el._pollId = window.setTimeout(retry, wait)
          break
        default:
          el.classList.add('error')
          break
      }
    }

    xhr.onerror = function() {
      el.classList.add('error')
    }

    xhr.ontimeout = function() {
      el.classList.add('error', 'timeout')
    }

    xhr.timeout = 5 * 1000
    xhr.open('GET', url)
    xhr.send(null)
    return xhr
  }

  var DeferredContentPrototype = Object.create(window.HTMLElement.prototype)

  DeferredContentPrototype.createdCallback = function() {
    this._xhr = null
    this._pollId = null
  }

  DeferredContentPrototype.attachedCallback = function() {
    this._xhr = poll(this, 1000)
  }

  DeferredContentPrototype.detachedCallback = function() {
    if (this._xhr) {
      this._xhr.abort()
      this._xhr = null
    }

    if (this._pollId) {
      window.clearTimeout(this._pollId)
      this._pollId = null
    }
  }

  window.DeferredContentElement = document.registerElement('deferred-content', {
    prototype: DeferredContentPrototype
  })
})()
<|endoftext|>


<commit_before>import * as UsersController from "./controllers/users"

export default (app, Router) => {
  return app.use("/users", routeController(UsersController, new Router()))
}

export const __useDefault = true

const routeController = (Controller, router) => {
  router.param("uuid", async (req, res, next, uuid) => {
    req.user = await User.findOne({ where: { uuid } })
    next()
  })

  Object.entries(Controller).map(([name, fn]) => {
    switch(name) {
      case "index":
        router.get("/", fn)
        break
      case "create":
        router.post("/", fn)
        break
      case "show":
        router.get(":uuid", fn)
        break
      case "update":
        router.put(":uuid", fn)
        break
      case "destroy":
        router.delete(":uuid", fn)
        break
    }
  })

  return router
}
<commit_msg>configure body-parser<commit_after>import bodyParser from "body-parser"

import * as UsersController from "./controllers/users"

export default (app, Router) => {
  app.use(bodyParser.urlencoded())

  return app.use("/users", routeController(UsersController, new Router()))
}

export const __useDefault = true

const routeController = (Controller, router) => {
  router.param("uuid", async (req, res, next, uuid) => {
    req.user = await User.findOne({ where: { uuid } })
    next()
  })

  Object.entries(Controller).map(([name, fn]) => {
    switch(name) {
      case "index":
        router.get("/", fn)
        break
      case "create":
        router.post("/", fn)
        break
      case "show":
        router.get(":uuid", fn)
        break
      case "update":
        router.put(":uuid", fn)
        break
      case "destroy":
        router.delete(":uuid", fn)
        break
    }
  })

  return router
}
<|endoftext|>


<commit_before>/**
 * Created by Serhii Maksymchuk from Ubrainians for imCode
 * 14.08.17.
 */
Imcms.define("imcms-document-editor-builder",
    [
        "imcms-bem-builder", "imcms-page-info-builder", "imcms-components-builder", "imcms-primitives-builder",
        "imcms-documents-rest-api", "imcms-controls-builder", "imcms-users-rest-api", "imcms-categories-rest-api",
        "imcms-window-builder", "jquery"
    ],
    function (BEM, pageInfoBuilder, components, primitives, docRestApi, controlsBuilder, usersRestApi,
              categoriesRestApi, WindowBuilder, $) {

        var isMouseDown = false,
            mouseCoords = {
                pageX: undefined,
                pageY: undefined,
                newPageX: undefined,
                newPageY: undefined
            },
            $menuArea,
            menuAreaProp = {
                top: 0,
                left: 0,
                right: 0,
                bottom: 0
            }
        ;

        function buildBodyHeadTools() {

            function onNewDocButtonClick(e) {
                e.preventDefault();
                pageInfoBuilder.build();
            }

            function buildNewDocButton() {
                return components.buttons.negativeButton({
                    text: "New",
                    click: onNewDocButtonClick
                });
            }

            function buildSearchDocField() {
                return new BEM({
                    block: "imcms-input-search",
                    elements: {
                        "text-box": primitives.imcmsInputText({
                            id: "searchText",
                            name: "search",
                            placeholder: "Type to find document"
                        }),
                        "button": components.buttons.searchButton()
                    }
                }).buildBlockStructure("<div>");
            }

            function buildUsersFilterSelect() {
                var $usersFilterSelect = components.selects.imcmsSelect("<div>", {
                    id: "users-filter",
                    name: "users-filter"
                });

                usersRestApi.read(null).done(function (users) {
                    var usersDataMapped = users.map(function (user) {
                        return {
                            text: user.username,
                            "data-value": user.id
                        }
                    });
                    components.selects.addOptionsToSelect(usersDataMapped, $usersFilterSelect);
                });

                return $usersFilterSelect;
            }

            function buildCategoriesFilterSelect() {
                var $categoriesFilterSelect = components.selects.imcmsSelect("<div>", {
                    id: "categories-filter",
                    name: "categories-filter"
                });

                categoriesRestApi.read(null).done(function (categories) {
                    var categoriesDataMapped = categories.map(function (category) {
                        return {
                            text: category.name,
                            "data-value": category.id
                        }
                    });
                    components.selects.addOptionsToSelect(categoriesDataMapped, $categoriesFilterSelect);
                });

                return $categoriesFilterSelect;
            }

            var toolBEM = new BEM({
                block: "imcms-document-editor-head-tool",
                elements: {
                    "search": "imcms-input-search",
                    "button": "imcms-button"
                }
            });

            var $newDocButtonContainer = toolBEM.buildBlock("<div>", [{"button": buildNewDocButton()}]);
            $newDocButtonContainer.modifiers = ["grid-col-2"];

            var $searchContainer = toolBEM.buildBlock("<div>", [{"search": buildSearchDocField()}]);
            $searchContainer.modifiers = ["grid-col-4"];

            var $usersFilter = toolBEM.buildBlock("<div>", [{"select": buildUsersFilterSelect()}]);
            $usersFilter.modifiers = ["grid-col-3"];

            var $categoriesFilter = toolBEM.buildBlock("<div>", [{"select": buildCategoriesFilterSelect()}]);
            $categoriesFilter.modifiers = ["grid-col-3"];

            return new BEM({
                block: "imcms-document-editor-head-tools",
                elements: {
                    "tool": [
                        $newDocButtonContainer,
                        $searchContainer,
                        $usersFilter,
                        $categoriesFilter
                    ]
                }
            }).buildBlockStructure("<div>");
        }

        function buildBodyHead() {
            return new BEM({
                block: "imcms-document-editor-head",
                elements: {
                    "tools": buildBodyHeadTools()
                }
            }).buildBlockStructure("<div>");
        }

        function buildDocumentListTitlesRow() {
            var $idColumnHead = $("<div>", {text: "id"});
            $idColumnHead.modifiers = ["col-2"];

            var $titleColumnHead = $("<div>", {text: "Title"});
            $titleColumnHead.modifiers = ["col-3"];

            var $aliasColumnHead = $("<div>", {text: "Alias"});
            $aliasColumnHead.modifiers = ["col-3"];

            var $typeColumnHead = $("<div>", {text: "Type"});
            $typeColumnHead.modifiers = ["col-4"];

            return new BEM({
                block: "imcms-document-list-titles",
                elements: {
                    "title": [
                        $idColumnHead,
                        $titleColumnHead,
                        $aliasColumnHead,
                        $typeColumnHead
                    ]
                }
            }).buildBlockStructure("<div>");
        }

        function buildDocItemControls(documentId, opts) {
            var controls = [];

            if (opts) {
                if (opts.moveEnable) {
                    var $controlMove = controlsBuilder.move(function () {
                        console.log("%c Not implemented feature: move doc", "color: red;");
                    });
                    controls.push($controlMove);
                }

                if (opts.removeEnable) {
                    var $controlRemove = controlsBuilder.remove(function () {
                        removeDocument.call(this, documentId);
                    });
                    controls.push($controlRemove);
                }

                if (opts.editEnable) {
                    var $controlEdit = controlsBuilder.edit(pageInfoBuilder.build.bind(pageInfoBuilder, documentId));
                    controls.push($controlEdit);
                }
            }

            return controlsBuilder.buildControlsBlock("<div>", controls);
        }

        function moveFrame(event) {
            var $frame = $(".imcms-document-items--frame");
            mouseCoords.newPageX = event.clientX;
            mouseCoords.newPageY = event.clientY;

            if (isMouseDown) {
                $frame.css({
                    "top": (mouseCoords.newPageY - mouseCoords.pageY) + mouseCoords.top,
                    "left": (mouseCoords.newPageX - mouseCoords.pageX) + mouseCoords.left
                });

                if (detectTargetArea(event)) {
                    $menuArea.css({
                        "border-color": "#51aeea"
                    });
                    getDocumentParent();
                } else {
                    $menuArea.css({
                        "border-color": "transparent"
                    });
                    disableHighlightingMenuDoc()
                }

            }
        }

        function checkDocInMenuEditor(original) {
            var status = true,
                originalId = parseInt(original.find(".imcms-title").first().text())
            ;
            $(".imcms-menu-items").each(function () {
                if (parseInt($(this).attr("data-menu-id")) === originalId) {
                    status = false;
                }
            });

            return status;
        }

        function createFrame(event) {
            var $this = $(this),
                original = $this.closest(".imcms-document-items"),
                $frame = original.clone(),
                frameItem = $frame.find(".imcms-document-item")
            ;
            $menuArea = $(".imcms-menu-items-tree");

            if (!checkDocInMenuEditor(original)) {
                event.preventDefault();
                return
            }

            isMouseDown = true;
            mouseCoords = {
                pageX: event.clientX,
                pageY: event.clientY,
                top: $this.closest(".imcms-document-items").position().top,
                left: $this.closest(".imcms-document-items").position().left
            };
            menuAreaProp = {
                top: $menuArea.position().top,
                left: $menuArea.position().left,
                right: menuAreaProp.left + $menuArea.outerWidth(),
                bottom: menuAreaProp.top + $menuArea.outerHeight()
            };

            frameItem.attr("data-id", frameItem.children().first().text());
            frameItem.attr("data-title", frameItem.children().eq(1).text());

            $frame.addClass("imcms-document-items--frame");
            $frame.css({
                "background-color": "#e9e9f5",
                "position": "absolute",
                "z-index": 11001,
                "width": $(".imcms-document-list__items").outerWidth(),
                "top": mouseCoords.top,
                "left": mouseCoords.left
            });

            $frame.appendTo("body");
            $(document).on("mousemove", moveFrame);

            $(document).on("dragstart", function () {
                return false;
            });

        }

        function detectTargetArea(event) {
            return (event.pageY > menuAreaProp.top) && (event.pageY < menuAreaProp.bottom) && (event.pageX > menuAreaProp.left) && (event.pageX < menuAreaProp.right);
        }

        function getMenuDocByObjId(obj) {
            var menuDocs = $(".imcms-menu-items-tree").find(".imcms-menu-items"),
                menuDoc = null
            ;

            menuDocs.each(function () {
                if ($(this).attr("data-menu-id") === obj) {
                    menuDoc = $(this)
                }
            });

            return menuDoc;
        }

        function disableHighlightingMenuDoc() {
            $(".imcms-menu-items-tree").find(".imcms-menu-items").css({
                "border": "none"
            });
        }

        function checkFramePositioning(allMenuDocObjArray, frameTop) {
            var menuDoc = null,
                placeStatus = null
            ;
            // false -> under parent; true -> in parent; null -> under all

            function highlightMenuDoc(param, elem) {
                disableHighlightingMenuDoc();
                if (param) {
                    elem.css({
                        "border-top": "1px solid #51aeea",
                        "border-bottom": "1px solid #51aeea"
                    });
                } else {
                    elem.css({
                        "border-bottom": "1px solid #51aeea"
                    })
                }
            }

            $.each(allMenuDocObjArray, function (obj, param) {
                if (frameTop > param.top && frameTop < ((param.bottom + param.top) / 2)) {
                    menuDoc = getMenuDocByObjId(obj);
                    placeStatus = true;
                } else if (frameTop > ((param.bottom + param.top) / 2) && frameTop < param.bottom) {
                    menuDoc = getMenuDocByObjId(obj);
                    placeStatus = false;
                }
            });

            // highlightingMenuDoc
            if (placeStatus !== null) {
                highlightMenuDoc(placeStatus, menuDoc);
            } else {
                disableHighlightingMenuDoc();
            }

            return {
                parent: menuDoc,
                status: placeStatus
            }
        }

        function getDocumentParent() {
            var allMenuDocObjArray = {},
                itemTree = $(".imcms-menu-items-tree"),
                menuDocs = itemTree.find(".imcms-menu-items"),
                $frame = $(".imcms-document-items--frame"),
                frameTop = $frame.offset().top
            ;
            if (menuDocs.length === 0) {
                return checkFramePositioning(allMenuDocObjArray, frameTop)
            }

            // get all menu doc coords
            menuDocs.each(function () {
                allMenuDocObjArray[$(this).attr("data-menu-id")] = {
                    top: $(this).offset().top,
                    bottom: $(this).offset().top + $(this).outerHeight()
                };
            });

            return checkFramePositioning(allMenuDocObjArray, frameTop);
        }

        $(document).on("mouseup", function (event) {
            var $frame = $(".imcms-document-items--frame"),
                frameItem = $frame.find(".imcms-document-item"),
                dataInput = $("#dataInput"),
                insertedParent = null
            ;

            if ($frame.length === 0) {
                return
            }

            if (detectTargetArea(event)) {
                insertedParent = getDocumentParent();
                if (insertedParent.parent !== null) {
                    dataInput.attr("data-parent-id", insertedParent.parent.attr("data-menu-id"));
                    dataInput.attr("data-insert-place", insertedParent.status);
                } else {
                    dataInput.attr("data-parent-id", "");
                    dataInput.attr("data-insert-place", "");
                }
                dataInput.attr("data-id", frameItem.attr("data-id"));
                dataInput.attr("data-title", frameItem.attr("data-title")).trigger("change");
                $menuArea.css({
                    "border-color": "transparent"
                });
                disableHighlightingMenuDoc();
            }

            $frame.remove();
            isMouseDown = false;
        });

        function buildDocItem(document, opts) {
            var $docItemId = components.texts.titleText("<div>", document.id);
            $docItemId.modifiers = ["col-2"];

            var $docItemTitle = components.texts.titleText("<div>", document.title);
            $docItemTitle.modifiers = ["col-3"];

            var $docItemAlias = components.texts.titleText("<div>", document.alias);
            $docItemAlias.modifiers = ["col-3"];

            var $docItemType = components.texts.titleText("<div>", document.type);
            $docItemType.modifiers = ["col-4"];

            var $docItem = new BEM({
                block: "imcms-document-item",
                elements: {
                    "info": [
                        $docItemId,
                        $docItemTitle,
                        $docItemAlias,
                        $docItemType
                    ],
                    "controls": buildDocItemControls(document.id, opts)
                }
            }).buildBlockStructure("<div>");

            if (opts.moveEnable === true) {
                $docItem.find(".imcms-control--move").on("mousedown", createFrame);
            }

            return $docItem;
        }

        function buildDocumentItemContainer(document, opts) {
            return new BEM({
                block: "imcms-document-items",
                elements: {
                    "document-item": buildDocItem(document, opts)
                }
            }).buildBlockStructure("<div>");
        }

        function buildDocumentList(documentList, opts) {
            var $blockElements = documentList.map(function (document) {
                return buildDocumentItemContainer(document, opts);
            });

            return new BEM({
                block: "imcms-document-items-list",
                elements: {
                    "document-items": $blockElements
                }
            }).buildBlockStructure("<div>");
        }

        function buildEditorBody(documentList, opts) {
            return new BEM({
                block: "imcms-document-list",
                elements: {
                    "titles": buildDocumentListTitlesRow(),
                    "items": buildDocumentList(documentList, opts)
                }
            }).buildBlockStructure("<div>");
        }

        var $documentsContainer, $editorBody;

        function buildHead() {
            return documentWindowBuilder.buildHead("Document editor");
        }

        function buildFooter() {
            return documentWindowBuilder.buildFooter();
        }

        function buildBody() {
            return $documentsContainer = new BEM({
                block: "imcms-document-editor-body",
                elements: {
                    "body-head": buildBodyHead()
                }
            }).buildBlockStructure("<div>");
        }

        function loadDocumentEditorContent(opts) {
            docRestApi.read(null).done(function (documentList) {
                $editorBody = buildEditorBody(documentList, opts);
                $documentsContainer.append($editorBody);
            });
        }

        function buildDocumentEditor() {
            return new BEM({
                block: "imcms-document-editor",
                elements: {
                    "head": buildHead(),
                    "body": buildBody(),
                    "footer": buildFooter()
                }
            }).buildBlockStructure("<div>", {"class": "imcms-editor-window"});
        }

        function removeDocument(documentId) {
            var $documentRow = $(this).parent().parent();

            docRestApi.remove(documentId).done(function (responseCode) {
                responseCode === 200 && $documentRow.remove();
            });
        }

        function loadData() {
            loadDocumentEditorContent({
                editEnable: true,
                removeEnable: true
            });
        }

        function clearData() {
            $editorBody.detach();
        }

        var documentWindowBuilder = new WindowBuilder({
            factory: buildDocumentEditor,
            loadDataStrategy: loadData,
            clearDataStrategy: clearData
        });

        return {
            buildBody: buildBody,
            loadDocumentEditorContent: loadDocumentEditorContent,
            build: function () {
                documentWindowBuilder.buildWindow.applyAsync(arguments, documentWindowBuilder);
            }
        };
    }
);
<commit_msg>IMCMS-233 - Apply new UI to the admin panel and editors: - Documents moving in Menu Editor refactored.<commit_after>/**
 * Created by Serhii Maksymchuk from Ubrainians for imCode
 * 14.08.17.
 */
Imcms.define("imcms-document-editor-builder",
    [
        "imcms-bem-builder", "imcms-page-info-builder", "imcms-components-builder", "imcms-primitives-builder",
        "imcms-documents-rest-api", "imcms-controls-builder", "imcms-users-rest-api", "imcms-categories-rest-api",
        "imcms-window-builder", "jquery"
    ],
    function (BEM, pageInfoBuilder, components, primitives, docRestApi, controlsBuilder, usersRestApi,
              categoriesRestApi, WindowBuilder, $) {

        var isMouseDown = false,
            mouseCoords = {
                pageX: undefined,
                pageY: undefined,
                newPageX: undefined,
                newPageY: undefined
            },
            $menuArea,
            menuAreaProp = {
                top: 0,
                left: 0,
                right: 0,
                bottom: 0
            }
        ;

        function buildBodyHeadTools() {

            function onNewDocButtonClick(e) {
                e.preventDefault();
                pageInfoBuilder.build();
            }

            function buildNewDocButton() {
                return components.buttons.negativeButton({
                    text: "New",
                    click: onNewDocButtonClick
                });
            }

            function buildSearchDocField() {
                return new BEM({
                    block: "imcms-input-search",
                    elements: {
                        "text-box": primitives.imcmsInputText({
                            id: "searchText",
                            name: "search",
                            placeholder: "Type to find document"
                        }),
                        "button": components.buttons.searchButton()
                    }
                }).buildBlockStructure("<div>");
            }

            function buildUsersFilterSelect() {
                var $usersFilterSelect = components.selects.imcmsSelect("<div>", {
                    id: "users-filter",
                    name: "users-filter"
                });

                usersRestApi.read(null).done(function (users) {
                    var usersDataMapped = users.map(function (user) {
                        return {
                            text: user.username,
                            "data-value": user.id
                        }
                    });
                    components.selects.addOptionsToSelect(usersDataMapped, $usersFilterSelect);
                });

                return $usersFilterSelect;
            }

            function buildCategoriesFilterSelect() {
                var $categoriesFilterSelect = components.selects.imcmsSelect("<div>", {
                    id: "categories-filter",
                    name: "categories-filter"
                });

                categoriesRestApi.read(null).done(function (categories) {
                    var categoriesDataMapped = categories.map(function (category) {
                        return {
                            text: category.name,
                            "data-value": category.id
                        }
                    });
                    components.selects.addOptionsToSelect(categoriesDataMapped, $categoriesFilterSelect);
                });

                return $categoriesFilterSelect;
            }

            var toolBEM = new BEM({
                block: "imcms-document-editor-head-tool",
                elements: {
                    "search": "imcms-input-search",
                    "button": "imcms-button"
                }
            });

            var $newDocButtonContainer = toolBEM.buildBlock("<div>", [{"button": buildNewDocButton()}]);
            $newDocButtonContainer.modifiers = ["grid-col-2"];

            var $searchContainer = toolBEM.buildBlock("<div>", [{"search": buildSearchDocField()}]);
            $searchContainer.modifiers = ["grid-col-4"];

            var $usersFilter = toolBEM.buildBlock("<div>", [{"select": buildUsersFilterSelect()}]);
            $usersFilter.modifiers = ["grid-col-3"];

            var $categoriesFilter = toolBEM.buildBlock("<div>", [{"select": buildCategoriesFilterSelect()}]);
            $categoriesFilter.modifiers = ["grid-col-3"];

            return new BEM({
                block: "imcms-document-editor-head-tools",
                elements: {
                    "tool": [
                        $newDocButtonContainer,
                        $searchContainer,
                        $usersFilter,
                        $categoriesFilter
                    ]
                }
            }).buildBlockStructure("<div>");
        }

        function buildBodyHead() {
            return new BEM({
                block: "imcms-document-editor-head",
                elements: {
                    "tools": buildBodyHeadTools()
                }
            }).buildBlockStructure("<div>");
        }

        function buildDocumentListTitlesRow() {
            var $idColumnHead = $("<div>", {text: "id"});
            $idColumnHead.modifiers = ["col-2"];

            var $titleColumnHead = $("<div>", {text: "Title"});
            $titleColumnHead.modifiers = ["col-3"];

            var $aliasColumnHead = $("<div>", {text: "Alias"});
            $aliasColumnHead.modifiers = ["col-3"];

            var $typeColumnHead = $("<div>", {text: "Type"});
            $typeColumnHead.modifiers = ["col-4"];

            return new BEM({
                block: "imcms-document-list-titles",
                elements: {
                    "title": [
                        $idColumnHead,
                        $titleColumnHead,
                        $aliasColumnHead,
                        $typeColumnHead
                    ]
                }
            }).buildBlockStructure("<div>");
        }

        function createFrame(event) {
            var $this = $(this),
                original = $this.closest(".imcms-document-items"),
                $frame = original.clone(),
                frameItem = $frame.find(".imcms-document-item")
            ;
            $menuArea = $(".imcms-menu-items-tree");

            if (!checkDocInMenuEditor(original)) {
                event.preventDefault();
                return
            }

            isMouseDown = true;
            mouseCoords = {
                pageX: event.clientX,
                pageY: event.clientY,
                top: $this.closest(".imcms-document-items").position().top,
                left: $this.closest(".imcms-document-items").position().left
            };
            menuAreaProp = {
                top: $menuArea.position().top,
                left: $menuArea.position().left,
                right: menuAreaProp.left + $menuArea.outerWidth(),
                bottom: menuAreaProp.top + $menuArea.outerHeight()
            };

            frameItem.attr("data-id", frameItem.children().first().text());
            frameItem.attr("data-title", frameItem.children().eq(1).text());

            $frame.addClass("imcms-document-items--frame");
            $frame.css({
                "background-color": "#e9e9f5",
                "position": "absolute",
                "z-index": 11001,
                "width": $(".imcms-document-list__items").outerWidth(),
                "top": mouseCoords.top,
                "left": mouseCoords.left
            });

            $frame.appendTo("body");

            $(document).on("mousemove", moveFrame)
                .on("dragstart", function () {
                    return false;
                });
        }

        function buildDocItemControls(documentId, opts) {
            var controls = [];

            if (opts) {
                if (opts.moveEnable) {
                    var $controlMove = controlsBuilder.move().on("mousedown", createFrame);
                    controls.push($controlMove);
                }

                if (opts.removeEnable) {
                    var $controlRemove = controlsBuilder.remove(function () {
                        removeDocument.call(this, documentId);
                    });
                    controls.push($controlRemove);
                }

                if (opts.editEnable) {
                    var $controlEdit = controlsBuilder.edit(pageInfoBuilder.build.bind(pageInfoBuilder, documentId));
                    controls.push($controlEdit);
                }
            }

            return controlsBuilder.buildControlsBlock("<div>", controls);
        }

        function moveFrame(event) {
            var $frame = $(".imcms-document-items--frame");
            mouseCoords.newPageX = event.clientX;
            mouseCoords.newPageY = event.clientY;

            if (isMouseDown) {
                $frame.css({
                    "top": (mouseCoords.newPageY - mouseCoords.pageY) + mouseCoords.top,
                    "left": (mouseCoords.newPageX - mouseCoords.pageX) + mouseCoords.left
                });

                if (detectTargetArea(event)) {
                    $menuArea.css({
                        "border-color": "#51aeea"
                    });
                    getDocumentParent();
                } else {
                    $menuArea.css({
                        "border-color": "transparent"
                    });
                    disableHighlightingMenuDoc()
                }

            }
        }

        function checkDocInMenuEditor(original) {
            var status = true,
                originalId = parseInt(original.find(".imcms-title").first().text())
            ;
            $(".imcms-menu-items").each(function () {
                if (parseInt($(this).attr("data-menu-id")) === originalId) {
                    status = false;
                }
            });

            return status;
        }

        function detectTargetArea(event) {
            return (event.pageY > menuAreaProp.top) && (event.pageY < menuAreaProp.bottom) && (event.pageX > menuAreaProp.left) && (event.pageX < menuAreaProp.right);
        }

        function getMenuDocByObjId(obj) {
            var menuDocs = $(".imcms-menu-items-tree").find(".imcms-menu-items"),
                menuDoc = null
            ;

            menuDocs.each(function () {
                if ($(this).attr("data-menu-id") === obj) {
                    menuDoc = $(this)
                }
            });

            return menuDoc;
        }

        function disableHighlightingMenuDoc() {
            $(".imcms-menu-items-tree").find(".imcms-menu-items").css({
                "border": "none"
            });
        }

        function checkFramePositioning(allMenuDocObjArray, frameTop) {
            var menuDoc = null,
                placeStatus = null
            ;

            // false -> under parent; true -> in parent; null -> under all

            function highlightMenuDoc(param, elem) {
                disableHighlightingMenuDoc();
                if (param) {
                    elem.css({
                        "border-top": "1px solid #51aeea",
                        "border-bottom": "1px solid #51aeea"
                    });
                } else {
                    elem.css({
                        "border-bottom": "1px solid #51aeea"
                    })
                }
            }

            $.each(allMenuDocObjArray, function (obj, param) {
                if (frameTop > param.top && frameTop < ((param.bottom + param.top) / 2)) {
                    menuDoc = getMenuDocByObjId(obj);
                    placeStatus = true;
                } else if (frameTop > ((param.bottom + param.top) / 2) && frameTop < param.bottom) {
                    menuDoc = getMenuDocByObjId(obj);
                    placeStatus = false;
                }
            });

            // highlightingMenuDoc
            if (placeStatus !== null) {
                highlightMenuDoc(placeStatus, menuDoc);
            } else {
                disableHighlightingMenuDoc();
            }

            return {
                parent: menuDoc,
                status: placeStatus
            }
        }

        function getDocumentParent() {
            var allMenuDocObjArray = {},
                itemTree = $(".imcms-menu-items-tree"),
                menuDocs = itemTree.find(".imcms-menu-items"),
                $frame = $(".imcms-document-items--frame"),
                frameTop = $frame.offset().top
            ;
            if (menuDocs.length === 0) {
                return checkFramePositioning(allMenuDocObjArray, frameTop)
            }

            // get all menu doc coords
            menuDocs.each(function () {
                allMenuDocObjArray[$(this).attr("data-menu-id")] = {
                    top: $(this).offset().top,
                    bottom: $(this).offset().top + $(this).outerHeight()
                };
            });

            return checkFramePositioning(allMenuDocObjArray, frameTop);
        }

        $(document).on("mouseup", function (event) {
            var $frame = $(".imcms-document-items--frame"),
                frameItem = $frame.find(".imcms-document-item"),
                dataInput = $("#dataInput"),
                insertedParent = null
            ;

            if ($frame.length === 0) {
                return
            }

            if (detectTargetArea(event)) {
                insertedParent = getDocumentParent();
                if (insertedParent.parent !== null) {
                    dataInput.attr("data-parent-id", insertedParent.parent.attr("data-menu-id"));
                    dataInput.attr("data-insert-place", insertedParent.status);
                } else {
                    dataInput.attr("data-parent-id", "");
                    dataInput.attr("data-insert-place", "");
                }
                dataInput.attr("data-id", frameItem.attr("data-id"));
                dataInput.attr("data-title", frameItem.attr("data-title")).trigger("change");
                $menuArea.css({
                    "border-color": "transparent"
                });
                disableHighlightingMenuDoc();
            }

            $frame.remove();
            isMouseDown = false;
        });

        function buildDocItem(document, opts) {
            var $docItemId = components.texts.titleText("<div>", document.id);
            $docItemId.modifiers = ["col-2"];

            var $docItemTitle = components.texts.titleText("<div>", document.title);
            $docItemTitle.modifiers = ["col-3"];

            var $docItemAlias = components.texts.titleText("<div>", document.alias);
            $docItemAlias.modifiers = ["col-3"];

            var $docItemType = components.texts.titleText("<div>", document.type);
            $docItemType.modifiers = ["col-4"];

            return new BEM({
                block: "imcms-document-item",
                elements: {
                    "info": [
                        $docItemId,
                        $docItemTitle,
                        $docItemAlias,
                        $docItemType
                    ],
                    "controls": buildDocItemControls(document.id, opts)
                }
            }).buildBlockStructure("<div>");
        }

        function buildDocumentItemContainer(document, opts) {
            return new BEM({
                block: "imcms-document-items",
                elements: {
                    "document-item": buildDocItem(document, opts)
                }
            }).buildBlockStructure("<div>");
        }

        function buildDocumentList(documentList, opts) {
            var $blockElements = documentList.map(function (document) {
                return buildDocumentItemContainer(document, opts);
            });

            return new BEM({
                block: "imcms-document-items-list",
                elements: {
                    "document-items": $blockElements
                }
            }).buildBlockStructure("<div>");
        }

        function buildEditorBody(documentList, opts) {
            return new BEM({
                block: "imcms-document-list",
                elements: {
                    "titles": buildDocumentListTitlesRow(),
                    "items": buildDocumentList(documentList, opts)
                }
            }).buildBlockStructure("<div>");
        }

        var $documentsContainer, $editorBody;

        function buildHead() {
            return documentWindowBuilder.buildHead("Document editor");
        }

        function buildFooter() {
            return documentWindowBuilder.buildFooter();
        }

        function buildBody() {
            return $documentsContainer = new BEM({
                block: "imcms-document-editor-body",
                elements: {
                    "body-head": buildBodyHead()
                }
            }).buildBlockStructure("<div>");
        }

        function loadDocumentEditorContent(opts) {
            docRestApi.read(null).done(function (documentList) {
                $editorBody = buildEditorBody(documentList, opts);
                $documentsContainer.append($editorBody);
            });
        }

        function buildDocumentEditor() {
            return new BEM({
                block: "imcms-document-editor",
                elements: {
                    "head": buildHead(),
                    "body": buildBody(),
                    "footer": buildFooter()
                }
            }).buildBlockStructure("<div>", {"class": "imcms-editor-window"});
        }

        function removeDocument(documentId) {
            var $documentRow = $(this).parent().parent();

            docRestApi.remove(documentId).done(function (responseCode) {
                responseCode === 200 && $documentRow.remove();
            });
        }

        function loadData() {
            loadDocumentEditorContent({
                editEnable: true,
                removeEnable: true
            });
        }

        function clearData() {
            $editorBody.detach();
        }

        var documentWindowBuilder = new WindowBuilder({
            factory: buildDocumentEditor,
            loadDataStrategy: loadData,
            clearDataStrategy: clearData
        });

        return {
            buildBody: buildBody,
            loadDocumentEditorContent: loadDocumentEditorContent,
            build: function () {
                documentWindowBuilder.buildWindow.applyAsync(arguments, documentWindowBuilder);
            }
        };
    }
);
<|endoftext|>


<commit_before>(function (global) {

  function extractParams() {
    //FF already decodes the URL fragment in document.location.hash, so use this instead:
    var location = RemoteStorage.Authorize.getLocation(),
        hashPos  = location.href.indexOf('#'),
        hash;
    if (hashPos === -1) { return; }
    hash = location.href.substring(hashPos+1);
    // if hash is not of the form #key=val&key=val, it's probably not for us
    if (hash.indexOf('=') === -1) { return; }
    return hash.split('&').reduce(function (m, kvs) {
      var kv = kvs.split('=');
      m[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
      return m;
    }, {});
  }

  RemoteStorage.ImpliedAuth = function (storageApi, redirectUri) {
    RemoteStorage.log('ImpliedAuth proceeding due to absent authURL; storageApi = ' + storageApi + ' redirectUri = ' + redirectUri);
    // Set a fixed access token, signalling to not send it as Bearer
    remoteStorage.remote.configure(undefined, undefined, undefined, RemoteStorage.Authorize.IMPLIED_FAKE_TOKEN);
    document.location = redirectUri;
  };

  RemoteStorage.Authorize = function (authURL, scope, redirectUri, clientId) {
    RemoteStorage.log('[Authorize] authURL = ', authURL, 'scope = ', scope, 'redirectUri = ', redirectUri, 'clientId = ', clientId);

    var url = authURL, hashPos = redirectUri.indexOf('#');
    url += authURL.indexOf('?') > 0 ? '&' : '?';
    url += 'redirect_uri=' + encodeURIComponent(redirectUri.replace(/#.*$/, ''));
    url += '&scope=' + encodeURIComponent(scope);
    url += '&client_id=' + encodeURIComponent(clientId);
    if (hashPos !== -1) {
      url += '&state=' + encodeURIComponent(redirectUri.substring(hashPos+1));
    }
    url += '&response_type=token';
    RemoteStorage.Authorize.setLocation(url);
  };

  RemoteStorage.Authorize.IMPLIED_FAKE_TOKEN = false;

  RemoteStorage.prototype.authorize = function (authURL) {
    this.access.setStorageType(this.remote.storageType);
    var scope = this.access.scopeParameter;

    var redirectUri = String(RemoteStorage.Authorize.getLocation());
    var clientId = redirectUri.match(/^(https?:\/\/[^\/]+)/)[0];

    RemoteStorage.Authorize(authURL, scope, redirectUri, clientId);
  };

  /**
   * Get current document location
   *
   * Override this method if access to document.location is forbidden
   */
  RemoteStorage.Authorize.getLocation = function () {
    return global.document.location;
  };

  /**
   * Set current document location
   *
   * Override this method if access to document.location is forbidden
   */
  RemoteStorage.Authorize.setLocation = function (location) {
    if (typeof location === 'string') {
      global.document.location.href = location;
    } else if (typeof location === 'object') {
      global.document.location = location;
    } else {
      throw "Invalid location " + location;
    }
  };

  RemoteStorage.prototype.impliedauth = function () {
    RemoteStorage.ImpliedAuth(this.remote.storageApi, String(document.location));
  };

  RemoteStorage.Authorize._rs_supported = function (remoteStorage) {
    return typeof(document) !== 'undefined';
  };

  var onFeaturesLoaded;
  RemoteStorage.Authorize._rs_init = function (remoteStorage) {

    onFeaturesLoaded = function () {
      var authParamsUsed = false;
      if (params) {
        if (params.error) {
          throw "Authorization server errored: " + params.error;
        }
        if (params.access_token) {
          remoteStorage.remote.configure(undefined, undefined, undefined, params.access_token);
          authParamsUsed = true;
        }
        if (params.remotestorage) {
          remoteStorage.connect(params.remotestorage);
          authParamsUsed = true;
        }
        if (params.state) {
          RemoteStorage.Authorize.setLocation('#'+params.state);
        }
      }
      if (!authParamsUsed) {
        remoteStorage.remote.stopWaitingForToken();
      }
    };
    var params = extractParams(),
        location;
    if (params) {
      location = RemoteStorage.Authorize.getLocation();
      location.hash = '';
    }
    remoteStorage.on('features-loaded', onFeaturesLoaded);
  };

  RemoteStorage.Authorize._rs_cleanup = function (remoteStorage) {
    remoteStorage.removeEventListener('features-loaded', onFeaturesLoaded);
  };

})(typeof(window) !== 'undefined' ? window : global);
<commit_msg>dont expect param here. its never passed, and not used in this function<commit_after>(function (global) {

  function extractParams() {
    //FF already decodes the URL fragment in document.location.hash, so use this instead:
    var location = RemoteStorage.Authorize.getLocation(),
        hashPos  = location.href.indexOf('#'),
        hash;
    if (hashPos === -1) { return; }
    hash = location.href.substring(hashPos+1);
    // if hash is not of the form #key=val&key=val, it's probably not for us
    if (hash.indexOf('=') === -1) { return; }
    return hash.split('&').reduce(function (m, kvs) {
      var kv = kvs.split('=');
      m[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
      return m;
    }, {});
  }

  RemoteStorage.ImpliedAuth = function (storageApi, redirectUri) {
    RemoteStorage.log('ImpliedAuth proceeding due to absent authURL; storageApi = ' + storageApi + ' redirectUri = ' + redirectUri);
    // Set a fixed access token, signalling to not send it as Bearer
    remoteStorage.remote.configure(undefined, undefined, undefined, RemoteStorage.Authorize.IMPLIED_FAKE_TOKEN);
    document.location = redirectUri;
  };

  RemoteStorage.Authorize = function (authURL, scope, redirectUri, clientId) {
    RemoteStorage.log('[Authorize] authURL = ', authURL, 'scope = ', scope, 'redirectUri = ', redirectUri, 'clientId = ', clientId);

    var url = authURL, hashPos = redirectUri.indexOf('#');
    url += authURL.indexOf('?') > 0 ? '&' : '?';
    url += 'redirect_uri=' + encodeURIComponent(redirectUri.replace(/#.*$/, ''));
    url += '&scope=' + encodeURIComponent(scope);
    url += '&client_id=' + encodeURIComponent(clientId);
    if (hashPos !== -1) {
      url += '&state=' + encodeURIComponent(redirectUri.substring(hashPos+1));
    }
    url += '&response_type=token';
    RemoteStorage.Authorize.setLocation(url);
  };

  RemoteStorage.Authorize.IMPLIED_FAKE_TOKEN = false;

  RemoteStorage.prototype.authorize = function (authURL) {
    this.access.setStorageType(this.remote.storageType);
    var scope = this.access.scopeParameter;

    var redirectUri = String(RemoteStorage.Authorize.getLocation());
    var clientId = redirectUri.match(/^(https?:\/\/[^\/]+)/)[0];

    RemoteStorage.Authorize(authURL, scope, redirectUri, clientId);
  };

  /**
   * Get current document location
   *
   * Override this method if access to document.location is forbidden
   */
  RemoteStorage.Authorize.getLocation = function () {
    return global.document.location;
  };

  /**
   * Set current document location
   *
   * Override this method if access to document.location is forbidden
   */
  RemoteStorage.Authorize.setLocation = function (location) {
    if (typeof location === 'string') {
      global.document.location.href = location;
    } else if (typeof location === 'object') {
      global.document.location = location;
    } else {
      throw "Invalid location " + location;
    }
  };

  RemoteStorage.prototype.impliedauth = function () {
    RemoteStorage.ImpliedAuth(this.remote.storageApi, String(document.location));
  };

  RemoteStorage.Authorize._rs_supported = function () {
    return typeof(document) !== 'undefined';
  };

  var onFeaturesLoaded;
  RemoteStorage.Authorize._rs_init = function (remoteStorage) {

    onFeaturesLoaded = function () {
      var authParamsUsed = false;
      if (params) {
        if (params.error) {
          throw "Authorization server errored: " + params.error;
        }
        if (params.access_token) {
          remoteStorage.remote.configure(undefined, undefined, undefined, params.access_token);
          authParamsUsed = true;
        }
        if (params.remotestorage) {
          remoteStorage.connect(params.remotestorage);
          authParamsUsed = true;
        }
        if (params.state) {
          RemoteStorage.Authorize.setLocation('#'+params.state);
        }
      }
      if (!authParamsUsed) {
        remoteStorage.remote.stopWaitingForToken();
      }
    };
    var params = extractParams(),
        location;
    if (params) {
      location = RemoteStorage.Authorize.getLocation();
      location.hash = '';
    }
    remoteStorage.on('features-loaded', onFeaturesLoaded);
  };

  RemoteStorage.Authorize._rs_cleanup = function (remoteStorage) {
    remoteStorage.removeEventListener('features-loaded', onFeaturesLoaded);
  };

})(typeof(window) !== 'undefined' ? window : global);
<|endoftext|>


<commit_before>
(function($){

$.gm=function(){
	return $.gm;
}

$.fn.extend({gm:function(){
	var u=new $.gm;
	u.jquery=this;
	return u;
}});

$.gm._import=function(name,fn){
	$.gm[name]=function(){
		var ret=fn.apply($.gm,arguments);
		return ret?ret:$.gm;
	}
}

$.each({

  latlng: function(lat, lng){
  	return new google.maps.LatLng(lat,lng);
  },
  start: function(lat,lng,zoom,options){
  	def={
  		zoom: zoom,
  		center: new google.maps.LatLng(lat,lng),
  		mapTypeId: google.maps.MapTypeId.ROADMAP
  	};

  	this.map = new google.maps.Map(this.jquery[0],$.extend(def,options));
  },
  fitZoom: function(points){
      if (points) {
          var NorthEast = new google.maps.LatLng(points['NorthEastLat'],points['NorthEastLng']);
          var SouthWest = new google.maps.LatLng(points['SouthWestLat'],points['SouthWestLng']);
          console.log(NorthEast);
          console.log(SouthWest);
          var bounds = new google.maps.LatLngBounds(NorthEast,SouthWest);
          console.log(bounds);
          $.gm.map.fitBounds(bounds);
      } else {
          console.log('points is null');
      }
  },
  marker: function(args){
      //console.log('args');
      //console.log(args);
//      markerImage = new google.maps.MarkerImage({
//           url: 'http://localhost/agile/elexu/prototype/upload/0/fsgZjWCr'
//      });
//      marker.setIcon(markerImage);

  	var marker = new google.maps.Marker({
      position: new google.maps.LatLng(args['f_lat'],args['f_lon']),
      animation: google.maps.Animation.DROP,
      map: this.map,
      title:args['f_name'],
      clickable:true
  	});

      if(args['thumb']) {
          $.ajax({
              url:args['thumb'],
              type:'HEAD',
              error: function() {
                  //file not exists
              },
              success: function() {
                  //file exists
                  marker.setIcon(args['thumb']);
              }
          });
      }

      if(args['name']) {
          google.maps.event.addListener(marker, 'click', function() {
              //$.univ().frameURL('title',args['frame_url']);
              if( typeof $.gm.marker.infowindow != 'undefined' ) {
                  $.gm.marker.infowindow.close();
              }
              $.gm.marker.infowindow = new google.maps.InfoWindow({
                 content: args['name']
              });
              $.gm.marker.infowindow.open(this.map,marker);
          });
      }

      return marker;
  },
  markerNew: function(lat,lng,title,args){
//      console.log('marker new = ' + $.gm.markerNew.marker);
//      console.log('lat = '+ lat);
//      console.log('lng = ' + lng);
//      console.log('args');
//      console.log(args);
      if( typeof $.gm.markerNew.marker != 'undefined' ) {
          if ( $.gm.markerNew.lat != lat && $.gm.markerNew.lng != lng && lat != null && lng != null ) {
              if ( typeof $.gm.markerNew.lat != 'undefined' && typeof $.gm.markerNew.lng != 'undefined' ) {
                      $.gm.markerNew.marker.setMap(null);
              }
              $.gm.markerNew.lat = lat;
              $.gm.markerNew.lng = lng;
              var ar = {'f_lat':lat,'f_lon':lng,'f_name':title};
              $.gm.markerNew.marker = $.gm.marker(ar);
              $.gm.map.panTo(new google.maps.LatLng(lat,lng));

              $('#'+$.gm.f_location).val( title );
              $('#'+$.gm.f_lat).val( lat );
              $('#'+$.gm.f_lng).val( lng );
          }
      } else if (lat != null && lng != null) {
//          console.log('========>>>>> undefined <<<<<<=======');
          $.gm.markerNew.lat = lat;
          $.gm.markerNew.lng = lng;
          var ar = {'f_lat':lat,'f_lon':lng,'f_name':title};
          $.gm.markerNew.marker = $.gm.marker(ar);
          $.gm.map.panTo(new google.maps.LatLng(lat,lng));

          $('#'+$.gm.f_location).val( title );
          $('#'+$.gm.f_lat).val( lat );
          $('#'+$.gm.f_lng).val( lng );
      }

  },
  markerCounter: function(marker){
      if( typeof $.gm.markerCounter.markers == 'undefined' ) { $.gm.markerCounter.markers = []; }
//      console.log($.gm.markerCounter.markers.length);
      $.each($.gm.markerCounter.markers, function(index, value) {
          if (value.title == marker.title) {
              console.log('===> ' +value.title + ': ' + marker.title);
          }
      });

      $.gm.markerCounter.markers[$.gm.markerCounter.markers.length] = marker;
  },
  getCoordinatesByAddr: function(url,addr,map_id){
      // TODO simetimes it sends same request any way. Why?
      // TODO It is not crytical but interesting :)
      if ($.gm.getCoordinatesByAddr.lastRequest == addr) {
          //console.log('last request match. return  = '+$.gm.getCoordinatesByAddr.lastRequest);
          return;
      }
      if (addr.length >= 3 && $.gm.getCoordinatesByAddr.lastRequest != addr) {
          if( typeof $.gm.getCoordinatesByAddr.lineCounter == 'undefined' ) {
              $.gm.getCoordinatesByAddr.lineCounter = 0;
          } else {
              $.gm.getCoordinatesByAddr.lineCounter++;
              //console.log('up   = '+$.gm.getCoordinatesByAddr.lineCounter);
          }
          setTimeout(
              function () {
                  if ( $.gm.getCoordinatesByAddr.lineCounter > 0) {
                      $.gm.getCoordinatesByAddr.lineCounter--;
                      //console.log('down = '+$.gm.getCoordinatesByAddr.lineCounter);
                      return;
                  }

                  $.gm.getCoordinatesByAddr.lineCounter--;
                  console.log("BINGO " +$.gm.getCoordinatesByAddr.lineCounter);
                  $.getJSON(url+'&addr='+addr,
                      function(data) {
                        $('.res').html(''+data.name+'. lng '+data.lon+' lat '+data.lat+'');
                        $('#'+map_id).gm().markerNew(data.lat,data.lon,data.name,data);
                        //alert('Load was performed.');
                  });
                  $.gm.getCoordinatesByAddr.lastRequest = addr;
                  //console.log('last request   = '+$.gm.getCoordinatesByAddr.lastRequest);
              }
              ,1000
          );
      }
  },
    bindLocationFields : function (f_location, f_lat, f_lng, search){
    	$.gm.f_location = f_location;
    	$.gm.f_lat  = f_lat;
    	$.gm.f_lng  = f_lng;
    	$.gm.search = search;
    },
    renderMapWithTimeout: function(map,time){
        $.gm.getCoordinatesByAddr.lastRequest = '';
        $.gm.markerNew.marker = undefined;
        //console.log('marker must be undefined - '+$.gm.markerNew.marker );
        if ( typeof time == 'undefined' ) time = 5000;
        setTimeout(
            function () {
                $(map).trigger('render_map');

                setTimeout(
                    function () {
                        //console.log('$.gm.f_location value = ' + $('#'+$.gm.f_location).val());
                        //console.log('$.gm.f_lat value = ' + $('#'+$.gm.f_lat).val());
                        //console.log('$.gm.f_lng value = ' + $('#'+$.gm.f_lng).val());
                        if (
                          //$('#'+$.gm.f_location).val() != null && $('#'+$.gm.f_location).val() != '' &&
                          $('#'+$.gm.f_lat).val() != null && $('#'+$.gm.f_lat).val() != '' &&
                          $('#'+$.gm.f_lng).val() != null &&$('#'+$.gm.f_lng).val() != ''
                        ) {
                            $.gm.markerNew($('#'+$.gm.f_lat).val(),$('#'+$.gm.f_lng).val(),$('#'+$.gm.f_location).val());
                        }
                    },500)
                }
                ,time
        );
    }
},$.gm._import);

})(jQuery);<commit_msg>marker<commit_after>
(function($){

$.gm=function(){
	return $.gm;
}

$.fn.extend({gm:function(){
	var u=new $.gm;
	u.jquery=this;
	return u;
}});

$.gm._import=function(name,fn){
	$.gm[name]=function(){
		var ret=fn.apply($.gm,arguments);
		return ret?ret:$.gm;
	}
}

$.each({

  latlng: function(lat, lng){
  	return new google.maps.LatLng(lat,lng);
  },
  start: function(lat,lng,zoom,options){
  	def={
  		zoom: zoom,
  		center: new google.maps.LatLng(lat,lng),
  		mapTypeId: google.maps.MapTypeId.ROADMAP
  	};

  	this.map = new google.maps.Map(this.jquery[0],$.extend(def,options));
  },
  fitZoom: function(points){
      if (points) {
          var NorthEast = new google.maps.LatLng(points['NorthEastLat'],points['NorthEastLng']);
          var SouthWest = new google.maps.LatLng(points['SouthWestLat'],points['SouthWestLng']);
          console.log(NorthEast);
          console.log(SouthWest);
          var bounds = new google.maps.LatLngBounds(NorthEast,SouthWest);
          console.log(bounds);
          $.gm.map.fitBounds(bounds);
      } else {
          console.log('points is null');
      }
  },
  marker: function(args){
      //console.log('args');
      //console.log(args);
//      markerImage = new google.maps.MarkerImage({
//           url: 'http://localhost/agile/elexu/prototype/upload/0/fsgZjWCr'
//      });
//      marker.setIcon(markerImage);

  	var marker = new google.maps.Marker({
      position: new google.maps.LatLng(args['f_lat'],args['f_lon']),
      animation: google.maps.Animation.DROP,
      map: this.map,
      title:args['f_name'],
      clickable:true
  	});

      if(args['thumb']) {
          console.log(args['thumb']);
          $.ajax({
              url:args['thumb'],
              type:'HEAD',
              error: function() {
                  //file not exists
              },
              success: function() {
                  //file exists
                  marker.setIcon(args['thumb']);
              }
          });
      }

      if(args['name']) {
          google.maps.event.addListener(marker, 'click', function() {
              //$.univ().frameURL('title',args['frame_url']);
              if( typeof $.gm.marker.infowindow != 'undefined' ) {
                  $.gm.marker.infowindow.close();
              }
              $.gm.marker.infowindow = new google.maps.InfoWindow({
                 content: args['name']
              });
              $.gm.marker.infowindow.open(this.map,marker);
          });
      }

      return marker;
  },
  markerNew: function(lat,lng,title,args){
//      console.log('marker new = ' + $.gm.markerNew.marker);
//      console.log('lat = '+ lat);
//      console.log('lng = ' + lng);
//      console.log('args');
//      console.log(args);
      if( typeof $.gm.markerNew.marker != 'undefined' ) {
          if ( $.gm.markerNew.lat != lat && $.gm.markerNew.lng != lng && lat != null && lng != null ) {
              if ( typeof $.gm.markerNew.lat != 'undefined' && typeof $.gm.markerNew.lng != 'undefined' ) {
                      $.gm.markerNew.marker.setMap(null);
              }
              $.gm.markerNew.lat = lat;
              $.gm.markerNew.lng = lng;
              var ar = {'f_lat':lat,'f_lon':lng,'f_name':title};
              $.gm.markerNew.marker = $.gm.marker(ar);
              $.gm.map.panTo(new google.maps.LatLng(lat,lng));

              $('#'+$.gm.f_location).val( title );
              $('#'+$.gm.f_lat).val( lat );
              $('#'+$.gm.f_lng).val( lng );
          }
      } else if (lat != null && lng != null) {
//          console.log('========>>>>> undefined <<<<<<=======');
          $.gm.markerNew.lat = lat;
          $.gm.markerNew.lng = lng;
          var ar = {'f_lat':lat,'f_lon':lng,'f_name':title};
          $.gm.markerNew.marker = $.gm.marker(ar);
          $.gm.map.panTo(new google.maps.LatLng(lat,lng));

          $('#'+$.gm.f_location).val( title );
          $('#'+$.gm.f_lat).val( lat );
          $('#'+$.gm.f_lng).val( lng );
      }

  },
  markerCounter: function(marker){
      if( typeof $.gm.markerCounter.markers == 'undefined' ) { $.gm.markerCounter.markers = []; }
//      console.log($.gm.markerCounter.markers.length);
      $.each($.gm.markerCounter.markers, function(index, value) {
          if (value.title == marker.title) {
              console.log('===> ' +value.title + ': ' + marker.title);
          }
      });

      $.gm.markerCounter.markers[$.gm.markerCounter.markers.length] = marker;
  },
  getCoordinatesByAddr: function(url,addr,map_id){
      // TODO simetimes it sends same request any way. Why?
      // TODO It is not crytical but interesting :)
      if ($.gm.getCoordinatesByAddr.lastRequest == addr) {
          //console.log('last request match. return  = '+$.gm.getCoordinatesByAddr.lastRequest);
          return;
      }
      if (addr.length >= 3 && $.gm.getCoordinatesByAddr.lastRequest != addr) {
          if( typeof $.gm.getCoordinatesByAddr.lineCounter == 'undefined' ) {
              $.gm.getCoordinatesByAddr.lineCounter = 0;
          } else {
              $.gm.getCoordinatesByAddr.lineCounter++;
              //console.log('up   = '+$.gm.getCoordinatesByAddr.lineCounter);
          }
          setTimeout(
              function () {
                  if ( $.gm.getCoordinatesByAddr.lineCounter > 0) {
                      $.gm.getCoordinatesByAddr.lineCounter--;
                      //console.log('down = '+$.gm.getCoordinatesByAddr.lineCounter);
                      return;
                  }

                  $.gm.getCoordinatesByAddr.lineCounter--;
                  console.log("BINGO " +$.gm.getCoordinatesByAddr.lineCounter);
                  $.getJSON(url+'&addr='+addr,
                      function(data) {
                        $('.res').html(''+data.name+'. lng '+data.lon+' lat '+data.lat+'');
                        $('#'+map_id).gm().markerNew(data.lat,data.lon,data.name,data);
                        //alert('Load was performed.');
                  });
                  $.gm.getCoordinatesByAddr.lastRequest = addr;
                  //console.log('last request   = '+$.gm.getCoordinatesByAddr.lastRequest);
              }
              ,1000
          );
      }
  },
    bindLocationFields : function (f_location, f_lat, f_lng, search){
    	$.gm.f_location = f_location;
    	$.gm.f_lat  = f_lat;
    	$.gm.f_lng  = f_lng;
    	$.gm.search = search;
    },
    renderMapWithTimeout: function(map,time){
        $.gm.getCoordinatesByAddr.lastRequest = '';
        $.gm.markerNew.marker = undefined;
        //console.log('marker must be undefined - '+$.gm.markerNew.marker );
        if ( typeof time == 'undefined' ) time = 5000;
        setTimeout(
            function () {
                $(map).trigger('render_map');

                setTimeout(
                    function () {
                        //console.log('$.gm.f_location value = ' + $('#'+$.gm.f_location).val());
                        //console.log('$.gm.f_lat value = ' + $('#'+$.gm.f_lat).val());
                        //console.log('$.gm.f_lng value = ' + $('#'+$.gm.f_lng).val());
                        if (
                          //$('#'+$.gm.f_location).val() != null && $('#'+$.gm.f_location).val() != '' &&
                          $('#'+$.gm.f_lat).val() != null && $('#'+$.gm.f_lat).val() != '' &&
                          $('#'+$.gm.f_lng).val() != null &&$('#'+$.gm.f_lng).val() != ''
                        ) {
                            $.gm.markerNew($('#'+$.gm.f_lat).val(),$('#'+$.gm.f_lng).val(),$('#'+$.gm.f_location).val());
                        }
                    },500)
                }
                ,time
        );
    }
},$.gm._import);

})(jQuery);<|endoftext|>


<commit_before>
if( typeof process != 'undefined' ) {
    if( typeof process.argv[2] != 'string' ) {
	process.stderr.write('usage: node validate.js [indoorjson-file]\n');
	process.exit(1);
	return;
    }

    try {
	var json = JSON.parse(require('fs').readFileSync
			      (process.argv[2]).toString('utf8'));
    } catch(err) {
	process.stderr.write('invalid JSON at ' + process.argv[2]);
	process.exit(1);
	return;
    }

    var res = validateGeoJSON(json);
    if( res ) {
	process.stderr.write('invalid GeoJSON: ' + res + '\n');
	process.exit(1);
	return;
    } else
	process.exit(0);
}

function validateCoords(c) {
    var res = validateArray(c);
    if( res )
	return res;
    if( c.length < 2 )
	return 'not enough coordinates';
    if( typeof c[0] != 'number' ||
	typeof c[1] != 'number' )
	return 'non-number coordinates';
    if( isNaN(c[0]) || isNaN(c[1]) )
	return 'NaN coordinates';
    return null;
}

function validateArray(arr) {
    if( arr == null )
	return 'null array';
    else if( typeof arr != 'object' )
	return 'non-object array';
    else if( typeof arr.length != 'number' )
	return 'unknown array length';
    else if( Math.floor(arr.length) != arr.length )
	return 'non-integer geometries array length';
    else {
	for( var ai = 0; ai < arr.length; ai++ )
	    if( typeof arr[ai] == 'undefined' )
		return 'undefined array element';
	for( var a in arr ) {
	    if( a == 'length' )
		continue;
	    if( a.match(/^[0-9]+$/) ) {
		var aint = parseInt(a);
		if( a < 0 || a >= arr.length )
		    return 'unknown attribute in array: ' + a;
	    } else
		return 'unknown attribute in array: ' + a;
	}
    }
    return null;
}

function validateGeometry(geom, toplevel) {
    if( geom == null )
	return 'null geometry';
    else if( typeof geom != 'object' )
	return 'non-object geometry';
    else if( typeof geom.type != 'string' )
	return 'no geometry type';
    else if( geom.type == 'GeometryCollection' ) {
	var res = validateArray(geom.geometries);
	if( res )
	    return res;

	for( var gi = 0; gi < geom.geometries.length; gi++ ) {
	    var res = validateGeometry(geom.geometries[gi]);
	    if( res )
		return res;
	}

	for( var a in geom ) {
	    if( a == 'crs' && toplevel ) {
		var res = validateCRS(feat.crs);
		if( res )
		    return res;
		continue;
	    }
	    if( a != 'type' &&
		a != 'geometries' )
		return 'unknown attribute ' + a;
	}
	return null;
    } else {
	var res = validateArray(geom.coordinates);
	if( res )
	    return res;
	if( geom.type == 'Point' ) {
	    var res = validateCoords(geom.coordinates);
	    if( res )
		return res;
	} else if( geom.type != 'MultiPoint' ||
		   geom.type != 'LineString' ) {
	    for( var gi = 0; gi < geom.coordinates.length; gi++ ) {
		var res = validateCoords(geom.coordinates[gi]);
		if( res )
		    return res;
	    }
	} else if( geom.type != 'MultiLineString' ||
		   geom.type != 'Polygon' ) {
	    for( var pi = 0; pi < geom.coordinates.length; pi++ ) {
		var res = validateArray(geom.coordinates[pi]);
		if( res )
		    return res;
		for( var gi = 0; gi < geom.coordinates[pi].length; gi++ ) {
		    var res = validateCoords(geom.coordinates[pi][gi]);
		    if( res )
			return res;
		}
	    }
	} else if( geom.type != 'MultiPolygon' ) {
	    for( var ppi = 0; ppi < geom.coordinates.length; ppi++ ) {
		var res = validateArray(geom.coordinates[ppi]);
		if( res )
		    return res;
		for( var pi = 0; pi < geom.coordinates[ppi].length; pi++ ) {
		    var res = validateArray(geom.coordinates[ppi][pi]);
		    if( res )
			return res;
		    for( var gi = 0; gi < geom.coordinates[ppi][pi].length;
			 gi++ ) {
			var res = validateCoords(geom.coordinates[ppi][pi][gi]);
			if( res )
			    return res;
		    }
		}
	    }
	} else
	    return 'unknown geometry type';
	for( var a in geom ) {
	    if( a == 'crs' && toplevel ) {
		var res = validateCRS(feat.crs);
		if( res )
		    return res;
		continue;
	    }
	    if( a != 'type' &&
		a != 'coordinates' )
		return 'unknown attribute ' + a;
	}
	return null;
    }
}

function validateCRS(crs) {
    if( crs == null )
	return 'null crs';
    else if( typeof crs != 'object' )
	return 'non-object crs';
    else if( typeof crs.type != 'string' )
	return 'non-string crs type';
    else if( typeof crs.properties != 'object' )
	return 'non-object crs properties';
    for( var a in crs )
	if( a != 'type' &&
	    a != 'properties' )
	    return 'unknown attribute in crs: ' + a;
    return null;
}

function validateFeature(feat, toplevel) {
    if( feat == null )
	return 'null feature';
    else if( typeof feat != 'object' )
	return 'non-object feature';
    else if( typeof feat.type == 'string' ) {
	if( feat.type == 'Feature' ) {

	    var res = validateGeometry(feat.geometry, false);
	    if( res )
		return res;

	    if( typeof feat.properties != 'object' )
		return 'no properties in a feature';

	    for( var a in feat ) {
		if( a != 'type' &&
		    a != 'geometry' &&
		    a != 'properties' )
		    return 'unknown attribute ' + a;
	    }
	} else if( feat.type == 'FeatureCollection' ) {
	    var res = validateArray(feat.features);
	    if( res )
		return res;
	    for( var fi = 0; fi < feat.features.length; fi++ ) {
		var res = validateFeature(feat.features[fi], false);
		if( res )
		    return res;
	    }
	    for( var a in feat ) {
		if( a == 'crs' && toplevel ) {
		    var res = validateCRS(feat.crs);
		    if( res )
			return res;
		    continue;
		}
		if(a != 'type' &&
		   a != 'features' )
		    return 'unknown attribute ' + a;
	    }
	    return null;
	} else
	    return 'invalid feature type ' + feat.type;
    } else
	return 'invalid feature ' + JSON.stringify(feat).substring(0, 50);
}

function validateObject(obj, toplevel) {
    if( obj == null )
	return 'null object';
    if( typeof obj != 'object' )
	return 'non-object object';
    if( typeof obj.type != 'string' )
	return 'unknown type';
    if( obj.type == 'Feature' ||
	obj.type == 'FeatureCollection' )
	return validateFeature(obj, toplevel);
    else
	return validateGeometry(obj, toplevel);
}

function validateGeoJSON(json) {
    return validateFeature(json, true);
}

<commit_msg>updated validate.js<commit_after>
if( typeof process != 'undefined' ) {
    if( typeof process.argv[2] != 'string' ) {
	process.stderr.write('usage: node validate.js [indoorjson-file]\n');
	process.exit(1);
	return;
    }

    try {
	var json = JSON.parse(require('fs').readFileSync
			      (process.argv[2]).toString('utf8'));
    } catch(err) {
	process.stderr.write('invalid JSON at ' + process.argv[2] + '\n');
	process.exit(1);
	return;
    }

    var res = validateGeoJSON(json, true);
    if( res ) {
	process.stderr.write('invalid GeoJSON: ' + res + '\n');
	process.exit(1);
	return;
    } else
	process.exit(0);
}

function validateCoords(c) {
    var res = validateArray(c);
    if( res )
	return res;
    if( c.length < 2 )
	return 'not enough coordinates';
    for( var ci = 0; ci < c.length; ci++ ) {
	if( typeof c[ci] != 'number' )
	    return 'non-number coordinates';
	if( isNaN(c[ci]) )
	    return 'NaN coordinates';
    }
    return null;
}

function validateArray(arr) {
    if( arr == null )
	return 'null array';
    else if( typeof arr != 'object' )
	return 'non-object array';
    else if( typeof arr.length != 'number' )
	return 'unknown array length';
    else if( Math.floor(arr.length) != arr.length )
	return 'non-integer geometries array length';
    else {
	for( var ai = 0; ai < arr.length; ai++ )
	    if( typeof arr[ai] == 'undefined' )
		return 'undefined array element';
	for( var a in arr ) {
	    if( a == 'length' )
		continue;
	    if( a.match(/^[0-9]+$/) ) {
		var aint = parseInt(a);
		if( a < 0 || a >= arr.length )
		    return 'unknown attribute in array: ' + a;
	    } else
		return 'unknown attribute in array: ' + a;
	}
    }
    return null;
}

function validateGeometry(geom, toplevel) {
    if( geom == null )
	return 'null geometry';
    else if( typeof geom != 'object' )
	return 'non-object geometry';
    else if( typeof geom.type != 'string' )
	return 'no geometry type';
    else if( geom.type == 'GeometryCollection' ) {
	var res = validateArray(geom.geometries);
	if( res )
	    return res;

	for( var gi = 0; gi < geom.geometries.length; gi++ ) {
	    var res = validateGeometry(geom.geometries[gi]);
	    if( res )
		return res;
	}

	for( var a in geom ) {
	    if( a == 'crs' && toplevel ) {
		var res = validateCRS(feat.crs);
		if( res )
		    return res;
		continue;
	    }
	    if( a != 'type' &&
		a != 'geometries' )
		return 'unknown attribute ' + a;
	}
	return null;
    } else {
	var res = validateArray(geom.coordinates);
	if( res )
	    return res;
	if( geom.type == 'Point' ) {
	    var res = validateCoords(geom.coordinates);
	    if( res )
		return res;
	} else if( geom.type == 'MultiPoint' ||
		   geom.type == 'LineString' ) {
	    for( var gi = 0; gi < geom.coordinates.length; gi++ ) {
		var res = validateCoords(geom.coordinates[gi]);
		if( res )
		    return res;
	    }
	} else if( geom.type == 'MultiLineString' ||
		   geom.type == 'Polygon' ) {
	    for( var pi = 0; pi < geom.coordinates.length; pi++ ) {
		var res = validateArray(geom.coordinates[pi]);
		if( res )
		    return res;
		for( var gi = 0; gi < geom.coordinates[pi].length; gi++ ) {
		    var res = validateCoords(geom.coordinates[pi][gi]);
		    if( res )
			return res;
		}
	    }
	} else if( geom.type == 'MultiPolygon' ) {
	    for( var ppi = 0; ppi < geom.coordinates.length; ppi++ ) {
		var res = validateArray(geom.coordinates[ppi]);
		if( res )
		    return res;
		for( var pi = 0; pi < geom.coordinates[ppi].length; pi++ ) {
		    var res = validateArray(geom.coordinates[ppi][pi]);
		    if( res )
			return res;
		    for( var gi = 0; gi < geom.coordinates[ppi][pi].length;
			 gi++ ) {
			var res = validateCoords(geom.coordinates[ppi][pi][gi]);
			if( res )
			    return res;
		    }
		}
	    }
	} else
	    return 'unknown geometry type';
	for( var a in geom ) {
	    if( a == 'crs' && toplevel ) {
		var res = validateCRS(feat.crs);
		if( res )
		    return res;
		continue;
	    }
	    if( a != 'type' &&
		a != 'coordinates' )
		return 'unknown attribute ' + a;
	}
	return null;
    }
}

function validateCRS(crs) {
    if( crs == null )
	return 'null crs';
    else if( typeof crs != 'object' )
	return 'non-object crs';
    else if( typeof crs.type != 'string' )
	return 'non-string crs type';
    else if( typeof crs.properties != 'object' )
	return 'non-object crs properties';
    for( var a in crs )
	if( a != 'type' &&
	    a != 'properties' )
	    return 'unknown attribute in crs: ' + a;
    return null;
}

function validateFeature(feat, toplevel) {
    if( feat == null )
	return 'null feature';
    else if( typeof feat != 'object' )
	return 'non-object feature';
    else if( typeof feat.type == 'string' ) {
	if( feat.type == 'Feature' ) {

	    var res = validateGeometry(feat.geometry, false);
	    if( res )
		return res;

	    if( typeof feat.properties != 'object' )
		return 'no properties in a feature';

	    for( var a in feat ) {
		if( a != 'type' &&
		    a != 'geometry' &&
		    a != 'properties' )
		    return 'unknown attribute ' + a;
	    }
	} else if( feat.type == 'FeatureCollection' ) {
	    var res = validateArray(feat.features);
	    if( res )
		return res;
	    for( var fi = 0; fi < feat.features.length; fi++ ) {
		var res = validateFeature(feat.features[fi], false);
		if( res )
		    return res;
	    }
	    for( var a in feat ) {
		if( a == 'crs' && toplevel ) {
		    var res = validateCRS(feat.crs);
		    if( res )
			return res;
		    continue;
		}
		if(a != 'type' &&
		   a != 'features' )
		    return 'unknown attribute ' + a;
	    }
	    return null;
	} else
	    return 'invalid feature type ' + feat.type;
    } else
	return 'invalid feature ' + JSON.stringify(feat).substring(0, 50);
}

function validateGeoJSON(obj, toplevel) {
    if( obj == null )
	return 'null object';
    if( typeof obj != 'object' )
	return 'non-object object';
    if( typeof obj.type != 'string' )
	return 'unknown type';
    if( obj.type == 'Feature' ||
	obj.type == 'FeatureCollection' )
	return validateFeature(obj, toplevel);
    else
	return validateGeometry(obj, toplevel);
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) Telecom ParisTech/TSI/MM/GPAC Cyril Concolato
 * License: BSD-3-Clause (see LICENSE file)
 */
BoxParser.parseUUID = function(stream) {
	return BoxParser.parseHex16(stream);
}

BoxParser.parseHex16 = function(stream) {
	var hex16 = ""
	for (var i = 0; i <16; i++) {
		var hex = stream.readUint8().toString(16);
		hex16 += (hex.length === 1 ? "0"+hex : hex);
	}
	return hex16;
}

BoxParser.parseOneBox = function(stream, headerOnly, parentSize) {
	var box;
	var start = stream.getPosition();
	var hdr_size = 0;
	var diff;
	var uuid;
	if (stream.getEndPosition() - start < 8) {
		Log.debug("BoxParser", "Not enough data in stream to parse the type and size of the box");
		return { code: BoxParser.ERR_NOT_ENOUGH_DATA };
	}
	if (parentSize && parentSize < 8) {
		Log.debug("BoxParser", "Not enough bytes left in the parent box to parse a new box");
		return { code: BoxParser.ERR_NOT_ENOUGH_DATA };
	}
	var size = stream.readUint32();
	var type = stream.readString(4);
	var box_type = type;
	Log.debug("BoxParser", "Found box of type '"+type+"' and size "+size+" at position "+start);
	hdr_size = 8;
	if (type == "uuid") {
		if ((stream.getEndPosition() - stream.getPosition() < 16*8) || (parentSize -hdr_size < 16*8)) {
			stream.seek(start);
			Log.debug("BoxParser", "Not enough bytes left in the parent box to parse a UUID box");
			return { code: BoxParser.ERR_NOT_ENOUGH_DATA };
		}
		uuid = BoxParser.parseUUID(stream);
		hdr_size += 16;
		box_type = uuid;
	}
	if (size == 1) {
		if ((stream.getEndPosition() - stream.getPosition() < 8) || (parentSize && (parentSize - hdr_size) < 8)) {
			stream.seek(start);
			Log.warn("BoxParser", "Not enough data in stream to parse the extended size of the \""+type+"\" box");
			return { code: BoxParser.ERR_NOT_ENOUGH_DATA };
		}
		size = stream.readUint64();
		hdr_size += 8;
	} else if (size === 0) {
		/* box extends till the end of file or invalid file */
		if (parentSize) {
			size = parentSize;
		} else {
			/* box extends till the end of file */
			if (type !== "mdat") {
				Log.error("BoxParser", "Unlimited box size not supported for type: '"+type+"'");
				box = new BoxParser.Box(type, size);
				return { code: BoxParser.OK, box: box, size: box.size };
			}
		}
	}
	if (size < hdr_size) {
		Log.error("BoxParser", "Box of type "+type+" has an invalid size "+size+" (too small to be a box)");
		return { code: BoxParser.ERR_NOT_ENOUGH_DATA, type: type, size: size, hdr_size: hdr_size, start: start };
	}
	if (parentSize && size > parentSize) {
		Log.error("BoxParser", "Box of type '"+type+"' has a size "+size+" greater than its container size "+parentSize);
		return { code: BoxParser.ERR_NOT_ENOUGH_DATA, type: type, size: size, hdr_size: hdr_size, start: start };
	}
	if (start + size > stream.getEndPosition()) {
		stream.seek(start);
		Log.info("BoxParser", "Not enough data in stream to parse the entire '"+type+"' box");
		return { code: BoxParser.ERR_NOT_ENOUGH_DATA, type: type, size: size, hdr_size: hdr_size, start: start };
	}
	if (headerOnly) {
		return { code: BoxParser.OK, type: type, size: size, hdr_size: hdr_size, start: start };
	} else {
		if (BoxParser[type+"Box"]) {
			box = new BoxParser[type+"Box"](size);
		} else {
			if (type !== "uuid") {
				Log.warn("BoxParser", "Unknown box type: '"+type+"'");
				box = new BoxParser.Box(type, size);
				box.has_unparsed_data = true;
			} else {
				if (BoxParser.UUIDBoxes[uuid]) {
					box = new BoxParser.UUIDBoxes[uuid](size);
				} else {
					Log.warn("BoxParser", "Unknown uuid type: '"+uuid+"'");
					box = new BoxParser.Box(type, size);
					box.uuid = uuid;
					box.has_unparsed_data = true;
				}
			}
		}
	}
	box.hdr_size = hdr_size;
	/* recording the position of the box in the input stream */
	box.start = start;
	if (box.write === BoxParser.Box.prototype.write && box.type !== "mdat") {
		Log.info("BoxParser", "'"+box_type+"' box writing not yet implemented, keeping unparsed data in memory for later write");
		box.parseDataAndRewind(stream);
	}
	box.parse(stream);
	diff = stream.getPosition() - (box.start+box.size);
	if (diff < 0) {
		Log.warn("BoxParser", "Parsing of box '"+box_type+"' did not read the entire indicated box data size (missing "+(-diff)+" bytes), seeking forward");
		stream.seek(box.start+box.size);
	} else if (diff > 0) {
		Log.error("BoxParser", "Parsing of box '"+box_type+"' read "+diff+" more bytes than the indicated box data size, seeking backwards");
		stream.seek(box.start+box.size);
	}
	return { code: BoxParser.OK, box: box, size: box.size };
}

BoxParser.Box.prototype.parse = function(stream) {
	if (this.type != "mdat") {
		this.data = stream.readUint8Array(this.size-this.hdr_size);
	} else {
		if (this.size === 0) {
			stream.seek(stream.getEndPosition());
		} else {
			stream.seek(this.start+this.size);
		}
	}
}

/* Used to parse a box without consuming its data, to allow detailled parsing
   Useful for boxes for which a write method is not yet implemented */
BoxParser.Box.prototype.parseDataAndRewind = function(stream) {
	this.data = stream.readUint8Array(this.size-this.hdr_size);
	// rewinding
	stream.position -= this.size-this.hdr_size;
}

BoxParser.FullBox.prototype.parseDataAndRewind = function(stream) {
	this.parseFullHeader(stream);
	this.data = stream.readUint8Array(this.size-this.hdr_size);
	// restore the header size as if the full header had not been parsed
	this.hdr_size -= 4;
	// rewinding
	stream.position -= this.size-this.hdr_size;
}

BoxParser.FullBox.prototype.parseFullHeader = function (stream) {
	this.version = stream.readUint8();
	this.flags = stream.readUint24();
	this.hdr_size += 4;
}

BoxParser.FullBox.prototype.parse = function (stream) {
	this.parseFullHeader(stream);
	this.data = stream.readUint8Array(this.size-this.hdr_size);
}

BoxParser.ContainerBox.prototype.parse = function(stream) {
	var ret;
	var box;
	while (stream.getPosition() < this.start+this.size) {
		ret = BoxParser.parseOneBox(stream, false, this.size - (stream.getPosition() - this.start));
		if (ret.code === BoxParser.OK) {
			box = ret.box;
			/* store the box in the 'boxes' array to preserve box order (for offset) but also store box in a property for more direct access */
			this.boxes.push(box);
			if (this.subBoxNames && this.subBoxNames.indexOf(box.type) != -1) {
				this[this.subBoxNames[this.subBoxNames.indexOf(box.type)]+"s"].push(box);
			} else {
				var box_type = box.type !== "uuid" ? box.type : box.uuid;
				if (this[box_type]) {
					Log.warn("Box of type "+box_type+" already stored in field of this type");
				} else {
					this[box_type] = box;
				}
			}
		} else {
			return;
		}
	}
}

BoxParser.Box.prototype.parseLanguage = function(stream) {
	this.language = stream.readUint16();
	var chars = [];
	chars[0] = (this.language>>10)&0x1F;
	chars[1] = (this.language>>5)&0x1F;
	chars[2] = (this.language)&0x1F;
	this.languageString = String.fromCharCode(chars[0]+0x60, chars[1]+0x60, chars[2]+0x60);
}

<commit_msg>fix check for space to parse UUID<commit_after>/*
 * Copyright (c) Telecom ParisTech/TSI/MM/GPAC Cyril Concolato
 * License: BSD-3-Clause (see LICENSE file)
 */
BoxParser.parseUUID = function(stream) {
	return BoxParser.parseHex16(stream);
}

BoxParser.parseHex16 = function(stream) {
	var hex16 = ""
	for (var i = 0; i <16; i++) {
		var hex = stream.readUint8().toString(16);
		hex16 += (hex.length === 1 ? "0"+hex : hex);
	}
	return hex16;
}

BoxParser.parseOneBox = function(stream, headerOnly, parentSize) {
	var box;
	var start = stream.getPosition();
	var hdr_size = 0;
	var diff;
	var uuid;
	if (stream.getEndPosition() - start < 8) {
		Log.debug("BoxParser", "Not enough data in stream to parse the type and size of the box");
		return { code: BoxParser.ERR_NOT_ENOUGH_DATA };
	}
	if (parentSize && parentSize < 8) {
		Log.debug("BoxParser", "Not enough bytes left in the parent box to parse a new box");
		return { code: BoxParser.ERR_NOT_ENOUGH_DATA };
	}
	var size = stream.readUint32();
	var type = stream.readString(4);
	var box_type = type;
	Log.debug("BoxParser", "Found box of type '"+type+"' and size "+size+" at position "+start);
	hdr_size = 8;
	if (type == "uuid") {
		if ((stream.getEndPosition() - stream.getPosition() < 16) || (parentSize -hdr_size < 16)) {
			stream.seek(start);
			Log.debug("BoxParser", "Not enough bytes left in the parent box to parse a UUID box");
			return { code: BoxParser.ERR_NOT_ENOUGH_DATA };
		}
		uuid = BoxParser.parseUUID(stream);
		hdr_size += 16;
		box_type = uuid;
	}
	if (size == 1) {
		if ((stream.getEndPosition() - stream.getPosition() < 8) || (parentSize && (parentSize - hdr_size) < 8)) {
			stream.seek(start);
			Log.warn("BoxParser", "Not enough data in stream to parse the extended size of the \""+type+"\" box");
			return { code: BoxParser.ERR_NOT_ENOUGH_DATA };
		}
		size = stream.readUint64();
		hdr_size += 8;
	} else if (size === 0) {
		/* box extends till the end of file or invalid file */
		if (parentSize) {
			size = parentSize;
		} else {
			/* box extends till the end of file */
			if (type !== "mdat") {
				Log.error("BoxParser", "Unlimited box size not supported for type: '"+type+"'");
				box = new BoxParser.Box(type, size);
				return { code: BoxParser.OK, box: box, size: box.size };
			}
		}
	}
	if (size < hdr_size) {
		Log.error("BoxParser", "Box of type "+type+" has an invalid size "+size+" (too small to be a box)");
		return { code: BoxParser.ERR_NOT_ENOUGH_DATA, type: type, size: size, hdr_size: hdr_size, start: start };
	}
	if (parentSize && size > parentSize) {
		Log.error("BoxParser", "Box of type '"+type+"' has a size "+size+" greater than its container size "+parentSize);
		return { code: BoxParser.ERR_NOT_ENOUGH_DATA, type: type, size: size, hdr_size: hdr_size, start: start };
	}
	if (start + size > stream.getEndPosition()) {
		stream.seek(start);
		Log.info("BoxParser", "Not enough data in stream to parse the entire '"+type+"' box");
		return { code: BoxParser.ERR_NOT_ENOUGH_DATA, type: type, size: size, hdr_size: hdr_size, start: start };
	}
	if (headerOnly) {
		return { code: BoxParser.OK, type: type, size: size, hdr_size: hdr_size, start: start };
	} else {
		if (BoxParser[type+"Box"]) {
			box = new BoxParser[type+"Box"](size);
		} else {
			if (type !== "uuid") {
				Log.warn("BoxParser", "Unknown box type: '"+type+"'");
				box = new BoxParser.Box(type, size);
				box.has_unparsed_data = true;
			} else {
				if (BoxParser.UUIDBoxes[uuid]) {
					box = new BoxParser.UUIDBoxes[uuid](size);
				} else {
					Log.warn("BoxParser", "Unknown uuid type: '"+uuid+"'");
					box = new BoxParser.Box(type, size);
					box.uuid = uuid;
					box.has_unparsed_data = true;
				}
			}
		}
	}
	box.hdr_size = hdr_size;
	/* recording the position of the box in the input stream */
	box.start = start;
	if (box.write === BoxParser.Box.prototype.write && box.type !== "mdat") {
		Log.info("BoxParser", "'"+box_type+"' box writing not yet implemented, keeping unparsed data in memory for later write");
		box.parseDataAndRewind(stream);
	}
	box.parse(stream);
	diff = stream.getPosition() - (box.start+box.size);
	if (diff < 0) {
		Log.warn("BoxParser", "Parsing of box '"+box_type+"' did not read the entire indicated box data size (missing "+(-diff)+" bytes), seeking forward");
		stream.seek(box.start+box.size);
	} else if (diff > 0) {
		Log.error("BoxParser", "Parsing of box '"+box_type+"' read "+diff+" more bytes than the indicated box data size, seeking backwards");
		stream.seek(box.start+box.size);
	}
	return { code: BoxParser.OK, box: box, size: box.size };
}

BoxParser.Box.prototype.parse = function(stream) {
	if (this.type != "mdat") {
		this.data = stream.readUint8Array(this.size-this.hdr_size);
	} else {
		if (this.size === 0) {
			stream.seek(stream.getEndPosition());
		} else {
			stream.seek(this.start+this.size);
		}
	}
}

/* Used to parse a box without consuming its data, to allow detailled parsing
   Useful for boxes for which a write method is not yet implemented */
BoxParser.Box.prototype.parseDataAndRewind = function(stream) {
	this.data = stream.readUint8Array(this.size-this.hdr_size);
	// rewinding
	stream.position -= this.size-this.hdr_size;
}

BoxParser.FullBox.prototype.parseDataAndRewind = function(stream) {
	this.parseFullHeader(stream);
	this.data = stream.readUint8Array(this.size-this.hdr_size);
	// restore the header size as if the full header had not been parsed
	this.hdr_size -= 4;
	// rewinding
	stream.position -= this.size-this.hdr_size;
}

BoxParser.FullBox.prototype.parseFullHeader = function (stream) {
	this.version = stream.readUint8();
	this.flags = stream.readUint24();
	this.hdr_size += 4;
}

BoxParser.FullBox.prototype.parse = function (stream) {
	this.parseFullHeader(stream);
	this.data = stream.readUint8Array(this.size-this.hdr_size);
}

BoxParser.ContainerBox.prototype.parse = function(stream) {
	var ret;
	var box;
	while (stream.getPosition() < this.start+this.size) {
		ret = BoxParser.parseOneBox(stream, false, this.size - (stream.getPosition() - this.start));
		if (ret.code === BoxParser.OK) {
			box = ret.box;
			/* store the box in the 'boxes' array to preserve box order (for offset) but also store box in a property for more direct access */
			this.boxes.push(box);
			if (this.subBoxNames && this.subBoxNames.indexOf(box.type) != -1) {
				this[this.subBoxNames[this.subBoxNames.indexOf(box.type)]+"s"].push(box);
			} else {
				var box_type = box.type !== "uuid" ? box.type : box.uuid;
				if (this[box_type]) {
					Log.warn("Box of type "+box_type+" already stored in field of this type");
				} else {
					this[box_type] = box;
				}
			}
		} else {
			return;
		}
	}
}

BoxParser.Box.prototype.parseLanguage = function(stream) {
	this.language = stream.readUint16();
	var chars = [];
	chars[0] = (this.language>>10)&0x1F;
	chars[1] = (this.language>>5)&0x1F;
	chars[2] = (this.language)&0x1F;
	this.languageString = String.fromCharCode(chars[0]+0x60, chars[1]+0x60, chars[2]+0x60);
}

<|endoftext|>